From d8d55a8294acbd5c2e2b5666b45ffed5c1c6d897 Mon Sep 17 00:00:00 2001 From: kameshsr <47484458+kameshsr@users.noreply.github.com> Date: Fri, 30 Jun 2023 13:35:03 +0530 Subject: [PATCH] Moved latest develop code to release 1201 (#985) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * MOSIP-24630 Improved code coverage. (#770) * Fixed service history issue. * MOSIP-24630 Changed service history implementation. * MOSIP-24630 Added jpa repo for service history api. * MOSIP-24630 Improved code coverage. * MOSIP-24630 Fixed typo. * MOSIP-24630 Reverted default start date. * MOSIP-24630 Improved code coverage. * MOSIP-24630 Improved code coverage. * MOSIP-24630 Improved code coverage. * MOSIP-24630 Improved code coverage. * MOSIP-24630 Improved code coverage. * Fix class cast issue (#771) Co-authored-by: Loganathan Sekar * Mosip 26247 fix update otp validation issue in update contact (#772) * Fix class cast issue * MOSIP-26247 WIP-fix-to-double-entry-for-update-contact * Test fixes * Code fix --------- Co-authored-by: Loganathan Sekar * MOSIP-25861-resident-api-able-to-upload-document-with-all-invalid-details-as-input (#763) * fixed automation issues * fixed download service history API * corrected the proprty name * fixed 2 eventID generated error * removed null condition * validated doccatcode and doctypcode * validate doctype based on doccat * set indivudual id in db entity * fixed batch job issue * revert changes in template util * added test case * put validation on transaction id * fixed transaction id validation * added regex validation for eventId and transactionId * validated documentid, transactionid and otp * updated regex names * fixed mumeric method name * updated test properties --------- Co-authored-by: Ritik Jain Co-authored-by: Loganathan Sekar <42532387+LoganathanSekar7627@users.noreply.github.com> * Mosip 25391 individualid decryption fix share cred status fix (#773) * Fix class cast issue * MOSIP-26247 WIP-fix-to-double-entry-for-update-contact * Test fixes * Code fix * Individual ID decryption fixed in interceptor, share cred status initialized to NEW. * pom fix --------- Co-authored-by: Loganathan Sekar * MOSIP-26090-tech-story-fix-the-status-updates-for-vid-card-download-update-uin-events (#775) * fixed automation issues * fixed download service history API * corrected the proprty name * fixed 2 eventID generated error * removed null condition * validated doccatcode and doctypcode * validate doctype based on doccat * set indivudual id in db entity * fixed batch job issue * revert changes in template util * added test case * put validation on transaction id * fixed transaction id validation * added regex validation for eventId and transactionId * validated documentid, transactionid and otp * updated regex names * fixed mumeric method name * updated test properties * changed status to new --------- Co-authored-by: Ritik Jain * MOSIP-24773 Fixed Download card issue. (#774) * Fixed service history issue. * MOSIP-24773 Fixed Download card issue. * MOSIP-24773 Fixed Download card issue. * MOSIP-24773 Fixed Download card issue. * MOSIP-24773 Fixed Download card issue. * MOSIP-24773 Refactor code * removed unused variable from request (#777) Co-authored-by: Ritik Jain * Mosip 26090 tech story fix the status updates for vid card download update uin events (#778) * removed unused variable from request * fixed batch job * fixed code * formatted code * fixed batch job * added stored status * updated batch job and created download card link --------- Co-authored-by: Ritik Jain * MOSIP-26272] Added validation for update-uin API (#779) * [MOSIP-24670] Updated API correction id and version * [MOSIP-24670] Updated API body correction * [MOSIP-22640] Fixed Sonar Bugs * updated PR * updated PR * updated review code * [MOSIP-22640] Fixed sonar bugs * updated PR * updated PR * [MOSIP-22639] Resolved security hotspots in code * [MOSIP-24630] Fixed Security Vulnerability in code * added error for isValidUrl method * renamed vaildateURL method * updated PR * updated PR * [MOSIP-24670] Made corrections in id and version * resolved conflicts * updated PR * updated PR * [MOSIP-24670] Made corrections n API body, response code * updated PR * updated PR * updated dateTime * updated PR * [MOSIP-25539] Made corrections in API body, response code * [MOSIP-25539] made corrections in API body * updated error message * updated error code * updated trasactionid dto change * added equals * [MOSIP-25539] made corrections in api body * [MOSIP-25539] Corrected API response body Task 5 * resolved build failure * [MOSIP-25539] Task 2 Added error code for vaildateOtp API * updated PR * updated PR * updated PR * updated PR * [MOSIP-25539] Updated validateotp method * updated PR * [MOSIP-25798] Added validations * updated PR * updated PR * updated PR * updated PR * updated PR * [MOSIP-25791] Added purpose as mandatory * Added error * Added Audit logs * updated test cases * [MOSIP-22913],[MOSIP-22914],[MOSIP-24653],[MOSIP-24796] Added Audit logs * updated logs * updated auditlog code * updated enum name for audit logs * updated enum name for audit logs * updated enum name for audit logs * updated enum name for audit logs * updated enum name for audit logs * [MOSIP-25268] Fixed Sonar vulnerability * [MOSIP-25268] Fixed Sonar vulnerability * [MOSIP-26272] Added validation for /update-uin API * updated PR * Mosip 26090 tech story fix the status updates for vid card download update uin events (#780) * removed unused variable from request * fixed batch job * fixed code * formatted code * fixed batch job * added stored status * updated batch job and created download card link * updated batch job and fixed download-card api * fixed placeholder and method name --------- Co-authored-by: Ritik Jain * [MOSIP-26272] updated update-uin PR, test cases (#781) * [MOSIP-24670] Updated API correction id and version * [MOSIP-24670] Updated API body correction * [MOSIP-22640] Fixed Sonar Bugs * updated PR * updated PR * updated review code * [MOSIP-22640] Fixed sonar bugs * updated PR * updated PR * [MOSIP-22639] Resolved security hotspots in code * [MOSIP-24630] Fixed Security Vulnerability in code * added error for isValidUrl method * renamed vaildateURL method * updated PR * updated PR * [MOSIP-24670] Made corrections in id and version * resolved conflicts * updated PR * updated PR * [MOSIP-24670] Made corrections n API body, response code * updated PR * updated PR * updated dateTime * updated PR * [MOSIP-25539] Made corrections in API body, response code * [MOSIP-25539] made corrections in API body * updated error message * updated error code * updated trasactionid dto change * added equals * [MOSIP-25539] made corrections in api body * [MOSIP-25539] Corrected API response body Task 5 * resolved build failure * [MOSIP-25539] Task 2 Added error code for vaildateOtp API * updated PR * updated PR * updated PR * updated PR * [MOSIP-25539] Updated validateotp method * updated PR * [MOSIP-25798] Added validations * updated PR * updated PR * updated PR * updated PR * updated PR * [MOSIP-25791] Added purpose as mandatory * Added error * Added Audit logs * updated test cases * [MOSIP-22913],[MOSIP-22914],[MOSIP-24653],[MOSIP-24796] Added Audit logs * updated logs * updated auditlog code * updated enum name for audit logs * updated enum name for audit logs * updated enum name for audit logs * updated enum name for audit logs * updated enum name for audit logs * [MOSIP-25268] Fixed Sonar vulnerability * [MOSIP-25268] Fixed Sonar vulnerability * [MOSIP-26272] Added validation for /update-uin API * updated PR * updated update-uin PR * updated PR * MOSIP-24939 Improved code coverage. (#776) * Fixed service history issue. * MOSIP-24939 Improved code coverage. * MOSIP-24939 Improved code coverage. * MOSIP-24939 Improved code coverage. * MOSIP-24939 Improved code coverage. * MOSIP-24939 Improved code coverage. * MOSIP-24939 Improved code coverage. * Fixed build issue (#782) * [MOSIP-24670] Updated API correction id and version * [MOSIP-24670] Updated API body correction * [MOSIP-22640] Fixed Sonar Bugs * updated PR * updated PR * updated review code * [MOSIP-22640] Fixed sonar bugs * updated PR * updated PR * [MOSIP-22639] Resolved security hotspots in code * [MOSIP-24630] Fixed Security Vulnerability in code * added error for isValidUrl method * renamed vaildateURL method * updated PR * updated PR * [MOSIP-24670] Made corrections in id and version * resolved conflicts * updated PR * updated PR * [MOSIP-24670] Made corrections n API body, response code * updated PR * updated PR * updated dateTime * updated PR * [MOSIP-25539] Made corrections in API body, response code * [MOSIP-25539] made corrections in API body * updated error message * updated error code * updated trasactionid dto change * added equals * [MOSIP-25539] made corrections in api body * [MOSIP-25539] Corrected API response body Task 5 * resolved build failure * [MOSIP-25539] Task 2 Added error code for vaildateOtp API * updated PR * updated PR * updated PR * updated PR * [MOSIP-25539] Updated validateotp method * updated PR * [MOSIP-25798] Added validations * updated PR * updated PR * updated PR * updated PR * updated PR * [MOSIP-25791] Added purpose as mandatory * Added error * Added Audit logs * updated test cases * [MOSIP-22913],[MOSIP-22914],[MOSIP-24653],[MOSIP-24796] Added Audit logs * updated logs * updated auditlog code * updated enum name for audit logs * updated enum name for audit logs * updated enum name for audit logs * updated enum name for audit logs * updated enum name for audit logs * [MOSIP-25268] Fixed Sonar vulnerability * [MOSIP-25268] Fixed Sonar vulnerability * [MOSIP-26272] Added validation for /update-uin API * updated PR * updated update-uin PR * Fixed build issue * Mosip 26090 tech story fix the status updates for vid card download update uin events (#783) * removed unused variable from request * fixed batch job * fixed code * formatted code * fixed batch job * added stored status * updated batch job and created download card link * updated batch job and fixed download-card api * fixed placeholder and method name * added suffix for rid * removed unused property * update the data time --------- Co-authored-by: Ritik Jain * MOSIP-25854 Fixed vid card issue. (#785) * Fixed service history issue. * MOSIP-24939 Improved code coverage. * MOSIP-24939 Improved code coverage. * MOSIP-24939 Improved code coverage. * MOSIP-24939 Improved code coverage. * MOSIP-24939 Improved code coverage. * MOSIP-24939 Improved code coverage. * MOSIP-25854 Fixed vid card issue. * Updated transactionId error message (#784) * [MOSIP-24670] Updated API correction id and version * [MOSIP-24670] Updated API body correction * [MOSIP-22640] Fixed Sonar Bugs * updated PR * updated PR * updated review code * [MOSIP-22640] Fixed sonar bugs * updated PR * updated PR * [MOSIP-22639] Resolved security hotspots in code * [MOSIP-24630] Fixed Security Vulnerability in code * added error for isValidUrl method * renamed vaildateURL method * updated PR * updated PR * [MOSIP-24670] Made corrections in id and version * resolved conflicts * updated PR * updated PR * [MOSIP-24670] Made corrections n API body, response code * updated PR * updated PR * updated dateTime * updated PR * [MOSIP-25539] Made corrections in API body, response code * [MOSIP-25539] made corrections in API body * updated error message * updated error code * updated trasactionid dto change * added equals * [MOSIP-25539] made corrections in api body * [MOSIP-25539] Corrected API response body Task 5 * resolved build failure * [MOSIP-25539] Task 2 Added error code for vaildateOtp API * updated PR * updated PR * updated PR * updated PR * [MOSIP-25539] Updated validateotp method * updated PR * [MOSIP-25798] Added validations * updated PR * updated PR * updated PR * updated PR * updated PR * [MOSIP-25791] Added purpose as mandatory * Added error * Added Audit logs * updated test cases * [MOSIP-22913],[MOSIP-22914],[MOSIP-24653],[MOSIP-24796] Added Audit logs * updated logs * updated auditlog code * updated enum name for audit logs * updated enum name for audit logs * updated enum name for audit logs * updated enum name for audit logs * updated enum name for audit logs * [MOSIP-25268] Fixed Sonar vulnerability * [MOSIP-25268] Fixed Sonar vulnerability * [MOSIP-26272] Added validation for /update-uin API * updated PR * updated update-uin PR * Fixed build issue * Updated transactionId error message * MOSIP-25854 Fixed vid card issue. (#786) * Fixed service history issue. * MOSIP-24939 Improved code coverage. * MOSIP-24939 Improved code coverage. * MOSIP-24939 Improved code coverage. * MOSIP-24939 Improved code coverage. * MOSIP-24939 Improved code coverage. * MOSIP-24939 Improved code coverage. * MOSIP-25854 Fixed vid card issue. * MOSIP-25854 Fixed vid card issue. * MOSIP-25854 Fixed vid card issue. (#787) * Fixed service history issue. * MOSIP-24939 Improved code coverage. * MOSIP-24939 Improved code coverage. * MOSIP-24939 Improved code coverage. * MOSIP-24939 Improved code coverage. * MOSIP-24939 Improved code coverage. * MOSIP-24939 Improved code coverage. * MOSIP-25854 Fixed vid card issue. * MOSIP-25854 Fixed vid card issue. * MOSIP-25854 Fixed vid card issue. * Updated Test cases for ResidentServiceResUpdate class (#788) * [MOSIP-24670] Updated API correction id and version * [MOSIP-24670] Updated API body correction * [MOSIP-22640] Fixed Sonar Bugs * updated PR * updated PR * updated review code * [MOSIP-22640] Fixed sonar bugs * updated PR * updated PR * [MOSIP-22639] Resolved security hotspots in code * [MOSIP-24630] Fixed Security Vulnerability in code * added error for isValidUrl method * renamed vaildateURL method * updated PR * updated PR * [MOSIP-24670] Made corrections in id and version * resolved conflicts * updated PR * updated PR * [MOSIP-24670] Made corrections n API body, response code * updated PR * updated PR * updated dateTime * updated PR * [MOSIP-25539] Made corrections in API body, response code * [MOSIP-25539] made corrections in API body * updated error message * updated error code * updated trasactionid dto change * added equals * [MOSIP-25539] made corrections in api body * [MOSIP-25539] Corrected API response body Task 5 * resolved build failure * [MOSIP-25539] Task 2 Added error code for vaildateOtp API * updated PR * updated PR * updated PR * updated PR * [MOSIP-25539] Updated validateotp method * updated PR * [MOSIP-25798] Added validations * updated PR * updated PR * updated PR * updated PR * updated PR * [MOSIP-25791] Added purpose as mandatory * Added error * Added Audit logs * updated test cases * [MOSIP-22913],[MOSIP-22914],[MOSIP-24653],[MOSIP-24796] Added Audit logs * updated logs * updated auditlog code * updated enum name for audit logs * updated enum name for audit logs * updated enum name for audit logs * updated enum name for audit logs * updated enum name for audit logs * [MOSIP-25268] Fixed Sonar vulnerability * [MOSIP-25268] Fixed Sonar vulnerability * [MOSIP-26272] Added validation for /update-uin API * updated PR * updated update-uin PR * Fixed build issue * Updated transactionId error message * Updated Test cases ResidentServiceResUpdateTest class * MOSIP-25536 Added online verification partner id in jpa repo view history. (#790) * Fixed service history issue. * MOSIP-24939 Improved code coverage. * MOSIP-24939 Improved code coverage. * MOSIP-24939 Improved code coverage. * MOSIP-24939 Improved code coverage. * MOSIP-24939 Improved code coverage. * MOSIP-24939 Improved code coverage. * MOSIP-25854 Fixed vid card issue. * MOSIP-25854 Fixed vid card issue. * MOSIP-25854 Fixed vid card issue. * MOSIP-25536 Added online verification partner id in jpa repo view history. * MOSIP-25536 Fixed test case failure. * Fix for setting read status to false (#791) Co-authored-by: Loganathan Sekar * Revert mosip 26314 fix for read status for auth lock status (#792) * Fix for setting read status to false * Revert "Fix for setting read status to false (#791)" This reverts commit c00a0512aac93ec9a38350ccf9c8617b80cee6a3. --------- Co-authored-by: Loganathan Sekar * Revert mosip 26314 fix for read status for auth lock status (#793) * Fix for setting read status to false * Revert "Fix for setting read status to false (#791)" This reverts commit c00a0512aac93ec9a38350ccf9c8617b80cee6a3. * Check test fix --------- Co-authored-by: Loganathan Sekar * Revert mosip 26314 fix for read status for auth lock status (#794) * Fix for setting read status to false * Revert "Fix for setting read status to false (#791)" This reverts commit c00a0512aac93ec9a38350ccf9c8617b80cee6a3. * Check test fix * Fix NPE in test in github --------- Co-authored-by: Loganathan Sekar * Revert mosip 26314 fix for read status for auth lock status (#796) * Fix for setting read status to false * Revert "Fix for setting read status to false (#791)" This reverts commit c00a0512aac93ec9a38350ccf9c8617b80cee6a3. * Check test fix * Fix NPE in test in github * Test fix --------- Co-authored-by: Loganathan Sekar * Revert mosip 26314 fix for read status for auth lock status (#797) * Fix for setting read status to false * Revert "Fix for setting read status to false (#791)" This reverts commit c00a0512aac93ec9a38350ccf9c8617b80cee6a3. * Check test fix * Fix NPE in test in github * Test fix * logic fix in test --------- Co-authored-by: Loganathan Sekar * Revert mosip 26314 fix for read status for auth lock status (#798) * Fix for setting read status to false * Revert "Fix for setting read status to false (#791)" This reverts commit c00a0512aac93ec9a38350ccf9c8617b80cee6a3. * Check test fix * Fix NPE in test in github * Test fix * logic fix in test * Test fix --------- Co-authored-by: Loganathan Sekar * Revert mosip 26314 fix for read status for auth lock status (#799) * Fix for setting read status to false * Revert "Fix for setting read status to false (#791)" This reverts commit c00a0512aac93ec9a38350ccf9c8617b80cee6a3. * Check test fix * Fix NPE in test in github * Test fix * logic fix in test * Test fix * Test fix --------- Co-authored-by: Loganathan Sekar * Revert mosip 26314 fix for read status for auth lock status (#800) * Fix for setting read status to false * Revert "Fix for setting read status to false (#791)" This reverts commit c00a0512aac93ec9a38350ccf9c8617b80cee6a3. * Check test fix * Fix NPE in test in github * Test fix * logic fix in test * Test fix * Test fix * Minor fixes * Ignoring test for build failure in github action. to be reverted and fixed --------- Co-authored-by: Loganathan Sekar * Mosip 26314 fix for read status for auth lock status 2 (#801) * Fix for setting read status to false * Revert "Fix for setting read status to false (#791)" This reverts commit c00a0512aac93ec9a38350ccf9c8617b80cee6a3. * Check test fix * Fix NPE in test in github * Test fix * logic fix in test * Test fix * Test fix * Minor fixes * Ignoring test for build failure in github action. to be reverted and fixed * Fix for setting read status to false (#791) Co-authored-by: Loganathan Sekar --------- Co-authored-by: Loganathan Sekar * Mosip 26350 fix share cred req (#802) * Fix for setting read status to false * Revert "Fix for setting read status to false (#791)" This reverts commit c00a0512aac93ec9a38350ccf9c8617b80cee6a3. * Check test fix * Fix NPE in test in github * Test fix * logic fix in test * Test fix * Test fix * Minor fixes * Ignoring test for build failure in github action. to be reverted and fixed * Fix for setting read status to false (#791) Co-authored-by: Loganathan Sekar * Fix for share credential request to cred req service * fix for is masked false * Fix for isMasked --------- Co-authored-by: Loganathan Sekar * added log for number of entries (#804) Co-authored-by: Ritik Jain * [MOSIP-26343] Created module specific audits (#803) * [MOSIP-24670] Updated API correction id and version * [MOSIP-24670] Updated API body correction * [MOSIP-22640] Fixed Sonar Bugs * updated PR * updated PR * updated review code * [MOSIP-22640] Fixed sonar bugs * updated PR * updated PR * [MOSIP-22639] Resolved security hotspots in code * [MOSIP-24630] Fixed Security Vulnerability in code * added error for isValidUrl method * renamed vaildateURL method * updated PR * updated PR * [MOSIP-24670] Made corrections in id and version * resolved conflicts * updated PR * updated PR * [MOSIP-24670] Made corrections n API body, response code * updated PR * updated PR * updated dateTime * updated PR * [MOSIP-25539] Made corrections in API body, response code * [MOSIP-25539] made corrections in API body * updated error message * updated error code * updated trasactionid dto change * added equals * [MOSIP-25539] made corrections in api body * [MOSIP-25539] Corrected API response body Task 5 * resolved build failure * [MOSIP-25539] Task 2 Added error code for vaildateOtp API * updated PR * updated PR * updated PR * updated PR * [MOSIP-25539] Updated validateotp method * updated PR * [MOSIP-25798] Added validations * updated PR * updated PR * updated PR * updated PR * updated PR * [MOSIP-25791] Added purpose as mandatory * Added error * Added Audit logs * updated test cases * [MOSIP-22913],[MOSIP-22914],[MOSIP-24653],[MOSIP-24796] Added Audit logs * updated logs * updated auditlog code * updated enum name for audit logs * updated enum name for audit logs * updated enum name for audit logs * updated enum name for audit logs * updated enum name for audit logs * [MOSIP-25268] Fixed Sonar vulnerability * [MOSIP-25268] Fixed Sonar vulnerability * [MOSIP-26272] Added validation for /update-uin API * updated PR * updated update-uin PR * Fixed build issue * Updated transactionId error message * Updated Test cases ResidentServiceResUpdateTest class * [MOSIP-26343] Created module specific audits * updated PR * updated PR * Removed unwanted fields, fixed coding issue to avoid state in bean, o… (#805) * Removed unwanted fields, fixed coding issue to avoid state in bean, organized imports * Text fix --------- Co-authored-by: Loganathan Sekar * MOSIP-24939 Fixed service history issue. (#807) * Fixed service history issue. * MOSIP-24939 Improved code coverage. * MOSIP-24939 Improved code coverage. * MOSIP-24939 Improved code coverage. * MOSIP-24939 Improved code coverage. * MOSIP-24939 Improved code coverage. * MOSIP-24939 Improved code coverage. * MOSIP-25854 Fixed vid card issue. * MOSIP-25854 Fixed vid card issue. * MOSIP-25854 Fixed vid card issue. * MOSIP-25536 Added online verification partner id in jpa repo view history. * MOSIP-25536 Fixed test case failure. * MOSIP-24939 Improved sonar coverage. * MOSIP-24939 Improved sonar coverage. * MOSIP-24939 Fixed service history issue. * MOSIP-24939 Fixed service history issue. * MOSIP-24939 Fixed service history issue. * Mosip 26515 format fixing (#806) * added log for number of entries * fix batch job individual id null * added notification for vid card download * rename the method to get individual id from session * update websub notification --------- Co-authored-by: Ritik Jain * Mosip 26515 format fixing (#808) * added log for number of entries * fix batch job individual id null * added notification for vid card download * rename the method to get individual id from session * update websub notification * fix feature names --------- Co-authored-by: Ritik Jain * batch job fix (#812) * added log for number of entries * fix batch job individual id null * added notification for vid card download * rename the method to get individual id from session * update websub notification * fix feature names * fix share credential status update in batch job * fixed docTypCode issue --------- Co-authored-by: Ritik Jain * MOSIP-24737 Added proper error code for invalid page fetch value. (#813) * Fixed service history issue. * MOSIP-24737 Added proper error code for invalid page fetch value. * MOSIP-24737 corrected id-schema value in update-uin. * MOSIP-24737 corrected id-schema value in update-uin. * MOSIP-26121-resident-ui-in-verify-phone-number-email-id-not-able-to-track-event-id-status-its-displayed-empty-screen (#814) * added log for number of entries * fix batch job individual id null * added notification for vid card download * rename the method to get individual id from session * update websub notification * fix feature names * fix share credential status update in batch job * fixed docTypCode issue * fixed 400 httpstatus code --------- Co-authored-by: Ritik Jain * Automation fix dev3 (#816) * Fixed service history issue. * update-uin old api fix for id-schema version issue * update-uin old api fix for id-schema version issue * update-uin old api fix for id-schema version issue * MOSIP-26292-resident-api-appropriate-error-message-is-not-displayed-when-purpose-is-empty (#819) * added log for number of entries * fix batch job individual id null * added notification for vid card download * rename the method to get individual id from session * update websub notification * fix feature names * fix share credential status update in batch job * fixed docTypCode issue * fixed 400 httpstatus code * fixed missing parameter error --------- Co-authored-by: Ritik Jain * Fix for email notification for failure case (#821) Co-authored-by: Loganathan Sekar * [MOSIP-26087],[MOSIP-26355] Added featureName in ack pdf filename (#820) * [MOSIP-24670] Updated API correction id and version * [MOSIP-24670] Updated API body correction * [MOSIP-22640] Fixed Sonar Bugs * updated PR * updated PR * updated review code * [MOSIP-22640] Fixed sonar bugs * updated PR * updated PR * [MOSIP-22639] Resolved security hotspots in code * [MOSIP-24630] Fixed Security Vulnerability in code * added error for isValidUrl method * renamed vaildateURL method * updated PR * updated PR * [MOSIP-24670] Made corrections in id and version * resolved conflicts * updated PR * updated PR * [MOSIP-24670] Made corrections n API body, response code * updated PR * updated PR * updated dateTime * updated PR * [MOSIP-25539] Made corrections in API body, response code * [MOSIP-25539] made corrections in API body * updated error message * updated error code * updated trasactionid dto change * added equals * [MOSIP-25539] made corrections in api body * [MOSIP-25539] Corrected API response body Task 5 * resolved build failure * [MOSIP-25539] Task 2 Added error code for vaildateOtp API * updated PR * updated PR * updated PR * updated PR * [MOSIP-25539] Updated validateotp method * updated PR * [MOSIP-25798] Added validations * updated PR * updated PR * updated PR * updated PR * updated PR * [MOSIP-25791] Added purpose as mandatory * Added error * Added Audit logs * updated test cases * [MOSIP-22913],[MOSIP-22914],[MOSIP-24653],[MOSIP-24796] Added Audit logs * updated logs * updated auditlog code * updated enum name for audit logs * updated enum name for audit logs * updated enum name for audit logs * updated enum name for audit logs * updated enum name for audit logs * [MOSIP-25268] Fixed Sonar vulnerability * [MOSIP-25268] Fixed Sonar vulnerability * [MOSIP-26272] Added validation for /update-uin API * updated PR * updated update-uin PR * Fixed build issue * Updated transactionId error message * Updated Test cases ResidentServiceResUpdateTest class * [MOSIP-26343] Created module specific audits * updated PR * updated PR * [MOSIP-26087] Added featureName in pdf name * updated PR * Updated PR as per review * updated PR * updated PR * Fix failure notifications (#823) * Fix for email notification for failure case * Added missing file --------- Co-authored-by: Loganathan Sekar * MOSIP-26121-resident-ui-in-verify-phone-number-email-id-not-able-to-track-event-id-status-its-displayed-empty-screen (#822) * added log for number of entries * fix batch job individual id null * added notification for vid card download * rename the method to get individual id from session * update websub notification * fix feature names * fix share credential status update in batch job * fixed docTypCode issue * fixed 400 httpstatus code * fixed missing parameter error * fixed ida token issue * fixed to get individualId --------- Co-authored-by: Ritik Jain * fixed individual id issue (#825) * added log for number of entries * fix batch job individual id null * added notification for vid card download * rename the method to get individual id from session * update websub notification * fix feature names * fix share credential status update in batch job * fixed docTypCode issue * fixed 400 httpstatus code * fixed missing parameter error * fixed ida token issue * fixed to get individualId * fix individual id issue and added comments * made constant --------- Co-authored-by: Ritik Jain * MOSIP-26289 bug fixed (#824) * MOSIP-26289 changes done * MOSIP-26289 changes done --------- Co-authored-by: Neha Farheen * Bug fixed (#827) * MOSIP-26289 changes done * MOSIP-26289 changes done * Bug fixed --------- Co-authored-by: Neha Farheen * fixed id version for document APIs (#828) Co-authored-by: Ritik Jain * updated enum names and removed duplicate constants (#829) * fixed id version for document APIs * update constant names * used constant file_text --------- Co-authored-by: Ritik Jain * MOSIP-24939 Fixed test case failure. (#831) * Fixed service history issue. * MOSIP-24939 Fixed test case failure. * MOSIP-26693-api-resident-service-request-id-is-getting-generate-from-credential-issuance-when-credential-type-and-issuer-not-present-in-the-request-body (#830) * fixed id version for document APIs * update constant names * used constant file_text * added validation on req credential API * added validation for req credential API --------- Co-authored-by: Ritik Jain * Mosip 25391 fix bell notification issue (#832) * Fix for email notification for failure case * Added missing file * Fix bell notification icon issue * Test fix --------- Co-authored-by: Loganathan Sekar * [MOSIP-24494] Updated transliterate API error msg (#833) * [MOSIP-24670] Updated API correction id and version * [MOSIP-24670] Updated API body correction * [MOSIP-22640] Fixed Sonar Bugs * updated PR * updated PR * updated review code * [MOSIP-22640] Fixed sonar bugs * updated PR * updated PR * [MOSIP-22639] Resolved security hotspots in code * [MOSIP-24630] Fixed Security Vulnerability in code * added error for isValidUrl method * renamed vaildateURL method * updated PR * updated PR * [MOSIP-24670] Made corrections in id and version * resolved conflicts * updated PR * updated PR * [MOSIP-24670] Made corrections n API body, response code * updated PR * updated PR * updated dateTime * updated PR * [MOSIP-25539] Made corrections in API body, response code * [MOSIP-25539] made corrections in API body * updated error message * updated error code * updated trasactionid dto change * added equals * [MOSIP-25539] made corrections in api body * [MOSIP-25539] Corrected API response body Task 5 * resolved build failure * [MOSIP-25539] Task 2 Added error code for vaildateOtp API * updated PR * updated PR * updated PR * updated PR * [MOSIP-25539] Updated validateotp method * updated PR * [MOSIP-25798] Added validations * updated PR * updated PR * updated PR * updated PR * updated PR * [MOSIP-25791] Added purpose as mandatory * Added error * Added Audit logs * updated test cases * [MOSIP-22913],[MOSIP-22914],[MOSIP-24653],[MOSIP-24796] Added Audit logs * updated logs * updated auditlog code * updated enum name for audit logs * updated enum name for audit logs * updated enum name for audit logs * updated enum name for audit logs * updated enum name for audit logs * [MOSIP-25268] Fixed Sonar vulnerability * [MOSIP-25268] Fixed Sonar vulnerability * [MOSIP-26272] Added validation for /update-uin API * updated PR * updated update-uin PR * Fixed build issue * Updated transactionId error message * Updated Test cases ResidentServiceResUpdateTest class * [MOSIP-26343] Created module specific audits * updated PR * updated PR * [MOSIP-26087] Added featureName in pdf name * updated PR * Updated PR as per review * updated PR * updated PR * Updated build * [MOSIP-24494] Updated trasnliterate API error msg * updated PR * updated PR * Added properties for default page size (#836) * Added properties for default page size * minor import fix --------- Co-authored-by: Loganathan Sekar * Add property for default page size 2 (#837) * Added properties for default page size * minor import fix * Fix to the default page size logic --------- Co-authored-by: Loganathan Sekar * MOSIP-26334 Fixed update uin invalid lang code error. (#838) * Fixed service history issue. * MOSIP-26334 Fixed update uin invalid lang code error. * MOSIP-26334 Corrected code as per review comment. * MOSIP-26334 Corrected code as per review comment. * MOSIP-26334 Corrected code as per review comment. * MOSIP-26334 Corrected code as per review comment. * [MOSIP-25363],[MOSIP-24796],[MOSIP-25711] Updated audit logs (#839) * [MOSIP-24670] Updated API correction id and version * [MOSIP-24670] Updated API body correction * [MOSIP-22640] Fixed Sonar Bugs * updated PR * updated PR * updated review code * [MOSIP-22640] Fixed sonar bugs * updated PR * updated PR * [MOSIP-22639] Resolved security hotspots in code * [MOSIP-24630] Fixed Security Vulnerability in code * added error for isValidUrl method * renamed vaildateURL method * updated PR * updated PR * [MOSIP-24670] Made corrections in id and version * resolved conflicts * updated PR * updated PR * [MOSIP-24670] Made corrections n API body, response code * updated PR * updated PR * updated dateTime * updated PR * [MOSIP-25539] Made corrections in API body, response code * [MOSIP-25539] made corrections in API body * updated error message * updated error code * updated trasactionid dto change * added equals * [MOSIP-25539] made corrections in api body * [MOSIP-25539] Corrected API response body Task 5 * resolved build failure * [MOSIP-25539] Task 2 Added error code for vaildateOtp API * updated PR * updated PR * updated PR * updated PR * [MOSIP-25539] Updated validateotp method * updated PR * [MOSIP-25798] Added validations * updated PR * updated PR * updated PR * updated PR * updated PR * [MOSIP-25791] Added purpose as mandatory * Added error * Added Audit logs * updated test cases * [MOSIP-22913],[MOSIP-22914],[MOSIP-24653],[MOSIP-24796] Added Audit logs * updated logs * updated auditlog code * updated enum name for audit logs * updated enum name for audit logs * updated enum name for audit logs * updated enum name for audit logs * updated enum name for audit logs * [MOSIP-25268] Fixed Sonar vulnerability * [MOSIP-25268] Fixed Sonar vulnerability * [MOSIP-26272] Added validation for /update-uin API * updated PR * updated update-uin PR * Fixed build issue * Updated transactionId error message * Updated Test cases ResidentServiceResUpdateTest class * [MOSIP-26343] Created module specific audits * updated PR * updated PR * [MOSIP-26087] Added featureName in pdf name * updated PR * Updated PR as per review * updated PR * updated PR * Updated build * [MOSIP-24494] Updated trasnliterate API error msg * updated PR * updated PR * [MOSIP-25363],[MOSIP-24796],[MOSIP-25711] Updated audit logs * MOSIP-26347-aid-stage-is-returning-success-even-though-it-is-failed-in-regproc (#835) * fixed id version for document APIs * update constant names * used constant file_text * added validation on req credential API * added validation for req credential API * removed duplicate code * fixed rid status issue * removed name from enum * code fix for rid status issue * update validate request body method --------- Co-authored-by: Ritik Jain * Mosip 25391 fix bell notification issue (#840) * Fix for email notification for failure case * Added missing file * Fix bell notification icon issue * Test fix * Fixed cred batch job issues * Minor refactoring and fixes * test fix * Card status update fix * added author --------- Co-authored-by: Loganathan Sekar * Mosip 25391 fix bell notification issue 1 (#841) * Fix for email notification for failure case * Added missing file * Fix bell notification icon issue * Test fix * Fixed cred batch job issues * Minor refactoring and fixes * test fix * Card status update fix * added author * Added missing file * Added jdoc --------- Co-authored-by: Loganathan Sekar * Mosip 25391 fix bell notification issue 2 (#842) * Fix for email notification for failure case * Added missing file * Fix bell notification icon issue * Test fix * Fixed cred batch job issues * Minor refactoring and fixes * test fix * Card status update fix * added author * Added missing file * Added jdoc * Updated logging --------- Co-authored-by: Loganathan Sekar * Removed logic to mark failure for unavailable req id (#844) Co-authored-by: Loganathan Sekar * [MOSIP-26089] Added authentication mode (#845) * [MOSIP-24670] Updated API correction id and version * [MOSIP-24670] Updated API body correction * [MOSIP-22640] Fixed Sonar Bugs * updated PR * updated PR * updated review code * [MOSIP-22640] Fixed sonar bugs * updated PR * updated PR * [MOSIP-22639] Resolved security hotspots in code * [MOSIP-24630] Fixed Security Vulnerability in code * added error for isValidUrl method * renamed vaildateURL method * updated PR * updated PR * [MOSIP-24670] Made corrections in id and version * resolved conflicts * updated PR * updated PR * [MOSIP-24670] Made corrections n API body, response code * updated PR * updated PR * updated dateTime * updated PR * [MOSIP-25539] Made corrections in API body, response code * [MOSIP-25539] made corrections in API body * updated error message * updated error code * updated trasactionid dto change * added equals * [MOSIP-25539] made corrections in api body * [MOSIP-25539] Corrected API response body Task 5 * resolved build failure * [MOSIP-25539] Task 2 Added error code for vaildateOtp API * updated PR * updated PR * updated PR * updated PR * [MOSIP-25539] Updated validateotp method * updated PR * [MOSIP-25798] Added validations * updated PR * updated PR * updated PR * updated PR * updated PR * [MOSIP-25791] Added purpose as mandatory * Added error * Added Audit logs * updated test cases * [MOSIP-22913],[MOSIP-22914],[MOSIP-24653],[MOSIP-24796] Added Audit logs * updated logs * updated auditlog code * updated enum name for audit logs * updated enum name for audit logs * updated enum name for audit logs * updated enum name for audit logs * updated enum name for audit logs * [MOSIP-25268] Fixed Sonar vulnerability * [MOSIP-25268] Fixed Sonar vulnerability * [MOSIP-26272] Added validation for /update-uin API * updated PR * updated update-uin PR * Fixed build issue * Updated transactionId error message * Updated Test cases ResidentServiceResUpdateTest class * [MOSIP-26343] Created module specific audits * updated PR * updated PR * [MOSIP-26087] Added featureName in pdf name * updated PR * Updated PR as per review * updated PR * updated PR * Updated build * [MOSIP-24494] Updated trasnliterate API error msg * updated PR * updated PR * [MOSIP-25363],[MOSIP-24796],[MOSIP-25711] Updated audit logs * [MOSIP-26089] Added authentication mode * MOSIP-22871-api-add-api-to-convert-the-list-of-registration-centers-request-as-a-downloadable-pdf (#847) * fixed id version for document APIs * update constant names * used constant file_text * added validation on req credential API * added validation for req credential API * removed duplicate code * fixed rid status issue * removed name from enum * code fix for rid status issue * update validate request body method * fixed registration center issue --------- Co-authored-by: Ritik Jain * Added debug logging filter (#849) * Added debug logging filter * Added jdoc * Minor cleanup --------- Co-authored-by: Loganathan Sekar * Mosip 22874 authtype lock websub issue 1 (#851) * Added debug logging filter * Added jdoc * Minor cleanup * Added condition for debug log * Added support to auto repeat of servlet request stream, added topic resubscription support * Minor fix * Removed unwanted file * Test fixes --------- Co-authored-by: Loganathan Sekar * Fixed Download UIN card using VID. (#848) * Fixed service history issue. * Fixed download card using vid. * MOSIP-24818 Changed deprecated admin module proxy API endpoint. (#852) * Fixed service history issue. * MOSIP-24818 Changed deprecated admin module proxy API endpoint. * MOSIP-24818 Removed un-necessary commits. * Mosip 22874 authtype lock websub issue 3 (#853) * Added debug logging filter * Added jdoc * Minor cleanup * Added condition for debug log * Added support to auto repeat of servlet request stream, added topic resubscription support * Minor fix * Removed unwanted file * Test fixes * Fix auth type lock unlock notification --------- Co-authored-by: Loganathan Sekar * Mosip 22874 authtype lock websub issue 3 (#854) * Added debug logging filter * Added jdoc * Minor cleanup * Added condition for debug log * Added support to auto repeat of servlet request stream, added topic resubscription support * Minor fix * Removed unwanted file * Test fixes * Fix auth type lock unlock notification * Fix for notification count for entries having olv partner id --------- Co-authored-by: Loganathan Sekar * Mosip 22874 authtype lock websub issue 4 (#855) * Added debug logging filter * Added jdoc * Minor cleanup * Added condition for debug log * Added support to auto repeat of servlet request stream, added topic resubscription support * Minor fix * Removed unwanted file * Test fixes * Fix auth type lock unlock notification * Fix for notification count for entries having olv partner id * junit fix --------- Co-authored-by: Loganathan Sekar * Mosip 22874 authtype lock websub issue 5 (#857) * Added debug logging filter * Added jdoc * Minor cleanup * Added condition for debug log * Added support to auto repeat of servlet request stream, added topic resubscription support * Minor fix * Removed unwanted file * Test fixes * Fix auth type lock unlock notification * Fix for notification count for entries having olv partner id * junit fix * WIP-fixing auth txn saving * Updated logic to save auth txn * Added Y and N status for getting description --------- Co-authored-by: Loganathan Sekar * Mosip 22874 authtype lock websub issue 5 (#858) * Added debug logging filter * Added jdoc * Minor cleanup * Added condition for debug log * Added support to auto repeat of servlet request stream, added topic resubscription support * Minor fix * Removed unwanted file * Test fixes * Fix auth type lock unlock notification * Fix for notification count for entries having olv partner id * junit fix * WIP-fixing auth txn saving * Updated logic to save auth txn * Added Y and N status for getting description * Test fix --------- Co-authored-by: Loganathan Sekar * Fixed Sonar bugs (#859) * [MOSIP-24670] Updated API correction id and version * [MOSIP-24670] Updated API body correction * [MOSIP-22640] Fixed Sonar Bugs * updated PR * updated PR * updated review code * [MOSIP-22640] Fixed sonar bugs * updated PR * updated PR * [MOSIP-22639] Resolved security hotspots in code * [MOSIP-24630] Fixed Security Vulnerability in code * added error for isValidUrl method * renamed vaildateURL method * updated PR * updated PR * [MOSIP-24670] Made corrections in id and version * resolved conflicts * updated PR * updated PR * [MOSIP-24670] Made corrections n API body, response code * updated PR * updated PR * updated dateTime * updated PR * [MOSIP-25539] Made corrections in API body, response code * [MOSIP-25539] made corrections in API body * updated error message * updated error code * updated trasactionid dto change * added equals * [MOSIP-25539] made corrections in api body * [MOSIP-25539] Corrected API response body Task 5 * resolved build failure * [MOSIP-25539] Task 2 Added error code for vaildateOtp API * updated PR * updated PR * updated PR * updated PR * [MOSIP-25539] Updated validateotp method * updated PR * [MOSIP-25798] Added validations * updated PR * updated PR * updated PR * updated PR * updated PR * [MOSIP-25791] Added purpose as mandatory * Added error * Added Audit logs * updated test cases * [MOSIP-22913],[MOSIP-22914],[MOSIP-24653],[MOSIP-24796] Added Audit logs * updated logs * updated auditlog code * updated enum name for audit logs * updated enum name for audit logs * updated enum name for audit logs * updated enum name for audit logs * updated enum name for audit logs * [MOSIP-25268] Fixed Sonar vulnerability * [MOSIP-25268] Fixed Sonar vulnerability * [MOSIP-26272] Added validation for /update-uin API * updated PR * updated update-uin PR * Fixed build issue * Updated transactionId error message * Updated Test cases ResidentServiceResUpdateTest class * [MOSIP-26343] Created module specific audits * updated PR * updated PR * [MOSIP-26087] Added featureName in pdf name * updated PR * Updated PR as per review * updated PR * updated PR * Updated build * [MOSIP-24494] Updated trasnliterate API error msg * updated PR * updated PR * [MOSIP-25363],[MOSIP-24796],[MOSIP-25711] Updated audit logs * [MOSIP-26089] Added authentication mode * Fixed Sonar Bugs * updated PR * updated as per review * Updated Sonar bug fix (#860) * [MOSIP-24670] Updated API correction id and version * [MOSIP-24670] Updated API body correction * [MOSIP-22640] Fixed Sonar Bugs * updated PR * updated PR * updated review code * [MOSIP-22640] Fixed sonar bugs * updated PR * updated PR * [MOSIP-22639] Resolved security hotspots in code * [MOSIP-24630] Fixed Security Vulnerability in code * added error for isValidUrl method * renamed vaildateURL method * updated PR * updated PR * [MOSIP-24670] Made corrections in id and version * resolved conflicts * updated PR * updated PR * [MOSIP-24670] Made corrections n API body, response code * updated PR * updated PR * updated dateTime * updated PR * [MOSIP-25539] Made corrections in API body, response code * [MOSIP-25539] made corrections in API body * updated error message * updated error code * updated trasactionid dto change * added equals * [MOSIP-25539] made corrections in api body * [MOSIP-25539] Corrected API response body Task 5 * resolved build failure * [MOSIP-25539] Task 2 Added error code for vaildateOtp API * updated PR * updated PR * updated PR * updated PR * [MOSIP-25539] Updated validateotp method * updated PR * [MOSIP-25798] Added validations * updated PR * updated PR * updated PR * updated PR * updated PR * [MOSIP-25791] Added purpose as mandatory * Added error * Added Audit logs * updated test cases * [MOSIP-22913],[MOSIP-22914],[MOSIP-24653],[MOSIP-24796] Added Audit logs * updated logs * updated auditlog code * updated enum name for audit logs * updated enum name for audit logs * updated enum name for audit logs * updated enum name for audit logs * updated enum name for audit logs * [MOSIP-25268] Fixed Sonar vulnerability * [MOSIP-25268] Fixed Sonar vulnerability * [MOSIP-26272] Added validation for /update-uin API * updated PR * updated update-uin PR * Fixed build issue * Updated transactionId error message * Updated Test cases ResidentServiceResUpdateTest class * [MOSIP-26343] Created module specific audits * updated PR * updated PR * [MOSIP-26087] Added featureName in pdf name * updated PR * Updated PR as per review * updated PR * updated PR * Updated build * [MOSIP-24494] Updated trasnliterate API error msg * updated PR * updated PR * [MOSIP-25363],[MOSIP-24796],[MOSIP-25711] Updated audit logs * [MOSIP-26089] Added authentication mode * Fixed Sonar Bugs * updated PR * updated as per review * Updated Sonar Fix * Updated Sonar bug fix (#861) * [MOSIP-24670] Updated API correction id and version * [MOSIP-24670] Updated API body correction * [MOSIP-22640] Fixed Sonar Bugs * updated PR * updated PR * updated review code * [MOSIP-22640] Fixed sonar bugs * updated PR * updated PR * [MOSIP-22639] Resolved security hotspots in code * [MOSIP-24630] Fixed Security Vulnerability in code * added error for isValidUrl method * renamed vaildateURL method * updated PR * updated PR * [MOSIP-24670] Made corrections in id and version * resolved conflicts * updated PR * updated PR * [MOSIP-24670] Made corrections n API body, response code * updated PR * updated PR * updated dateTime * updated PR * [MOSIP-25539] Made corrections in API body, response code * [MOSIP-25539] made corrections in API body * updated error message * updated error code * updated trasactionid dto change * added equals * [MOSIP-25539] made corrections in api body * [MOSIP-25539] Corrected API response body Task 5 * resolved build failure * [MOSIP-25539] Task 2 Added error code for vaildateOtp API * updated PR * updated PR * updated PR * updated PR * [MOSIP-25539] Updated validateotp method * updated PR * [MOSIP-25798] Added validations * updated PR * updated PR * updated PR * updated PR * updated PR * [MOSIP-25791] Added purpose as mandatory * Added error * Added Audit logs * updated test cases * [MOSIP-22913],[MOSIP-22914],[MOSIP-24653],[MOSIP-24796] Added Audit logs * updated logs * updated auditlog code * updated enum name for audit logs * updated enum name for audit logs * updated enum name for audit logs * updated enum name for audit logs * updated enum name for audit logs * [MOSIP-25268] Fixed Sonar vulnerability * [MOSIP-25268] Fixed Sonar vulnerability * [MOSIP-26272] Added validation for /update-uin API * updated PR * updated update-uin PR * Fixed build issue * Updated transactionId error message * Updated Test cases ResidentServiceResUpdateTest class * [MOSIP-26343] Created module specific audits * updated PR * updated PR * [MOSIP-26087] Added featureName in pdf name * updated PR * Updated PR as per review * updated PR * updated PR * Updated build * [MOSIP-24494] Updated trasnliterate API error msg * updated PR * updated PR * [MOSIP-25363],[MOSIP-24796],[MOSIP-25711] Updated audit logs * [MOSIP-26089] Added authentication mode * Fixed Sonar Bugs * updated PR * updated as per review * Updated Sonar Fix * Updated Sonar bug fix * MOSIP-22874-tech-story-check-the-email-sms-notification-messages (#863) * fixed id version for document APIs * update constant names * used constant file_text * added validation on req credential API * added validation for req credential API * removed duplicate code * fixed rid status issue * removed name from enum * code fix for rid status issue * update validate request body method * fixed registration center issue * added notification in validate otp API * fixed authentication request description * removed space --------- Co-authored-by: Ritik Jain * Mosip 22874 authtype lock websub issue 6 (#864) * Added debug logging filter * Added jdoc * Minor cleanup * Added condition for debug log * Added support to auto repeat of servlet request stream, added topic resubscription support * Minor fix * Removed unwanted file * Test fixes * Fix auth type lock unlock notification * Fix for notification count for entries having olv partner id * junit fix * WIP-fixing auth txn saving * Updated logic to save auth txn * Added Y and N status for getting description * Test fix * Fix for parse issue in event model with timestamp coming as list in websub callbacks * Test fix --------- Co-authored-by: Loganathan Sekar * fixed service type (#865) * fixed id version for document APIs * update constant names * used constant file_text * added validation on req credential API * added validation for req credential API * removed duplicate code * fixed rid status issue * removed name from enum * code fix for rid status issue * update validate request body method * fixed registration center issue * added notification in validate otp API * fixed authentication request description * removed space * removed validate otp from auth request service type --------- Co-authored-by: Ritik Jain * Mosip 22874 authtype lock websub issue 8 (#867) * Added debug logging filter * Added jdoc * Minor cleanup * Added condition for debug log * Added support to auto repeat of servlet request stream, added topic resubscription support * Minor fix * Removed unwanted file * Test fixes * Fix auth type lock unlock notification * Fix for notification count for entries having olv partner id * junit fix * WIP-fixing auth txn saving * Updated logic to save auth txn * Added Y and N status for getting description * Test fix * Fix for parse issue in event model with timestamp coming as list in websub callbacks * Test fix * Fix to include auth request in all category * Fixed all request types --------- Co-authored-by: Loganathan Sekar * Updated Sonar bug fix (#862) * [MOSIP-24670] Updated API correction id and version * [MOSIP-24670] Updated API body correction * [MOSIP-22640] Fixed Sonar Bugs * updated PR * updated PR * updated review code * [MOSIP-22640] Fixed sonar bugs * updated PR * updated PR * [MOSIP-22639] Resolved security hotspots in code * [MOSIP-24630] Fixed Security Vulnerability in code * added error for isValidUrl method * renamed vaildateURL method * updated PR * updated PR * [MOSIP-24670] Made corrections in id and version * resolved conflicts * updated PR * updated PR * [MOSIP-24670] Made corrections n API body, response code * updated PR * updated PR * updated dateTime * updated PR * [MOSIP-25539] Made corrections in API body, response code * [MOSIP-25539] made corrections in API body * updated error message * updated error code * updated trasactionid dto change * added equals * [MOSIP-25539] made corrections in api body * [MOSIP-25539] Corrected API response body Task 5 * resolved build failure * [MOSIP-25539] Task 2 Added error code for vaildateOtp API * updated PR * updated PR * updated PR * updated PR * [MOSIP-25539] Updated validateotp method * updated PR * [MOSIP-25798] Added validations * updated PR * updated PR * updated PR * updated PR * updated PR * [MOSIP-25791] Added purpose as mandatory * Added error * Added Audit logs * updated test cases * [MOSIP-22913],[MOSIP-22914],[MOSIP-24653],[MOSIP-24796] Added Audit logs * updated logs * updated auditlog code * updated enum name for audit logs * updated enum name for audit logs * updated enum name for audit logs * updated enum name for audit logs * updated enum name for audit logs * [MOSIP-25268] Fixed Sonar vulnerability * [MOSIP-25268] Fixed Sonar vulnerability * [MOSIP-26272] Added validation for /update-uin API * updated PR * updated update-uin PR * Fixed build issue * Updated transactionId error message * Updated Test cases ResidentServiceResUpdateTest class * [MOSIP-26343] Created module specific audits * updated PR * updated PR * [MOSIP-26087] Added featureName in pdf name * updated PR * Updated PR as per review * updated PR * updated PR * Updated build * [MOSIP-24494] Updated trasnliterate API error msg * updated PR * updated PR * [MOSIP-25363],[MOSIP-24796],[MOSIP-25711] Updated audit logs * [MOSIP-26089] Added authentication mode * Fixed Sonar Bugs * updated PR * updated as per review * Updated Sonar Fix * Updated Sonar bug fix * Updated Sonar bug fix * Updated Sonar bug fix * Updated Sonar bug fix * Updated Sonar bug fix * MOSIP-26923 Corrected error code for maximum allowed vid. (#868) * Fixed service history issue. * MOSIP-26923 Corrected error code for maximum allowed vid. * MOSIP-26923 Added if condition for vidAlreadyPresent Exception class. * Updated sonar bug fix (#869) * [MOSIP-24670] Updated API correction id and version * [MOSIP-24670] Updated API body correction * [MOSIP-22640] Fixed Sonar Bugs * updated PR * updated PR * updated review code * [MOSIP-22640] Fixed sonar bugs * updated PR * updated PR * [MOSIP-22639] Resolved security hotspots in code * [MOSIP-24630] Fixed Security Vulnerability in code * added error for isValidUrl method * renamed vaildateURL method * updated PR * updated PR * [MOSIP-24670] Made corrections in id and version * resolved conflicts * updated PR * updated PR * [MOSIP-24670] Made corrections n API body, response code * updated PR * updated PR * updated dateTime * updated PR * [MOSIP-25539] Made corrections in API body, response code * [MOSIP-25539] made corrections in API body * updated error message * updated error code * updated trasactionid dto change * added equals * [MOSIP-25539] made corrections in api body * [MOSIP-25539] Corrected API response body Task 5 * resolved build failure * [MOSIP-25539] Task 2 Added error code for vaildateOtp API * updated PR * updated PR * updated PR * updated PR * [MOSIP-25539] Updated validateotp method * updated PR * [MOSIP-25798] Added validations * updated PR * updated PR * updated PR * updated PR * updated PR * [MOSIP-25791] Added purpose as mandatory * Added error * Added Audit logs * updated test cases * [MOSIP-22913],[MOSIP-22914],[MOSIP-24653],[MOSIP-24796] Added Audit logs * updated logs * updated auditlog code * updated enum name for audit logs * updated enum name for audit logs * updated enum name for audit logs * updated enum name for audit logs * updated enum name for audit logs * [MOSIP-25268] Fixed Sonar vulnerability * [MOSIP-25268] Fixed Sonar vulnerability * [MOSIP-26272] Added validation for /update-uin API * updated PR * updated update-uin PR * Fixed build issue * Updated transactionId error message * Updated Test cases ResidentServiceResUpdateTest class * [MOSIP-26343] Created module specific audits * updated PR * updated PR * [MOSIP-26087] Added featureName in pdf name * updated PR * Updated PR as per review * updated PR * updated PR * Updated build * [MOSIP-24494] Updated trasnliterate API error msg * updated PR * updated PR * [MOSIP-25363],[MOSIP-24796],[MOSIP-25711] Updated audit logs * [MOSIP-26089] Added authentication mode * Fixed Sonar Bugs * updated PR * updated as per review * Updated Sonar Fix * Updated Sonar bug fix * Updated Sonar bug fix * Updated Sonar bug fix * Updated Sonar bug fix * Updated Sonar bug fix * Updated Sonar bug fix * [MOSIP-25793] Added audit logs for credential failure (#871) * [MOSIP-24670] Updated API correction id and version * [MOSIP-24670] Updated API body correction * [MOSIP-22640] Fixed Sonar Bugs * updated PR * updated PR * updated review code * [MOSIP-22640] Fixed sonar bugs * updated PR * updated PR * [MOSIP-22639] Resolved security hotspots in code * [MOSIP-24630] Fixed Security Vulnerability in code * added error for isValidUrl method * renamed vaildateURL method * updated PR * updated PR * [MOSIP-24670] Made corrections in id and version * resolved conflicts * updated PR * updated PR * [MOSIP-24670] Made corrections n API body, response code * updated PR * updated PR * updated dateTime * updated PR * [MOSIP-25539] Made corrections in API body, response code * [MOSIP-25539] made corrections in API body * updated error message * updated error code * updated trasactionid dto change * added equals * [MOSIP-25539] made corrections in api body * [MOSIP-25539] Corrected API response body Task 5 * resolved build failure * [MOSIP-25539] Task 2 Added error code for vaildateOtp API * updated PR * updated PR * updated PR * updated PR * [MOSIP-25539] Updated validateotp method * updated PR * [MOSIP-25798] Added validations * updated PR * updated PR * updated PR * updated PR * updated PR * [MOSIP-25791] Added purpose as mandatory * Added error * Added Audit logs * updated test cases * [MOSIP-22913],[MOSIP-22914],[MOSIP-24653],[MOSIP-24796] Added Audit logs * updated logs * updated auditlog code * updated enum name for audit logs * updated enum name for audit logs * updated enum name for audit logs * updated enum name for audit logs * updated enum name for audit logs * [MOSIP-25268] Fixed Sonar vulnerability * [MOSIP-25268] Fixed Sonar vulnerability * [MOSIP-26272] Added validation for /update-uin API * updated PR * updated update-uin PR * Fixed build issue * Updated transactionId error message * Updated Test cases ResidentServiceResUpdateTest class * [MOSIP-26343] Created module specific audits * updated PR * updated PR * [MOSIP-26087] Added featureName in pdf name * updated PR * Updated PR as per review * updated PR * updated PR * Updated build * [MOSIP-24494] Updated trasnliterate API error msg * updated PR * updated PR * [MOSIP-25363],[MOSIP-24796],[MOSIP-25711] Updated audit logs * [MOSIP-26089] Added authentication mode * Fixed Sonar Bugs * updated PR * updated as per review * Updated Sonar Fix * Updated Sonar bug fix * Updated Sonar bug fix * Updated Sonar bug fix * Updated Sonar bug fix * Updated Sonar bug fix * Updated Sonar bug fix * [MOSIP-25793] Added audit logs * MOSIP-22874-tech-story-check-the-email-sms-notification-messages (#870) * fixed id version for document APIs * update constant names * used constant file_text * added validation on req credential API * added validation for req credential API * removed duplicate code * fixed rid status issue * removed name from enum * code fix for rid status issue * update validate request body method * fixed registration center issue * added notification in validate otp API * fixed authentication request description * removed space * removed validate otp from auth request service type * added notification to get my uin API * added notification in personalised card API * fixed null check * refactor code --------- Co-authored-by: Ritik Jain * MOSIP-26923 Return Http status 200 for error message. (#879) * Fixed service history issue. * MOSIP-26923 Corrected error code for maximum allowed vid. * MOSIP-26923 Added if condition for vidAlreadyPresent Exception class. * MOSIP-26923 Return Http status 200 for error message. * Fixed Build failure (#881) * Fixed service history issue. * Fixed build failure. * MOSIP-26954 Added date of birth to vid card. (#880) * Fixed service history issue. * MOSIP-26954 Added date of birth to vid card. * MOSIP-26844 & fixed code for notification and track service (#878) * fixed id version for document APIs * update constant names * used constant file_text * added validation on req credential API * added validation for req credential API * removed duplicate code * fixed rid status issue * removed name from enum * code fix for rid status issue * update validate request body method * fixed registration center issue * added notification in validate otp API * fixed authentication request description * removed space * removed validate otp from auth request service type * added notification to get my uin API * added notification in personalised card API * fixed null check * refactor code * fixed code for notify * code refactoring * fixed test case failure * take templatetype code from properties --------- Co-authored-by: Ritik Jain * Fixed sonar bug (#884) * [MOSIP-24670] Updated API correction id and version * [MOSIP-24670] Updated API body correction * [MOSIP-22640] Fixed Sonar Bugs * updated PR * updated PR * updated review code * [MOSIP-22640] Fixed sonar bugs * updated PR * updated PR * [MOSIP-22639] Resolved security hotspots in code * [MOSIP-24630] Fixed Security Vulnerability in code * added error for isValidUrl method * renamed vaildateURL method * updated PR * updated PR * [MOSIP-24670] Made corrections in id and version * resolved conflicts * updated PR * updated PR * [MOSIP-24670] Made corrections n API body, response code * updated PR * updated PR * updated dateTime * updated PR * [MOSIP-25539] Made corrections in API body, response code * [MOSIP-25539] made corrections in API body * updated error message * updated error code * updated trasactionid dto change * added equals * [MOSIP-25539] made corrections in api body * [MOSIP-25539] Corrected API response body Task 5 * resolved build failure * [MOSIP-25539] Task 2 Added error code for vaildateOtp API * updated PR * updated PR * updated PR * updated PR * [MOSIP-25539] Updated validateotp method * updated PR * [MOSIP-25798] Added validations * updated PR * updated PR * updated PR * updated PR * updated PR * [MOSIP-25791] Added purpose as mandatory * Added error * Added Audit logs * updated test cases * [MOSIP-22913],[MOSIP-22914],[MOSIP-24653],[MOSIP-24796] Added Audit logs * updated logs * updated auditlog code * updated enum name for audit logs * updated enum name for audit logs * updated enum name for audit logs * updated enum name for audit logs * updated enum name for audit logs * [MOSIP-25268] Fixed Sonar vulnerability * [MOSIP-25268] Fixed Sonar vulnerability * [MOSIP-26272] Added validation for /update-uin API * updated PR * updated update-uin PR * Fixed build issue * Updated transactionId error message * Updated Test cases ResidentServiceResUpdateTest class * [MOSIP-26343] Created module specific audits * updated PR * updated PR * [MOSIP-26087] Added featureName in pdf name * updated PR * Updated PR as per review * updated PR * updated PR * Updated build * [MOSIP-24494] Updated trasnliterate API error msg * updated PR * updated PR * [MOSIP-25363],[MOSIP-24796],[MOSIP-25711] Updated audit logs * [MOSIP-26089] Added authentication mode * Fixed Sonar Bugs * updated PR * updated as per review * Updated Sonar Fix * Updated Sonar bug fix * Updated Sonar bug fix * Updated Sonar bug fix * Updated Sonar bug fix * Updated Sonar bug fix * Updated Sonar bug fix * [MOSIP-25793] Added audit logs * Fixed sonar bug * Fixed sonar bug * MOSIP-26899 Added flag for preferred lang. (#885) * Fixed service history issue. * MOSIP-26899 Added flag for preferred lang. * MOSIP-26899 Added flag for preferred lang. * MOSIP-26899 Added flag for preferred lang. * MOSIP-26899 Added flag for preferred lang. * MOSIP-26899 Added flag for preferred lang. * fixed code to get correct attribute list (#886) * fixed code to get attribute list * fixed null check --------- Co-authored-by: Ritik Jain * Develop optimize async processing with websub callback (#887) * WIP-for-credential update callback * Fixed conditions for updating the auth type lock status query * Added debug statements --------- Co-authored-by: Loganathan Sekar * Develop optimize async processing with websub callback (#888) * WIP-for-credential update callback * Fixed conditions for updating the auth type lock status query * Added debug statements * Test fix --------- Co-authored-by: Loganathan Sekar * Develop optimize async processing with websub callback (#889) * WIP-for-credential update callback * Fixed conditions for updating the auth type lock status query * Added debug statements * Test fix * Test fix --------- Co-authored-by: Loganathan Sekar * MOSIP-27035-in-update-my-data-page-getting-error-message-like-invalid-input-parameter-transaction-id-when-we-update-the-language-preference (#882) * fixed id version for document APIs * update constant names * used constant file_text * added validation on req credential API * added validation for req credential API * removed duplicate code * fixed rid status issue * removed name from enum * code fix for rid status issue * update validate request body method * fixed registration center issue * added notification in validate otp API * fixed authentication request description * removed space * removed validate otp from auth request service type * added notification to get my uin API * added notification in personalised card API * fixed null check * refactor code * fixed code for notify * code refactoring * fixed test case failure * take templatetype code from properties * fixed preferred language doc error * fixed code * renamed variable * take list from property * removed unused import * added comment and changed list to stream --------- Co-authored-by: Ritik Jain * Added preferred lang code from value for notification (#890) * Fixed service history issue. * Added preferred lang code from value for notification * Converted for loop into stream API. * Used @value instead of env.get property. * MOSIP-26981-resident-ui-in-share-my-data-after-download-the-pdf-selected-attributes-is-not-showing-in-the-downloaded-pdf (#891) * fixed id version for document APIs * update constant names * used constant file_text * added validation on req credential API * added validation for req credential API * removed duplicate code * fixed rid status issue * removed name from enum * code fix for rid status issue * update validate request body method * fixed registration center issue * added notification in validate otp API * fixed authentication request description * removed space * removed validate otp from auth request service type * added notification to get my uin API * added notification in personalised card API * fixed null check * refactor code * fixed code for notify * code refactoring * fixed test case failure * take templatetype code from properties * fixed preferred language doc error * fixed code * renamed variable * take list from property * removed unused import * added comment and changed list to stream * added photo to attribute list --------- Co-authored-by: Ritik Jain * Develop optimize async processing with websub callback (#892) * WIP-for-credential update callback * Fixed conditions for updating the auth type lock status query * Added debug statements * Test fix * Test fix * Added code for credential status update callback * Test fix --------- Co-authored-by: Loganathan Sekar * MOSIP-26579-resident-ui-after-sharing-the-credential-with-the-partner-in-view-history-the-description-is-not-proper (#893) * fixed id version for document APIs * update constant names * used constant file_text * added validation on req credential API * added validation for req credential API * removed duplicate code * fixed rid status issue * removed name from enum * code fix for rid status issue * update validate request body method * fixed registration center issue * added notification in validate otp API * fixed authentication request description * removed space * removed validate otp from auth request service type * added notification to get my uin API * added notification in personalised card API * fixed null check * refactor code * fixed code for notify * code refactoring * fixed test case failure * take templatetype code from properties * fixed preferred language doc error * fixed code * renamed variable * take list from property * removed unused import * added comment and changed list to stream * added photo to attribute list * fixed update uin summary and purpose * fixed summary description for share-credential API --------- Co-authored-by: Ritik Jain * MOSIP-27014 Fixed ack template issue. (#894) * Fixed service history issue. * MOSIP-27014 Fixed ack template issue. * Fixed Sonar Bug (#895) * [MOSIP-24670] Updated API correction id and version * [MOSIP-24670] Updated API body correction * [MOSIP-22640] Fixed Sonar Bugs * updated PR * updated PR * updated review code * [MOSIP-22640] Fixed sonar bugs * updated PR * updated PR * [MOSIP-22639] Resolved security hotspots in code * [MOSIP-24630] Fixed Security Vulnerability in code * added error for isValidUrl method * renamed vaildateURL method * updated PR * updated PR * [MOSIP-24670] Made corrections in id and version * resolved conflicts * updated PR * updated PR * [MOSIP-24670] Made corrections n API body, response code * updated PR * updated PR * updated dateTime * updated PR * [MOSIP-25539] Made corrections in API body, response code * [MOSIP-25539] made corrections in API body * updated error message * updated error code * updated trasactionid dto change * added equals * [MOSIP-25539] made corrections in api body * [MOSIP-25539] Corrected API response body Task 5 * resolved build failure * [MOSIP-25539] Task 2 Added error code for vaildateOtp API * updated PR * updated PR * updated PR * updated PR * [MOSIP-25539] Updated validateotp method * updated PR * [MOSIP-25798] Added validations * updated PR * updated PR * updated PR * updated PR * updated PR * [MOSIP-25791] Added purpose as mandatory * Added error * Added Audit logs * updated test cases * [MOSIP-22913],[MOSIP-22914],[MOSIP-24653],[MOSIP-24796] Added Audit logs * updated logs * updated auditlog code * updated enum name for audit logs * updated enum name for audit logs * updated enum name for audit logs * updated enum name for audit logs * updated enum name for audit logs * [MOSIP-25268] Fixed Sonar vulnerability * [MOSIP-25268] Fixed Sonar vulnerability * [MOSIP-26272] Added validation for /update-uin API * updated PR * updated update-uin PR * Fixed build issue * Updated transactionId error message * Updated Test cases ResidentServiceResUpdateTest class * [MOSIP-26343] Created module specific audits * updated PR * updated PR * [MOSIP-26087] Added featureName in pdf name * updated PR * Updated PR as per review * updated PR * updated PR * Updated build * [MOSIP-24494] Updated trasnliterate API error msg * updated PR * updated PR * [MOSIP-25363],[MOSIP-24796],[MOSIP-25711] Updated audit logs * [MOSIP-26089] Added authentication mode * Fixed Sonar Bugs * updated PR * updated as per review * Updated Sonar Fix * Updated Sonar bug fix * Updated Sonar bug fix * Updated Sonar bug fix * Updated Sonar bug fix * Updated Sonar bug fix * Updated Sonar bug fix * [MOSIP-25793] Added audit logs * Fixed sonar bug * Fixed sonar bug * Fixed Sonar Bug * Updated Sonar Fix * Fixed build failure (#896) * [MOSIP-24670] Updated API correction id and version * [MOSIP-24670] Updated API body correction * [MOSIP-22640] Fixed Sonar Bugs * updated PR * updated PR * updated review code * [MOSIP-22640] Fixed sonar bugs * updated PR * updated PR * [MOSIP-22639] Resolved security hotspots in code * [MOSIP-24630] Fixed Security Vulnerability in code * added error for isValidUrl method * renamed vaildateURL method * updated PR * updated PR * [MOSIP-24670] Made corrections in id and version * resolved conflicts * updated PR * updated PR * [MOSIP-24670] Made corrections n API body, response code * updated PR * updated PR * updated dateTime * updated PR * [MOSIP-25539] Made corrections in API body, response code * [MOSIP-25539] made corrections in API body * updated error message * updated error code * updated trasactionid dto change * added equals * [MOSIP-25539] made corrections in api body * [MOSIP-25539] Corrected API response body Task 5 * resolved build failure * [MOSIP-25539] Task 2 Added error code for vaildateOtp API * updated PR * updated PR * updated PR * updated PR * [MOSIP-25539] Updated validateotp method * updated PR * [MOSIP-25798] Added validations * updated PR * updated PR * updated PR * updated PR * updated PR * [MOSIP-25791] Added purpose as mandatory * Added error * Added Audit logs * updated test cases * [MOSIP-22913],[MOSIP-22914],[MOSIP-24653],[MOSIP-24796] Added Audit logs * updated logs * updated auditlog code * updated enum name for audit logs * updated enum name for audit logs * updated enum name for audit logs * updated enum name for audit logs * updated enum name for audit logs * [MOSIP-25268] Fixed Sonar vulnerability * [MOSIP-25268] Fixed Sonar vulnerability * [MOSIP-26272] Added validation for /update-uin API * updated PR * updated update-uin PR * Fixed build issue * Updated transactionId error message * Updated Test cases ResidentServiceResUpdateTest class * [MOSIP-26343] Created module specific audits * updated PR * updated PR * [MOSIP-26087] Added featureName in pdf name * updated PR * Updated PR as per review * updated PR * updated PR * Updated build * [MOSIP-24494] Updated trasnliterate API error msg * updated PR * updated PR * [MOSIP-25363],[MOSIP-24796],[MOSIP-25711] Updated audit logs * [MOSIP-26089] Added authentication mode * Fixed Sonar Bugs * updated PR * updated as per review * Updated Sonar Fix * Updated Sonar bug fix * Updated Sonar bug fix * Updated Sonar bug fix * Updated Sonar bug fix * Updated Sonar bug fix * Updated Sonar bug fix * [MOSIP-25793] Added audit logs * Fixed sonar bug * Fixed sonar bug * Fixed Sonar Bug * Updated Sonar Fix * Fixed build failure * MOSIP-27155-api-description-purpose-and-summary-is-not-matching-in-acknowledgement-and-track-service-api (#897) * fixed id version for document APIs * update constant names * used constant file_text * added validation on req credential API * added validation for req credential API * removed duplicate code * fixed rid status issue * removed name from enum * code fix for rid status issue * update validate request body method * fixed registration center issue * added notification in validate otp API * fixed authentication request description * removed space * removed validate otp from auth request service type * added notification to get my uin API * added notification in personalised card API * fixed null check * refactor code * fixed code for notify * code refactoring * fixed test case failure * take templatetype code from properties * fixed preferred language doc error * fixed code * renamed variable * take list from property * removed unused import * added comment and changed list to stream * added photo to attribute list * fixed update uin summary and purpose * fixed summary description for share-credential API * fixed acknowledgement summary purpose * fixed summary issue * white spaces * fixed authentication mode issue --------- Co-authored-by: Ritik Jain * MOSIP-27036, MOSIP-27155-api-description-purpose-and-summary-is-not-matching-in-acknowledgement-and-track-service-api (#899) * fixed id version for document APIs * update constant names * used constant file_text * added validation on req credential API * added validation for req credential API * removed duplicate code * fixed rid status issue * removed name from enum * code fix for rid status issue * update validate request body method * fixed registration center issue * added notification in validate otp API * fixed authentication request description * removed space * removed validate otp from auth request service type * added notification to get my uin API * added notification in personalised card API * fixed null check * refactor code * fixed code for notify * code refactoring * fixed test case failure * take templatetype code from properties * fixed preferred language doc error * fixed code * renamed variable * take list from property * removed unused import * added comment and changed list to stream * added photo to attribute list * fixed update uin summary and purpose * fixed summary description for share-credential API * fixed acknowledgement summary purpose * fixed summary issue * white spaces * fixed authentication mode issue * changed from purpose to attribute list * fixed db calling multiple times issue * MOSIP-27036 fixed the summary * review comments --------- Co-authored-by: Ritik Jain * MOSIP-27079 Fixed notification issue. (#898) * Fixed service history issue. * MOSIP-27079 Fixed notification issue. * MOSIP-27079 Fixed notification issue. * MOSIP-27079 Added imports. * MOSIP-27079 Added imports. * MOSIP-27079 Added imports. * MOSIP-27079 Refactor code as per comment * MOSIP-27079 Refactor code as per comment * MOSIP-27079 Refactor code as per comment * MOSIP-27079 Added null check. * MOSIP-26984-resident-ui-in-share-my-data-the-format-details-are-not-displayed-properly-in-the-downloaded-pdf-for-name-dob-address (#900) * fixed id version for document APIs * update constant names * used constant file_text * added validation on req credential API * added validation for req credential API * removed duplicate code * fixed rid status issue * removed name from enum * code fix for rid status issue * update validate request body method * fixed registration center issue * added notification in validate otp API * fixed authentication request description * removed space * removed validate otp from auth request service type * added notification to get my uin API * added notification in personalised card API * fixed null check * refactor code * fixed code for notify * code refactoring * fixed test case failure * take templatetype code from properties * fixed preferred language doc error * fixed code * renamed variable * take list from property * removed unused import * added comment and changed list to stream * added photo to attribute list * fixed update uin summary and purpose * fixed summary description for share-credential API * fixed acknowledgement summary purpose * fixed summary issue * white spaces * fixed authentication mode issue * changed from purpose to attribute list * fixed db calling multiple times issue * MOSIP-27036 fixed the summary * review comments * removed unused method * code refactoring * added cause --------- Co-authored-by: Ritik Jain * Error code fix for invalid uin/vid (#903) * Fixed service history issue. * Move latest develop to develop 1.2.1 * MOSIP-26586-resident-in-secure-my-id-after-locked-and-unlocked-in-view-history-description-is-not-proper (#906) * fixed id version for document APIs * update constant names * used constant file_text * added validation on req credential API * added validation for req credential API * removed duplicate code * fixed rid status issue * removed name from enum * code fix for rid status issue * update validate request body method * fixed registration center issue * added notification in validate otp API * fixed authentication request description * removed space * removed validate otp from auth request service type * added notification to get my uin API * added notification in personalised card API * fixed null check * refactor code * fixed code for notify * code refactoring * fixed test case failure * take templatetype code from properties * fixed preferred language doc error * fixed code * renamed variable * take list from property * removed unused import * added comment and changed list to stream * added photo to attribute list * fixed update uin summary and purpose * fixed summary description for share-credential API * fixed acknowledgement summary purpose * fixed summary issue * white spaces * fixed authentication mode issue * changed from purpose to attribute list * fixed db calling multiple times issue * MOSIP-27036 fixed the summary * review comments * removed unused method * code refactoring * added cause * fixed description issue in auth lock unlock API * added comment --------- Co-authored-by: Ritik Jain * [MOSIP-27213] Updated ObjectValidator method (#907) * [MOSIP-24670] Updated API correction id and version * [MOSIP-24670] Updated API body correction * [MOSIP-22640] Fixed Sonar Bugs * updated PR * updated PR * updated review code * [MOSIP-22640] Fixed sonar bugs * updated PR * updated PR * [MOSIP-22639] Resolved security hotspots in code * [MOSIP-24630] Fixed Security Vulnerability in code * added error for isValidUrl method * renamed vaildateURL method * updated PR * updated PR * [MOSIP-24670] Made corrections in id and version * resolved conflicts * updated PR * updated PR * [MOSIP-24670] Made corrections n API body, response code * updated PR * updated PR * updated dateTime * updated PR * [MOSIP-25539] Made corrections in API body, response code * [MOSIP-25539] made corrections in API body * updated error message * updated error code * updated trasactionid dto change * added equals * [MOSIP-25539] made corrections in api body * [MOSIP-25539] Corrected API response body Task 5 * resolved build failure * [MOSIP-25539] Task 2 Added error code for vaildateOtp API * updated PR * updated PR * updated PR * updated PR * [MOSIP-25539] Updated validateotp method * updated PR * [MOSIP-25798] Added validations * updated PR * updated PR * updated PR * updated PR * updated PR * [MOSIP-25791] Added purpose as mandatory * Added error * Added Audit logs * updated test cases * [MOSIP-22913],[MOSIP-22914],[MOSIP-24653],[MOSIP-24796] Added Audit logs * updated logs * updated auditlog code * updated enum name for audit logs * updated enum name for audit logs * updated enum name for audit logs * updated enum name for audit logs * updated enum name for audit logs * [MOSIP-25268] Fixed Sonar vulnerability * [MOSIP-25268] Fixed Sonar vulnerability * [MOSIP-26272] Added validation for /update-uin API * updated PR * updated update-uin PR * Fixed build issue * Updated transactionId error message * Updated Test cases ResidentServiceResUpdateTest class * [MOSIP-26343] Created module specific audits * updated PR * updated PR * [MOSIP-26087] Added featureName in pdf name * updated PR * Updated PR as per review * updated PR * updated PR * Updated build * [MOSIP-24494] Updated trasnliterate API error msg * updated PR * updated PR * [MOSIP-25363],[MOSIP-24796],[MOSIP-25711] Updated audit logs * [MOSIP-26089] Added authentication mode * Fixed Sonar Bugs * updated PR * updated as per review * Updated Sonar Fix * Updated Sonar bug fix * Updated Sonar bug fix * Updated Sonar bug fix * Updated Sonar bug fix * Updated Sonar bug fix * Updated Sonar bug fix * [MOSIP-25793] Added audit logs * Fixed sonar bug * Fixed sonar bug * Fixed Sonar Bug * Updated Sonar Fix * Fixed build failure * [MOSIP-27213] Updated update-uin method * [MOSIP-27213] Updated ObjectValidator method * [MOSIP-27213] Updated ObjectValidator method * [MOSIP-27213] Updated ObjectValidator method * MOSIP-26586-resident-in-secure-my-id-after-locked-and-unlocked-in-view-history-description-is-not-proper (#908) * fixed id version for document APIs * update constant names * used constant file_text * added validation on req credential API * added validation for req credential API * removed duplicate code * fixed rid status issue * removed name from enum * code fix for rid status issue * update validate request body method * fixed registration center issue * added notification in validate otp API * fixed authentication request description * removed space * removed validate otp from auth request service type * added notification to get my uin API * added notification in personalised card API * fixed null check * refactor code * fixed code for notify * code refactoring * fixed test case failure * take templatetype code from properties * fixed preferred language doc error * fixed code * renamed variable * take list from property * removed unused import * added comment and changed list to stream * added photo to attribute list * fixed update uin summary and purpose * fixed summary description for share-credential API * fixed acknowledgement summary purpose * fixed summary issue * white spaces * fixed authentication mode issue * changed from purpose to attribute list * fixed db calling multiple times issue * MOSIP-27036 fixed the summary * review comments * removed unused method * code refactoring * added cause * fixed description issue in auth lock unlock API * added comment * used contant delimiter --------- Co-authored-by: Ritik Jain * MOSIP-26586-resident-in-secure-my-id-after-locked-and-unlocked-in-view-history-description-is-not-proper (#909) * fixed id version for document APIs * update constant names * used constant file_text * added validation on req credential API * added validation for req credential API * removed duplicate code * fixed rid status issue * removed name from enum * code fix for rid status issue * update validate request body method * fixed registration center issue * added notification in validate otp API * fixed authentication request description * removed space * removed validate otp from auth request service type * added notification to get my uin API * added notification in personalised card API * fixed null check * refactor code * fixed code for notify * code refactoring * fixed test case failure * take templatetype code from properties * fixed preferred language doc error * fixed code * renamed variable * take list from property * removed unused import * added comment and changed list to stream * added photo to attribute list * fixed update uin summary and purpose * fixed summary description for share-credential API * fixed acknowledgement summary purpose * fixed summary issue * white spaces * fixed authentication mode issue * changed from purpose to attribute list * fixed db calling multiple times issue * MOSIP-27036 fixed the summary * review comments * removed unused method * code refactoring * added cause * fixed description issue in auth lock unlock API * added comment * used contant delimiter * fixed status to take from templates --------- Co-authored-by: Ritik Jain * fixed callback/authTransaction status code failure (#910) * fixed id version for document APIs * update constant names * used constant file_text * added validation on req credential API * added validation for req credential API * removed duplicate code * fixed rid status issue * removed name from enum * code fix for rid status issue * update validate request body method * fixed registration center issue * added notification in validate otp API * fixed authentication request description * removed space * removed validate otp from auth request service type * added notification to get my uin API * added notification in personalised card API * fixed null check * refactor code * fixed code for notify * code refactoring * fixed test case failure * take templatetype code from properties * fixed preferred language doc error * fixed code * renamed variable * take list from property * removed unused import * added comment and changed list to stream * added photo to attribute list * fixed update uin summary and purpose * fixed summary description for share-credential API * fixed acknowledgement summary purpose * fixed summary issue * white spaces * fixed authentication mode issue * changed from purpose to attribute list * fixed db calling multiple times issue * MOSIP-27036 fixed the summary * review comments * removed unused method * code refactoring * added cause * fixed description issue in auth lock unlock API * added comment * used contant delimiter * fixed status to take from templates * added null check for status code * assign to single variable --------- Co-authored-by: Ritik Jain * MOSIP-26984-resident-ui-in-share-my-data-the-format-details-are-not-displayed-properly-in-the-downloaded-pdf-for-name-dob-address (#911) * fixed id version for document APIs * update constant names * used constant file_text * added validation on req credential API * added validation for req credential API * removed duplicate code * fixed rid status issue * removed name from enum * code fix for rid status issue * update validate request body method * fixed registration center issue * added notification in validate otp API * fixed authentication request description * removed space * removed validate otp from auth request service type * added notification to get my uin API * added notification in personalised card API * fixed null check * refactor code * fixed code for notify * code refactoring * fixed test case failure * take templatetype code from properties * fixed preferred language doc error * fixed code * renamed variable * take list from property * removed unused import * added comment and changed list to stream * added photo to attribute list * fixed update uin summary and purpose * fixed summary description for share-credential API * fixed acknowledgement summary purpose * fixed summary issue * white spaces * fixed authentication mode issue * changed from purpose to attribute list * fixed db calling multiple times issue * MOSIP-27036 fixed the summary * review comments * removed unused method * code refactoring * added cause * fixed description issue in auth lock unlock API * added comment * used contant delimiter * fixed status to take from templates * added null check for status code * assign to single variable * fixed share credential attribute format issue --------- Co-authored-by: Ritik Jain * [MOSIP-27253,MOSIP-27254,MOSIP27255] Updated Download card method (#912) * [MOSIP-24670] Updated API correction id and version * [MOSIP-24670] Updated API body correction * [MOSIP-22640] Fixed Sonar Bugs * updated PR * updated PR * updated review code * [MOSIP-22640] Fixed sonar bugs * updated PR * updated PR * [MOSIP-22639] Resolved security hotspots in code * [MOSIP-24630] Fixed Security Vulnerability in code * added error for isValidUrl method * renamed vaildateURL method * updated PR * updated PR * [MOSIP-24670] Made corrections in id and version * resolved conflicts * updated PR * updated PR * [MOSIP-24670] Made corrections n API body, response code * updated PR * updated PR * updated dateTime * updated PR * [MOSIP-25539] Made corrections in API body, response code * [MOSIP-25539] made corrections in API body * updated error message * updated error code * updated trasactionid dto change * added equals * [MOSIP-25539] made corrections in api body * [MOSIP-25539] Corrected API response body Task 5 * resolved build failure * [MOSIP-25539] Task 2 Added error code for vaildateOtp API * updated PR * updated PR * updated PR * updated PR * [MOSIP-25539] Updated validateotp method * updated PR * [MOSIP-25798] Added validations * updated PR * updated PR * updated PR * updated PR * updated PR * [MOSIP-25791] Added purpose as mandatory * Added error * Added Audit logs * updated test cases * [MOSIP-22913],[MOSIP-22914],[MOSIP-24653],[MOSIP-24796] Added Audit logs * updated logs * updated auditlog code * updated enum name for audit logs * updated enum name for audit logs * updated enum name for audit logs * updated enum name for audit logs * updated enum name for audit logs * [MOSIP-25268] Fixed Sonar vulnerability * [MOSIP-25268] Fixed Sonar vulnerability * [MOSIP-26272] Added validation for /update-uin API * updated PR * updated update-uin PR * Fixed build issue * Updated transactionId error message * Updated Test cases ResidentServiceResUpdateTest class * [MOSIP-26343] Created module specific audits * updated PR * updated PR * [MOSIP-26087] Added featureName in pdf name * updated PR * Updated PR as per review * updated PR * updated PR * Updated build * [MOSIP-24494] Updated trasnliterate API error msg * updated PR * updated PR * [MOSIP-25363],[MOSIP-24796],[MOSIP-25711] Updated audit logs * [MOSIP-26089] Added authentication mode * Fixed Sonar Bugs * updated PR * updated as per review * Updated Sonar Fix * Updated Sonar bug fix * Updated Sonar bug fix * Updated Sonar bug fix * Updated Sonar bug fix * Updated Sonar bug fix * Updated Sonar bug fix * [MOSIP-25793] Added audit logs * Fixed sonar bug * Fixed sonar bug * Fixed Sonar Bug * Updated Sonar Fix * Fixed build failure * [MOSIP-27213] Updated update-uin method * [MOSIP-27213] Updated ObjectValidator method * [MOSIP-27213] Updated ObjectValidator method * [MOSIP-27213] Updated ObjectValidator method * [MOSIP-27253,MOSIP-27254,MOSIP27255] Updated Download card method * updated PR * code refactoring (#913) * fixed id version for document APIs * update constant names * used constant file_text * added validation on req credential API * added validation for req credential API * removed duplicate code * fixed rid status issue * removed name from enum * code fix for rid status issue * update validate request body method * fixed registration center issue * added notification in validate otp API * fixed authentication request description * removed space * removed validate otp from auth request service type * added notification to get my uin API * added notification in personalised card API * fixed null check * refactor code * fixed code for notify * code refactoring * fixed test case failure * take templatetype code from properties * fixed preferred language doc error * fixed code * renamed variable * take list from property * removed unused import * added comment and changed list to stream * added photo to attribute list * fixed update uin summary and purpose * fixed summary description for share-credential API * fixed acknowledgement summary purpose * fixed summary issue * white spaces * fixed authentication mode issue * changed from purpose to attribute list * fixed db calling multiple times issue * MOSIP-27036 fixed the summary * review comments * removed unused method * code refactoring * added cause * fixed description issue in auth lock unlock API * added comment * used contant delimiter * fixed status to take from templates * added null check for status code * assign to single variable * fixed share credential attribute format issue * used a existing method --------- Co-authored-by: Ritik Jain * [MOSIP-25363,MOSIP-27337] Updated Audit logs (#915) * [MOSIP-24670] Updated API correction id and version * [MOSIP-24670] Updated API body correction * [MOSIP-22640] Fixed Sonar Bugs * updated PR * updated PR * updated review code * [MOSIP-22640] Fixed sonar bugs * updated PR * updated PR * [MOSIP-22639] Resolved security hotspots in code * [MOSIP-24630] Fixed Security Vulnerability in code * added error for isValidUrl method * renamed vaildateURL method * updated PR * updated PR * [MOSIP-24670] Made corrections in id and version * resolved conflicts * updated PR * updated PR * [MOSIP-24670] Made corrections n API body, response code * updated PR * updated PR * updated dateTime * updated PR * [MOSIP-25539] Made corrections in API body, response code * [MOSIP-25539] made corrections in API body * updated error message * updated error code * updated trasactionid dto change * added equals * [MOSIP-25539] made corrections in api body * [MOSIP-25539] Corrected API response body Task 5 * resolved build failure * [MOSIP-25539] Task 2 Added error code for vaildateOtp API * updated PR * updated PR * updated PR * updated PR * [MOSIP-25539] Updated validateotp method * updated PR * [MOSIP-25798] Added validations * updated PR * updated PR * updated PR * updated PR * updated PR * [MOSIP-25791] Added purpose as mandatory * Added error * Added Audit logs * updated test cases * [MOSIP-22913],[MOSIP-22914],[MOSIP-24653],[MOSIP-24796] Added Audit logs * updated logs * updated auditlog code * updated enum name for audit logs * updated enum name for audit logs * updated enum name for audit logs * updated enum name for audit logs * updated enum name for audit logs * [MOSIP-25268] Fixed Sonar vulnerability * [MOSIP-25268] Fixed Sonar vulnerability * [MOSIP-26272] Added validation for /update-uin API * updated PR * updated update-uin PR * Fixed build issue * Updated transactionId error message * Updated Test cases ResidentServiceResUpdateTest class * [MOSIP-26343] Created module specific audits * updated PR * updated PR * [MOSIP-26087] Added featureName in pdf name * updated PR * Updated PR as per review * updated PR * updated PR * Updated build * [MOSIP-24494] Updated trasnliterate API error msg * updated PR * updated PR * [MOSIP-25363],[MOSIP-24796],[MOSIP-25711] Updated audit logs * [MOSIP-26089] Added authentication mode * Fixed Sonar Bugs * updated PR * updated as per review * Updated Sonar Fix * Updated Sonar bug fix * Updated Sonar bug fix * Updated Sonar bug fix * Updated Sonar bug fix * Updated Sonar bug fix * Updated Sonar bug fix * [MOSIP-25793] Added audit logs * Fixed sonar bug * Fixed sonar bug * Fixed Sonar Bug * Updated Sonar Fix * Fixed build failure * [MOSIP-27213] Updated update-uin method * [MOSIP-27213] Updated ObjectValidator method * [MOSIP-27213] Updated ObjectValidator method * [MOSIP-27213] Updated ObjectValidator method * [MOSIP-27253,MOSIP-27254,MOSIP27255] Updated Download card method * updated PR * [MOSIP-25363,MOSIP-27337] Updated Audit logs (#916) * [MOSIP-24670] Updated API correction id and version * [MOSIP-24670] Updated API body correction * [MOSIP-22640] Fixed Sonar Bugs * updated PR * updated PR * updated review code * [MOSIP-22640] Fixed sonar bugs * updated PR * updated PR * [MOSIP-22639] Resolved security hotspots in code * [MOSIP-24630] Fixed Security Vulnerability in code * added error for isValidUrl method * renamed vaildateURL method * updated PR * updated PR * [MOSIP-24670] Made corrections in id and version * resolved conflicts * updated PR * updated PR * [MOSIP-24670] Made corrections n API body, response code * updated PR * updated PR * updated dateTime * updated PR * [MOSIP-25539] Made corrections in API body, response code * [MOSIP-25539] made corrections in API body * updated error message * updated error code * updated trasactionid dto change * added equals * [MOSIP-25539] made corrections in api body * [MOSIP-25539] Corrected API response body Task 5 * resolved build failure * [MOSIP-25539] Task 2 Added error code for vaildateOtp API * updated PR * updated PR * updated PR * updated PR * [MOSIP-25539] Updated validateotp method * updated PR * [MOSIP-25798] Added validations * updated PR * updated PR * updated PR * updated PR * updated PR * [MOSIP-25791] Added purpose as mandatory * Added error * Added Audit logs * updated test cases * [MOSIP-22913],[MOSIP-22914],[MOSIP-24653],[MOSIP-24796] Added Audit logs * updated logs * updated auditlog code * updated enum name for audit logs * updated enum name for audit logs * updated enum name for audit logs * updated enum name for audit logs * updated enum name for audit logs * [MOSIP-25268] Fixed Sonar vulnerability * [MOSIP-25268] Fixed Sonar vulnerability * [MOSIP-26272] Added validation for /update-uin API * updated PR * updated update-uin PR * Fixed build issue * Updated transactionId error message * Updated Test cases ResidentServiceResUpdateTest class * [MOSIP-26343] Created module specific audits * updated PR * updated PR * [MOSIP-26087] Added featureName in pdf name * updated PR * Updated PR as per review * updated PR * updated PR * Updated build * [MOSIP-24494] Updated trasnliterate API error msg * updated PR * updated PR * [MOSIP-25363],[MOSIP-24796],[MOSIP-25711] Updated audit logs * [MOSIP-26089] Added authentication mode * Fixed Sonar Bugs * updated PR * updated as per review * Updated Sonar Fix * Updated Sonar bug fix * Updated Sonar bug fix * Updated Sonar bug fix * Updated Sonar bug fix * Updated Sonar bug fix * Updated Sonar bug fix * [MOSIP-25793] Added audit logs * Fixed sonar bug * Fixed sonar bug * Fixed Sonar Bug * Updated Sonar Fix * Fixed build failure * [MOSIP-27213] Updated update-uin method * [MOSIP-27213] Updated ObjectValidator method * [MOSIP-27213] Updated ObjectValidator method * [MOSIP-27213] Updated ObjectValidator method * [MOSIP-27253,MOSIP-27254,MOSIP27255] Updated Download card method * updated PR * [MOSIP-25363,MOSIP-27337] Updated Audit logs * MOSIP-27213 Fixed preferred lang issue in update uin api. (#917) * Fixed service history issue. * Fixed preferred lang issue in update uin api. * mapped ui schema type with request type (#918) * fixed id version for document APIs * update constant names * used constant file_text * added validation on req credential API * added validation for req credential API * removed duplicate code * fixed rid status issue * removed name from enum * code fix for rid status issue * update validate request body method * fixed registration center issue * added notification in validate otp API * fixed authentication request description * removed space * removed validate otp from auth request service type * added notification to get my uin API * added notification in personalised card API * fixed null check * refactor code * fixed code for notify * code refactoring * fixed test case failure * take templatetype code from properties * fixed preferred language doc error * fixed code * renamed variable * take list from property * removed unused import * added comment and changed list to stream * added photo to attribute list * fixed update uin summary and purpose * fixed summary description for share-credential API * fixed acknowledgement summary purpose * fixed summary issue * white spaces * fixed authentication mode issue * changed from purpose to attribute list * fixed db calling multiple times issue * MOSIP-27036 fixed the summary * review comments * removed unused method * code refactoring * added cause * fixed description issue in auth lock unlock API * added comment * used contant delimiter * fixed status to take from templates * added null check for status code * assign to single variable * fixed share credential attribute format issue * used a existing method * removed extra track link constant * mapped schema type with request type * fixed service type overflow issue in pdf * changed to request type * updated parameter --------- Co-authored-by: Ritik Jain * Marked read status false for async request type. (#919) * Fixed service history issue. * Marked read status false for async request type. * Refactor code. * updated enum name values (#920) * fixed id version for document APIs * update constant names * used constant file_text * added validation on req credential API * added validation for req credential API * removed duplicate code * fixed rid status issue * removed name from enum * code fix for rid status issue * update validate request body method * fixed registration center issue * added notification in validate otp API * fixed authentication request description * removed space * removed validate otp from auth request service type * added notification to get my uin API * added notification in personalised card API * fixed null check * refactor code * fixed code for notify * code refactoring * fixed test case failure * take templatetype code from properties * fixed preferred language doc error * fixed code * renamed variable * take list from property * removed unused import * added comment and changed list to stream * added photo to attribute list * fixed update uin summary and purpose * fixed summary description for share-credential API * fixed acknowledgement summary purpose * fixed summary issue * white spaces * fixed authentication mode issue * changed from purpose to attribute list * fixed db calling multiple times issue * MOSIP-27036 fixed the summary * review comments * removed unused method * code refactoring * added cause * fixed description issue in auth lock unlock API * added comment * used contant delimiter * fixed status to take from templates * added null check for status code * assign to single variable * fixed share credential attribute format issue * used a existing method * removed extra track link constant * mapped schema type with request type * fixed service type overflow issue in pdf * changed to request type * updated parameter * changed enum name values --------- Co-authored-by: Ritik Jain * Updated Audit event name (#921) * [MOSIP-24670] Updated API correction id and version * [MOSIP-24670] Updated API body correction * [MOSIP-22640] Fixed Sonar Bugs * updated PR * updated PR * updated review code * [MOSIP-22640] Fixed sonar bugs * updated PR * updated PR * [MOSIP-22639] Resolved security hotspots in code * [MOSIP-24630] Fixed Security Vulnerability in code * added error for isValidUrl method * renamed vaildateURL method * updated PR * updated PR * [MOSIP-24670] Made corrections in id and version * resolved conflicts * updated PR * updated PR * [MOSIP-24670] Made corrections n API body, response code * updated PR * updated PR * updated dateTime * updated PR * [MOSIP-25539] Made corrections in API body, response code * [MOSIP-25539] made corrections in API body * updated error message * updated error code * updated trasactionid dto change * added equals * [MOSIP-25539] made corrections in api body * [MOSIP-25539] Corrected API response body Task 5 * resolved build failure * [MOSIP-25539] Task 2 Added error code for vaildateOtp API * updated PR * updated PR * updated PR * updated PR * [MOSIP-25539] Updated validateotp method * updated PR * [MOSIP-25798] Added validations * updated PR * updated PR * updated PR * updated PR * updated PR * [MOSIP-25791] Added purpose as mandatory * Added error * Added Audit logs * updated test cases * [MOSIP-22913],[MOSIP-22914],[MOSIP-24653],[MOSIP-24796] Added Audit logs * updated logs * updated auditlog code * updated enum name for audit logs * updated enum name for audit logs * updated enum name for audit logs * updated enum name for audit logs * updated enum name for audit logs * [MOSIP-25268] Fixed Sonar vulnerability * [MOSIP-25268] Fixed Sonar vulnerability * [MOSIP-26272] Added validation for /update-uin API * updated PR * updated update-uin PR * Fixed build issue * Updated transactionId error message * Updated Test cases ResidentServiceResUpdateTest class * [MOSIP-26343] Created module specific audits * updated PR * updated PR * [MOSIP-26087] Added featureName in pdf name * updated PR * Updated PR as per review * updated PR * updated PR * Updated build * [MOSIP-24494] Updated trasnliterate API error msg * updated PR * updated PR * [MOSIP-25363],[MOSIP-24796],[MOSIP-25711] Updated audit logs * [MOSIP-26089] Added authentication mode * Fixed Sonar Bugs * updated PR * updated as per review * Updated Sonar Fix * Updated Sonar bug fix * Updated Sonar bug fix * Updated Sonar bug fix * Updated Sonar bug fix * Updated Sonar bug fix * Updated Sonar bug fix * [MOSIP-25793] Added audit logs * Fixed sonar bug * Fixed sonar bug * Fixed Sonar Bug * Updated Sonar Fix * Fixed build failure * [MOSIP-27213] Updated update-uin method * [MOSIP-27213] Updated ObjectValidator method * [MOSIP-27213] Updated ObjectValidator method * [MOSIP-27213] Updated ObjectValidator method * [MOSIP-27253,MOSIP-27254,MOSIP27255] Updated Download card method * updated PR * [MOSIP-25363,MOSIP-27337] Updated Audit logs * Updated Audit event name * fixed attribute list issue (#923) Co-authored-by: Ritik Jain * Improved code coverage. (#924) * Fixed service history issue. * Improved code coverage. * MOSIP-27338, MOSIP-25724, MOSIP-26984-resident-ui-in-share-my-data-the-format-details-are-not-displayed-properly-in-the-downloaded-pdf-for-name-dob-address (#926) * fixed attribute list issue * fixed attribute list issue * updated * updated if condition --------- Co-authored-by: Ritik Jain * Updated sonar coverage (#927) * [MOSIP-24670] Updated API correction id and version * [MOSIP-24670] Updated API body correction * [MOSIP-22640] Fixed Sonar Bugs * updated PR * updated PR * updated review code * [MOSIP-22640] Fixed sonar bugs * updated PR * updated PR * [MOSIP-22639] Resolved security hotspots in code * [MOSIP-24630] Fixed Security Vulnerability in code * added error for isValidUrl method * renamed vaildateURL method * updated PR * updated PR * [MOSIP-24670] Made corrections in id and version * resolved conflicts * updated PR * updated PR * [MOSIP-24670] Made corrections n API body, response code * updated PR * updated PR * updated dateTime * updated PR * [MOSIP-25539] Made corrections in API body, response code * [MOSIP-25539] made corrections in API body * updated error message * updated error code * updated trasactionid dto change * added equals * [MOSIP-25539] made corrections in api body * [MOSIP-25539] Corrected API response body Task 5 * resolved build failure * [MOSIP-25539] Task 2 Added error code for vaildateOtp API * updated PR * updated PR * updated PR * updated PR * [MOSIP-25539] Updated validateotp method * updated PR * [MOSIP-25798] Added validations * updated PR * updated PR * updated PR * updated PR * updated PR * [MOSIP-25791] Added purpose as mandatory * Added error * Added Audit logs * updated test cases * [MOSIP-22913],[MOSIP-22914],[MOSIP-24653],[MOSIP-24796] Added Audit logs * updated logs * updated auditlog code * updated enum name for audit logs * updated enum name for audit logs * updated enum name for audit logs * updated enum name for audit logs * updated enum name for audit logs * [MOSIP-25268] Fixed Sonar vulnerability * [MOSIP-25268] Fixed Sonar vulnerability * [MOSIP-26272] Added validation for /update-uin API * updated PR * updated update-uin PR * Fixed build issue * Updated transactionId error message * Updated Test cases ResidentServiceResUpdateTest class * [MOSIP-26343] Created module specific audits * updated PR * updated PR * [MOSIP-26087] Added featureName in pdf name * updated PR * Updated PR as per review * updated PR * updated PR * Updated build * [MOSIP-24494] Updated trasnliterate API error msg * updated PR * updated PR * [MOSIP-25363],[MOSIP-24796],[MOSIP-25711] Updated audit logs * [MOSIP-26089] Added authentication mode * Fixed Sonar Bugs * updated PR * updated as per review * Updated Sonar Fix * Updated Sonar bug fix * Updated Sonar bug fix * Updated Sonar bug fix * Updated Sonar bug fix * Updated Sonar bug fix * Updated Sonar bug fix * [MOSIP-25793] Added audit logs * Fixed sonar bug * Fixed sonar bug * Fixed Sonar Bug * Updated Sonar Fix * Fixed build failure * [MOSIP-27213] Updated update-uin method * [MOSIP-27213] Updated ObjectValidator method * [MOSIP-27213] Updated ObjectValidator method * [MOSIP-27213] Updated ObjectValidator method * [MOSIP-27253,MOSIP-27254,MOSIP27255] Updated Download card method * updated PR * [MOSIP-25363,MOSIP-27337] Updated Audit logs * Updated Audit event name * Updated sonar coverage * fixed address issue in identity/info API (#928) * fixed attribute list issue * fixed attribute list issue * updated * updated if condition * fixed address issue in identity API --------- Co-authored-by: Ritik Jain * MOSIP-27438 Added validation for identity in update uin. (#925) * Fixed service history issue. * MOSIP-27438 Added validation for identity in update uin. * Code refactor. * Code refactor. * Code refactor. * Code refactor. * Code refactor. * Code refactor. * Code refactor. * [MOSIP-27548,MOSIP-27547]Updated audits (#929) * [MOSIP-24670] Updated API correction id and version * [MOSIP-24670] Updated API body correction * [MOSIP-22640] Fixed Sonar Bugs * updated PR * updated PR * updated review code * [MOSIP-22640] Fixed sonar bugs * updated PR * updated PR * [MOSIP-22639] Resolved security hotspots in code * [MOSIP-24630] Fixed Security Vulnerability in code * added error for isValidUrl method * renamed vaildateURL method * updated PR * updated PR * [MOSIP-24670] Made corrections in id and version * resolved conflicts * updated PR * updated PR * [MOSIP-24670] Made corrections n API body, response code * updated PR * updated PR * updated dateTime * updated PR * [MOSIP-25539] Made corrections in API body, response code * [MOSIP-25539] made corrections in API body * updated error message * updated error code * updated trasactionid dto change * added equals * [MOSIP-25539] made corrections in api body * [MOSIP-25539] Corrected API response body Task 5 * resolved build failure * [MOSIP-25539] Task 2 Added error code for vaildateOtp API * updated PR * updated PR * updated PR * updated PR * [MOSIP-25539] Updated validateotp method * updated PR * [MOSIP-25798] Added validations * updated PR * updated PR * updated PR * updated PR * updated PR * [MOSIP-25791] Added purpose as mandatory * Added error * Added Audit logs * updated test cases * [MOSIP-22913],[MOSIP-22914],[MOSIP-24653],[MOSIP-24796] Added Audit logs * updated logs * updated auditlog code * updated enum name for audit logs * updated enum name for audit logs * updated enum name for audit logs * updated enum name for audit logs * updated enum name for audit logs * [MOSIP-25268] Fixed Sonar vulnerability * [MOSIP-25268] Fixed Sonar vulnerability * [MOSIP-26272] Added validation for /update-uin API * updated PR * updated update-uin PR * Fixed build issue * Updated transactionId error message * Updated Test cases ResidentServiceResUpdateTest class * [MOSIP-26343] Created module specific audits * updated PR * updated PR * [MOSIP-26087] Added featureName in pdf name * updated PR * Updated PR as per review * updated PR * updated PR * Updated build * [MOSIP-24494] Updated trasnliterate API error msg * updated PR * updated PR * [MOSIP-25363],[MOSIP-24796],[MOSIP-25711] Updated audit logs * [MOSIP-26089] Added authentication mode * Fixed Sonar Bugs * updated PR * updated as per review * Updated Sonar Fix * Updated Sonar bug fix * Updated Sonar bug fix * Updated Sonar bug fix * Updated Sonar bug fix * Updated Sonar bug fix * Updated Sonar bug fix * [MOSIP-25793] Added audit logs * Fixed sonar bug * Fixed sonar bug * Fixed Sonar Bug * Updated Sonar Fix * Fixed build failure * [MOSIP-27213] Updated update-uin method * [MOSIP-27213] Updated ObjectValidator method * [MOSIP-27213] Updated ObjectValidator method * [MOSIP-27213] Updated ObjectValidator method * [MOSIP-27253,MOSIP-27254,MOSIP27255] Updated Download card method * updated PR * [MOSIP-25363,MOSIP-27337] Updated Audit logs * Updated Audit event name * Updated sonar coverage * [MOSIP-27548,MOSIP-27547]Updated audits * fixed attribute list null issue (#930) * fixed attribute list issue * fixed attribute list issue * updated * updated if condition * fixed address issue in identity API * fixed null attribute list issue * fixed variable issue * format --------- Co-authored-by: Ritik Jain * [MOSIP-27405] Updated Audits Event name (#933) * [MOSIP-24670] Updated API correction id and version * [MOSIP-24670] Updated API body correction * [MOSIP-22640] Fixed Sonar Bugs * updated PR * updated PR * updated review code * [MOSIP-22640] Fixed sonar bugs * updated PR * updated PR * [MOSIP-22639] Resolved security hotspots in code * [MOSIP-24630] Fixed Security Vulnerability in code * added error for isValidUrl method * renamed vaildateURL method * updated PR * updated PR * [MOSIP-24670] Made corrections in id and version * resolved conflicts * updated PR * updated PR * [MOSIP-24670] Made corrections n API body, response code * updated PR * updated PR * updated dateTime * updated PR * [MOSIP-25539] Made corrections in API body, response code * [MOSIP-25539] made corrections in API body * updated error message * updated error code * updated trasactionid dto change * added equals * [MOSIP-25539] made corrections in api body * [MOSIP-25539] Corrected API response body Task 5 * resolved build failure * [MOSIP-25539] Task 2 Added error code for vaildateOtp API * updated PR * updated PR * updated PR * updated PR * [MOSIP-25539] Updated validateotp method * updated PR * [MOSIP-25798] Added validations * updated PR * updated PR * updated PR * updated PR * updated PR * [MOSIP-25791] Added purpose as mandatory * Added error * Added Audit logs * updated test cases * [MOSIP-22913],[MOSIP-22914],[MOSIP-24653],[MOSIP-24796] Added Audit logs * updated logs * updated auditlog code * updated enum name for audit logs * updated enum name for audit logs * updated enum name for audit logs * updated enum name for audit logs * updated enum name for audit logs * [MOSIP-25268] Fixed Sonar vulnerability * [MOSIP-25268] Fixed Sonar vulnerability * [MOSIP-26272] Added validation for /update-uin API * updated PR * updated update-uin PR * Fixed build issue * Updated transactionId error message * Updated Test cases ResidentServiceResUpdateTest class * [MOSIP-26343] Created module specific audits * updated PR * updated PR * [MOSIP-26087] Added featureName in pdf name * updated PR * Updated PR as per review * updated PR * updated PR * Updated build * [MOSIP-24494] Updated trasnliterate API error msg * updated PR * updated PR * [MOSIP-25363],[MOSIP-24796],[MOSIP-25711] Updated audit logs * [MOSIP-26089] Added authentication mode * Fixed Sonar Bugs * updated PR * updated as per review * Updated Sonar Fix * Updated Sonar bug fix * Updated Sonar bug fix * Updated Sonar bug fix * Updated Sonar bug fix * Updated Sonar bug fix * Updated Sonar bug fix * [MOSIP-25793] Added audit logs * Fixed sonar bug * Fixed sonar bug * Fixed Sonar Bug * Updated Sonar Fix * Fixed build failure * [MOSIP-27213] Updated update-uin method * [MOSIP-27213] Updated ObjectValidator method * [MOSIP-27213] Updated ObjectValidator method * [MOSIP-27213] Updated ObjectValidator method * [MOSIP-27253,MOSIP-27254,MOSIP27255] Updated Download card method * updated PR * [MOSIP-25363,MOSIP-27337] Updated Audit logs * Updated Audit event name * Updated sonar coverage * [MOSIP-27548,MOSIP-27547]Updated audits * Updated Audits Event name * Updated PR * Updated PR * Updated PR * Updated PR * fixed format attribute list null issue and did code formatting (#931) * fixed attribute list issue * fixed attribute list issue * updated * updated if condition * fixed address issue in identity API * fixed null attribute list issue * fixed variable issue * format * code formatting * null format attribute list issue --------- Co-authored-by: Ritik Jain * Fixed update uin issue for a particular schema version. (#932) * Fixed service history issue. * update uin fix * Fixed test case failure. * Fixed update uin issue. * Fixed update uin issue. * Fixed build failure. (#934) * Fixed service history issue. * update uin fix * Fixed test case failure. * Fixed update uin issue. * Fixed update uin issue. * Improved test coverage for resident vid service test. * [MOSIP-27405] Updated Audits (#937) * [MOSIP-24670] Updated API correction id and version * [MOSIP-24670] Updated API body correction * [MOSIP-22640] Fixed Sonar Bugs * updated PR * updated PR * updated review code * [MOSIP-22640] Fixed sonar bugs * updated PR * updated PR * [MOSIP-22639] Resolved security hotspots in code * [MOSIP-24630] Fixed Security Vulnerability in code * added error for isValidUrl method * renamed vaildateURL method * updated PR * updated PR * [MOSIP-24670] Made corrections in id and version * resolved conflicts * updated PR * updated PR * [MOSIP-24670] Made corrections n API body, response code * updated PR * updated PR * updated dateTime * updated PR * [MOSIP-25539] Made corrections in API body, response code * [MOSIP-25539] made corrections in API body * updated error message * updated error code * updated trasactionid dto change * added equals * [MOSIP-25539] made corrections in api body * [MOSIP-25539] Corrected API response body Task 5 * resolved build failure * [MOSIP-25539] Task 2 Added error code for vaildateOtp API * updated PR * updated PR * updated PR * updated PR * [MOSIP-25539] Updated validateotp method * updated PR * [MOSIP-25798] Added validations * updated PR * updated PR * updated PR * updated PR * updated PR * [MOSIP-25791] Added purpose as mandatory * Added error * Added Audit logs * updated test cases * [MOSIP-22913],[MOSIP-22914],[MOSIP-24653],[MOSIP-24796] Added Audit logs * updated logs * updated auditlog code * updated enum name for audit logs * updated enum name for audit logs * updated enum name for audit logs * updated enum name for audit logs * updated enum name for audit logs * [MOSIP-25268] Fixed Sonar vulnerability * [MOSIP-25268] Fixed Sonar vulnerability * [MOSIP-26272] Added validation for /update-uin API * updated PR * updated update-uin PR * Fixed build issue * Updated transactionId error message * Updated Test cases ResidentServiceResUpdateTest class * [MOSIP-26343] Created module specific audits * updated PR * updated PR * [MOSIP-26087] Added featureName in pdf name * updated PR * Updated PR as per review * updated PR * updated PR * Updated build * [MOSIP-24494] Updated trasnliterate API error msg * updated PR * updated PR * [MOSIP-25363],[MOSIP-24796],[MOSIP-25711] Updated audit logs * [MOSIP-26089] Added authentication mode * Fixed Sonar Bugs * updated PR * updated as per review * Updated Sonar Fix * Updated Sonar bug fix * Updated Sonar bug fix * Updated Sonar bug fix * Updated Sonar bug fix * Updated Sonar bug fix * Updated Sonar bug fix * [MOSIP-25793] Added audit logs * Fixed sonar bug * Fixed sonar bug * Fixed Sonar Bug * Updated Sonar Fix * Fixed build failure * [MOSIP-27213] Updated update-uin method * [MOSIP-27213] Updated ObjectValidator method * [MOSIP-27213] Updated ObjectValidator method * [MOSIP-27213] Updated ObjectValidator method * [MOSIP-27253,MOSIP-27254,MOSIP27255] Updated Download card method * updated PR * [MOSIP-25363,MOSIP-27337] Updated Audit logs * Updated Audit event name * Updated sonar coverage * [MOSIP-27548,MOSIP-27547]Updated audits * Updated Audits Event name * Updated PR * Updated PR * Updated PR * Updated PR * [MOSIP-27405] Updated Audits * [MOSIP-27405] Updated Audits * Mosip-24939 Improved code coverage. (#935) * Fixed service history issue. * Added test class for CredentialStatusUpdateHelper. * Improved test coverage for resident vid service test. * Improved test coverage for resident vid service test. * Improved test coverage for resident vid service test. * Improved test coverage for TemplateUtil. * MOSIP-27700 Handled acess denied error code (#938) * MOSIP-26289 changes done * MOSIP-26289 changes done * Bug fixed * MOSIP-27700 Handled Access denied error code --------- Co-authored-by: Neha Farheen * [MOSIP-27552] Added ref_id as hash value of id (#939) * [MOSIP-24670] Updated API correction id and version * [MOSIP-24670] Updated API body correction * [MOSIP-22640] Fixed Sonar Bugs * updated PR * updated PR * updated review code * [MOSIP-22640] Fixed sonar bugs * updated PR * updated PR * [MOSIP-22639] Resolved security hotspots in code * [MOSIP-24630] Fixed Security Vulnerability in code * added error for isValidUrl method * renamed vaildateURL method * updated PR * updated PR * [MOSIP-24670] Made corrections in id and version * resolved conflicts * updated PR * updated PR * [MOSIP-24670] Made corrections n API body, response code * updated PR * updated PR * updated dateTime * updated PR * [MOSIP-25539] Made corrections in API body, response code * [MOSIP-25539] made corrections in API body * updated error message * updated error code * updated trasactionid dto change * added equals * [MOSIP-25539] made corrections in api body * [MOSIP-25539] Corrected API response body Task 5 * resolved build failure * [MOSIP-25539] Task 2 Added error code for vaildateOtp API * updated PR * updated PR * updated PR * updated PR * [MOSIP-25539] Updated validateotp method * updated PR * [MOSIP-25798] Added validations * updated PR * updated PR * updated PR * updated PR * updated PR * [MOSIP-25791] Added purpose as mandatory * Added error * Added Audit logs * updated test cases * [MOSIP-22913],[MOSIP-22914],[MOSIP-24653],[MOSIP-24796] Added Audit logs * updated logs * updated auditlog code * updated enum name for audit logs * updated enum name for audit logs * updated enum name for audit logs * updated enum name for audit logs * updated enum name for audit logs * [MOSIP-25268] Fixed Sonar vulnerability * [MOSIP-25268] Fixed Sonar vulnerability * [MOSIP-26272] Added validation for /update-uin API * updated PR * updated update-uin PR * Fixed build issue * Updated transactionId error message * Updated Test cases ResidentServiceResUpdateTest class * [MOSIP-26343] Created module specific audits * updated PR * updated PR * [MOSIP-26087] Added featureName in pdf name * updated PR * Updated PR as per review * updated PR * updated PR * Updated build * [MOSIP-24494] Updated trasnliterate API error msg * updated PR * updated PR * [MOSIP-25363],[MOSIP-24796],[MOSIP-25711] Updated audit logs * [MOSIP-26089] Added authentication mode * Fixed Sonar Bugs * updated PR * updated as per review * Updated Sonar Fix * Updated Sonar bug fix * Updated Sonar bug fix * Updated Sonar bug fix * Updated Sonar bug fix * Updated Sonar bug fix * Updated Sonar bug fix * [MOSIP-25793] Added audit logs * Fixed sonar bug * Fixed sonar bug * Fixed Sonar Bug * Updated Sonar Fix * Fixed build failure * [MOSIP-27213] Updated update-uin method * [MOSIP-27213] Updated ObjectValidator method * [MOSIP-27213] Updated ObjectValidator method * [MOSIP-27213] Updated ObjectValidator method * [MOSIP-27253,MOSIP-27254,MOSIP27255] Updated Download card method * updated PR * [MOSIP-25363,MOSIP-27337] Updated Audit logs * Updated Audit event name * Updated sonar coverage * [MOSIP-27548,MOSIP-27547]Updated audits * Updated Audits Event name * Updated PR * Updated PR * Updated PR * Updated PR * [MOSIP-27405] Updated Audits * [MOSIP-27405] Updated Audits * [MOSIP-27552] Added ref_id as hash value of id * [MOSIP-27552] Added ref_id as hash value of id * [MOSIP-27729,MOSIP-27730,27696] Updated Audits (#942) * [MOSIP-24670] Updated API correction id and version * [MOSIP-24670] Updated API body correction * [MOSIP-22640] Fixed Sonar Bugs * updated PR * updated PR * updated review code * [MOSIP-22640] Fixed sonar bugs * updated PR * updated PR * [MOSIP-22639] Resolved security hotspots in code * [MOSIP-24630] Fixed Security Vulnerability in code * added error for isValidUrl method * renamed vaildateURL method * updated PR * updated PR * [MOSIP-24670] Made corrections in id and version * resolved conflicts * updated PR * updated PR * [MOSIP-24670] Made corrections n API body, response code * updated PR * updated PR * updated dateTime * updated PR * [MOSIP-25539] Made corrections in API body, response code * [MOSIP-25539] made corrections in API body * updated error message * updated error code * updated trasactionid dto change * added equals * [MOSIP-25539] made corrections in api body * [MOSIP-25539] Corrected API response body Task 5 * resolved build failure * [MOSIP-25539] Task 2 Added error code for vaildateOtp API * updated PR * updated PR * updated PR * updated PR * [MOSIP-25539] Updated validateotp method * updated PR * [MOSIP-25798] Added validations * updated PR * updated PR * updated PR * updated PR * updated PR * [MOSIP-25791] Added purpose as mandatory * Added error * Added Audit logs * updated test cases * [MOSIP-22913],[MOSIP-22914],[MOSIP-24653],[MOSIP-24796] Added Audit logs * updated logs * updated auditlog code * updated enum name for audit logs * updated enum name for audit logs * updated enum name for audit logs * updated enum name for audit logs * updated enum name for audit logs * [MOSIP-25268] Fixed Sonar vulnerability * [MOSIP-25268] Fixed Sonar vulnerability * [MOSIP-26272] Added validation for /update-uin API * updated PR * updated update-uin PR * Fixed build issue * Updated transactionId error message * Updated Test cases ResidentServiceResUpdateTest class * [MOSIP-26343] Created module specific audits * updated PR * updated PR * [MOSIP-26087] Added featureName in pdf name * updated PR * Updated PR as per review * updated PR * updated PR * Updated build * [MOSIP-24494] Updated trasnliterate API error msg * updated PR * updated PR * [MOSIP-25363],[MOSIP-24796],[MOSIP-25711] Updated audit logs * [MOSIP-26089] Added authentication mode * Fixed Sonar Bugs * updated PR * updated as per review * Updated Sonar Fix * Updated Sonar bug fix * Updated Sonar bug fix * Updated Sonar bug fix * Updated Sonar bug fix * Updated Sonar bug fix * Updated Sonar bug fix * [MOSIP-25793] Added audit logs * Fixed sonar bug * Fixed sonar bug * Fixed Sonar Bug * Updated Sonar Fix * Fixed build failure * [MOSIP-27213] Updated update-uin method * [MOSIP-27213] Updated ObjectValidator method * [MOSIP-27213] Updated ObjectValidator method * [MOSIP-27213] Updated ObjectValidator method * [MOSIP-27253,MOSIP-27254,MOSIP27255] Updated Download card method * updated PR * [MOSIP-25363,MOSIP-27337] Updated Audit logs * Updated Audit event name * Updated sonar coverage * [MOSIP-27548,MOSIP-27547]Updated audits * Updated Audits Event name * Updated PR * Updated PR * Updated PR * Updated PR * [MOSIP-27405] Updated Audits * [MOSIP-27405] Updated Audits * [MOSIP-27552] Added ref_id as hash value of id * [MOSIP-27552] Added ref_id as hash value of id * [MOSIP-27729,MOSIP-27730,27696] Updated Audits * [MOSIP-27729,MOSIP-27730,27696] Updated Audits * MOSIP-27126 Added validation for future and past request time. (#940) * Fixed service history issue. * MOSIP-27126 Added validation for future and past re * MOSIP-27545-manage-my-vid-feature-is-not-working-as-per-vid-policy-in-the-configuration (#944) * fixed attribute list issue * fixed attribute list issue * updated * updated if condition * fixed address issue in identity API * fixed null attribute list issue * fixed variable issue * format * code formatting * null format attribute list issue * fixed vid left count issue --------- Co-authored-by: Ritik Jain * MOSIP-27716 Moved identity-data-formatter.mvel to credentialdata.mvel. * MOSIP-24939 MOSIP-27716 Improved Code coverage. (#947) * Fixed service history issue. * Added test class for CredentialStatusUpdateHelper. * Improved test coverage for resident vid service test. * Improved test coverage for resident vid service test. * Improved test coverage for resident vid service test. * Improved test coverage for TemplateUtil. * MOSIP-24939 Improved code coverage. * MOSIP-24939 Improved code coverage of DownLoadMasterDataController. * MOSIP-24939 Improved code coverage of GrievanceController. * MOSIP-24939 Improved code coverage of IdAuthController. * MOSIP-24939 Improved code coverage of ProxyOtpController. * MOSIP-24939 Improved code coverage of ResidentController. * MOSIP-24939 Improved code coverage of ResidentOtpController. * Replaced convertToMaskDataFormat method name to convertToMaskData * MOSIP-24939 Fixed build failure. (#949) * Fixed service history issue. * Added test class for CredentialStatusUpdateHelper. * Improved test coverage for resident vid service test. * Improved test coverage for resident vid service test. * Improved test coverage for resident vid service test. * Improved test coverage for TemplateUtil. * MOSIP-24939 Improved code coverage. * MOSIP-24939 Improved code coverage of DownLoadMasterDataController. * MOSIP-24939 Improved code coverage of GrievanceController. * MOSIP-24939 Improved code coverage of IdAuthController. * MOSIP-24939 Improved code coverage of ProxyOtpController. * MOSIP-24939 Improved code coverage of ResidentController. * MOSIP-24939 Improved code coverage of ResidentOtpController. * Replaced convertToMaskDataFormat method name to convertToMaskData * MOSIP-24939 Fixed build failure. * MOSIP-24939 Removed un-necessary comments. * [MOSIP-27696,MOSIP-27405]Updated Audits (#948) * [MOSIP-24670] Updated API correction id and version * [MOSIP-24670] Updated API body correction * [MOSIP-22640] Fixed Sonar Bugs * updated PR * updated PR * updated review code * [MOSIP-22640] Fixed sonar bugs * updated PR * updated PR * [MOSIP-22639] Resolved security hotspots in code * [MOSIP-24630] Fixed Security Vulnerability in code * added error for isValidUrl method * renamed vaildateURL method * updated PR * updated PR * [MOSIP-24670] Made corrections in id and version * resolved conflicts * updated PR * updated PR * [MOSIP-24670] Made corrections n API body, response code * updated PR * updated PR * updated dateTime * updated PR * [MOSIP-25539] Made corrections in API body, response code * [MOSIP-25539] made corrections in API body * updated error message * updated error code * updated trasactionid dto change * added equals * [MOSIP-25539] made corrections in api body * [MOSIP-25539] Corrected API response body Task 5 * resolved build failure * [MOSIP-25539] Task 2 Added error code for vaildateOtp API * updated PR * updated PR * updated PR * updated PR * [MOSIP-25539] Updated validateotp method * updated PR * [MOSIP-25798] Added validations * updated PR * updated PR * updated PR * updated PR * updated PR * [MOSIP-25791] Added purpose as mandatory * Added error * Added Audit logs * updated test cases * [MOSIP-22913],[MOSIP-22914],[MOSIP-24653],[MOSIP-24796] Added Audit logs * updated logs * updated auditlog code * updated enum name for audit logs * updated enum name for audit logs * updated enum name for audit logs * updated enum name for audit logs * updated enum name for audit logs * [MOSIP-25268] Fixed Sonar vulnerability * [MOSIP-25268] Fixed Sonar vulnerability * [MOSIP-26272] Added validation for /update-uin API * updated PR * updated update-uin PR * Fixed build issue * Updated transactionId error message * Updated Test cases ResidentServiceResUpdateTest class * [MOSIP-26343] Created module specific audits * updated PR * updated PR * [MOSIP-26087] Added featureName in pdf name * updated PR * Updated PR as per review * updated PR * updated PR * Updated build * [MOSIP-24494] Updated trasnliterate API error msg * updated PR * updated PR * [MOSIP-25363],[MOSIP-24796],[MOSIP-25711] Updated audit logs * [MOSIP-26089] Added authentication mode * Fixed Sonar Bugs * updated PR * updated as per review * Updated Sonar Fix * Updated Sonar bug fix * Updated Sonar bug fix * Updated Sonar bug fix * Updated Sonar bug fix * Updated Sonar bug fix * Updated Sonar bug fix * [MOSIP-25793] Added audit logs * Fixed sonar bug * Fixed sonar bug * Fixed Sonar Bug * Updated Sonar Fix * Fixed build failure * [MOSIP-27213] Updated update-uin method * [MOSIP-27213] Updated ObjectValidator method * [MOSIP-27213] Updated ObjectValidator method * [MOSIP-27213] Updated ObjectValidator method * [MOSIP-27253,MOSIP-27254,MOSIP27255] Updated Download card method * updated PR * [MOSIP-25363,MOSIP-27337] Updated Audit logs * Updated Audit event name * Updated sonar coverage * [MOSIP-27548,MOSIP-27547]Updated audits * Updated Audits Event name * Updated PR * Updated PR * Updated PR * Updated PR * [MOSIP-27405] Updated Audits * [MOSIP-27405] Updated Audits * [MOSIP-27552] Added ref_id as hash value of id * [MOSIP-27552] Added ref_id as hash value of id * [MOSIP-27729,MOSIP-27730,27696] Updated Audits * [MOSIP-27729,MOSIP-27730,27696] Updated Audits * Updated PR * Updated PR * [MOSIP-27696,MOSIP-27405]Updated Audits * MOSIP-24939 Fixed build failure. (#950) * Fixed service history issue. * Added test class for CredentialStatusUpdateHelper. * Improved test coverage for resident vid service test. * Improved test coverage for resident vid service test. * Improved test coverage for resident vid service test. * Improved test coverage for TemplateUtil. * MOSIP-24939 Improved code coverage. * MOSIP-24939 Improved code coverage of DownLoadMasterDataController. * MOSIP-24939 Improved code coverage of GrievanceController. * MOSIP-24939 Improved code coverage of IdAuthController. * MOSIP-24939 Improved code coverage of ProxyOtpController. * MOSIP-24939 Improved code coverage of ResidentController. * MOSIP-24939 Improved code coverage of ResidentOtpController. * Replaced convertToMaskDataFormat method name to convertToMaskData * MOSIP-24939 Fixed build failure. * MOSIP-24939 Removed un-necessary comments. * MOSIP-24939 Fixed build failure. * fixed invalid otp issue, renamed method and removed unused code (#946) * fixed attribute list issue * fixed attribute list issue * updated * updated if condition * fixed address issue in identity API * fixed null attribute list issue * fixed variable issue * format * code formatting * null format attribute list issue * fixed vid left count issue * updated method name * take status code from templates * status from templates * removed unused code * undo changes * remove unused import * fixed invalid otp issue * updated method name --------- Co-authored-by: Ritik Jain * Fixed update uin issue. (#953) * Fixed service history issue. * MOSIP-27716 Moved identity-data-formatter.mvel to credentialdata.mvel. * Fixed email update issue. * MOSIP-27872-view-history-is-showing-additional-entry-for-verify-phone-email-when-downloading-uin-card (#954) * fixed attribute list issue * fixed attribute list issue * updated * updated if condition * fixed address issue in identity API * fixed null attribute list issue * fixed variable issue * format * code formatting * null format attribute list issue * fixed vid left count issue * updated method name * take status code from templates * status from templates * removed unused code * undo changes * remove unused import * fixed invalid otp issue * updated method name * removed additional entity * fixed entity issue * passed requesttype instead of string * fixed update times * removed unused code --------- Co-authored-by: Ritik Jain * MOSIP-27872-view-history-is-showing-additional-entry-for-verify-phone-email-when-downloading-uin-card (#955) * fixed attribute list issue * fixed attribute list issue * updated * updated if condition * fixed address issue in identity API * fixed null attribute list issue * fixed variable issue * format * code formatting * null format attribute list issue * fixed vid left count issue * updated method name * take status code from templates * status from templates * removed unused code * undo changes * remove unused import * fixed invalid otp issue * updated method name * removed additional entity * fixed entity issue * passed requesttype instead of string * fixed update times * removed unused code * fixed failure case --------- Co-authored-by: Ritik Jain * MOSIP-27932 - Locale based datetime formatting develop (#956) * Added locale based timestamp formatting * resolved merge conflicts * Test fixes --------- Co-authored-by: Loganathan Sekar * MOSIP-25268 Fixed Sonar Vulnerability. (#957) * Fixed service history issue. * MOSIP-27716 Moved identity-data-formatter.mvel to credentialdata.mvel. * MOSIP-25268 Fixed Sonar Vulnerability. * MOSIP-25268 Fixed Sonar Vulnerability. --------- Signed-off-by: kameshsr <47484458+kameshsr@users.noreply.github.com> * Fix to filename datepattern (#958) Co-authored-by: Loganathan Sekar * sonar coverage (#959) * fixed attribute list issue * fixed attribute list issue * updated * updated if condition * fixed address issue in identity API * fixed null attribute list issue * fixed variable issue * format * code formatting * null format attribute list issue * fixed vid left count issue * updated method name * take status code from templates * status from templates * removed unused code * undo changes * remove unused import * fixed invalid otp issue * updated method name * removed additional entity * fixed entity issue * passed requesttype instead of string * fixed update times * removed unused code * fixed failure case * added test cases for notification endpoints --------- Co-authored-by: Ritik Jain * MOSIP-24939 Improved code coverage of service history. (#961) * Fixed service history issue. * MOSIP-27716 Moved identity-data-formatter.mvel to credentialdata.mvel. * MOSIP-24939 Improved code coverage of service history. * MOSIP-24939 Improved code coverage of service history. * MOSIP-24939 Improved code coverage of service history. * MOSIP-24939 Improved code coverage of service history. * Sonar coverage (#960) * fixed attribute list issue * fixed attribute list issue * updated * updated if condition * fixed address issue in identity API * fixed null attribute list issue * fixed variable issue * format * code formatting * null format attribute list issue * fixed vid left count issue * updated method name * take status code from templates * status from templates * removed unused code * undo changes * remove unused import * fixed invalid otp issue * updated method name * removed additional entity * fixed entity issue * passed requesttype instead of string * fixed update times * removed unused code * fixed failure case * added test cases for notification endpoints * code coverage --------- Co-authored-by: Ritik Jain * [MOSIP-27405] Updated Audits (#962) * [MOSIP-24670] Updated API correction id and version * [MOSIP-24670] Updated API body correction * [MOSIP-22640] Fixed Sonar Bugs * updated PR * updated PR * updated review code * [MOSIP-22640] Fixed sonar bugs * updated PR * updated PR * [MOSIP-22639] Resolved security hotspots in code * [MOSIP-24630] Fixed Security Vulnerability in code * added error for isValidUrl method * renamed vaildateURL method * updated PR * updated PR * [MOSIP-24670] Made corrections in id and version * resolved conflicts * updated PR * updated PR * [MOSIP-24670] Made corrections n API body, response code * updated PR * updated PR * updated dateTime * updated PR * [MOSIP-25539] Made corrections in API body, response code * [MOSIP-25539] made corrections in API body * updated error message * updated error code * updated trasactionid dto change * added equals * [MOSIP-25539] made corrections in api body * [MOSIP-25539] Corrected API response body Task 5 * resolved build failure * [MOSIP-25539] Task 2 Added error code for vaildateOtp API * updated PR * updated PR * updated PR * updated PR * [MOSIP-25539] Updated validateotp method * updated PR * [MOSIP-25798] Added validations * updated PR * updated PR * updated PR * updated PR * updated PR * [MOSIP-25791] Added purpose as mandatory * Added error * Added Audit logs * updated test cases * [MOSIP-22913],[MOSIP-22914],[MOSIP-24653],[MOSIP-24796] Added Audit logs * updated logs * updated auditlog code * updated enum name for audit logs * updated enum name for audit logs * updated enum name for audit logs * updated enum name for audit logs * updated enum name for audit logs * [MOSIP-25268] Fixed Sonar vulnerability * [MOSIP-25268] Fixed Sonar vulnerability * [MOSIP-26272] Added validation for /update-uin API * updated PR * updated update-uin PR * Fixed build issue * Updated transactionId error message * Updated Test cases ResidentServiceResUpdateTest class * [MOSIP-26343] Created module specific audits * updated PR * updated PR * [MOSIP-26087] Added featureName in pdf name * updated PR * Updated PR as per review * updated PR * updated PR * Updated build * [MOSIP-24494] Updated trasnliterate API error msg * updated PR * updated PR * [MOSIP-25363],[MOSIP-24796],[MOSIP-25711] Updated audit logs * [MOSIP-26089] Added authentication mode * Fixed Sonar Bugs * updated PR * updated as per review * Updated Sonar Fix * Updated Sonar bug fix * Updated Sonar bug fix * Updated Sonar bug fix * Updated Sonar bug fix * Updated Sonar bug fix * Updated Sonar bug fix * [MOSIP-25793] Added audit logs * Fixed sonar bug * Fixed sonar bug * Fixed Sonar Bug * Updated Sonar Fix * Fixed build failure * [MOSIP-27213] Updated update-uin method * [MOSIP-27213] Updated ObjectValidator method * [MOSIP-27213] Updated ObjectValidator method * [MOSIP-27213] Updated ObjectValidator method * [MOSIP-27253,MOSIP-27254,MOSIP27255] Updated Download card method * updated PR * [MOSIP-25363,MOSIP-27337] Updated Audit logs * Updated Audit event name * Updated sonar coverage * [MOSIP-27548,MOSIP-27547]Updated audits * Updated Audits Event name * Updated PR * Updated PR * Updated PR * Updated PR * [MOSIP-27405] Updated Audits * [MOSIP-27405] Updated Audits * [MOSIP-27552] Added ref_id as hash value of id * [MOSIP-27552] Added ref_id as hash value of id * [MOSIP-27729,MOSIP-27730,27696] Updated Audits * [MOSIP-27729,MOSIP-27730,27696] Updated Audits * Updated PR * Updated PR * [MOSIP-27696,MOSIP-27405]Updated Audits * [MOSIP-27405]Updated Audits] * [MOSIP-27405]Updated Audits * updated PR * [MOSIP-27405]Updated Audits (#966) * [MOSIP-24670] Updated API correction id and version * [MOSIP-24670] Updated API body correction * [MOSIP-22640] Fixed Sonar Bugs * updated PR * updated PR * updated review code * [MOSIP-22640] Fixed sonar bugs * updated PR * updated PR * [MOSIP-22639] Resolved security hotspots in code * [MOSIP-24630] Fixed Security Vulnerability in code * added error for isValidUrl method * renamed vaildateURL method * updated PR * updated PR * [MOSIP-24670] Made corrections in id and version * resolved conflicts * updated PR * updated PR * [MOSIP-24670] Made corrections n API body, response code * updated PR * updated PR * updated dateTime * updated PR * [MOSIP-25539] Made corrections in API body, response code * [MOSIP-25539] made corrections in API body * updated error message * updated error code * updated trasactionid dto change * added equals * [MOSIP-25539] made corrections in api body * [MOSIP-25539] Corrected API response body Task 5 * resolved build failure * [MOSIP-25539] Task 2 Added error code for vaildateOtp API * updated PR * updated PR * updated PR * updated PR * [MOSIP-25539] Updated validateotp method * updated PR * [MOSIP-25798] Added validations * updated PR * updated PR * updated PR * updated PR * updated PR * [MOSIP-25791] Added purpose as mandatory * Added error * Added Audit logs * updated test cases * [MOSIP-22913],[MOSIP-22914],[MOSIP-24653],[MOSIP-24796] Added Audit logs * updated logs * updated auditlog code * updated enum name for audit logs * updated enum name for audit logs * updated enum name for audit logs * updated enum name for audit logs * updated enum name for audit logs * [MOSIP-25268] Fixed Sonar vulnerability * [MOSIP-25268] Fixed Sonar vulnerability * [MOSIP-26272] Added validation for /update-uin API * updated PR * updated update-uin PR * Fixed build issue * Updated transactionId error message * Updated Test cases ResidentServiceResUpdateTest class * [MOSIP-26343] Created module specific audits * updated PR * updated PR * [MOSIP-26087] Added featureName in pdf name * updated PR * Updated PR as per review * updated PR * updated PR * Updated build * [MOSIP-24494] Updated trasnliterate API error msg * updated PR * updated PR * [MOSIP-25363],[MOSIP-24796],[MOSIP-25711] Updated audit logs * [MOSIP-26089] Added authentication mode * Fixed Sonar Bugs * updated PR * updated as per review * Updated Sonar Fix * Updated Sonar bug fix * Updated Sonar bug fix * Updated Sonar bug fix * Updated Sonar bug fix * Updated Sonar bug fix * Updated Sonar bug fix * [MOSIP-25793] Added audit logs * Fixed sonar bug * Fixed sonar bug * Fixed Sonar Bug * Updated Sonar Fix * Fixed build failure * [MOSIP-27213] Updated update-uin method * [MOSIP-27213] Updated ObjectValidator method * [MOSIP-27213] Updated ObjectValidator method * [MOSIP-27213] Updated ObjectValidator method * [MOSIP-27253,MOSIP-27254,MOSIP27255] Updated Download card method * updated PR * [MOSIP-25363,MOSIP-27337] Updated Audit logs * Updated Audit event name * Updated sonar coverage * [MOSIP-27548,MOSIP-27547]Updated audits * Updated Audits Event name * Updated PR * Updated PR * Updated PR * Updated PR * [MOSIP-27405] Updated Audits * [MOSIP-27405] Updated Audits * [MOSIP-27552] Added ref_id as hash value of id * [MOSIP-27552] Added ref_id as hash value of id * [MOSIP-27729,MOSIP-27730,27696] Updated Audits * [MOSIP-27729,MOSIP-27730,27696] Updated Audits * Updated PR * Updated PR * [MOSIP-27696,MOSIP-27405]Updated Audits * [MOSIP-27405]Updated Audits] * [MOSIP-27405]Updated Audits * updated PR * [MOSIP-27405]Updated Audits * updated package of some classes (#964) * updated package * updated package of validation test calsses * updated * formatting * updated packages of controller test classes * updated package of service impl test classes * updated package of util test classes * updated package of aspect test classes * updated package of config test classes * updated package of handler test classes * added some exception test cases --------- Co-authored-by: Ritik Jain * Fixed Null pointer exception in notification method. * Fixed Null pointer exception in notification method. (#967) * Fixed service history issue. * MOSIP-27716 Moved identity-data-formatter.mvel to credentialdata.mvel. * Fixed Null pointer exception in notification method. * Sonar coverage (#969) * updated package * updated package of validation test calsses * updated * formatting * updated packages of controller test classes * updated package of service impl test classes * updated package of util test classes * updated package of aspect test classes * updated package of config test classes * updated package of handler test classes * added some exception test cases * added coverage for vid controller * added junit for configservice impl --------- Co-authored-by: Ritik Jain * fix build issue (#970) Co-authored-by: Loganathan Sekar * Sonar coverage (#972) * updated package * updated package of validation test calsses * updated * formatting * updated packages of controller test classes * updated package of service impl test classes * updated package of util test classes * updated package of aspect test classes * updated package of config test classes * updated package of handler test classes * added some exception test cases * added coverage for vid controller * added junit for configservice impl * added junits for config service impl * formatting --------- Co-authored-by: Ritik Jain * Sonar coverage and formatting (#974) * updated package * updated package of validation test calsses * updated * formatting * updated packages of controller test classes * updated package of service impl test classes * updated package of util test classes * updated package of aspect test classes * updated package of config test classes * updated package of handler test classes * added some exception test cases * added coverage for vid controller * added junit for configservice impl * added junits for config service impl * formatting * updated test cases --------- Co-authored-by: Ritik Jain * Fixed Null pointer exception in download card. (#971) * Fixed service history issue. * MOSIP-27716 Moved identity-data-formatter.mvel to credentialdata.mvel. * Fixed Null pointer exception in notification method. * Fixed Null pointer exception in download card. * Fixed Null pointer exception in download card. * MOSIP-24939 Improved code coverage. (#973) * Fixed service history issue. * MOSIP-27716 Moved identity-data-formatter.mvel to credentialdata.mvel. * Fixed Null pointer exception in notification method. * MOSIP-24939 Improved code coverage of request validator . * MOSIP-24939 Improved code coverage of request validator . * MOSIP-24939 Improved code coverage of request validator . * MOSIP-24939 Improved code coverage of request validator . * MOSIP-24939 Improved code coverage of request validator . * MOSIP-24939 Improved code coverage of request validator . * MOSIP-24939 Improved code coverage of request validator . * MOSIP-24939 Improved code coverage of request validator . * Code cleanup (#977) * fix build issue * Fix local startup issue * Code cleanup, added domain-url config, organised imports --------- Co-authored-by: Loganathan Sekar * MOSIP-24939 Improved code coverage of ResidentVidServiceImpl. (#979) * Fixed service history issue. * MOSIP-27716 Moved identity-data-formatter.mvel to credentialdata.mvel. * Fixed Null pointer exception in notification method. * MOSIP-24939 Improved code coverage of ResidentVidServiceImpl. * MOSIP-24939 Improved code coverage of ResidentVidServiceImpl. (#980) * Fixed service history issue. * MOSIP-27716 Moved identity-data-formatter.mvel to credentialdata.mvel. * Fixed Null pointer exception in notification method. * MOSIP-24939 Improved code coverage of ResidentVidServiceImpl. * MOSIP-24939 Improved code coverage of ResidentVidServiceImpl. * MOSIP-24939 Improved code coverage of ResidentVidServiceImpl. * MOSIP-24939 Improved code coverage of ResidentVidServiceImpl. * Fixed update uin issue (#981) * Fixed service history issue. * MOSIP-27716 Moved identity-data-formatter.mvel to credentialdata.mvel. * Fixed Null pointer exception in notification method. * MOSIP-24939 Improved code coverage of ResidentVidServiceImpl. * MOSIP-24939 Improved code coverage of ResidentVidServiceImpl. * MOSIP-24939 Improved code coverage of ResidentVidServiceImpl. * MOSIP-24939 Improved code coverage of ResidentVidServiceImpl. * MOSIP-24939 Improved code coverage of ResidentVidServiceImpl. * Fix update uin issue. (#982) * Fixed service history issue. * MOSIP-27716 Moved identity-data-formatter.mvel to credentialdata.mvel. * Fixed Null pointer exception in notification method. * MOSIP-24939 Improved code coverage of ResidentVidServiceImpl. * MOSIP-24939 Improved code coverage of ResidentVidServiceImpl. * MOSIP-24939 Improved code coverage of ResidentVidServiceImpl. * MOSIP-24939 Improved code coverage of ResidentVidServiceImpl. * MOSIP-24939 Improved code coverage of ResidentVidServiceImpl. * MOSIP-24939 Improved code coverage of ResidentVidServiceImpl. * Updated pom version * Updated pom version * Added upgrade and rollback sql files. * Added upgrade and rollback sql files. --------- Signed-off-by: kameshsr <47484458+kameshsr@users.noreply.github.com> Co-authored-by: Loganathan Sekar <42532387+LoganathanSekar7627@users.noreply.github.com> Co-authored-by: Loganathan Sekar Co-authored-by: RitikJain4108 <99730411+RitikJain4108@users.noreply.github.com> Co-authored-by: Ritik Jain Co-authored-by: Aiham Hasan <89243555+aihamh@users.noreply.github.com> Co-authored-by: Neha2365 <110969715+Neha2365@users.noreply.github.com> Co-authored-by: Neha Farheen --- .../sql/1.1.5.5_1.2.0.1-B2_rollback.sql | 20 + .../sql/1.1.5.5_to_1.2.0.1-B2_upgrade.sql | 21 + resident/resident-service/pom.xml | 56 +- .../resident/ResidentBootApplication.java | 4 +- .../io/mosip/resident/aspect/LoginCheck.java | 2 +- .../batch/CredentialStatusUpdateBatchJob.java | 302 +---- .../resident/config/ResidentFilterConfig.java | 49 + .../io/mosip/resident/constant/ApiName.java | 2 +- .../resident/constant/EventStatusFailure.java | 3 +- .../resident/constant/EventStatusSuccess.java | 5 +- .../mosip/resident/constant/PacketStatus.java | 62 +- .../constant/PreUpdateInBatchJob.java | 35 + .../constant/RegistrationConstants.java | 1 + .../mosip/resident/constant/RequestType.java | 259 ++-- .../resident/constant/ResidentConstants.java | 64 +- .../resident/constant/ResidentErrorCode.java | 9 +- .../mosip/resident/constant/ServiceType.java | 27 +- .../mosip/resident/constant/TemplateType.java | 1 + .../constant/TemplateVariablesConstants.java | 3 +- .../resident/constant/TransactionStage.java | 84 +- .../resident/constant/UISchemaTypes.java | 54 + .../controller/AcknowledgementController.java | 9 +- .../AuthTransactionCallbackController.java | 49 +- .../DownLoadMasterDataController.java | 103 +- .../controller/DownloadCardController.java | 109 +- .../controller/GrievanceController.java | 36 +- .../resident/controller/IdAuthController.java | 6 +- .../controller/IdentityController.java | 1 + .../controller/OrderCardController.java | 15 +- .../controller/PinStatusController.java | 53 +- .../controller/ProxyMasterdataController.java | 16 +- .../controller/ProxyOtpController.java | 137 +++ .../ProxyPartnerManagementController.java | 16 +- .../controller/ResidentController.java | 258 ++-- .../ResidentCredentialController.java | 48 +- .../controller/ResidentOtpController.java | 5 +- .../controller/ResidentVidController.java | 14 +- .../controller/TransliterationController.java | 81 ++ .../controller/VerificationController.java | 52 +- ...ebSubCredentialStatusUpdateController.java | 90 ++ .../WebSubUpdateAuthTypeController.java | 49 +- .../dto/DynamicFieldCodeValueDTO.java | 23 + .../DynamicFieldConsolidateResponseDto.java | 26 + .../io/mosip/resident/dto/IdentityDTO.java | 1 + .../RegistrationCenterInfoResponseDto.java | 20 + .../io/mosip/resident/dto/UserInfoDto.java | 3 +- .../entity/ResidentTransactionEntity.java | 3 + .../exception/ApiExceptionHandler.java | 36 + .../exception/InvalidInputException.java | 3 +- .../exception/VidAlreadyPresentException.java | 8 +- .../mosip/resident/filter/LoggingFilter.java | 87 ++ .../RepeatableStreamHttpServletRequest.java | 205 ++++ .../WebsubCallbackRequestDecoratorFilter.java | 54 + .../resident/function/FiveArgsFunction.java | 29 + .../resident/function/FourArgsFunction.java | 27 + .../service/ResidentConfigService.java | 12 +- .../service/ResidentUpdateService.java | 13 +- .../helper/CredentialStatusUpdateHelper.java | 155 +++ .../resident/helper/ObjectStoreHelper.java | 2 +- .../ResidentTransactionRepository.java | 291 +++-- .../service/AcknowledgementService.java | 2 +- .../AuthTransactionCallBackService.java | 4 +- .../service/DownLoadMasterDataService.java | 3 +- .../resident/service/DownloadCardService.java | 13 +- .../mosip/resident/service/IdAuthService.java | 7 +- .../io/mosip/resident/service/OtpManager.java | 19 + .../service/PinUnpinStatusService.java | 3 +- .../service/ProxyMasterdataService.java | 16 +- .../resident/service/ProxyOtpService.java | 20 + .../service/ResidentCredentialService.java | 11 +- .../resident/service/ResidentService.java | 23 +- .../resident/service/ResidentVidService.java | 4 +- .../WebSubCredentialStatusUpdateService.java | 20 + .../service/WebSubUpdateAuthTypeService.java | 6 +- .../impl/AcknowledgementServiceImpl.java | 15 +- .../AuthTransactionCallBackServiceImpl.java | 78 +- .../service/impl/BaseWebSubInitializer.java | 93 +- .../impl/DownLoadMasterDataServiceImpl.java | 53 +- .../service/impl/DownloadCardServiceImpl.java | 282 +++-- .../service/impl/IdAuthServiceImpl.java | 100 +- .../service/impl/IdentityServiceImpl.java | 12 +- .../service/impl/OrderCardServiceImpl.java | 10 +- .../service/impl/OtpManagerServiceImpl.java | 255 ++++ .../impl/PinUnpinStatusServiceImpl.java | 3 +- .../service/impl/ProxyIdRepoServiceImpl.java | 3 +- .../impl/ProxyMasterdataServiceImpl.java | 33 +- .../service/impl/ProxyOtpServiceImpl.java | 211 ++++ .../impl/ResidentConfigServiceImpl.java | 157 ++- .../impl/ResidentCredentialServiceImpl.java | 69 +- .../service/impl/ResidentOtpServiceImpl.java | 15 +- .../service/impl/ResidentServiceImpl.java | 536 ++++---- .../service/impl/ResidentVidServiceImpl.java | 96 +- ...bSubCredentialStatusUpdateServiceImpl.java | 68 ++ .../impl/WebSubUpdateAuthTypeServiceImpl.java | 94 +- .../io/mosip/resident/util/AuditUtil.java | 28 +- .../io/mosip/resident/util/EventEnum.java | 485 +++++--- .../util/ResidentServiceRestClient.java | 6 +- .../io/mosip/resident/util/TemplateUtil.java | 1080 +++++++++-------- .../io/mosip/resident/util/Utilities.java | 65 +- .../java/io/mosip/resident/util/Utility.java | 236 +++- .../resident/validator/RequestValidator.java | 297 +++-- .../resources/application-local.properties | 8 + .../mosip/resident/aspect/LoginCheckTest.java | 201 +++ .../CredentialStatusUpdateBatchJobTest.java | 127 +- .../config/ResidentServiceConfigTest.java | 10 +- .../{test => }/config/TestSecurityConfig.java | 8 +- .../AcknowledgmentControllerTest.java | 137 +++ ...AuthTransactionCallbackControllerTest.java | 140 +++ .../controller/DocumentControllerTest.java | 48 +- .../DownloadCardControllerTest.java | 234 ++++ .../DownloadMasterdataControllerTest.java | 184 +++ .../controller/GrievanceControllerTest.java | 154 +++ .../controller/IdAuthControllerTest.java | 115 ++ .../controller/IdentityControllerTest.java | 132 ++ .../controller/OrderCardControllerTest.java | 152 +++ .../controller/PinStatusControllerTest.java | 83 ++ .../controller/ProxyAuditControllerTest.java | 140 +++ .../controller/ProxyConfigControllerTest.java | 117 ++ .../ProxyMasterdataControllerTest.java | 218 ++++ .../controller/ProxyOtpControllerTest.java | 183 +++ .../ProxyPartnerManagementControllerTest.java | 113 ++ .../controller/ResidentControllerTest.java | 235 +++- .../ResidentCredentialControllerTest.java | 5 +- .../controller/ResidentOtpControllerTest.java | 43 +- .../ResidentVerificationControllerTest.java | 114 ++ .../controller/ResidentVidControllerTest.java | 106 +- .../TransliterationControllerTest.java | 86 ++ ...bCredentialStatusUpdateControllerTest.java | 138 +++ .../WebSubUpdateAuthTypeControllerTest.java | 135 +++ .../service}/ResidentUpdateServiceTest.java | 6 +- .../service}/SyncAndUploadServiceTest.java | 3 +- .../service}/UinCardRePrintServiceTest.java | 4 +- .../CredentialStatusUpdateHelperTest.java | 77 ++ .../impl}/IdAuthServiceTest.java | 17 +- .../impl}/NotificationServiceTest.java | 2 +- .../impl/OTPManagerServiceImplTest.java | 184 +++ .../impl/ProxyOtpServiceImpllTest.java | 271 +++++ .../impl/ResidentConfigServiceImplTest.java | 133 +- .../impl}/ResidentCredentialServiceTest.java | 78 +- .../impl/ResidentOtpServiceImplTest.java | 2 +- .../impl}/ResidentOtpServiceTest.java | 4 +- .../ResidentServiceReqAuthHistoryTest.java | 3 +- .../impl}/ResidentServiceReqEUinTest.java | 3 +- .../impl}/ResidentServiceReqReprintTest.java | 3 +- .../ResidentServiceRequestAuthLockTest.java | 104 +- .../impl}/ResidentServiceResUpdateTest.java | 131 +- .../impl}/ResidentVidServiceTest.java | 301 ++++- .../impl}/RidStatusServiceTest.java | 3 +- .../service/AcknowledgmentServiceTest.java | 217 ---- .../AuthTransactionCallbackServiceTest.java | 113 -- .../service/BaseWebSubInitializerTest.java | 160 --- .../test/service/DownloadCardServiceTest.java | 367 ------ .../DownloadmasterDataServiceImplTest.java | 186 --- .../service/GrievanceServiceImplTest.java | 74 -- .../test/service/IdentityServiceTest.java | 618 ---------- .../test/service/OrderCardServiceTest.java | 174 --- .../test/service/PartnerServiceImplTest.java | 96 -- .../service/PinUnpinStatusServiceTest.java | 83 -- .../test/service/ProxyIdRepoServiceTest.java | 66 - .../service/ProxyMasterdataServiceTest.java | 657 ---------- .../ProxyPartnerManagementServiceTest.java | 116 -- .../ResidentServiceDownloadCardTest.java | 386 ------ ...sidentServiceGetCredentialRequestTest.java | 106 -- .../ResidentServiceGetEventStatusTest.java | 180 --- .../ResidentServiceGetServiceHistoryTest.java | 407 ------- ...esidentServiceRequestTypeAuthLockTest.java | 326 ----- .../ResidentVerificationServiceTest.java | 79 -- .../WebSubUpdateAuthTypeServiceTest.java | 121 -- .../RequestHandlerRequestValidatorTest.java | 505 -------- .../{test => }/util/AuditUtilTest.java | 40 +- .../{test => }/util/EncryptorUtilTest.java | 4 +- .../{test => }/util/IdSchemaUtilTest.java | 4 +- .../{test => }/util/JsonUtilTest.java | 2 +- .../util/ResidentServiceRestClientTest.java | 3 +- .../{test => }/util/ServerUtilTest.java | 4 +- .../mosip/resident/util/TemplateUtilTest.java | 533 ++++++++ .../{test => }/util/TokenGeneratorTest.java | 2 +- .../{test => }/util/UINCardDownloadTest.java | 2 +- .../{test => }/util/UtilitiesTest.java | 21 +- .../resident/{test => }/util/UtilityTest.java | 128 +- .../RequestHandlerRequestValidatorTest.java | 512 ++++++++ .../validator/RequestValidatorTest.java | 689 ++++++++++- .../src/test/resources/amr-acr-mapping.json | 14 + .../src/test/resources/application.properties | 26 +- .../src/test/resources/credentialdata.mvel | 10 + 185 files changed, 11665 insertions(+), 7800 deletions(-) create mode 100644 db_release_scripts/mosip_resident/sql/1.1.5.5_1.2.0.1-B2_rollback.sql create mode 100644 db_release_scripts/mosip_resident/sql/1.1.5.5_to_1.2.0.1-B2_upgrade.sql create mode 100644 resident/resident-service/src/main/java/io/mosip/resident/config/ResidentFilterConfig.java create mode 100644 resident/resident-service/src/main/java/io/mosip/resident/constant/PreUpdateInBatchJob.java create mode 100644 resident/resident-service/src/main/java/io/mosip/resident/constant/UISchemaTypes.java create mode 100644 resident/resident-service/src/main/java/io/mosip/resident/controller/ProxyOtpController.java create mode 100644 resident/resident-service/src/main/java/io/mosip/resident/controller/TransliterationController.java create mode 100644 resident/resident-service/src/main/java/io/mosip/resident/controller/WebSubCredentialStatusUpdateController.java create mode 100644 resident/resident-service/src/main/java/io/mosip/resident/dto/DynamicFieldCodeValueDTO.java create mode 100644 resident/resident-service/src/main/java/io/mosip/resident/dto/DynamicFieldConsolidateResponseDto.java create mode 100644 resident/resident-service/src/main/java/io/mosip/resident/dto/RegistrationCenterInfoResponseDto.java create mode 100644 resident/resident-service/src/main/java/io/mosip/resident/filter/LoggingFilter.java create mode 100644 resident/resident-service/src/main/java/io/mosip/resident/filter/RepeatableStreamHttpServletRequest.java create mode 100644 resident/resident-service/src/main/java/io/mosip/resident/filter/WebsubCallbackRequestDecoratorFilter.java create mode 100644 resident/resident-service/src/main/java/io/mosip/resident/function/FiveArgsFunction.java create mode 100644 resident/resident-service/src/main/java/io/mosip/resident/function/FourArgsFunction.java create mode 100644 resident/resident-service/src/main/java/io/mosip/resident/helper/CredentialStatusUpdateHelper.java create mode 100644 resident/resident-service/src/main/java/io/mosip/resident/service/OtpManager.java create mode 100644 resident/resident-service/src/main/java/io/mosip/resident/service/ProxyOtpService.java create mode 100644 resident/resident-service/src/main/java/io/mosip/resident/service/WebSubCredentialStatusUpdateService.java create mode 100644 resident/resident-service/src/main/java/io/mosip/resident/service/impl/OtpManagerServiceImpl.java create mode 100644 resident/resident-service/src/main/java/io/mosip/resident/service/impl/ProxyOtpServiceImpl.java create mode 100644 resident/resident-service/src/main/java/io/mosip/resident/service/impl/WebSubCredentialStatusUpdateServiceImpl.java create mode 100644 resident/resident-service/src/test/java/io/mosip/resident/aspect/LoginCheckTest.java rename resident/resident-service/src/test/java/io/mosip/resident/{test => }/config/ResidentServiceConfigTest.java (81%) rename resident/resident-service/src/test/java/io/mosip/resident/{test => }/config/TestSecurityConfig.java (96%) create mode 100644 resident/resident-service/src/test/java/io/mosip/resident/controller/AcknowledgmentControllerTest.java create mode 100644 resident/resident-service/src/test/java/io/mosip/resident/controller/AuthTransactionCallbackControllerTest.java create mode 100644 resident/resident-service/src/test/java/io/mosip/resident/controller/DownloadCardControllerTest.java create mode 100644 resident/resident-service/src/test/java/io/mosip/resident/controller/DownloadMasterdataControllerTest.java create mode 100644 resident/resident-service/src/test/java/io/mosip/resident/controller/GrievanceControllerTest.java create mode 100644 resident/resident-service/src/test/java/io/mosip/resident/controller/IdAuthControllerTest.java create mode 100644 resident/resident-service/src/test/java/io/mosip/resident/controller/IdentityControllerTest.java create mode 100644 resident/resident-service/src/test/java/io/mosip/resident/controller/OrderCardControllerTest.java create mode 100644 resident/resident-service/src/test/java/io/mosip/resident/controller/PinStatusControllerTest.java create mode 100644 resident/resident-service/src/test/java/io/mosip/resident/controller/ProxyAuditControllerTest.java create mode 100644 resident/resident-service/src/test/java/io/mosip/resident/controller/ProxyConfigControllerTest.java create mode 100644 resident/resident-service/src/test/java/io/mosip/resident/controller/ProxyMasterdataControllerTest.java create mode 100644 resident/resident-service/src/test/java/io/mosip/resident/controller/ProxyOtpControllerTest.java create mode 100644 resident/resident-service/src/test/java/io/mosip/resident/controller/ProxyPartnerManagementControllerTest.java rename resident/resident-service/src/test/java/io/mosip/resident/{test => }/controller/ResidentControllerTest.java (66%) rename resident/resident-service/src/test/java/io/mosip/resident/{test => }/controller/ResidentCredentialControllerTest.java (98%) rename resident/resident-service/src/test/java/io/mosip/resident/{test => }/controller/ResidentOtpControllerTest.java (74%) create mode 100644 resident/resident-service/src/test/java/io/mosip/resident/controller/ResidentVerificationControllerTest.java rename resident/resident-service/src/test/java/io/mosip/resident/{test => }/controller/ResidentVidControllerTest.java (80%) create mode 100644 resident/resident-service/src/test/java/io/mosip/resident/controller/TransliterationControllerTest.java create mode 100644 resident/resident-service/src/test/java/io/mosip/resident/controller/WebSubCredentialStatusUpdateControllerTest.java create mode 100644 resident/resident-service/src/test/java/io/mosip/resident/controller/WebSubUpdateAuthTypeControllerTest.java rename resident/resident-service/src/test/java/io/mosip/resident/{test/handler => handler/service}/ResidentUpdateServiceTest.java (94%) rename resident/resident-service/src/test/java/io/mosip/resident/{test/handler => handler/service}/SyncAndUploadServiceTest.java (98%) rename resident/resident-service/src/test/java/io/mosip/resident/{test/handler => handler/service}/UinCardRePrintServiceTest.java (96%) create mode 100644 resident/resident-service/src/test/java/io/mosip/resident/helper/CredentialStatusUpdateHelperTest.java rename resident/resident-service/src/test/java/io/mosip/resident/{test/service => service/impl}/IdAuthServiceTest.java (98%) rename resident/resident-service/src/test/java/io/mosip/resident/{test/service => service/impl}/NotificationServiceTest.java (97%) create mode 100644 resident/resident-service/src/test/java/io/mosip/resident/service/impl/OTPManagerServiceImplTest.java create mode 100644 resident/resident-service/src/test/java/io/mosip/resident/service/impl/ProxyOtpServiceImpllTest.java rename resident/resident-service/src/test/java/io/mosip/resident/{test/service => service/impl}/ResidentCredentialServiceTest.java (87%) rename resident/resident-service/src/test/java/io/mosip/resident/{test/service => service/impl}/ResidentOtpServiceTest.java (95%) rename resident/resident-service/src/test/java/io/mosip/resident/{test/service => service/impl}/ResidentServiceReqAuthHistoryTest.java (98%) rename resident/resident-service/src/test/java/io/mosip/resident/{test/service => service/impl}/ResidentServiceReqEUinTest.java (98%) rename resident/resident-service/src/test/java/io/mosip/resident/{test/service => service/impl}/ResidentServiceReqReprintTest.java (98%) rename resident/resident-service/src/test/java/io/mosip/resident/{test/service => service/impl}/ResidentServiceRequestAuthLockTest.java (50%) rename resident/resident-service/src/test/java/io/mosip/resident/{test/service => service/impl}/ResidentServiceResUpdateTest.java (80%) rename resident/resident-service/src/test/java/io/mosip/resident/{test/service => service/impl}/ResidentVidServiceTest.java (51%) rename resident/resident-service/src/test/java/io/mosip/resident/{test/service => service/impl}/RidStatusServiceTest.java (98%) delete mode 100644 resident/resident-service/src/test/java/io/mosip/resident/test/service/AcknowledgmentServiceTest.java delete mode 100644 resident/resident-service/src/test/java/io/mosip/resident/test/service/AuthTransactionCallbackServiceTest.java delete mode 100644 resident/resident-service/src/test/java/io/mosip/resident/test/service/BaseWebSubInitializerTest.java delete mode 100644 resident/resident-service/src/test/java/io/mosip/resident/test/service/DownloadCardServiceTest.java delete mode 100644 resident/resident-service/src/test/java/io/mosip/resident/test/service/DownloadmasterDataServiceImplTest.java delete mode 100644 resident/resident-service/src/test/java/io/mosip/resident/test/service/GrievanceServiceImplTest.java delete mode 100644 resident/resident-service/src/test/java/io/mosip/resident/test/service/IdentityServiceTest.java delete mode 100644 resident/resident-service/src/test/java/io/mosip/resident/test/service/OrderCardServiceTest.java delete mode 100644 resident/resident-service/src/test/java/io/mosip/resident/test/service/PartnerServiceImplTest.java delete mode 100644 resident/resident-service/src/test/java/io/mosip/resident/test/service/PinUnpinStatusServiceTest.java delete mode 100644 resident/resident-service/src/test/java/io/mosip/resident/test/service/ProxyIdRepoServiceTest.java delete mode 100644 resident/resident-service/src/test/java/io/mosip/resident/test/service/ProxyMasterdataServiceTest.java delete mode 100644 resident/resident-service/src/test/java/io/mosip/resident/test/service/ProxyPartnerManagementServiceTest.java delete mode 100644 resident/resident-service/src/test/java/io/mosip/resident/test/service/ResidentServiceDownloadCardTest.java delete mode 100644 resident/resident-service/src/test/java/io/mosip/resident/test/service/ResidentServiceGetCredentialRequestTest.java delete mode 100644 resident/resident-service/src/test/java/io/mosip/resident/test/service/ResidentServiceGetEventStatusTest.java delete mode 100644 resident/resident-service/src/test/java/io/mosip/resident/test/service/ResidentServiceGetServiceHistoryTest.java delete mode 100644 resident/resident-service/src/test/java/io/mosip/resident/test/service/ResidentServiceRequestTypeAuthLockTest.java delete mode 100644 resident/resident-service/src/test/java/io/mosip/resident/test/service/ResidentVerificationServiceTest.java delete mode 100644 resident/resident-service/src/test/java/io/mosip/resident/test/service/WebSubUpdateAuthTypeServiceTest.java delete mode 100644 resident/resident-service/src/test/java/io/mosip/resident/test/validator/RequestHandlerRequestValidatorTest.java rename resident/resident-service/src/test/java/io/mosip/resident/{test => }/util/AuditUtilTest.java (79%) rename resident/resident-service/src/test/java/io/mosip/resident/{test => }/util/EncryptorUtilTest.java (97%) rename resident/resident-service/src/test/java/io/mosip/resident/{test => }/util/IdSchemaUtilTest.java (99%) rename resident/resident-service/src/test/java/io/mosip/resident/{test => }/util/JsonUtilTest.java (98%) rename resident/resident-service/src/test/java/io/mosip/resident/{test => }/util/ResidentServiceRestClientTest.java (99%) rename resident/resident-service/src/test/java/io/mosip/resident/{test => }/util/ServerUtilTest.java (91%) create mode 100644 resident/resident-service/src/test/java/io/mosip/resident/util/TemplateUtilTest.java rename resident/resident-service/src/test/java/io/mosip/resident/{test => }/util/TokenGeneratorTest.java (99%) rename resident/resident-service/src/test/java/io/mosip/resident/{test => }/util/UINCardDownloadTest.java (98%) rename resident/resident-service/src/test/java/io/mosip/resident/{test => }/util/UtilitiesTest.java (94%) rename resident/resident-service/src/test/java/io/mosip/resident/{test => }/util/UtilityTest.java (82%) create mode 100644 resident/resident-service/src/test/java/io/mosip/resident/validator/RequestHandlerRequestValidatorTest.java rename resident/resident-service/src/test/java/io/mosip/resident/{test => }/validator/RequestValidatorTest.java (75%) create mode 100644 resident/resident-service/src/test/resources/amr-acr-mapping.json create mode 100644 resident/resident-service/src/test/resources/credentialdata.mvel diff --git a/db_release_scripts/mosip_resident/sql/1.1.5.5_1.2.0.1-B2_rollback.sql b/db_release_scripts/mosip_resident/sql/1.1.5.5_1.2.0.1-B2_rollback.sql new file mode 100644 index 00000000000..307278cb025 --- /dev/null +++ b/db_release_scripts/mosip_resident/sql/1.1.5.5_1.2.0.1-B2_rollback.sql @@ -0,0 +1,20 @@ +-- ------------------------------------------------------------------------------------------------- +-- Database Name: mosip_resident +-- Release Version : 1.2.1 +-- Purpose : Database scripts for Resident Service DB. +-- Create By : Manoj SP +-- Created Date : April-2022 +-- +-- Modified Date Modified By Comments / Remarks +-- -------------------------------------------------------------------------------------------------- +-- April-2022 Manoj SP Added otp_transaction table creation scripts with comments. +-- April-2022 Kamesh Shekhar Prasad Added resident_transaction table creation scripts with comments. +----------------------------------------------------------------------------------------------------- +\c mosip_resident sysadmin + +DROP TABLE IF EXISTS resident.otp_transaction; +DROP TABLE IF EXISTS resident.resident_transaction; +DROP TABLE IF EXISTS resident.resident_session; +DROP TABLE IF EXISTS resident.resident_user_actions; + +----------------------------------------------------------------------------------------------------- \ No newline at end of file diff --git a/db_release_scripts/mosip_resident/sql/1.1.5.5_to_1.2.0.1-B2_upgrade.sql b/db_release_scripts/mosip_resident/sql/1.1.5.5_to_1.2.0.1-B2_upgrade.sql new file mode 100644 index 00000000000..03b163b8a65 --- /dev/null +++ b/db_release_scripts/mosip_resident/sql/1.1.5.5_to_1.2.0.1-B2_upgrade.sql @@ -0,0 +1,21 @@ +-- ------------------------------------------------------------------------------------------------- +-- Database Name: mosip_resident +-- Release Version : 1.2.1 +-- Purpose : Database scripts for Resident Service DB. +-- Create By : Manoj SP +-- Created Date : April-2022 +-- +-- Modified Date Modified By Comments / Remarks +-- -------------------------------------------------------------------------------------------------- +-- April-2022 Manoj SP Added otp_transaction table creation scripts with comments. +-- April-2022 Kamesh Shekhar Prasad Added resident_transaction table creation scripts with comments. +-- Dec-2022 Kamesh Shekhar Prasad Added resident_grievance_ticket, resident_user_actions table creation scripts with comments. +----------------------------------------------------------------------------------------------------- +\c mosip_resident sysadmin + +\ir ddl/otp_transaction.sql +\ir ddl/resident_transaction.sql +\ir ddl/resident_grievance_ticket.sql +\ir ddl/resident_user_actions.sql +\ir ddl/resident_sessions.sql +----------------------------------------------------------------------------------------------------- \ No newline at end of file diff --git a/resident/resident-service/pom.xml b/resident/resident-service/pom.xml index 133f39e42b3..a0a382a4a17 100644 --- a/resident/resident-service/pom.xml +++ b/resident/resident-service/pom.xml @@ -11,27 +11,25 @@ resident-service resident-service - 1.2.0.1-B2 + 1.2.0.1-SNAPSHOT - 1.2.0.1-B1 - 1.2.0.1-B1 - 1.2.0.1-B1 - 1.2.0.1-B1 - 1.2.0.1-B1 - 1.2.0.1-B2 + 1.2.0.1-SNAPSHOT + 1.2.0.1-SNAPSHOT + 1.2.0.1-SNAPSHOT + 1.2.0.1-SNAPSHOT + 1.2.0.1-SNAPSHOT + 1.2.0.1-SNAPSHOT 1.2.0 ${kernel.parent.version} - 1.2.0.1-B1 - 1.2.0.1-B2 1.5.10 UTF-8 2.12.0 2.12.0 - 1.2.0.1-B1 - 1.2.0.1-B1 - 1.2.0.1-B2 - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT + 1.2.0.1-SNAPSHOT + 1.2.0.1-SNAPSHOT + 1.2.0.1-SNAPSHOT @@ -348,7 +346,7 @@ io.mosip.kernel kernel-websubclient-api - ${kernel-websubclient-api.version} + ${project.version} io.mosip.kernel @@ -372,7 +370,6 @@ - org.apache.commons commons-lang3 @@ -405,6 +401,32 @@ commons-io 2.11.0 + + com.nimbusds + nimbus-jose-jwt + 9.31 + + + com.itextpdf + itextpdf + 5.5.13.3 + + + io.mosip.kernel + kernel-pdfgenerator-itext + 1.2.0.1-SNAPSHOT + + + org.springframework.security + spring-security-test + 5.3.3.RELEASE + test + + + org.bitbucket.b_c + jose4j + 0.9.3 + @@ -434,7 +456,7 @@ io.mosip.kernel kernel-auth-adapter - ${kernel.authadapter.version} + ${project.version} org.springframework.boot diff --git a/resident/resident-service/src/main/java/io/mosip/resident/ResidentBootApplication.java b/resident/resident-service/src/main/java/io/mosip/resident/ResidentBootApplication.java index 8cfaf52187f..fcd7ddb1b4f 100644 --- a/resident/resident-service/src/main/java/io/mosip/resident/ResidentBootApplication.java +++ b/resident/resident-service/src/main/java/io/mosip/resident/ResidentBootApplication.java @@ -8,6 +8,8 @@ import io.mosip.kernel.authcodeflowproxy.api.validator.ValidateTokenUtil; import io.mosip.kernel.cbeffutil.impl.CbeffImpl; import io.mosip.kernel.dataaccess.hibernate.config.HibernateDaoConfig; +import io.mosip.preregistration.application.service.TransliterationService; +import io.mosip.preregistration.application.service.util.TransliterationServiceUtil; @SpringBootApplication(scanBasePackages = { "io.mosip.resident.*", @@ -20,7 +22,7 @@ "io.mosip.kernel.virusscanner.*", "io.mosip.commons.khazana.*", "io.mosip.idrepository.core.util.*"},exclude = HibernateDaoConfig.class) -@Import({TokenIDGenerator.class, ValidateTokenUtil.class, CbeffImpl.class}) +@Import({TokenIDGenerator.class, ValidateTokenUtil.class, CbeffImpl.class, TransliterationService.class, TransliterationServiceUtil.class}) public class ResidentBootApplication { public static void main(String[] args) { diff --git a/resident/resident-service/src/main/java/io/mosip/resident/aspect/LoginCheck.java b/resident/resident-service/src/main/java/io/mosip/resident/aspect/LoginCheck.java index 021ea7fec5a..aa10f04559c 100644 --- a/resident/resident-service/src/main/java/io/mosip/resident/aspect/LoginCheck.java +++ b/resident/resident-service/src/main/java/io/mosip/resident/aspect/LoginCheck.java @@ -86,7 +86,7 @@ public void getUserDetails(String redirectURI, String state, String sessionState break; } } - + audit.setAuditRequestDto(EventEnum.LOGIN_REQ); if(idaToken!=null && !idaToken.isEmpty() && sessionId != null && !sessionId.isEmpty()) { audit.setAuditRequestDto(EventEnum.LOGIN_REQ_SUCCESS); ResidentSessionEntity newSessionData = new ResidentSessionEntity(sessionId, idaToken, DateUtils.getUTCCurrentDateTime(), diff --git a/resident/resident-service/src/main/java/io/mosip/resident/batch/CredentialStatusUpdateBatchJob.java b/resident/resident-service/src/main/java/io/mosip/resident/batch/CredentialStatusUpdateBatchJob.java index 0ac759d5311..9544eef8e7f 100644 --- a/resident/resident-service/src/main/java/io/mosip/resident/batch/CredentialStatusUpdateBatchJob.java +++ b/resident/resident-service/src/main/java/io/mosip/resident/batch/CredentialStatusUpdateBatchJob.java @@ -1,35 +1,12 @@ package io.mosip.resident.batch; import static io.mosip.resident.constant.EventStatusFailure.FAILED; -import static io.mosip.resident.constant.EventStatusInProgress.IN_TRANSIT; -import static io.mosip.resident.constant.EventStatusInProgress.ISSUED; -import static io.mosip.resident.constant.EventStatusInProgress.NEW; -import static io.mosip.resident.constant.EventStatusInProgress.PAYMENT_CONFIRMED; -import static io.mosip.resident.constant.EventStatusInProgress.PRINTING; -import static io.mosip.resident.constant.EventStatusSuccess.CARD_READY_TO_DOWNLOAD; -import static io.mosip.resident.constant.EventStatusSuccess.RECEIVED; -import static io.mosip.resident.constant.EventStatusSuccess.STORED; -import static io.mosip.resident.constant.RequestType.ORDER_PHYSICAL_CARD; -import static io.mosip.resident.constant.RequestType.SHARE_CRED_WITH_PARTNER; -import static io.mosip.resident.constant.RequestType.UPDATE_MY_UIN; -import static io.mosip.resident.constant.RequestType.VID_CARD_DOWNLOAD; import static io.mosip.resident.constant.ResidentConstants.CREDENTIAL_UPDATE_STATUS_UPDATE_INITIAL_DELAY; import static io.mosip.resident.constant.ResidentConstants.CREDENTIAL_UPDATE_STATUS_UPDATE_INITIAL_DELAY_DEFAULT; import static io.mosip.resident.constant.ResidentConstants.CREDENTIAL_UPDATE_STATUS_UPDATE_INTERVAL; import static io.mosip.resident.constant.ResidentConstants.CREDENTIAL_UPDATE_STATUS_UPDATE_INTERVAL_DEFAULT; import static io.mosip.resident.constant.ResidentConstants.IS_CREDENTIAL_STATUS_UPDATE_JOB_ENABLED; -import static io.mosip.resident.constant.ResidentConstants.NOTIFICATION_DATE_PATTERN; -import static io.mosip.resident.constant.ResidentConstants.NOTIFICATION_TIME_PATTERN; -import static io.mosip.resident.constant.ResidentConstants.NOTIFICATION_ZONE; -import static io.mosip.resident.constant.ResidentConstants.PUBLIC_URL; -import static io.mosip.resident.constant.ResidentConstants.RESIDENT; -import static io.mosip.resident.constant.ResidentConstants.STATUS_CODE; -import static io.mosip.resident.constant.ResidentConstants.URL; -import java.time.LocalDateTime; -import java.time.ZoneId; -import java.time.ZonedDateTime; -import java.time.format.DateTimeFormatter; import java.util.Collections; import java.util.List; import java.util.Map; @@ -39,101 +16,69 @@ import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.core.env.Environment; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import com.fasterxml.jackson.core.type.TypeReference; +import io.mosip.kernel.core.exception.ServiceError; import io.mosip.kernel.core.http.ResponseWrapper; import io.mosip.kernel.core.logger.spi.Logger; -import io.mosip.kernel.core.util.DateUtils; import io.mosip.resident.config.LoggerConfiguration; import io.mosip.resident.constant.ApiName; import io.mosip.resident.constant.RequestType; import io.mosip.resident.constant.ResidentErrorCode; -import io.mosip.resident.constant.TemplateType; -import io.mosip.resident.constant.TemplateVariablesConstants; -import io.mosip.resident.dto.NotificationRequestDtoV2; import io.mosip.resident.entity.ResidentTransactionEntity; import io.mosip.resident.exception.ApisResourceAccessException; import io.mosip.resident.exception.IdRepoAppException; import io.mosip.resident.exception.ResidentServiceCheckedException; import io.mosip.resident.exception.ResidentServiceException; import io.mosip.resident.function.RunnableWithException; +import io.mosip.resident.helper.CredentialStatusUpdateHelper; import io.mosip.resident.repository.ResidentTransactionRepository; -import io.mosip.resident.service.IdentityService; -import io.mosip.resident.service.NotificationService; -import io.mosip.resident.service.ResidentService; import io.mosip.resident.util.JsonUtil; import io.mosip.resident.util.ResidentServiceRestClient; -import reactor.util.function.Tuple2; -import reactor.util.function.Tuples; /** * @author Manoj SP + * @author Loganathan S * */ @Component -//@Transactional @ConditionalOnProperty(name = IS_CREDENTIAL_STATUS_UPDATE_JOB_ENABLED, havingValue = "true", matchIfMissing = true) public class CredentialStatusUpdateBatchJob { - private static final String DEFAULT_NOTIF_TIME_PATTERN = "HH:mm:ss"; - - private static final String DEFAULT_NOTIF_DATE_PATTERN = "dd-MM-yyyy"; - - @Value("${" + PUBLIC_URL + "}") - private String publicUrl; - - @Value("${" + NOTIFICATION_ZONE + "}") - private String notificationZone; - - @Value("${" + NOTIFICATION_DATE_PATTERN + ":" + DEFAULT_NOTIF_DATE_PATTERN + "}") - private String notificationDatePattern; - - @Value("${" + NOTIFICATION_TIME_PATTERN + ":" + DEFAULT_NOTIF_TIME_PATTERN + "}") - private String notificationTimePattern; - private final Logger logger = LoggerConfiguration.logConfig(CredentialStatusUpdateBatchJob.class); + @Autowired private ResidentTransactionRepository repo; - - @Autowired - @Qualifier("restClientWithSelfTOkenRestTemplate") - private ResidentServiceRestClient residentServiceRestClient; - + + @Value("#{'${resident.async.request.types}'.split(',')}") + private List requestTypeCodesToProcessInBatchJob; + @Autowired - private NotificationService notificationService; - + private CredentialStatusUpdateHelper credentialStatusUpdateHelper; + @Autowired - private ResidentService residentService; - + private Environment env; + @Autowired - private IdentityService identityService; - - @Value("${resident.batchjob.process.status.list}") - private String statusCodes; - - @Value("${resident.async.request.types}") - private String requestTypeCodes; + @Qualifier("restClientWithSelfTOkenRestTemplate") + private ResidentServiceRestClient residentServiceRestClient; private void handleWithTryCatch(RunnableWithException runnableWithException) { try { runnableWithException.run(); - } catch (ApisResourceAccessException e) { - logErrorForBatchJob(e); - } catch (ResidentServiceCheckedException e) { - logErrorForBatchJob(e); - } catch (ResidentServiceException e) { - logErrorForBatchJob(e); - } catch (IdRepoAppException e) { + } catch (ApisResourceAccessException | ResidentServiceCheckedException | ResidentServiceException | + IdRepoAppException e) { logErrorForBatchJob(e); } } private void logErrorForBatchJob(Exception e) { - logger.error(String.format("Error in batch job: %s : %s : %s", e.getClass().getSimpleName(), e.getMessage(), + logger.debug(String.format("Error in batch job: %s : %s : %s", e.getClass().getSimpleName(), e.getMessage(), (e.getCause() != null ? "rootcause: " + e.getCause().getMessage() : ""))); } @@ -142,212 +87,61 @@ private void logErrorForBatchJob(Exception e) { + CREDENTIAL_UPDATE_STATUS_UPDATE_INTERVAL + ":" + CREDENTIAL_UPDATE_STATUS_UPDATE_INTERVAL_DEFAULT + "}") public void scheduleCredentialStatusUpdateJob() throws ResidentServiceCheckedException { - List residentTxnList = repo.findByStatusCodeInAndRequestTypeCodeInOrderByCrDtimesAsc( - List.of(statusCodes.split(",")), List.of(requestTypeCodes.split(","))); - logger.info("Total records picked from resident_transaction table for processing is " + residentTxnList.size()); + List residentTxnList = repo.findByStatusCodeInAndRequestTypeCodeInAndCredentialRequestIdIsNotNullOrderByCrDtimesAsc( + getStatusCodesToProcess(), requestTypeCodesToProcessInBatchJob); + logger.debug("Total records picked from resident_transaction table for processing is " + residentTxnList.size()); for (ResidentTransactionEntity txn : residentTxnList) { - logger.info("Processing event:" + txn.getEventId()); + logger.debug("Processing event:" + txn.getEventId()); if (txn.getIndividualId() == null) { txn.setStatusCode(FAILED.name()); txn.setStatusComment("individualId is null"); - repo.save(txn); + credentialStatusUpdateHelper.updateEntity(txn); + credentialStatusUpdateHelper.saveEntity(txn); + } else { + handleWithTryCatch(() -> updateTransactionStatus(txn)); } - handleWithTryCatch(() -> updateVidCardDownloadTxnStatus(txn)); - handleWithTryCatch(() -> updateOrderPhysicalCardTxnStatus(txn)); - handleWithTryCatch(() -> updateShareCredentialWithPartnerTxnStatus(txn)); - handleWithTryCatch(() -> updateUinDemoDataUpdateTxnStatus(txn)); } - repo.saveAll(residentTxnList); } - - private void updateVidCardDownloadTxnStatus(ResidentTransactionEntity txn) - throws ResidentServiceCheckedException, ApisResourceAccessException { - if (txn.getRequestTypeCode().contentEquals(VID_CARD_DOWNLOAD.name())) { - Map eventDetails = trackAndUpdateNewOrIssuedStatus(txn); - trackAnddownloadPrintingOrStoredStatus(txn, TemplateType.SUCCESS, RequestType.VID_CARD_DOWNLOAD, - eventDetails);// mentioned in sheet and in story also - trackAndUpdateFailedStatus(txn, TemplateType.FAILURE, RequestType.VID_CARD_DOWNLOAD); - } - } - - private void updateOrderPhysicalCardTxnStatus(ResidentTransactionEntity txn) - throws ResidentServiceCheckedException, ApisResourceAccessException { - if (txn.getRequestTypeCode().contentEquals(ORDER_PHYSICAL_CARD.name())) { - Map eventDetails = trackAndUpdateNewOrIssuedStatus(txn); - trackAndUpdatePaymentConfirmedStatus(txn); - trackAnddownloadPrintingOrIntransitStatus(txn, TemplateType.SUCCESS, RequestType.ORDER_PHYSICAL_CARD, - eventDetails); - trackAndUpdateFailedStatus(txn, TemplateType.FAILURE, RequestType.ORDER_PHYSICAL_CARD); - } - } - - private void updateShareCredentialWithPartnerTxnStatus(ResidentTransactionEntity txn) - throws ResidentServiceCheckedException, ApisResourceAccessException { - if (txn.getRequestTypeCode().contentEquals(SHARE_CRED_WITH_PARTNER.name())) { - Map eventDetails = trackAndUpdateNewOrIssuedStatus(txn); - trackAndUpdatePrintingOrStoredStatus(txn, TemplateType.SUCCESS, RequestType.SHARE_CRED_WITH_PARTNER); - trackAndUpdateFailedStatus(txn, TemplateType.FAILURE, RequestType.SHARE_CRED_WITH_PARTNER); - } - } - - private void updateUinDemoDataUpdateTxnStatus(ResidentTransactionEntity txn) - throws ResidentServiceCheckedException, ApisResourceAccessException { - if (txn.getRequestTypeCode().contentEquals(UPDATE_MY_UIN.name())) { - Map eventDetails = trackAndUpdateNewOrIssuedStatus(txn); - trackAndUpdatePrintingOrReceivedOrStoredStatus(txn, TemplateType.SUCCESS, RequestType.UPDATE_MY_UIN, eventDetails); - trackAndUpdateFailedStatus(txn, TemplateType.FAILURE, RequestType.UPDATE_MY_UIN); - } - } - - private Map trackAndUpdateNewOrIssuedStatus(ResidentTransactionEntity txn) + + public void updateTransactionStatus(ResidentTransactionEntity txn) throws ResidentServiceCheckedException, ApisResourceAccessException { - if (txn.getStatusCode().contentEquals(NEW.name()) || txn.getStatusCode().contentEquals(ISSUED.name())) { - if (txn.getCredentialRequestId() != null && !txn.getCredentialRequestId().isEmpty()) { - Map eventDetails = getCredentialEventDetails(txn.getCredentialRequestId()); - txn.setStatusCode(eventDetails.get(STATUS_CODE)); - txn.setReadStatus(false); - txn.setUpdBy(RESIDENT); - txn.setUpdDtimes(DateUtils.getUTCCurrentDateTime()); - repo.save(txn); - return eventDetails; + String requestTypeCode = txn.getRequestTypeCode(); + if (requestTypeCodesToProcessInBatchJob.contains(requestTypeCode)) { + RequestType requestType = RequestType.getRequestTypeFromString(requestTypeCode); + // If it is already a success / failed status, do not process it. + if (!requestType.isSuccessOrFailedStatus(env, txn.getStatusCode())) { + Map credentialStatus = getCredentialStatusForEntity(txn); + credentialStatusUpdateHelper.updateStatus(txn, credentialStatus); } } - return Map.of(); } - - private void trackAndUpdatePrintingOrReceivedOrStoredStatus(ResidentTransactionEntity txn, TemplateType templateType, - RequestType requestType, Map eventDetails) throws ResidentServiceCheckedException { - if (txn.getStatusCode().contentEquals(PRINTING.name()) || txn.getStatusCode().contentEquals(RECEIVED.name()) - || txn.getStatusCode().contentEquals(STORED.name())) { - txn.setStatusCode(CARD_READY_TO_DOWNLOAD.name()); - txn.setReadStatus(false); - createResidentDwldUrl(txn, templateType, requestType, eventDetails); - sendNotification(txn, templateType, requestType); - } + + public List getStatusCodesToProcess() { + return RequestType.getAllNewOrInprogressStatusList(env); } - - private void trackAnddownloadPrintingOrStoredStatus(ResidentTransactionEntity txn, TemplateType templateType, - RequestType requestType, Map eventDetails) throws ResidentServiceCheckedException { - if (txn.getStatusCode().contentEquals(PRINTING.name()) || txn.getStatusCode().contentEquals(STORED.name())) { - txn.setStatusCode(CARD_READY_TO_DOWNLOAD.name()); - txn.setReadStatus(false); - createResidentDwldUrl(txn, templateType, requestType, eventDetails); - sendNotification(txn, templateType, requestType); - } - } - - private void trackAnddownloadPrintingOrIntransitStatus(ResidentTransactionEntity txn, TemplateType templateType, - RequestType requestType, Map eventDetails) - throws ResidentServiceCheckedException, ApisResourceAccessException { - if (txn.getStatusCode().contentEquals(PRINTING.name()) || txn.getStatusCode().contentEquals(IN_TRANSIT.name()) - || txn.getStatusCode().contentEquals(STORED.name())) { - String trackingId = getTrackingId(txn.getRequestTrnId(), txn.getIndividualId()); - txn.setTrackingId(trackingId); - createResidentDwldUrl(txn, templateType, requestType, eventDetails); - sendNotification(txn, templateType, requestType); - } - } - - private void trackAndUpdatePrintingOrStoredStatus(ResidentTransactionEntity txn, TemplateType templateType, - RequestType requestType) throws ResidentServiceCheckedException { - if (txn.getStatusCode().contentEquals(PRINTING.name()) || txn.getStatusCode().contentEquals(STORED.name())) { - sendNotification(txn, templateType, requestType); - } - } - - private void trackAndUpdatePaymentConfirmedStatus(ResidentTransactionEntity txn) - throws ResidentServiceCheckedException, ApisResourceAccessException { - if (txn.getStatusCode().contentEquals(PAYMENT_CONFIRMED.name())) { - Map eventDetails = getCredentialEventDetails(txn.getCredentialRequestId()); - txn.setStatusCode(eventDetails.get(STATUS_CODE)); - txn.setReadStatus(false); - txn.setUpdBy(RESIDENT); - txn.setUpdDtimes(DateUtils.getUTCCurrentDateTime()); - } - } - - private void createResidentDwldUrl(ResidentTransactionEntity txn, TemplateType templateType, - RequestType requestType, Map eventDetails) throws ResidentServiceCheckedException { - txn.setReferenceLink(eventDetails.get(URL)); - txn.setUpdBy(RESIDENT); - txn.setUpdDtimes(DateUtils.getUTCCurrentDateTime()); - repo.save(txn); - } - - private void sendNotification(ResidentTransactionEntity txn, TemplateType templateType, RequestType requestType) - throws ResidentServiceCheckedException { - NotificationRequestDtoV2 notificationRequestDtoV2 = new NotificationRequestDtoV2(); - notificationRequestDtoV2.setTemplateType(templateType); - notificationRequestDtoV2.setRequestType(requestType); - notificationRequestDtoV2.setEventId(txn.getEventId()); - notificationRequestDtoV2.setId(txn.getIndividualId()); - notificationService.sendNotification(notificationRequestDtoV2); - } - - private void trackAndUpdateFailedStatus(ResidentTransactionEntity txn, TemplateType templateType, - RequestType requestType) throws ResidentServiceCheckedException, ApisResourceAccessException { - if (txn.getStatusCode().contentEquals(FAILED.name())) { - sendNotification(txn, templateType, requestType); - } - } - - private Map getCredentialEventDetails(String credentialRequestId) + + private Map getCredentialEventDetails(String credentialRequestId, ResidentTransactionEntity txn) throws ResidentServiceCheckedException, ApisResourceAccessException { Object object = residentServiceRestClient.getApi(ApiName.CREDENTIAL_STATUS_URL, List.of(credentialRequestId), Collections.emptyList(), Collections.emptyList(), ResponseWrapper.class); ResponseWrapper> responseWrapper = JsonUtil.convertValue(object, new TypeReference>>() { }); - if (Objects.nonNull(responseWrapper.getErrors()) && !responseWrapper.getErrors().isEmpty()) { - logger.error("CREDENTIAL_STATUS_URL returned error " + responseWrapper.getErrors()); + List errors = responseWrapper.getErrors(); + if (Objects.nonNull(errors) && !errors.isEmpty()) { + logger.debug("CREDENTIAL_STATUS_URL returned error " + errors); throw new ResidentServiceCheckedException(ResidentErrorCode.UNKNOWN_EXCEPTION); } return responseWrapper.getResponse(); } - private boolean isRecordAvailableInIdRepo(String individualId) throws ResidentServiceCheckedException { - try { - getNameForIndividualId(individualId); - } catch (ResidentServiceCheckedException e) { - logger.error("individualId not available in IDRepo"); - return false; - } - return true; - } - - private String getNameForIndividualId(String individualId) throws ResidentServiceCheckedException { - if (individualId == null) { - logger.error("individualId is null"); - throw new ResidentServiceCheckedException(ResidentErrorCode.UNKNOWN_EXCEPTION); - } - return identityService.getIdentity(individualId).getFullName(); - } - - private String getAIDStatusFromRegProc(String aid) { - return residentService.getRidStatus(aid).getRidStatus(); - } - - private Tuple2 getDateAndTime(LocalDateTime timestamp) { - ZonedDateTime dateTime = ZonedDateTime.of(timestamp, ZoneId.of("UTC")) - .withZoneSameInstant(ZoneId.of(notificationZone)); - String date = dateTime.format(DateTimeFormatter.ofPattern(notificationDatePattern)); - String time = dateTime.format(DateTimeFormatter.ofPattern(notificationTimePattern)); - return Tuples.of(date, time); - } - - private String getTrackingId(String transactionId, String individualId) + private Map getCredentialStatusForEntity(ResidentTransactionEntity txn) throws ResidentServiceCheckedException, ApisResourceAccessException { - Object object = residentServiceRestClient.getApi(ApiName.GET_ORDER_STATUS_URL, List.of(), - List.of(TemplateVariablesConstants.TRANSACTION_ID, TemplateVariablesConstants.INDIVIDUAL_ID), - List.of(transactionId, individualId), ResponseWrapper.class); - ResponseWrapper> responseWrapper = JsonUtil.convertValue(object, - new TypeReference>>() { - }); - if (Objects.nonNull(responseWrapper.getErrors()) && !responseWrapper.getErrors().isEmpty()) { - logger.error("ORDER_STATUS_URL returned error " + responseWrapper.getErrors()); - throw new ResidentServiceCheckedException(ResidentErrorCode.UNKNOWN_EXCEPTION); + if (txn.getCredentialRequestId() != null && !txn.getCredentialRequestId().isEmpty()) { + Map eventDetails = getCredentialEventDetails(txn.getCredentialRequestId(), txn); + return eventDetails; } - return responseWrapper.getResponse().get(TemplateVariablesConstants.TRACKING_ID); + return Map.of(); } } diff --git a/resident/resident-service/src/main/java/io/mosip/resident/config/ResidentFilterConfig.java b/resident/resident-service/src/main/java/io/mosip/resident/config/ResidentFilterConfig.java new file mode 100644 index 00000000000..631b38d91fe --- /dev/null +++ b/resident/resident-service/src/main/java/io/mosip/resident/config/ResidentFilterConfig.java @@ -0,0 +1,49 @@ +package io.mosip.resident.config; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.boot.web.servlet.FilterRegistrationBean; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import io.mosip.resident.filter.LoggingFilter; +import io.mosip.resident.filter.WebsubCallbackRequestDecoratorFilter; + +/** + * The configuration for adding filters. + * + * @author Loganathan S + */ + +@Configuration +public class ResidentFilterConfig { + + @Value("${resident.logging.filter.url.pattern:/*}") + private String loggingFilterUrlPattern; + + /** + * Gets the auth filter. + * + * @return the auth filter + */ + @Bean + @ConditionalOnProperty(value = "resident.logging.filter.enabled", havingValue = "true", matchIfMissing = false) + public FilterRegistrationBean getLoggingFilter(LoggingFilter loggingFilter) { + FilterRegistrationBean registrationBean = new FilterRegistrationBean<>(); + registrationBean.setFilter(loggingFilter); + registrationBean.addUrlPatterns(loggingFilterUrlPattern); + return registrationBean; + } + + @Bean + @ConditionalOnProperty(value = "resident.websub.request.decorator.filter.enabled", havingValue = "true", matchIfMissing = true) + public FilterRegistrationBean getWebsubCallbackRequestDecoratorFilter( + @Autowired(required = false) WebsubCallbackRequestDecoratorFilter loggingFilter) { + FilterRegistrationBean registrationBean = new FilterRegistrationBean<>(); + registrationBean.setFilter(loggingFilter); + registrationBean.addUrlPatterns("/callback/*"); + return registrationBean; + } + +} diff --git a/resident/resident-service/src/main/java/io/mosip/resident/constant/ApiName.java b/resident/resident-service/src/main/java/io/mosip/resident/constant/ApiName.java index 2a3505f4c7b..0c06aa2f94d 100644 --- a/resident/resident-service/src/main/java/io/mosip/resident/constant/ApiName.java +++ b/resident/resident-service/src/main/java/io/mosip/resident/constant/ApiName.java @@ -78,7 +78,7 @@ public enum ApiName { GET_ORDER_STATUS_URL, TEMPLATES_BY_LANGCODE_AND_TEMPLATETYPECODE_URL, IDREPO_IDENTITY_UPDATE_COUNT, - GENDER_TYPE_BY_LANGCODE, + DYNAMIC_FIELD_BASED_ON_LANG_CODE_AND_FIELD_NAME, GET_RID_BY_INDIVIDUAL_ID, PDFSIGN, PARTNER_DETAILS_NEW_URL, diff --git a/resident/resident-service/src/main/java/io/mosip/resident/constant/EventStatusFailure.java b/resident/resident-service/src/main/java/io/mosip/resident/constant/EventStatusFailure.java index d558096431c..56d7f83ca32 100644 --- a/resident/resident-service/src/main/java/io/mosip/resident/constant/EventStatusFailure.java +++ b/resident/resident-service/src/main/java/io/mosip/resident/constant/EventStatusFailure.java @@ -10,7 +10,8 @@ public enum EventStatusFailure { PAYMENT_FAILED, REJECTED, REPROCESS_FAILED, - OTP_VERIFICATION_FAILED; + OTP_VERIFICATION_FAILED, + N; public static boolean containsStatus(String status) { for (EventStatusFailure eventStatusFailure : EventStatusFailure.values()) { diff --git a/resident/resident-service/src/main/java/io/mosip/resident/constant/EventStatusSuccess.java b/resident/resident-service/src/main/java/io/mosip/resident/constant/EventStatusSuccess.java index 9780115aead..be6bd333792 100644 --- a/resident/resident-service/src/main/java/io/mosip/resident/constant/EventStatusSuccess.java +++ b/resident/resident-service/src/main/java/io/mosip/resident/constant/EventStatusSuccess.java @@ -5,7 +5,7 @@ @author Kamesh Shekhar Prasad */ public enum EventStatusSuccess { - AUTHENTICATION_SUCCESSFUL, + AUTHENTICATION_SUCCESSFULL, STORED, CARD_READY_TO_DOWNLOAD, CARD_DOWNLOADED, @@ -25,7 +25,8 @@ public enum EventStatusSuccess { OTP_VERIFIED, COMPLETED, AUTHENTICATION_TYPE_UPDATED, - PHYSICAL_CARD_ORDERED; + PHYSICAL_CARD_ORDERED, + Y; public static boolean containsStatus(String status) { for (EventStatusSuccess eventStatusSuccess : EventStatusSuccess.values()) { diff --git a/resident/resident-service/src/main/java/io/mosip/resident/constant/PacketStatus.java b/resident/resident-service/src/main/java/io/mosip/resident/constant/PacketStatus.java index 0d730747375..feee2023810 100644 --- a/resident/resident-service/src/main/java/io/mosip/resident/constant/PacketStatus.java +++ b/resident/resident-service/src/main/java/io/mosip/resident/constant/PacketStatus.java @@ -1,30 +1,50 @@ package io.mosip.resident.constant; import java.util.List; +import java.util.Optional; + +import org.springframework.core.env.Environment; /** -Enum to store the TransactionStage -@author Kamesh Shekhar Prasad + * Enum to store the TransactionStage + * + * @author Kamesh Shekhar Prasad */ public enum PacketStatus { - SUCCESS("SUCCESS", List.of("PROCESSED", "SUCCESS", "UIN_GENERATED")), - IN_PROGRESS("IN-PROGRESS", List.of("PROCESSING", "REREGISTER", "RESEND", "RECEIVED", "UPLOAD_PENDING", - "AWAITING_INFORMATION")), - FAILURE("FAILURE", List.of("REJECTED", "FAILURE", "REPROCESS_FAILED")); - private List listOfName; - private String name; - PacketStatus(String name, List listOfName) { - this.name = name; - this.listOfName = listOfName; - } - - public static String getStatusCode(String statusCode){ - for (PacketStatus packetStatus : values()) { - if(packetStatus.listOfName.contains(statusCode)){ - return packetStatus.name; - } - } - return ""; - } + SUCCESS("SUCCESS", "resident.success.packet-status-code.list"), + IN_PROGRESS("IN-PROGRESS", "resident.in-progress.packet-status-code.list"), + FAILURE("FAILURE", "resident.failure.packet-status-code.list"); + + private String name; + private String statusCodePropertyName; + + PacketStatus(String name, String statusCodePropertyName) { + this.name = name; + this.statusCodePropertyName = statusCodePropertyName; + } + + public String getName() { + return name; + } + + public static Optional getStatusCode(String statusCode, Environment env) { + for (PacketStatus packetStatus : values()) { + if (getStatusCodeList(packetStatus, env).contains(statusCode)) { + return Optional.of(packetStatus.name); + } + } + return Optional.empty(); + } + + private static List getStatusCodeList(PacketStatus packetStatus, Environment env) { + List statusCode = List.of(); + if (packetStatus.statusCodePropertyName != null) { + String propertyName = env.getProperty(packetStatus.statusCodePropertyName); + if (propertyName != null) { + statusCode = List.of(propertyName.split(",")); + } + } + return statusCode; + } } diff --git a/resident/resident-service/src/main/java/io/mosip/resident/constant/PreUpdateInBatchJob.java b/resident/resident-service/src/main/java/io/mosip/resident/constant/PreUpdateInBatchJob.java new file mode 100644 index 00000000000..9f1a8e91e5a --- /dev/null +++ b/resident/resident-service/src/main/java/io/mosip/resident/constant/PreUpdateInBatchJob.java @@ -0,0 +1,35 @@ +package io.mosip.resident.constant; + +import java.util.Map; + +import org.springframework.core.env.Environment; + +import io.mosip.resident.entity.ResidentTransactionEntity; +import io.mosip.resident.exception.ApisResourceAccessException; +import io.mosip.resident.exception.ResidentServiceCheckedException; +import io.mosip.resident.util.Utility; + +/** + * The interface for implementing logic to be invoked before updating the status in batch job + * + * @author Loganathan S + * + */ +public interface PreUpdateInBatchJob { + + /** + * Invoked before updating the status in the database and before sending notification + * + * @param env + * @param utility + * @param txn + * @param credentialStatus + * @param newStatusCode + * @throws ResidentServiceCheckedException + * @throws ApisResourceAccessException + */ + void preUpdateInBatchJob(Environment env, Utility utility, ResidentTransactionEntity txn, + Map credentialStatus, String newStatusCode) + throws ResidentServiceCheckedException, ApisResourceAccessException; + +} \ No newline at end of file diff --git a/resident/resident-service/src/main/java/io/mosip/resident/constant/RegistrationConstants.java b/resident/resident-service/src/main/java/io/mosip/resident/constant/RegistrationConstants.java index e6c409047d9..59585eea7e0 100644 --- a/resident/resident-service/src/main/java/io/mosip/resident/constant/RegistrationConstants.java +++ b/resident/resident-service/src/main/java/io/mosip/resident/constant/RegistrationConstants.java @@ -310,6 +310,7 @@ private RegistrationConstants() { // update UIN public static final String UIN_LABEL = "UIN"; + public static final String VID_LABEL = "VID"; public static final String FIRST_TOGGLE_LABEL = "toggleLabel1"; public static final String SECOND_TOGGLE_LABEL = "toggleLabel2"; public static final String PACKET_TYPE_UPDATE = "Update"; diff --git a/resident/resident-service/src/main/java/io/mosip/resident/constant/RequestType.java b/resident/resident-service/src/main/java/io/mosip/resident/constant/RequestType.java index fc5d0e5e2f5..51d4ef79959 100644 --- a/resident/resident-service/src/main/java/io/mosip/resident/constant/RequestType.java +++ b/resident/resident-service/src/main/java/io/mosip/resident/constant/RequestType.java @@ -1,13 +1,24 @@ package io.mosip.resident.constant; -import java.util.Collections; +import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.function.BiFunction; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import org.springframework.core.env.Environment; + +import io.mosip.kernel.core.logger.spi.Logger; +import io.mosip.resident.config.LoggerConfiguration; import io.mosip.resident.dto.NotificationTemplateVariableDTO; -import io.mosip.resident.function.QuadFunction; +import io.mosip.resident.entity.ResidentTransactionEntity; +import io.mosip.resident.exception.ApisResourceAccessException; +import io.mosip.resident.exception.ResidentServiceCheckedException; +import io.mosip.resident.function.FiveArgsFunction; +import io.mosip.resident.function.FourArgsFunction; import io.mosip.resident.util.TemplateUtil; +import io.mosip.resident.util.Utility; import reactor.util.function.Tuple2; /** @@ -16,115 +27,134 @@ * @author Kamesh Shekhar Prasad */ -public enum RequestType { +public enum RequestType implements PreUpdateInBatchJob { AUTHENTICATION_REQUEST("Authentication Request", TemplateUtil::getAckTemplateVariablesForAuthenticationRequest, - List.of(EventStatusSuccess.AUTHENTICATION_SUCCESSFUL), List.of(EventStatusFailure.AUTHENTICATION_FAILED), - List.of(), "", null, TemplateUtil::getDescriptionTemplateVariablesForAuthenticationRequest), + "", null, TemplateUtil::getDescriptionTemplateVariablesForAuthenticationRequest), SHARE_CRED_WITH_PARTNER("Share Credential With Partner", TemplateUtil::getAckTemplateVariablesForCredentialShare, - List.of(EventStatusSuccess.RECEIVED, EventStatusSuccess.DATA_SHARED_SUCCESSFULLY), - List.of(EventStatusFailure.FAILED), List.of(EventStatusInProgress.NEW, EventStatusInProgress.ISSUED), "share-cred-with-partner", TemplateUtil::getNotificationTemplateVariablesForShareCredentialWithPartner, TemplateUtil::getDescriptionTemplateVariablesForShareCredential, ResidentConstants.ACK_SHARE_CREDENTIAL_NAMING_CONVENTION_PROPERTY), DOWNLOAD_PERSONALIZED_CARD("Download Personalized Card", TemplateUtil::getAckTemplateVariablesForDownloadPersonalizedCard, - List.of(EventStatusSuccess.STORED, EventStatusSuccess.CARD_DOWNLOADED), List.of(EventStatusFailure.FAILED), - List.of(EventStatusInProgress.NEW, EventStatusInProgress.ISSUED), "cust-and-down-my-card", + "cust-and-down-my-card", TemplateUtil::getNotificationTemplateVariablesForDownloadPersonalizedCard, TemplateUtil::getDescriptionTemplateVariablesForDownloadPersonalizedCard, ResidentConstants.ACK_PERSONALIZED_CARD_NAMING_CONVENTION_PROPERTY), ORDER_PHYSICAL_CARD("Order a Physical Card", TemplateUtil::getAckTemplateVariablesForOrderPhysicalCard, - List.of(EventStatusSuccess.CARD_DELIVERED), - List.of(EventStatusFailure.FAILED, EventStatusFailure.PAYMENT_FAILED), - List.of(EventStatusInProgress.PAYMENT_CONFIRMED, EventStatusInProgress.NEW, EventStatusInProgress.ISSUED, - EventStatusInProgress.PRINTING, EventStatusInProgress.IN_TRANSIT), "order-a-physical-card", TemplateUtil::getNotificationTemplateVariablesForOrderPhysicalCard, TemplateUtil::getDescriptionTemplateVariablesForOrderPhysicalCard, - ResidentConstants.ACK_ORDER_PHYSICAL_CARD_NAMING_CONVENTION_PROPERTY), + ResidentConstants.ACK_ORDER_PHYSICAL_CARD_NAMING_CONVENTION_PROPERTY) { + @Override + public void preUpdateInBatchJob(Environment env, Utility utility, ResidentTransactionEntity txn, Map credentialStatus, + String newStatusCode) + throws ResidentServiceCheckedException, ApisResourceAccessException { + if (this.isSuccessStatus(env, newStatusCode)) { + String trackingId = utility.getCardOrderTrackingId(txn.getRequestTrnId(), txn.getIndividualId()); + txn.setTrackingId(trackingId); + } + } + + }, GET_MY_ID("Get UIN Card", TemplateUtil::getAckTemplateVariablesForGetMyId, - List.of(EventStatusSuccess.CARD_DOWNLOADED, EventStatusSuccess.OTP_VERIFIED), - List.of(EventStatusFailure.FAILED), List.of(EventStatusInProgress.NEW, EventStatusInProgress.OTP_REQUESTED), "get-my-uin-card", TemplateUtil::getNotificationTemplateVariablesForGetMyId, TemplateUtil::getDescriptionTemplateVariablesForGetMyId), - BOOK_AN_APPOINTMENT("Book An Appointment", TemplateUtil::getAckTemplateVariablesForBookAnAppointment, List.of(), - List.of(), List.of(), "", null, null), + BOOK_AN_APPOINTMENT("Book An Appointment", TemplateUtil::getAckTemplateVariablesForBookAnAppointment, "", null, null), UPDATE_MY_UIN("Update UIN Data", TemplateUtil::getAckTemplateVariablesForUpdateMyUin, - List.of(EventStatusSuccess.PROCESSED, EventStatusSuccess.DATA_UPDATED), - List.of(EventStatusFailure.FAILED, EventStatusFailure.REJECTED, EventStatusFailure.REPROCESS_FAILED), - List.of(EventStatusInProgress.NEW, EventStatusInProgress.PROCESSING, EventStatusInProgress.PAUSED, - EventStatusInProgress.RESUMABLE, EventStatusInProgress.REPROCESS, - EventStatusInProgress.PAUSED_FOR_ADDITIONAL_INFO), "update-demo-data", TemplateUtil::getNotificationTemplateVariablesForUpdateMyUin, TemplateUtil::getDescriptionTemplateVariablesForUpdateMyUin, - ResidentConstants.ACK_UPDATE_MY_DATA_NAMING_CONVENTION_PROPERTY), + ResidentConstants.ACK_UPDATE_MY_DATA_NAMING_CONVENTION_PROPERTY) { + @Override + public void preUpdateInBatchJob(Environment env, Utility utility, ResidentTransactionEntity txn, + Map credentialStatus, String newStatusCode) + throws ResidentServiceCheckedException, ApisResourceAccessException { + if (this.isSuccessStatus(env, newStatusCode)) { + txn.setStatusCode(EventStatusSuccess.CARD_READY_TO_DOWNLOAD.name()); + } + } + }, GENERATE_VID("Generate VID", TemplateUtil::getAckTemplateVariablesForGenerateVid, - List.of(EventStatusSuccess.VID_GENERATED), List.of(EventStatusFailure.FAILED), - List.of(EventStatusInProgress.NEW), "gen-or-revoke-vid", + "gen-or-revoke-vid", TemplateUtil::getNotificationTemplateVariablesForGenerateOrRevokeVid, TemplateUtil::getDescriptionTemplateVariablesForManageMyVid, ResidentConstants.ACK_MANAGE_MY_VID_NAMING_CONVENTION_PROPERTY), - REVOKE_VID("Revoke VID", TemplateUtil::getAckTemplateVariablesForRevokeVid, List.of(EventStatusSuccess.VID_REVOKED), - List.of(EventStatusFailure.FAILED), List.of(EventStatusInProgress.NEW), "gen-or-revoke-vid", + REVOKE_VID("Revoke VID", TemplateUtil::getAckTemplateVariablesForRevokeVid, "gen-or-revoke-vid", TemplateUtil::getNotificationTemplateVariablesForGenerateOrRevokeVid, TemplateUtil::getDescriptionTemplateVariablesForManageMyVid, ResidentConstants.ACK_MANAGE_MY_VID_NAMING_CONVENTION_PROPERTY), - AUTH_TYPE_LOCK_UNLOCK("Lock or/and Unlock Authentication Types", + AUTH_TYPE_LOCK_UNLOCK("Secure My ID", TemplateUtil::getAckTemplateVariablesForAuthTypeLockUnlock, - List.of(EventStatusSuccess.LOCKED, EventStatusSuccess.UNLOCKED, - EventStatusSuccess.AUTHENTICATION_TYPE_LOCKED, EventStatusSuccess.AUTHENTICATION_TYPE_UNLOCKED), - List.of(EventStatusFailure.FAILED), List.of(EventStatusInProgress.NEW), "lock-unlock-auth", + "lock-unlock-auth", TemplateUtil::getNotificationTemplateVariablesForAuthTypeLockUnlock, TemplateUtil::getDescriptionTemplateVariablesForSecureMyId, ResidentConstants.ACK_SECURE_MY_ID_NAMING_CONVENTION_PROPERTY), VID_CARD_DOWNLOAD("Download VID Card", TemplateUtil::getAckTemplateVariablesForVidCardDownload, - List.of(EventStatusSuccess.STORED, EventStatusSuccess.CARD_DOWNLOADED), List.of(EventStatusFailure.FAILED), - List.of(EventStatusInProgress.NEW, EventStatusInProgress.ISSUED), "vid-card-download", + "vid-card-download", TemplateUtil::getNotificationTemplateVariablesForVidCardDownload, - TemplateUtil::getDescriptionTemplateVariablesForVidCardDownload), + TemplateUtil::getDescriptionTemplateVariablesForVidCardDownload) { + @Override + public void preUpdateInBatchJob(Environment env, Utility utility, ResidentTransactionEntity txn, + Map credentialStatus, String newStatusCode) + throws ResidentServiceCheckedException, ApisResourceAccessException { + if (this.isSuccessStatus(env, newStatusCode)) { + txn.setStatusCode(EventStatusSuccess.CARD_READY_TO_DOWNLOAD.name()); + } + } + }, - SEND_OTP("Send OTP", TemplateUtil::getAckTemplateVariablesForSendOtp, List.of(), List.of(), List.of(), "send-otp", + SEND_OTP("Send OTP", TemplateUtil::getAckTemplateVariablesForSendOtp, "send-otp", TemplateUtil::getNotificationSendOtpVariables, null), - VALIDATE_OTP("Validate OTP", TemplateUtil::getAckTemplateVariablesForValidateOtp, - List.of(EventStatusSuccess.OTP_VERIFIED), List.of(EventStatusFailure.OTP_VERIFICATION_FAILED), - List.of(EventStatusInProgress.OTP_REQUESTED), "verify-my-phone-email", + VALIDATE_OTP("Verify My Phone/Email", TemplateUtil::getAckTemplateVariablesForValidateOtp, + "verify-my-phone-email", TemplateUtil::getNotificationCommonTemplateVariables, TemplateUtil::getDescriptionTemplateVariablesForValidateOtp), - DEFAULT("Default", TemplateUtil::getDefaultTemplateVariables, List.of(), List.of(), List.of(), "", + DEFAULT("Default", TemplateUtil::getDefaultTemplateVariables, "", TemplateUtil::getNotificationCommonTemplateVariables, null); - private QuadFunction, String>> ackTemplateVariablesFunction; - private List successStatusList; - private List failureStatusList; - private List inProgressStatusList; + private static final String PREFIX_RESIDENT_TEMPLATE_EMAIL_SUBJECT = "resident.template.email.subject.%s.%s"; + + private static final String PREFIX_RESIDENT_TEMPLATE_EMAIL_CONTENT = "resident.template.email.content.%s.%s"; + + private static final String PREFIX_RESIDENT_TEMPLATE_SMS = "resident.template.sms.%s.%s"; + + private static final String PREFIX_RESIDENT_TEMPLATE_BELL_ICON = "resident.template.bell-icon.%s.%s"; + + private static final String PREFIX_RESIDENT_TEMPLATE_PURPOSE = "resident.template.purpose.%s.%s"; + + private static final String PREFIX_RESIDENT_TEMPLATE_SUMMARY = "resident.template.summary.%s.%s"; + + private static final Logger logger = LoggerConfiguration.logConfig(RequestType.class); + + private static final String PREFIX_RESIDENT_REQUEST_NOTIFICATION_STATUS_LIST = "resident.request.notification.status.list."; + private static final String PREFIX_RESIDENT_REQUEST_FAILED_STATUS_LIST = "resident.request.failed.status.list."; + private static final String PREFIX_RESIDENT_REQUEST_SUCCESS_STATUS_LIST = "resident.request.success.status.list."; + private static final String PREFIX_RESIDENT_REQUEST_IN_PROGRESS_STATUS_LIST = "resident.request.in-progress.status.list."; + private static final String PREFIX_RESIDENT_REQUEST_NEW_STATUS_LIST = "resident.request.new.status.list."; + private static final String SEPARATOR = ","; + private FiveArgsFunction, String>> ackTemplateVariablesFunction; private String featureName; private BiFunction> notificationTemplateVariablesFunction; - private QuadFunction getDescriptionTemplateVariables; + private FourArgsFunction getDescriptionTemplateVariables; private String namingProperty; private String name; private RequestType(String name, - QuadFunction, String>> ackTemplateVariablesFunction, - List successStatusList, List failureStatusList, - List inProgressStatusList, String featureName, + FiveArgsFunction, String>> ackTemplateVariablesFunction, + String featureName, BiFunction> notificationTemplateVariablesFunction, - QuadFunction getDescriptionTemplateVariables) { - this(name, ackTemplateVariablesFunction, successStatusList, failureStatusList, inProgressStatusList, + FourArgsFunction getDescriptionTemplateVariables) { + this(name, ackTemplateVariablesFunction, featureName, notificationTemplateVariablesFunction, getDescriptionTemplateVariables, null); } private RequestType(String name, - QuadFunction, String>> ackTemplateVariablesFunction, - List successStatusList, List failureStatusList, - List inProgressStatusList, String featureName, + FiveArgsFunction, String>> ackTemplateVariablesFunction, + String featureName, BiFunction> notificationTemplateVariablesFunction, - QuadFunction getDescriptionTemplateVariables, + FourArgsFunction getDescriptionTemplateVariables, String namingProperty) { this.name = name; this.ackTemplateVariablesFunction = ackTemplateVariablesFunction; - this.successStatusList = Collections.unmodifiableList(successStatusList); - this.failureStatusList = Collections.unmodifiableList(failureStatusList); - this.inProgressStatusList = Collections.unmodifiableList(inProgressStatusList); this.featureName = featureName; this.notificationTemplateVariablesFunction = notificationTemplateVariablesFunction; this.getDescriptionTemplateVariables = getDescriptionTemplateVariables; @@ -148,17 +178,92 @@ public static RequestType getRequestTypeByName(String name) { } return RequestType.DEFAULT; } + + public Stream getNewStatusList(Environment env) { + return getStatusListFromProperty(env, PREFIX_RESIDENT_REQUEST_NEW_STATUS_LIST); + } + + public Stream getSuccessStatusList(Environment env) { + return getStatusListFromProperty(env, PREFIX_RESIDENT_REQUEST_SUCCESS_STATUS_LIST); + } + + public Stream getFailedStatusList(Environment env) { + return getStatusListFromProperty(env, PREFIX_RESIDENT_REQUEST_FAILED_STATUS_LIST); + } + + public Stream getInProgressStatusList(Environment env) { + return getStatusListFromProperty(env, PREFIX_RESIDENT_REQUEST_IN_PROGRESS_STATUS_LIST); + } + + public Stream getNotificationStatusList(Environment env) { + return getStatusListFromProperty(env, PREFIX_RESIDENT_REQUEST_NOTIFICATION_STATUS_LIST); + } + + public boolean isNewStatus(Environment env, String statusCode) { + return isStatusPresent(statusCode, getNewStatusList(env)); + } + + public boolean isSuccessStatus(Environment env, String statusCode) { + return isStatusPresent(statusCode, getSuccessStatusList(env)); + } + + public boolean isFailedStatus(Environment env, String statusCode) { + return isStatusPresent(statusCode, getFailedStatusList(env)); + } + + public boolean isSuccessOrFailedStatus(Environment env, String statusCode) { + return isSuccessStatus(env, statusCode) || isFailedStatus(env, statusCode); + } - public List getSuccessStatusList() { - return successStatusList; + public boolean isInProgressStatus(Environment env, String statusCode) { + return isStatusPresent(statusCode, getInProgressStatusList(env)); + } + + public boolean isNotificationStatus(Environment env, String statusCode) { + return isStatusPresent(statusCode, getNotificationStatusList(env)); + } + + private boolean isStatusPresent(String statusCode, Stream stream) { + return statusCode != null && stream.anyMatch(statusCode::equals); + } + + private Stream getStatusListFromProperty(Environment env, String propertyPrefix) { + String propertyName = propertyPrefix + this.name(); + String statusListStr = env.getProperty(propertyName); + if (statusListStr == null) { + logger.debug("missing property: " + propertyName); + return Stream.empty(); + } else { + return Arrays.stream(statusListStr.split(SEPARATOR)); + } + } + + public Stream getNewOrInprogressStatusList(Environment env) { + return Stream.concat(getNewStatusList(env), getInProgressStatusList(env)); + } + + public static List getAllNewOrInprogressStatusList(Environment env) { + return Stream.of(values()).flatMap(requestType -> { + return Stream.concat(requestType.getNewStatusList(env), requestType.getInProgressStatusList(env)); + }).filter(str -> !str.isEmpty()) + .distinct() + .collect(Collectors.toUnmodifiableList()); } - public List getFailureStatusList() { - return failureStatusList; + public static List getAllFailedStatusList(Environment env) { + return Stream.of(values()).flatMap(requestType -> { + return requestType.getFailedStatusList(env); + }).filter(str -> !str.isEmpty()) + .distinct() + .collect(Collectors.toUnmodifiableList()); } - public List getInProgressStatusList() { - return inProgressStatusList; + public static List getAllSuccessStatusList(Environment env) { + return Stream.of(values()).flatMap(requestType -> { + return requestType.getSuccessStatusList(env); + }).filter(str -> !str.isEmpty()) + .distinct() + .collect(Collectors.toUnmodifiableList()); } public String getFeatureName() { @@ -168,43 +273,51 @@ public String getFeatureName() { public String getName() { return name; } public String getEmailSubjectTemplateCodeProperty(TemplateType templateType) { - return "resident.template.email.subject." + templateType.getType() + "." + getFeatureName(); + return String.format(PREFIX_RESIDENT_TEMPLATE_EMAIL_SUBJECT, templateType.getType(), getFeatureName()); } public String getEmailContentTemplateCodeProperty(TemplateType templateType) { - return "resident.template.email.content." + templateType.getType() + "." + getFeatureName(); + return String.format(PREFIX_RESIDENT_TEMPLATE_EMAIL_CONTENT, templateType.getType(), getFeatureName()); } public String getSmsTemplateCodeProperty(TemplateType templateType) { - return "resident.template.sms." + templateType.getType() + "." + getFeatureName(); + return String.format(PREFIX_RESIDENT_TEMPLATE_SMS, templateType.getType(), getFeatureName()); } public String getBellIconTemplateCodeProperty(TemplateType templateType) { - return "resident.template.bell-icon." + templateType.getType() + "." + getFeatureName(); + return String.format(PREFIX_RESIDENT_TEMPLATE_BELL_ICON, templateType.getType(), getFeatureName()); } public String getPurposeTemplateCodeProperty(TemplateType templateType) { - return "resident.template.purpose." + templateType.getType() + "." + getFeatureName(); + return String.format(PREFIX_RESIDENT_TEMPLATE_PURPOSE, templateType.getType(), getFeatureName()); } public String getSummaryTemplateCodeProperty(TemplateType templateType) { - return "resident.template.summary." + templateType.getType() + "." + getFeatureName(); + return String.format(PREFIX_RESIDENT_TEMPLATE_SUMMARY, templateType.getType(), getFeatureName()); } - public Tuple2, String> getAckTemplateVariables(TemplateUtil templateUtil, String eventId, String languageCode, Integer timeZoneOffset) { - return ackTemplateVariablesFunction.apply(templateUtil, eventId, languageCode, timeZoneOffset); + public Tuple2, String> getAckTemplateVariables(TemplateUtil templateUtil, String eventId, String languageCode, Integer timeZoneOffset, String locale) { + return ackTemplateVariablesFunction.apply(templateUtil, eventId, languageCode, timeZoneOffset, locale); } public Map getNotificationTemplateVariables(TemplateUtil templateUtil, NotificationTemplateVariableDTO dto) { return notificationTemplateVariablesFunction.apply(templateUtil, dto); } - public String getDescriptionTemplateVariables(TemplateUtil templateUtil, String eventId, String fileText, String languageCode){ - return getDescriptionTemplateVariables.apply(templateUtil, eventId, fileText, languageCode); + public String getDescriptionTemplateVariables(TemplateUtil templateUtil, ResidentTransactionEntity residentTransactionEntity, String fileText, String languageCode){ + return getDescriptionTemplateVariables.apply(templateUtil, residentTransactionEntity, fileText, languageCode); } public String getNamingProperty() { return namingProperty; } + @Override + public void preUpdateInBatchJob(Environment env, Utility utility, ResidentTransactionEntity txn, + Map credentialStatus, String newStatusCode) + throws ResidentServiceCheckedException, ApisResourceAccessException { + //Default does nothing + } + + } \ No newline at end of file diff --git a/resident/resident-service/src/main/java/io/mosip/resident/constant/ResidentConstants.java b/resident/resident-service/src/main/java/io/mosip/resident/constant/ResidentConstants.java index 52167daffed..3bd7a39ebdc 100644 --- a/resident/resident-service/src/main/java/io/mosip/resident/constant/ResidentConstants.java +++ b/resident/resident-service/src/main/java/io/mosip/resident/constant/ResidentConstants.java @@ -28,6 +28,8 @@ private ResidentConstants() { public static final String SUBSCRIPTIONS_DELAY_ON_STARTUP = "subscriptions-delay-on-startup_millisecs"; + public static final String RESUBSCRIPTIONS_INTERVAL_SECS = "re-subscription-interval-in-seconds"; + public static final String CREDENTIAL_UPDATE_STATUS_UPDATE_INITIAL_DELAY = "mosip.resident.update.service.status.job.initial-delay"; public static final String CREDENTIAL_UPDATE_STATUS_UPDATE_INITIAL_DELAY_DEFAULT = "60000"; @@ -49,6 +51,7 @@ private ResidentConstants() { public static final String DOWNLOAD_CARD = "/download/card/"; public static final String STATUS_CODE = "statusCode"; + public static final String STATUS = "status"; public static final String URL = "url"; public static final String RESIDENT = "RESIDENT"; public static final String RESIDENT_SERVICES = "resident-services"; @@ -88,6 +91,8 @@ private ResidentConstants() { public static final String CREATE_PASSWORD_METHOD_NAME = "resident.create.password.method.name"; public static final String DOWNLOAD_PERSONALIZED_CARD_NAMING_CONVENTION_PROPERTY = "mosip.resident.download.personalized.card.naming.convention"; + + public static final String DOWNLOAD_CARD_NAMING_CONVENTION_PROPERTY = "mosip.resident.download.card.naming.convention"; public static final String IS_PASSWORD_FLAG_ENABLED = "mosip.digitalcard.pdf.password.enable.flag"; @@ -100,6 +105,7 @@ private ResidentConstants() { public static final String SERVICE_HISTORY_PROPERTY_TEMPLATE_TYPE_CODE = "mosip.resident.service.history.template.type.code"; public static final String PHOTO_ATTRIBUTE_NAME = "mosip.resident.photo.attribute.name"; public static final String APPLICANT_NAME_PROPERTY = "mosip.resident.applicant.name.property"; + public static final String AUTHENTICATION_MODE_PROPERTY = "mosip.resident.authentication.mode.property"; public static final String INDIVIDUALID_CLAIM_NAME = "mosip.resident.individual.id.claim.name"; public static final String MOSIP_CREDENTIAL_TYPE_PROPERTY="mosip.digital.card.credential.type"; @@ -128,9 +134,27 @@ private ResidentConstants() { public static final String DOWNLOAD_SERVICE_HISTORY_FILE_NAME_CONVENTION_PROPERTY = "mosip.resident.download.service.history.file.name.convention"; public static final String GRIEVANCE_REQUEST_ID = "mosip.resident.grievance.ticket.request.id"; public static final String GRIEVANCE_REQUEST_VERSION = "mosip.resident.grievance.ticket.request.version"; + public static final String DOWNLOAD_REG_CENTER_ID = "resident.download.reg.centers.list.id"; + public static final String DOWNLOAD_NEAREST_REG_CENTER_ID = "resident.download.nearest.reg.centers.id"; + public static final String DOWNLOAD_SUPPORTING_DOCS_ID = "resident.download.supporting.documents.id"; + public static final String SEND_CARD_ID = "resident.send.card.id"; + public static final String PINNED_EVENTID_ID = "resident.pinned.eventid.id"; + public static final String UNPINNED_EVENTID_ID = "resident.unpinned.eventid.id"; + public static final String AUTH_PROXY_PARTNERS_ID = "resident.auth.proxy.partners.id"; + public static final String AUTH_HISTORY_ID = "resident.authhistory.id"; + public static final String EVENTS_EVENTID_ID = "resident.events.eventid.id"; + public static final String UPDATE_UIN_ID = "resident.updateuin.id"; + public static final String NOTIFICATION_CLICK_ID = "resident.notification.click.id"; + public static final String NOTIFICATION_ID = "resident.notification.id"; + public static final String SERVICE_HISTORY_ID = "resident.service.history.id"; + public static final String PROFILE_ID = "resident.profile.id"; + public static final String CREDENTIAL_STORE_ID = "mosip.credential.store.id"; + public static final String GET_VIDS_ID = "resident.vids.id"; + public static final String TRANSLITERATE_ID = "mosip.resident.transliteration.transliterate.id"; + public static final String VERIFICATION_STATUS_ID = "resident.channel.verification.status.id"; public static final String NAME_FROM_PROFILE = "mosip.resident.name.token.claim-name"; - + public static final String UNKNOWN = "Unknown"; public static final String EMAIL_FROM_PROFILE = "mosip.resident.email.token.claim-email"; public static final String PHONE_FROM_PROFILE = "mosip.resident.phone.token.claim-phone"; @@ -149,15 +173,18 @@ private ResidentConstants() { public static final String ADDITIONAL_ATTRIBUTE_TO_FETCH = "resident.additional.identity.attribute.to.fetch"; public static final String COMMA = ","; public static final String COLON = ":"; + public static final String SEMI_COLON = ";"; + public static final String OPEN_PARENTHESIS = "("; + public static final String CLOSE_PARENTHESIS = ")"; public static final String FILE_TEXT = "fileText"; public static final String DOLLAR = "$"; public static final String AUTH_TYPE = "authType"; public static final String CHANNEL = "channel"; - - public static final String MASK_PREFIX = "masked_"; - public static final String MASK_PERPETUAL_VID = "masked_perpetualVID"; + public static final String ATTRIBUTE_LIST_DELIMITER = ","; + public static final String UI_ATTRIBUTE_DATA_DELIMITER = ", "; + public static final String AUTH_TYPE_LIST_DELIMITER = ", "; public static final String HTTP_STATUS_CODE = "httpStatusCode"; public static final String REQ_RES_ID = "reqResId"; @@ -177,8 +204,8 @@ private ResidentConstants() { public static final String ACTION_PERFORMED = "actionPerformed"; public static final String VID_TYPE = "vidType"; public static final String MASKED_VID = "*masked VID*"; - public static final String UI_DATE_TIME_PATTERN = "resident.ui.datetime.pattern"; - public static final String FILENAME_DATETIME_PATTERN = "resident.filename.datetime.pattern"; + public static final String UI_DATE_TIME_PATTERN_DEFAULT = "resident.ui.datetime.pattern.default"; + public static final String FILENAME_DATETIME_PATTERN_DEFAULT = "resident.filename.datetime.pattern.default"; public static final String NO_ID = "NO_ID"; public static final String NO_ID_TYPE = "NO_ID_TYPE"; @@ -234,4 +261,29 @@ private ResidentConstants() { public static final String VID = "vid"; public static final String NAME = "name"; public static final String ONLINE_VERIFICATION_PARTNER_ID = "ida.online-verification-partner-id"; + + public static final String RESIDENT_NOTIFICATIONS_DEFAULT_PAGE_SIZE = "resident.notifications.default.page.size"; + public static final String RESIDENT_SERVICE_HISTORY_DOWNLOAD_MAX_COUNT = "resident.service-history.download.max.count"; + public static final String RESIDENT_VIEW_HISTORY_DEFAULT_PAGE_SIZE = "resident.view-history.default.page.size"; + public static final String LANGUAGE = "language"; + public static final String VALUE = "value"; + + public static final String RESIDENT_REGISTRATION_CENTERS_DOWNLOAD_MAX_COUNT = "resident.registration-centers.download.max.count"; + + public static final String PREFERRED_LANG_PROPERTY = "resident.update.preferred.language.by.name"; + public static final String PREFERRED_LANGUAGE = "preferredLanguage"; + public static final String RESIDENT_ATTRIBUTE_NAMES_WITHOUT_DOCUMENTS_REQUIRED = "resident.attribute.names.without.documents.required"; + +// UI Schema keys + public static final String FORMAT_REQUIRED = "formatRequired"; + public static final String ATTRIBUTE_NAME = "attributeName"; + public static final String FORMAT_OPTION = "formatOption"; + public static final String LABEL = "label"; + public static final String MASK_REQUIRED = "maskRequired"; + public static final String MASK_ATTRIBUTE_NAME = "maskAttributeName"; + public static final String MASK_PREFIX = "masked_"; + public static final String MASK_PERPETUAL_VID = "masked_perpetualVID"; + public static final String RESIDENT_FUTURE_TIME_LIMIT = "resident.future.time.limit"; + public static final String RESIDENT_PAST_TIME_LIMIT = "resident.past.time.limit"; + } diff --git a/resident/resident-service/src/main/java/io/mosip/resident/constant/ResidentErrorCode.java b/resident/resident-service/src/main/java/io/mosip/resident/constant/ResidentErrorCode.java index f4b458ad60e..ff9c2070f3a 100644 --- a/resident/resident-service/src/main/java/io/mosip/resident/constant/ResidentErrorCode.java +++ b/resident/resident-service/src/main/java/io/mosip/resident/constant/ResidentErrorCode.java @@ -55,7 +55,7 @@ public enum ResidentErrorCode { AUTH_LOCK_STATUS_FAILED("RES-SER-442", "Failed to retrieve auth lock status"), AUTH_TYPE_CALLBACK_NOT_AVAILABLE("RES-SER-443", "Callback url is not available for auth type: %s"), - RESIDENT_WEBSUB_UPDATE_AUTH_TYPE_FAILED("RES-SER-444", "Failed to update auth type for resident websub"), + RESIDENT_WEBSUB_UPDATE_AUTH_TYPE_FAILED("RES-SER-444", "Failed to update auth type status for resident"), RESIDENT_AUTH_TXN_DETAILS_FAILURE("RES-SER-445", "Failed to retrieve auth transaction details"), INVALID_PAGE_START_VALUE("RES-SER-446", "Invalid page start value"), @@ -127,7 +127,12 @@ public enum ResidentErrorCode { CONTAINS_SPECIAL_CHAR("RES-SER-515","Input text contains special characters;inputType=%s"), UN_SUPPORTED_FILE_TYPE("RES-SER-516", "Unsupported file type. Supported file extensions: jpg, jpeg, png, pdf"), UNABLE_TO_FETCH_SERVICE_HISTORY_FROM_DB("RES-SER-517", "Unable to fetch service history from database."), - INVALID_REG_CENTER_NAME("RES-SER-518", "Name cannot be empty as it is a mandatory field."); + INVALID_REG_CENTER_NAME("RES-SER-518", "Name cannot be empty as it is a mandatory field."), + SAME_EMAIL_ERROR("RES-SER-519", "Enter a new email ID"), + SAME_PHONE_ERROR("RES-SER-520", "Enter a new phone number"), + INVALID_LANGUAGE_NAME("RES-SER-521", "Invalid Language Name" ), + INVALID_UIN_VID_ENTERED("RES-SER-522", "Invalid UIN/VID entered"), + FORBIDDEN("RES-SER-403","Access is denied"); diff --git a/resident/resident-service/src/main/java/io/mosip/resident/constant/ServiceType.java b/resident/resident-service/src/main/java/io/mosip/resident/constant/ServiceType.java index d74ac60500a..48487639af5 100644 --- a/resident/resident-service/src/main/java/io/mosip/resident/constant/ServiceType.java +++ b/resident/resident-service/src/main/java/io/mosip/resident/constant/ServiceType.java @@ -3,6 +3,8 @@ import java.util.Collections; import java.util.List; import java.util.Optional; +import java.util.stream.Collectors; +import java.util.stream.Stream; /** * The Enum ServiceType. @@ -10,26 +12,35 @@ */ public enum ServiceType { - AUTHENTICATION_REQUEST(List.of(RequestType.AUTHENTICATION_REQUEST, RequestType.VALIDATE_OTP)), + AUTHENTICATION_REQUEST(List.of(RequestType.AUTHENTICATION_REQUEST)), SERVICE_REQUEST(List.of(RequestType.DOWNLOAD_PERSONALIZED_CARD, RequestType.ORDER_PHYSICAL_CARD, RequestType.GET_MY_ID, RequestType.BOOK_AN_APPOINTMENT, RequestType.VID_CARD_DOWNLOAD)), DATA_UPDATE_REQUEST(List.of(RequestType.UPDATE_MY_UIN)), ID_MANAGEMENT_REQUEST(List.of(RequestType.GENERATE_VID, RequestType.REVOKE_VID, RequestType.VALIDATE_OTP, RequestType.AUTH_TYPE_LOCK_UNLOCK)), DATA_SHARE_REQUEST(List.of(RequestType.SHARE_CRED_WITH_PARTNER)), - ASYNC(List.of(RequestType.VID_CARD_DOWNLOAD,RequestType.ORDER_PHYSICAL_CARD,RequestType.SHARE_CRED_WITH_PARTNER,RequestType.UPDATE_MY_UIN)), - ALL(List.of(RequestType.VALIDATE_OTP, RequestType.DOWNLOAD_PERSONALIZED_CARD, RequestType.ORDER_PHYSICAL_CARD, - RequestType.GET_MY_ID, RequestType.BOOK_AN_APPOINTMENT, RequestType.VID_CARD_DOWNLOAD, RequestType.UPDATE_MY_UIN, - RequestType.GENERATE_VID, RequestType.REVOKE_VID, RequestType.AUTH_TYPE_LOCK_UNLOCK, - RequestType.SHARE_CRED_WITH_PARTNER)); + ASYNC(List.of(RequestType.VID_CARD_DOWNLOAD, RequestType.ORDER_PHYSICAL_CARD, RequestType.SHARE_CRED_WITH_PARTNER, + RequestType.UPDATE_MY_UIN, RequestType.AUTH_TYPE_LOCK_UNLOCK)), + ALL() { + public List getRequestTypes() { + return Stream.of(ServiceType.values()) + .filter(type -> !type.equals(this)) + .flatMap(type -> type.getRequestTypes().stream()) + .distinct() + .collect(Collectors.toList()); + } + }; private List subTypes; + + ServiceType() { + } ServiceType(List subTypes) { this.subTypes = Collections.unmodifiableList(subTypes); } - public List getRequestType() { + public List getRequestTypes() { return subTypes; } @@ -44,7 +55,7 @@ public static Optional getServiceTypeFromString(String serviceTypeS public static Optional getServiceTypeFromRequestType(RequestType requestType) { for (ServiceType serviceType : values()) { - List requestTypesList = serviceType.getRequestType(); + List requestTypesList = serviceType.getRequestTypes(); if (requestTypesList.contains(requestType)) { return Optional.of(serviceType.name()); } diff --git a/resident/resident-service/src/main/java/io/mosip/resident/constant/TemplateType.java b/resident/resident-service/src/main/java/io/mosip/resident/constant/TemplateType.java index e773db7e679..0bd89f83c39 100644 --- a/resident/resident-service/src/main/java/io/mosip/resident/constant/TemplateType.java +++ b/resident/resident-service/src/main/java/io/mosip/resident/constant/TemplateType.java @@ -3,6 +3,7 @@ public enum TemplateType { REQUEST_RECEIVED("request-received"), + IN_PROGRESS("in-progress"), SUCCESS("success"), FAILURE("failure"); diff --git a/resident/resident-service/src/main/java/io/mosip/resident/constant/TemplateVariablesConstants.java b/resident/resident-service/src/main/java/io/mosip/resident/constant/TemplateVariablesConstants.java index da8baeb2098..d6eeb5687c1 100644 --- a/resident/resident-service/src/main/java/io/mosip/resident/constant/TemplateVariablesConstants.java +++ b/resident/resident-service/src/main/java/io/mosip/resident/constant/TemplateVariablesConstants.java @@ -6,6 +6,7 @@ */ public class TemplateVariablesConstants { public static final String EVENT_ID = "eventId"; + public static final String ID = "id"; public static final String FEATURE_NAME = "featureName"; public static final String EVENT_TYPE = "eventType"; public static final String PURPOSE = "purpose"; @@ -16,6 +17,7 @@ public class TemplateVariablesConstants { public static final String SUMMARY = "summary"; public static final String TRACKING_ID = "trackingId"; public static final String ORDER_TRACKING_LINK = "orderTrackingLink"; + public static final String PARTNER_ID = "partner"; public static final String PARTNER_NAME = "partnerName"; public static final String PARTNER_LOGO = "partnerLogo"; public static final String ATTRIBUTE_LIST = "attributeList"; @@ -30,7 +32,6 @@ public class TemplateVariablesConstants { public static final String NAME = "name"; public static final String STATUS = "status"; public static final String TRACK_SERVICE_REQUEST_LINK = "trackServiceRequestLink"; - public static final String TRACK_SERVICE_LINK = "trackServiceLink"; public static final String DOWNLOAD_LINK = "downloadLink"; public static final String TRANSACTION_ID = "transactionId"; public static final String OTP = "otp"; diff --git a/resident/resident-service/src/main/java/io/mosip/resident/constant/TransactionStage.java b/resident/resident-service/src/main/java/io/mosip/resident/constant/TransactionStage.java index 02a27b65f60..328745ec732 100644 --- a/resident/resident-service/src/main/java/io/mosip/resident/constant/TransactionStage.java +++ b/resident/resident-service/src/main/java/io/mosip/resident/constant/TransactionStage.java @@ -1,46 +1,54 @@ package io.mosip.resident.constant; import java.util.List; +import java.util.Optional; + +import org.springframework.core.env.Environment; /** -Enum to store the TransactionStage -@author Kamesh Shekhar Prasad + * Enum to store the TransactionStage + * + * @author Kamesh Shekhar Prasad */ public enum TransactionStage { - REQUEST_RECEIVED("Request received", List.of("PACKET_RECEIVER", "UPLOAD_PACKET", "VALIDATE_PACKET", "PACKET_CLASSIFICATION")), - VALIDATION_STAGE("Validation stage", List.of("CMD_VALIDATION", "OPERATOR_VALIDATION", "SUPERVISOR_VALIDATION", - "INTRODUCER_VALIDATION", "EXTERNAL_INTEGRATION")), - VERIFICATION_STAGE("Verification stage", List.of("DEMOGRAPHIC_VERIFICATION", "MANUAL_ADJUDICATION", - "VERIFICATION", "BIOGRAPHIC_VERIFICATION")), - UIN_GENERATION_STAGE("UIN generation stage", List.of("UIN_GENERATOR", "BIOMETRIC_EXTRACTION", "NOTIFICATION")), - CARD_READY_TO_DOWNLOAD("Card ready to download", List.of("PRINT_SERVICE", "PRINT_POSTAL_SERVICE", "PRINT")); - private List listOfName; - private String name; - TransactionStage(String name, List listOfName) { - this.name = name; - this.listOfName = listOfName; - } - - public String getName() { - return name; - } - - public static String getTypeCode(String transactionTypeCode){ - for (TransactionStage transactionStage : values()) { - if(transactionStage.listOfName.contains(transactionTypeCode)){ - return transactionStage.name; - } - } - return ""; - } - - public static boolean containsStatus(String status) { - for (TransactionStage transactionStage : - TransactionStage.values()) { - if (transactionStage.name().equals(status)) { - return true; - } - } - return false; - } + REQUEST_RECEIVED("resident.REQUEST_RECEIVED.packet-transaction-type-code.list"), + VALIDATION_STAGE("resident.VALIDATION_STAGE.packet-transaction-type-code.list"), + VERIFICATION_STAGE("resident.VERIFICATION_STAGE.packet-transaction-type-code.list"), + UIN_GENERATION_STAGE("resident.UIN_GENERATION_STAGE.packet-transaction-type-code.list"), + CARD_READY_TO_DOWNLOAD("resident.CARD_READY_TO_DOWNLOAD.packet-transaction-type-code.list"); + + private String transactionTypeCodePropertyName; + + TransactionStage(String transactionTypeCodePropertyName) { + this.transactionTypeCodePropertyName = transactionTypeCodePropertyName; + } + + public static Optional getTypeCode(String transactionTypeCode, Environment env) { + for (TransactionStage transactionStage : values()) { + if (getTransactionTypeCodeList(transactionStage, env).contains(transactionTypeCode)) { + return Optional.of(transactionStage.name()); + } + } + return Optional.empty(); + } + + private static List getTransactionTypeCodeList(TransactionStage transactionStage, Environment env) { + List transactionTypeCode = List.of(); + if (transactionStage.transactionTypeCodePropertyName != null) { + String propertyName = env.getProperty(transactionStage.transactionTypeCodePropertyName); + if (propertyName != null) { + transactionTypeCode = List.of(propertyName.split(",")); + } + } + return transactionTypeCode; + } + + public static boolean containsStatus(String status) { + for (TransactionStage transactionStage : TransactionStage.values()) { + if (transactionStage.name().equals(status)) { + return true; + } + } + return false; + } } diff --git a/resident/resident-service/src/main/java/io/mosip/resident/constant/UISchemaTypes.java b/resident/resident-service/src/main/java/io/mosip/resident/constant/UISchemaTypes.java new file mode 100644 index 00000000000..c89f681daea --- /dev/null +++ b/resident/resident-service/src/main/java/io/mosip/resident/constant/UISchemaTypes.java @@ -0,0 +1,54 @@ +package io.mosip.resident.constant; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +public enum UISchemaTypes { + UPDATE_DEMOGRAPHICS("update-demographics", RequestType.UPDATE_MY_UIN), + PERSONALIZED_CARD("personalized-card", RequestType.DOWNLOAD_PERSONALIZED_CARD), + SHARE_CREDENTIAL("share-credential", RequestType.SHARE_CRED_WITH_PARTNER); + ; + + private String fileIdentifier; + private RequestType requestType; + + private UISchemaTypes(String fileIdentifier, RequestType requestType) { + this.fileIdentifier = fileIdentifier; + this.requestType = requestType; + } + + public String getFileIdentifier() { + return fileIdentifier; + } + + public RequestType getRequestType() { + return requestType; + } + + public static Optional getUISchemaTypeFromString(String schemaTypeString) { + for (UISchemaTypes uiSchemaType : values()) { + if (uiSchemaType.getFileIdentifier().equals(schemaTypeString)) { + return Optional.of(uiSchemaType); + } + } + return Optional.empty(); + } + + public static Optional getUISchemaTypeFromRequestTypeCode(RequestType requestType) { + for (UISchemaTypes uiSchemaType : values()) { + if (uiSchemaType.getRequestType().name().equals(requestType.name())) { + return Optional.of(uiSchemaType.getFileIdentifier()); + } + } + return Optional.empty(); + } + + public static List getUISchemaTypesList() { + List uiSchemaValues = new ArrayList<>(); + for (UISchemaTypes uiSchemaType : values()) { + uiSchemaValues.add(uiSchemaType.getFileIdentifier()); + } + return uiSchemaValues; + } +} diff --git a/resident/resident-service/src/main/java/io/mosip/resident/controller/AcknowledgementController.java b/resident/resident-service/src/main/java/io/mosip/resident/controller/AcknowledgementController.java index 545264a4aa3..e7060c1cac8 100644 --- a/resident/resident-service/src/main/java/io/mosip/resident/controller/AcknowledgementController.java +++ b/resident/resident-service/src/main/java/io/mosip/resident/controller/AcknowledgementController.java @@ -65,7 +65,8 @@ public class AcknowledgementController { @GetMapping("/ack/download/pdf/event/{eventId}/language/{languageCode}") public ResponseEntity getAcknowledgement(@PathVariable("eventId") String eventId, @PathVariable("languageCode") String languageCode, - @RequestHeader(name = "time-zone-offset", required = false, defaultValue = "0") int timeZoneOffset) throws ResidentServiceCheckedException, IOException { + @RequestHeader(name = "time-zone-offset", required = false, defaultValue = "0") int timeZoneOffset, + @RequestHeader(name = "locale", required = false) String locale) throws ResidentServiceCheckedException, IOException { logger.debug("AcknowledgementController::acknowledgement()::entry"); InputStreamResource resource = null; String featureName = null; @@ -78,11 +79,11 @@ public ResponseEntity getAcknowledgement(@PathVariable("eventId") String } try { auditUtil.setAuditRequestDto(EventEnum.getEventEnumWithValue(EventEnum.GET_ACKNOWLEDGEMENT_DOWNLOAD_URL, "acknowledgement")); - byte[] pdfBytes = acknowledgementService.getAcknowledgementPDF(eventId, languageCode, timeZoneOffset); + byte[] pdfBytes = acknowledgementService.getAcknowledgementPDF(eventId, languageCode, timeZoneOffset, locale); resource = new InputStreamResource(new ByteArrayInputStream(pdfBytes)); auditUtil.setAuditRequestDto(EventEnum.GET_ACKNOWLEDGEMENT_DOWNLOAD_URL_SUCCESS); logger.debug("AcknowledgementController::acknowledgement()::exit"); - featureName = templateUtil.getFeatureName(eventId); + featureName = templateUtil.getFeatureName(eventId, locale); } catch(ResidentServiceCheckedException e) { auditUtil.setAuditRequestDto(EventEnum.GET_ACKNOWLEDGEMENT_DOWNLOAD_URL_FAILURE); logger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), @@ -93,7 +94,7 @@ public ResponseEntity getAcknowledgement(@PathVariable("eventId") String } return ResponseEntity.ok().contentType(MediaType.APPLICATION_PDF) .header("Content-Disposition", "attachment; filename=\"" + - utility.getFileNameAsPerFeatureName(eventId, featureName, timeZoneOffset) + ".pdf\"") + utility.getFileNameAsPerFeatureName(eventId, featureName, timeZoneOffset, locale) + ".pdf\"") .body(resource); } } diff --git a/resident/resident-service/src/main/java/io/mosip/resident/controller/AuthTransactionCallbackController.java b/resident/resident-service/src/main/java/io/mosip/resident/controller/AuthTransactionCallbackController.java index a835e3a7722..4aa5dc8c4bb 100644 --- a/resident/resident-service/src/main/java/io/mosip/resident/controller/AuthTransactionCallbackController.java +++ b/resident/resident-service/src/main/java/io/mosip/resident/controller/AuthTransactionCallbackController.java @@ -1,6 +1,7 @@ package io.mosip.resident.controller; import java.security.NoSuchAlgorithmException; +import java.util.Map; import org.apache.commons.lang3.exception.ExceptionUtils; import org.springframework.beans.factory.annotation.Autowired; @@ -9,7 +10,6 @@ import org.springframework.web.bind.annotation.RestController; import io.mosip.kernel.core.logger.spi.Logger; -import io.mosip.kernel.core.websub.model.EventModel; import io.mosip.kernel.core.websub.spi.SubscriptionClient; import io.mosip.kernel.websub.api.annotation.PreAuthenticateContentAndVerifyIntent; import io.mosip.kernel.websub.api.model.SubscriptionChangeRequest; @@ -57,30 +57,29 @@ public class AuthTransactionCallbackController { @ApiResponse(responseCode = "404", description = "Not Found", content = @Content(schema = @Schema(hidden = true)))}) @PreAuthenticateContentAndVerifyIntent(secret = "${resident.websub.authTransaction-status.secret}", callback = "${resident.websub.callback.authTransaction-status.relative.url}", topic = "${resident.websub.authTransaction-status.topic}") - public void authTypeCallback(@RequestBody EventModel eventModel) throws ApisResourceAccessException, NoSuchAlgorithmException { + public void authTransactionCallback(@RequestBody Map eventModel) + throws ApisResourceAccessException, NoSuchAlgorithmException { - logger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), - LoggerFileConstant.APPLICATIONID.toString(), "AuthTransactionCallbackController :: authTransactionCallback() :: Start"); + logger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), + LoggerFileConstant.APPLICATIONID.toString(), + "AuthTransactionCallbackController :: authTransactionCallback() :: Start"); - if(eventModel.getEvent() != null && eventModel.getEvent().getData() != null) { - logger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), - LoggerFileConstant.APPLICATIONID.toString(), "AuthTransactionCallbackController :: authTransactionCallback() :: Start"); - try { - logger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), - LoggerFileConstant.APPLICATIONID.toString(), "AuthTransactionCallbackController :: authTransactionCallback() :: Start"); - auditUtil.setAuditRequestDto(EventEnum.AUTH_TYPE_CALL_BACK); - authTransactionCallBackService.updateAuthTransactionCallBackService(eventModel); - auditUtil.setAuditRequestDto(EventEnum.AUTH_TYPE_CALL_BACK_SUCCESS); - } catch (ResidentServiceCheckedException e) { - logger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), - LoggerFileConstant.APPLICATIONID.toString(), - ResidentErrorCode.AUTH_TYPE_CALLBACK_NOT_AVAILABLE.getErrorCode() - + ResidentErrorCode.AUTH_TYPE_CALLBACK_NOT_AVAILABLE.getErrorMessage() - + ExceptionUtils.getStackTrace(e)); - auditUtil.setAuditRequestDto(EventEnum.AUTH_TYPE_CALL_BACK_FAILURE); - throw new ResidentServiceException(ResidentErrorCode.AUTH_TYPE_CALLBACK_NOT_AVAILABLE.getErrorCode(), - ResidentErrorCode.AUTH_TYPE_CALLBACK_NOT_AVAILABLE.getErrorMessage(), e); - } - } - } + try { + logger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), + LoggerFileConstant.APPLICATIONID.toString(), + "AuthTransactionCallbackController :: authTransactionCallback() :: Start"); + auditUtil.setAuditRequestDto(EventEnum.AUTH_TYPE_CALL_BACK); + authTransactionCallBackService.updateAuthTransactionCallBackService(eventModel); + auditUtil.setAuditRequestDto(EventEnum.AUTH_TYPE_CALL_BACK_SUCCESS); + } catch (ResidentServiceCheckedException e) { + logger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), + LoggerFileConstant.APPLICATIONID.toString(), + ResidentErrorCode.AUTH_TYPE_CALLBACK_NOT_AVAILABLE.getErrorCode() + + ResidentErrorCode.AUTH_TYPE_CALLBACK_NOT_AVAILABLE.getErrorMessage() + + ExceptionUtils.getStackTrace(e)); + auditUtil.setAuditRequestDto(EventEnum.AUTH_TYPE_CALL_BACK_FAILURE); + throw new ResidentServiceException(ResidentErrorCode.AUTH_TYPE_CALLBACK_NOT_AVAILABLE.getErrorCode(), + ResidentErrorCode.AUTH_TYPE_CALLBACK_NOT_AVAILABLE.getErrorMessage(), e); + } + } } diff --git a/resident/resident-service/src/main/java/io/mosip/resident/controller/DownLoadMasterDataController.java b/resident/resident-service/src/main/java/io/mosip/resident/controller/DownLoadMasterDataController.java index fd4ffdfa8ab..1db98280d81 100644 --- a/resident/resident-service/src/main/java/io/mosip/resident/controller/DownLoadMasterDataController.java +++ b/resident/resident-service/src/main/java/io/mosip/resident/controller/DownLoadMasterDataController.java @@ -4,7 +4,7 @@ import java.io.InputStream; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; -import java.util.List; +import java.util.Map; import java.util.Objects; import org.springframework.beans.factory.annotation.Autowired; @@ -18,9 +18,12 @@ import org.springframework.web.bind.annotation.RestController; import io.mosip.kernel.core.logger.spi.Logger; +import io.mosip.kernel.core.util.DateUtils; import io.mosip.resident.config.LoggerConfiguration; import io.mosip.resident.constant.ResidentConstants; +import io.mosip.resident.exception.InvalidInputException; import io.mosip.resident.exception.ResidentServiceCheckedException; +import io.mosip.resident.exception.ResidentServiceException; import io.mosip.resident.service.DownLoadMasterDataService; import io.mosip.resident.util.AuditUtil; import io.mosip.resident.util.EventEnum; @@ -72,24 +75,36 @@ public class DownLoadMasterDataController { */ @GetMapping("/download/registration-centers-list") public ResponseEntity downloadRegistrationCentersByHierarchyLevel(@RequestParam(name="langcode") String langCode, - @RequestParam(name="hierarchylevel") Short hierarchyLevel, @RequestParam("name") List name, - @RequestHeader(name = "time-zone-offset", required = false, defaultValue = "0") int timeZoneOffset) + @RequestParam(name="hierarchylevel") Short hierarchyLevel, @RequestParam("name") String name, + @RequestHeader(name = "time-zone-offset", required = false, defaultValue = "0") int timeZoneOffset, + @RequestHeader(name = "locale", required = false) String locale) throws ResidentServiceCheckedException, IOException, Exception { logger.debug("DownLoadMasterDataController::getRegistrationCentersByHierarchyLevel()::entry"); DOWNLOADABLE_REGCEN_FILENAME = "regcenter-"; DOWNLOADABLE_REGCEN_FILENAME = DOWNLOADABLE_REGCEN_FILENAME + getCurrentDateAndTime(); auditUtil.setAuditRequestDto(EventEnum.DOWNLOAD_REGISTRATION_CENTER); - validator.validateOnlyLanguageCode(langCode); - validator.validateName(name); - InputStream pdfInputStream = downLoadMasterDataService.downloadRegistrationCentersByHierarchyLevel(langCode,hierarchyLevel, name); - InputStreamResource resource = new InputStreamResource(pdfInputStream); - audit.setAuditRequestDto(EventEnum.DOWNLOAD_REGISTRATION_CENTER_SUCCESS); - logger.debug("downLoad file name::" + DOWNLOADABLE_REGCEN_FILENAME); - logger.debug("AcknowledgementController::acknowledgement()::exit"); + InputStreamResource resource = null; + try { + validator.validateOnlyLanguageCode(langCode); + validator.validateName(name); + InputStream pdfInputStream = downLoadMasterDataService.downloadRegistrationCentersByHierarchyLevel(langCode, + hierarchyLevel, name); + resource = new InputStreamResource(pdfInputStream); + audit.setAuditRequestDto(EventEnum.DOWNLOAD_REGISTRATION_CENTER_SUCCESS); + logger.debug("downLoad file name::" + DOWNLOADABLE_REGCEN_FILENAME); + logger.debug("AcknowledgementController::acknowledgement()::exit"); + } catch (ResidentServiceException | InvalidInputException | ResidentServiceCheckedException e) { + auditUtil.setAuditRequestDto(EventEnum.DOWNLOAD_REGISTRATION_CENTER_FAILURE); + e.setMetadata(Map.of(ResidentConstants.REQ_RES_ID, + environment.getProperty(ResidentConstants.DOWNLOAD_REG_CENTER_ID))); + throw e; + } return ResponseEntity.ok().contentType(MediaType.parseMediaType("application/pdf")) - .header("Content-Disposition", "attachment; filename=\"" + utility.getFileName(null, - Objects.requireNonNull(this.environment.getProperty( - ResidentConstants.DOWNLOAD_REGISTRATION_CENTRE_FILE_NAME_CONVENTION_PROPERTY)), timeZoneOffset) + ".pdf\"") + .header("Content-Disposition", + "attachment; filename=\"" + utility.getFileName(null, + Objects.requireNonNull(this.environment.getProperty( + ResidentConstants.DOWNLOAD_REGISTRATION_CENTRE_FILE_NAME_CONVENTION_PROPERTY)), + timeZoneOffset, locale) + ".pdf\"") .body(resource); } @@ -97,43 +112,65 @@ public ResponseEntity downloadRegistrationCentersByHierarchyLevel(@Reque public ResponseEntity downloadNearestRegistrationcenters(@RequestParam(name="langcode") String langCode, @RequestParam(name="longitude") double longitude, @RequestParam(name="latitude") double latitude, @RequestParam(name="proximitydistance") int proximityDistance, - @RequestHeader(name = "time-zone-offset", required = false, defaultValue = "0") int timeZoneOffset) + @RequestHeader(name = "time-zone-offset", required = false, defaultValue = "0") int timeZoneOffset, + @RequestHeader(name = "locale", required = false) String locale) throws ResidentServiceCheckedException, IOException, Exception { logger.debug("DownLoadMasterDataController::getRegistrationCentersByHierarchyLevel()::entry"); DOWNLOADABLE_REGCEN_FILENAME = "regcenter-"; DOWNLOADABLE_REGCEN_FILENAME = DOWNLOADABLE_REGCEN_FILENAME + getCurrentDateAndTime(); - auditUtil.setAuditRequestDto(EventEnum.DOWNLOAD_REGISTRATION_CENTER); - validator.validateOnlyLanguageCode(langCode); - InputStream pdfInputStream = downLoadMasterDataService.getNearestRegistrationcenters(langCode,longitude, latitude, proximityDistance); - InputStreamResource resource = new InputStreamResource(pdfInputStream); - audit.setAuditRequestDto(EventEnum.DOWNLOAD_REGISTRATION_CENTER_SUCCESS); - logger.debug("downLoad file name::" + DOWNLOADABLE_REGCEN_FILENAME); - logger.debug("AcknowledgementController::acknowledgement()::exit"); + auditUtil.setAuditRequestDto(EventEnum.DOWNLOAD_REGISTRATION_CENTER_NEAREST); + InputStreamResource resource = null; + try { + validator.validateOnlyLanguageCode(langCode); + InputStream pdfInputStream = downLoadMasterDataService.getNearestRegistrationcenters(langCode, longitude, + latitude, proximityDistance); + resource = new InputStreamResource(pdfInputStream); + audit.setAuditRequestDto(EventEnum.DOWNLOAD_REGISTRATION_CENTER_NEAREST_SUCCESS); + logger.debug("downLoad file name::" + DOWNLOADABLE_REGCEN_FILENAME); + logger.debug("AcknowledgementController::acknowledgement()::exit"); + } catch (ResidentServiceException | InvalidInputException | ResidentServiceCheckedException e) { + auditUtil.setAuditRequestDto(EventEnum.DOWNLOAD_REGISTRATION_CENTER_NEAREST_FAILURE); + e.setMetadata(Map.of(ResidentConstants.REQ_RES_ID, + environment.getProperty(ResidentConstants.DOWNLOAD_NEAREST_REG_CENTER_ID))); + throw e; + } return ResponseEntity.ok().contentType(MediaType.parseMediaType("application/pdf")) .header("Content-Disposition", "attachment; filename=\"" + utility.getFileName(null, Objects.requireNonNull(this.environment.getProperty( - ResidentConstants.DOWNLOAD_NEAREST_REGISTRATION_CENTRE_FILE_NAME_CONVENTION_PROPERTY)), timeZoneOffset) + ".pdf\"") + ResidentConstants.DOWNLOAD_NEAREST_REGISTRATION_CENTRE_FILE_NAME_CONVENTION_PROPERTY)), + timeZoneOffset, locale) + ".pdf\"") .body(resource); } @GetMapping(path = "/download/supporting-documents", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) public ResponseEntity downloadSupportingDocsByLanguage(@RequestParam(name = "langcode") String langCode, - @RequestHeader(name = "time-zone-offset", required = false, defaultValue = "0") int timeZoneOffset) + @RequestHeader(name = "time-zone-offset", required = false, defaultValue = "0") int timeZoneOffset, + @RequestHeader(name = "locale", required = false) String locale) throws ResidentServiceCheckedException, IOException, Exception { logger.debug("DownLoadMasterDataController::getSupportingDocsByLanguageCode()::entry"); DOWNLOADABLE_SUPPORTING_FILENAME = "supportingDocs-"; DOWNLOADABLE_SUPPORTING_FILENAME = DOWNLOADABLE_SUPPORTING_FILENAME + getCurrentDateAndTime(); auditUtil.setAuditRequestDto(EventEnum.DOWNLOAD_SUPPORTING_DOCS); - validator.validateOnlyLanguageCode(langCode); - InputStream pdfInputStream = downLoadMasterDataService.downloadSupportingDocsByLanguage(langCode); - InputStreamResource resource = new InputStreamResource(pdfInputStream); - audit.setAuditRequestDto(EventEnum.DOWNLOAD_SUPPORTING_DOCS_SUCCESS); - logger.debug("downLoad file name::" + DOWNLOADABLE_SUPPORTING_FILENAME); - logger.debug("AcknowledgementController::acknowledgement()::exit"); + InputStreamResource resource = null; + try { + validator.validateOnlyLanguageCode(langCode); + InputStream pdfInputStream = downLoadMasterDataService.downloadSupportingDocsByLanguage(langCode); + resource = new InputStreamResource(pdfInputStream); + audit.setAuditRequestDto(EventEnum.DOWNLOAD_SUPPORTING_DOCS_SUCCESS); + logger.debug("downLoad file name::" + DOWNLOADABLE_SUPPORTING_FILENAME); + logger.debug("AcknowledgementController::acknowledgement()::exit"); + } catch (ResidentServiceException | InvalidInputException | ResidentServiceCheckedException e) { + auditUtil.setAuditRequestDto(EventEnum.DOWNLOAD_SUPPORTING_DOCS_FAILURE); + e.setMetadata(Map.of(ResidentConstants.REQ_RES_ID, + environment.getProperty(ResidentConstants.DOWNLOAD_SUPPORTING_DOCS_ID))); + throw e; + } return ResponseEntity.ok().contentType(MediaType.parseMediaType("application/pdf")) - .header("Content-Disposition", "attachment; filename=\"" + utility.getFileName(null, - Objects.requireNonNull(this.environment.getProperty( - ResidentConstants.DOWNLOAD_SUPPORTING_DOCUMENT_FILE_NAME_CONVENTION_PROPERTY)), timeZoneOffset) + ".pdf\"") + .header("Content-Disposition", + "attachment; filename=\"" + utility.getFileName(null, + Objects.requireNonNull(this.environment.getProperty( + ResidentConstants.DOWNLOAD_SUPPORTING_DOCUMENT_FILE_NAME_CONVENTION_PROPERTY)), + timeZoneOffset, locale) + ".pdf\"") .body(resource); } /** @@ -143,7 +180,7 @@ public ResponseEntity downloadSupportingDocsByLanguage(@RequestParam(nam */ private String getCurrentDateAndTime() { DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd/MM/yyyy-HH:mm:ss"); - LocalDateTime now = LocalDateTime.now(); + LocalDateTime now = DateUtils.getUTCCurrentDateTime(); return dtf.format(now); } } diff --git a/resident/resident-service/src/main/java/io/mosip/resident/controller/DownloadCardController.java b/resident/resident-service/src/main/java/io/mosip/resident/controller/DownloadCardController.java index 1da6bababbe..6fc2eee63c4 100644 --- a/resident/resident-service/src/main/java/io/mosip/resident/controller/DownloadCardController.java +++ b/resident/resident-service/src/main/java/io/mosip/resident/controller/DownloadCardController.java @@ -5,6 +5,7 @@ import java.util.Map; import java.util.Objects; +import org.apache.commons.lang3.exception.ExceptionUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; import org.springframework.core.io.InputStreamResource; @@ -23,6 +24,7 @@ import io.mosip.kernel.core.exception.BaseCheckedException; import io.mosip.kernel.core.logger.spi.Logger; import io.mosip.resident.config.LoggerConfiguration; +import io.mosip.resident.constant.LoggerFileConstant; import io.mosip.resident.constant.ResidentConstants; import io.mosip.resident.dto.CheckStatusResponseDTO; import io.mosip.resident.dto.DownloadCardRequestDTO; @@ -32,6 +34,7 @@ import io.mosip.resident.dto.VidDownloadCardResponseDto; import io.mosip.resident.exception.CardNotReadyException; import io.mosip.resident.exception.InvalidInputException; +import io.mosip.resident.exception.ResidentServiceCheckedException; import io.mosip.resident.exception.ResidentServiceException; import io.mosip.resident.service.DownloadCardService; import io.mosip.resident.util.AuditUtil; @@ -79,39 +82,61 @@ public class DownloadCardController { @ApiResponse(responseCode = "401", description = "Unauthorized", content = @Content(schema = @Schema(hidden = true))), @ApiResponse(responseCode = "403", description = "Forbidden", content = @Content(schema = @Schema(hidden = true))), @ApiResponse(responseCode = "404", description = "Not Found", content = @Content(schema = @Schema(hidden = true))) }) - public ResponseEntity downloadCard(@Validated @RequestBody MainRequestDTO downloadCardRequestDTOMainRequestDTO){ - logger.debug("DownloadCardController::downloadCard()::entry"); - auditUtil.setAuditRequestDto(EventEnum.REQ_CARD); - requestValidator.validateDownloadCardRequest(downloadCardRequestDTOMainRequestDTO); - Tuple2 tupleResponse = downloadCardService - .getDownloadCardPDF(downloadCardRequestDTOMainRequestDTO); - InputStreamResource resource = new InputStreamResource(new ByteArrayInputStream(tupleResponse.getT1())); - if(tupleResponse.getT1().length==0){ - throw new CardNotReadyException(); - } - auditUtil.setAuditRequestDto(EventEnum.GET_ACKNOWLEDGEMENT_DOWNLOAD_URL_SUCCESS); - logger.debug("AcknowledgementController::acknowledgement()::exit"); - return ResponseEntity.ok().contentType(MediaType.parseMediaType("application/pdf")) - .header("Content-Disposition", "attachment; filename=\"" + - downloadCardRequestDTOMainRequestDTO.getRequest().getIndividualId() + ".pdf\"") - .header(ResidentConstants.EVENT_ID, tupleResponse.getT2()) - .body(resource); - } + public ResponseEntity downloadCard( + @Validated @RequestBody MainRequestDTO downloadCardRequestDTOMainRequestDTO, + @RequestHeader(name = "time-zone-offset", required = false, defaultValue = "0") int timeZoneOffset, + @RequestHeader(name = "locale", required = false) String locale) + throws ResidentServiceCheckedException { + logger.debug("DownloadCardController::downloadCard()::entry"); + auditUtil.setAuditRequestDto(EventEnum.REQ_CARD); + InputStreamResource resource = null; + Tuple2 tupleResponse = null; + try { + auditUtil.setAuditRequestDto(EventEnum.RID_DIGITAL_CARD_REQ); + requestValidator.validateDownloadCardRequest(downloadCardRequestDTOMainRequestDTO); + tupleResponse = downloadCardService.getDownloadCardPDF(downloadCardRequestDTOMainRequestDTO); + resource = new InputStreamResource(new ByteArrayInputStream(tupleResponse.getT1())); + if (tupleResponse.getT1().length == 0) { + throw new CardNotReadyException(); + } + } catch (ResidentServiceException | InvalidInputException | CardNotReadyException e) { + auditUtil.setAuditRequestDto(EventEnum.RID_DIGITAL_CARD_REQ_FAILURE); + logger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), + LoggerFileConstant.APPLICATIONID.toString(), ExceptionUtils.getStackTrace(e)); + e.setMetadata(Map.of(ResidentConstants.REQ_RES_ID, + this.environment.getProperty(ResidentConstants.DOWNLOAD_UIN_CARD_ID))); + throw e; + } + auditUtil.setAuditRequestDto(EventEnum.RID_DIGITAL_CARD_REQ_SUCCESS); + logger.debug("AcknowledgementController::acknowledgement()::exit"); + return ResponseEntity.ok().contentType(MediaType.parseMediaType("application/pdf")) + .header("Content-Disposition", + "attachment; filename=\"" + utility.getFileNameforId( + downloadCardRequestDTOMainRequestDTO.getRequest().getIndividualId(), + Objects.requireNonNull(this.environment + .getProperty(ResidentConstants.DOWNLOAD_CARD_NAMING_CONVENTION_PROPERTY)), + timeZoneOffset, locale) + ".pdf\"") + .header(ResidentConstants.EVENT_ID, tupleResponse.getT2()).body(resource); + } @PreAuthorize("@scopeValidator.hasAllScopes(" + "@authorizedScopes.getPostPersonalizedCard()" + ")") @PostMapping("/download/personalized-card") - public ResponseEntity downloadPersonalizedCard(@Validated @RequestBody MainRequestDTO downloadPersonalizedCardMainRequestDTO, - @RequestHeader(name = "time-zone-offset", required = false, defaultValue = "0") int timeZoneOffset){ + public ResponseEntity downloadPersonalizedCard( + @Validated @RequestBody MainRequestDTO downloadPersonalizedCardMainRequestDTO, + @RequestHeader(name = "time-zone-offset", required = false, defaultValue = "0") int timeZoneOffset, + @RequestHeader(name = "locale", required = false) String locale) + throws ResidentServiceCheckedException { logger.debug("DownloadCardController::downloadPersonalizedCard()::entry"); auditUtil.setAuditRequestDto(EventEnum.DOWNLOAD_PERSONALIZED_CARD); try { requestValidator.validateDownloadPersonalizedCard(downloadPersonalizedCardMainRequestDTO); } catch (InvalidInputException e) { - throw new ResidentServiceException(e.getErrorCode(), e.getErrorText(), e, - Map.of(ResidentConstants.HTTP_STATUS_CODE, HttpStatus.BAD_REQUEST, ResidentConstants.REQ_RES_ID, - environment.getProperty(ResidentConstants.MOSIP_RESIDENT_DOWNLOAD_PERSONALIZED_CARD_ID))); + auditUtil.setAuditRequestDto(EventEnum.DOWNLOAD_PERSONALIZED_CARD_FAILURE); + e.setMetadata(Map.of(ResidentConstants.REQ_RES_ID, + environment.getProperty(ResidentConstants.MOSIP_RESIDENT_DOWNLOAD_PERSONALIZED_CARD_ID))); + throw e; } - Tuple2 tupleResponse = downloadCardService.downloadPersonalizedCard(downloadPersonalizedCardMainRequestDTO, timeZoneOffset); + Tuple2 tupleResponse = downloadCardService.downloadPersonalizedCard(downloadPersonalizedCardMainRequestDTO, timeZoneOffset, locale); InputStreamResource resource = new InputStreamResource(new ByteArrayInputStream(tupleResponse.getT1())); if(tupleResponse.getT1().length==0){ return new ResponseEntity<>(HttpStatus.BAD_REQUEST); @@ -120,7 +145,7 @@ public ResponseEntity downloadPersonalizedCard(@Validated @RequestBody M .header("Content-Disposition", "attachment; filename=\"" + utility.getFileName(tupleResponse.getT2(), Objects.requireNonNull(this.environment.getProperty( - ResidentConstants.DOWNLOAD_PERSONALIZED_CARD_NAMING_CONVENTION_PROPERTY)), timeZoneOffset) + ResidentConstants.DOWNLOAD_PERSONALIZED_CARD_NAMING_CONVENTION_PROPERTY)), timeZoneOffset, locale) + ".pdf\"") .header(ResidentConstants.EVENT_ID, tupleResponse.getT2()) .body(resource); @@ -128,19 +153,37 @@ public ResponseEntity downloadPersonalizedCard(@Validated @RequestBody M @GetMapping("/request-card/vid/{VID}") public ResponseEntity requestVidCard(@PathVariable("VID") String vid, - @RequestHeader(name = "time-zone-offset", required = false, defaultValue = "0") int timeZoneOffset) throws BaseCheckedException { + @RequestHeader(name = "time-zone-offset", required = false, defaultValue = "0") int timeZoneOffset, + @RequestHeader(name = "locale", required = false) String locale) throws BaseCheckedException { auditUtil.setAuditRequestDto(EventEnum.RID_DIGITAL_CARD_REQ); - requestValidator.validateDownloadCardVid(vid); - Tuple2, String> tupleResponse = downloadCardService.getVidCardEventId(vid, timeZoneOffset); - auditUtil.setAuditRequestDto(EventEnum.RID_DIGITAL_CARD_REQ_SUCCESS); - return ResponseEntity.ok() - .header(ResidentConstants.EVENT_ID, tupleResponse.getT2()) + Tuple2, String> tupleResponse = null; + try { + requestValidator.validateDownloadCardVid(vid); + tupleResponse = downloadCardService.getVidCardEventId(vid, timeZoneOffset, locale); + } catch (ResidentServiceException | InvalidInputException e) { + auditUtil.setAuditRequestDto(EventEnum.RID_DIGITAL_CARD_REQ_FAILURE); + e.setMetadata(Map.of(ResidentConstants.REQ_RES_ID, + environment.getProperty(ResidentConstants.VID_DOWNLOAD_CARD_ID))); + throw e; + } + auditUtil.setAuditRequestDto(EventEnum.RID_DIGITAL_CARD_REQ_SUCCESS); + return ResponseEntity.ok().header(ResidentConstants.EVENT_ID, tupleResponse.getT2()) .body(tupleResponse.getT1()); - } + } @GetMapping("/aid-stage/{aid}") public ResponseEntity getStatus(@PathVariable("aid") String aid) throws BaseCheckedException, IOException { - ResponseWrapper responseWrapper = downloadCardService.getIndividualIdStatus(aid); + ResponseWrapper responseWrapper = null; + auditUtil.setAuditRequestDto(EventEnum.AID_STAGE); + try { + responseWrapper = downloadCardService.getIndividualIdStatus(aid); + } catch (ResidentServiceException | InvalidInputException e) { + auditUtil.setAuditRequestDto(EventEnum.AID_STAGE_FAILURE); + e.setMetadata(Map.of(ResidentConstants.REQ_RES_ID, + environment.getProperty(ResidentConstants.CHECK_STATUS_INDIVIDUAL_ID))); + throw e; + } + auditUtil.setAuditRequestDto(EventEnum.AID_STAGE_SUCCESS); return ResponseEntity.ok() .body(responseWrapper); } diff --git a/resident/resident-service/src/main/java/io/mosip/resident/controller/GrievanceController.java b/resident/resident-service/src/main/java/io/mosip/resident/controller/GrievanceController.java index e35decad484..db59494f2b1 100644 --- a/resident/resident-service/src/main/java/io/mosip/resident/controller/GrievanceController.java +++ b/resident/resident-service/src/main/java/io/mosip/resident/controller/GrievanceController.java @@ -1,8 +1,10 @@ package io.mosip.resident.controller; import java.io.IOException; +import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; @@ -11,10 +13,13 @@ import io.mosip.kernel.core.http.ResponseWrapper; import io.mosip.kernel.core.logger.spi.Logger; import io.mosip.resident.config.LoggerConfiguration; +import io.mosip.resident.constant.ResidentConstants; import io.mosip.resident.dto.GrievanceRequestDTO; import io.mosip.resident.dto.MainRequestDTO; import io.mosip.resident.exception.ApisResourceAccessException; +import io.mosip.resident.exception.InvalidInputException; import io.mosip.resident.exception.ResidentServiceCheckedException; +import io.mosip.resident.exception.ResidentServiceException; import io.mosip.resident.service.GrievanceService; import io.mosip.resident.util.AuditUtil; import io.mosip.resident.util.EventEnum; @@ -38,16 +43,29 @@ public class GrievanceController { @Autowired GrievanceService grievanceService; + + @Autowired + private Environment environment; private static final Logger logger = LoggerConfiguration.logConfig(GrievanceController.class); - @PostMapping("/grievance/ticket") - public ResponseWrapper grievanceTicket(@Validated @RequestBody MainRequestDTO - grievanceRequestDTOMainRequestDTO) throws ResidentServiceCheckedException, - ApisResourceAccessException, IOException { - logger.debug("DownloadCardController::grievanceTicket()::entry"); - auditUtil.setAuditRequestDto(EventEnum.GRIEVANCE_TICKET_REQUEST); - requestValidator.validateGrievanceRequestDto(grievanceRequestDTOMainRequestDTO); - return grievanceService.getGrievanceTicket(grievanceRequestDTOMainRequestDTO); - } + @PostMapping("/grievance/ticket") + public ResponseWrapper grievanceTicket( + @Validated @RequestBody MainRequestDTO grievanceRequestDTOMainRequestDTO) + throws ResidentServiceCheckedException, ApisResourceAccessException, IOException { + logger.debug("DownloadCardController::grievanceTicket()::entry"); + auditUtil.setAuditRequestDto(EventEnum.GRIEVANCE_TICKET_REQUEST); + ResponseWrapper response = null; + try { + requestValidator.validateGrievanceRequestDto(grievanceRequestDTOMainRequestDTO); + response = grievanceService.getGrievanceTicket(grievanceRequestDTOMainRequestDTO); + } catch (ResidentServiceException | InvalidInputException | ResidentServiceCheckedException e) { + auditUtil.setAuditRequestDto(EventEnum.GRIEVANCE_TICKET_REQUEST_FAILED); + e.setMetadata(Map.of(ResidentConstants.REQ_RES_ID, + environment.getProperty(ResidentConstants.GRIEVANCE_REQUEST_ID))); + throw e; + } + auditUtil.setAuditRequestDto(EventEnum.GRIEVANCE_TICKET_REQUEST_SUCCESS); + return response; + } } diff --git a/resident/resident-service/src/main/java/io/mosip/resident/controller/IdAuthController.java b/resident/resident-service/src/main/java/io/mosip/resident/controller/IdAuthController.java index 84ba70352ed..c49c1bd2a7f 100644 --- a/resident/resident-service/src/main/java/io/mosip/resident/controller/IdAuthController.java +++ b/resident/resident-service/src/main/java/io/mosip/resident/controller/IdAuthController.java @@ -80,8 +80,12 @@ public ResponseEntity validateOtp(@RequestBody RequestWrapper responseWrapper = new ResponseWrapper(); ValidateOtpResponseDto validateOtpResponseDto = new ValidateOtpResponseDto(); diff --git a/resident/resident-service/src/main/java/io/mosip/resident/controller/IdentityController.java b/resident/resident-service/src/main/java/io/mosip/resident/controller/IdentityController.java index 9a8a205c2ba..a8a09e6ad5a 100644 --- a/resident/resident-service/src/main/java/io/mosip/resident/controller/IdentityController.java +++ b/resident/resident-service/src/main/java/io/mosip/resident/controller/IdentityController.java @@ -75,6 +75,7 @@ public ResponseWrapper getInputAttributeValues(@PathVariable("schemaType try { validator.validateSchemaType(schemaType); } catch (InvalidInputException e) { + auditUtil.setAuditRequestDto(EventEnum.GET_INPUT_ATTRIBUTES_EXCEPTION); throw new ResidentServiceException(e.getErrorCode(), e.getErrorText(), e, Map.of(ResidentConstants.REQ_RES_ID, residentIdentityInfoId)); } diff --git a/resident/resident-service/src/main/java/io/mosip/resident/controller/OrderCardController.java b/resident/resident-service/src/main/java/io/mosip/resident/controller/OrderCardController.java index 342dbd0394d..b6de563d6bd 100644 --- a/resident/resident-service/src/main/java/io/mosip/resident/controller/OrderCardController.java +++ b/resident/resident-service/src/main/java/io/mosip/resident/controller/OrderCardController.java @@ -1,8 +1,10 @@ package io.mosip.resident.controller; import java.net.URI; +import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; @@ -16,6 +18,7 @@ import io.mosip.kernel.core.http.ResponseWrapper; import io.mosip.kernel.core.logger.spi.Logger; import io.mosip.resident.config.LoggerConfiguration; +import io.mosip.resident.constant.ResidentConstants; import io.mosip.resident.dto.RequestWrapper; import io.mosip.resident.dto.ResidentCredentialRequestDto; import io.mosip.resident.dto.ResidentCredentialResponseDto; @@ -49,6 +52,9 @@ public class OrderCardController { @Autowired private IdentityServiceImpl identityServiceImpl; + + @Autowired + private Environment env; private static final Logger logger = LoggerConfiguration.logConfig(OrderCardController.class); @@ -73,9 +79,14 @@ public ResponseWrapper sendPhysicalCard( @RequestBody RequestWrapper requestWrapper) throws ResidentServiceCheckedException, ApisResourceAccessException { logger.debug("OrderCardController::sendPhysicalCard()::entry"); - auditUtil.setAuditRequestDto(EventEnum.SEND_PHYSICAL_CARD); ResponseWrapper responseWrapper = new ResponseWrapper<>(); - responseWrapper.setResponse(orderCardService.sendPhysicalCard(requestWrapper.getRequest())); + try { + auditUtil.setAuditRequestDto(EventEnum.SEND_PHYSICAL_CARD); + responseWrapper.setResponse(orderCardService.sendPhysicalCard(requestWrapper.getRequest())); + } catch (ResidentServiceCheckedException e) { + auditUtil.setAuditRequestDto(EventEnum.SEND_PHYSICAL_CARD_EXCEPTION); + e.setMetadata(Map.of(ResidentConstants.REQ_RES_ID, env.getProperty(ResidentConstants.SEND_CARD_ID))); + } auditUtil.setAuditRequestDto(EventEnum.SEND_PHYSICAL_CARD_SUCCESS); logger.debug("OrderCardController::sendPhysicalCard()::exit"); return responseWrapper; diff --git a/resident/resident-service/src/main/java/io/mosip/resident/controller/PinStatusController.java b/resident/resident-service/src/main/java/io/mosip/resident/controller/PinStatusController.java index ca859165a8e..49135d08003 100644 --- a/resident/resident-service/src/main/java/io/mosip/resident/controller/PinStatusController.java +++ b/resident/resident-service/src/main/java/io/mosip/resident/controller/PinStatusController.java @@ -1,6 +1,9 @@ package io.mosip.resident.controller; +import java.util.Map; + import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; @@ -9,7 +12,10 @@ import io.mosip.kernel.core.http.ResponseWrapper; import io.mosip.kernel.core.logger.spi.Logger; import io.mosip.resident.config.LoggerConfiguration; +import io.mosip.resident.constant.ResidentConstants; import io.mosip.resident.dto.ResponseDTO; +import io.mosip.resident.exception.InvalidInputException; +import io.mosip.resident.exception.ResidentServiceCheckedException; import io.mosip.resident.service.PinUnpinStatusService; import io.mosip.resident.util.AuditUtil; import io.mosip.resident.util.EventEnum; @@ -31,26 +37,47 @@ public class PinStatusController { @Autowired private PinUnpinStatusService pinUnpinStatusService; + + @Autowired + private Environment env; @PreAuthorize("@scopeValidator.hasAllScopes(" + "@authorizedScopes.getPostPinStatus()" + ")") @PostMapping(path = "pinned/{eventId}") - public ResponseWrapper pinStatus(@PathVariable("eventId") String eventId){ - audit.setAuditRequestDto(EventEnum.getEventEnumWithValue(EventEnum.VALIDATE_REQUEST, "Pin Status API")); - requestValidator.validateEventId(eventId); - audit.setAuditRequestDto(EventEnum.getEventEnumWithValue(EventEnum.PIN_STATUS, eventId)); - return pinUnpinStatusService.pinStatus(eventId, true); - } + public ResponseWrapper pinStatus(@PathVariable("eventId") String eventId) + throws ResidentServiceCheckedException { + audit.setAuditRequestDto(EventEnum.getEventEnumWithValue(EventEnum.VALIDATE_REQUEST, "Pin Status API")); + ResponseWrapper response = new ResponseWrapper<>(); + try { + requestValidator.validateEventId(eventId); + audit.setAuditRequestDto(EventEnum.getEventEnumWithValue(EventEnum.PIN_STATUS, eventId)); + response = pinUnpinStatusService.pinStatus(eventId, true); + } catch (InvalidInputException | ResidentServiceCheckedException e) { + audit.setAuditRequestDto(EventEnum.getEventEnumWithValue(EventEnum.PIN_STATUS_FAILURE, eventId)); + e.setMetadata(Map.of(ResidentConstants.REQ_RES_ID, env.getProperty(ResidentConstants.PINNED_EVENTID_ID))); + throw e; + } + return response; + } @PreAuthorize("@scopeValidator.hasAllScopes(" + "@authorizedScopes.getPostUnPinStatus()" + ")") - @PostMapping(path = "unpinned/{eventId}") - public ResponseWrapper unPinStatus(@PathVariable("eventId") String eventId){ - audit.setAuditRequestDto(EventEnum.getEventEnumWithValue(EventEnum.VALIDATE_REQUEST, "Pin Status API")); - requestValidator.validateEventId(eventId); - audit.setAuditRequestDto(EventEnum.getEventEnumWithValue(EventEnum.UN_PIN_STATUS, eventId)); - return pinUnpinStatusService.pinStatus(eventId, false); - } + @PostMapping(path = "unpinned/{eventId}") + public ResponseWrapper unPinStatus(@PathVariable("eventId") String eventId) + throws ResidentServiceCheckedException { + audit.setAuditRequestDto(EventEnum.getEventEnumWithValue(EventEnum.VALIDATE_REQUEST, "Pin Status API")); + ResponseWrapper response = new ResponseWrapper<>(); + try { + requestValidator.validateEventId(eventId); + audit.setAuditRequestDto(EventEnum.getEventEnumWithValue(EventEnum.UN_PIN_STATUS, eventId)); + response = pinUnpinStatusService.pinStatus(eventId, false); + } catch (InvalidInputException | ResidentServiceCheckedException e) { + audit.setAuditRequestDto(EventEnum.getEventEnumWithValue(EventEnum.UN_PIN_STATUS_FAILURE, eventId)); + e.setMetadata(Map.of(ResidentConstants.REQ_RES_ID, env.getProperty(ResidentConstants.UNPINNED_EVENTID_ID))); + throw e; + } + return response; + } } diff --git a/resident/resident-service/src/main/java/io/mosip/resident/controller/ProxyMasterdataController.java b/resident/resident-service/src/main/java/io/mosip/resident/controller/ProxyMasterdataController.java index eb61d67242d..1b1c1973feb 100644 --- a/resident/resident-service/src/main/java/io/mosip/resident/controller/ProxyMasterdataController.java +++ b/resident/resident-service/src/main/java/io/mosip/resident/controller/ProxyMasterdataController.java @@ -376,21 +376,23 @@ public ResponseWrapper getAllTemplateBylangCodeAndTemplateTypeCode(@PathVaria * @throws ResidentServiceCheckedException */ @ResponseFilter - @GetMapping("/auth-proxy/masterdata/gendertypes/{langcode}") - @Operation(summary = "getGenderTypesByLangCode", description = "getGenderTypesByLangCode", tags = { + @GetMapping("/auth-proxy/masterdata/dynamicfields/{fieldName}/{langCode}") + @Operation(summary = "getDynamicFieldBasedOnLangCodeAndFieldName", description = "Service to fetch dynamic field based on langcode and field name", tags = { "proxy-masterdata-controller" }) @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "OK"), @ApiResponse(responseCode = "201", description = "Created", content = @Content(schema = @Schema(hidden = true))), @ApiResponse(responseCode = "401", description = "Unauthorized", content = @Content(schema = @Schema(hidden = true))), @ApiResponse(responseCode = "403", description = "Forbidden", content = @Content(schema = @Schema(hidden = true))), @ApiResponse(responseCode = "404", description = "Not Found", content = @Content(schema = @Schema(hidden = true))) }) - public ResponseWrapper getGenderTypesByLangCode(@PathVariable("langcode") String langCode) + public ResponseWrapper getDynamicFieldBasedOnLangCodeAndFieldName(@PathVariable("fieldName") String fieldName, + @PathVariable("langCode") String langCode, + @RequestParam(value = "withValue", defaultValue = "false") boolean withValue) throws ResidentServiceCheckedException { - logger.debug("ProxyMasterdataController::getGenderTypesByLangCode()::entry"); - auditUtil.setAuditRequestDto(EventEnum.GET_GENDER_TYPES); - ResponseWrapper responseWrapper = proxyMasterdataService.getGenderTypesByLangCode(langCode); + logger.debug("ProxyMasterdataController::getDynamicFieldBasedOnLangCodeAndFieldName()::entry"); + auditUtil.setAuditRequestDto(EventEnum.GET_DYNAMIC_FIELD_BASED_ON_LANG_CODE_AND_FIELD_NAME); + ResponseWrapper responseWrapper = proxyMasterdataService.getDynamicFieldBasedOnLangCodeAndFieldName(fieldName, langCode, withValue); auditUtil.setAuditRequestDto(EventEnum.GET_GENDER_TYPES_SUCCESS); - logger.debug("ProxyMasterdataController::getGenderTypesByLangCode()::exit"); + logger.debug("ProxyMasterdataController::getDynamicFieldBasedOnLangCodeAndFieldName()::exit"); return responseWrapper; } diff --git a/resident/resident-service/src/main/java/io/mosip/resident/controller/ProxyOtpController.java b/resident/resident-service/src/main/java/io/mosip/resident/controller/ProxyOtpController.java new file mode 100644 index 00000000000..20840a79805 --- /dev/null +++ b/resident/resident-service/src/main/java/io/mosip/resident/controller/ProxyOtpController.java @@ -0,0 +1,137 @@ +package io.mosip.resident.controller; + +import java.util.Map; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.bind.annotation.RestController; + +import io.mosip.kernel.core.authmanager.model.AuthNResponse; +import io.mosip.kernel.core.logger.spi.Logger; +import io.mosip.resident.config.LoggerConfiguration; +import io.mosip.resident.constant.ResidentConstants; +import io.mosip.resident.constant.ResidentErrorCode; +import io.mosip.resident.dto.MainRequestDTO; +import io.mosip.resident.dto.MainResponseDTO; +import io.mosip.resident.dto.OtpRequestDTOV2; +import io.mosip.resident.dto.OtpRequestDTOV3; +import io.mosip.resident.exception.ApisResourceAccessException; +import io.mosip.resident.exception.InvalidInputException; +import io.mosip.resident.exception.ResidentServiceException; +import io.mosip.resident.service.ProxyOtpService; +import io.mosip.resident.util.AuditUtil; +import io.mosip.resident.util.EventEnum; +import io.mosip.resident.validator.RequestValidator; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import io.swagger.v3.oas.annotations.responses.ApiResponses; +import io.swagger.v3.oas.annotations.tags.Tag; +import reactor.util.function.Tuple2; + +/** + * This class provides different api to perform operation for login + * + * @author Kamesh Shekhar Prasad + * @since 1.0.0 + * + */ +@RestController +@Tag(name = "login-controller", description = "Login Controller") +public class ProxyOtpController { + + private Logger log = LoggerConfiguration.logConfig(ProxyOtpController.class); + + @Autowired + private ProxyOtpService proxyOtpService; + + @Autowired + private RequestValidator requestValidator; + + @Autowired + private Environment environment; + + @Autowired + private AuditUtil audit; + + /** + * This Post api use to send otp to the user by email or sms + * + * @param userOtpRequest + * @return AuthNResponse + */ + + @PostMapping(value = "/contact-details/send-otp", produces = MediaType.APPLICATION_JSON_VALUE) + @Operation(summary = "sendOTP", description = "Send Otp to UserId", tags = "login-controller") + @ApiResponses(value = { + @ApiResponse(responseCode = "200", description = "OK"), + @ApiResponse(responseCode = "201", description = "Created" ,content = @Content(schema = @Schema(hidden = true))), + @ApiResponse(responseCode = "401", description = "Unauthorized" ,content = @Content(schema = @Schema(hidden = true))), + @ApiResponse(responseCode = "403", description = "Forbidden" ,content = @Content(schema = @Schema(hidden = true))), + @ApiResponse(responseCode = "404", description = "Not Found" ,content = @Content(schema = @Schema(hidden = true)))}) + @ResponseStatus(value = HttpStatus.OK) + public ResponseEntity> sendOTP( + @Validated @RequestBody MainRequestDTO userOtpRequest) throws ApisResourceAccessException { + String userid = null; + try { + requestValidator.validateProxySendOtpRequest(userOtpRequest); + userid = userOtpRequest.getRequest().getUserId(); + } + catch (InvalidInputException e) { + audit.setAuditRequestDto(EventEnum.getEventEnumWithValue(EventEnum.SEND_OTP_FAILURE, userid, "Send OTP")); + throw new ResidentServiceException(e.getErrorCode(), e.getErrorText(), e, + Map.of(ResidentConstants.REQ_RES_ID, + environment.getProperty(ResidentConstants.RESIDENT_CONTACT_DETAILS_SEND_OTP_ID))); + } catch (ApisResourceAccessException e) { + audit.setAuditRequestDto(EventEnum.getEventEnumWithValue(EventEnum.SEND_OTP_FAILURE, userid, "Send OTP")); + throw new ApisResourceAccessException(ResidentErrorCode.CLAIM_NOT_AVAILABLE.getErrorCode(), + ResidentErrorCode.CLAIM_NOT_AVAILABLE.getErrorMessage(), e); + } + return proxyOtpService.sendOtp(userOtpRequest); + } + + + + /** + * This Post api use to validate userid and otp + * + * @param userIdOtpRequest + * @return AuthNResponse + */ + @PostMapping(value = "/contact-details/update-data", produces = MediaType.APPLICATION_JSON_VALUE) + @Operation(summary = "validateWithUserIdOtp", description = "Validate UserId and Otp", tags = "login-controller") + @ApiResponses(value = { + @ApiResponse(responseCode = "200", description = "OK"), + @ApiResponse(responseCode = "201", description = "Created" ,content = @Content(schema = @Schema(hidden = true))), + @ApiResponse(responseCode = "401", description = "Unauthorized" ,content = @Content(schema = @Schema(hidden = true))), + @ApiResponse(responseCode = "403", description = "Forbidden" ,content = @Content(schema = @Schema(hidden = true))), + @ApiResponse(responseCode = "404", description = "Not Found" ,content = @Content(schema = @Schema(hidden = true)))}) + public ResponseEntity> validateWithUserIdOtp( + @Validated @RequestBody MainRequestDTO userIdOtpRequest) { + + log.debug("User ID: {}", userIdOtpRequest.getRequest().getUserId()); + String userId = null; + try { + requestValidator.validateUpdateDataRequest(userIdOtpRequest); + userId = userIdOtpRequest.getRequest().getUserId(); + } catch (InvalidInputException e) { + audit.setAuditRequestDto( + EventEnum.getEventEnumWithValue(EventEnum.OTP_VALIDATION_FAILED, userId, "Validate OTP Failed")); + throw new ResidentServiceException(e.getErrorCode(), e.getErrorText(), e, + Map.of(ResidentConstants.REQ_RES_ID, + environment.getProperty(ResidentConstants.RESIDENT_CONTACT_DETAILS_UPDATE_ID))); + } + Tuple2, String> tupleResponse = proxyOtpService.validateWithUserIdOtp(userIdOtpRequest); + return ResponseEntity.ok() + .header(ResidentConstants.EVENT_ID, tupleResponse.getT2()) + .body(tupleResponse.getT1()); + } +} diff --git a/resident/resident-service/src/main/java/io/mosip/resident/controller/ProxyPartnerManagementController.java b/resident/resident-service/src/main/java/io/mosip/resident/controller/ProxyPartnerManagementController.java index d56ac6e40e9..c84122ba874 100644 --- a/resident/resident-service/src/main/java/io/mosip/resident/controller/ProxyPartnerManagementController.java +++ b/resident/resident-service/src/main/java/io/mosip/resident/controller/ProxyPartnerManagementController.java @@ -1,8 +1,10 @@ package io.mosip.resident.controller; +import java.util.Map; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; @@ -12,6 +14,7 @@ import io.mosip.kernel.core.http.ResponseWrapper; import io.mosip.kernel.core.logger.spi.Logger; import io.mosip.resident.config.LoggerConfiguration; +import io.mosip.resident.constant.ResidentConstants; import io.mosip.resident.exception.ResidentServiceCheckedException; import io.mosip.resident.service.ProxyPartnerManagementService; import io.mosip.resident.util.AuditUtil; @@ -38,6 +41,9 @@ public class ProxyPartnerManagementController { @Autowired private AuditUtil auditUtil; + + @Autowired + private Environment env; private static final Logger logger = LoggerConfiguration.logConfig(ProxyPartnerManagementController.class); @@ -61,7 +67,15 @@ public ResponseWrapper getPartnersByPartnerType(@RequestParam("partnerType") throws ResidentServiceCheckedException { logger.debug("ProxyPartnerManagementController::getPartnersByPartnerType():: entry"); auditUtil.setAuditRequestDto(EventEnum.GET_PARTNERS_BY_PARTNER_TYPE); - ResponseWrapper responseWrapper = proxyPartnerManagementService.getPartnersByPartnerType(partnerType); + ResponseWrapper responseWrapper = new ResponseWrapper<>(); + try { + responseWrapper = proxyPartnerManagementService.getPartnersByPartnerType(partnerType); + } catch (ResidentServiceCheckedException e) { + auditUtil.setAuditRequestDto(EventEnum.GET_PARTNERS_BY_PARTNER_TYPE_EXCEPTION); + e.setMetadata( + Map.of(ResidentConstants.REQ_RES_ID, env.getProperty(ResidentConstants.AUTH_PROXY_PARTNERS_ID))); + throw e; + } auditUtil.setAuditRequestDto(EventEnum.GET_PARTNERS_BY_PARTNER_TYPE_SUCCESS); logger.debug("ProxyPartnerManagementController::getPartnersByPartnerType():: exit"); return responseWrapper; diff --git a/resident/resident-service/src/main/java/io/mosip/resident/controller/ResidentController.java b/resident/resident-service/src/main/java/io/mosip/resident/controller/ResidentController.java index 40e537215d5..1419eef6641 100644 --- a/resident/resident-service/src/main/java/io/mosip/resident/controller/ResidentController.java +++ b/resident/resident-service/src/main/java/io/mosip/resident/controller/ResidentController.java @@ -1,5 +1,8 @@ package io.mosip.resident.controller; +import static io.mosip.resident.constant.ResidentConstants.RESIDENT_SERVICE_HISTORY_DOWNLOAD_MAX_COUNT; +import static io.mosip.resident.constant.ResidentConstants.RESIDENT_VIEW_HISTORY_DEFAULT_PAGE_SIZE; + import java.io.ByteArrayInputStream; import java.io.IOException; import java.time.LocalDate; @@ -128,9 +131,15 @@ public class ResidentController { @Value("${resident.checkstatus.id}") private String checkStatusId; - @Value("${resident.service-history.download.max.count}") + @Value("${resident.service.history.id}") + private String serviceHistoryId; + + @Value("${resident.service.event.id}") + private String serviceEventId; + + @Value("${" + RESIDENT_SERVICE_HISTORY_DOWNLOAD_MAX_COUNT + "}") private Integer maxEventsServiceHistoryPageSize; - + private static final Logger logger = LoggerConfiguration.logConfig(ResidentController.class); @ResponseFilter @@ -143,11 +152,17 @@ public class ResidentController { @ApiResponse(responseCode = "404", description = "Not Found", content = @Content(schema = @Schema(hidden = true))) }) public ResponseWrapper getRidStatus( @Valid @RequestBody RequestWrapper requestDTO) throws ApisResourceAccessException { - audit.setAuditRequestDto(EventEnum.getEventEnumWithValue(EventEnum.VALIDATE_REQUEST, "get Rid status API")); - validator.validateRidCheckStatusRequestDTO(requestDTO); ResponseWrapper response = new ResponseWrapper<>(); - audit.setAuditRequestDto(EventEnum.RID_STATUS); - response.setResponse(residentService.getRidStatus(requestDTO.getRequest())); + try { + audit.setAuditRequestDto(EventEnum.getEventEnumWithValue(EventEnum.VALIDATE_REQUEST, "get Rid status API")); + validator.validateRidCheckStatusRequestDTO(requestDTO); + audit.setAuditRequestDto(EventEnum.RID_STATUS); + response.setResponse(residentService.getRidStatus(requestDTO.getRequest())); + } catch (InvalidInputException | ApisResourceAccessException e) { + audit.setAuditRequestDto(EventEnum.RID_STATUS_FAILURE); + e.setMetadata(Map.of(ResidentConstants.REQ_RES_ID, checkStatusId)); + throw e; + } audit.setAuditRequestDto(EventEnum.RID_STATUS_SUCCESS); return response; } @@ -260,18 +275,28 @@ public ResponseEntity reqAauthTypeStatusUpdateV2( throws ResidentServiceCheckedException, ApisResourceAccessException { audit.setAuditRequestDto( EventEnum.getEventEnumWithValue(EventEnum.VALIDATE_REQUEST, "update auth Type status API")); - String individualId = identityServiceImpl.getResidentIndvidualIdFromSession(); - validator.validateAuthLockOrUnlockRequestV2(requestDTO); - audit.setAuditRequestDto(EventEnum.getEventEnumWithValue(EventEnum.REQ_AUTH_LOCK, individualId)); + String individualId = null; ResponseWrapper response = new ResponseWrapper<>(); - Tuple2 tupleResponse = residentService.reqAauthTypeStatusUpdateV2(requestDTO.getRequest()); - response.setResponse(tupleResponse.getT1()); - response.setId(authLockStatusUpdateV2Id); - response.setVersion(authLockStatusUpdateV2Version); + Tuple2 tupleResponse = null; + try { + individualId = identityServiceImpl.getResidentIndvidualIdFromSession(); + validator.validateAuthLockOrUnlockRequestV2(requestDTO); + audit.setAuditRequestDto(EventEnum.getEventEnumWithValue(EventEnum.REQ_AUTH_LOCK, individualId)); + tupleResponse = residentService.reqAauthTypeStatusUpdateV2(requestDTO.getRequest()); + response.setResponse(tupleResponse.getT1()); + response.setId(authLockStatusUpdateV2Id); + response.setVersion(authLockStatusUpdateV2Version); + } catch (InvalidInputException | ResidentServiceCheckedException e) { + audit.setAuditRequestDto( + EventEnum.getEventEnumWithValue(EventEnum.REQUEST_FAILED, "Request for auth lock failed")); + e.setMetadata(Map.of(ResidentConstants.REQ_RES_ID, authLockStatusUpdateV2Id)); + throw e; + } audit.setAuditRequestDto(EventEnum.getEventEnumWithValue(EventEnum.REQ_AUTH_LOCK_SUCCESS, individualId)); return ResponseEntity.ok() .header(ResidentConstants.EVENT_ID, tupleResponse.getT2()) .body(response); + } @ResponseFilter @@ -286,33 +311,51 @@ public ResponseWrapper reqAuthHistory( @Valid @RequestBody RequestWrapper requestDTO) throws ResidentServiceCheckedException { audit.setAuditRequestDto(EventEnum.getEventEnumWithValue(EventEnum.VALIDATE_REQUEST, "request auth history")); - validator.validateAuthHistoryRequest(requestDTO); ResponseWrapper response = new ResponseWrapper<>(); - audit.setAuditRequestDto(EventEnum.getEventEnumWithValue(EventEnum.REQ_AUTH_HISTORY, - requestDTO.getRequest().getTransactionID())); - response.setResponse(residentService.reqAuthHistory(requestDTO.getRequest())); + try { + validator.validateAuthHistoryRequest(requestDTO); + response = new ResponseWrapper<>(); + audit.setAuditRequestDto(EventEnum.getEventEnumWithValue(EventEnum.REQ_AUTH_HISTORY, + requestDTO.getRequest().getTransactionID())); + response.setResponse(residentService.reqAuthHistory(requestDTO.getRequest())); + } catch (InvalidInputException | ResidentServiceCheckedException e) { + audit.setAuditRequestDto(EventEnum.getEventEnumWithValue(EventEnum.REQUEST_FAILED, + requestDTO.getRequest().getTransactionID(), "Request for auth history")); + e.setMetadata(Map.of(ResidentConstants.REQ_RES_ID, ResidentConstants.AUTH_HISTORY_ID)); + throw e; + } audit.setAuditRequestDto(EventEnum.getEventEnumWithValue(EventEnum.REQ_AUTH_HISTORY_SUCCESS, requestDTO.getRequest().getTransactionID())); return response; } @GetMapping(path = "/events/{event-id}") - @Operation(summary = "getGetCheckEventIdStatus", description = "checkEventIdStatus", tags = { + @Operation(summary = "checkEventIdStatus", description = "checkEventIdStatus", tags = { "resident-controller" }) @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "OK"), @ApiResponse(responseCode = "201", description = "Created", content = @Content(schema = @Schema(hidden = true))), @ApiResponse(responseCode = "401", description = "Unauthorized", content = @Content(schema = @Schema(hidden = true))), @ApiResponse(responseCode = "403", description = "Forbidden", content = @Content(schema = @Schema(hidden = true))), @ApiResponse(responseCode = "404", description = "Not Found", content = @Content(schema = @Schema(hidden = true))) }) - public ResponseWrapper checkAidStatus(@PathVariable(name = "event-id") String eventId, + public ResponseWrapper checkEventIdStatus(@PathVariable(name = "event-id") String eventId, @RequestParam(name = "langCode") String languageCode, - @RequestHeader(name = "time-zone-offset", required = false, defaultValue = "0") int timeZoneOffset) throws ResidentServiceCheckedException { + @RequestHeader(name = "time-zone-offset", required = false, defaultValue = "0") int timeZoneOffset, + @RequestHeader(name = "locale", required = false) String locale) throws ResidentServiceCheckedException { audit.setAuditRequestDto(EventEnum.getEventEnumWithValue(EventEnum.VALIDATE_REQUEST, "checkAidStatus")); logger.debug("checkAidStatus controller entry"); - validator.validateEventIdLanguageCode(eventId, languageCode); - audit.setAuditRequestDto(EventEnum.getEventEnumWithValue(EventEnum.CHECK_AID_STATUS_REQUEST, eventId)); - ResponseWrapper responseWrapper = residentService.getEventStatus(eventId, languageCode, timeZoneOffset); + ResponseWrapper responseWrapper = new ResponseWrapper<>(); + try { + validator.validateEventIdLanguageCode(eventId, languageCode); + audit.setAuditRequestDto(EventEnum.getEventEnumWithValue(EventEnum.CHECK_AID_STATUS_REQUEST, eventId)); + responseWrapper = residentService.getEventStatus(eventId, languageCode, timeZoneOffset, locale); + } catch (InvalidInputException | ResidentServiceCheckedException e) { + audit.setAuditRequestDto( + EventEnum.getEventEnumWithValue(EventEnum.CHECK_AID_STATUS_REQUEST_FAILED, eventId)); + e.setMetadata(Map.of(ResidentConstants.REQ_RES_ID, ResidentConstants.EVENTS_EVENTID_ID)); + throw e; + } audit.setAuditRequestDto(EventEnum.getEventEnumWithValue(EventEnum.CHECK_AID_STATUS_REQUEST_SUCCESS, eventId)); + logger.debug("ResidentController::checkEventIdStatus()::exit"); return responseWrapper; } @@ -333,16 +376,27 @@ public ResponseWrapper> getServiceHistory(@Pa @RequestParam(name = "serviceType", required = false) String serviceType, @RequestParam(name = "statusFilter", required = false) String statusFilter, @RequestParam(name = "searchText", required = false) String searchText, - @RequestHeader(name = "time-zone-offset", required = false, defaultValue = "0") int timeZoneOffset) + @RequestHeader(name = "time-zone-offset", required = false, defaultValue = "0") int timeZoneOffset, + @RequestHeader(name = "locale", required = false) String locale) throws ResidentServiceCheckedException, ApisResourceAccessException { logger.info("TimeZone-offset: " + timeZoneOffset); audit.setAuditRequestDto(EventEnum.getEventEnumWithValue(EventEnum.VALIDATE_REQUEST, "getServiceHistory")); - validator.validateOnlyLanguageCode(langCode); - validator.validateServiceHistoryRequest(fromDate, toDate, sortType, serviceType, statusFilter); - validator.validateSearchText(searchText); - audit.setAuditRequestDto(EventEnum.getEventEnumWithValue(EventEnum.GET_SERVICE_HISTORY, "getServiceHistory")); - ResponseWrapper> responseWrapper = residentService.getServiceHistory( - pageStart, pageFetch, fromDate, toDate, serviceType, sortType, statusFilter, searchText, langCode, timeZoneOffset); + ResponseWrapper> responseWrapper = new ResponseWrapper<>(); + try { + validator.validateOnlyLanguageCode(langCode); + validator.validateServiceHistoryRequest(fromDate, toDate, sortType, serviceType, statusFilter); + validator.validateSearchText(searchText); + audit.setAuditRequestDto( + EventEnum.getEventEnumWithValue(EventEnum.GET_SERVICE_HISTORY, "getServiceHistory")); + responseWrapper = residentService.getServiceHistory(pageStart, pageFetch, fromDate, toDate, serviceType, + sortType, statusFilter, searchText, langCode, timeZoneOffset, locale, + RESIDENT_VIEW_HISTORY_DEFAULT_PAGE_SIZE, null); + } catch (InvalidInputException | ResidentServiceCheckedException e) { + audit.setAuditRequestDto(EventEnum.GET_SERVICE_HISTORY_FAILURE); + e.setMetadata(Map.of(ResidentConstants.REQ_RES_ID, serviceHistoryId)); + throw e; + } + audit.setAuditRequestDto(EventEnum.GET_SERVICE_HISTORY_SUCCESS); return responseWrapper; } @@ -357,7 +411,7 @@ public ResponseWrapper> getServiceHistory(@Pa @ApiResponse(responseCode = "404", description = "Not Found", content = @Content(schema = @Schema(hidden = true))) }) public ResponseWrapper updateUin( @Valid @RequestBody RequestWrapper requestDTO) - throws ResidentServiceCheckedException { + throws ResidentServiceCheckedException, ApisResourceAccessException, IOException { audit.setAuditRequestDto(EventEnum.getEventEnumWithValue(EventEnum.VALIDATE_REQUEST, "update Uin API")); validator.validateUpdateRequest(requestDTO, false); ResponseWrapper response = new ResponseWrapper<>(); @@ -387,31 +441,37 @@ public ResponseWrapper updateUin( @ApiResponse(responseCode = "404", description = "Not Found", content = @Content(schema = @Schema(hidden = true))) }) public ResponseEntity updateUinDemographics( @Valid @RequestBody RequestWrapper requestDTO) - throws ResidentServiceCheckedException, ApisResourceAccessException { + throws ResidentServiceCheckedException, ApisResourceAccessException, IOException { audit.setAuditRequestDto(EventEnum.getEventEnumWithValue(EventEnum.VALIDATE_REQUEST, "update UIN API")); RequestWrapper requestWrapper = JsonUtil.convertValue(requestDTO, new TypeReference>() { }); String individualId = identityServiceImpl.getResidentIndvidualIdFromSession(); + ResponseWrapper response = new ResponseWrapper<>(); + Tuple2 tupleResponse = null; ResidentUpdateRequestDto request = requestWrapper.getRequest(); if (request != null) { request.setIndividualId(individualId); request.setIndividualIdType(getIdType(individualId)); } - validator.validateUpdateRequest(requestWrapper, true); - ResponseWrapper response = new ResponseWrapper<>(); - audit.setAuditRequestDto( - EventEnum.getEventEnumWithValue(EventEnum.UPDATE_UIN, requestDTO.getRequest().getTransactionID())); - requestDTO.getRequest().getIdentity().put(IdType.UIN.name(), identityServiceImpl.getUinForIndividualId(individualId)); - Tuple2 tupleResponse = residentService.reqUinUpdate(request, requestDTO.getRequest().getIdentity(), true); - response.setId(requestDTO.getId()); - response.setVersion(requestDTO.getVersion()); - response.setResponse(tupleResponse.getT1()); + try { + validator.validateUpdateRequest(requestWrapper, true); + audit.setAuditRequestDto( + EventEnum.getEventEnumWithValue(EventEnum.UPDATE_UIN, requestDTO.getRequest().getTransactionID())); + requestDTO.getRequest().getIdentity().put(IdType.UIN.name(), + identityServiceImpl.getUinForIndividualId(individualId)); + tupleResponse = residentService.reqUinUpdate(request, requestDTO.getRequest().getIdentity(), true); + response.setId(requestDTO.getId()); + response.setVersion(requestDTO.getVersion()); + response.setResponse(tupleResponse.getT1()); + } catch (InvalidInputException | ResidentServiceCheckedException e) { + audit.setAuditRequestDto(EventEnum.UPDATE_UIN_FAILURE); + e.setMetadata(Map.of(ResidentConstants.REQ_RES_ID, ResidentConstants.UPDATE_UIN_ID)); + throw e; + } audit.setAuditRequestDto(EventEnum.getEventEnumWithValue(EventEnum.UPDATE_UIN_SUCCESS, requestDTO.getRequest().getTransactionID())); - return ResponseEntity.ok() - .header(ResidentConstants.EVENT_ID, tupleResponse.getT2()) - .body(response); + return ResponseEntity.ok().header(ResidentConstants.EVENT_ID, tupleResponse.getT2()).body(response); } @PreAuthorize("@scopeValidator.hasAllScopes(" + "@authorizedScopes.getGetAuthLockStatus()" + ")") @@ -446,7 +506,8 @@ public ResponseWrapper getAuthLockStatus() throws @ApiResponse(responseCode = "404", description = "Not Found", content = @Content(schema = @Schema(hidden = true))) }) public ResponseEntity downloadCard( @PathVariable("eventId") String eventId, - @RequestHeader(name = "time-zone-offset", required = false, defaultValue = "0") int timeZoneOffset) throws ResidentServiceCheckedException { + @RequestHeader(name = "time-zone-offset", required = false, defaultValue = "0") int timeZoneOffset, + @RequestHeader(name = "locale", required = false) String locale) throws ResidentServiceCheckedException { audit.setAuditRequestDto( EventEnum.getEventEnumWithValue(EventEnum.VALIDATE_REQUEST, "request download card API")); InputStreamResource resource = null; @@ -469,7 +530,7 @@ public ResponseEntity downloadCard( downloadCardEventidId)); } return ResponseEntity.ok().contentType(MediaType.APPLICATION_PDF) - .header("Content-Disposition", "attachment; filename=\"" + residentService.getFileName(eventId, timeZoneOffset) + ".pdf\"") + .header("Content-Disposition", "attachment; filename=\"" + residentService.getFileName(eventId, timeZoneOffset, locale) + ".pdf\"") .header(ResidentConstants.EVENT_ID, eventId) .body(resource); } @@ -501,11 +562,12 @@ public ResponseWrapper checkAidStatus(@RequestBody Request logger.debug("ResidentController::getAidStatus()::entry"); AidStatusResponseDTO resp = new AidStatusResponseDTO(); try { - validator.validateAidStatusRequestDto(reqDto); - audit.setAuditRequestDto(EventEnum.AID_STATUS); - resp = residentService.getAidStatus(reqDto.getRequest()); - } catch (ResidentServiceCheckedException | ApisResourceAccessException | OtpValidationFailedException e ) { - throw new ResidentServiceException( e.getErrorCode(), e.getErrorText(), e, + validator.validateAidStatusRequestDto(reqDto); + audit.setAuditRequestDto(EventEnum.AID_STATUS); + resp = residentService.getAidStatus(reqDto.getRequest(), true); + } catch (ResidentServiceCheckedException | ApisResourceAccessException | OtpValidationFailedException e) { + audit.setAuditRequestDto(EventEnum.AID_STATUS_FAILURE); + throw new ResidentServiceException(e.getErrorCode(), e.getErrorText(), e, Map.of(ResidentConstants.REQ_RES_ID, checkStatusId)); } audit.setAuditRequestDto(EventEnum.AID_STATUS_SUCCESS); @@ -529,12 +591,18 @@ public ResponseWrapper checkAidStatus(@RequestBody Request @ApiResponse(responseCode = "404", description = "Not Found", content = @Content(schema = @Schema(hidden = true))) }) public ResponseWrapper notificationCount() throws ResidentServiceCheckedException, ApisResourceAccessException { + ResponseWrapper count = new ResponseWrapper<>(); logger.debug("ResidentController::getunreadnotificationCount()::entry"); String individualId = identityServiceImpl.getResidentIdaToken(); - - ResponseWrapper count = residentService.getnotificationCount(individualId); + try { + count = residentService.getnotificationCount(individualId); + } catch (ResidentServiceCheckedException e) { + audit.setAuditRequestDto(EventEnum.UNREAD_NOTIF_COUNT_FAILURE); + e.setMetadata(Map.of(ResidentConstants.REQ_RES_ID, serviceEventId)); + throw e; + } + audit.setAuditRequestDto(EventEnum.UNREAD_NOTIF_COUNT_SUCCESS); logger.debug("ResidentController::getunreadnotificationCount()::exit"); - return count; } @@ -551,8 +619,17 @@ public ResponseWrapper notificationCount() public ResponseWrapper bellClickdttimes() throws ResidentServiceCheckedException, ApisResourceAccessException { logger.debug("ResidentController::getnotificationclickdttimes()::entry"); - String idaToken = identityServiceImpl.getResidentIdaToken(); - ResponseWrapper response = residentService.getbellClickdttimes(idaToken); + String idaToken = null; + ResponseWrapper response = new ResponseWrapper<>(); + try { + idaToken = identityServiceImpl.getResidentIdaToken(); + response = residentService.getbellClickdttimes(idaToken); + } catch (ResidentServiceCheckedException | ApisResourceAccessException e) { + audit.setAuditRequestDto(EventEnum.GET_NOTIF_CLICK_FAILURE); + e.setMetadata(Map.of(ResidentConstants.REQ_RES_ID, ResidentConstants.NOTIFICATION_CLICK_ID)); + throw e; + } + audit.setAuditRequestDto(EventEnum.GET_NOTIF_CLICK_SUCCESS); logger.debug("ResidentController::getnotificationclickdttimes::exit"); return response; } @@ -584,13 +661,23 @@ public int bellupdateClickdttimes() throws ResidentServiceCheckedException, Apis public ResponseWrapper getNotificationsList(@PathVariable("langCode") String langCode, @RequestParam(name = "pageStart", required = false) Integer pageStart, @RequestParam(name = "pageFetch", required = false) Integer pageFetch, - @RequestHeader(name = "time-zone-offset", required = false, defaultValue = "0") int timeZoneOffset) + @RequestHeader(name = "time-zone-offset", required = false, defaultValue = "0") int timeZoneOffset, + @RequestHeader(name = "locale", required = false) String locale) throws ResidentServiceCheckedException, ApisResourceAccessException { logger.debug("ResidentController::getunreadServiceList()::entry"); - validator.validateOnlyLanguageCode(langCode); - String id = identityServiceImpl.getResidentIdaToken(); - ResponseWrapper> notificationDtoList = residentService - .getNotificationList(pageStart, pageFetch, id, langCode, timeZoneOffset); + String id = null; + ResponseWrapper> notificationDtoList = new ResponseWrapper<>(); + try { + validator.validateOnlyLanguageCode(langCode); + id = identityServiceImpl.getResidentIdaToken(); + notificationDtoList = residentService.getNotificationList(pageStart, pageFetch, id, langCode, + timeZoneOffset, locale); + } catch (ResidentServiceCheckedException | ApisResourceAccessException | InvalidInputException e) { + audit.setAuditRequestDto(EventEnum.GET_NOTIFICATION_FAILURE); + e.setMetadata(Map.of(ResidentConstants.REQ_RES_ID, ResidentConstants.NOTIFICATION_ID)); + throw e; + } + audit.setAuditRequestDto(EventEnum.GET_NOTIFICATION_SUCCESS); logger.debug("ResidentController::getunreadServiceList()::exit"); return notificationDtoList; } @@ -605,24 +692,35 @@ public ResponseEntity downLoadServiceHistory( @RequestParam(name = "statusFilter", required = false) String statusFilter, @RequestParam(name = "searchText", required = false) String searchText, @RequestParam(name = "languageCode", required = true) String languageCode, - @RequestHeader(name = "time-zone-offset", required = false, defaultValue = "0") int timeZoneOffset) + @RequestHeader(name = "time-zone-offset", required = false, defaultValue = "0") int timeZoneOffset, + @RequestHeader(name = "locale", required = false) String locale) throws ResidentServiceCheckedException, ApisResourceAccessException, IOException { logger.debug("ResidentController::serviceHistory::pdf"); audit.setAuditRequestDto( EventEnum.getEventEnumWithValue(EventEnum.DOWNLOAD_SERVICE_HISTORY, "acknowledgement")); - validator.validateOnlyLanguageCode(languageCode); - ResponseWrapper> responseWrapper = residentService.getServiceHistory( - null, maxEventsServiceHistoryPageSize, fromDate, toDate, serviceType, sortType, statusFilter, searchText, languageCode, timeZoneOffset); - logger.debug("after response wrapper size of " + responseWrapper.getResponse().getData().size()); - byte[] pdfBytes = residentService.downLoadServiceHistory(responseWrapper, languageCode, eventReqDateTime, - fromDate, toDate, serviceType, statusFilter, timeZoneOffset); - InputStreamResource resource = new InputStreamResource(new ByteArrayInputStream(pdfBytes)); + InputStreamResource resource = null; + try { + validator.validateOnlyLanguageCode(languageCode); + ResponseWrapper> responseWrapper = residentService.getServiceHistory( + null, maxEventsServiceHistoryPageSize, fromDate, toDate, serviceType, sortType, statusFilter, + searchText, languageCode, timeZoneOffset, locale); + logger.debug("after response wrapper size of " + responseWrapper.getResponse().getData().size()); + byte[] pdfBytes = residentService.downLoadServiceHistory(responseWrapper, languageCode, eventReqDateTime, + fromDate, toDate, serviceType, statusFilter, timeZoneOffset, locale); + resource = new InputStreamResource(new ByteArrayInputStream(pdfBytes)); + } catch (ResidentServiceCheckedException | ApisResourceAccessException | InvalidInputException e) { + audit.setAuditRequestDto(EventEnum.DOWNLOAD_SERVICE_HISTORY_FAILURE); + e.setMetadata(Map.of(ResidentConstants.REQ_RES_ID, ResidentConstants.SERVICE_HISTORY_ID)); + throw e; + } audit.setAuditRequestDto(EventEnum.DOWNLOAD_SERVICE_HISTORY_SUCCESS); logger.debug("AcknowledgementController::acknowledgement()::exit"); return ResponseEntity.ok().contentType(MediaType.parseMediaType("application/pdf")) - .header("Content-Disposition", "attachment; filename=\"" + utility.getFileName(null, - Objects.requireNonNull(this.environment.getProperty( - ResidentConstants.DOWNLOAD_SERVICE_HISTORY_FILE_NAME_CONVENTION_PROPERTY)), timeZoneOffset) + ".pdf\"") + .header("Content-Disposition", + "attachment; filename=\"" + utility.getFileName(null, + Objects.requireNonNull(this.environment.getProperty( + ResidentConstants.DOWNLOAD_SERVICE_HISTORY_FILE_NAME_CONVENTION_PROPERTY)), + timeZoneOffset, locale) + ".pdf\"") .body(resource); } @@ -635,11 +733,21 @@ public ResponseEntity downLoadServiceHistory( @ApiResponse(responseCode = "403", description = "Forbidden", content = @Content(schema = @Schema(hidden = true))), @ApiResponse(responseCode = "404", description = "Not Found", content = @Content(schema = @Schema(hidden = true))) }) - public ResponseWrapper userinfo(@RequestHeader(name = "time-zone-offset", required = false, defaultValue = "0") int timeZoneOffset) + public ResponseWrapper userinfo(@RequestHeader(name = "time-zone-offset", required = false, defaultValue = "0") int timeZoneOffset, + @RequestHeader(name = "locale", required = false) String locale) throws ResidentServiceCheckedException, ApisResourceAccessException { logger.debug("ResidentController::getuserinfo()::entry"); - String Id = identityServiceImpl.getResidentIdaToken(); - ResponseWrapper userInfoDto = residentService.getUserinfo(Id, timeZoneOffset); + String Id = null; + ResponseWrapper userInfoDto = new ResponseWrapper<>(); + try { + Id = identityServiceImpl.getResidentIdaToken(); + userInfoDto = residentService.getUserinfo(Id, timeZoneOffset, locale); + } catch (ResidentServiceCheckedException | ApisResourceAccessException e) { + audit.setAuditRequestDto(EventEnum.GET_PROFILE_FAILURE); + e.setMetadata(Map.of(ResidentConstants.REQ_RES_ID, ResidentConstants.PROFILE_ID)); + throw e; + } + audit.setAuditRequestDto(EventEnum.GET_PROFILE_SUCCESS); logger.debug("ResidentController::getuserinfo()::exit"); return userInfoDto; } diff --git a/resident/resident-service/src/main/java/io/mosip/resident/controller/ResidentCredentialController.java b/resident/resident-service/src/main/java/io/mosip/resident/controller/ResidentCredentialController.java index eb7fcd281e1..a631baa9f54 100644 --- a/resident/resident-service/src/main/java/io/mosip/resident/controller/ResidentCredentialController.java +++ b/resident/resident-service/src/main/java/io/mosip/resident/controller/ResidentCredentialController.java @@ -28,8 +28,8 @@ import io.mosip.kernel.core.http.ResponseFilter; import io.mosip.kernel.core.http.ResponseWrapper; import io.mosip.resident.constant.RequestIdType; -import io.mosip.resident.constant.RequestType; import io.mosip.resident.constant.ResidentConstants; +import io.mosip.resident.constant.UISchemaTypes; import io.mosip.resident.dto.CredentialCancelRequestResponseDto; import io.mosip.resident.dto.CredentialRequestStatusResponseDto; import io.mosip.resident.dto.CredentialTypeResponse; @@ -41,10 +41,10 @@ import io.mosip.resident.dto.SharableAttributesDTO; import io.mosip.resident.dto.ShareCredentialRequestDto; import io.mosip.resident.exception.ApisResourceAccessException; +import io.mosip.resident.exception.InvalidInputException; import io.mosip.resident.exception.ResidentServiceCheckedException; import io.mosip.resident.service.ResidentCredentialService; import io.mosip.resident.service.impl.ResidentConfigServiceImpl; -import io.mosip.resident.service.impl.UISchemaTypes; import io.mosip.resident.util.AuditUtil; import io.mosip.resident.util.EventEnum; import io.mosip.resident.validator.RequestValidator; @@ -90,9 +90,15 @@ public class ResidentCredentialController { public ResponseEntity reqCredential(@RequestBody RequestWrapper requestDTO) throws ResidentServiceCheckedException { audit.setAuditRequestDto(EventEnum.CREDENTIAL_REQ); - validator.validateReqCredentialRequest(requestDTO); ResponseWrapper response = new ResponseWrapper<>(); - response.setResponse(residentCredentialService.reqCredential(requestDTO.getRequest())); + try { + validator.validateReqCredentialRequest(requestDTO); + response.setResponse(residentCredentialService.reqCredential(requestDTO.getRequest())); + } catch (InvalidInputException | ResidentServiceCheckedException e) { + audit.setAuditRequestDto(EventEnum.CREDENTIAL_REQ_EXCEPTION); + e.setMetadata(Map.of(ResidentConstants.REQ_RES_ID, ResidentConstants.CREDENTIAL_STORE_ID)); + throw e; + } audit.setAuditRequestDto(EventEnum.CREDENTIAL_REQ_SUCCESS); return ResponseEntity.status(HttpStatus.OK).body(response); } @@ -110,26 +116,32 @@ public ResponseEntity reqCredential(@RequestBody RequestWrapper requestShareCredWithPartner( @RequestBody RequestWrapper requestDTO) throws ResidentServiceCheckedException, ApisResourceAccessException, JsonParseException, JsonMappingException, IOException { - validator.validateRequestNewApi(requestDTO, RequestIdType.SHARE_CREDENTIAL); - validator.validateSharableAttributes(requestDTO.getRequest().getSharableAttributes()); - validator.validatePurpose(requestDTO.getRequest().getPurpose()); - String purpose = requestDTO.getRequest().getPurpose(); - audit.setAuditRequestDto(EventEnum.CREDENTIAL_REQ); - RequestWrapper request = new RequestWrapper(); - ResidentCredentialRequestDto credentialRequestDto = new ResidentCredentialRequestDto(); - credentialRequestDto.setIssuer(requestDTO.getRequest().getPartnerId()); - credentialRequestDto.setConsent(requestDTO.getRequest().getConsent()); - request.setRequest(credentialRequestDto); - buildAdditionalMetadata(requestDTO, request); ResponseWrapper response = new ResponseWrapper<>(); Tuple2 tupleResponse; - tupleResponse = residentCredentialService.shareCredential(request.getRequest(), RequestType.SHARE_CRED_WITH_PARTNER.name(),purpose); + try { + validator.validateRequestNewApi(requestDTO, RequestIdType.SHARE_CREDENTIAL); + validator.validateSharableAttributes(requestDTO.getRequest().getSharableAttributes()); + validator.validatePurpose(requestDTO.getRequest().getPurpose()); + String purpose = requestDTO.getRequest().getPurpose(); + audit.setAuditRequestDto(EventEnum.CREDENTIAL_REQ); + RequestWrapper request = new RequestWrapper(); + ResidentCredentialRequestDto credentialRequestDto = new ResidentCredentialRequestDto(); + credentialRequestDto.setIssuer(requestDTO.getRequest().getPartnerId()); + credentialRequestDto.setConsent(requestDTO.getRequest().getConsent()); + request.setRequest(credentialRequestDto); + buildAdditionalMetadata(requestDTO, request); + tupleResponse = residentCredentialService.shareCredential(request.getRequest(), purpose, + requestDTO.getRequest().getSharableAttributes()); + } catch (InvalidInputException | ResidentServiceCheckedException e) { + audit.setAuditRequestDto(EventEnum.CREDENTIAL_REQ_EXCEPTION); + e.setMetadata(Map.of(ResidentConstants.REQ_RES_ID, shareCredentialId)); + throw e; + } response.setId(shareCredentialId); response.setVersion(shareCredentialVersion); response.setResponse(tupleResponse.getT1()); audit.setAuditRequestDto(EventEnum.CREDENTIAL_REQ_SUCCESS); - return ResponseEntity.status(HttpStatus.OK) - .header(ResidentConstants.EVENT_ID, tupleResponse.getT2()) + return ResponseEntity.status(HttpStatus.OK).header(ResidentConstants.EVENT_ID, tupleResponse.getT2()) .body(response); } diff --git a/resident/resident-service/src/main/java/io/mosip/resident/controller/ResidentOtpController.java b/resident/resident-service/src/main/java/io/mosip/resident/controller/ResidentOtpController.java index 124508ac0ef..715abde59d4 100644 --- a/resident/resident-service/src/main/java/io/mosip/resident/controller/ResidentOtpController.java +++ b/resident/resident-service/src/main/java/io/mosip/resident/controller/ResidentOtpController.java @@ -15,6 +15,7 @@ import io.mosip.resident.dto.OtpRequestDTO; import io.mosip.resident.dto.OtpResponseDTO; import io.mosip.resident.exception.ApisResourceAccessException; +import io.mosip.resident.exception.InvalidInputException; import io.mosip.resident.exception.ResidentServiceCheckedException; import io.mosip.resident.exception.ResidentServiceException; import io.mosip.resident.service.ResidentOtpService; @@ -77,9 +78,11 @@ public IndividualIdResponseDto reqOtpForIndividualId(@RequestBody IndividualIdOt requestValidator.validateReqOtp(individualIdRequestDto); individualIdResponseDto = residentOtpService.generateOtpForIndividualId(individualIdRequestDto); } catch (ResidentServiceCheckedException | ApisResourceAccessException e) { + audit.setAuditRequestDto(EventEnum.OTP_AID_GEN_EXCEPTION); throw new ResidentServiceException(e.getErrorCode(), e.getErrorText(), e, Map.of(ResidentConstants.REQ_RES_ID, otpRequestId)); - } catch (ResidentServiceException e) { + } catch (ResidentServiceException | InvalidInputException e) { + audit.setAuditRequestDto(EventEnum.OTP_AID_GEN_EXCEPTION); e.setMetadata(Map.of(ResidentConstants.REQ_RES_ID, otpRequestId)); throw e; } diff --git a/resident/resident-service/src/main/java/io/mosip/resident/controller/ResidentVidController.java b/resident/resident-service/src/main/java/io/mosip/resident/controller/ResidentVidController.java index 2285e99ebef..6b0a2afe774 100644 --- a/resident/resident-service/src/main/java/io/mosip/resident/controller/ResidentVidController.java +++ b/resident/resident-service/src/main/java/io/mosip/resident/controller/ResidentVidController.java @@ -97,9 +97,11 @@ public ResponseEntity> getVidPolicy() { response.setResponsetime(DateUtils.getUTCCurrentDateTimeString()); response.setResponse(residentVidService.getVidPolicy()); } catch (ResidentServiceCheckedException e) { + auditUtil.setAuditRequestDto(EventEnum.GET_VID_POLICY_SUCCESS); response.setErrors(List.of(new ServiceError(ResidentErrorCode.POLICY_EXCEPTION.getErrorCode(), ResidentErrorCode.POLICY_EXCEPTION.getErrorMessage()))); } + auditUtil.setAuditRequestDto(EventEnum.GET_VID_POLICY_FAILURE); return ResponseEntity.ok().body(response); } @@ -265,11 +267,19 @@ private String getResidentIndividualId() throws ApisResourceAccessException { @ApiResponse(responseCode = "401", description = "Unauthorized" ,content = @Content(schema = @Schema(hidden = true))), @ApiResponse(responseCode = "403", description = "Forbidden" ,content = @Content(schema = @Schema(hidden = true))), @ApiResponse(responseCode = "404", description = "Not Found" ,content = @Content(schema = @Schema(hidden = true)))}) - public ResponseWrapper retrieveVids(@RequestHeader(name = "time-zone-offset", required = false, defaultValue = "0") int timeZoneOffset) throws ResidentServiceException, ApisResourceAccessException, ResidentServiceCheckedException { + public ResponseWrapper retrieveVids(@RequestHeader(name = "time-zone-offset", required = false, defaultValue = "0") int timeZoneOffset, + @RequestHeader(name = "locale", required = false) String locale) throws ResidentServiceException, ApisResourceAccessException, ResidentServiceCheckedException { logger.debug("ResidentVidController::retrieveVids()::entry"); auditUtil.setAuditRequestDto(EventEnum.GET_VIDS); + ResponseWrapper>> retrieveVids = new ResponseWrapper<>(); String residentIndividualId = getResidentIndividualId(); - ResponseWrapper>> retrieveVids = residentVidService.retrieveVids(residentIndividualId, timeZoneOffset); + try { + retrieveVids = residentVidService.retrieveVids(residentIndividualId, timeZoneOffset, locale); + } catch (ResidentServiceException | ApisResourceAccessException | ResidentServiceCheckedException e) { + auditUtil.setAuditRequestDto(EventEnum.GET_VIDS_EXCEPTION); + e.setMetadata(Map.of(ResidentConstants.REQ_RES_ID, ResidentConstants.GET_VIDS_ID)); + throw e; + } auditUtil.setAuditRequestDto(EventEnum.GET_VIDS_SUCCESS); logger.debug("ResidentVidController::retrieveVids()::exit"); return retrieveVids; diff --git a/resident/resident-service/src/main/java/io/mosip/resident/controller/TransliterationController.java b/resident/resident-service/src/main/java/io/mosip/resident/controller/TransliterationController.java new file mode 100644 index 00000000000..caaf0f10503 --- /dev/null +++ b/resident/resident-service/src/main/java/io/mosip/resident/controller/TransliterationController.java @@ -0,0 +1,81 @@ +package io.mosip.resident.controller; + +import java.util.Map; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import io.mosip.preregistration.application.dto.TransliterationRequestDTO; +import io.mosip.preregistration.application.dto.TransliterationResponseDTO; +import io.mosip.preregistration.application.service.TransliterationService; +import io.mosip.preregistration.core.common.dto.MainRequestDTO; +import io.mosip.preregistration.core.common.dto.MainResponseDTO; +import io.mosip.resident.constant.ResidentConstants; +import io.mosip.resident.exception.InvalidInputException; +import io.mosip.resident.util.AuditUtil; +import io.mosip.resident.util.EventEnum; +import io.mosip.resident.validator.RequestValidator; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import io.swagger.v3.oas.annotations.responses.ApiResponses; +import io.swagger.v3.oas.annotations.tags.Tag; + +/** + * This class provides different API's to perform operations on + * Transliteration Application + * + * @author Kamesh Shekhar Prasad + * + */ +@RestController +@RequestMapping("/transliteration") +@Tag(name = "Transliteration Controller", description = "Transliteration Controller") +public class TransliterationController { + + /** Autowired reference for {@link #transliterationService}. */ + @Autowired + private TransliterationService transliterationService; + + @Autowired + private RequestValidator requestValidator; + + @Autowired + private AuditUtil audit; + + /** The Constant for GET UPDATED DATE TIME application. */ + private static final String TRANS = "resident.transliteration.transliterate"; + + /** + * Post API to transliterate from transliteration application. + * + * @param requestDTO + * @return responseDto with transliterated toFieldValue. + */ + @PostMapping(path = "/transliterate", consumes = MediaType.APPLICATION_JSON_VALUE,produces = MediaType.APPLICATION_JSON_VALUE) + @Operation(summary = "Get Pre-Registartion-Translitration data", description = "Get Pre-Registartion-Translitration data", tags = "Transliteration Controller") + @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "Given key is translitrated successfully"), + @ApiResponse(responseCode = "201", description = "Created" ,content = @Content(schema = @Schema(hidden = true))), + @ApiResponse(responseCode = "401", description = "Unauthorized" ,content = @Content(schema = @Schema(hidden = true))), + @ApiResponse(responseCode = "403", description = "Forbidden" ,content = @Content(schema = @Schema(hidden = true))), + @ApiResponse(responseCode = "404", description = "Not Found" ,content = @Content(schema = @Schema(hidden = true)))}) + public ResponseEntity> translitrator( + @Validated @RequestBody() MainRequestDTO requestDTO) { + try { + requestValidator.validateId(requestDTO); + } catch (InvalidInputException e) { + audit.setAuditRequestDto(EventEnum.TRANSLITERATION_FAILURE); + e.setMetadata(Map.of(ResidentConstants.REQ_RES_ID, ResidentConstants.TRANSLITERATE_ID)); + throw e; + } + return ResponseEntity.status(HttpStatus.OK).body(transliterationService.translitratorService(requestDTO)); + } +} diff --git a/resident/resident-service/src/main/java/io/mosip/resident/controller/VerificationController.java b/resident/resident-service/src/main/java/io/mosip/resident/controller/VerificationController.java index e012539b1fd..923ffd4a5e9 100644 --- a/resident/resident-service/src/main/java/io/mosip/resident/controller/VerificationController.java +++ b/resident/resident-service/src/main/java/io/mosip/resident/controller/VerificationController.java @@ -1,6 +1,7 @@ package io.mosip.resident.controller; import java.security.NoSuchAlgorithmException; +import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; @@ -9,11 +10,15 @@ import io.mosip.kernel.core.logger.spi.Logger; import io.mosip.resident.config.LoggerConfiguration; +import io.mosip.resident.constant.ResidentConstants; import io.mosip.resident.dto.VerificationResponseDTO; import io.mosip.resident.exception.ApisResourceAccessException; +import io.mosip.resident.exception.InvalidInputException; import io.mosip.resident.exception.ResidentServiceCheckedException; -import io.mosip.resident.service.impl.VerificationServiceImpl; +import io.mosip.resident.exception.ResidentServiceException; +import io.mosip.resident.service.VerificationService; import io.mosip.resident.util.AuditUtil; +import io.mosip.resident.util.EventEnum; import io.mosip.resident.validator.RequestValidator; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.media.Content; @@ -22,36 +27,43 @@ import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.tags.Tag; - @RestController @Tag(name = "verification-controller", description = "controller for channel verification status") public class VerificationController { - @Autowired - private AuditUtil audit; + @Autowired + private AuditUtil audit; - @Autowired - private VerificationServiceImpl verificationServiceImpl; + @Autowired + private VerificationService verificationService; - @Autowired - private RequestValidator validator; + @Autowired + private RequestValidator validator; - private static final Logger logger = LoggerConfiguration.logConfig(VerificationController.class); + private static final Logger logger = LoggerConfiguration.logConfig(VerificationController.class); - @GetMapping(value = "/channel/verification-status/") - @Operation(summary = "get channel verification status", description = "get channel verification status") - @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "OK"), - @ApiResponse(responseCode = "201", description = "Created", content = @Content(schema = @Schema(hidden = true))), - @ApiResponse(responseCode = "401", description = "Unauthorized", content = @Content(schema = @Schema(hidden = true))), - @ApiResponse(responseCode = "403", description = "Forbidden", content = @Content(schema = @Schema(hidden = true))), - @ApiResponse(responseCode = "404", description = "Not Found", content = @Content(schema = @Schema(hidden = true))) }) + @GetMapping(value = "/channel/verification-status/") + @Operation(summary = "get channel verification status", description = "get channel verification status") + @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "OK"), + @ApiResponse(responseCode = "201", description = "Created", content = @Content(schema = @Schema(hidden = true))), + @ApiResponse(responseCode = "401", description = "Unauthorized", content = @Content(schema = @Schema(hidden = true))), + @ApiResponse(responseCode = "403", description = "Forbidden", content = @Content(schema = @Schema(hidden = true))), + @ApiResponse(responseCode = "404", description = "Not Found", content = @Content(schema = @Schema(hidden = true))) }) public VerificationResponseDTO getChannelVerificationStatus(@RequestParam("channel") String channel, @RequestParam("individualId") String individualId) throws ResidentServiceCheckedException, NoSuchAlgorithmException, ApisResourceAccessException { logger.info("getChannelVerificationStatus method started"); - validator.validateChannelVerificationStatus(channel, individualId); - VerificationResponseDTO verificationResponseDTO = verificationServiceImpl.checkChannelVerificationStatus(channel, individualId); - return verificationResponseDTO; - } + VerificationResponseDTO verificationResponseDTO; + try { + validator.validateChannelVerificationStatus(channel, individualId); + verificationResponseDTO = verificationService.checkChannelVerificationStatus(channel, individualId); + } catch (ResidentServiceCheckedException | ResidentServiceException | InvalidInputException e) { + audit.setAuditRequestDto(EventEnum.VERIFICATION_STATUS_FAILURE); + e.setMetadata(Map.of(ResidentConstants.REQ_RES_ID, ResidentConstants.VERIFICATION_STATUS_ID)); + throw e; + } + audit.setAuditRequestDto(EventEnum.VERIFICATION_STATUS_SUCCESS); + return verificationResponseDTO; + } } diff --git a/resident/resident-service/src/main/java/io/mosip/resident/controller/WebSubCredentialStatusUpdateController.java b/resident/resident-service/src/main/java/io/mosip/resident/controller/WebSubCredentialStatusUpdateController.java new file mode 100644 index 00000000000..22defbbad9f --- /dev/null +++ b/resident/resident-service/src/main/java/io/mosip/resident/controller/WebSubCredentialStatusUpdateController.java @@ -0,0 +1,90 @@ +package io.mosip.resident.controller; + +import java.util.Map; + +import org.apache.commons.lang3.exception.ExceptionUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RestController; + +import io.mosip.kernel.core.logger.spi.Logger; +import io.mosip.kernel.core.websub.spi.SubscriptionClient; +import io.mosip.kernel.websub.api.annotation.PreAuthenticateContentAndVerifyIntent; +import io.mosip.kernel.websub.api.model.SubscriptionChangeRequest; +import io.mosip.kernel.websub.api.model.SubscriptionChangeResponse; +import io.mosip.kernel.websub.api.model.UnsubscriptionRequest; +import io.mosip.resident.config.LoggerConfiguration; +import io.mosip.resident.constant.LoggerFileConstant; +import io.mosip.resident.constant.ResidentErrorCode; +import io.mosip.resident.exception.ApisResourceAccessException; +import io.mosip.resident.exception.ResidentServiceCheckedException; +import io.mosip.resident.exception.ResidentServiceException; +import io.mosip.resident.service.WebSubCredentialStatusUpdateService; +import io.mosip.resident.util.AuditUtil; +import io.mosip.resident.util.EventEnum; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import io.swagger.v3.oas.annotations.responses.ApiResponses; +import io.swagger.v3.oas.annotations.tags.Tag; + +/** + * API to update the resident transaction status from the credential status + * update in the websub event. + * + * @author Loganathan S + * + */ +@RestController +@Tag(name="WebSubCredentialStatusUpdateController", description="WebSubCredentialStatusUpdateController") +public class WebSubCredentialStatusUpdateController { + + private static Logger logger = LoggerConfiguration.logConfig(WebSubCredentialStatusUpdateController.class); + + @Autowired + SubscriptionClient subscribe; + + @Autowired + private WebSubCredentialStatusUpdateService webSubCredentialStatusUpdateService; + + @Autowired + private AuditUtil auditUtil; + + @PostMapping(value = "/callback/credentialStatusUpdate", consumes = "application/json") + @Operation(summary = "WebSubCredentialStatusUpdateController", description = "WebSubCredentialStatusUpdateController", + tags = {"WebSubCredentialStatusUpdateController"}) + @ApiResponses(value = { + @ApiResponse(responseCode = "200", description = "OK"), + @ApiResponse(responseCode = "201", description = "Created", content = @Content(schema = @Schema(hidden = true))), + @ApiResponse(responseCode = "401", description = "Unauthorized", content = @Content(schema = @Schema(hidden = true))), + @ApiResponse(responseCode = "403", description = "Forbidden", content = @Content(schema = @Schema(hidden = true))), + @ApiResponse(responseCode = "404", description = "Not Found", content = @Content(schema = @Schema(hidden = true)))}) + + @PreAuthenticateContentAndVerifyIntent(secret = "${resident.websub.credential-status.secret}", callback = "${resident.websub.callback.credential-status.relative.url}", topic = "${resident.websub.credential-status.topic}") + public void credentialStatusUpdateCallback(@RequestBody Map eventModel) { + + logger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), + LoggerFileConstant.APPLICATIONID.toString(), + "WebSubCredentialStatusUpdateController :: credentialStatusUpdateCallback() :: Start"); + + try { + logger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), + LoggerFileConstant.APPLICATIONID.toString(), + "WebSubCredentialStatusUpdateController :: credentialStatusUpdateCallback() :: Start"); + auditUtil.setAuditRequestDto(EventEnum.CREDENTIAL_STATUS_UPDATE_CALL_BACK); + webSubCredentialStatusUpdateService.updateCredentialStatus(eventModel); + auditUtil.setAuditRequestDto(EventEnum.CREDENTIAL_STATUS_UPDATE_CALL_BACK_SUCCESS); + } catch (ResidentServiceCheckedException | ApisResourceAccessException e) { + logger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), + LoggerFileConstant.APPLICATIONID.toString(), + ResidentErrorCode.AUTH_TYPE_CALLBACK_NOT_AVAILABLE.getErrorCode() + + ResidentErrorCode.AUTH_TYPE_CALLBACK_NOT_AVAILABLE.getErrorMessage() + + ExceptionUtils.getStackTrace(e)); + auditUtil.setAuditRequestDto(EventEnum.CREDENTIAL_STATUS_UPDATE_CALL_BACK_FAILURE); + throw new ResidentServiceException(ResidentErrorCode.AUTH_TYPE_CALLBACK_NOT_AVAILABLE.getErrorCode(), + ResidentErrorCode.AUTH_TYPE_CALLBACK_NOT_AVAILABLE.getErrorMessage(), e); + } + } +} diff --git a/resident/resident-service/src/main/java/io/mosip/resident/controller/WebSubUpdateAuthTypeController.java b/resident/resident-service/src/main/java/io/mosip/resident/controller/WebSubUpdateAuthTypeController.java index 684cb0d938d..e4937ec71d6 100644 --- a/resident/resident-service/src/main/java/io/mosip/resident/controller/WebSubUpdateAuthTypeController.java +++ b/resident/resident-service/src/main/java/io/mosip/resident/controller/WebSubUpdateAuthTypeController.java @@ -1,5 +1,7 @@ package io.mosip.resident.controller; +import java.util.Map; + import org.apache.commons.lang3.exception.ExceptionUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PostMapping; @@ -7,7 +9,6 @@ import org.springframework.web.bind.annotation.RestController; import io.mosip.kernel.core.logger.spi.Logger; -import io.mosip.kernel.core.websub.model.EventModel; import io.mosip.kernel.core.websub.spi.SubscriptionClient; import io.mosip.kernel.websub.api.annotation.PreAuthenticateContentAndVerifyIntent; import io.mosip.kernel.websub.api.model.SubscriptionChangeRequest; @@ -57,30 +58,28 @@ public class WebSubUpdateAuthTypeController { @ApiResponse(responseCode = "404", description = "Not Found", content = @Content(schema = @Schema(hidden = true)))}) @PreAuthenticateContentAndVerifyIntent(secret = "${resident.websub.authtype-status.secret}", callback = "${resident.websub.callback.authtype-status.relative.url}", topic = "${resident.websub.authtype-status.topic}") - public void authTypeCallback(@RequestBody EventModel eventModel) { + public void authTypeCallback(@RequestBody Map eventModel) { - logger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), - LoggerFileConstant.APPLICATIONID.toString(), "WebSubUpdateAuthTypeController :: authTypeCallback() :: Start"); + logger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), + LoggerFileConstant.APPLICATIONID.toString(), + "WebSubUpdateAuthTypeController :: authTypeCallback() :: Start"); - if(eventModel.getEvent() != null && eventModel.getEvent().getData() != null) { - logger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), - LoggerFileConstant.APPLICATIONID.toString(), "WebSubUpdateAuthTypeController :: authTypeCallback() :: Start"); - try { - logger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), - LoggerFileConstant.APPLICATIONID.toString(), "WebSubUpdateAuthTypeController :: authTypeCallback() :: Start"); - auditUtil.setAuditRequestDto(EventEnum.AUTH_TYPE_CALL_BACK); - webSubUpdateAuthTypeService.updateAuthTypeStatus(eventModel); - auditUtil.setAuditRequestDto(EventEnum.AUTH_TYPE_CALL_BACK_SUCCESS); - } catch (ResidentServiceCheckedException | ApisResourceAccessException e) { - logger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), - LoggerFileConstant.APPLICATIONID.toString(), - ResidentErrorCode.AUTH_TYPE_CALLBACK_NOT_AVAILABLE.getErrorCode() - + ResidentErrorCode.AUTH_TYPE_CALLBACK_NOT_AVAILABLE.getErrorMessage() - + ExceptionUtils.getStackTrace(e)); - auditUtil.setAuditRequestDto(EventEnum.AUTH_TYPE_CALL_BACK_FAILURE); - throw new ResidentServiceException(ResidentErrorCode.AUTH_TYPE_CALLBACK_NOT_AVAILABLE.getErrorCode(), - ResidentErrorCode.AUTH_TYPE_CALLBACK_NOT_AVAILABLE.getErrorMessage(), e); - } - } - } + try { + logger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), + LoggerFileConstant.APPLICATIONID.toString(), + "WebSubUpdateAuthTypeController :: authTypeCallback() :: Start"); + auditUtil.setAuditRequestDto(EventEnum.AUTH_TYPE_CALL_BACK); + webSubUpdateAuthTypeService.updateAuthTypeStatus(eventModel); + auditUtil.setAuditRequestDto(EventEnum.AUTH_TYPE_CALL_BACK_SUCCESS); + } catch (ResidentServiceCheckedException | ApisResourceAccessException e) { + logger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), + LoggerFileConstant.APPLICATIONID.toString(), + ResidentErrorCode.AUTH_TYPE_CALLBACK_NOT_AVAILABLE.getErrorCode() + + ResidentErrorCode.AUTH_TYPE_CALLBACK_NOT_AVAILABLE.getErrorMessage() + + ExceptionUtils.getStackTrace(e)); + auditUtil.setAuditRequestDto(EventEnum.AUTH_TYPE_CALL_BACK_FAILURE); + throw new ResidentServiceException(ResidentErrorCode.AUTH_TYPE_CALLBACK_NOT_AVAILABLE.getErrorCode(), + ResidentErrorCode.AUTH_TYPE_CALLBACK_NOT_AVAILABLE.getErrorMessage(), e); + } + } } diff --git a/resident/resident-service/src/main/java/io/mosip/resident/dto/DynamicFieldCodeValueDTO.java b/resident/resident-service/src/main/java/io/mosip/resident/dto/DynamicFieldCodeValueDTO.java new file mode 100644 index 00000000000..9c4a4b14400 --- /dev/null +++ b/resident/resident-service/src/main/java/io/mosip/resident/dto/DynamicFieldCodeValueDTO.java @@ -0,0 +1,23 @@ +package io.mosip.resident.dto; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +/** + * @author Kamesh Shekhar Prasad + * Dynamic Field Code value Dto + */ +@Data +@AllArgsConstructor +@NoArgsConstructor +@JsonIgnoreProperties(ignoreUnknown = true) +public class DynamicFieldCodeValueDTO { + + private String code; + + private String value; + +} diff --git a/resident/resident-service/src/main/java/io/mosip/resident/dto/DynamicFieldConsolidateResponseDto.java b/resident/resident-service/src/main/java/io/mosip/resident/dto/DynamicFieldConsolidateResponseDto.java new file mode 100644 index 00000000000..7eb525a7e16 --- /dev/null +++ b/resident/resident-service/src/main/java/io/mosip/resident/dto/DynamicFieldConsolidateResponseDto.java @@ -0,0 +1,26 @@ +package io.mosip.resident.dto; + +import java.util.List; + +import io.swagger.annotations.ApiModel; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +/** + * @author Kamesh Shekhar Prasad + * Dynamic Field Consolidate Response Dto + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +@ApiModel(description = "Model representing a response of dynamic field get by name Request") +public class DynamicFieldConsolidateResponseDto { + + private String name; + + private String description; + + private List values; + +} diff --git a/resident/resident-service/src/main/java/io/mosip/resident/dto/IdentityDTO.java b/resident/resident-service/src/main/java/io/mosip/resident/dto/IdentityDTO.java index 95869972199..3606d8e1276 100644 --- a/resident/resident-service/src/main/java/io/mosip/resident/dto/IdentityDTO.java +++ b/resident/resident-service/src/main/java/io/mosip/resident/dto/IdentityDTO.java @@ -11,5 +11,6 @@ public class IdentityDTO { private String yearOfBirth; private String fullName; private String face; + private String dateOfBirth; } diff --git a/resident/resident-service/src/main/java/io/mosip/resident/dto/RegistrationCenterInfoResponseDto.java b/resident/resident-service/src/main/java/io/mosip/resident/dto/RegistrationCenterInfoResponseDto.java new file mode 100644 index 00000000000..2e7f7724fee --- /dev/null +++ b/resident/resident-service/src/main/java/io/mosip/resident/dto/RegistrationCenterInfoResponseDto.java @@ -0,0 +1,20 @@ +package io.mosip.resident.dto; + +import java.util.List; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +/** + * @author Ritik Jain + */ +@Data +@AllArgsConstructor +@NoArgsConstructor +public class RegistrationCenterInfoResponseDto extends RegistrationCenterResponseDto { + + /** The registration centers data. */ + private List data; + +} diff --git a/resident/resident-service/src/main/java/io/mosip/resident/dto/UserInfoDto.java b/resident/resident-service/src/main/java/io/mosip/resident/dto/UserInfoDto.java index a816f09ef5e..d96d36e1414 100644 --- a/resident/resident-service/src/main/java/io/mosip/resident/dto/UserInfoDto.java +++ b/resident/resident-service/src/main/java/io/mosip/resident/dto/UserInfoDto.java @@ -1,6 +1,5 @@ package io.mosip.resident.dto; -import java.time.LocalDateTime; import java.util.Map; import lombok.Data; @@ -16,7 +15,7 @@ public class UserInfoDto { private String fullName; - private LocalDateTime lastLogin; + private String lastLogin; private Map photo; diff --git a/resident/resident-service/src/main/java/io/mosip/resident/entity/ResidentTransactionEntity.java b/resident/resident-service/src/main/java/io/mosip/resident/entity/ResidentTransactionEntity.java index 2fa93572f25..a376a749e2a 100644 --- a/resident/resident-service/src/main/java/io/mosip/resident/entity/ResidentTransactionEntity.java +++ b/resident/resident-service/src/main/java/io/mosip/resident/entity/ResidentTransactionEntity.java @@ -11,6 +11,7 @@ import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; +import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; /** @@ -28,10 +29,12 @@ @Builder @NoArgsConstructor @AllArgsConstructor +@EqualsAndHashCode(onlyExplicitlyIncluded = true) public class ResidentTransactionEntity { @Id @Column(name = "event_id") + @EqualsAndHashCode.Include private String eventId; @Column(name = "request_trn_id") diff --git a/resident/resident-service/src/main/java/io/mosip/resident/exception/ApiExceptionHandler.java b/resident/resident-service/src/main/java/io/mosip/resident/exception/ApiExceptionHandler.java index 794ac02530b..f71e0100771 100644 --- a/resident/resident-service/src/main/java/io/mosip/resident/exception/ApiExceptionHandler.java +++ b/resident/resident-service/src/main/java/io/mosip/resident/exception/ApiExceptionHandler.java @@ -19,6 +19,7 @@ import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.http.converter.HttpMessageNotReadableException; +import org.springframework.security.access.AccessDeniedException; import org.springframework.util.MultiValueMap; import org.springframework.validation.FieldError; import org.springframework.web.bind.MethodArgumentNotValidException; @@ -225,6 +226,30 @@ public ResponseEntity> controlRequestException(Htt return getErrorResponseEntity(httpServletRequest, e, HttpStatus.BAD_REQUEST); } + @ExceptionHandler(VidAlreadyPresentException.class) + public ResponseEntity> controlRequestException(HttpServletRequest httpServletRequest, + final VidAlreadyPresentException e) throws IOException{ + ExceptionUtils.logRootCause(e); + logStackTrace(e); + return getErrorResponseEntity(httpServletRequest, e, HttpStatus.OK); + } + + @ExceptionHandler(VidCreationException.class) + public ResponseEntity> controlRequestException(HttpServletRequest httpServletRequest, + final VidCreationException e) throws IOException{ + ExceptionUtils.logRootCause(e); + logStackTrace(e); + return getErrorResponseEntity(httpServletRequest, e, HttpStatus.OK); + } + + @ExceptionHandler(VidRevocationException.class) + public ResponseEntity> controlRequestException(HttpServletRequest httpServletRequest, + final VidRevocationException e) throws IOException{ + ExceptionUtils.logRootCause(e); + logStackTrace(e); + return getErrorResponseEntity(httpServletRequest, e, HttpStatus.OK); + } + @ExceptionHandler(HttpMessageNotReadableException.class) public ResponseEntity> onHttpMessageNotReadable( final HttpServletRequest httpServletRequest, final HttpMessageNotReadableException e) throws IOException { @@ -316,6 +341,17 @@ public ResponseEntity> getApiResourceStackTraceHan logStackTrace(e); return createResponseEntity(errorResponse, e, HttpStatus.BAD_REQUEST); } + + @ExceptionHandler(AccessDeniedException.class) + public ResponseEntity> handleAccessDeniedException( + final HttpServletRequest httpServletRequest, final AccessDeniedException e) throws IOException { + ResponseWrapper errorResponse = setErrors(httpServletRequest); + ServiceError error = new ServiceError(ResidentErrorCode.FORBIDDEN.getErrorCode(), e.getMessage()); + errorResponse.getErrors().add(error); + ExceptionUtils.logRootCause(e); + logStackTrace(e); + return createResponseEntity(errorResponse, e, HttpStatus.FORBIDDEN); + } private static void logStackTrace(Exception e) { logger.error(ExceptionUtils.getStackTrace(e)); diff --git a/resident/resident-service/src/main/java/io/mosip/resident/exception/InvalidInputException.java b/resident/resident-service/src/main/java/io/mosip/resident/exception/InvalidInputException.java index 417057e3886..df9fd1ba1c3 100644 --- a/resident/resident-service/src/main/java/io/mosip/resident/exception/InvalidInputException.java +++ b/resident/resident-service/src/main/java/io/mosip/resident/exception/InvalidInputException.java @@ -1,9 +1,8 @@ package io.mosip.resident.exception; -import io.mosip.kernel.core.exception.BaseUncheckedException; import io.mosip.resident.constant.ResidentErrorCode; -public class InvalidInputException extends BaseUncheckedException { +public class InvalidInputException extends BaseResidentUncheckedExceptionWithMetadata { /** * diff --git a/resident/resident-service/src/main/java/io/mosip/resident/exception/VidAlreadyPresentException.java b/resident/resident-service/src/main/java/io/mosip/resident/exception/VidAlreadyPresentException.java index 38d74f4b2b3..a1ee87c87ad 100644 --- a/resident/resident-service/src/main/java/io/mosip/resident/exception/VidAlreadyPresentException.java +++ b/resident/resident-service/src/main/java/io/mosip/resident/exception/VidAlreadyPresentException.java @@ -22,10 +22,14 @@ public VidAlreadyPresentException() { * @param errorMessage the error message */ public VidAlreadyPresentException(String errorCode, String errorMessage) { - super(errorCode, errorMessage); + super(errorCode, ResidentErrorCode.VID_ALREADY_PRESENT.getErrorMessage()); + } + + public VidAlreadyPresentException(String errorMessage, Throwable cause) { + super(ResidentErrorCode.VID_ALREADY_PRESENT.getErrorCode(), ResidentErrorCode.VID_ALREADY_PRESENT.getErrorMessage(), cause); } public VidAlreadyPresentException(String errorMessage, Throwable rootCause, Map metadata) { - super(ResidentErrorCode.VID_ALREADY_PRESENT.getErrorCode(), errorMessage, rootCause, metadata); + super(ResidentErrorCode.VID_ALREADY_PRESENT.getErrorCode(), ResidentErrorCode.VID_ALREADY_PRESENT.getErrorMessage(), rootCause, metadata); } } diff --git a/resident/resident-service/src/main/java/io/mosip/resident/filter/LoggingFilter.java b/resident/resident-service/src/main/java/io/mosip/resident/filter/LoggingFilter.java new file mode 100644 index 00000000000..1449c8226d8 --- /dev/null +++ b/resident/resident-service/src/main/java/io/mosip/resident/filter/LoggingFilter.java @@ -0,0 +1,87 @@ +package io.mosip.resident.filter; + +import java.io.IOException; +import java.util.Iterator; +import java.util.stream.Collectors; + +import javax.servlet.Filter; +import javax.servlet.FilterChain; +import javax.servlet.FilterConfig; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.HttpServletRequest; + +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.stereotype.Component; + +import io.mosip.kernel.core.logger.spi.Logger; +import io.mosip.kernel.core.util.DateUtils; +import io.mosip.resident.config.LoggerConfiguration; + +/** + * Logging filter - used to log the request for debugging purpose + * + * @author Loganathan S + * + */ +@Component +@ConditionalOnProperty(value = "resident.logging.filter.enabled", havingValue = "true", matchIfMissing = false) +public class LoggingFilter implements Filter { + + private static final Logger logger = LoggerConfiguration.logConfig(LoggingFilter.class); + + @Override + public void init(FilterConfig filterConfig) throws ServletException { + } + + @Override + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) + throws IOException, ServletException { + logger.debug("Beginning to process request at: " + DateUtils.getUTCCurrentDateTime()); + ServletRequest requestRef; + if (!(request instanceof RepeatableStreamHttpServletRequest) && request instanceof HttpServletRequest) { + //Since it is already RepeatableStreamHttpServletRequest, we can use the same + HttpServletRequest httpServletRequest = (HttpServletRequest) request; + RepeatableStreamHttpServletRequest reusableRequest = new RepeatableStreamHttpServletRequest( + httpServletRequest); + logger.debug("URI: " + httpServletRequest.getRequestURI()); + requestRef = reusableRequest; + printHeaders(reusableRequest); + printBody(reusableRequest); + } else { + requestRef = request; + } + chain.doFilter(requestRef, response); + logger.debug("Request processed at: " + DateUtils.getUTCCurrentDateTime()); + } + + private void printBody(ServletRequest request) throws IOException { + if(request instanceof HttpServletRequest) { + HttpServletRequest httpServletRequest = (HttpServletRequest) request; + String body = httpServletRequest.getReader().lines().collect(Collectors.joining(System.lineSeparator())); + if(!body.isEmpty()) { + logger.debug(String.format("Body: %s", body)); + } + } + } + + private void printHeaders(ServletRequest request) { + if(request instanceof HttpServletRequest) { + HttpServletRequest httpServletRequest = (HttpServletRequest) request; + Iterator headerNames = httpServletRequest.getHeaderNames().asIterator(); + StringBuffer headers = new StringBuffer(); + headerNames.forEachRemaining(header -> headers.append(String.format("%s -> %s; ", header, httpServletRequest.getHeader(header)))); + logger.debug(String.format("Headers: %s", headers)); + String headersTxt = headers.toString(); + if(!headersTxt.isEmpty()) { + logger.debug(String.format("Headers: %s", headersTxt)); + } + } + } + + @Override + public void destroy() { + } + +} diff --git a/resident/resident-service/src/main/java/io/mosip/resident/filter/RepeatableStreamHttpServletRequest.java b/resident/resident-service/src/main/java/io/mosip/resident/filter/RepeatableStreamHttpServletRequest.java new file mode 100644 index 00000000000..0bfc0ce15fb --- /dev/null +++ b/resident/resident-service/src/main/java/io/mosip/resident/filter/RepeatableStreamHttpServletRequest.java @@ -0,0 +1,205 @@ +package io.mosip.resident.filter; + +import java.io.BufferedReader; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.Map; + +import javax.servlet.ReadListener; +import javax.servlet.ServletInputStream; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletRequestWrapper; + +import org.springframework.util.StreamUtils; + +import io.mosip.resident.util.ObjectWithMetadata; + +/** + * The request wrapper used in filter that allows to re-read the request + * body. + * + * @author Loganathan Sekar + */ +public class RepeatableStreamHttpServletRequest extends HttpServletRequestWrapper implements ObjectWithMetadata { + + /** The raw data. */ + private byte[] rawData; + + /** The request. */ + private HttpServletRequest request; + + /** The servlet stream. */ + private RepeatableServletInputStream servletStream; + + private Map metadata; + + /** + * Instantiates a new resettable stream http servlet request. + * + * @param request the request + */ + public RepeatableStreamHttpServletRequest(HttpServletRequest request) { + super(request); + this.request = request; + this.servletStream = new RepeatableServletInputStream(); + } + + /** + * Reset input stream. + */ + public void resetInputStream() { + servletStream.stream = createServletInputStream(); + } + + private RepeatableServletInputStream createServletInputStream() { + return new RepeatableServletInputStream(new ByteArrayInputStream(rawData)); + } + + /* + * (non-Javadoc) + * + * @see javax.servlet.ServletRequestWrapper#getInputStream() + */ + @Override + public ServletInputStream getInputStream() throws IOException { + if (rawData == null) { + rawData = StreamUtils.copyToByteArray(this.request.getInputStream()); + servletStream.stream = createServletInputStream(); + } + RepeatableServletInputStream servletStreamOldRef = servletStream; + //Reset the servlet stream with a new copy + resetInputStream(); + //Return the old copy of servlet stream + return servletStreamOldRef; + } + + /* + * (non-Javadoc) + * + * @see javax.servlet.ServletRequestWrapper#getReader() + */ + @Override + public BufferedReader getReader() throws IOException { + if (rawData == null) { + rawData = StreamUtils.copyToByteArray(this.request.getInputStream()); + servletStream.stream = createServletInputStream(); + } + RepeatableServletInputStream servletStreamOldRef = servletStream; + //Reset the servlet stream with a new copy + resetInputStream(); + //Return the reader with the old copy of servlet stream + return new BufferedReader(new InputStreamReader(servletStreamOldRef)); + } + + /** + * Replace the request data with the given bytes + * + * @param newData the new data to be replaced with + */ + public void replaceData(byte[] newData) { + rawData = newData; + servletStream.stream = new ByteArrayInputStream(rawData); + } + + /** + * The Class RepeatableServletInputStream - used in + * RepeatableServletInputStream + */ + private class RepeatableServletInputStream extends ServletInputStream { + + /** The stream. */ + private InputStream stream; + + /** The eof reached. */ + private boolean eofReached; + + /** The closed. */ + private boolean closed; + + /** + * Instantiates a new resettable servlet input stream. + * + * @param stream the stream + */ + public RepeatableServletInputStream(InputStream stream) { + this.stream = stream; + } + + /** + * Instantiates a new resettable servlet input stream. + */ + public RepeatableServletInputStream() { + } + + /* + * (non-Javadoc) + * + * @see java.io.InputStream#read() + */ + @Override + public int read() throws IOException { + int val = stream.read(); + if (val == -1) { + eofReached = true; + } + return val; + } + + /* + * (non-Javadoc) + * + * @see javax.servlet.ServletInputStream#isFinished() + */ + @Override + public boolean isFinished() { + return eofReached; + } + + /* + * (non-Javadoc) + * + * @see javax.servlet.ServletInputStream#isReady() + */ + @Override + public boolean isReady() { + return !eofReached && !closed; + } + + /* + * (non-Javadoc) + * + * @see java.io.InputStream#close() + */ + @Override + public void close() throws IOException { + super.close(); + closed = true; + } + + /* + * (non-Javadoc) + * + * @see javax.servlet.ServletInputStream#setReadListener(javax.servlet. + * ReadListener) + */ + @Override + public void setReadListener(ReadListener listener) { + // Nothing to do + } + } + + @Override + public Map getMetadata() { + return metadata; + } + + @Override + public void setMetadata(Map metadata) { + this.metadata = metadata; + + } + + +} diff --git a/resident/resident-service/src/main/java/io/mosip/resident/filter/WebsubCallbackRequestDecoratorFilter.java b/resident/resident-service/src/main/java/io/mosip/resident/filter/WebsubCallbackRequestDecoratorFilter.java new file mode 100644 index 00000000000..c6daf9f4153 --- /dev/null +++ b/resident/resident-service/src/main/java/io/mosip/resident/filter/WebsubCallbackRequestDecoratorFilter.java @@ -0,0 +1,54 @@ +package io.mosip.resident.filter; + +import java.io.IOException; + +import javax.servlet.Filter; +import javax.servlet.FilterChain; +import javax.servlet.FilterConfig; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.HttpServletRequest; + +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.stereotype.Component; + +/** + * Servlet filter creating a repeatable servlet request wrapper to allow re-read + * of the request by the {@code WebSubClientAspect}. This was added because + * of the issue with the aspect was not able to get the request body for the signature + * verification as the request is already read by the spring framework message + * converter ({@code AbstractMessageConverterMethodArgumentResolver}. + * + * @author Loganathan S + * + */ +@Component +@ConditionalOnProperty(value = "resident.websub.request.decorator.filter.enabled", havingValue = "true", matchIfMissing = true) +public class WebsubCallbackRequestDecoratorFilter implements Filter { + + @Override + public void init(FilterConfig filterConfig) throws ServletException { + } + + @Override + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) + throws IOException, ServletException { + if (request instanceof RepeatableStreamHttpServletRequest) { + //Since it is already RepeatableStreamHttpServletRequest, we can use the same + chain.doFilter(request, response); + } else if (request instanceof HttpServletRequest) { + HttpServletRequest httpServletRequest = (HttpServletRequest) request; + RepeatableStreamHttpServletRequest reusableRequest = new RepeatableStreamHttpServletRequest( + httpServletRequest); + chain.doFilter(reusableRequest, response); + } else { + chain.doFilter(request, response); + } + } + + @Override + public void destroy() { + } + +} diff --git a/resident/resident-service/src/main/java/io/mosip/resident/function/FiveArgsFunction.java b/resident/resident-service/src/main/java/io/mosip/resident/function/FiveArgsFunction.java new file mode 100644 index 00000000000..c80c03396e7 --- /dev/null +++ b/resident/resident-service/src/main/java/io/mosip/resident/function/FiveArgsFunction.java @@ -0,0 +1,29 @@ +package io.mosip.resident.function; + +/** + * + * @author Loganathan Sekar + * + * @param Type Argument 1 + * @param Type Argument 2 + * @param Type Argument 3 + * @param Type Argument 4 + * @param Type Argument 5 + * @param Return type + */ +@FunctionalInterface +public interface FiveArgsFunction { + + /** + * Applies this function to the given arguments. + * + * @param t the first function argument + * @param u the second function argument + * @param v the third function argument + * @param w the fourth function argument + * @param w the fifth function argument + * @return the function result + */ + R apply(T t, U u, V v, W w, X x); + +} diff --git a/resident/resident-service/src/main/java/io/mosip/resident/function/FourArgsFunction.java b/resident/resident-service/src/main/java/io/mosip/resident/function/FourArgsFunction.java new file mode 100644 index 00000000000..ef320ac035d --- /dev/null +++ b/resident/resident-service/src/main/java/io/mosip/resident/function/FourArgsFunction.java @@ -0,0 +1,27 @@ +package io.mosip.resident.function; + +/** + * + * @author Loganathan Sekar + * + * @param Type Argument 1 + * @param Type Argument 2 + * @param Type Argument 3 + * @param Type Argument 4 + * @param Return type + */ +@FunctionalInterface +public interface FourArgsFunction { + + /** + * Applies this function to the given arguments. + * + * @param t the first function argument + * @param u the second function argument + * @param v the third function argument + * @param w the fourth function argument + * @return the function result + */ + R apply(T t, U u, V v, W w); + +} diff --git a/resident/resident-service/src/main/java/io/mosip/resident/handler/service/ResidentConfigService.java b/resident/resident-service/src/main/java/io/mosip/resident/handler/service/ResidentConfigService.java index 0a1cc4bd9aa..5a30fdb0903 100644 --- a/resident/resident-service/src/main/java/io/mosip/resident/handler/service/ResidentConfigService.java +++ b/resident/resident-service/src/main/java/io/mosip/resident/handler/service/ResidentConfigService.java @@ -2,6 +2,7 @@ import java.io.IOException; import java.util.List; +import java.util.Map; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; @@ -38,7 +39,7 @@ public interface ResidentConfigService { * @throws JsonMappingException the json mapping exception * @throws IOException Signals that an I/O exception has occurred. */ - List getUiSchemaFilteredInputAttributes(String schemaType) throws JsonParseException, JsonMappingException, IOException; + List getUiSchemaFilteredInputAttributes(String schemaType); /** * Gets the Identity Mapping json @@ -47,4 +48,13 @@ public interface ResidentConfigService { */ String getIdentityMapping() throws ResidentServiceCheckedException; + List> getUISchemaData(String schemaType); + + /** + * Gets Cacheable UI Schema data + * + * @return the UI Schema data. + */ + Map>> getUISchemaCacheableData(String schemaType); + } diff --git a/resident/resident-service/src/main/java/io/mosip/resident/handler/service/ResidentUpdateService.java b/resident/resident-service/src/main/java/io/mosip/resident/handler/service/ResidentUpdateService.java index 52923ea5287..77b62ecd83c 100644 --- a/resident/resident-service/src/main/java/io/mosip/resident/handler/service/ResidentUpdateService.java +++ b/resident/resident-service/src/main/java/io/mosip/resident/handler/service/ResidentUpdateService.java @@ -68,7 +68,7 @@ public class ResidentUpdateService { RequestHandlerRequestValidator validator; @Value("${IDSchema.Version}") - private String idschemaVersion; + private String defaultIdSchemaVersion; @Autowired private IdSchemaUtil idSchemaUtil; @@ -104,8 +104,15 @@ public class ResidentUpdateService { private static final String VALUE = "value"; public PacketGeneratorResDto createPacket(ResidentUpdateDto request) throws BaseCheckedException, IOException { + return createPacket(request, defaultIdSchemaVersion); + } + + public PacketGeneratorResDto createPacket(ResidentUpdateDto request, String idSchemaVersion) throws BaseCheckedException, IOException { logger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.UIN.toString(), request.getIdValue(), "ResidentUpdateServiceImpl::createPacket()"); + if(idSchemaVersion == null){ + idSchemaVersion = defaultIdSchemaVersion; + } byte[] packetZipBytes = null; audit.setAuditRequestDto(EventEnum.CREATE_PACKET); PackerGeneratorFailureDto dto = new PackerGeneratorFailureDto(); @@ -152,8 +159,8 @@ public PacketGeneratorResDto createPacket(ResidentUpdateDto request) throws Base packetDto.setId(generateRegistrationId(request.getCenterId(), request.getMachineId())); packetDto.setSource(utilities.getDefaultSource()); packetDto.setProcess(RegistrationType.RES_UPDATE.toString()); - packetDto.setSchemaVersion(idschemaVersion); - packetDto.setSchemaJson(idSchemaUtil.getIdSchema(Double.valueOf(idschemaVersion))); + packetDto.setSchemaVersion(idSchemaVersion); + packetDto.setSchemaJson(idSchemaUtil.getIdSchema(Double.valueOf(idSchemaVersion))); packetDto.setFields(idMap); packetDto.setDocuments(map); packetDto.setMetaInfo(getRegistrationMetaData(request.getIdValue(), diff --git a/resident/resident-service/src/main/java/io/mosip/resident/helper/CredentialStatusUpdateHelper.java b/resident/resident-service/src/main/java/io/mosip/resident/helper/CredentialStatusUpdateHelper.java new file mode 100644 index 00000000000..f75d46c7cec --- /dev/null +++ b/resident/resident-service/src/main/java/io/mosip/resident/helper/CredentialStatusUpdateHelper.java @@ -0,0 +1,155 @@ +package io.mosip.resident.helper; + +import static io.mosip.resident.constant.ResidentConstants.NOTIFICATION_DATE_PATTERN; +import static io.mosip.resident.constant.ResidentConstants.NOTIFICATION_TIME_PATTERN; +import static io.mosip.resident.constant.ResidentConstants.NOTIFICATION_ZONE; +import static io.mosip.resident.constant.ResidentConstants.PUBLIC_URL; +import static io.mosip.resident.constant.ResidentConstants.RESIDENT; +import static io.mosip.resident.constant.ResidentConstants.STATUS; +import static io.mosip.resident.constant.ResidentConstants.STATUS_CODE; +import static io.mosip.resident.constant.ResidentConstants.URL; + +import java.util.List; +import java.util.Map; +import java.util.Optional; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Component; + +import io.mosip.kernel.core.logger.spi.Logger; +import io.mosip.kernel.core.util.DateUtils; +import io.mosip.resident.config.LoggerConfiguration; +import io.mosip.resident.constant.RequestType; +import io.mosip.resident.constant.TemplateType; +import io.mosip.resident.dto.NotificationRequestDtoV2; +import io.mosip.resident.entity.ResidentTransactionEntity; +import io.mosip.resident.exception.ApisResourceAccessException; +import io.mosip.resident.exception.ResidentServiceCheckedException; +import io.mosip.resident.repository.ResidentTransactionRepository; +import io.mosip.resident.service.NotificationService; +import io.mosip.resident.util.Utility; + +/** + * Helper to update the resident transaction status based on the credential + * status and to send bell/email/sms notifications accordingly + * + * @author Loganathan S + * + */ +@Component +public class CredentialStatusUpdateHelper { + + private final Logger logger = LoggerConfiguration.logConfig(CredentialStatusUpdateHelper.class); + + private static final String DEFAULT_NOTIF_DATE_PATTERN = "dd-MM-yyyy"; + private static final String DEFAULT_NOTIF_TIME_PATTERN = "HH:mm:ss"; + + @Autowired + private Environment env; + + @Value("${" + NOTIFICATION_DATE_PATTERN + ":" + DEFAULT_NOTIF_DATE_PATTERN + "}") + private String notificationDatePattern; + + @Autowired + private NotificationService notificationService; + + @Value("${" + NOTIFICATION_TIME_PATTERN + ":" + DEFAULT_NOTIF_TIME_PATTERN + "}") + private String notificationTimePattern; + + @Value("${" + NOTIFICATION_ZONE + "}") + private String notificationZone; + + @Value("${" + PUBLIC_URL + "}") + private String publicUrl; + + @Autowired + private ResidentTransactionRepository repo; + + @Value("#{'${resident.async.request.types}'.split(',')}") + private List requestTypeCodesToProcessInBatchJob; + + @Autowired + private Utility utility; + + private Optional getTemplateType(RequestType requestType, String newStatusCode) { + Optional templateType; + if (requestType.isSuccessStatus(env, newStatusCode)) { + templateType = Optional.of(TemplateType.SUCCESS); + } else if (requestType.isFailedStatus(env, newStatusCode)) { + templateType = Optional.of(TemplateType.FAILURE); + } else if (requestType.isInProgressStatus(env, newStatusCode)) { + templateType = Optional.of(TemplateType.IN_PROGRESS); + } else { + templateType = Optional.empty(); + } + return templateType; + } + + public void saveEntity(ResidentTransactionEntity txn) { + repo.save(txn); + } + + private void sendNotification(ResidentTransactionEntity txn, TemplateType templateType, RequestType requestType) + throws ResidentServiceCheckedException { + NotificationRequestDtoV2 notificationRequestDtoV2 = new NotificationRequestDtoV2(); + notificationRequestDtoV2.setTemplateType(templateType); + notificationRequestDtoV2.setRequestType(requestType); + notificationRequestDtoV2.setEventId(txn.getEventId()); + notificationRequestDtoV2.setId(txn.getIndividualId()); + notificationService.sendNotification(notificationRequestDtoV2); + } + + public void updateEntity(ResidentTransactionEntity txn) { + txn.setUpdBy(RESIDENT); + txn.setUpdDtimes(DateUtils.getUTCCurrentDateTime()); + saveEntity(txn); + } + + public void updateStatus(ResidentTransactionEntity txn, Map credentialStatus) + throws ResidentServiceCheckedException, ApisResourceAccessException { + String requestTypeCode = txn.getRequestTypeCode(); + RequestType requestType = RequestType.getRequestTypeFromString(requestTypeCode); + + if (!credentialStatus.isEmpty()) { + // Save the new status to the resident transaction entity + String newStatusCode = getStatusCode(credentialStatus); + // If the status did not change, don't process it + if (newStatusCode != null && !txn.getStatusCode().equals(newStatusCode)) { + logger.debug(String.format("updating status for : %s as %s", txn.getEventId(), newStatusCode)); + txn.setStatusCode(newStatusCode); + + // Save the reference link if any + String referenceLink = credentialStatus.get(URL); + if (referenceLink != null) { + logger.debug(String.format("saving reference link for : %s", txn.getEventId())); + txn.setReferenceLink(referenceLink); + } + + // Send Notification + if (requestType.isNotificationStatus(env, newStatusCode)) { + logger.debug(String.format("invoking notifications for status: %s", newStatusCode)); + requestType.preUpdateInBatchJob(env, utility, txn, credentialStatus, newStatusCode); + + // For bell notification + txn.setReadStatus(false); + // Email/SMS notification + Optional templateType = getTemplateType(requestType, newStatusCode); + if (templateType.isPresent()) { + sendNotification(txn, templateType.get(), requestType); + } + } + + updateEntity(txn); + repo.save(txn); + } + } + } + + private String getStatusCode(Map credentialStatus) { + String status = credentialStatus.get(STATUS); + return status == null ? credentialStatus.get(STATUS_CODE) : status; + } + +} diff --git a/resident/resident-service/src/main/java/io/mosip/resident/helper/ObjectStoreHelper.java b/resident/resident-service/src/main/java/io/mosip/resident/helper/ObjectStoreHelper.java index 8fffc750c31..cd17937b678 100644 --- a/resident/resident-service/src/main/java/io/mosip/resident/helper/ObjectStoreHelper.java +++ b/resident/resident-service/src/main/java/io/mosip/resident/helper/ObjectStoreHelper.java @@ -223,7 +223,7 @@ public String encryptDecryptData(String data, boolean toEncrypt, String applicat ResponseWrapper.class); if (Objects.nonNull(responseWrapper.getErrors()) && !responseWrapper.getErrors().isEmpty()) { logger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), - LoggerFileConstant.APPLICATIONID.toString(), responseWrapper.getErrors().get(0).getMessage()); + LoggerFileConstant.APPLICATIONID.toString(), responseWrapper.getErrors().get(0).getMessage() + " \n at: " + Thread.getAllStackTraces()); throw new ResidentServiceException(ResidentErrorCode.ENCRYPT_DECRYPT_ERROR.getErrorCode(), ResidentErrorCode.ENCRYPT_DECRYPT_ERROR.getErrorMessage()); } diff --git a/resident/resident-service/src/main/java/io/mosip/resident/repository/ResidentTransactionRepository.java b/resident/resident-service/src/main/java/io/mosip/resident/repository/ResidentTransactionRepository.java index c31f65e85d2..1cd0573495b 100644 --- a/resident/resident-service/src/main/java/io/mosip/resident/repository/ResidentTransactionRepository.java +++ b/resident/resident-service/src/main/java/io/mosip/resident/repository/ResidentTransactionRepository.java @@ -2,11 +2,10 @@ import java.time.LocalDateTime; import java.util.List; +import java.util.Optional; import javax.transaction.Transactional; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; @@ -23,137 +22,193 @@ */ @Repository public interface ResidentTransactionRepository extends JpaRepository { - List findByRequestTrnIdAndRefIdOrderByCrDtimesDesc(String requestTrnId, String refId); - List findByCredentialRequestId(String credentialRequestId); + List findByRequestTrnId(String requestTrnId); - ResidentTransactionEntity findTopByRequestTrnIdAndTokenIdAndStatusCodeOrderByCrDtimesDesc - (String requestTrnId, String tokenId, String statusCode); - ResidentTransactionEntity findTopByAidOrderByCrDtimesDesc(String aid); + ResidentTransactionEntity findTopByRequestTrnIdAndTokenIdAndStatusCodeInOrderByCrDtimesDesc + (String requestTrnId, String tokenId, List statusCodes); ResidentTransactionEntity findTopByRefIdAndStatusCodeOrderByCrDtimesDesc(String refId, String statusCode); - List findByTokenId(String token); - - @Query(value = "Select new ResidentTransactionEntity( eventId, statusComment , crDtimes, statusCode, updDtimes, requestTypeCode) " - + "from ResidentTransactionEntity where tokenId=:tokenId AND crDtimes>= :fromDateTime AND crDtimes<= :toDateTime " - + " AND authTypeCode in :residentTransactionType " + " AND (eventId like %:searchText%" - + " OR statusComment like %:searchText% " + " OR statusCode like %:searchText%) " - + "ORDER BY pinnedStatus DESC") - List findByTokenAndTransactionType(@Param("tokenId") String tokenId, - @Param("fromDateTime") LocalDateTime fromDateTime, @Param("toDateTime") LocalDateTime toDateTime, - @Param("residentTransactionType") List residentTransactionType, Pageable pagaeable, - @Param("searchText") String searchText); - - @Query(value = "Select new ResidentTransactionEntity( eventId, statusComment , crDtimes, statusCode, updDtimes, requestTypeCode) " - + "from ResidentTransactionEntity where tokenId=:tokenId " - + " AND authTypeCode in :residentTransactionType " + " AND (eventId like %:searchText%" - + " OR statusComment like %:searchText% " + " OR statusCode like %:searchText%) " - + " ORDER BY pinnedStatus DESC LIMIT :pageFetch OFFSET :pageStart", nativeQuery = true) - List findByTokenWithoutDate(@Param("tokenId") String tokenId, - @Param("residentTransactionType") List residentTransactionType, - @Param("pageStart") String pageStart, @Param("pageFetch") String pageFetch, - @Param("searchText") String searchText); - - @Query(value = "Select new ResidentTransactionEntity(aid) " - + "from ResidentTransactionEntity where tokenId=:tokenId " - + " AND authTypeCode =:residentTransactionType ORDER BY crDtimes DESC") - List findRequestIdByToken(@Param("tokenId") String tokenId, - @Param("residentTransactionType") String residentTransactionType, Pageable pagaeable); - - @Query(value = "Select new ResidentTransactionEntity( eventId, statusComment , crDtimes, statusCode, updDtimes, requestTypeCode) " - + "from ResidentTransactionEntity where tokenId=:tokenId AND crDtimes>= :fromDateTime AND crDtimes<= :toDateTime " - + " AND (eventId like %:searchText%" + " OR statusComment like %:searchText% " - + " OR statusCode like %:searchText%) " + "ORDER BY pinnedStatus DESC") - List findByTokenWithoutServiceType(@Param("tokenId") String tokenId, - @Param("fromDateTime") LocalDateTime fromDateTime, @Param("toDateTime") LocalDateTime toDateTime, - Pageable pagaeable, @Param("searchText") String searchText); - - @Query(value = "Select new ResidentTransactionEntity( eventId, statusComment , crDtimes, statusCode, updDtimes, requestTypeCode) " - + "from ResidentTransactionEntity where tokenId=:tokenId " + " AND (eventId like %:searchText%" - + " OR statusComment like %:searchText% " + " OR statusCode like %:searchText%) " - + " ORDER BY pinnedStatus DESC LIMIT :pageFetch OFFSET :pageStart", nativeQuery = true) - List findByTokenWithoutServiceTypeAndDate(@Param("tokenId") String tokenId, - @Param("pageStart") int pageStart, @Param("pageFetch") int pageFetch, - @Param("searchText") String searchText); - - public List findByStatusCodeInAndRequestTypeCodeInOrderByCrDtimesAsc(List statusCodes, List requestTypes); - - Long countByTokenId(String tokenId); - - @Query(value = "SELECT COUNT(*) from ResidentTransactionEntity where tokenId=:tokenId AND read_status='false' and requestTypeCode in (:requestTypes)") - Long countByIdAndUnreadStatusForRequestTypes(@Param("tokenId") String tokenId, @Param("requestTypes") List requestTypes); - - @Query(value = "SELECT COUNT(*) from ResidentTransactionEntity where tokenId=:tokenId AND (crDtimes>= :notificationClickTime OR updDtimes>= :notificationClickTime) AND read_status='false' AND requestTypeCode in (:requestTypes)") - Long countByIdAndUnreadStatusForRequestTypesAfterNotificationClick(@Param("tokenId") String tokenId,@Param("notificationClickTime") LocalDateTime notificationClickTime, @Param("requestTypes") List requestTypes); + public List findByStatusCodeInAndRequestTypeCodeInAndCredentialRequestIdIsNotNullOrderByCrDtimesAsc(List statusCodes, List requestTypes); + - @Query(value = "Select new ResidentTransactionEntity(eventId, requestSummary, statusCode,requestDtimes,requestTypeCode) " - + "from ResidentTransactionEntity where tokenId=:tokenId AND read_status='false' and requestTypeCode in (:requestTypes)") - List findByIdAndUnreadStatusForRequestTypes(@Param("tokenId") String tokenId, @Param("requestTypes") List requestTypes); + @Query(value = "SELECT COUNT(*) from ResidentTransactionEntity where tokenId=:tokenId AND read_status='false' and requestTypeCode in (:requestTypes) AND (olvPartnerId IS NULL OR olvPartnerId = :olvPartnerId)") + Long countByIdAndUnreadStatusForRequestTypes(@Param("tokenId") String tokenId, @Param("requestTypes") List requestTypes, @Param("olvPartnerId") String olvPartnerId); + + @Query(value = "SELECT COUNT(*) from ResidentTransactionEntity where tokenId=:tokenId AND (crDtimes>= :notificationClickTime OR updDtimes>= :notificationClickTime) AND read_status='false' AND requestTypeCode in (:requestTypes) AND (olvPartnerId IS NULL OR olvPartnerId = :olvPartnerId)") + Long countByIdAndUnreadStatusForRequestTypesAfterNotificationClick(@Param("tokenId") String tokenId,@Param("notificationClickTime") LocalDateTime notificationClickTime, @Param("requestTypes") List requestTypes, @Param("olvPartnerId") String olvPartnerId); - @Query(value = "SELECT COUNT(*) from ResidentTransactionEntity where ref_id=:hashrefid AND auth_type_code !='OTP_REQUESTED'") /** * AuthTransaction entries only will be expected here. This wouldn't fetch the otp Requested performed in resident service. */ - Integer findByrefIdandauthtype(@Param("hashrefid") String hashrefid); + @Query(value = "SELECT COUNT(*) from ResidentTransactionEntity where ref_id=:hashRefId AND auth_type_code like %:authType") + Integer findByRefIdAndAuthTypeCodeLike(@Param("hashRefId") String hashRefId, @Param("authType") String authType); @Modifying @Transactional @Query("update ResidentTransactionEntity set read_status='true' where event_id=:eventId") int updateReadStatus(@Param("eventId") String eventId); - Page findByTokenIdAndOlvPartnerIdIsNullOrOlvPartnerId(String tokenId, String olvPartnerId,Pageable pageable); - - Page findByTokenIdAndCrDtimesBetweenAndRequestTypeCodeInAndStatusCodeInAndEventIdLikeAndOlvPartnerIdIsNullOrOlvPartnerId( - String tokenId, - LocalDateTime startDate, - LocalDateTime endDate, - List requestTypeCodes, - List statusCodes, - String eventId, - String onlineVerificationPartnerId, Pageable pageable - ); - - Page findByEventIdLikeAndOlvPartnerIdIsNullOrOlvPartnerId(String eventId, String onlineVerificationPartnerId, Pageable pageable); - - Page findByTokenIdAndCrDtimesBetweenAndRequestTypeCodeInAndStatusCodeInAndOlvPartnerIdIsNullOrOlvPartnerId( - String tokenId, LocalDateTime startDate, LocalDateTime endDate, List requestTypeCodes, - List statusCodes, String onlineVerificationPartnerId, Pageable pageable); - - Page findByTokenIdAndCrDtimesBetweenAndRequestTypeCodeInAndEventIdLikeAndOlvPartnerIdIsNullOrOlvPartnerId( - String tokenId, LocalDateTime startDate, - LocalDateTime endDate, - List requestTypeCodes, String eventId, String onlineVerificationPartnerId, Pageable pageable); - - Page findByTokenIdAndCrDtimesBetweenAndStatusCodeInAndEventIdLikeAndOlvPartnerIdIsNullOrOlvPartnerId( - String tokenId, LocalDateTime startDate, LocalDateTime endDate, List statusCodes, String eventId, String onlineVerificationPartnerId, Pageable pageable); - - Page findByTokenIdAndRequestTypeCodeInAndStatusCodeInAndEventIdLikeAndOlvPartnerIdIsNullOrOlvPartnerId( - String tokenId, List requestTypeCodes, List statusCodes, String eventId, String onlineVerificationPartnerId, Pageable pageable); - - Page findByTokenIdAndRequestTypeCodeInAndStatusCodeInAndOlvPartnerIdIsNullOrOlvPartnerId( - String tokenId, List requestTypeCodes, List statusCodes, String onlineVerificationPartnerId, Pageable pageable); - - Page findByTokenIdAndRequestTypeCodeInAndEventIdLikeAndOlvPartnerIdIsNullOrOlvPartnerId( - String tokenId, List requestTypeCodes, String eventId, String onlineVerificationPartnerId, Pageable pageable); - - Page findByTokenIdAndStatusCodeInAndEventIdLikeAndOlvPartnerIdIsNullOrOlvPartnerId( - String tokenId, List statusCodes, String eventId, String onlineVerificationPartnerId, Pageable pageable); - - Page findByTokenIdAndCrDtimesBetweenAndEventIdLikeAndOlvPartnerIdIsNullOrOlvPartnerId( - String tokenId, LocalDateTime startDate, LocalDateTime endDate, String eventId, String onlineVerificationPartnerId, Pageable pageable); - - Page findByTokenIdAndCrDtimesBetweenAndStatusCodeInAndOlvPartnerIdIsNullOrOlvPartnerId( - String tokenId, LocalDateTime startDate, LocalDateTime endDate, List statusCodes, String onlineVerificationPartnerId, Pageable pageable); - - Page findByTokenIdAndCrDtimesBetweenAndRequestTypeCodeInAndOlvPartnerIdIsNullOrOlvPartnerId( - String tokenId, LocalDateTime startDate, LocalDateTime endDate, List requestTypeCodes, String onlineVerificationPartnerId, Pageable pageable); - - Page findByTokenIdAndCrDtimesBetweenAndOlvPartnerIdIsNullOrOlvPartnerId( - String tokenId, LocalDateTime startDate, LocalDateTime endDate, String onlineVerificationPartnerId, Pageable pageable); - - Page findByTokenIdAndRequestTypeCodeInAndOlvPartnerIdIsNullOrOlvPartnerId( - String tokenId, List requestTypeCodes, String onlineVerificationPartnerId, Pageable pageable); + Optional findOneByCredentialRequestId(String requestId); + + @Query(value = "SELECT * FROM resident_transaction WHERE token_id = :tokenId " + + " AND request_type_code IN (:requestTypeCodes) " + + "AND (olv_partner_id is null OR \n" + + "olv_partner_id=:olvPartnerId)" + + " order by pinned_status desc, " + + " cr_dtimes DESC LIMIT :limit OFFSET :offset", nativeQuery = true) + List findByTokenId(@Param("tokenId") String tokenId , @Param("limit") int limit, @Param("offset") int offset, + @Param("olvPartnerId") String olvPartnerId, + @Param("requestTypeCodes") List requestTypeCodes); + + @Query(value = "SELECT COUNT(*) FROM resident_transaction " + + "WHERE token_id = :tokenId " + + " AND request_type_code IN (:requestTypeCodes) " + + "AND (olv_partner_id is null OR \n" + + "olv_partner_id=:olvPartnerId)" , nativeQuery = true) + int countByTokenId(@Param("tokenId") String tokenId, @Param("olvPartnerId") String olvPartnerId, + @Param("requestTypeCodes") List requestTypeCodes); + + @Query(value = "SELECT * FROM resident_transaction WHERE token_id = :tokenId " + + " AND request_type_code IN (:requestTypeCodes) " + + "AND (olv_partner_id is null OR \n" + + "olv_partner_id=:olvPartnerId)" + + "AND event_id LIKE CONCAT('%', :eventId, '%') " + + " order by pinned_status desc, " + + " cr_dtimes DESC LIMIT :limit OFFSET :offset", nativeQuery = true) + List findByTokenIdAndSearchEventId(@Param("tokenId") String tokenId , @Param("limit") int limit, @Param("offset") int offset, + @Param("olvPartnerId") String olvPartnerId, + @Param("requestTypeCodes") List requestTypeCodes, @Param("eventId") String eventId); + + @Query(value = "SELECT COUNT(*) FROM resident_transaction " + + "WHERE token_id = :tokenId " + + " AND request_type_code IN (:requestTypeCodes) " + + "AND (olv_partner_id is null OR \n" + + "olv_partner_id=:olvPartnerId) " + + "AND event_id LIKE CONCAT('%', :eventId, '%') " + , nativeQuery = true) + int countByTokenIdAndSearchEventId(@Param("tokenId") String tokenId, @Param("olvPartnerId") String olvPartnerId, + @Param("requestTypeCodes") List requestTypeCodes , @Param("eventId") String eventId); + + @Query(value = "SELECT * FROM resident_transaction WHERE token_id = :tokenId " + + " AND request_type_code IN (:requestTypeCodes) " + + "AND (olv_partner_id is null OR \n" + + "olv_partner_id=:olvPartnerId)" + + "AND cr_dtimes BETWEEN :startDate AND :endDate " + + " order by pinned_status desc, " + + " cr_dtimes DESC LIMIT :limit OFFSET :offset", nativeQuery = true) + List findByTokenIdBetweenCrDtimes(@Param("tokenId") String tokenId , @Param("limit") int limit, @Param("offset") int offset, + @Param("olvPartnerId") String olvPartnerId, + @Param("requestTypeCodes") List requestTypeCodes, @Param("startDate") LocalDateTime startDate, + @Param("endDate") LocalDateTime endDate); + + @Query(value = "SELECT COUNT(*) FROM resident_transaction " + + "WHERE token_id = :tokenId " + + " AND request_type_code IN (:requestTypeCodes) " + + "AND (olv_partner_id is null OR \n" + + "olv_partner_id=:olvPartnerId)" + + "AND cr_dtimes BETWEEN :startDate AND :endDate ", nativeQuery = true) + int countByTokenIdBetweenCrDtimes(@Param("tokenId") String tokenId, @Param("olvPartnerId") String olvPartnerId, + @Param("requestTypeCodes") List requestTypeCodes, @Param("startDate") LocalDateTime startDate, + @Param("endDate") LocalDateTime endDate); + + @Query(value = "SELECT * FROM resident_transaction WHERE token_id = :tokenId " + + " AND request_type_code IN (:requestTypeCodes) " + + " AND status_code IN (:statusCode) " + + "AND (olv_partner_id is null OR \n" + + "olv_partner_id=:olvPartnerId)" + + " order by pinned_status desc, " + + " cr_dtimes DESC LIMIT :limit OFFSET :offset", nativeQuery = true) + List findByTokenIdInStatus(@Param("tokenId") String tokenId , @Param("limit") int limit, @Param("offset") int offset, + @Param("olvPartnerId") String olvPartnerId, + @Param("requestTypeCodes") List requestTypeCodes, + @Param("statusCode") List statusCode); + + @Query(value = "SELECT COUNT(*) FROM resident_transaction " + + "WHERE token_id = :tokenId " + + " AND request_type_code IN (:requestTypeCodes) " + + " AND status_code IN (:statusCode) " + + "AND (olv_partner_id is null OR \n" + + "olv_partner_id=:olvPartnerId)" , nativeQuery = true) + int countByTokenIdInStatus(@Param("tokenId") String tokenId, @Param("olvPartnerId") String olvPartnerId, + @Param("requestTypeCodes") List requestTypeCodes, + @Param("statusCode") List statusCode); + + @Query(value = "SELECT * FROM resident_transaction WHERE token_id = :tokenId " + + " AND request_type_code IN (:requestTypeCodes) " + + " AND status_code IN (:statusCode) " + + "AND (olv_partner_id is null OR \n" + + "olv_partner_id=:olvPartnerId)" + + "AND cr_dtimes BETWEEN :startDate AND :endDate " + + " order by pinned_status desc, " + + " cr_dtimes DESC LIMIT :limit OFFSET :offset", nativeQuery = true) + List findByTokenIdInStatusBetweenCrDtimes(@Param("tokenId") String tokenId , @Param("limit") int limit, @Param("offset") int offset, + @Param("olvPartnerId") String olvPartnerId, + @Param("requestTypeCodes") List requestTypeCodes, + @Param("statusCode") List statusCode, + @Param("startDate") LocalDateTime startDate, + @Param("endDate") LocalDateTime endDate); + + @Query(value = "SELECT COUNT(*) FROM resident_transaction " + + "WHERE token_id = :tokenId " + + " AND request_type_code IN (:requestTypeCodes) " + + " AND status_code IN (:statusCode) " + + "AND (olv_partner_id is null OR \n" + + "olv_partner_id=:olvPartnerId)"+ + "AND cr_dtimes BETWEEN :startDate AND :endDate ", nativeQuery = true) + int countByTokenIdInStatusBetweenCrDtimes(@Param("tokenId") String tokenId, @Param("olvPartnerId") String olvPartnerId, + @Param("requestTypeCodes") List requestTypeCodes, + @Param("statusCode") List statusCode, @Param("startDate") LocalDateTime startDate, + @Param("endDate") LocalDateTime endDate); + + @Query(value = "SELECT * FROM resident_transaction WHERE token_id = :tokenId " + + " AND request_type_code IN (:requestTypeCodes) " + + "AND (olv_partner_id is null OR \n" + + "olv_partner_id=:olvPartnerId)" + + "AND cr_dtimes BETWEEN :startDate AND :endDate " + + "AND event_id LIKE CONCAT('%', :eventId, '%') " + + " order by pinned_status desc, " + + " cr_dtimes DESC LIMIT :limit OFFSET :offset", nativeQuery = true) + List findByTokenIdBetweenCrDtimesSearchEventId(@Param("tokenId") String tokenId , @Param("limit") int limit, @Param("offset") int offset, + @Param("olvPartnerId") String olvPartnerId, + @Param("requestTypeCodes") List requestTypeCodes, + @Param("startDate") LocalDateTime startDate, + @Param("endDate") LocalDateTime endDate, @Param("eventId") String eventId); + + @Query(value = "SELECT COUNT(*) FROM resident_transaction " + + "WHERE token_id = :tokenId " + + " AND request_type_code IN (:requestTypeCodes) " + + "AND (olv_partner_id is null OR \n" + + "olv_partner_id=:olvPartnerId)" + + "AND cr_dtimes BETWEEN :startDate AND :endDate "+ + "AND event_id LIKE CONCAT('%', :eventId, '%') ", nativeQuery = true) + int countByTokenIdBetweenCrDtimesSearchEventId(@Param("tokenId") String tokenId, @Param("olvPartnerId") String olvPartnerId, + @Param("requestTypeCodes") List requestTypeCodes, @Param("startDate") LocalDateTime startDate, + @Param("endDate") LocalDateTime endDate, @Param("eventId") String eventId); + + @Query(value = "SELECT * FROM resident_transaction WHERE token_id = :tokenId " + + " AND request_type_code IN (:requestTypeCodes) " + + " AND status_code IN (:statusCode) " + + "AND (olv_partner_id is null OR \n" + + "olv_partner_id=:olvPartnerId)" + + "AND event_id LIKE CONCAT('%', :eventId, '%') " + + " order by pinned_status desc, " + + " cr_dtimes DESC LIMIT :limit OFFSET :offset", nativeQuery = true) + List findByTokenIdInStatusSearchEventId(@Param("tokenId") String tokenId , @Param("limit") int limit, @Param("offset") int offset, + @Param("olvPartnerId") String olvPartnerId, + @Param("requestTypeCodes") List requestTypeCodes, + @Param("statusCode") List statusCode, @Param("eventId") String eventId); + + @Query(value = "SELECT COUNT(*) FROM resident_transaction " + + "WHERE token_id = :tokenId " + + " AND request_type_code IN (:requestTypeCodes) " + + " AND status_code IN (:statusCode) " + + "AND (olv_partner_id is null OR \n" + + "olv_partner_id=:olvPartnerId)"+ + "AND event_id LIKE CONCAT('%', :eventId, '%') " , nativeQuery = true) + int countByTokenIdInStatusSearchEventId(@Param("tokenId") String tokenId, @Param("olvPartnerId") String olvPartnerId, + @Param("requestTypeCodes") List requestTypeCodes, + @Param("statusCode") List statusCode, @Param("eventId") String eventId); - Page findByTokenIdAndStatusCodeInAndOlvPartnerIdIsNullOrOlvPartnerId(String tokenId, List statusCodes, String onlineVerificationPartnerId, Pageable pageable); } diff --git a/resident/resident-service/src/main/java/io/mosip/resident/service/AcknowledgementService.java b/resident/resident-service/src/main/java/io/mosip/resident/service/AcknowledgementService.java index 44e726b9009..c12004fca21 100644 --- a/resident/resident-service/src/main/java/io/mosip/resident/service/AcknowledgementService.java +++ b/resident/resident-service/src/main/java/io/mosip/resident/service/AcknowledgementService.java @@ -9,5 +9,5 @@ * @Author Kamesh Shekhar Prasad */ public interface AcknowledgementService { - byte[] getAcknowledgementPDF(String eventId, String languageCode, int timeZoneOffset) throws ResidentServiceCheckedException, IOException; + byte[] getAcknowledgementPDF(String eventId, String languageCode, int timeZoneOffset, String locale) throws ResidentServiceCheckedException, IOException; } diff --git a/resident/resident-service/src/main/java/io/mosip/resident/service/AuthTransactionCallBackService.java b/resident/resident-service/src/main/java/io/mosip/resident/service/AuthTransactionCallBackService.java index 98ef4978ff0..4afa88dc9df 100644 --- a/resident/resident-service/src/main/java/io/mosip/resident/service/AuthTransactionCallBackService.java +++ b/resident/resident-service/src/main/java/io/mosip/resident/service/AuthTransactionCallBackService.java @@ -1,14 +1,14 @@ package io.mosip.resident.service; import java.security.NoSuchAlgorithmException; +import java.util.Map; import org.springframework.stereotype.Service; -import io.mosip.kernel.core.websub.model.EventModel; import io.mosip.resident.exception.ApisResourceAccessException; import io.mosip.resident.exception.ResidentServiceCheckedException; @Service public interface AuthTransactionCallBackService { - public void updateAuthTransactionCallBackService(EventModel eventModel) throws ResidentServiceCheckedException, ApisResourceAccessException, NoSuchAlgorithmException; + public void updateAuthTransactionCallBackService(Map eventModel) throws ResidentServiceCheckedException, ApisResourceAccessException, NoSuchAlgorithmException; } diff --git a/resident/resident-service/src/main/java/io/mosip/resident/service/DownLoadMasterDataService.java b/resident/resident-service/src/main/java/io/mosip/resident/service/DownLoadMasterDataService.java index 9f1e5d8d3f1..195d64ca439 100644 --- a/resident/resident-service/src/main/java/io/mosip/resident/service/DownLoadMasterDataService.java +++ b/resident/resident-service/src/main/java/io/mosip/resident/service/DownLoadMasterDataService.java @@ -2,7 +2,6 @@ import java.io.IOException; import java.io.InputStream; -import java.util.List; import org.springframework.stereotype.Service; @@ -25,7 +24,7 @@ public interface DownLoadMasterDataService { * @throws ResidentServiceCheckedException */ public InputStream downloadRegistrationCentersByHierarchyLevel(String langCode, Short hierarchyLevel, - List name) throws ResidentServiceCheckedException, IOException, Exception; + String name) throws ResidentServiceCheckedException, IOException, Exception; /** * diff --git a/resident/resident-service/src/main/java/io/mosip/resident/service/DownloadCardService.java b/resident/resident-service/src/main/java/io/mosip/resident/service/DownloadCardService.java index 2327a62db07..4dbd9e093e0 100644 --- a/resident/resident-service/src/main/java/io/mosip/resident/service/DownloadCardService.java +++ b/resident/resident-service/src/main/java/io/mosip/resident/service/DownloadCardService.java @@ -10,6 +10,7 @@ import io.mosip.resident.dto.ResponseWrapper; import io.mosip.resident.dto.VidDownloadCardResponseDto; import io.mosip.resident.exception.ApisResourceAccessException; +import io.mosip.resident.exception.ResidentServiceCheckedException; import reactor.util.function.Tuple2; /** @@ -17,11 +18,15 @@ * @Author Kamesh Shekhar Prasad */ public interface DownloadCardService { - Tuple2 getDownloadCardPDF(MainRequestDTO downloadCardRequestDTOMainRequestDTO); + Tuple2 getDownloadCardPDF( + MainRequestDTO downloadCardRequestDTOMainRequestDTO) + throws ResidentServiceCheckedException; - Tuple2 downloadPersonalizedCard(MainRequestDTO downloadPersonalizedCardMainRequestDTO, int timeZoneOffset); + Tuple2 downloadPersonalizedCard( + MainRequestDTO downloadPersonalizedCardMainRequestDTO, int timeZoneOffset, String locale) + throws ResidentServiceCheckedException; - Tuple2, String> getVidCardEventId(String vid, int timeZoneOffset) throws BaseCheckedException; + Tuple2, String> getVidCardEventId(String vid, int timeZoneOffset, String locale) throws BaseCheckedException; - ResponseWrapper getIndividualIdStatus(String vid) throws ApisResourceAccessException, IOException; + ResponseWrapper getIndividualIdStatus(String vid) throws ApisResourceAccessException, IOException, ResidentServiceCheckedException; } diff --git a/resident/resident-service/src/main/java/io/mosip/resident/service/IdAuthService.java b/resident/resident-service/src/main/java/io/mosip/resident/service/IdAuthService.java index 35d2ce7a1f5..5b53d470c6b 100644 --- a/resident/resident-service/src/main/java/io/mosip/resident/service/IdAuthService.java +++ b/resident/resident-service/src/main/java/io/mosip/resident/service/IdAuthService.java @@ -6,7 +6,9 @@ import org.springframework.stereotype.Service; import io.mosip.resident.constant.AuthTypeStatus; +import io.mosip.resident.constant.RequestType; import io.mosip.resident.dto.AuthTxnDetailsDTO; +import io.mosip.resident.entity.ResidentTransactionEntity; import io.mosip.resident.exception.ApisResourceAccessException; import io.mosip.resident.exception.OtpValidationFailedException; import io.mosip.resident.exception.ResidentServiceCheckedException; @@ -21,10 +23,7 @@ public boolean validateOtp(String transactionID, String individualId, String otp public Tuple2 validateOtpV1(String transactionId, String individualId, String otp) throws OtpValidationFailedException, ResidentServiceCheckedException; - public boolean validateOtpv2(String transactionId, String individualId, String otp) - throws OtpValidationFailedException, ResidentServiceCheckedException; - - public Tuple2 validateOtpV2(String transactionId, String individualId, String otp) + public Tuple2 validateOtpV2(String transactionId, String individualId, String otp, RequestType requestType) throws OtpValidationFailedException, ResidentServiceCheckedException; public boolean authTypeStatusUpdate(String individualId, List authType, diff --git a/resident/resident-service/src/main/java/io/mosip/resident/service/OtpManager.java b/resident/resident-service/src/main/java/io/mosip/resident/service/OtpManager.java new file mode 100644 index 00000000000..e0cb57eee3c --- /dev/null +++ b/resident/resident-service/src/main/java/io/mosip/resident/service/OtpManager.java @@ -0,0 +1,19 @@ +package io.mosip.resident.service; + +import java.io.IOException; + +import io.mosip.resident.dto.MainRequestDTO; +import io.mosip.resident.dto.OtpRequestDTOV2; +import io.mosip.resident.exception.ApisResourceAccessException; +import io.mosip.resident.exception.ResidentServiceCheckedException; +import reactor.util.function.Tuple2; + +/** + * @author Kamesh Shekhar Prasad + * This interface is used to create method declaration for sending and validating otp. + */ +public interface OtpManager { + public boolean sendOtp(MainRequestDTO requestDTO, String channelType, String language) throws IOException, ResidentServiceCheckedException, ApisResourceAccessException; + public boolean validateOtp(String otp, String userId, String transactionId) throws ApisResourceAccessException, ResidentServiceCheckedException; + public Tuple2 updateUserId(String userId, String transactionId) throws ApisResourceAccessException, ResidentServiceCheckedException, IOException; +} diff --git a/resident/resident-service/src/main/java/io/mosip/resident/service/PinUnpinStatusService.java b/resident/resident-service/src/main/java/io/mosip/resident/service/PinUnpinStatusService.java index 0aa517172db..a26589a97a3 100644 --- a/resident/resident-service/src/main/java/io/mosip/resident/service/PinUnpinStatusService.java +++ b/resident/resident-service/src/main/java/io/mosip/resident/service/PinUnpinStatusService.java @@ -4,6 +4,7 @@ import io.mosip.kernel.core.http.ResponseWrapper; import io.mosip.resident.dto.ResponseDTO; +import io.mosip.resident.exception.ResidentServiceCheckedException; /** * This class is service class of pin or unpin status api based on event id. @@ -11,6 +12,6 @@ */ @Service public interface PinUnpinStatusService { - ResponseWrapper pinStatus(String eventId, boolean status); + ResponseWrapper pinStatus(String eventId, boolean status) throws ResidentServiceCheckedException; } diff --git a/resident/resident-service/src/main/java/io/mosip/resident/service/ProxyMasterdataService.java b/resident/resident-service/src/main/java/io/mosip/resident/service/ProxyMasterdataService.java index 381df0513de..bcccac33f3c 100644 --- a/resident/resident-service/src/main/java/io/mosip/resident/service/ProxyMasterdataService.java +++ b/resident/resident-service/src/main/java/io/mosip/resident/service/ProxyMasterdataService.java @@ -152,13 +152,15 @@ public ResponseWrapper getAllTemplateBylangCodeAndTemplateTypeCode(String lan throws ResidentServiceCheckedException; /** - * Get gender types by language code. - * - * @param langCode - * @return ResponseWrapper object - * @throws ResidentServiceCheckedException - */ - public ResponseWrapper getGenderTypesByLangCode(String langCode) throws ResidentServiceCheckedException; + * Get gender types by language code. + * + * @param fieldName + * @param langCode + * @param withValue + * @return ResponseWrapper object + * @throws ResidentServiceCheckedException + */ + public ResponseWrapper getDynamicFieldBasedOnLangCodeAndFieldName(String fieldName, String langCode, boolean withValue) throws ResidentServiceCheckedException; public ResponseWrapper getDocumentTypesByDocumentCategoryAndLangCode(String documentcategorycode, String langCode) throws ResidentServiceCheckedException; diff --git a/resident/resident-service/src/main/java/io/mosip/resident/service/ProxyOtpService.java b/resident/resident-service/src/main/java/io/mosip/resident/service/ProxyOtpService.java new file mode 100644 index 00000000000..5352a84fb0a --- /dev/null +++ b/resident/resident-service/src/main/java/io/mosip/resident/service/ProxyOtpService.java @@ -0,0 +1,20 @@ +package io.mosip.resident.service; + +import org.springframework.http.ResponseEntity; + +import io.mosip.kernel.core.authmanager.model.AuthNResponse; +import io.mosip.resident.dto.MainRequestDTO; +import io.mosip.resident.dto.MainResponseDTO; +import io.mosip.resident.dto.OtpRequestDTOV2; +import io.mosip.resident.dto.OtpRequestDTOV3; +import reactor.util.function.Tuple2; + +/** + * @Author Kamesh Shekhar Prasad + * This class is used to do operations on otp. + */ +public interface ProxyOtpService { + ResponseEntity> sendOtp(MainRequestDTO userOtpRequest); + + Tuple2, String> validateWithUserIdOtp(MainRequestDTO userIdOtpRequest); +} diff --git a/resident/resident-service/src/main/java/io/mosip/resident/service/ResidentCredentialService.java b/resident/resident-service/src/main/java/io/mosip/resident/service/ResidentCredentialService.java index f339f806418..9fa456d5851 100644 --- a/resident/resident-service/src/main/java/io/mosip/resident/service/ResidentCredentialService.java +++ b/resident/resident-service/src/main/java/io/mosip/resident/service/ResidentCredentialService.java @@ -1,5 +1,7 @@ package io.mosip.resident.service; +import java.util.List; + import io.mosip.resident.dto.CredentialCancelRequestResponseDto; import io.mosip.resident.dto.CredentialRequestStatusResponseDto; import io.mosip.resident.dto.CredentialTypeResponse; @@ -8,6 +10,7 @@ import io.mosip.resident.dto.ResidentCredentialResponseDto; import io.mosip.resident.dto.ResidentCredentialResponseDtoV2; import io.mosip.resident.dto.ResponseWrapper; +import io.mosip.resident.dto.SharableAttributesDTO; import io.mosip.resident.exception.ApisResourceAccessException; import io.mosip.resident.exception.ResidentServiceCheckedException; import reactor.util.function.Tuple2; @@ -17,11 +20,9 @@ public interface ResidentCredentialService { public ResidentCredentialResponseDto reqCredential(ResidentCredentialRequestDto request) throws ResidentServiceCheckedException; public ResidentCredentialResponseDto reqCredential(ResidentCredentialRequestDto request, String id) throws ResidentServiceCheckedException; - - public Tuple2 shareCredential(ResidentCredentialRequestDto request, String requestType) throws ResidentServiceCheckedException, ApisResourceAccessException; - - public Tuple2 shareCredential(ResidentCredentialRequestDto request, String requestType, String purpose) throws ResidentServiceCheckedException, ApisResourceAccessException; - + + public Tuple2 shareCredential(ResidentCredentialRequestDto request, String purpose, List sharableAttributes) throws ResidentServiceCheckedException, ApisResourceAccessException; + public CredentialRequestStatusResponseDto getStatus(String requestId) throws ResidentServiceCheckedException; public CredentialTypeResponse getCredentialTypes(); diff --git a/resident/resident-service/src/main/java/io/mosip/resident/service/ResidentService.java b/resident/resident-service/src/main/java/io/mosip/resident/service/ResidentService.java index 13a3c6f5ba2..faba0bed879 100644 --- a/resident/resident-service/src/main/java/io/mosip/resident/service/ResidentService.java +++ b/resident/resident-service/src/main/java/io/mosip/resident/service/ResidentService.java @@ -3,6 +3,7 @@ import java.io.IOException; import java.time.LocalDate; import java.time.LocalDateTime; +import java.util.List; import org.json.simple.JSONObject; @@ -56,21 +57,16 @@ public Tuple2 reqAauthTypeStatusUpdateV2(AuthLockOrUnLockRe RegStatusCheckResponseDTO getRidStatus(String rid); - AidStatusResponseDTO getAidStatus(AidStatusRequestDTO reqDto) - throws ResidentServiceCheckedException, ApisResourceAccessException, OtpValidationFailedException; - ResponseWrapper> getServiceHistory(Integer pageStart, Integer pageFetch, LocalDate fromDateTime, LocalDate toDateTime, String serviceType, String sortType, - String searchColumn, String searchText, String langCode, int timeZoneOffset) throws ResidentServiceCheckedException, ApisResourceAccessException; + String searchColumn, String searchText, String langCode, int timeZoneOffset, String locale) throws ResidentServiceCheckedException, ApisResourceAccessException; byte[] downloadCard(String eventId) throws ResidentServiceCheckedException; AidStatusResponseDTO getAidStatus(AidStatusRequestDTO reqDto, boolean performOtpValidation) throws ResidentServiceCheckedException, ApisResourceAccessException, OtpValidationFailedException; - String checkAidStatus(String aid) throws ResidentServiceCheckedException; - - ResponseWrapper getEventStatus(String id, String eventId, int timeZoneOffset) + ResponseWrapper getEventStatus(String id, String eventId, int timeZoneOffset, String locale) throws ResidentServiceCheckedException; ResponseWrapper getnotificationCount(String Id) throws ApisResourceAccessException, ResidentServiceCheckedException; @@ -79,15 +75,20 @@ ResponseWrapper getEventStatus(String id, String eventId int updatebellClickdttimes(String idaToken) throws ApisResourceAccessException, ResidentServiceCheckedException; - ResponseWrapper> getNotificationList(Integer pageStart, Integer pageFetch, String Id, String languageCode, int timeZoneOffset) throws ResidentServiceCheckedException, ApisResourceAccessException; + ResponseWrapper> getNotificationList(Integer pageStart, Integer pageFetch, String Id, String languageCode, int timeZoneOffset, String locale) throws ResidentServiceCheckedException, ApisResourceAccessException; byte[] downLoadServiceHistory(ResponseWrapper> responseWrapper, String languageCode, LocalDateTime eventReqDateTime, LocalDate fromDateTime, LocalDate toDateTime, - String serviceType, String statusFilter, int timeZoneOffset) throws ResidentServiceCheckedException, IOException; + String serviceType, String statusFilter, int timeZoneOffset, String locale) throws ResidentServiceCheckedException, IOException; - public ResponseWrapper getUserinfo(String Id, int timeZoneOffset) throws ApisResourceAccessException; + public ResponseWrapper getUserinfo(String Id, int timeZoneOffset, String locale) throws ApisResourceAccessException; - public String getFileName(String eventId, int timeZoneOffset); + public String getFileName(String eventId, int timeZoneOffset, String locale); + + ResponseWrapper> getServiceHistory(Integer pageStart, Integer pageFetch, + LocalDate fromDateTime, LocalDate toDateTime, String serviceType, String sortType, String statusFilter, + String searchText, String langCode, int timeZoneOffset, String locale, String defaultPageSizeProperty, List statusCodeList) + throws ResidentServiceCheckedException, ApisResourceAccessException; } diff --git a/resident/resident-service/src/main/java/io/mosip/resident/service/ResidentVidService.java b/resident/resident-service/src/main/java/io/mosip/resident/service/ResidentVidService.java index 49b536f1dd0..91da905df63 100644 --- a/resident/resident-service/src/main/java/io/mosip/resident/service/ResidentVidService.java +++ b/resident/resident-service/src/main/java/io/mosip/resident/service/ResidentVidService.java @@ -25,7 +25,7 @@ public interface ResidentVidService { public String getVidPolicy() throws ResidentServiceCheckedException; - public ResponseWrapper>> retrieveVids(String residentIndividualId, int timeZoneOffset) throws ResidentServiceCheckedException, ApisResourceAccessException; + public ResponseWrapper>> retrieveVids(String residentIndividualId, int timeZoneOffset, String locale) throws ResidentServiceCheckedException, ApisResourceAccessException; public Optional getPerpatualVid(String uin) throws ResidentServiceCheckedException, ApisResourceAccessException; @@ -36,7 +36,7 @@ public Tuple2, String> revokeVidV2(BaseVid String vid, String indivudalId) throws OtpValidationFailedException, ResidentServiceCheckedException, ApisResourceAccessException; - ResponseWrapper>> retrieveVidsfromUin(String uin, int timeZoneOffset) + ResponseWrapper>> retrieveVidsfromUin(String uin, int timeZoneOffset, String locale) throws ResidentServiceCheckedException, ApisResourceAccessException; } diff --git a/resident/resident-service/src/main/java/io/mosip/resident/service/WebSubCredentialStatusUpdateService.java b/resident/resident-service/src/main/java/io/mosip/resident/service/WebSubCredentialStatusUpdateService.java new file mode 100644 index 00000000000..6168b503651 --- /dev/null +++ b/resident/resident-service/src/main/java/io/mosip/resident/service/WebSubCredentialStatusUpdateService.java @@ -0,0 +1,20 @@ +package io.mosip.resident.service; + +import java.util.Map; + +import org.springframework.stereotype.Service; + +import io.mosip.resident.exception.ApisResourceAccessException; +import io.mosip.resident.exception.ResidentServiceCheckedException; + +/** + * Service to update the resident transaction status from the credential status + * update in the websub event. + * + * @author Loganathan S + * + */ +@Service +public interface WebSubCredentialStatusUpdateService { + public void updateCredentialStatus(Map eventModel) throws ResidentServiceCheckedException, ApisResourceAccessException; +} diff --git a/resident/resident-service/src/main/java/io/mosip/resident/service/WebSubUpdateAuthTypeService.java b/resident/resident-service/src/main/java/io/mosip/resident/service/WebSubUpdateAuthTypeService.java index c271afde2cd..366532ed45a 100644 --- a/resident/resident-service/src/main/java/io/mosip/resident/service/WebSubUpdateAuthTypeService.java +++ b/resident/resident-service/src/main/java/io/mosip/resident/service/WebSubUpdateAuthTypeService.java @@ -1,12 +1,12 @@ package io.mosip.resident.service; +import java.util.Map; + import org.springframework.stereotype.Service; -import io.mosip.kernel.core.websub.model.EventModel; import io.mosip.resident.exception.ApisResourceAccessException; import io.mosip.resident.exception.ResidentServiceCheckedException; - @Service public interface WebSubUpdateAuthTypeService { - public void updateAuthTypeStatus(EventModel eventModel) throws ResidentServiceCheckedException, ApisResourceAccessException; + public void updateAuthTypeStatus(Map eventModel) throws ResidentServiceCheckedException, ApisResourceAccessException; } diff --git a/resident/resident-service/src/main/java/io/mosip/resident/service/impl/AcknowledgementServiceImpl.java b/resident/resident-service/src/main/java/io/mosip/resident/service/impl/AcknowledgementServiceImpl.java index d8ce45786f6..57985e5c510 100644 --- a/resident/resident-service/src/main/java/io/mosip/resident/service/impl/AcknowledgementServiceImpl.java +++ b/resident/resident-service/src/main/java/io/mosip/resident/service/impl/AcknowledgementServiceImpl.java @@ -5,7 +5,6 @@ import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.util.HashMap; -import java.util.LinkedHashMap; import java.util.Map; import java.util.Optional; @@ -14,13 +13,11 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; -import io.mosip.kernel.core.http.ResponseWrapper; import io.mosip.kernel.core.logger.spi.Logger; import io.mosip.kernel.core.templatemanager.spi.TemplateManager; import io.mosip.kernel.core.templatemanager.spi.TemplateManagerBuilder; import io.mosip.resident.config.LoggerConfiguration; import io.mosip.resident.constant.RequestType; -import io.mosip.resident.constant.ResidentConstants; import io.mosip.resident.constant.ResidentErrorCode; import io.mosip.resident.entity.ResidentTransactionEntity; import io.mosip.resident.exception.ResidentServiceCheckedException; @@ -42,9 +39,6 @@ public class AcknowledgementServiceImpl implements AcknowledgementService { @Autowired private ResidentTransactionRepository residentTransactionRepository; - @Autowired - private ProxyMasterdataServiceImpl proxyMasterdataServiceImpl; - @Autowired private TemplateUtil templateUtil; @@ -66,7 +60,7 @@ public void idTemplateManagerPostConstruct() { private Utility utility; @Override - public byte[] getAcknowledgementPDF(String eventId, String languageCode, int timeZoneOffset) throws ResidentServiceCheckedException, IOException { + public byte[] getAcknowledgementPDF(String eventId, String languageCode, int timeZoneOffset, String locale) throws ResidentServiceCheckedException, IOException { logger.debug("AcknowledgementServiceImpl::getAcknowledgementPDF()::entry"); Optional residentTransactionEntity = residentTransactionRepository @@ -77,12 +71,9 @@ public byte[] getAcknowledgementPDF(String eventId, String languageCode, int tim } else { throw new ResidentServiceCheckedException(ResidentErrorCode.EVENT_STATUS_NOT_FOUND); } - Tuple2, String> ackTemplateVariables = RequestType.valueOf(requestTypeCode).getAckTemplateVariables(templateUtil, eventId, languageCode, timeZoneOffset); + Tuple2, String> ackTemplateVariables = RequestType.getRequestTypeFromString(requestTypeCode).getAckTemplateVariables(templateUtil, eventId, languageCode, timeZoneOffset, locale); String requestProperty = ackTemplateVariables.getT2(); - ResponseWrapper responseWrapper = proxyMasterdataServiceImpl. - getAllTemplateBylangCodeAndTemplateTypeCode(languageCode, requestProperty); - Map templateResponse = new LinkedHashMap<>((Map) responseWrapper.getResponse()); - String fileText = (String) templateResponse.get(ResidentConstants.FILE_TEXT); + String fileText = templateUtil.getTemplateValueFromTemplateTypeCodeAndLangCode(languageCode, requestProperty); Map templateVariables = ackTemplateVariables.getT1(); InputStream stream = new ByteArrayInputStream(fileText.getBytes(StandardCharsets.UTF_8)); InputStream templateValue = templateManager.merge(stream, convertMapValueFromStringToObject(templateVariables)); diff --git a/resident/resident-service/src/main/java/io/mosip/resident/service/impl/AuthTransactionCallBackServiceImpl.java b/resident/resident-service/src/main/java/io/mosip/resident/service/impl/AuthTransactionCallBackServiceImpl.java index f90eb83ddca..85ac7061a7a 100644 --- a/resident/resident-service/src/main/java/io/mosip/resident/service/impl/AuthTransactionCallBackServiceImpl.java +++ b/resident/resident-service/src/main/java/io/mosip/resident/service/impl/AuthTransactionCallBackServiceImpl.java @@ -1,17 +1,16 @@ package io.mosip.resident.service.impl; -import static io.mosip.resident.constant.ResidentConstants.RESIDENT_SERVICES; - import java.security.NoSuchAlgorithmException; +import java.time.LocalDateTime; +import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; +import com.fasterxml.jackson.databind.ObjectMapper; + import io.mosip.kernel.core.logger.spi.Logger; -import io.mosip.kernel.core.util.DateUtils; -import io.mosip.kernel.core.websub.model.EventModel; import io.mosip.resident.config.LoggerConfiguration; import io.mosip.resident.constant.EventStatusFailure; -import io.mosip.resident.constant.EventStatusSuccess; import io.mosip.resident.constant.LoggerFileConstant; import io.mosip.resident.constant.RequestType; import io.mosip.resident.constant.ResidentErrorCode; @@ -27,7 +26,16 @@ @Component public class AuthTransactionCallBackServiceImpl implements AuthTransactionCallBackService { - private static final String INDIVIDUAL_ID = "individualId"; + private static final String AUTHTYPE_CODE = "authtypeCode"; + private static final String REQUESTDATETIME = "requestdatetime"; + private static final String STATUS_COMMENT = "statusComment"; + private static final String STATUS_CODE = "statusCode"; + private static final String RESPONSE_SIGNATURE = "responseSignature"; + private static final String REQUEST_SIGNATURE = "requestSignature"; + private static final String ENTITY_NAME = "entityName"; + private static final String REFERENCE_ID_TYPE = "referenceIdType"; + private static final String TRANSACTION_ID = "transactionID"; + private static final String INDIVIDUAL_ID = "individualId"; private static final String ENTITY_ID = "entityId"; private static final String TOKEN_ID = "tokenId"; private static final Logger logger = LoggerConfiguration.logConfig(AuthTransactionCallBackServiceImpl.class); @@ -40,19 +48,19 @@ public class AuthTransactionCallBackServiceImpl implements AuthTransactionCallBa private ResidentTransactionRepository residentTransactionRepository; @Autowired - private IdentityServiceImpl identityService; + private ObjectMapper objectMapper; @Autowired private Utility utility; @Override - public void updateAuthTransactionCallBackService(EventModel eventModel) throws ResidentServiceCheckedException, ApisResourceAccessException, NoSuchAlgorithmException { + public void updateAuthTransactionCallBackService(Map eventModel) throws ResidentServiceCheckedException, ApisResourceAccessException, NoSuchAlgorithmException { logger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), "AuthTransactionCallbackServiceImpl::updateAuthTransactionCallBackService()::entry"); auditUtil.setAuditRequestDto(EventEnum.UPDATE_AUTH_TYPE_STATUS); try { logger.info("AuthTransactionCallbackServiceImpl::updateAuthTransactionCallBackService()::partnerId"); - insertInResidentTransactionTable(eventModel, EventStatusSuccess.AUTHENTICATION_SUCCESSFUL.name()); + insertInResidentTransactionTable(eventModel, null); } catch (Exception e) { logger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), "AuthTransactionCallbackServiceImpl::updateAuthTransactionCallBackService()::exception"); @@ -62,21 +70,47 @@ public void updateAuthTransactionCallBackService(EventModel eventModel) throws R } } - private void insertInResidentTransactionTable(EventModel eventModel, String status) throws ApisResourceAccessException, NoSuchAlgorithmException { + private void insertInResidentTransactionTable(Map eventModel, String status) throws ApisResourceAccessException, NoSuchAlgorithmException { logger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), "AuthTransactionCallbackServiceImpl::insertInResidentTransactionTable()::entry"); - - ResidentTransactionEntity residentTransactionEntity = utility.createEntity(); - residentTransactionEntity.setEventId(utility.createEventId()); - residentTransactionEntity.setRequestTypeCode(RequestType.AUTHENTICATION_REQUEST.name()); - residentTransactionEntity.setStatusCode(status); - residentTransactionEntity.setRefId(utility.convertToMaskDataFormat((String) eventModel.getEvent().getData().get(INDIVIDUAL_ID))); - residentTransactionEntity.setIndividualId((String) eventModel.getEvent().getData().get(INDIVIDUAL_ID)); - residentTransactionEntity.setRequestSummary(""); - residentTransactionEntity.setTokenId((String) eventModel.getEvent().getData().get(TOKEN_ID)); - residentTransactionEntity.setRequestedEntityId((String) eventModel.getEvent().getData().get(ENTITY_ID)); - residentTransactionEntity.setOlvPartnerId((String) eventModel.getEvent().getData().get(OLV_PARTNER_ID)); - residentTransactionRepository.save(residentTransactionEntity); + Object eventObj = eventModel.get("event"); + if (eventObj instanceof Map) { + Map eventMap = (Map) eventObj; + Object dataObject = eventMap.get("data"); + if (dataObject instanceof Map) { + Map dataMap = (Map) dataObject; + ResidentTransactionEntity residentTransactionEntity = utility.createEntity(RequestType.AUTHENTICATION_REQUEST); + residentTransactionEntity.setEventId(utility.createEventId()); + residentTransactionEntity.setRefId((String) dataMap.get(INDIVIDUAL_ID)); + residentTransactionEntity.setIndividualId((String) dataMap.get(INDIVIDUAL_ID)); + residentTransactionEntity.setRequestSummary(RequestType.AUTHENTICATION_REQUEST.name()); + residentTransactionEntity.setTokenId((String) dataMap.get(TOKEN_ID)); + residentTransactionEntity.setOlvPartnerId((String) dataMap.get(OLV_PARTNER_ID)); + residentTransactionEntity.setRequestTrnId((String) dataMap.get(TRANSACTION_ID)); + residentTransactionEntity.setRefIdType((String) dataMap.get(REFERENCE_ID_TYPE)); + residentTransactionEntity.setRequestedEntityId((String) dataMap.get(ENTITY_ID)); + residentTransactionEntity.setRequestedEntityName((String) dataMap.get(ENTITY_NAME)); + residentTransactionEntity.setRequestSignature((String) dataMap.get(REQUEST_SIGNATURE)); + residentTransactionEntity.setResponseSignature((String) dataMap.get(RESPONSE_SIGNATURE)); + if (status == null) { + Object object = dataMap.get(STATUS_CODE); + if (object instanceof String) { + status = (String) object; + } else { + status = EventStatusFailure.N.name(); + } + } + residentTransactionEntity.setStatusCode(status); + residentTransactionEntity.setAuthTypeCode((String) dataMap.get(AUTHTYPE_CODE)); + residentTransactionEntity.setStatusComment((String) dataMap.get(STATUS_COMMENT)); + Object reqdatetimeObj = dataMap.get(REQUESTDATETIME); + if (reqdatetimeObj != null) { + residentTransactionEntity + .setRequestDtimes(objectMapper.convertValue(reqdatetimeObj, LocalDateTime.class)); + } + residentTransactionRepository.save(residentTransactionEntity); + } + } logger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), "AuthTransactionCallbackServiceImpl::insertInResidentTransactionTable()::exit"); diff --git a/resident/resident-service/src/main/java/io/mosip/resident/service/impl/BaseWebSubInitializer.java b/resident/resident-service/src/main/java/io/mosip/resident/service/impl/BaseWebSubInitializer.java index 9c214c5ab17..ec40b3733d5 100644 --- a/resident/resident-service/src/main/java/io/mosip/resident/service/impl/BaseWebSubInitializer.java +++ b/resident/resident-service/src/main/java/io/mosip/resident/service/impl/BaseWebSubInitializer.java @@ -1,5 +1,7 @@ package io.mosip.resident.service.impl; +import java.time.Duration; +import java.time.Instant; import java.util.Date; import org.springframework.beans.factory.annotation.Autowired; @@ -31,7 +33,10 @@ public class BaseWebSubInitializer implements ApplicationListener subscribe; - @Value("${resident.websub.authtype-status.topic}") - private String topic; - @Value("${websub.publish.url}") private String publishUrl; @@ -52,37 +54,90 @@ public class BaseWebSubInitializer implements ApplicationListener { //Invoke topic registrations. This is done only once. //Note: With authenticated websub, only register topics which are only published by IDA - tryRegisterTopicEvent(topic); - tryRegisterTopicEvent(authTransactionTopic); + tryRegisteringTopics(); //Init topic subscriptions - initSubsriptions(); - authTransactionSubscription(); - }, new Date(System.currentTimeMillis() + taskSubsctiptionDelay)); + initTopicSubscriptions(); + }, new Date(System.currentTimeMillis() + taskSubscriptionInitialDelay)); + + if (reSubscriptionIntervalSecs > 0) { + logger.info("Work around for web-sub notification issue after some time."); + scheduleRetrySubscriptions(); + } else { + logger.info("Scheduling for re-subscription is Disabled as the re-subsctription delay value is: " + + reSubscriptionIntervalSecs); + } } - public void authTransactionSubscription() { - subscribe(authTransactionTopic, callbackAuthTransactionUrl, authTransactionSecret, hubUrl); + private void initTopicSubscriptions() { + authTypStatusTopicSubsriptions(); + authTransactionTopicSubscription(); + credentialStatusUpdateTopicSubscription(); + } + + private void tryRegisteringTopics() { + tryRegisterTopicEvent(autTypeStatusTopic); + tryRegisterTopicEvent(authTransactionTopic); + tryRegisterTopicEvent(credentialStatusUpdateTopic); + } + + private void scheduleRetrySubscriptions() { + taskScheduler.scheduleAtFixedRate(this::initTopicSubscriptions, Instant.now().plusSeconds(reSubscriptionIntervalSecs), + Duration.ofSeconds(reSubscriptionIntervalSecs)); + } + + public void authTransactionTopicSubscription() { + logger.debug("subscribe", "", + "Trying to subscribe to topic: " + authTransactionTopic + " callback-url: " + + authTransactionCallbackUrl); + subscribe(authTransactionTopic, authTransactionCallbackUrl, authTransactionSecret, hubUrl); + logger.info("subscribe", "", + "Subscribed to topic: " + authTransactionTopic); + } + + public void credentialStatusUpdateTopicSubscription() { + logger.debug("subscribe", "", + "Trying to subscribe to topic: " + credentialStatusUpdateTopic + " callback-url: " + + credentialStatusUpdateCallbackUrl); + subscribe(credentialStatusUpdateTopic, credentialStatusUpdateCallbackUrl, credentialStatusUpdateSecret, hubUrl); + logger.info("subscribe", "", + "Subscribed to topic: " + credentialStatusUpdateTopic); } protected void tryRegisterTopicEvent(String eventTopic) { @@ -98,13 +153,13 @@ protected void tryRegisterTopicEvent(String eventTopic) { } } - protected void initSubsriptions() { + protected void authTypStatusTopicSubsriptions() { logger.debug("subscribe", "", - "Trying to subscribe to topic: " + topic + " callback-url: " - + callbackUrl); - subscribe(topic, callbackUrl, secret, hubUrl); + "Trying to subscribe to topic: " + autTypeStatusTopic + " callback-url: " + + authTypeStatusCallbackUrl); + subscribe(autTypeStatusTopic, authTypeStatusCallbackUrl, authTypeStatusSecret, hubUrl); logger.info("subscribe", "", - "Subscribed to topic: " + topic); + "Subscribed to topic: " + autTypeStatusTopic); } diff --git a/resident/resident-service/src/main/java/io/mosip/resident/service/impl/DownLoadMasterDataServiceImpl.java b/resident/resident-service/src/main/java/io/mosip/resident/service/impl/DownLoadMasterDataServiceImpl.java index 7b3f9ca3e2b..600443224fc 100644 --- a/resident/resident-service/src/main/java/io/mosip/resident/service/impl/DownLoadMasterDataServiceImpl.java +++ b/resident/resident-service/src/main/java/io/mosip/resident/service/impl/DownLoadMasterDataServiceImpl.java @@ -1,5 +1,7 @@ package io.mosip.resident.service.impl; +import static io.mosip.resident.constant.ResidentConstants.RESIDENT_REGISTRATION_CENTERS_DOWNLOAD_MAX_COUNT; + import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; @@ -22,6 +24,7 @@ import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.exception.ExceptionUtils; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; @@ -32,16 +35,18 @@ import io.mosip.kernel.core.templatemanager.spi.TemplateManager; import io.mosip.kernel.core.templatemanager.spi.TemplateManagerBuilder; import io.mosip.resident.config.LoggerConfiguration; +import io.mosip.resident.constant.OrderEnum; import io.mosip.resident.constant.ResidentConstants; import io.mosip.resident.constant.ResidentErrorCode; import io.mosip.resident.dto.RegistrationCenterDto; -import io.mosip.resident.dto.RegistrationCenterResponseDto; +import io.mosip.resident.dto.RegistrationCenterInfoResponseDto; import io.mosip.resident.dto.WorkingDaysDto; import io.mosip.resident.dto.WorkingDaysResponseDto; import io.mosip.resident.exception.ResidentServiceCheckedException; import io.mosip.resident.exception.ResidentServiceException; import io.mosip.resident.service.DownLoadMasterDataService; import io.mosip.resident.service.ProxyMasterdataService; +import io.mosip.resident.util.TemplateUtil; import io.mosip.resident.util.Utility; /** @@ -73,6 +78,12 @@ public class DownLoadMasterDataServiceImpl implements DownLoadMasterDataService @Autowired private Utility utility; + @Autowired + private TemplateUtil templateUtil; + + @Value("${" + RESIDENT_REGISTRATION_CENTERS_DOWNLOAD_MAX_COUNT + "}") + private Integer maxRegistrationCenterPageSize; + private static final Logger logger = LoggerConfiguration.logConfig(ProxyMasterdataServiceImpl.class); @PostConstruct @@ -86,21 +97,19 @@ public void idTemplateManagerPostConstruct() { * center names */ public InputStream downloadRegistrationCentersByHierarchyLevel(String langCode, Short hierarchyLevel, - List name) throws ResidentServiceCheckedException, IOException, Exception { + String name) throws ResidentServiceCheckedException, IOException, Exception { logger.debug("DownLoadMasterDataService::downloadRegistrationCentersByHierarchyLevel()::entry"); - ResponseWrapper regCentResponseWrapper = proxyMasterdataService.getRegistrationCentersByHierarchyLevel(langCode, hierarchyLevel, name); - return getRegistrationCentrePdf(langCode, regCentResponseWrapper); + ResponseWrapper regCentResponseWrapper = proxyMasterdataService.getRegistrationCenterByHierarchyLevelAndTextPaginated(langCode, hierarchyLevel, name, 0, maxRegistrationCenterPageSize, OrderEnum.desc, null); + return getRegistrationCentersPdf(langCode, regCentResponseWrapper); } - public InputStream getRegistrationCentrePdf(String langCode, ResponseWrapper regCentResponseWrapper) throws ResidentServiceCheckedException, IOException { - ResponseWrapper proxyResponseWrapper = proxyMasterdataService - .getAllTemplateBylangCodeAndTemplateTypeCode(langCode, this.env.getProperty(ResidentConstants.REGISTRATION_CENTRE_TEMPLATE_PROPERTY)); + public InputStream getRegistrationCentersPdf(String langCode, ResponseWrapper regCentResponseWrapper) throws ResidentServiceCheckedException, IOException { Map regCentersMap = new LinkedHashMap<>(); if (regCentResponseWrapper != null) { - RegistrationCenterResponseDto registrationCentersDtls = mapper.readValue( + RegistrationCenterInfoResponseDto registrationCentersDtls = mapper.readValue( mapper.writeValueAsString(regCentResponseWrapper.getResponse()), - RegistrationCenterResponseDto.class); - List regCenterIntialList = registrationCentersDtls.getRegistrationCenters(); + RegistrationCenterInfoResponseDto.class); + List regCenterIntialList = getRegCenterList(registrationCentersDtls); if (regCenterIntialList != null && !regCenterIntialList.isEmpty()) { IntStream.range(0, regCenterIntialList.size()).forEach(i -> { try { @@ -112,10 +121,8 @@ public InputStream getRegistrationCentrePdf(String langCode, ResponseWrapper } regCentersMap.put("regCenterIntialList", regCenterIntialList); } - logger.debug("template data from DB:" + proxyResponseWrapper.getResponse()); - Map templateResponse = new LinkedHashMap<>( - (Map) proxyResponseWrapper.getResponse()); - String fileText = (String) templateResponse.get(ResidentConstants.FILE_TEXT); + String templateTypeCode = this.env.getProperty(ResidentConstants.REGISTRATION_CENTRE_TEMPLATE_PROPERTY); + String fileText = templateUtil.getTemplateValueFromTemplateTypeCodeAndLangCode(langCode, templateTypeCode); InputStream downLoadRegCenterTemplate = new ByteArrayInputStream(fileText.getBytes(StandardCharsets.UTF_8)); InputStream downLoadRegCenterTemplateData = templateManager.merge(downLoadRegCenterTemplate, regCentersMap); @@ -123,6 +130,15 @@ public InputStream getRegistrationCentrePdf(String langCode, ResponseWrapper IOUtils.copy(downLoadRegCenterTemplateData, writer, "UTF-8"); return new ByteArrayInputStream(utility.signPdf(new ByteArrayInputStream(writer.toString().getBytes()), null)); } + + private List getRegCenterList(RegistrationCenterInfoResponseDto registrationCentersDtls) { + if (registrationCentersDtls.getData() != null && !registrationCentersDtls.getData().isEmpty()) { + return registrationCentersDtls.getData(); + } else if (registrationCentersDtls.getRegistrationCenters() != null && !registrationCentersDtls.getRegistrationCenters().isEmpty()) { + return registrationCentersDtls.getRegistrationCenters(); + } + return List.of(); + } /** * download the nearest registration centers @@ -132,7 +148,7 @@ public InputStream getNearestRegistrationcenters(String langCode, double longitu logger.debug("DownLoadMasterDataService::downloadRegistrationCentersByHierarchyLevel()::entry"); ResponseWrapper regCentResponseWrapper = proxyMasterdataService.getCoordinateSpecificRegistrationCenters(langCode, longitude, latitude, proximityDistance); - return getRegistrationCentrePdf(langCode, regCentResponseWrapper); + return getRegistrationCentersPdf(langCode, regCentResponseWrapper); } @@ -142,11 +158,8 @@ public InputStream getNearestRegistrationcenters(String langCode, double longitu */ public InputStream downloadSupportingDocsByLanguage(String langCode) throws ResidentServiceCheckedException, IOException, Exception { logger.debug("ResidentServiceImpl::getResidentServicePDF()::entry"); - ResponseWrapper proxyResponseWrapper = proxyMasterdataService - .getAllTemplateBylangCodeAndTemplateTypeCode(langCode, this.env.getProperty(ResidentConstants.SUPPORTING_DOCS_TEMPLATE_PROPERTY)); - logger.debug("template data from DB:" + proxyResponseWrapper.getResponse()); - Map templateResponse = new LinkedHashMap<>((Map) proxyResponseWrapper.getResponse()); - String fileText = (String) templateResponse.get(ResidentConstants.FILE_TEXT); + String templateTypeCode = this.env.getProperty(ResidentConstants.SUPPORTING_DOCS_TEMPLATE_PROPERTY); + String fileText = templateUtil.getTemplateValueFromTemplateTypeCodeAndLangCode(langCode, templateTypeCode); Map supportingsDocsMap = new HashMap<>(); supportingsDocsMap.put("supportingsDocMap", supportingsDocsMap); InputStream supportingDocsTemplate = new ByteArrayInputStream(fileText.getBytes(StandardCharsets.UTF_8)); diff --git a/resident/resident-service/src/main/java/io/mosip/resident/service/impl/DownloadCardServiceImpl.java b/resident/resident-service/src/main/java/io/mosip/resident/service/impl/DownloadCardServiceImpl.java index 6cd2b53f3b4..99762f2032b 100644 --- a/resident/resident-service/src/main/java/io/mosip/resident/service/impl/DownloadCardServiceImpl.java +++ b/resident/resident-service/src/main/java/io/mosip/resident/service/impl/DownloadCardServiceImpl.java @@ -1,6 +1,7 @@ package io.mosip.resident.service.impl; import static io.mosip.resident.constant.EventStatusSuccess.CARD_DOWNLOADED; +import static io.mosip.resident.constant.ResidentConstants.SEMI_COLON; import static io.mosip.resident.constant.TemplateVariablesConstants.OTP; import static io.mosip.resident.constant.TemplateVariablesConstants.VID; import static io.mosip.resident.constant.TemplateVariablesConstants.VID_TYPE; @@ -13,6 +14,7 @@ import java.util.Map; import java.util.stream.Collectors; +import io.mosip.resident.exception.ResidentCredentialServiceException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.env.Environment; @@ -25,11 +27,11 @@ import io.mosip.kernel.core.util.DateUtils; import io.mosip.resident.config.LoggerConfiguration; import io.mosip.resident.constant.ApiName; -import io.mosip.resident.constant.EventStatus; import io.mosip.resident.constant.EventStatusFailure; import io.mosip.resident.constant.EventStatusInProgress; import io.mosip.resident.constant.IdType; import io.mosip.resident.constant.LoggerFileConstant; +import io.mosip.resident.constant.PacketStatus; import io.mosip.resident.constant.RequestType; import io.mosip.resident.constant.ResidentConstants; import io.mosip.resident.constant.ResidentErrorCode; @@ -85,6 +87,7 @@ public class DownloadCardServiceImpl implements DownloadCardService { private static final String TEMPLATE_TYPE_CODE = "templateTypeCode"; private static final String APPLICANT_PHOTO = "ApplicantPhoto"; private static final Object NA = "NA"; + private static final String DATE_OF_BIRTH = "dob"; @Autowired private Utilities utilities; @@ -125,63 +128,108 @@ public class DownloadCardServiceImpl implements DownloadCardService { private static final Logger logger = LoggerConfiguration.logConfig(DownloadCardServiceImpl.class); @Override - public Tuple2 getDownloadCardPDF(MainRequestDTO downloadCardRequestDTOMainRequestDTO) { - String rid = ""; - String eventId = utility.createEventId(); - byte[] pdfBytes = new byte[0]; - try { - if (idAuthService.validateOtpv2(downloadCardRequestDTOMainRequestDTO.getRequest().getTransactionId(), - getIndividualIdForAid(downloadCardRequestDTOMainRequestDTO.getRequest().getIndividualId()) - , downloadCardRequestDTOMainRequestDTO.getRequest().getOtp())) { - String individualId = downloadCardRequestDTOMainRequestDTO.getRequest().getIndividualId(); - String idType = identityService.getIndividualIdType(individualId); - if (idType.equalsIgnoreCase(AID)) { - rid = individualId; - HashMap ridStatus = utilities.getPacketStatus(rid); - String transactionTypeCode = ridStatus.get(ResidentConstants.TRANSACTION_TYPE_CODE); - String aidStatus = ridStatus.get(ResidentConstants.AID_STATUS); - if (transactionTypeCode.equalsIgnoreCase(TransactionStage.CARD_READY_TO_DOWNLOAD.getName()) && aidStatus.equalsIgnoreCase(EventStatus.SUCCESS.name())) { - pdfBytes = residentCredentialService.getCard(rid + ridSuffix, null, null); - } else { - throw new ResidentServiceException(ResidentErrorCode.CARD_NOT_READY.getErrorCode(), - ResidentErrorCode.CARD_NOT_READY.getErrorMessage()); - } - }else { - rid = utilities.getRidByIndividualId(individualId); - pdfBytes = residentCredentialService.getCard(rid + ridSuffix, null, null); - } - if(pdfBytes.length==0){ - insertDataForDownloadCard(downloadCardRequestDTOMainRequestDTO, eventId, EventStatus.FAILED.name()); - } else { - insertDataForDownloadCard(downloadCardRequestDTOMainRequestDTO, eventId, EventStatus.SUCCESS.name()); - } - - } else { - logger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), - LoggerFileConstant.APPLICATIONID.toString(), - ResidentErrorCode.OTP_VALIDATION_FAILED.getErrorMessage()); - audit.setAuditRequestDto(EventEnum.CREDENTIAL_REQ_EXCEPTION); - throw new ResidentServiceException(ResidentErrorCode.OTP_VALIDATION_FAILED.getErrorCode(), - ResidentErrorCode.OTP_VALIDATION_FAILED.getErrorMessage()); - } - } catch (ApisResourceAccessException e) { - audit.setAuditRequestDto(EventEnum.RID_DIGITAL_CARD_REQ_EXCEPTION); - throw new ResidentServiceException( - ResidentErrorCode.API_RESOURCE_ACCESS_EXCEPTION.getErrorCode(), - ResidentErrorCode.API_RESOURCE_ACCESS_EXCEPTION.getErrorMessage(), e); - } catch (OtpValidationFailedException e) { - audit.setAuditRequestDto(EventEnum.REQ_CARD); - throw new ResidentServiceException(ResidentErrorCode.OTP_VALIDATION_FAILED.getErrorCode(), e.getErrorText(), - e); - } catch (Exception e) { + public Tuple2 getDownloadCardPDF( + MainRequestDTO downloadCardRequestDTOMainRequestDTO) + throws ResidentServiceCheckedException { + String rid = ""; + String individualId = downloadCardRequestDTOMainRequestDTO.getRequest().getIndividualId(); + String eventId = ResidentConstants.NOT_AVAILABLE; + ResidentTransactionEntity residentTransactionEntity = null; + byte[] pdfBytes = new byte[0]; + try { + String transactionId = downloadCardRequestDTOMainRequestDTO.getRequest().getTransactionId(); + String id = getIndividualIdForAid(individualId); + Tuple2 tupleResponse = idAuthService.validateOtpV2(transactionId, id, + downloadCardRequestDTOMainRequestDTO.getRequest().getOtp(), RequestType.GET_MY_ID); + residentTransactionEntity = updateResidentTransaction(individualId, transactionId, tupleResponse.getT2(), id); + if (residentTransactionEntity != null) { + eventId = residentTransactionEntity.getEventId(); + if (tupleResponse.getT1()) { + String idType = identityService.getIndividualIdType(individualId); + if (idType.equalsIgnoreCase(AID)) { + rid = individualId; + Map ridStatus = utilities.getPacketStatus(rid); + String transactionTypeCode = ridStatus.get(ResidentConstants.TRANSACTION_TYPE_CODE); + String aidStatus = ridStatus.get(ResidentConstants.AID_STATUS); + if (transactionTypeCode.equalsIgnoreCase(TransactionStage.CARD_READY_TO_DOWNLOAD.name()) + && aidStatus.equalsIgnoreCase(PacketStatus.SUCCESS.getName())) { + pdfBytes = residentCredentialService.getCard(rid + ridSuffix, null, null); + } else { + throw new ResidentServiceException(ResidentErrorCode.CARD_NOT_READY.getErrorCode(), + ResidentErrorCode.CARD_NOT_READY.getErrorMessage()); + } + } else { + rid = utilities.getRidByIndividualId(individualId); + pdfBytes = residentCredentialService.getCard(rid + ridSuffix, null, null); + } + if (pdfBytes.length == 0) { + residentTransactionEntity.setStatusCode(EventStatusFailure.FAILED.name()); + residentTransactionEntity.setStatusComment( + ResidentErrorCode.CARD_NOT_READY.getErrorMessage() + " - zero length"); + residentTransactionEntity + .setRequestSummary(RequestType.GET_MY_ID.name() + " - " + ResidentConstants.FAILED); + } else { + residentTransactionEntity.setStatusCode(CARD_DOWNLOADED.name()); + residentTransactionEntity.setStatusComment(CARD_DOWNLOADED.name()); + residentTransactionEntity + .setRequestSummary(RequestType.GET_MY_ID.name() + " - " + ResidentConstants.SUCCESS); + } + } else { + logger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), + LoggerFileConstant.APPLICATIONID.toString(), + ResidentErrorCode.OTP_VALIDATION_FAILED.getErrorMessage()); + audit.setAuditRequestDto(EventEnum.CREDENTIAL_REQ_EXCEPTION); + throw new ResidentServiceException(ResidentErrorCode.OTP_VALIDATION_FAILED.getErrorCode(), + ResidentErrorCode.OTP_VALIDATION_FAILED.getErrorMessage()); + } + } + } catch (ApisResourceAccessException | ResidentCredentialServiceException e) { + audit.setAuditRequestDto(EventEnum.RID_DIGITAL_CARD_REQ_EXCEPTION); + throw new ResidentServiceException(ResidentErrorCode.API_RESOURCE_ACCESS_EXCEPTION.getErrorCode(), + ResidentErrorCode.API_RESOURCE_ACCESS_EXCEPTION.getErrorMessage(), e, + Map.of(ResidentConstants.EVENT_ID, eventId)); + } catch (OtpValidationFailedException e) { + audit.setAuditRequestDto(EventEnum.RID_DIGITAL_CARD_REQ_EXCEPTION); + if (residentTransactionEntity != null) { + residentTransactionEntity.setStatusCode(EventStatusFailure.OTP_VERIFICATION_FAILED.name()); + residentTransactionEntity.setStatusComment(EventStatusFailure.OTP_VERIFICATION_FAILED.name()); + } + throw new ResidentServiceException(ResidentErrorCode.OTP_VALIDATION_FAILED.getErrorCode(), e.getErrorText(), + e, Map.of(ResidentConstants.EVENT_ID, eventId)); + } catch (Exception e) { audit.setAuditRequestDto(EventEnum.RID_DIGITAL_CARD_REQ_EXCEPTION); throw new ResidentServiceException(ResidentErrorCode.CARD_NOT_READY.getErrorCode(), - ResidentErrorCode.CARD_NOT_READY.getErrorMessage(), e); + ResidentErrorCode.CARD_NOT_READY.getErrorMessage(), e, Map.of(ResidentConstants.EVENT_ID, eventId)); + } finally { + if (residentTransactionEntity != null) { + /** + * Here we are setting RID in AID column. + */ + residentTransactionEntity.setAid(rid); + // if the status code will come as null, it will set it as failed. + if (residentTransactionEntity.getStatusCode() == null) { + residentTransactionEntity.setStatusCode(EventStatusFailure.FAILED.name()); + residentTransactionEntity.setStatusComment(ResidentErrorCode.CARD_NOT_READY.getErrorMessage()); + } + if (residentTransactionEntity.getRequestSummary() == null) { + residentTransactionEntity + .setRequestSummary(RequestType.GET_MY_ID.name() + " - " + ResidentConstants.FAILED); + } + residentTransactionEntity.setUpdBy(utility.getSessionUserName()); + residentTransactionEntity.setUpdDtimes(DateUtils.getUTCCurrentDateTime()); + residentTransactionRepository.save(residentTransactionEntity); + + TemplateType templateType = (residentTransactionEntity.getStatusCode() + .equals(CARD_DOWNLOADED.name())) ? TemplateType.SUCCESS + : TemplateType.FAILURE; + + sendNotificationV2(individualId, RequestType.GET_MY_ID, templateType, eventId, null); + } + } + return Tuples.of(pdfBytes, eventId); } - return Tuples.of(pdfBytes, eventId); - } - private ResponseWrapper getCheckStatusResponse(HashMap packetStatusMap) { + private ResponseWrapper getCheckStatusResponse(Map packetStatusMap) { ResponseWrapper checkStatusResponseDTOResponseWrapper = new ResponseWrapper<>(); CheckStatusResponseDTO checkStatusResponseDTO = new CheckStatusResponseDTO(); String aidStatus = packetStatusMap.get(ResidentConstants.AID_STATUS); @@ -192,59 +240,53 @@ private ResponseWrapper getCheckStatusResponse(HashMap downloadCardRequestDTOMainRequestDTO, - String eventId, String status) throws ApisResourceAccessException, ResidentServiceCheckedException { - ResidentTransactionEntity residentTransactionEntity = utility.createEntity(); - residentTransactionEntity.setEventId(eventId); - residentTransactionEntity.setRequestTypeCode(RequestType.GET_MY_ID.name()); - residentTransactionEntity.setRequestSummary(RequestType.GET_MY_ID.name()); - residentTransactionEntity.setStatusCode(status); - residentTransactionEntity.setAuthTypeCode(OTP); - residentTransactionEntity.setStatusComment(String.valueOf(CARD_DOWNLOADED)); - residentTransactionEntity.setRefId(utility.convertToMaskDataFormat( - downloadCardRequestDTOMainRequestDTO.getRequest().getIndividualId())); - residentTransactionEntity.setIndividualId(downloadCardRequestDTOMainRequestDTO.getRequest().getIndividualId()); - residentTransactionEntity.setTokenId(identityService.getIDATokenForIndividualId( - getIndividualIdForAid(downloadCardRequestDTOMainRequestDTO.getRequest().getIndividualId()))); - residentTransactionEntity.setRequestTrnId(downloadCardRequestDTOMainRequestDTO.getRequest().getTransactionId()); - residentTransactionRepository.save(residentTransactionEntity); - - } + private ResidentTransactionEntity updateResidentTransaction(String individualId, String transactionId, + ResidentTransactionEntity residentTransactionEntity, String id) throws ResidentServiceCheckedException { + residentTransactionEntity.setAuthTypeCode(OTP); + residentTransactionEntity.setRefId(utility.convertToMaskData(individualId)); + residentTransactionEntity.setIndividualId(individualId); + residentTransactionEntity.setTokenId(identityService.getIDATokenForIndividualId(id)); + residentTransactionEntity.setRequestTrnId(transactionId); + return residentTransactionEntity; + } @Override - public Tuple2 downloadPersonalizedCard(MainRequestDTO downloadPersonalizedCardMainRequestDTO, int timeZoneOffset) { + public Tuple2 downloadPersonalizedCard( + MainRequestDTO downloadPersonalizedCardMainRequestDTO, int timeZoneOffset, String locale) + throws ResidentServiceCheckedException { String encodeHtml = downloadPersonalizedCardMainRequestDTO.getRequest().getHtml(); - byte[] decodedData; + byte[] decodedData = new byte[0]; String password=null; + String individualId = ""; String eventId = ResidentConstants.NOT_AVAILABLE; ResidentTransactionEntity residentTransactionEntity = null; try { - residentTransactionEntity = createResidentTransactionEntity(); - if (residentTransactionEntity != null) { - eventId = residentTransactionEntity.getEventId(); - } - decodedData = CryptoUtil.decodePlainBase64(encodeHtml); - List attributeValues = getAttributeList(); - if(Boolean.parseBoolean(this.environment.getProperty(ResidentConstants.IS_PASSWORD_FLAG_ENABLED))){ - password = utility.getPassword(attributeValues); - } - List attributes = downloadPersonalizedCardMainRequestDTO.getRequest().getAttributes(); - if(attributes != null){ - String attributeList = attributes. - stream().collect(Collectors.joining(", ")); - residentTransactionEntity.setAttributeList(attributeList); - } - residentTransactionEntity.setRequestSummary(ResidentConstants.SUCCESS); - residentTransactionEntity.setStatusCode(CARD_DOWNLOADED.name()); - residentTransactionEntity.setStatusComment(CARD_DOWNLOADED.name()); + individualId = identityService.getResidentIndvidualIdFromSession(); + residentTransactionEntity = createResidentTransactionEntity(individualId, + downloadPersonalizedCardMainRequestDTO.getRequest()); + if (residentTransactionEntity != null) { + eventId = residentTransactionEntity.getEventId(); + decodedData = CryptoUtil.decodePlainBase64(encodeHtml); + List attributeValues = getAttributeList(); + if (Boolean.parseBoolean(this.environment.getProperty(ResidentConstants.IS_PASSWORD_FLAG_ENABLED))) { + password = utility.getPassword(attributeValues); + } + residentTransactionEntity.setRequestSummary( + RequestType.DOWNLOAD_PERSONALIZED_CARD.name() + " - " + ResidentConstants.SUCCESS); + residentTransactionEntity.setStatusCode(CARD_DOWNLOADED.name()); + residentTransactionEntity.setStatusComment(CARD_DOWNLOADED.name()); + } } catch (Exception e) { if (residentTransactionEntity != null) { - residentTransactionEntity.setRequestSummary(ResidentConstants.FAILED); - residentTransactionEntity.setStatusCode(EventStatusFailure.FAILED.name()); + residentTransactionEntity.setRequestSummary( + RequestType.DOWNLOAD_PERSONALIZED_CARD.name() + " - " + ResidentConstants.FAILED); + residentTransactionEntity.setStatusCode(EventStatusFailure.FAILED.name()); + residentTransactionEntity.setStatusComment(ResidentErrorCode.DOWNLOAD_PERSONALIZED_CARD.getErrorMessage()); } audit.setAuditRequestDto(EventEnum.DOWNLOAD_PERSONALIZED_CARD); logger.error("Unable to convert html to pdf RootCause- "+e); @@ -253,26 +295,37 @@ public Tuple2 downloadPersonalizedCard(MainRequestDTO getAttributeList(String individualId) throws IOException, A } @Override - public Tuple2, String> getVidCardEventId(String vid, int timeZoneOffset) throws BaseCheckedException { + public Tuple2, String> getVidCardEventId(String vid, int timeZoneOffset, String locale) throws BaseCheckedException { ResponseWrapper responseWrapper= new ResponseWrapper<>(); VidDownloadCardResponseDto vidDownloadCardResponseDto = new VidDownloadCardResponseDto(); String eventId = ResidentConstants.NOT_AVAILABLE; @@ -348,7 +401,7 @@ public Tuple2, String> getVidCardEve credentialReqestDto.setIssuer(environment.getProperty(ResidentConstants.CREDENTIAL_ISSUER)); credentialReqestDto.setEncrypt(Boolean.parseBoolean(environment.getProperty(ResidentConstants.CREDENTIAL_ENCRYPTION_FLAG))); credentialReqestDto.setEncryptionKey(environment.getProperty(ResidentConstants.CREDENTIAL_ENCRYPTION_KEY)); - Map additionalAttributes = getVidDetails(vid, uinForVid, timeZoneOffset); + Map additionalAttributes = getVidDetails(vid, uinForVid, timeZoneOffset, locale); additionalAttributes.put(TEMPLATE_TYPE_CODE, this.environment.getProperty(ResidentConstants.VID_CARD_TEMPLATE_PROPERTY)); additionalAttributes.put(APPLICANT_PHOTO, identityService.getAvailableclaimValue(environment.getProperty(ResidentConstants.IMAGE))); credentialReqestDto.setAdditionalData(additionalAttributes); @@ -382,6 +435,7 @@ public Tuple2, String> getVidCardEve throw new ApisResourceAccessException(ResidentErrorCode.VID_REQUEST_CARD_FAILED.toString(), e, Map.of(ResidentConstants.EVENT_ID, eventId)); } catch (IOException exception) { + audit.setAuditRequestDto(EventEnum.RID_DIGITAL_CARD_REQ_EXCEPTION); if (residentTransactionEntity != null) { residentTransactionEntity.setRequestSummary(ResidentConstants.FAILED); residentTransactionEntity.setStatusCode(EventStatusFailure.FAILED.name()); @@ -411,9 +465,9 @@ public Tuple2, String> getVidCardEve } @Override - public ResponseWrapper getIndividualIdStatus(String individualId) throws ApisResourceAccessException, IOException { + public ResponseWrapper getIndividualIdStatus(String individualId) throws ApisResourceAccessException, IOException, ResidentServiceCheckedException { individualId = getRidForIndividualId(individualId); - HashMap packetStatusMap = utilities.getPacketStatus(individualId); + Map packetStatusMap = utilities.getPacketStatus(individualId); return getCheckStatusResponse(packetStatusMap); } @@ -430,12 +484,11 @@ private String getRidForIndividualId(String individualId) { } } - private ResidentTransactionEntity insertDataForVidCard(String vid, String uin) throws ApisResourceAccessException, IOException { - ResidentTransactionEntity residentTransactionEntity = utility.createEntity(); + private ResidentTransactionEntity insertDataForVidCard(String vid, String uin) throws ApisResourceAccessException, IOException, ResidentServiceCheckedException { + ResidentTransactionEntity residentTransactionEntity = utility.createEntity(RequestType.VID_CARD_DOWNLOAD); residentTransactionEntity.setEventId(utility.createEventId()); residentTransactionEntity.setAuthTypeCode(identityService.getResidentAuthenticationMode()); - residentTransactionEntity.setRequestTypeCode(RequestType.VID_CARD_DOWNLOAD.name()); - residentTransactionEntity.setRefId(utility.convertToMaskDataFormat(uin)); + residentTransactionEntity.setRefId(utility.convertToMaskData(uin)); residentTransactionEntity.setIndividualId(uin); residentTransactionEntity.setTokenId(identityService.getIDAToken(uin)); residentTransactionEntity.setStatusCode(EventStatusInProgress.NEW.name()); @@ -448,12 +501,12 @@ private ResidentTransactionEntity insertDataForVidCard(String vid, String uin) t return residentTransactionEntity; } - private Map getVidDetails(String vid, String uin, int timeZoneOffset) throws ResidentServiceCheckedException, ApisResourceAccessException, IOException { + private Map getVidDetails(String vid, String uin, int timeZoneOffset, String locale) throws ResidentServiceCheckedException, ApisResourceAccessException, IOException { Map additionalAttributes = new HashMap<>(); String name=null; ResponseWrapper>> vidResponse = null; if(uin!=null){ - vidResponse =vidService.retrieveVids(uin, timeZoneOffset); + vidResponse =vidService.retrieveVids(uin, timeZoneOffset, locale); name = getFullName(uin); } if (vidResponse!=null){ @@ -469,6 +522,7 @@ private Map getVidDetails(String vid, String uin, int timeZoneOf additionalAttributes.put(TRANSACTION_LIMIT, replaceNullValueWithNA(vidData.get(TRANSACTION_LIMIT))); additionalAttributes.put(TRANSACTION_COUNT, replaceNullValueWithNA(vidData.get(TRANSACTION_COUNT))); additionalAttributes.put(CARD_FORMAT, VID_CARD); + additionalAttributes.put(DATE_OF_BIRTH, identityService.getIdentity(identityService.getResidentIndvidualIdFromSession()).getDateOfBirth()); if(name!=null){ additionalAttributes.put(ResidentConstants.NAME, name); } @@ -501,7 +555,7 @@ private String getFullName(String uin) throws IOException, ApisResourceAccessExc */ private String getIndividualIdForAid(String individualId) { String idType = identityService.getIndividualIdType(individualId); - if(idType.equalsIgnoreCase(IdType.UIN.toString()) || idType.equalsIgnoreCase(IdType.VID.toString())){ + if(idType.equalsIgnoreCase(IdType.UIN.toString())){ return individualId; } else { try { diff --git a/resident/resident-service/src/main/java/io/mosip/resident/service/impl/IdAuthServiceImpl.java b/resident/resident-service/src/main/java/io/mosip/resident/service/impl/IdAuthServiceImpl.java index 47e6bf48fb4..b0118f1f5f4 100644 --- a/resident/resident-service/src/main/java/io/mosip/resident/service/impl/IdAuthServiceImpl.java +++ b/resident/resident-service/src/main/java/io/mosip/resident/service/impl/IdAuthServiceImpl.java @@ -1,7 +1,5 @@ package io.mosip.resident.service.impl; -import static io.mosip.resident.constant.ResidentConstants.RESIDENT_SERVICES; - import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.StringReader; @@ -50,11 +48,14 @@ import io.mosip.resident.config.LoggerConfiguration; import io.mosip.resident.constant.ApiName; import io.mosip.resident.constant.AuthTypeStatus; +import io.mosip.resident.constant.EventStatusFailure; import io.mosip.resident.constant.EventStatusInProgress; +import io.mosip.resident.constant.EventStatusSuccess; import io.mosip.resident.constant.LoggerFileConstant; import io.mosip.resident.constant.RequestType; import io.mosip.resident.constant.ResidentConstants; import io.mosip.resident.constant.ResidentErrorCode; +import io.mosip.resident.constant.TemplateType; import io.mosip.resident.dto.AuthRequestDTO; import io.mosip.resident.dto.AuthResponseDTO; import io.mosip.resident.dto.AuthTxnDetailsDTO; @@ -63,6 +64,7 @@ import io.mosip.resident.dto.AuthTypeStatusResponseDto; import io.mosip.resident.dto.AutnTxnDto; import io.mosip.resident.dto.AutnTxnResponseDto; +import io.mosip.resident.dto.NotificationRequestDtoV2; import io.mosip.resident.dto.OtpAuthRequestDTO; import io.mosip.resident.dto.PublicKeyResponseDto; import io.mosip.resident.entity.ResidentTransactionEntity; @@ -72,7 +74,11 @@ import io.mosip.resident.exception.ResidentServiceCheckedException; import io.mosip.resident.repository.ResidentTransactionRepository; import io.mosip.resident.service.IdAuthService; +import io.mosip.resident.service.NotificationService; +import io.mosip.resident.util.AuditUtil; +import io.mosip.resident.util.EventEnum; import io.mosip.resident.util.ResidentServiceRestClient; +import io.mosip.resident.util.Utility; import io.mosip.resident.validator.RequestValidator; import reactor.util.function.Tuple2; import reactor.util.function.Tuples; @@ -91,7 +97,7 @@ public class IdAuthServiceImpl implements IdAuthService { @Value("${auth.type.status.id}") private String authTypeStatusId; - @Value("${mosipbox.public.url:null}") + @Value("${mosip.ida.domain-url:null}") private String domainUrl; @Value("${mosip.ida.env:Staging}") @@ -117,9 +123,18 @@ public class IdAuthServiceImpl implements IdAuthService { @Autowired private IdentityServiceImpl identityService; - + + @Autowired + private NotificationService notificationService; + @Autowired RequestValidator requestValidator; + + @Autowired + private AuditUtil auditUtil; + + @Autowired + private Utility utility; @Override public boolean validateOtp(String transactionId, String individualId, String otp) @@ -132,38 +147,58 @@ public Tuple2 validateOtpV1(String transactionId, String indivi throws OtpValidationFailedException, ResidentServiceCheckedException { AuthResponseDTO response = null; String eventId = ResidentConstants.NOT_AVAILABLE; - ResidentTransactionEntity residentTransactionEntity = null; + boolean authStatus = false; try { response = internelOtpAuth(transactionId, individualId, otp); - residentTransactionEntity = updateResidentTransaction(response.getResponse().isAuthStatus(), transactionId, - individualId); - if (residentTransactionEntity != null) { - eventId = residentTransactionEntity.getEventId(); + if (response.getErrors() != null && !response.getErrors().isEmpty()) { + response.getErrors().stream().forEach(error -> logger.error(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.USERID.toString(), error.getErrorCode(), error.getErrorMessage())); + eventId = updateResidentTransactionAndSendNotification(transactionId, individualId, eventId, authStatus); + throw new OtpValidationFailedException(response.getErrors().get(0).getErrorMessage(), + Map.of(ResidentConstants.EVENT_ID, eventId)); + } + if (response.getResponse() != null) { + authStatus = response.getResponse().isAuthStatus(); + eventId = updateResidentTransactionAndSendNotification(transactionId, individualId, eventId, authStatus); } } catch (ApisResourceAccessException | InvalidKeySpecException | NoSuchAlgorithmException | IOException | JsonProcessingException | java.security.cert.CertificateException e) { + auditUtil.setAuditRequestDto(EventEnum.getEventEnumWithValue(EventEnum.VALIDATE_OTP_FAILURE, transactionId, + "OTP Validation Failed")); logger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), null, "IdAuthServiceImpl::validateOtp():: validate otp method call" + ExceptionUtils.getStackTrace(e)); + eventId = updateResidentTransactionAndSendNotification(transactionId, individualId, eventId, authStatus); throw new OtpValidationFailedException(e.getMessage(), Map.of(ResidentConstants.EVENT_ID, eventId)); } - if (response.getErrors() != null && !response.getErrors().isEmpty()) { - response.getErrors().stream().forEach(error -> logger.error(LoggerFileConstant.SESSIONID.toString(), - LoggerFileConstant.USERID.toString(), error.getErrorCode(), error.getErrorMessage())); - throw new OtpValidationFailedException(response.getErrors().get(0).getErrorMessage(), - Map.of(ResidentConstants.EVENT_ID, eventId)); + return Tuples.of(authStatus, eventId); + } + + private String updateResidentTransactionAndSendNotification(String transactionId, String individualId, + String eventId, boolean authStatus) throws ResidentServiceCheckedException { + ResidentTransactionEntity residentTransactionEntity = null; + residentTransactionEntity = updateResidentTransaction(authStatus, transactionId, individualId, RequestType.VALIDATE_OTP); + if (residentTransactionEntity != null) { + eventId = residentTransactionEntity.getEventId(); + TemplateType templateType = authStatus == true ? TemplateType.SUCCESS : TemplateType.FAILURE; + sendNotificationV2(individualId, templateType, eventId, residentTransactionEntity.getAttributeList()); } - return Tuples.of(response.getResponse().isAuthStatus(), eventId); + return eventId; } - @Override - public boolean validateOtpv2(String transactionId, String individualId, String otp) - throws OtpValidationFailedException, ResidentServiceCheckedException { - return validateOtpV2(transactionId, individualId, otp).getT1(); + private void sendNotificationV2(String id, TemplateType templateType, String eventId, String channels) + throws ResidentServiceCheckedException { + NotificationRequestDtoV2 notificationRequestDtoV2 = new NotificationRequestDtoV2(); + notificationRequestDtoV2.setId(id); + notificationRequestDtoV2.setRequestType(RequestType.VALIDATE_OTP); + notificationRequestDtoV2.setTemplateType(templateType); + notificationRequestDtoV2.setEventId(eventId); + notificationService.sendNotification(notificationRequestDtoV2, + channels != null ? List.of(channels.split(ResidentConstants.ATTRIBUTE_LIST_DELIMITER)) : null, null, null); } - + @SuppressWarnings("null") @Override - public Tuple2 validateOtpV2(String transactionId, String individualId, String otp) + public Tuple2 validateOtpV2(String transactionId, String individualId, String otp, RequestType requestType) throws OtpValidationFailedException, ResidentServiceCheckedException { requestValidator.validateOtpCharLimit(otp); AuthResponseDTO response = null; @@ -172,14 +207,15 @@ public Tuple2 validateOtpV2(String transactionId, String indivi String authType = null; try { residentTransactionEntity = residentTransactionRepository - .findTopByRequestTrnIdAndTokenIdAndStatusCodeOrderByCrDtimesDesc(transactionId, - identityService.getIDATokenForIndividualId(individualId), EventStatusInProgress.OTP_REQUESTED.toString()); + .findTopByRequestTrnIdAndTokenIdAndStatusCodeInOrderByCrDtimesDesc(transactionId, + identityService.getIDATokenForIndividualId(individualId), + List.of(EventStatusInProgress.OTP_REQUESTED.name(), EventStatusFailure.OTP_VERIFICATION_FAILED.name())); if (residentTransactionEntity != null) { authType = residentTransactionEntity.getAuthTypeCode(); } response = internelOtpAuth(transactionId, individualId, otp); residentTransactionEntity = updateResidentTransaction(response.getResponse().isAuthStatus(), transactionId, - individualId); + individualId, requestType); if (residentTransactionEntity != null) { eventId = residentTransactionEntity.getEventId(); } @@ -229,19 +265,19 @@ public Tuple2 validateOtpV2(String transactionId, String indivi throw new OtpValidationFailedException(response.getErrors().get(0).getErrorMessage(), Map.of(ResidentConstants.EVENT_ID, eventId)); } - return Tuples.of(response.getResponse().isAuthStatus(), eventId); + return Tuples.of(response.getResponse().isAuthStatus(), residentTransactionEntity); } - - private ResidentTransactionEntity updateResidentTransaction(boolean verified,String transactionId, String individualId) throws NoSuchAlgorithmException, ResidentServiceCheckedException { + + private ResidentTransactionEntity updateResidentTransaction(boolean verified,String transactionId, String individualId, RequestType requestType) throws ResidentServiceCheckedException { ResidentTransactionEntity residentTransactionEntity = residentTransactionRepository. - findTopByRequestTrnIdAndTokenIdAndStatusCodeOrderByCrDtimesDesc(transactionId, identityService.getIDATokenForIndividualId(individualId) - , EventStatusInProgress.OTP_REQUESTED.toString()); + findTopByRequestTrnIdAndTokenIdAndStatusCodeInOrderByCrDtimesDesc(transactionId, identityService.getIDATokenForIndividualId(individualId) + , List.of(EventStatusInProgress.OTP_REQUESTED.name(), EventStatusFailure.OTP_VERIFICATION_FAILED.name())); if (residentTransactionEntity != null ) { - residentTransactionEntity.setRequestTypeCode(RequestType.VALIDATE_OTP.name()); + residentTransactionEntity.setRequestTypeCode(requestType.name()); residentTransactionEntity.setRequestSummary(verified? "OTP verified successfully": "OTP verification failed"); - residentTransactionEntity.setStatusCode(verified? "OTP_VERIFIED": "OTP_VERIFICATION_FAILED"); + residentTransactionEntity.setStatusCode(verified? EventStatusSuccess.OTP_VERIFIED.name(): EventStatusFailure.OTP_VERIFICATION_FAILED.name()); residentTransactionEntity.setStatusComment(verified? "OTP verified successfully": "OTP verification failed"); - residentTransactionEntity.setUpdBy(RESIDENT_SERVICES); + residentTransactionEntity.setUpdBy(utility.getSessionUserName()); residentTransactionEntity.setUpdDtimes(DateUtils.getUTCCurrentDateTime()); residentTransactionRepository.save(residentTransactionEntity); } diff --git a/resident/resident-service/src/main/java/io/mosip/resident/service/impl/IdentityServiceImpl.java b/resident/resident-service/src/main/java/io/mosip/resident/service/impl/IdentityServiceImpl.java index d2ca5a5d720..6fc92dccd74 100644 --- a/resident/resident-service/src/main/java/io/mosip/resident/service/impl/IdentityServiceImpl.java +++ b/resident/resident-service/src/main/java/io/mosip/resident/service/impl/IdentityServiceImpl.java @@ -180,6 +180,7 @@ public IdentityDTO getIdentity(String id, boolean fetchFace, String langCode) th identityDTO.setPhone(getMappingValue(identity, PHONE)); String dateOfBirth = getMappingValue(identity, DATE_OF_BIRTH); if(dateOfBirth != null && !dateOfBirth.isEmpty()) { + identityDTO.setDateOfBirth(dateOfBirth); DateTimeFormatter formatter=DateTimeFormatter.ofPattern(dateFormat); LocalDate localDate=LocalDate.parse(dateOfBirth, formatter); identityDTO.setYearOfBirth(Integer.toString(localDate.getYear())); @@ -280,7 +281,7 @@ public Map getIdentityAttributes(String id, String schemaType, if(attr.contains(ResidentConstants.MASK_PREFIX)) { String attributeName = attr.replace(ResidentConstants.MASK_PREFIX, ""); if(identity.containsKey(attributeName)) { - identity.put(attr, utility.convertToMaskDataFormat((String) identity.get(attributeName))); + identity.put(attr, utility.convertToMaskData((String) identity.get(attributeName))); } } }) @@ -289,7 +290,7 @@ public Map getIdentityAttributes(String id, String schemaType, logger.debug("IdentityServiceImpl::getIdentityAttributes()::exit"); return response; - } catch (ApisResourceAccessException | IOException e) { + } catch (ApisResourceAccessException e) { logger.error("Error occured in accessing identity data %s", e.getMessage()); throw new ResidentServiceCheckedException(ResidentErrorCode.API_RESOURCE_ACCESS_EXCEPTION.getErrorCode(), ResidentErrorCode.API_RESOURCE_ACCESS_EXCEPTION.getErrorMessage(), e); @@ -538,8 +539,11 @@ public String getIndividualIdForAid(String aid) return individualId; } - public String getResidentAuthenticationMode() throws ApisResourceAccessException { - return getClaimFromIdToken(this.env.getProperty(ResidentConstants.AUTHENTICATION_MODE_CLAIM_NAME)); + public String getResidentAuthenticationMode() throws ApisResourceAccessException, ResidentServiceCheckedException { + String authenticationMode = getClaimFromIdToken( + this.env.getProperty(ResidentConstants.AUTHENTICATION_MODE_CLAIM_NAME)); + String authTypeCode = utility.getAuthTypeCodefromkey(authenticationMode); + return authTypeCode; } public String getClaimFromAccessToken(String claim) { diff --git a/resident/resident-service/src/main/java/io/mosip/resident/service/impl/OrderCardServiceImpl.java b/resident/resident-service/src/main/java/io/mosip/resident/service/impl/OrderCardServiceImpl.java index 8e79d2a9809..c362a1fe719 100644 --- a/resident/resident-service/src/main/java/io/mosip/resident/service/impl/OrderCardServiceImpl.java +++ b/resident/resident-service/src/main/java/io/mosip/resident/service/impl/OrderCardServiceImpl.java @@ -128,12 +128,11 @@ private void checkConsent(String consent, ResidentTransactionEntity residentTran private ResidentTransactionEntity createResidentTransactionEntity(ResidentCredentialRequestDto requestDto, String individualId) throws ApisResourceAccessException, ResidentServiceCheckedException { - ResidentTransactionEntity residentTransactionEntity = utility.createEntity(); + ResidentTransactionEntity residentTransactionEntity = utility.createEntity(RequestType.ORDER_PHYSICAL_CARD); residentTransactionEntity.setEventId(utility.createEventId()); String attributeList = requestDto.getSharableAttributes().stream().collect(Collectors.joining(", ")); residentTransactionEntity.setAttributeList(attributeList); - residentTransactionEntity.setRequestTypeCode(RequestType.ORDER_PHYSICAL_CARD.name()); - residentTransactionEntity.setRefId(utility.convertToMaskDataFormat(individualId)); + residentTransactionEntity.setRefId(utility.convertToMaskData(individualId)); residentTransactionEntity.setIndividualId(individualId); residentTransactionEntity.setRequestedEntityId(requestDto.getIssuer()); Map partnerDetail = proxyPartnerManagementServiceImpl.getPartnerDetailFromPartnerId(requestDto.getIssuer()); @@ -307,10 +306,9 @@ public String getRedirectUrl(String partnerId, String individualId) } private ResidentTransactionEntity createResidentTransactionEntityOrderCard(String partnerId, String individualId) throws ApisResourceAccessException, ResidentServiceCheckedException { - ResidentTransactionEntity residentTransactionEntity = utility.createEntity(); + ResidentTransactionEntity residentTransactionEntity = utility.createEntity(RequestType.ORDER_PHYSICAL_CARD); residentTransactionEntity.setEventId(utility.createEventId()); - residentTransactionEntity.setRequestTypeCode(RequestType.ORDER_PHYSICAL_CARD.name()); - residentTransactionEntity.setRefId(utility.convertToMaskDataFormat(individualId)); + residentTransactionEntity.setRefId(utility.convertToMaskData(individualId)); residentTransactionEntity.setIndividualId(individualId); residentTransactionEntity.setRequestedEntityId(partnerId); Map partnerDetail = proxyPartnerManagementServiceImpl.getPartnerDetailFromPartnerId(partnerId); diff --git a/resident/resident-service/src/main/java/io/mosip/resident/service/impl/OtpManagerServiceImpl.java b/resident/resident-service/src/main/java/io/mosip/resident/service/impl/OtpManagerServiceImpl.java new file mode 100644 index 00000000000..69a09552030 --- /dev/null +++ b/resident/resident-service/src/main/java/io/mosip/resident/service/impl/OtpManagerServiceImpl.java @@ -0,0 +1,255 @@ +package io.mosip.resident.service.impl; + +import java.io.IOException; +import java.util.Arrays; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; + +import javax.xml.bind.DatatypeConverter; + +import io.mosip.resident.constant.IdType; +import org.json.simple.JSONObject; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.core.env.Environment; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.MediaType; +import org.springframework.stereotype.Service; +import org.springframework.web.client.RestTemplate; + +import io.mosip.kernel.core.http.ResponseWrapper; +import io.mosip.kernel.core.logger.spi.Logger; +import io.mosip.kernel.core.util.CryptoUtil; +import io.mosip.kernel.core.util.DateUtils; +import io.mosip.kernel.core.util.HMACUtils; +import io.mosip.preregistration.application.constant.PreRegLoginConstant; +import io.mosip.preregistration.application.constant.PreRegLoginErrorConstants; +import io.mosip.preregistration.application.dto.OTPGenerateRequestDTO; +import io.mosip.preregistration.application.dto.RequestDTO; +import io.mosip.resident.config.LoggerConfiguration; +import io.mosip.resident.constant.RequestType; +import io.mosip.resident.constant.ResidentErrorCode; +import io.mosip.resident.constant.TemplateType; +import io.mosip.resident.dto.MainRequestDTO; +import io.mosip.resident.dto.NotificationRequestDto; +import io.mosip.resident.dto.NotificationRequestDtoV2; +import io.mosip.resident.dto.OtpRequestDTOV2; +import io.mosip.resident.dto.ResidentUpdateRequestDto; +import io.mosip.resident.entity.OtpTransactionEntity; +import io.mosip.resident.exception.ApisResourceAccessException; +import io.mosip.resident.exception.ResidentServiceCheckedException; +import io.mosip.resident.exception.ResidentServiceException; +import io.mosip.resident.repository.OtpTransactionRepository; +import io.mosip.resident.service.NotificationService; +import io.mosip.resident.service.OtpManager; +import io.mosip.resident.service.ResidentService; +import io.mosip.resident.util.TemplateUtil; +import io.mosip.resident.util.Utilities; +import io.mosip.resident.validator.RequestValidator; +import reactor.util.function.Tuple2; + +/** + * @author Kamesh Shekhar Prasad + * This class is used to generate otp and validate otp. + */ +@Service +public class OtpManagerServiceImpl implements OtpManager { + + private static final Logger logger = LoggerConfiguration.logConfig(OtpManagerServiceImpl.class); + private static final String OTP_EXPIRED = "OTP_EXPIRED"; + private static final String ACCEPTED = "accepted"; + private static final String PHONE = "phone"; + private static final String EMAIL = "email"; + + @Autowired + private OtpTransactionRepository otpRepo; + + @Autowired + private Environment environment; + + @Autowired + @Qualifier("selfTokenRestTemplate") + RestTemplate restTemplate; + + @Autowired + private NotificationService notificationService; + + @Autowired + private IdentityServiceImpl identityService; + + @Autowired + private ResidentService residentService; + + @Autowired + private TemplateUtil templateUtil; + + @Autowired + private RequestValidator requestValidator; + @Autowired + private Utilities utilities; + + + @Override + public boolean sendOtp(MainRequestDTO requestDTO, String channelType, String language) throws IOException, ResidentServiceCheckedException, ApisResourceAccessException { + this.logger.info("sessionId", "idType", "id", "In sendOtp method of otpmanager service "); + String userId = requestDTO.getRequest().getUserId(); + NotificationRequestDto notificationRequestDto = new NotificationRequestDtoV2(); + notificationRequestDto.setId(identityService.getResidentIndvidualIdFromSession()); + String refId = this.hash(userId+requestDTO.getRequest().getTransactionId()); + if (this.otpRepo.checkotpsent(refId, "active", DateUtils.getUTCCurrentDateTime(), DateUtils.getUTCCurrentDateTime() + .minusMinutes(Objects.requireNonNull(this.environment.getProperty("otp.request.flooding.duration", Long.class)))) > + Objects.requireNonNull(this.environment.getProperty("otp.request.flooding.max-count", Integer.class))) { + this.logger.error("sessionId", this.getClass().getSimpleName(), ResidentErrorCode.OTP_REQUEST_FLOODED.getErrorCode(), "OTP_REQUEST_FLOODED"); + throw new ResidentServiceCheckedException(ResidentErrorCode.OTP_REQUEST_FLOODED.getErrorCode(), ResidentErrorCode.OTP_REQUEST_FLOODED.getErrorMessage()); + } else { + String otp = this.generateOTP(requestDTO); + this.logger.info("sessionId", "idType", "id", "In generateOTP method of otpmanager service OTP generated"); + String otpHash = digestAsPlainText((userId + this.environment.getProperty("mosip.kernel.data-key-splitter") + otp+ + requestDTO.getRequest().getTransactionId()).getBytes()); + OtpTransactionEntity otpTxn; + otpTxn = new OtpTransactionEntity(); + otpTxn.setId(UUID.randomUUID().toString()); + otpTxn.setRefId(this.hash(userId + requestDTO.getRequest().getTransactionId())); + otpTxn.setOtpHash(otpHash); + otpTxn.setCrBy(this.environment.getProperty("resident.clientId")); + otpTxn.setCrDtimes(DateUtils.getUTCCurrentDateTime()); + otpTxn.setGeneratedDtimes(DateUtils.getUTCCurrentDateTime()); + otpTxn.setExpiryDtimes(DateUtils.getUTCCurrentDateTime().plusSeconds((Long) + this.environment.getProperty("mosip.kernel.otp.expiry-time", Long.class))); + otpTxn.setStatusCode("active"); + this.otpRepo.save(otpTxn); + if (channelType.equalsIgnoreCase("phone")) { + this.logger.info("sessionId", "idType", "id", "In generateOTP method of otpmanager service invoking sms notification"); + NotificationRequestDtoV2 notificationRequestDtoV2=(NotificationRequestDtoV2) notificationRequestDto; + notificationRequestDtoV2.setTemplateType(TemplateType.SUCCESS); + notificationRequestDtoV2.setRequestType(RequestType.SEND_OTP); + notificationRequestDtoV2.setOtp(otp); + notificationService + .sendNotification(notificationRequestDto, List.of(channelType), null, userId); + } + + if (channelType.equalsIgnoreCase("email")) { + this.logger.info("sessionId", "idType", "id", "In generateOTP method of otpmanager service invoking email notification"); + NotificationRequestDtoV2 notificationRequestDtoV2=(NotificationRequestDtoV2) notificationRequestDto; + notificationRequestDtoV2.setTemplateType(TemplateType.SUCCESS); + notificationRequestDtoV2.setRequestType(RequestType.SEND_OTP); + notificationRequestDtoV2.setOtp(otp); + notificationService + .sendNotification(notificationRequestDto, List.of(channelType), userId, null); + } + + return true; + } + } + + private String generateOTP(MainRequestDTO requestDTO) { + this.logger.info("sessionId", "idType", "id", "In generateOTP method of otpmanager service "); + + try { + OTPGenerateRequestDTO otpRequestDTO = new OTPGenerateRequestDTO(); + otpRequestDTO.setId(requestDTO.getId()); + otpRequestDTO.setRequesttime(requestDTO.getRequesttime()); + otpRequestDTO.setVersion(requestDTO.getVersion()); + RequestDTO req = new RequestDTO(); + req.setKey(requestDTO.getRequest().getUserId()); + otpRequestDTO.setRequest(req); + HttpHeaders headers1 = new HttpHeaders(); + headers1.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); + headers1.setContentType(MediaType.APPLICATION_JSON_UTF8); + headers1.add("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36"); + HttpEntity entity1 = new HttpEntity(otpRequestDTO, headers1); + ResponseWrapper> response = (ResponseWrapper)this.restTemplate.exchange(this.environment.getProperty("otp-generate.rest.uri"), HttpMethod.POST, entity1, ResponseWrapper.class, new Object[0]).getBody(); + String otp = null; + if (response != null) { + Map res = (Map)response.getResponse(); + if (res != null) { + if (((String)res.get("status")).equals("USER_BLOCKED")) { + this.logger.error("sessionId", this.getClass().getSimpleName(), ResidentErrorCode.BLOCKED_OTP_VALIDATE.getErrorCode(), "USER_BLOCKED"); + throw new ResidentServiceException(ResidentErrorCode.BLOCKED_OTP_VALIDATE.getErrorCode(), ResidentErrorCode.BLOCKED_OTP_VALIDATE.getErrorMessage()); + } + + otp = res.get("otp"); + } + } + + return otp; + } catch (ResidentServiceException var9) { + this.logger.error("sessionId", this.getClass().getSimpleName(), "generateOTP", var9.getMessage()); + throw new ResidentServiceException(ResidentErrorCode.UNABLE_TO_PROCESS.getErrorCode(), ResidentErrorCode.UNABLE_TO_PROCESS.getErrorMessage()); + } catch (Exception var10) { + this.logger.error("sessionId", this.getClass().getSimpleName(), ResidentErrorCode.SERVER_ERROR.getErrorCode(), ResidentErrorCode.SERVER_ERROR.getErrorMessage()); + throw new ResidentServiceException(ResidentErrorCode.SERVER_ERROR.getErrorCode(), ResidentErrorCode.SERVER_ERROR.getErrorMessage()); + } + } + + @Override + public boolean validateOtp(String otp, String userId, String transactionId) throws ApisResourceAccessException, ResidentServiceCheckedException { + logger.info("sessionId", "idType", "id", "In validateOtp method of otpmanager service "); + String otpHash; + otpHash = digestAsPlainText( + (userId + this.environment.getProperty("mosip.kernel.data-key-splitter") + otp+transactionId).getBytes()); + + if (!otpRepo.existsByOtpHashAndStatusCode(otpHash, PreRegLoginConstant.ACTIVE_STATUS)) { + return false; + } + + OtpTransactionEntity otpTxn = otpRepo.findTopByOtpHashAndStatusCode(otpHash, PreRegLoginConstant.ACTIVE_STATUS); + otpTxn.setStatusCode(PreRegLoginConstant.USED_STATUS); + otpRepo.save(otpTxn); + if (!(otpTxn.getExpiryDtimes().isAfter(DateUtils.getUTCCurrentDateTime()))) { + logger.error(PreRegLoginConstant.SESSION_ID, this.getClass().getSimpleName(), + PreRegLoginErrorConstants.EXPIRED_OTP.getErrorCode(), OTP_EXPIRED); + throw new ResidentServiceException(ResidentErrorCode.EXPIRED_OTP.getErrorCode(), + ResidentErrorCode.EXPIRED_OTP.getErrorMessage()); + } + return true; + } + + public Tuple2 updateUserId(String userId, String transactionId) throws ApisResourceAccessException, ResidentServiceCheckedException, IOException { + ResidentUpdateRequestDto residentUpdateRequestDto = new ResidentUpdateRequestDto(); + String individualId= identityService.getResidentIndvidualIdFromSession(); + String individualIdType = templateUtil.getIndividualIdType(); + residentUpdateRequestDto.setIndividualId(individualId); + residentUpdateRequestDto.setConsent(ACCEPTED); + residentUpdateRequestDto.setIdentityJson(getIdentityJson(individualId, transactionId, userId, individualIdType)); + residentUpdateRequestDto.setIndividualIdType(individualIdType); + return residentService.reqUinUpdate(residentUpdateRequestDto); + } + + public String getIdentityJson(String individualId, String transactionId, String userId, String individualIdType) throws ApisResourceAccessException, IOException { + Map identityMap = new LinkedHashMap(); + JSONObject obj = utilities.retrieveIdrepoJson(individualId); + String idSchemaVersionStr = String.valueOf(obj.get("IDSchemaVersion")); + String uin = String.valueOf(obj.get(IdType.UIN.name())); + identityMap.put("IDSchemaVersion", idSchemaVersionStr); + identityMap.put(IdType.UIN.name(), uin); + String channel = getChannel(userId, transactionId); + identityMap.put(channel, userId); + JSONObject jsonObject = new JSONObject(); + jsonObject.put("identity", identityMap); + String str = CryptoUtil.encodeToPlainBase64(jsonObject.toString().getBytes()); + return String.valueOf(str); + } + + public String getChannel(String userId, String transactionId) { + List channels = requestValidator.validateUserIdAndTransactionId(userId, transactionId); + if(channels.get(0).equalsIgnoreCase(PHONE)){ + return PHONE; + } else{ + return EMAIL; + } + } + + public static String digestAsPlainText(byte[] data) { + return DatatypeConverter.printHexBinary(data).toUpperCase(); + } + + public String hash(String id) throws ResidentServiceException { + return HMACUtils.digestAsPlainText(id.getBytes()); + } +} diff --git a/resident/resident-service/src/main/java/io/mosip/resident/service/impl/PinUnpinStatusServiceImpl.java b/resident/resident-service/src/main/java/io/mosip/resident/service/impl/PinUnpinStatusServiceImpl.java index b44b78f5e36..f3ece236756 100644 --- a/resident/resident-service/src/main/java/io/mosip/resident/service/impl/PinUnpinStatusServiceImpl.java +++ b/resident/resident-service/src/main/java/io/mosip/resident/service/impl/PinUnpinStatusServiceImpl.java @@ -54,7 +54,8 @@ public class PinUnpinStatusServiceImpl implements PinUnpinStatusService { private String unPinnedStatusVersion; @Override - public ResponseWrapper pinStatus(String eventId, boolean status) { + public ResponseWrapper pinStatus(String eventId, boolean status) + throws ResidentServiceCheckedException { try { Optional optionalResidentTransactionEntity = residentTransactionRepository.findById(eventId); if (optionalResidentTransactionEntity.isPresent()) { diff --git a/resident/resident-service/src/main/java/io/mosip/resident/service/impl/ProxyIdRepoServiceImpl.java b/resident/resident-service/src/main/java/io/mosip/resident/service/impl/ProxyIdRepoServiceImpl.java index 4dbe08d53b7..a7cfe8aa9a2 100644 --- a/resident/resident-service/src/main/java/io/mosip/resident/service/impl/ProxyIdRepoServiceImpl.java +++ b/resident/resident-service/src/main/java/io/mosip/resident/service/impl/ProxyIdRepoServiceImpl.java @@ -6,6 +6,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.stream.Collectors; import org.apache.commons.lang3.exception.ExceptionUtils; @@ -49,7 +50,7 @@ public ResponseWrapper getRemainingUpdateCountByIndividualId(List att queryParamName.add("attribute_list"); List queryParamValue = new ArrayList<>(); - queryParamValue.add(attributeList.stream().collect(Collectors.joining(","))); + queryParamValue.add(Objects.isNull(attributeList) ? "" : attributeList.stream().collect(Collectors.joining(","))); ResponseWrapper responseWrapper = residentServiceRestClient.getApi(ApiName.IDREPO_IDENTITY_UPDATE_COUNT, pathsegements, queryParamName, queryParamValue, ResponseWrapper.class); diff --git a/resident/resident-service/src/main/java/io/mosip/resident/service/impl/ProxyMasterdataServiceImpl.java b/resident/resident-service/src/main/java/io/mosip/resident/service/impl/ProxyMasterdataServiceImpl.java index c2f2af26814..66538779c3c 100644 --- a/resident/resident-service/src/main/java/io/mosip/resident/service/impl/ProxyMasterdataServiceImpl.java +++ b/resident/resident-service/src/main/java/io/mosip/resident/service/impl/ProxyMasterdataServiceImpl.java @@ -1,5 +1,7 @@ package io.mosip.resident.service.impl; +import static io.mosip.resident.constant.MappingJsonConstants.GENDER; + import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; @@ -72,6 +74,7 @@ public ResponseWrapper getValidDocumentByLangCode(String langCode) throws Res ResponseWrapper.class); if (responseWrapper.getErrors() != null && !responseWrapper.getErrors().isEmpty()) { + auditUtil.setAuditRequestDto(EventEnum.GET_VALID_DOCUMENT_EXCEPTION); logger.debug(responseWrapper.getErrors().get(0).toString()); throw new ResidentServiceCheckedException(ResidentErrorCode.BAD_REQUEST.getErrorCode(), responseWrapper.getErrors().get(0).getMessage()); @@ -128,6 +131,7 @@ public ResponseWrapper getLocationHierarchyLevelByLangCode(String langCode) pathsegments, ResponseWrapper.class); if (responseWrapper.getErrors() != null && !responseWrapper.getErrors().isEmpty()) { + auditUtil.setAuditRequestDto(EventEnum.GET_LOCATION_HIERARCHY_LEVEL_EXCEPTION); logger.debug(responseWrapper.getErrors().get(0).toString()); throw new ResidentServiceCheckedException(ResidentErrorCode.BAD_REQUEST.getErrorCode(), responseWrapper.getErrors().get(0).getMessage()); @@ -155,6 +159,7 @@ public ResponseWrapper getImmediateChildrenByLocCodeAndLangCode(String locati ApiName.IMMEDIATE_CHILDREN_BY_LOCATIONCODE_AND_LANGCODE_URL, pathsegments, ResponseWrapper.class); if (responseWrapper.getErrors() != null && !responseWrapper.getErrors().isEmpty()) { + auditUtil.setAuditRequestDto(EventEnum.GET_IMMEDIATE_CHILDREN_EXCEPTION); logger.debug(responseWrapper.getErrors().get(0).toString()); throw new ResidentServiceCheckedException(ResidentErrorCode.BAD_REQUEST.getErrorCode(), responseWrapper.getErrors().get(0).getMessage()); @@ -182,6 +187,7 @@ public ResponseWrapper getLocationDetailsByLocCodeAndLangCode(String location pathsegments, ResponseWrapper.class); if (responseWrapper.getErrors() != null && !responseWrapper.getErrors().isEmpty()) { + auditUtil.setAuditRequestDto(EventEnum.GET_LOCATION_DETAILS_EXCEPTION); logger.debug(responseWrapper.getErrors().get(0).toString()); throw new ResidentServiceCheckedException(ResidentErrorCode.BAD_REQUEST.getErrorCode(), responseWrapper.getErrors().get(0).getMessage()); @@ -211,6 +217,7 @@ public ResponseWrapper getCoordinateSpecificRegistrationCenters(String langCo pathsegements, ResponseWrapper.class); if (responseWrapper.getErrors() != null && !responseWrapper.getErrors().isEmpty()) { + auditUtil.setAuditRequestDto(EventEnum.GET_COORDINATE_SPECIFIC_REG_CENTERS_EXCEPTION); logger.debug(responseWrapper.getErrors().get(0).toString()); throw new ResidentServiceCheckedException(ResidentErrorCode.BAD_REQUEST.getErrorCode(), responseWrapper.getErrors().get(0).getMessage()); @@ -279,6 +286,7 @@ public ResponseWrapper getRegistrationCentersByHierarchyLevel(String langCode pathsegements, queryParamName, queryParamValue, ResponseWrapper.class); if (responseWrapper.getErrors() != null && !responseWrapper.getErrors().isEmpty()) { + auditUtil.setAuditRequestDto(EventEnum.GET_REG_CENTERS_FOR_LOCATION_CODE_EXCEPTION); logger.debug(responseWrapper.getErrors().get(0).toString()); throw new ResidentServiceCheckedException(ResidentErrorCode.BAD_REQUEST.getErrorCode(), responseWrapper.getErrors().get(0).getMessage()); @@ -323,6 +331,7 @@ public ResponseWrapper getRegistrationCenterByHierarchyLevelAndTextPaginated( queryParamName, queryParamValue, ResponseWrapper.class); if (responseWrapper.getErrors() != null && !responseWrapper.getErrors().isEmpty()) { + auditUtil.setAuditRequestDto(EventEnum.GET_REG_CENTERS_PAGINATED_EXCEPTION); logger.debug(responseWrapper.getErrors().get(0).toString()); throw new ResidentServiceCheckedException(ResidentErrorCode.BAD_REQUEST.getErrorCode(), responseWrapper.getErrors().get(0).getMessage()); @@ -350,6 +359,7 @@ public ResponseWrapper getRegistrationCenterWorkingDays(String registrationCe ResponseWrapper.class); if (responseWrapper.getErrors() != null && !responseWrapper.getErrors().isEmpty()) { + auditUtil.setAuditRequestDto(EventEnum.GET_REG_CENTER_WORKING_DAYS_EXCEPTION); logger.debug(responseWrapper.getErrors().get(0).toString()); throw new ResidentServiceCheckedException(ResidentErrorCode.BAD_REQUEST.getErrorCode(), responseWrapper.getErrors().get(0).getMessage()); @@ -386,6 +396,7 @@ public ResponseWrapper getLatestIdSchema(double schemaVersion, String domain, responseWrapper = (ResponseWrapper) residentServiceRestClient.getApi(ApiName.LATEST_ID_SCHEMA_URL, pathsegements, queryParamName, queryParamValue, ResponseWrapper.class); if (responseWrapper.getErrors() != null && !responseWrapper.getErrors().isEmpty()) { + auditUtil.setAuditRequestDto(EventEnum.GET_LATEST_ID_SCHEMA_EXCEPTION); logger.debug(responseWrapper.getErrors().get(0).toString()); throw new ResidentServiceCheckedException(ResidentErrorCode.BAD_REQUEST.getErrorCode(), responseWrapper.getErrors().get(0).getMessage()); @@ -413,6 +424,7 @@ public ResponseWrapper getAllTemplateBylangCodeAndTemplateTypeCode(String lan response = residentServiceRestClient.getApi(ApiName.TEMPLATES_BY_LANGCODE_AND_TEMPLATETYPECODE_URL, pathsegments, ResponseWrapper.class); if (response.getErrors() != null && !response.getErrors().isEmpty()) { + auditUtil.setAuditRequestDto(EventEnum.GET_TEMPLATES_EXCEPTION); logger.debug(response.getErrors().get(0).toString()); throw new ResidentServiceCheckedException(ResidentErrorCode.TEMPLATE_EXCEPTION); } @@ -432,21 +444,29 @@ public ResponseWrapper getAllTemplateBylangCodeAndTemplateTypeCode(String lan throw new ResidentServiceCheckedException(ResidentErrorCode.API_RESOURCE_ACCESS_EXCEPTION.getErrorCode(), ResidentErrorCode.API_RESOURCE_ACCESS_EXCEPTION.getErrorMessage(), e); } catch (IOException e) { + auditUtil.setAuditRequestDto(EventEnum.GET_TEMPLATES_EXCEPTION); throw new ResidentServiceCheckedException(ResidentErrorCode.IO_EXCEPTION.getErrorCode(), ResidentErrorCode.IO_EXCEPTION.getErrorMessage(), e); } } @Override - public ResponseWrapper getGenderTypesByLangCode(String langCode) throws ResidentServiceCheckedException { - logger.debug("ProxyMasterdataServiceImpl::getGenderTypesByLangCode()::entry"); + public ResponseWrapper getDynamicFieldBasedOnLangCodeAndFieldName(String fieldName, String langCode, boolean withValue) throws ResidentServiceCheckedException { + logger.debug("ProxyMasterdataServiceImpl::getDynamicFieldBasedOnLangCodeAndFieldName()::entry"); ResponseWrapper responseWrapper = new ResponseWrapper<>(); Map pathsegments = new HashMap(); pathsegments.put("langcode", langCode); + pathsegments.put("fieldName", fieldName); + List queryParamName = new ArrayList(); + queryParamName.add("withValue"); + + List queryParamValue = new ArrayList<>(); + queryParamValue.add(withValue); try { - responseWrapper = residentServiceRestClient.getApi(ApiName.GENDER_TYPE_BY_LANGCODE, pathsegments, - ResponseWrapper.class); + responseWrapper = residentServiceRestClient.getApi(ApiName.DYNAMIC_FIELD_BASED_ON_LANG_CODE_AND_FIELD_NAME, pathsegments, queryParamName, + queryParamValue, ResponseWrapper.class); if (responseWrapper.getErrors() != null && !responseWrapper.getErrors().isEmpty()) { + auditUtil.setAuditRequestDto(EventEnum.GET_GENDER_TYPES_EXCEPTION); logger.debug(responseWrapper.getErrors().get(0).toString()); throw new ResidentServiceCheckedException(ResidentErrorCode.BAD_REQUEST.getErrorCode(), responseWrapper.getErrors().get(0).getMessage()); @@ -457,7 +477,7 @@ public ResponseWrapper getGenderTypesByLangCode(String langCode) throws Resid throw new ResidentServiceCheckedException(ResidentErrorCode.API_RESOURCE_ACCESS_EXCEPTION.getErrorCode(), ResidentErrorCode.API_RESOURCE_ACCESS_EXCEPTION.getErrorMessage(), e); } - logger.debug("ProxyMasterdataServiceImpl::getGenderTypesByLangCode()::exit"); + logger.debug("ProxyMasterdataServiceImpl::getDynamicFieldBasedOnLangCodeAndFieldName()::exit"); return responseWrapper; } @@ -471,6 +491,7 @@ public ResponseWrapper getDocumentTypesByDocumentCategoryAndLangCode(String d try { responseWrapper=residentServiceRestClient.getApi(ApiName.DOCUMENT_TYPE_BY_DOCUMENT_CATEGORY_AND_LANG_CODE, pathsegments, ResponseWrapper.class); if (responseWrapper.getErrors() != null && !responseWrapper.getErrors().isEmpty()) { + auditUtil.setAuditRequestDto(EventEnum.GET_DOCUMENT_TYPES_EXCEPTION); logger.debug(responseWrapper.getErrors().get(0).toString()); throw new ResidentServiceCheckedException(ResidentErrorCode.BAD_REQUEST.getErrorCode(), responseWrapper.getErrors().get(0).getMessage()); @@ -491,7 +512,7 @@ public ResponseWrapper getGenderCodeByGenderTypeAndLangCo logger.debug("ProxyMasterdataServiceImpl::getGenderCodeByGenderTypeAndLangCode()::entry"); ResponseWrapper responseWrapper = new ResponseWrapper<>(); GenderCodeResponseDTO genderCodeResponseDTO = new GenderCodeResponseDTO(); - ResponseWrapper res = getGenderTypesByLangCode(langCode); + ResponseWrapper res = getDynamicFieldBasedOnLangCodeAndFieldName(GENDER, langCode, true); GenderTypeListDTO response = JsonUtil.readValue(JsonUtil.writeValueAsString(res.getResponse()), GenderTypeListDTO.class); Optional genderCode = response.getGenderType().stream() diff --git a/resident/resident-service/src/main/java/io/mosip/resident/service/impl/ProxyOtpServiceImpl.java b/resident/resident-service/src/main/java/io/mosip/resident/service/impl/ProxyOtpServiceImpl.java new file mode 100644 index 00000000000..8d362280808 --- /dev/null +++ b/resident/resident-service/src/main/java/io/mosip/resident/service/impl/ProxyOtpServiceImpl.java @@ -0,0 +1,211 @@ +package io.mosip.resident.service.impl; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Service; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.web.client.HttpServerErrorException; + +import io.mosip.kernel.core.authmanager.model.AuthNResponse; +import io.mosip.kernel.core.logger.spi.Logger; +import io.mosip.kernel.core.util.DateUtils; +import io.mosip.preregistration.application.constant.PreRegLoginConstant; +import io.mosip.preregistration.core.util.GenericUtil; +import io.mosip.resident.config.LoggerConfiguration; +import io.mosip.resident.constant.ResidentConstants; +import io.mosip.resident.constant.ResidentErrorCode; +import io.mosip.resident.dto.ExceptionJSONInfoDTO; +import io.mosip.resident.dto.MainRequestDTO; +import io.mosip.resident.dto.MainResponseDTO; +import io.mosip.resident.dto.OtpRequestDTOV2; +import io.mosip.resident.dto.OtpRequestDTOV3; +import io.mosip.resident.exception.ApisResourceAccessException; +import io.mosip.resident.exception.ResidentServiceCheckedException; +import io.mosip.resident.exception.ResidentServiceException; +import io.mosip.resident.service.OtpManager; +import io.mosip.resident.service.ProxyOtpService; +import io.mosip.resident.util.AuditUtil; +import io.mosip.resident.util.EventEnum; +import io.mosip.resident.util.Utility; +import io.mosip.resident.validator.RequestValidator; +import reactor.util.function.Tuple2; +import reactor.util.function.Tuples; + +/** + * @author Kamesh Shekhar Prasad + * This class is used to implement opt service impl class. + */ +@Service +public class ProxyOtpServiceImpl implements ProxyOtpService { + + private Logger log = LoggerConfiguration.logConfig(ProxyOtpServiceImpl.class); + + private List otpChannel; + + @Autowired + private OtpManager otpManager; + + @Autowired + private AuditUtil audit; + + @Autowired + RequestValidator requestValidator; + + @Autowired + private IdentityServiceImpl identityServiceImpl; + + @Autowired + private Utility utility; + + @Value("${mosip.mandatory-languages}") + private String mandatoryLanguage; + + @Override + public ResponseEntity> sendOtp(MainRequestDTO userOtpRequest) { + MainResponseDTO response = new MainResponseDTO<>(); + String userid = null; + boolean isSuccess = false; + String language = mandatoryLanguage; + log.info("In callsendOtp method of login service with userID: {} and langCode", + userOtpRequest.getRequest().getUserId(), language); + + try { + response = (MainResponseDTO) getMainResponseDto(userOtpRequest); + log.info("Response after loginCommonUtil {}", response); + + userid = userOtpRequest.getRequest().getUserId(); + otpChannel = requestValidator.validateUserIdAndTransactionId(userid, userOtpRequest.getRequest().getTransactionId()); + boolean otpSent = otpManager.sendOtp(userOtpRequest, otpChannel.get(0), language); + AuthNResponse authNResponse = null; + if (otpSent) { + if (otpChannel.get(0).equalsIgnoreCase(PreRegLoginConstant.PHONE_NUMBER)) + authNResponse = new AuthNResponse(PreRegLoginConstant.SMS_SUCCESS, PreRegLoginConstant.SUCCESS); + else + authNResponse = new AuthNResponse(PreRegLoginConstant.EMAIL_SUCCESS, PreRegLoginConstant.SUCCESS); + response.setResponse(authNResponse); + isSuccess = true; + } else + isSuccess = false; + + response.setResponsetime(DateUtils.getUTCCurrentDateTimeString()); + } catch (HttpServerErrorException | HttpClientErrorException ex) { + log.error("In callsendOtp method of login service- ", ex.getResponseBodyAsString()); + audit.setAuditRequestDto(EventEnum.getEventEnumWithValue(EventEnum.SEND_OTP_FAILURE, + userid, "Send OTP")); + if(ex instanceof HttpServerErrorException || ex instanceof HttpClientErrorException){ + throw new ResidentServiceException(ResidentErrorCode.CONFIG_FILE_NOT_FOUND_EXCEPTION.getErrorCode(), + ResidentErrorCode.CONFIG_FILE_NOT_FOUND_EXCEPTION.getErrorMessage()); + } + } + catch (Exception ex) { + log.error("In callsendOtp method of login service- ", ex); + audit.setAuditRequestDto(EventEnum.getEventEnumWithValue(EventEnum.SEND_OTP_FAILURE, + userid, "Send OTP")); + throw new ResidentServiceException(ResidentErrorCode.SEND_OTP_FAILED.getErrorCode(), + ResidentErrorCode.SEND_OTP_FAILED.getErrorMessage(), ex); + } finally { + if (isSuccess) { + audit.setAuditRequestDto(EventEnum.getEventEnumWithValue(EventEnum.SEND_OTP_SUCCESS, + userid, "Send OTP")); + } else { + + ExceptionJSONInfoDTO errors = new ExceptionJSONInfoDTO(ResidentErrorCode.SEND_OTP_FAILED.getErrorCode(), + ResidentErrorCode.SEND_OTP_FAILED.getErrorMessage()); + List lst = new ArrayList<>(); + lst.add(errors); + response.setErrors(lst); + response.setResponse(null); + audit.setAuditRequestDto(EventEnum.getEventEnumWithValue(EventEnum.SEND_OTP_FAILURE, + userid, "Send OTP")); + } + } + return ResponseEntity.status(HttpStatus.OK).body(response); + } + + @Override + public Tuple2, String> validateWithUserIdOtp(MainRequestDTO userIdOtpRequest) { + log.info("In calluserIdOtp method of login service "); + MainResponseDTO response = null; + response = (MainResponseDTO) getMainResponseDto(userIdOtpRequest); + String userid = null; + String transactionId = null; + boolean isSuccess = false; + String eventId = ResidentConstants.NOT_AVAILABLE; + + try { + OtpRequestDTOV3 user = userIdOtpRequest.getRequest(); + userid = user.getUserId(); + transactionId = user.getTransactionId(); + boolean validated = otpManager.validateOtp(user.getOtp(), userid, transactionId); + AuthNResponse authresponse = new AuthNResponse(); + if (validated) { + Tuple2 updateResult = otpManager.updateUserId(userid, transactionId); + eventId = updateResult.getT2(); + authresponse.setMessage(PreRegLoginConstant.VALIDATION_SUCCESS); + authresponse.setStatus(PreRegLoginConstant.SUCCESS); + } else { + throw new ResidentServiceException(ResidentErrorCode.OTP_VALIDATION_FAILED, + Map.of(ResidentConstants.EVENT_ID, eventId)); + } + response.setResponse(authresponse); + isSuccess = true; + } catch (ResidentServiceException ex) { + log.error("In calluserIdOtp method of login service- ", ex); + ex.setMetadata(Map.of(ResidentConstants.EVENT_ID, eventId)); + throw ex; + } catch (RuntimeException ex) { + log.error("In calluserIdOtp method of login service- ", ex); + throw new ResidentServiceException(ResidentErrorCode.OTP_VALIDATION_FAILED, ex, + Map.of(ResidentConstants.EVENT_ID, eventId)); + } catch (ResidentServiceCheckedException e) { + throw new ResidentServiceException(ResidentErrorCode.OTP_VALIDATION_FAILED, e, + Map.of(ResidentConstants.EVENT_ID, eventId)); + } catch (ApisResourceAccessException e) { + throw new ResidentServiceException(ResidentErrorCode.API_RESOURCE_ACCESS_EXCEPTION, e, + Map.of(ResidentConstants.EVENT_ID, eventId)); + } catch (IOException e) { + throw new ResidentServiceException(ResidentErrorCode.IO_EXCEPTION, e, + Map.of(ResidentConstants.EVENT_ID, eventId)); + } finally { + response.setResponsetime(GenericUtil.getCurrentResponseTime()); + + if (isSuccess) { + audit.setAuditRequestDto(EventEnum.getEventEnumWithValue(EventEnum.VALIDATE_OTP_SUCCESS, + userid, "Validate OTP Success")); + } else { + ExceptionJSONInfoDTO errors = new ExceptionJSONInfoDTO(ResidentErrorCode.OTP_VALIDATION_FAILED.getErrorCode(), + ResidentErrorCode.OTP_VALIDATION_FAILED.getErrorMessage()); + List lst = new ArrayList<>(); + lst.add(errors); + response.setErrors(lst); + response.setResponse(null); + audit.setAuditRequestDto(EventEnum.getEventEnumWithValue(EventEnum.OTP_VALIDATION_FAILED, + userid, "Validate OTP Failed")); + } + + } + return Tuples.of(response, eventId); + } + + /** + * This method will return the MainResponseDTO with id and version + * + * @param mainRequestDto + * @return MainResponseDTO + */ + public MainResponseDTO getMainResponseDto(MainRequestDTO mainRequestDto) { + log.info("In getMainResponseDTO method of ProxyOtpServiceImpl"); + MainResponseDTO response = new MainResponseDTO<>(); + response.setId(mainRequestDto.getId()); + response.setVersion(mainRequestDto.getVersion()); + return response; + } + +} diff --git a/resident/resident-service/src/main/java/io/mosip/resident/service/impl/ResidentConfigServiceImpl.java b/resident/resident-service/src/main/java/io/mosip/resident/service/impl/ResidentConfigServiceImpl.java index 01943838ff2..ac798ab469b 100644 --- a/resident/resident-service/src/main/java/io/mosip/resident/service/impl/ResidentConfigServiceImpl.java +++ b/resident/resident-service/src/main/java/io/mosip/resident/service/impl/ResidentConfigServiceImpl.java @@ -2,7 +2,9 @@ import java.io.IOException; import java.nio.charset.StandardCharsets; +import java.util.ArrayList; import java.util.Arrays; +import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; @@ -22,13 +24,18 @@ import com.fasterxml.jackson.databind.ObjectMapper; import io.mosip.kernel.core.http.ResponseWrapper; +import io.mosip.kernel.core.logger.spi.Logger; import io.mosip.kernel.core.util.StringUtils; +import io.mosip.resident.config.LoggerConfiguration; +import io.mosip.resident.constant.MappingJsonConstants; import io.mosip.resident.constant.ResidentConstants; import io.mosip.resident.constant.ResidentErrorCode; import io.mosip.resident.dto.SharableAttributesDTO; import io.mosip.resident.exception.ResidentServiceCheckedException; import io.mosip.resident.exception.ResidentServiceException; import io.mosip.resident.handler.service.ResidentConfigService; +import io.mosip.resident.util.AuditUtil; +import io.mosip.resident.util.EventEnum; import io.mosip.resident.util.Utility; /** @@ -37,14 +44,8 @@ */ @Component public class ResidentConfigServiceImpl implements ResidentConfigService { - - private static final String VALUE = "value"; private static final String UI_SCHEMA_ATTRIBUTE_NAME = "mosip.resident.schema.attribute-name"; - - private static final String MASK_REQUIRED = "maskRequired"; - - private static final String IDENTITY = "identity"; /** The prop keys. */ @Value("${resident.ui.propertyKeys:}") @@ -76,6 +77,11 @@ public class ResidentConfigServiceImpl implements ResidentConfigService { @Value("${resident.ui.properties.version}") private String residentUiPropertiesVersion; + @Autowired + private AuditUtil auditUtil; + + private static final Logger logger = LoggerConfiguration.logConfig(ResidentConfigServiceImpl.class); + /** * Gets the properties. * @@ -115,38 +121,31 @@ public String getUISchema(String schemaType) { if (residentUiSchemaJsonFileRes.exists()) { uiSchema = Utility.readResourceContent(residentUiSchemaJsonFileRes); } else { + auditUtil.setAuditRequestDto(EventEnum.GET_CONFIGURATION_PROPERTIES_EXCEPTION); throw new ResidentServiceException(ResidentErrorCode.API_RESOURCE_UNAVAILABLE); } return uiSchema; } @Override - @Cacheable(value="ui-schema-filtered-attributes", key="#schemaType") - public List getUiSchemaFilteredInputAttributes(String schemaType) throws JsonParseException, JsonMappingException, IOException { - return doGetUiSchemaFilteredInputAttributes(schemaType); - } - - private List doGetUiSchemaFilteredInputAttributes(String schemaType) throws JsonParseException, JsonMappingException, IOException { - String uiSchema = getUISchema(schemaType); - Map schemaMap = objectMapper.readValue(uiSchema.getBytes(StandardCharsets.UTF_8), Map.class); - Object identityObj = schemaMap.get(IDENTITY); - if(identityObj instanceof List) { - List> identityList = (List>) identityObj; - List uiSchemaFilteredInputAttributesList = identityList.stream() - .flatMap(map -> { - String attribName = (String)map.get(env.getProperty(UI_SCHEMA_ATTRIBUTE_NAME)); - if(Boolean.valueOf(String.valueOf(map.get(MASK_REQUIRED)))) { - //Include the attribute and its masked attribute - return Stream.of(attribName, ResidentConstants.MASK_PREFIX + attribName); - } else { - return Stream.of(attribName); - } - }) - .collect(Collectors.toList()); - return uiSchemaFilteredInputAttributesList; - } - return null; - + @Cacheable(value = "ui-schema-filtered-attributes", key = "#schemaType") + public List getUiSchemaFilteredInputAttributes(String schemaType) { + List> identityList = getUISchemaData(schemaType); + List uiSchemaFilteredInputAttributesList = identityList.stream().flatMap(map -> { + List attributeList = new ArrayList<>(); + attributeList.add((String) map.get(env.getProperty(UI_SCHEMA_ATTRIBUTE_NAME))); + if (Boolean.valueOf(String.valueOf(map.get(ResidentConstants.MASK_REQUIRED)))) { + attributeList.add(String.valueOf(map.get(ResidentConstants.MASK_ATTRIBUTE_NAME))); + } + if (Boolean.valueOf(String.valueOf(map.get(ResidentConstants.FORMAT_REQUIRED)))) { + attributeList.addAll( + ((List>) ((Map) map.get(ResidentConstants.FORMAT_OPTION)) + .entrySet().stream().findFirst().get().getValue()).stream() + .map(x -> x.get(ResidentConstants.VALUE)).collect(Collectors.toList())); + } + return attributeList.stream(); + }).distinct().collect(Collectors.toList()); + return uiSchemaFilteredInputAttributesList; } @Override @@ -161,38 +160,104 @@ public List getSharableAttributesList(List sharab throws ResidentServiceCheckedException, JsonParseException, JsonMappingException, IOException { // identity mapping json - String identityMapping = getIdentityMapping(); - Map identityMappingMap = objectMapper - .readValue(identityMapping.getBytes(StandardCharsets.UTF_8), Map.class); - Object identityObj = identityMappingMap.get(IDENTITY); - Map identityMap = (Map) identityObj; + Map identityMap = getIdentityMappingMap(); // ui schema share credential json - String uiSchema = getUISchema(schemaType); - Map schemaMap = objectMapper.readValue(uiSchema.getBytes(StandardCharsets.UTF_8), Map.class); - Object identitySchemaObj = schemaMap.get(IDENTITY); - List> identityList = (List>) identitySchemaObj; + List> identityList = getUISchemaData(schemaType); List idsListFromUISchema = identityList.stream().map(map -> String.valueOf(map.get(env.getProperty(UI_SCHEMA_ATTRIBUTE_NAME)))) .collect(Collectors.toList()); List shareableAttributes = sharableAttrList.stream() .flatMap(attribute -> { + List attributeList = new ArrayList<>(); // Get the attributes from the format if specified if(attribute.getFormat()!=null && !attribute.getFormat().isEmpty()) { - return Stream.of(attribute.getFormat().split(",")); + attributeList.addAll( + Stream.of(attribute.getFormat().split(ResidentConstants.ATTRIBUTE_LIST_DELIMITER)) + .collect(Collectors.toList())); } // Get the attributes from the identity mapping - if(identityMap.containsKey(attribute.getAttributeName())) { - return Stream.of(String.valueOf(((Map) identityMap.get(attribute.getAttributeName())).get(VALUE)) - .split(",")); + else if(identityMap.containsKey(attribute.getAttributeName())) { + attributeList.addAll(Stream.of(String.valueOf(((Map) identityMap.get(attribute.getAttributeName())) + .get(MappingJsonConstants.VALUE)) + .split(ResidentConstants.ATTRIBUTE_LIST_DELIMITER)) + .collect(Collectors.toList())); } + attributeList.add(attribute.getAttributeName()); // Return the attribute name itself - return Stream.of(attribute.getAttributeName()); + return attributeList.stream(); }) .filter(idsListFromUISchema::contains) + .distinct() .collect(Collectors.toList()); return shareableAttributes; } + public Map getIdentityMappingMap() + throws ResidentServiceCheckedException, IOException, JsonParseException, JsonMappingException { + String identityMapping = getIdentityMapping(); + Map identityMappingMap = objectMapper + .readValue(identityMapping.getBytes(StandardCharsets.UTF_8), Map.class); + Object identityObj = identityMappingMap.get(MappingJsonConstants.IDENTITY); + Map identityMap = (Map) identityObj; + return identityMap; + } + + @Override + public List> getUISchemaData(String schemaType) { + try { + String uiSchema = getUISchema(schemaType); + Map schemaMap = objectMapper.readValue(uiSchema.getBytes(StandardCharsets.UTF_8), Map.class); + Object identitySchemaObj = schemaMap.get(MappingJsonConstants.IDENTITY); + if(identitySchemaObj instanceof List) { + List> identityList = (List>) identitySchemaObj; + return identityList; + } else { + logger.error("Error occured in accessing ui-schema identity data"); + throw new ResidentServiceException(ResidentErrorCode.API_RESOURCE_UNAVAILABLE); + } + } catch (IOException e) { + logger.error("Error occured in getting ui-schema %s", e.getMessage()); + throw new ResidentServiceException(ResidentErrorCode.API_RESOURCE_UNAVAILABLE, e); + } + } + + @Override + @Cacheable(value = "ui-schema-data-map", key = "#schemaType") + public Map>> getUISchemaCacheableData(String schemaType) { + List> uiSchemaDataList = getUISchemaData(schemaType); + List languages = uiSchemaDataList.stream().map(map -> { + return ((Map) map.get(ResidentConstants.LABEL)).keySet().stream() + .collect(Collectors.toList()); + }).findAny().orElse(List.of()); + Map>> schemaDataMap = languages.stream().map(langCode -> { + return Map.entry(langCode, getUISchemaAttributesData(uiSchemaDataList, langCode)); + }).collect(Collectors.toMap(Entry::getKey, Entry::getValue)); + return schemaDataMap; + } + + private Map> getUISchemaAttributesData(List> uiSchemaDataList, + String langCode) { + Map> attributesDataMap = new HashMap<>(); + attributesDataMap = uiSchemaDataList.stream().map(map -> { + return Map.entry((String) map.get(ResidentConstants.ATTRIBUTE_NAME), + Map.of(ResidentConstants.LABEL, ((Map) map.get(ResidentConstants.LABEL)).get(langCode), + ResidentConstants.FORMAT_OPTION, getAttributeFormatData(map, langCode))); + }).collect(Collectors.toMap(Entry::getKey, Entry::getValue)); + return attributesDataMap; + } + + private Map getAttributeFormatData(Map map, String langCode) { + return map.entrySet().stream().filter(formatRequired -> formatRequired.getKey().equals(ResidentConstants.FORMAT_REQUIRED)) + .filter(formatCheck -> (boolean) formatCheck.getValue()) + .map(formatData -> { + return ((List>) ((Map) map.get(ResidentConstants.FORMAT_OPTION)) + .get(langCode)) + .stream() + .map(map1 -> Map.entry(map1.get(ResidentConstants.VALUE), + map1.get(ResidentConstants.LABEL))) + .collect(Collectors.toMap(Entry::getKey, Entry::getValue)); + }).findAny().orElse(Map.of()); + } } diff --git a/resident/resident-service/src/main/java/io/mosip/resident/service/impl/ResidentCredentialServiceImpl.java b/resident/resident-service/src/main/java/io/mosip/resident/service/impl/ResidentCredentialServiceImpl.java index 3d2497d8388..1beef3ba6fc 100644 --- a/resident/resident-service/src/main/java/io/mosip/resident/service/impl/ResidentCredentialServiceImpl.java +++ b/resident/resident-service/src/main/java/io/mosip/resident/service/impl/ResidentCredentialServiceImpl.java @@ -9,6 +9,7 @@ import java.util.List; import java.util.Map; import java.util.UUID; +import java.util.stream.Collectors; import org.apache.commons.collections.map.HashedMap; import org.springframework.beans.factory.annotation.Autowired; @@ -54,6 +55,7 @@ import io.mosip.resident.dto.ResidentCredentialResponseDto; import io.mosip.resident.dto.ResidentCredentialResponseDtoV2; import io.mosip.resident.dto.ResponseWrapper; +import io.mosip.resident.dto.SharableAttributesDTO; import io.mosip.resident.entity.ResidentTransactionEntity; import io.mosip.resident.exception.ApisResourceAccessException; import io.mosip.resident.exception.OtpValidationFailedException; @@ -222,14 +224,8 @@ public ResidentCredentialResponseDto reqCredential(ResidentCredentialRequestDto } @Override - public Tuple2 shareCredential(ResidentCredentialRequestDto dto, String requestType) - throws ResidentServiceCheckedException, ApisResourceAccessException { - return shareCredential(dto, requestType, null); - } - - @Override - public Tuple2 shareCredential(ResidentCredentialRequestDto dto, String requestType, - String purpose) throws ResidentServiceCheckedException, ApisResourceAccessException { + public Tuple2 shareCredential(ResidentCredentialRequestDto dto, + String purpose, List sharableAttributes) throws ResidentServiceCheckedException, ApisResourceAccessException { ResidentCredentialResponseDto residentCredentialResponseDto = new ResidentCredentialResponseDto(); ResidentCredentialResponseDtoV2 residentCredentialResponseDtoV2=new ResidentCredentialResponseDtoV2(); RequestWrapper requestDto = new RequestWrapper<>(); @@ -244,13 +240,14 @@ public Tuple2 shareCredential(ResidentC ResidentTransactionEntity residentTransactionEntity = null; try { - residentTransactionEntity = createResidentTransactionEntity(dto, requestType, individualId); + residentTransactionEntity = createResidentTransactionEntity(dto, individualId, purpose, sharableAttributes); if (residentTransactionEntity != null) { eventId = residentTransactionEntity.getEventId(); } if (dto.getConsent() == null || dto.getConsent().equalsIgnoreCase(ConsentStatusType.DENIED.name()) || dto.getConsent().trim().isEmpty() || dto.getConsent().equals(NULL) || !dto.getConsent().equalsIgnoreCase(ConsentStatusType.ACCEPTED.name())) { residentTransactionEntity.setStatusCode(EventStatusFailure.FAILED.name()); + residentTransactionEntity.setRequestSummary(String.format("%s - %s", RequestType.SHARE_CRED_WITH_PARTNER.getName(), EventStatusFailure.FAILED.name())); throw new ResidentServiceException(ResidentErrorCode.CONSENT_DENIED.getErrorCode(), ResidentErrorCode.CONSENT_DENIED.getErrorMessage()); } @@ -271,13 +268,8 @@ public Tuple2 shareCredential(ResidentC ResponseWrapper.class); residentCredentialResponseDto = JsonUtil.readValue(JsonUtil.writeValueAsString(responseDto.getResponse()), ResidentCredentialResponseDto.class); - if (purpose != null) { - String requestSummary = prepareReqSummaryMsg(dto.getSharableAttributes()); - residentTransactionEntity.setPurpose(purpose); - residentTransactionEntity.setRequestSummary(requestSummary); - } additionalAttributes.put("RID", residentCredentialResponseDto.getRequestId()); - sendNotificationV2(individualId, RequestType.valueOf(requestType), TemplateType.REQUEST_RECEIVED, + sendNotificationV2(individualId, RequestType.SHARE_CRED_WITH_PARTNER, TemplateType.REQUEST_RECEIVED, eventId, additionalAttributes); updateResidentTransaction(dto, residentCredentialResponseDto, residentTransactionEntity); @@ -285,8 +277,9 @@ public Tuple2 shareCredential(ResidentC } catch (ResidentServiceCheckedException | ApisResourceAccessException e) { if (residentTransactionEntity != null) { residentTransactionEntity.setStatusCode(EventStatusFailure.FAILED.name()); + residentTransactionEntity.setRequestSummary(String.format("%s - %s", RequestType.SHARE_CRED_WITH_PARTNER.getName(), EventStatusFailure.FAILED.name())); } - sendNotificationV2(individualId, RequestType.valueOf(requestType), TemplateType.FAILURE, + sendNotificationV2(individualId, RequestType.SHARE_CRED_WITH_PARTNER, TemplateType.FAILURE, eventId, additionalAttributes); audit.setAuditRequestDto(EventEnum.CREDENTIAL_REQ_EXCEPTION); throw new ResidentCredentialServiceException(ResidentErrorCode.API_RESOURCE_ACCESS_EXCEPTION, e, @@ -294,18 +287,20 @@ public Tuple2 shareCredential(ResidentC } catch (IOException e) { if (residentTransactionEntity != null) { residentTransactionEntity.setStatusCode(EventStatusFailure.FAILED.name()); + residentTransactionEntity.setRequestSummary(String.format("%s - %s", RequestType.SHARE_CRED_WITH_PARTNER.getName(), EventStatusFailure.FAILED.name())); } - sendNotificationV2(individualId, RequestType.valueOf(requestType), TemplateType.FAILURE, + sendNotificationV2(individualId, RequestType.SHARE_CRED_WITH_PARTNER, TemplateType.FAILURE, eventId, additionalAttributes); audit.setAuditRequestDto(EventEnum.CREDENTIAL_REQ_EXCEPTION); throw new ResidentCredentialServiceException(ResidentErrorCode.IO_EXCEPTION, e, Map.of(ResidentConstants.EVENT_ID, eventId)); } finally { - if (Utility.isSecureSession() && residentTransactionEntity != null) { - //if the status code will come as null, it will set it as failed. - if(residentTransactionEntity.getStatusCode()==null) { + if (residentTransactionEntity != null) { + //if the status code or request summary will come as null, it will set it as failed. + if(residentTransactionEntity.getStatusCode() == null || residentTransactionEntity.getRequestSummary() == null) { residentTransactionEntity.setStatusCode(EventStatusFailure.FAILED.name()); - residentTransactionEntity.setRequestSummary("failed"); + residentTransactionEntity.setStatusComment(EventStatusFailure.FAILED.name()); + residentTransactionEntity.setRequestSummary(String.format("%s - %s", RequestType.SHARE_CRED_WITH_PARTNER.getName(), EventStatusFailure.FAILED.name())); } residentTransactionRepository.save(residentTransactionEntity); } @@ -314,18 +309,25 @@ public Tuple2 shareCredential(ResidentC } private ResidentTransactionEntity createResidentTransactionEntity(ResidentCredentialRequestDto dto, - String requestType, String individualId) throws ApisResourceAccessException, ResidentServiceCheckedException { - ResidentTransactionEntity residentTransactionEntity = utility.createEntity(); + String individualId, String purpose, List sharableAttributes) throws ApisResourceAccessException, ResidentServiceCheckedException { + ResidentTransactionEntity residentTransactionEntity = utility.createEntity(RequestType.SHARE_CRED_WITH_PARTNER); residentTransactionEntity.setEventId(utility.createEventId()); - residentTransactionEntity.setRequestTypeCode(requestType); - residentTransactionEntity.setRefId(utility.convertToMaskDataFormat(individualId)); + residentTransactionEntity.setRefId(utility.convertToMaskData(individualId)); residentTransactionEntity.setIndividualId(individualId); residentTransactionEntity.setTokenId(identityServiceImpl.getResidentIdaToken()); residentTransactionEntity.setAuthTypeCode(identityServiceImpl.getResidentAuthenticationMode()); - residentTransactionEntity.setRequestSummary(EventStatusInProgress.NEW.name()); - List sharableAttributes = dto.getSharableAttributes(); - if(sharableAttributes != null){ - residentTransactionEntity.setAttributeList(String.join(", ", sharableAttributes)); + if (purpose != null) { + residentTransactionEntity.setPurpose(purpose); + } + if (sharableAttributes != null && !sharableAttributes.isEmpty()) { + String data = sharableAttributes.stream().map(map -> { + if (map.getFormat() != null && !map.getFormat().isEmpty()) { + return String.format("%s%s%s", map.getAttributeName(), ResidentConstants.COLON, map.getFormat()); + } else { + return map.getAttributeName(); + } + }).collect(Collectors.joining(ResidentConstants.SEMI_COLON)); + residentTransactionEntity.setAttributeList(data); } residentTransactionEntity.setRequestedEntityId(dto.getIssuer()); Map partnerDetail = proxyPartnerManagementServiceImpl.getPartnerDetailFromPartnerId(dto.getIssuer()); @@ -342,6 +344,7 @@ private void updateResidentTransaction(ResidentCredentialRequestDto dto, residentTransactionEntity.setRequestTrnId(dto.getTransactionID()); residentTransactionEntity.setStatusCode(EventStatusInProgress.NEW.name()); residentTransactionEntity.setStatusComment(EventStatusInProgress.NEW.name()); + residentTransactionEntity.setRequestSummary(String.format("%s - %s", RequestType.SHARE_CRED_WITH_PARTNER.getName(), EventStatusInProgress.NEW.name())); residentTransactionEntity.setAid(residentCredentialResponseDto.getRequestId()); residentTransactionEntity.setCredentialRequestId(residentCredentialResponseDto.getRequestId()); } @@ -366,6 +369,13 @@ public byte[] getCard(String requestId, String appId, String partnerRefId) throw responseDto = residentServiceRestClient.getApi(credentailStatusUri, ResponseWrapper.class); credentialRequestStatusResponseDto = JsonUtil.readValue( JsonUtil.writeValueAsString(responseDto.getResponse()), CredentialRequestStatusDto.class); + if(credentialRequestStatusResponseDto == null || credentialRequestStatusResponseDto.getUrl() == null + || credentialRequestStatusResponseDto.getUrl().isEmpty()){ + audit.setAuditRequestDto(EventEnum.REQ_CARD_EXCEPTION); + logger.error("Data share URL is not available."); + throw new ResidentCredentialServiceException(ResidentErrorCode.API_RESOURCE_ACCESS_EXCEPTION.getErrorCode(), + ResidentErrorCode.API_RESOURCE_ACCESS_EXCEPTION.getErrorMessage()); + } URI dataShareUri = URI.create(credentialRequestStatusResponseDto.getUrl()); if(appId!=null){ return getDataShareData(appId, partnerRefId, dataShareUri); @@ -522,6 +532,7 @@ public CredentialTypeResponse getCredentialTypes() { try { credentialTypeResponse = residentServiceRestClient.getApi(credentailTypesUri, CredentialTypeResponse.class); } catch (ApisResourceAccessException e) { + audit.setAuditRequestDto(EventEnum.CREDENTIAL_TYPES_EXCEPTION); throw new ResidentCredentialServiceException(ResidentErrorCode.API_RESOURCE_ACCESS_EXCEPTION.getErrorCode(), ResidentErrorCode.API_RESOURCE_ACCESS_EXCEPTION.getErrorMessage(), e); } diff --git a/resident/resident-service/src/main/java/io/mosip/resident/service/impl/ResidentOtpServiceImpl.java b/resident/resident-service/src/main/java/io/mosip/resident/service/impl/ResidentOtpServiceImpl.java index e3cc0a915d5..c73a48b5248 100644 --- a/resident/resident-service/src/main/java/io/mosip/resident/service/impl/ResidentOtpServiceImpl.java +++ b/resident/resident-service/src/main/java/io/mosip/resident/service/impl/ResidentOtpServiceImpl.java @@ -1,5 +1,7 @@ package io.mosip.resident.service.impl; +import static io.mosip.resident.constant.ResidentConstants.ATTRIBUTE_LIST_DELIMITER; + import java.security.NoSuchAlgorithmException; import java.util.stream.Collectors; @@ -13,8 +15,8 @@ import io.mosip.kernel.core.logger.spi.Logger; import io.mosip.resident.config.LoggerConfiguration; import io.mosip.resident.constant.ApiName; +import io.mosip.resident.constant.EventStatusInProgress; import io.mosip.resident.constant.RequestType; -import io.mosip.resident.constant.ResidentConstants; import io.mosip.resident.constant.ResidentErrorCode; import io.mosip.resident.dto.IndividualIdOtpRequestDTO; import io.mosip.resident.dto.IndividualIdResponseDto; @@ -88,18 +90,17 @@ public OtpResponseDTO generateOtp(OtpRequestDTO otpRequestDTO) throws NoSuchAlgo @Override public void insertData(OtpRequestDTO otpRequestDTO) throws ResidentServiceCheckedException, NoSuchAlgorithmException, ApisResourceAccessException { - ResidentTransactionEntity residentTransactionEntity = utility.createEntity(); + ResidentTransactionEntity residentTransactionEntity = utility.createEntity(RequestType.SEND_OTP); residentTransactionEntity.setEventId(utility.createEventId()); residentTransactionEntity.setRequestTrnId(otpRequestDTO.getTransactionID()); - residentTransactionEntity.setRequestTypeCode(RequestType.SEND_OTP.name()); - String attributeList = otpRequestDTO.getOtpChannel().stream().collect(Collectors.joining(", ")); + String attributeList = otpRequestDTO.getOtpChannel().stream().collect(Collectors.joining(ATTRIBUTE_LIST_DELIMITER)); residentTransactionEntity.setAttributeList(attributeList); residentTransactionEntity.setAuthTypeCode(attributeList); residentTransactionEntity.setRequestSummary("OTP Generated"); - residentTransactionEntity.setStatusCode("OTP_REQUESTED"); + residentTransactionEntity.setStatusCode(EventStatusInProgress.OTP_REQUESTED.name()); residentTransactionEntity.setStatusComment("OTP_REQUESTED"); residentTransactionEntity.setLangCode("eng"); - residentTransactionEntity.setRefIdType("UIN"); + residentTransactionEntity.setRefIdType(identityServiceImpl.getIndividualIdType(otpRequestDTO.getIndividualId())); if( otpRequestDTO.getOtpChannel()!=null && otpRequestDTO.getOtpChannel().size()==1){ residentTransactionEntity.setRefId(utility.getIdForResidentTransaction(otpRequestDTO.getIndividualId(), otpRequestDTO.getOtpChannel())); } else{ @@ -107,7 +108,7 @@ public void insertData(OtpRequestDTO otpRequestDTO) throws ResidentServiceChecke } residentTransactionEntity.setIndividualId(otpRequestDTO.getIndividualId()); residentTransactionEntity.setTokenId(identityServiceImpl.getIDATokenForIndividualId(otpRequestDTO.getIndividualId())); - residentTransactionEntity.setPurpose(String.join(ResidentConstants.COMMA, otpRequestDTO.getOtpChannel())); + residentTransactionEntity.setPurpose(attributeList); residentTransactionRepository.save(residentTransactionEntity); } diff --git a/resident/resident-service/src/main/java/io/mosip/resident/service/impl/ResidentServiceImpl.java b/resident/resident-service/src/main/java/io/mosip/resident/service/impl/ResidentServiceImpl.java index 21af1816a9d..89b9bca635a 100644 --- a/resident/resident-service/src/main/java/io/mosip/resident/service/impl/ResidentServiceImpl.java +++ b/resident/resident-service/src/main/java/io/mosip/resident/service/impl/ResidentServiceImpl.java @@ -1,17 +1,67 @@ package io.mosip.resident.service.impl; +import static io.mosip.resident.constant.EventStatusSuccess.CARD_DOWNLOADED; +import static io.mosip.resident.constant.EventStatusSuccess.LOCKED; +import static io.mosip.resident.constant.EventStatusSuccess.UNLOCKED; +import static io.mosip.resident.constant.MappingJsonConstants.IDSCHEMA_VERSION; +import static io.mosip.resident.constant.RegistrationConstants.UIN_LABEL; +import static io.mosip.resident.constant.RegistrationConstants.VID_LABEL; +import static io.mosip.resident.constant.ResidentConstants.ATTRIBUTE_LIST_DELIMITER; +import static io.mosip.resident.constant.ResidentConstants.RESIDENT_NOTIFICATIONS_DEFAULT_PAGE_SIZE; +import static io.mosip.resident.constant.ResidentConstants.SEMI_COLON; +import static io.mosip.resident.constant.ResidentConstants.UI_ATTRIBUTE_DATA_DELIMITER; +import static io.mosip.resident.constant.ResidentErrorCode.MACHINE_MASTER_CREATE_EXCEPTION; +import static io.mosip.resident.constant.ResidentErrorCode.PACKET_SIGNKEY_EXCEPTION; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.StringWriter; +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.Month; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.stream.Collectors; +import java.util.stream.IntStream; +import java.util.stream.Stream; + +import javax.annotation.PostConstruct; + +import org.apache.commons.io.IOUtils; +import org.apache.commons.lang3.exception.ExceptionUtils; +import org.json.simple.JSONObject; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.core.env.Environment; +import org.springframework.http.HttpEntity; +import org.springframework.http.MediaType; +import org.springframework.stereotype.Service; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.web.client.HttpServerErrorException; + import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; + import io.mosip.commons.khazana.exception.ObjectStoreAdapterException; import io.mosip.kernel.core.exception.BaseCheckedException; import io.mosip.kernel.core.http.ResponseWrapper; +import io.mosip.kernel.core.idobjectvalidator.exception.IdObjectValidationFailedException; +import io.mosip.kernel.core.idobjectvalidator.spi.IdObjectValidator; import io.mosip.kernel.core.logger.spi.Logger; import io.mosip.kernel.core.templatemanager.spi.TemplateManager; import io.mosip.kernel.core.templatemanager.spi.TemplateManagerBuilder; import io.mosip.kernel.core.util.CryptoUtil; import io.mosip.kernel.core.util.DateUtils; -import io.mosip.kernel.core.idobjectvalidator.exception.IdObjectValidationFailedException; -import io.mosip.kernel.core.idobjectvalidator.spi.IdObjectValidator; import io.mosip.resident.config.LoggerConfiguration; import io.mosip.resident.constant.ApiName; import io.mosip.resident.constant.AuthTypeStatus; @@ -73,7 +123,6 @@ import io.mosip.resident.dto.ResidentUpdateResponseDTOV2; import io.mosip.resident.dto.ResponseDTO; import io.mosip.resident.dto.ServiceHistoryResponseDto; -import io.mosip.resident.dto.SortType; import io.mosip.resident.dto.UnreadNotificationDto; import io.mosip.resident.dto.UserInfoDto; import io.mosip.resident.entity.ResidentSessionEntity; @@ -81,7 +130,6 @@ import io.mosip.resident.entity.ResidentUserEntity; import io.mosip.resident.exception.ApisResourceAccessException; import io.mosip.resident.exception.CardNotReadyException; -import io.mosip.resident.exception.EidNotBelongToSessionException; import io.mosip.resident.exception.EventIdNotPresentException; import io.mosip.resident.exception.InvalidRequestTypeCodeException; import io.mosip.resident.exception.OtpValidationFailedException; @@ -110,63 +158,17 @@ import io.mosip.resident.util.UINCardDownloadService; import io.mosip.resident.util.Utilities; import io.mosip.resident.util.Utility; -import org.apache.commons.io.IOUtils; -import org.apache.commons.lang3.exception.ExceptionUtils; -import org.json.simple.JSONObject; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.core.env.Environment; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.PageRequest; -import org.springframework.data.domain.Pageable; -import org.springframework.data.domain.Sort; -import org.springframework.http.HttpEntity; -import org.springframework.http.MediaType; -import org.springframework.stereotype.Service; -import org.springframework.web.client.HttpClientErrorException; -import org.springframework.web.client.HttpServerErrorException; import reactor.util.function.Tuple2; import reactor.util.function.Tuples; -import javax.annotation.PostConstruct; -import javax.persistence.EntityManager; -import javax.persistence.Query; -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.StringWriter; -import java.math.BigInteger; -import java.net.URI; -import java.nio.charset.StandardCharsets; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.time.Month; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; -import java.util.stream.Collectors; -import java.util.stream.IntStream; - -import static io.mosip.resident.constant.EventStatusSuccess.CARD_DOWNLOADED; -import static io.mosip.resident.constant.EventStatusSuccess.LOCKED; -import static io.mosip.resident.constant.EventStatusSuccess.UNLOCKED; -import static io.mosip.resident.constant.ResidentConstants.RESIDENT; -import static io.mosip.resident.constant.ResidentErrorCode.MACHINE_MASTER_CREATE_EXCEPTION; -import static io.mosip.resident.constant.ResidentErrorCode.PACKET_SIGNKEY_EXCEPTION; - @Service public class ResidentServiceImpl implements ResidentService { + private static final String NA = "NA"; + private static final String IDREPO_DUMMY_ONLINE_VERIFICATION_PARTNER_ID = "idrepo-dummy-online-verification-partner-id"; + private static final String ONLINE_VERIFICATION_PARTNER = "Online_Verification_Partner"; + private static final String MOSIP_IDA_PARTNER_TYPE = "mosip.ida.partner.type"; private static final int UPDATE_COUNT_FOR_NEW_USER_ACTION_ENTITY = 1; - private static final String AUTH_TYPE_LIST_DELIMITER = ", "; private static final String AUTH_TYPE_SEPERATOR = "-"; private static final String PROCESSED = "PROCESSED"; private static final String DATETIME_PATTERN = "mosip.utc-datetime-pattern"; @@ -187,14 +189,10 @@ public class ResidentServiceImpl implements ResidentService { private static final Logger logger = LoggerConfiguration.logConfig(ResidentServiceImpl.class); private static final Integer DEFAULT_PAGE_START = 0; private static final Integer DEFAULT_PAGE_COUNT = 10; - private static final String AVAILABLE = "AVAILABLE"; private static final String CLASSPATH = "classpath"; private static final String ENCODE_TYPE = "UTF-8"; private static final String UPDATED = " updated"; private static final String ALL = "ALL"; - private static final String CREATED_DATE_TIME = "crDtimes"; - private static final String PINNED_STATUS = "pinnedStatus"; - private static final String MODULO_OPERATOR = "%"; private static String cardType = "UIN"; @Autowired @@ -236,9 +234,6 @@ public class ResidentServiceImpl implements ResidentService { @Autowired private Utilities utilities; - @Autowired - private EntityManager entityManager; - @Value("${ida.online-verification-partner-id}") private String onlineVerificationPartnerId; @@ -276,6 +271,12 @@ public class ResidentServiceImpl implements ResidentService { @Value("${digital.card.pdf.encryption.enabled:false}") private boolean isDigitalCardPdfEncryptionEnabled; + @Value("${"+ResidentConstants.PREFERRED_LANG_PROPERTY+":false}") + private boolean isPreferedLangFlagEnabled; + + @Value("${resident.authLockStatusUpdateV2.id}") + private String authLockStatusUpdateV2Id; + @Autowired private AuditUtil audit; @@ -288,9 +289,6 @@ public class ResidentServiceImpl implements ResidentService { @Autowired private ObjectMapper objectMapper; - @Autowired - private ResidentCredentialServiceImpl residentCredentialServiceImpl; - @Autowired private ResidentUserRepository residentUserRepository; @@ -909,10 +907,10 @@ public Tuple2 reqUinUpdate(ResidentUpdateRequestDto dto, JSONObj String encodedIdentityJson = CryptoUtil.encodeToURLSafeBase64(jsonObject.toJSONString().getBytes()); regProcReqUpdateDto.setIdentityJson(encodedIdentityJson); String mappingJson = utility.getMappingJson(); - + String idSchemaVersionStr = null; + JSONObject obj = utilities.retrieveIdrepoJson(dto.getIndividualId()); + idSchemaVersionStr = String.valueOf(obj.get("IDSchemaVersion")); if(validateIdObject) { - JSONObject obj = utilities.retrieveIdrepoJson(dto.getIndividualId()); - String idSchemaVersionStr = String.valueOf(obj.get("IDSchemaVersion")); Double idSchemaVersion = Double.parseDouble(idSchemaVersionStr); ResponseWrapper idSchemaResponse = proxyMasterdataService.getLatestIdSchema(idSchemaVersion, null, null); Object idSchema = idSchemaResponse.getResponse(); @@ -921,10 +919,10 @@ public Tuple2 reqUinUpdate(ResidentUpdateRequestDto dto, JSONObj try { idObjectValidator.validateIdObject(schemaJson, jsonObject); } catch (IdObjectValidationFailedException e) { - String error = e.getErrorTexts().toString(); - if (error.contains(ResidentConstants.INVALID_INPUT_PARAMETER)) { - List errors = e.getErrorTexts(); - String errorMessage = errors.get(0); + Optional error = e.getErrorTexts().stream() + .filter(t -> t.contains(ResidentConstants.INVALID_INPUT_PARAMETER)).findAny(); + if (error.isPresent()) { + String errorMessage = error.get(); throw new ResidentServiceException(ResidentErrorCode.INVALID_INPUT.getErrorCode(), errorMessage); } @@ -966,7 +964,7 @@ public Tuple2 reqUinUpdate(ResidentUpdateRequestDto dto, JSONObj JSONObject proofOfBirthJson = JsonUtil.getJSONObject(demographicIdentity, pobMapping); regProcReqUpdateDto.setProofOfDateOfBirth(getDocumentValue(proofOfBirthJson, documents)); - PacketGeneratorResDto response = residentUpdateService.createPacket(regProcReqUpdateDto); + PacketGeneratorResDto response = residentUpdateService.createPacket(regProcReqUpdateDto, idSchemaVersionStr); Map additionalAttributes = new HashMap<>(); additionalAttributes.put("RID", response.getRegistrationId()); audit.setAuditRequestDto( @@ -1153,10 +1151,9 @@ public Tuple2 reqUinUpdate(ResidentUpdateRequestDto dto, JSONObj private ResidentTransactionEntity createResidentTransEntity(ResidentUpdateRequestDto dto) throws ApisResourceAccessException, IOException, ResidentServiceCheckedException { - ResidentTransactionEntity residentTransactionEntity = utility.createEntity(); + ResidentTransactionEntity residentTransactionEntity = utility.createEntity(RequestType.UPDATE_MY_UIN); residentTransactionEntity.setEventId(utility.createEventId()); - residentTransactionEntity.setRequestTypeCode(RequestType.UPDATE_MY_UIN.name()); - residentTransactionEntity.setRefId(utility.convertToMaskDataFormat(dto.getIndividualId())); + residentTransactionEntity.setRefId(utility.convertToMaskData(dto.getIndividualId())); residentTransactionEntity.setIndividualId(dto.getIndividualId()); residentTransactionEntity.setTokenId(identityServiceImpl.getResidentIdaToken()); residentTransactionEntity.setAuthTypeCode(identityServiceImpl.getResidentAuthenticationMode()); @@ -1167,10 +1164,10 @@ private ResidentTransactionEntity createResidentTransEntity(ResidentUpdateReques } else { identityMap = dto.getIdentity(); } - HashSet keys = new HashSet(identityMap.keySet()); - keys.remove("IDSchemaVersion"); - keys.remove("UIN"); - String attributeList = keys.stream().collect(Collectors.joining(AUTH_TYPE_LIST_DELIMITER)); + + String attributeList = identityMap.keySet().stream() + .filter(key -> !key.equals(IDSCHEMA_VERSION) && !key.equals(UIN_LABEL) && !key.equals(VID_LABEL)) + .collect(Collectors.joining(SEMI_COLON)); residentTransactionEntity.setAttributeList(attributeList); residentTransactionEntity.setConsent(dto.getConsent()); residentTransactionEntity.setStatusCode(EventStatusInProgress.NEW.name()); @@ -1221,8 +1218,11 @@ public Tuple2 reqAauthTypeStatusUpdateV2(AuthLockOrUnLockRe try { audit.setAuditRequestDto( EventEnum.getEventEnumWithValue(EventEnum.REQ_AUTH_TYPE_LOCK, "Request for Auth Type Lock")); - ArrayList partnerIds = partnerService.getPartnerDetails("Online_Verification_Partner"); - residentTransactionEntities = partnerIds.stream().map(partnerId -> { + ArrayList partnerIds = partnerService.getPartnerDetails(env.getProperty(MOSIP_IDA_PARTNER_TYPE,ONLINE_VERIFICATION_PARTNER)); + String dummyOnlineVerificationPartnerId = env.getProperty(IDREPO_DUMMY_ONLINE_VERIFICATION_PARTNER_ID, NA); + residentTransactionEntities = partnerIds.stream() + .filter(partnerId -> !dummyOnlineVerificationPartnerId.equalsIgnoreCase(partnerId)) + .map(partnerId -> { try { return createResidentTransactionEntity(individualId, partnerId); } catch (ApisResourceAccessException e) { @@ -1239,7 +1239,7 @@ public Tuple2 reqAauthTypeStatusUpdateV2(AuthLockOrUnLockRe List authTypesStatusList = authLockOrUnLockRequestDtoV2.getAuthTypes(); String authType = authTypesStatusList.stream().map(dto ->ResidentServiceImpl.getAuthTypeBasedOnConfigV2(dto) +ResidentConstants.COLON+ (dto.getLocked()? LOCKED:UNLOCKED)) - .collect(Collectors.joining(AUTH_TYPE_LIST_DELIMITER)); + .collect(Collectors.joining(ResidentConstants.AUTH_TYPE_LIST_DELIMITER)); Map authTypeStatusMap = authTypesStatusList.stream() .collect(Collectors.toMap(ResidentServiceImpl::getAuthTypeBasedOnConfigV2, @@ -1269,7 +1269,7 @@ public Tuple2 reqAauthTypeStatusUpdateV2(AuthLockOrUnLockRe audit.setAuditRequestDto(EventEnum.getEventEnumWithValue(EventEnum.REQUEST_FAILED, "Request for auth " + authLockOrUnLockRequestDtoV2.getAuthTypes() + " lock failed")); throw new ResidentServiceException(ResidentErrorCode.REQUEST_FAILED, - Map.of(ResidentConstants.EVENT_ID, eventId)); + Map.of(ResidentConstants.EVENT_ID, authLockStatusUpdateV2Id)); } } catch (ApisResourceAccessException e) { @@ -1286,7 +1286,7 @@ public Tuple2 reqAauthTypeStatusUpdateV2(AuthLockOrUnLockRe audit.setAuditRequestDto(EventEnum.getEventEnumWithValue(EventEnum.API_NOT_AVAILABLE, "Request for auth" + authLockOrUnLockRequestDtoV2.getAuthTypes() + " lock failed")); throw new ResidentServiceException(ResidentErrorCode.API_RESOURCE_UNAVAILABLE, e, - Map.of(ResidentConstants.EVENT_ID, eventId)); + Map.of(ResidentConstants.EVENT_ID, authLockStatusUpdateV2Id)); } finally { residentTransactionRepository.saveAll(residentTransactionEntities); @@ -1315,13 +1315,12 @@ public Tuple2 reqAauthTypeStatusUpdateV2(AuthLockOrUnLockRe private ResidentTransactionEntity createResidentTransactionEntity(String individualId, String partnerId) throws ApisResourceAccessException, ResidentServiceCheckedException { ResidentTransactionEntity residentTransactionEntity; - residentTransactionEntity = utility.createEntity(); + residentTransactionEntity = utility.createEntity(RequestType.AUTH_TYPE_LOCK_UNLOCK); residentTransactionEntity.setEventId(utility.createEventId()); residentTransactionEntity.setStatusCode(EventStatusInProgress.NEW.name()); residentTransactionEntity.setStatusComment(EventStatusInProgress.NEW.name()); - residentTransactionEntity.setRequestTypeCode(RequestType.AUTH_TYPE_LOCK_UNLOCK.name()); residentTransactionEntity.setRequestSummary("Updating auth type lock status"); - residentTransactionEntity.setRefId(utility.convertToMaskDataFormat(individualId)); + residentTransactionEntity.setRefId(utility.convertToMaskData(individualId)); residentTransactionEntity.setIndividualId(individualId); residentTransactionEntity.setTokenId(identityServiceImpl.getResidentIdaToken()); residentTransactionEntity.setAuthTypeCode(identityServiceImpl.getResidentAuthenticationMode()); @@ -1567,25 +1566,33 @@ public ResponseWrapper getAuthLockStatus(String in } } + @Override + public ResponseWrapper> getServiceHistory(Integer pageStart, Integer pageFetch, + LocalDate fromDateTime, LocalDate toDateTime, String serviceType, String sortType, + String statusFilter, String searchText, String langCode, int timeZoneOffset, String locale) + throws ResidentServiceCheckedException, ApisResourceAccessException { + return getServiceHistory(pageStart, pageFetch, fromDateTime, toDateTime, serviceType, sortType, statusFilter, + searchText, langCode, timeZoneOffset, locale, null, null); + } + @Override public ResponseWrapper> getServiceHistory(Integer pageStart, Integer pageFetch, LocalDate fromDateTime, LocalDate toDateTime, String serviceType, String sortType, - String statusFilter, String searchText, String langCode, int timeZoneOffset) + String statusFilter, String searchText, String langCode, int timeZoneOffset, String locale, + String defaultPageSizeProperty, List statusCodeList) throws ResidentServiceCheckedException, ApisResourceAccessException { if (pageStart == null) { - if (pageFetch == null) { - // If both Page start and page fetch values are null return all records - pageStart = DEFAULT_PAGE_START; - pageFetch = DEFAULT_PAGE_COUNT; - } else { - pageStart = DEFAULT_PAGE_START; - } - } else { - if (pageFetch == null) { - pageFetch = DEFAULT_PAGE_COUNT; - } + //By default page start is 0 + pageStart = DEFAULT_PAGE_START; + } + + if (pageFetch == null) { + // Get the default page size based on the property if mentioned otherwise it + // default would be 10 + pageFetch = getDefaultPageSize(defaultPageSizeProperty); } + if (pageStart < 0) { audit.setAuditRequestDto(EventEnum.getEventEnumWithValue(EventEnum.INVALID_PAGE_START_VALUE, pageStart.toString(), "Invalid page start value")); @@ -1598,18 +1605,24 @@ public ResponseWrapper> getServiceHistory(Int ResponseWrapper> serviceHistoryResponseDtoList = getServiceHistoryDetails( sortType, pageStart, pageFetch, fromDateTime, toDateTime, serviceType, statusFilter, searchText, - langCode, timeZoneOffset); + langCode, timeZoneOffset, locale, statusCodeList); return serviceHistoryResponseDtoList; } + private Integer getDefaultPageSize(String defaultPageSizeProperty) { + return defaultPageSizeProperty != null + ? env.getProperty(defaultPageSizeProperty, Integer.class, DEFAULT_PAGE_COUNT) + : DEFAULT_PAGE_COUNT; + } + @Override - public String getFileName(String eventId, int timeZoneOffset) { + public String getFileName(String eventId, int timeZoneOffset, String locale) { if (cardType.equalsIgnoreCase(IdType.UIN.toString())) { return utility.getFileName(eventId, Objects - .requireNonNull(this.env.getProperty(ResidentConstants.UIN_CARD_NAMING_CONVENTION_PROPERTY)), timeZoneOffset); + .requireNonNull(this.env.getProperty(ResidentConstants.UIN_CARD_NAMING_CONVENTION_PROPERTY)), timeZoneOffset, locale); } else { return utility.getFileName(eventId, Objects - .requireNonNull(this.env.getProperty(ResidentConstants.VID_CARD_NAMING_CONVENTION_PROPERTY)), timeZoneOffset); + .requireNonNull(this.env.getProperty(ResidentConstants.VID_CARD_NAMING_CONVENTION_PROPERTY)), timeZoneOffset, locale); } } @@ -1620,7 +1633,7 @@ public byte[] downloadCard(String eventId) { .findById(eventId); if (residentTransactionEntity.isPresent()) { String requestTypeCode = residentTransactionEntity.get().getRequestTypeCode(); - RequestType requestType = RequestType.valueOf(requestTypeCode); + RequestType requestType = RequestType.getRequestTypeFromString(requestTypeCode); if (requestType.name().equalsIgnoreCase(RequestType.UPDATE_MY_UIN.name())) { cardType = IdType.UIN.name(); return downloadCardFromDataShareUrl(residentTransactionEntity.get()); @@ -1663,7 +1676,7 @@ public byte[] downloadCardFromDataShareUrl(ResidentTransactionEntity residentTra residentTransactionEntity.setRequestSummary(ResidentConstants.SUCCESS); residentTransactionEntity.setStatusCode(EventStatusSuccess.CARD_DOWNLOADED.name()); residentTransactionEntity.setStatusComment(CARD_DOWNLOADED.name()); - residentTransactionEntity.setUpdBy(RESIDENT); + residentTransactionEntity.setUpdBy(utility.getSessionUserName()); residentTransactionEntity.setUpdDtimes(DateUtils.getUTCCurrentDateTime()); residentTransactionRepository.save(residentTransactionEntity); return pdfBytes; @@ -1678,160 +1691,116 @@ public byte[] downloadCardFromDataShareUrl(ResidentTransactionEntity residentTra private ResponseWrapper> getServiceHistoryDetails(String sortType, Integer pageStart, Integer pageFetch, LocalDate fromDateTime, LocalDate toDateTime, - String serviceType, String statusFilter, String searchText, String langCode, int timeZoneOffset) + String serviceType, String statusFilter, String searchText, String langCode, int timeZoneOffset, String locale, List statusCodeList) throws ResidentServiceCheckedException, ApisResourceAccessException { ResponseWrapper> responseWrapper = new ResponseWrapper<>(); String idaToken = identityServiceImpl.getResidentIdaToken(); responseWrapper.setResponse(getServiceHistoryResponse(sortType, pageStart, pageFetch, idaToken, statusFilter, - searchText, fromDateTime, toDateTime, serviceType, langCode, timeZoneOffset)); + searchText, fromDateTime, toDateTime, serviceType, langCode, timeZoneOffset, locale, statusCodeList)); responseWrapper.setId(serviceHistoryId); responseWrapper.setVersion(serviceHistoryVersion); - responseWrapper.setResponsetime(LocalDateTime.now()); + responseWrapper.setResponsetime(DateUtils.getUTCCurrentDateTime()); return responseWrapper; } public PageDto getServiceHistoryResponse(String sortType, Integer pageStart, Integer pageFetch, String idaToken, String statusFilter, String searchText, LocalDate fromDateTime, - LocalDate toDateTime, String serviceType, String langCode, int timeZoneOffset) + LocalDate toDateTime, String serviceType, String langCode, int timeZoneOffset, String locale, List statusCodeList) throws ResidentServiceCheckedException { - String nativeQueryString = getDynamicNativeQueryStringForServiceHistory(sortType, idaToken, pageStart, pageFetch, statusFilter, - searchText, fromDateTime, toDateTime, serviceType, timeZoneOffset); - Query nativeQuery = entityManager.createNativeQuery(nativeQueryString, ResidentTransactionEntity.class); - List residentTransactionEntityList = (List) nativeQuery - .getResultList(); - String[] split = nativeQueryString.split("order by"); - String nativeQueryStringWithoutOrderBy = split[0]; - nativeQueryStringWithoutOrderBy = nativeQueryStringWithoutOrderBy.replace("*", "count(*)"); - Query nativeQuery2 = entityManager.createNativeQuery(nativeQueryStringWithoutOrderBy); - BigInteger count = (BigInteger) nativeQuery2.getSingleResult(); - int size = count.intValue(); - return new PageDto<>(pageStart, pageFetch, size, (size / pageFetch) + 1, - convertResidentEntityListToServiceHistoryDto(residentTransactionEntityList, langCode, timeZoneOffset)); + Tuple2, Integer> serviceHistoryData = getServiceHistoryData(sortType, idaToken, pageStart, pageFetch, statusFilter, + searchText, fromDateTime, toDateTime, serviceType, timeZoneOffset, statusCodeList); + + return new PageDto<>(pageStart, pageFetch, serviceHistoryData.getT2(), ( serviceHistoryData.getT2()/ pageFetch) + 1, + convertResidentEntityListToServiceHistoryDto(serviceHistoryData.getT1(), langCode, timeZoneOffset, locale)); } - public String getDynamicNativeQueryStringForServiceHistory(String sortType, String idaToken, Integer pageStart, Integer pageFetch, - String statusFilter, String searchText, LocalDate fromDateTime, LocalDate toDateTime, - String serviceType, int timeZoneOffset) { - String query = "SELECT * FROM resident_transaction where token_id = '" - + idaToken+"'"; - String dynamicQuery = ""; - if (fromDateTime != null && toDateTime != null && serviceType != null && !serviceType.equalsIgnoreCase("ALL") - && statusFilter != null && searchText != null) { - dynamicQuery = getDateQuery(fromDateTime, toDateTime, timeZoneOffset) + getServiceQuery(serviceType) - + getStatusFilterQuery(statusFilter) + getSearchQuery(searchText); - } else if (fromDateTime != null && toDateTime != null && serviceType != null - && !serviceType.equalsIgnoreCase("ALL") && statusFilter != null) { - dynamicQuery = getDateQuery(fromDateTime, toDateTime, timeZoneOffset) + getServiceQuery(serviceType ) - + getStatusFilterQuery(statusFilter ); - } else if (fromDateTime != null && toDateTime != null && serviceType != null - && !serviceType.equalsIgnoreCase("ALL") && searchText != null) { - dynamicQuery = getDateQuery(fromDateTime, toDateTime, timeZoneOffset) + getServiceQuery(serviceType ) - + getSearchQuery(searchText ); - } else if (fromDateTime != null && toDateTime != null && statusFilter != null && searchText != null) { - dynamicQuery = getDateQuery(fromDateTime, toDateTime, timeZoneOffset) + getStatusFilterQuery(statusFilter ) - + getSearchQuery(searchText ); - } else if (serviceType != null && !serviceType.equalsIgnoreCase("ALL") && statusFilter != null - && searchText != null) { - dynamicQuery = getServiceQuery(serviceType ) + getStatusFilterQuery(statusFilter ) - + getSearchQuery(searchText ); - } else if (serviceType != null && !serviceType.equalsIgnoreCase("ALL") && statusFilter != null) { - dynamicQuery = getServiceQuery(serviceType ) + getStatusFilterQuery(statusFilter ); - } else if (serviceType != null && !serviceType.equalsIgnoreCase("ALL") && searchText != null) { - dynamicQuery = getServiceQuery(serviceType ) + getSearchQuery(searchText ); - } else if (statusFilter != null && searchText != null) { - dynamicQuery = getStatusFilterQuery(statusFilter ) + getSearchQuery(searchText ); - } else if (fromDateTime != null && toDateTime != null && searchText != null) { - dynamicQuery = getDateQuery(fromDateTime, toDateTime, timeZoneOffset) + getSearchQuery(searchText ); - } else if (fromDateTime != null && toDateTime != null && statusFilter != null) { - dynamicQuery = getDateQuery(fromDateTime, toDateTime, timeZoneOffset) + getStatusFilterQuery(statusFilter ); - } else if (fromDateTime != null && toDateTime != null && serviceType != null - && !serviceType.equalsIgnoreCase("ALL")) { - dynamicQuery = getDateQuery(fromDateTime, toDateTime, timeZoneOffset) + getServiceQuery(serviceType ); - } else if (fromDateTime != null && toDateTime != null) { - dynamicQuery = getDateQuery(fromDateTime, toDateTime, timeZoneOffset); - } else if (serviceType != null && !serviceType.equalsIgnoreCase("ALL")) { - dynamicQuery = getServiceQuery(serviceType ); - } else if (statusFilter != null) { - dynamicQuery = getStatusFilterQuery(statusFilter ); - } else if (searchText != null) { - dynamicQuery = getSearchQuery(searchText ); + public Tuple2, Integer> getServiceHistoryData(String sortType, String idaToken, Integer pageStart, Integer pageFetch, + String statusFilter, String searchText, LocalDate fromDateTime, LocalDate toDateTime, + String serviceType, int timeZoneOffset, List statusCodeList){ + List requestTypes; + List statusList = new ArrayList<>(); + Tuple2 dateTimeTuple2 = null; + if(serviceType==null) { + requestTypes = getServiceQueryForNullServiceType(); + } else { + requestTypes = convertServiceTypeToResidentTransactionType(serviceType); } - if(serviceType == null){ - dynamicQuery = dynamicQuery + getServiceQueryForNullServiceType(); + if(statusFilter!=null){ + statusList = getStatusFilterQuery(statusFilter, statusCodeList); } - dynamicQuery = dynamicQuery + getOlvPartnerIdQuery(); - if (sortType == null) { - sortType = SortType.DESC.toString(); + if(fromDateTime!=null && toDateTime!=null){ + dateTimeTuple2= getDateQuery(fromDateTime, toDateTime, timeZoneOffset); + } + if (statusFilter != null && searchText != null){ + return Tuples.of(residentTransactionRepository.findByTokenIdInStatusSearchEventId(idaToken, pageFetch, + (pageStart) * pageFetch, + onlineVerificationPartnerId, requestTypes, statusList, searchText), + residentTransactionRepository.countByTokenIdInStatusSearchEventId( + idaToken, onlineVerificationPartnerId, requestTypes, statusList, searchText)); + }else if (fromDateTime != null && toDateTime != null && searchText != null){ + return Tuples.of(residentTransactionRepository.findByTokenIdBetweenCrDtimesSearchEventId(idaToken, pageFetch, + (pageStart) * pageFetch, + onlineVerificationPartnerId, requestTypes, dateTimeTuple2.getT1(), dateTimeTuple2.getT2(), searchText), + residentTransactionRepository.countByTokenIdBetweenCrDtimesSearchEventId( + idaToken, onlineVerificationPartnerId, requestTypes, dateTimeTuple2.getT1(), dateTimeTuple2.getT2(), searchText)); + } else if (fromDateTime != null && toDateTime != null && statusFilter != null) { + return Tuples.of(residentTransactionRepository.findByTokenIdInStatusBetweenCrDtimes(idaToken, pageFetch, + (pageStart) * pageFetch, + onlineVerificationPartnerId, requestTypes, statusList, dateTimeTuple2.getT1(), dateTimeTuple2.getT2()), + residentTransactionRepository.countByTokenIdInStatusBetweenCrDtimes( + idaToken, onlineVerificationPartnerId, requestTypes, statusList, dateTimeTuple2.getT1(), dateTimeTuple2.getT2())); + } else if(searchText !=null){ + return Tuples.of(residentTransactionRepository.findByTokenIdAndSearchEventId(idaToken, pageFetch, (pageStart) * pageFetch, + onlineVerificationPartnerId, requestTypes, searchText), + residentTransactionRepository.countByTokenIdAndSearchEventId( + idaToken, onlineVerificationPartnerId, requestTypes, searchText)); + } else if (statusFilter != null) { + return Tuples.of(residentTransactionRepository.findByTokenIdInStatus(idaToken, pageFetch, (pageStart) * pageFetch, + onlineVerificationPartnerId, requestTypes, statusList), + residentTransactionRepository.countByTokenIdInStatus( + idaToken, onlineVerificationPartnerId, requestTypes, statusList)); + } else if (fromDateTime != null && toDateTime != null) { + return Tuples.of(residentTransactionRepository.findByTokenIdBetweenCrDtimes(idaToken, pageFetch, (pageStart) * pageFetch, + onlineVerificationPartnerId, requestTypes, dateTimeTuple2.getT1(), dateTimeTuple2.getT2()), + residentTransactionRepository.countByTokenIdBetweenCrDtimes( + idaToken, onlineVerificationPartnerId, requestTypes, dateTimeTuple2.getT1(), dateTimeTuple2.getT2())); + } else { + return Tuples.of(residentTransactionRepository.findByTokenId(idaToken, pageFetch, (pageStart) * pageFetch, + onlineVerificationPartnerId, requestTypes), + residentTransactionRepository.countByTokenId(idaToken, onlineVerificationPartnerId, requestTypes)); } - - String orderByQuery = " order by pinned_status desc, " + "cr_dtimes " + sortType + " limit " + pageFetch - + " offset " + (pageStart) * pageFetch; - return query + dynamicQuery + orderByQuery; - } - private String getOlvPartnerIdQuery() { - return " AND (olv_partner_id is null OR olv_partner_id='" + onlineVerificationPartnerId + "')"; - } - - private String getServiceQueryForNullServiceType() { - return " and request_type_code in (" + convertServiceTypeListToString( - (List) convertListOfRequestTypeToListOfString(ServiceType.ALL.getRequestType())) +")"; } - private String getServiceQuery(String serviceType) { - List requestTypeList = convertServiceTypeToResidentTransactionType(serviceType); - String requestTypeListString = convertServiceTypeListToString(requestTypeList); - return " and request_type_code in (" + requestTypeListString + ")"; + private List getServiceQueryForNullServiceType() { + return (List) convertListOfRequestTypeToListOfString(ServiceType.ALL.getRequestTypes()); } - private String getDateQuery(LocalDate fromDate, LocalDate toDate, int timeZoneOffset) { + private Tuple2 getDateQuery(LocalDate fromDate, LocalDate toDate, int timeZoneOffset) { //Converting local time to UTC before using in db query LocalDateTime fromDateTime = fromDate.atStartOfDay().plusMinutes(timeZoneOffset); LocalDateTime toDateTime = toDate.plusDays(1).atStartOfDay().plusMinutes(timeZoneOffset); - return " and cr_dtimes between '" + fromDateTime + "' and '" + - toDateTime+ "'"; + return Tuples.of(fromDateTime, toDateTime); } - private String getSearchQuery(String searchText) { - String text= "%" + searchText.replace(AUTH_TYPE_SEPERATOR, "") + "%"; - return " and Replace(event_id,'-','') like '"+text+ "'"; - } - - public String getStatusFilterQuery(String statusFilter) { + public List getStatusFilterQuery(String statusFilter, List statusCodeList) { List statusFilterList = List.of(statusFilter.split(",")).stream().map(String::trim) .collect(Collectors.toList()); - String statusFilterListString = ""; - List statusFilterListContainingALlStatus = new ArrayList<>(); - for (String status : statusFilterList) { - if (status.equalsIgnoreCase(EventStatus.SUCCESS.getStatus())) { - statusFilterListContainingALlStatus.addAll( - List.of(EventStatusSuccess.values()).stream().map(Enum::toString).collect(Collectors.toList())); - } else if (status.equalsIgnoreCase(EventStatus.FAILED.getStatus())) { - statusFilterListContainingALlStatus.addAll( - List.of(EventStatusFailure.values()).stream().map(Enum::toString).collect(Collectors.toList())); - } else if (status.equalsIgnoreCase(EventStatus.IN_PROGRESS.getStatus())) { - statusFilterListContainingALlStatus.addAll(List.of(EventStatusInProgress.values()).stream() - .map(Enum::toString).collect(Collectors.toList())); + List statusFilterListContainingAllStatus = new ArrayList<>(); + if(statusCodeList == null || statusCodeList.isEmpty()) { + for (String status : statusFilterList) { + if (status.equalsIgnoreCase(EventStatus.SUCCESS.getStatus())) { + statusFilterListContainingAllStatus.addAll(RequestType.getAllSuccessStatusList(env)); + } else if (status.equalsIgnoreCase(EventStatus.FAILED.getStatus())) { + statusFilterListContainingAllStatus.addAll(RequestType.getAllFailedStatusList(env)); + } else if (status.equalsIgnoreCase(EventStatus.IN_PROGRESS.getStatus())) { + statusFilterListContainingAllStatus.addAll(RequestType.getAllNewOrInprogressStatusList(env)); + } } + }else { + statusFilterListContainingAllStatus.addAll(statusFilterList); } - statusFilterListString = convertStatusFilterListToString(statusFilterListContainingALlStatus); - return " and status_code in (" + statusFilterListString + ")"; - } - - public String convertStatusFilterListToString(List statusFilterListContainingALlStatus) { - String statusFilterListString = ""; - for (String status : statusFilterListContainingALlStatus) { - statusFilterListString = statusFilterListString + "'" + status + "',"; - } - return statusFilterListString.substring(0, statusFilterListString.length() - 1); - } - - public String convertServiceTypeListToString(List serviceTypeList) { - String serviceTypeListString = ""; - for (String serviceType : serviceTypeList) { - serviceTypeListString = serviceTypeListString + "'" + serviceType + "',"; - } - return serviceTypeListString.substring(0, serviceTypeListString.length() - 1); + return statusFilterListContainingAllStatus; } private List convertServiceTypeToResidentTransactionType(String serviceType) { @@ -1841,7 +1810,7 @@ private List convertServiceTypeToResidentTransactionType(String serviceT .collect(Collectors.toList()); for (String service : serviceTypeList) { ServiceType type = ServiceType.valueOf(service); - residentTransactionTypeList.addAll(convertListOfRequestTypeToListOfString(type.getRequestType())); + residentTransactionTypeList.addAll(convertListOfRequestTypeToListOfString(type.getRequestTypes())); } } return residentTransactionTypeList; @@ -1852,7 +1821,7 @@ private Collection convertListOfRequestTypeToListOfString(List convertResidentEntityListToServiceHistoryDto( - List residentTransactionEntityList, String langCode, int timeZoneOffset) + List residentTransactionEntityList, String langCode, int timeZoneOffset, String locale) throws ResidentServiceCheckedException { List serviceHistoryResponseDtoList = new ArrayList<>(); for (ResidentTransactionEntity residentTransactionEntity : residentTransactionEntityList) { @@ -1867,16 +1836,15 @@ private List convertResidentEntityListToServiceHistor serviceHistoryResponseDto.setEventStatus(statusCode); if (residentTransactionEntity.getUpdDtimes() != null && residentTransactionEntity.getUpdDtimes().isAfter(residentTransactionEntity.getCrDtimes())) { - serviceHistoryResponseDto.setTimeStamp(utility.formatWithOffsetForUI(timeZoneOffset, residentTransactionEntity.getUpdDtimes())); + serviceHistoryResponseDto.setTimeStamp(utility.formatWithOffsetForUI(timeZoneOffset, locale, residentTransactionEntity.getUpdDtimes())); } else { - serviceHistoryResponseDto.setTimeStamp(utility.formatWithOffsetForUI(timeZoneOffset, residentTransactionEntity.getCrDtimes())); + serviceHistoryResponseDto.setTimeStamp(utility.formatWithOffsetForUI(timeZoneOffset,locale, residentTransactionEntity.getCrDtimes())); } if (serviceType.isPresent()) { if (!serviceType.get().equals(ServiceType.ALL.name())) { serviceHistoryResponseDto.setServiceType(serviceType.get()); serviceHistoryResponseDto - .setDescription(getDescriptionForLangCode(langCode, statusCode, requestType, - residentTransactionEntity.getEventId())); + .setDescription(getDescriptionForLangCode(residentTransactionEntity, langCode, statusCode, requestType)); } } else { serviceHistoryResponseDto.setDescription(requestType.name()); @@ -1888,7 +1856,7 @@ private List convertResidentEntityListToServiceHistor return serviceHistoryResponseDtoList; } - private String getDescriptionForLangCode(String langCode, String statusCode, RequestType requestType, String eventId) + public String getDescriptionForLangCode(ResidentTransactionEntity residentTransactionEntity, String langCode, String statusCode, RequestType requestType) throws ResidentServiceCheckedException { TemplateType templateType; if (statusCode.equalsIgnoreCase(EventStatus.SUCCESS.toString())) { @@ -1897,33 +1865,25 @@ private String getDescriptionForLangCode(String langCode, String statusCode, Req templateType = TemplateType.FAILURE; } String templateTypeCode = templateUtil.getPurposeTemplateTypeCode(requestType, templateType); - ResponseWrapper proxyResponseWrapper = proxyMasterdataService - .getAllTemplateBylangCodeAndTemplateTypeCode(langCode, templateTypeCode); - Map templateResponse = new LinkedHashMap<>( - (Map) proxyResponseWrapper.getResponse()); - String fileText = templateResponse.get(ResidentConstants.FILE_TEXT); - return replacePlaceholderValueInTemplate(fileText, eventId, requestType, langCode); + String fileText = templateUtil.getTemplateValueFromTemplateTypeCodeAndLangCode(langCode, templateTypeCode); + return replacePlaceholderValueInTemplate(residentTransactionEntity, fileText, requestType, langCode); } - private String replacePlaceholderValueInTemplate(String fileText, String eventId, RequestType requestType, String langCode) { - return requestType.getDescriptionTemplateVariables(templateUtil, eventId, fileText, langCode); + private String replacePlaceholderValueInTemplate(ResidentTransactionEntity residentTransactionEntity, String fileText, RequestType requestType, String langCode) { + return requestType.getDescriptionTemplateVariables(templateUtil, residentTransactionEntity, fileText, langCode); } - public String getSummaryForLangCode(String langCode, String statusCode, RequestType requestType, String eventId) + public String getSummaryForLangCode(ResidentTransactionEntity residentTransactionEntity, String langCode, String statusCode, RequestType requestType) throws ResidentServiceCheckedException { TemplateType templateType; if (statusCode.equalsIgnoreCase(EventStatus.SUCCESS.toString())) { templateType = TemplateType.SUCCESS; String templateTypeCode = templateUtil.getSummaryTemplateTypeCode(requestType, templateType); - ResponseWrapper proxyResponseWrapper = proxyMasterdataService - .getAllTemplateBylangCodeAndTemplateTypeCode(langCode, templateTypeCode); - Map templateResponse = new LinkedHashMap<>( - (Map) proxyResponseWrapper.getResponse()); - return replacePlaceholderValueInTemplate(templateResponse.get(ResidentConstants.FILE_TEXT), eventId, requestType, langCode); + String fileText = templateUtil.getTemplateValueFromTemplateTypeCodeAndLangCode(langCode, templateTypeCode); + return replacePlaceholderValueInTemplate(residentTransactionEntity, fileText, requestType, langCode); } else { - return getDescriptionForLangCode(langCode, statusCode, requestType, eventId); + return getDescriptionForLangCode(residentTransactionEntity, langCode, statusCode, requestType); } - } public String getEventStatusCode(String statusCode) { @@ -1936,12 +1896,6 @@ public String getEventStatusCode(String statusCode) { } } - @Override - public AidStatusResponseDTO getAidStatus(AidStatusRequestDTO reqDto) - throws ResidentServiceCheckedException, ApisResourceAccessException, OtpValidationFailedException { - return getAidStatus(reqDto, true); - } - @Override public AidStatusResponseDTO getAidStatus(AidStatusRequestDTO reqDto, boolean performOtpValidation) throws ResidentServiceCheckedException, ApisResourceAccessException, OtpValidationFailedException { @@ -1976,30 +1930,7 @@ public AidStatusResponseDTO getAidStatus(AidStatusRequestDTO reqDto, boolean per } @Override - public String checkAidStatus(String aid) throws ResidentServiceCheckedException { - - logger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), - LoggerFileConstant.APPLICATIONID.toString(), "ResidentServiceImpl::checkAidStatus()::Start"); - try { - String uin = identityServiceImpl.getUinForIndividualId(aid); - if (uin == null) { - throw new ResidentServiceCheckedException(ResidentErrorCode.AID_NOT_FOUND); - } - AidStatusRequestDTO aidStatusRequestDTO = new AidStatusRequestDTO(); - aidStatusRequestDTO.setIndividualId(aid); - AidStatusResponseDTO aidStatusResponseDTO = getAidStatus(aidStatusRequestDTO, false); - return aidStatusResponseDTO.getAidStatus(); - } catch (ApisResourceAccessException | OtpValidationFailedException e) { - logger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), - LoggerFileConstant.APPLICATIONID.toString(), - "ResidentServiceImpl::checkAidStatus():: ApisResourceAccessException"); - throw new ResidentServiceCheckedException(ResidentErrorCode.API_RESOURCE_ACCESS_EXCEPTION.getErrorCode(), - ResidentErrorCode.API_RESOURCE_ACCESS_EXCEPTION.getErrorMessage(), e); - } - } - - @Override - public ResponseWrapper getEventStatus(String eventId, String languageCode, int timeZoneOffset) + public ResponseWrapper getEventStatus(String eventId, String languageCode, int timeZoneOffset, String locale) throws ResidentServiceCheckedException { logger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), "ResidentServiceImpl::getEventStatus()::Start"); @@ -2025,7 +1956,7 @@ public ResponseWrapper getEventStatus(String eventId, St Optional serviceType = ServiceType.getServiceTypeFromRequestType(requestType); Map eventStatusMap; - eventStatusMap = requestType.getAckTemplateVariables(templateUtil, eventId, languageCode, timeZoneOffset).getT1(); + eventStatusMap = requestType.getAckTemplateVariables(templateUtil, eventId, languageCode, timeZoneOffset, locale).getT1(); EventStatusResponseDTO eventStatusResponseDTO = new EventStatusResponseDTO(); eventStatusResponseDTO.setEventId(eventId); @@ -2033,6 +1964,7 @@ public ResponseWrapper getEventStatus(String eventId, St eventStatusResponseDTO.setEventStatus(eventStatusMap.get(TemplateVariablesConstants.EVENT_STATUS)); eventStatusResponseDTO.setIndividualId(eventStatusMap.get(TemplateVariablesConstants.INDIVIDUAL_ID)); eventStatusResponseDTO.setTimestamp(eventStatusMap.get(TemplateVariablesConstants.TIMESTAMP)); + eventStatusResponseDTO.setSummary(eventStatusMap.get(TemplateVariablesConstants.SUMMARY)); /** * Removed map value from eventStatusMap to put outside of info in @@ -2045,19 +1977,17 @@ public ResponseWrapper getEventStatus(String eventId, St eventStatusMap.remove(TemplateVariablesConstants.SUMMARY); eventStatusMap.remove(TemplateVariablesConstants.TIMESTAMP); eventStatusMap.remove(TemplateVariablesConstants.TRACK_SERVICE_REQUEST_LINK); - eventStatusMap.remove(TemplateVariablesConstants.TRACK_SERVICE_LINK); String name = identityServiceImpl.getClaimValue(env.getProperty(ResidentConstants.NAME_FROM_PROFILE)); eventStatusMap.put(env.getProperty(ResidentConstants.APPLICANT_NAME_PROPERTY), name); + eventStatusMap.put(env.getProperty(ResidentConstants.AUTHENTICATION_MODE_PROPERTY), eventStatusMap.get(TemplateVariablesConstants.AUTHENTICATION_MODE)); if (serviceType.isPresent()) { if (!serviceType.get().equals(ServiceType.ALL.name())) { - eventStatusResponseDTO.setSummary(getSummaryForLangCode(languageCode, statusCode, requestType, eventId)); eventStatusMap.put(TemplateVariablesConstants.DESCRIPTION, - getDescriptionForLangCode(languageCode, statusCode, requestType, eventId)); + getDescriptionForLangCode(residentTransactionEntity.get(), languageCode, statusCode, requestType)); } } else { - eventStatusResponseDTO.setSummary(requestType.name()); eventStatusMap.put(TemplateVariablesConstants.DESCRIPTION, requestType.name()); } eventStatusResponseDTO.setInfo(eventStatusMap); @@ -2087,11 +2017,11 @@ public ResponseWrapper getnotificationCount(String idaTok time = residentUserEntity.get().getLastbellnotifDtimes(); //Get count of unread events after bell notification click time countOfUnreadNotifications = residentTransactionRepository - .countByIdAndUnreadStatusForRequestTypesAfterNotificationClick(idaToken, time, asyncRequestTypes); + .countByIdAndUnreadStatusForRequestTypesAfterNotificationClick(idaToken, time, asyncRequestTypes, onlineVerificationPartnerId); } else { //Get count of all unread events countOfUnreadNotifications = residentTransactionRepository.countByIdAndUnreadStatusForRequestTypes(idaToken, - asyncRequestTypes); + asyncRequestTypes, onlineVerificationPartnerId); } UnreadNotificationDto notification = new UnreadNotificationDto(); notification.setUnreadCount(countOfUnreadNotifications); @@ -2102,7 +2032,7 @@ public ResponseWrapper getnotificationCount(String idaTok } private List getAsyncRequestTypes() { - return ServiceType.ASYNC.getRequestType() + return ServiceType.ASYNC.getRequestTypes() .stream() .map(RequestType::name) .collect(Collectors.toList()); @@ -2138,10 +2068,15 @@ public int updatebellClickdttimes(String idaToken) throws ApisResourceAccessExce } public ResponseWrapper> getNotificationList(Integer pageStart, - Integer pageFetch, String id, String languageCode, int timeZoneOffset) throws ResidentServiceCheckedException, ApisResourceAccessException { + Integer pageFetch, String id, String languageCode, int timeZoneOffset, String locale) throws ResidentServiceCheckedException, ApisResourceAccessException { + List requestTypeList = ServiceType.ASYNC.getRequestTypes(); + List statusCodeList = requestTypeList.stream() + .flatMap(requestType -> requestType.getNotificationStatusList(env)) + .collect(Collectors.toCollection(ArrayList::new)); ResponseWrapper> responseWrapper = getServiceHistory(pageStart, pageFetch, null, null, ServiceType.ASYNC.name(), null, - null, null, languageCode, timeZoneOffset); + null, null, languageCode, timeZoneOffset, locale, + RESIDENT_NOTIFICATIONS_DEFAULT_PAGE_SIZE, statusCodeList); responseWrapper.setId(unreadnotificationlist); responseWrapper.setVersion(serviceEventVersion); return responseWrapper; @@ -2153,16 +2088,11 @@ public ResponseWrapper> getNotificationList(I */ public byte[] downLoadServiceHistory(ResponseWrapper> responseWrapper, String languageCode, LocalDateTime eventReqDateTime, LocalDate fromDate, LocalDate toDate, - String serviceType, String statusFilter, int timeZoneOffset) throws ResidentServiceCheckedException, IOException { + String serviceType, String statusFilter, int timeZoneOffset, String locale) throws ResidentServiceCheckedException, IOException { logger.debug("ResidentServiceImpl::getResidentServicePDF()::entry"); - String requestProperty = this.env.getProperty(ResidentConstants.SERVICE_HISTORY_PROPERTY_TEMPLATE_TYPE_CODE); - ResponseWrapper proxyResponseWrapper = proxyMasterdataService - .getAllTemplateBylangCodeAndTemplateTypeCode(languageCode, requestProperty); - logger.debug("template data from DB:" + proxyResponseWrapper.getResponse()); - Map templateResponse = new LinkedHashMap<>( - (Map) proxyResponseWrapper.getResponse()); - String fileText = (String) templateResponse.get(ResidentConstants.FILE_TEXT); + String templateTypeCode = this.env.getProperty(ResidentConstants.SERVICE_HISTORY_PROPERTY_TEMPLATE_TYPE_CODE); + String fileText = templateUtil.getTemplateValueFromTemplateTypeCodeAndLangCode(languageCode, templateTypeCode); // for avoiding null values in PDF List serviceHistoryDtlsList = responseWrapper.getResponse().getData(); if (serviceHistoryDtlsList != null && !serviceHistoryDtlsList.isEmpty()) { @@ -2193,11 +2123,11 @@ public byte[] downLoadServiceHistory(ResponseWrapper getUserinfo(String idaToken, int timeZoneOffset) throws ApisResourceAccessException { + public ResponseWrapper getUserinfo(String idaToken, int timeZoneOffset, String locale) throws ApisResourceAccessException { String name = identityServiceImpl.getAvailableclaimValue(env.getProperty(ResidentConstants.NAME_FROM_PROFILE)); String photo = identityServiceImpl.getAvailableclaimValue(env.getProperty(IMAGE)); String email = identityServiceImpl.getAvailableclaimValue(env.getProperty(ResidentConstants.EMAIL_FROM_PROFILE)); @@ -2235,7 +2165,7 @@ public ResponseWrapper getUserinfo(String idaToken, int timeZoneOff lastLoginDateTime = lastTwoLoginEntities.get(0).getLoginDtimes(); } - user.setLastLogin(utility.applyTimeZoneOffsetOnDateTime(timeZoneOffset, lastLoginDateTime)); + user.setLastLogin(utility.formatWithOffsetForUI(timeZoneOffset, locale, lastLoginDateTime)); user.setPhoto(data); responseWrapper.setResponse(user); return responseWrapper; diff --git a/resident/resident-service/src/main/java/io/mosip/resident/service/impl/ResidentVidServiceImpl.java b/resident/resident-service/src/main/java/io/mosip/resident/service/impl/ResidentVidServiceImpl.java index 0e535e7864f..23c6afafcf0 100644 --- a/resident/resident-service/src/main/java/io/mosip/resident/service/impl/ResidentVidServiceImpl.java +++ b/resident/resident-service/src/main/java/io/mosip/resident/service/impl/ResidentVidServiceImpl.java @@ -89,6 +89,8 @@ @Component public class ResidentVidServiceImpl implements ResidentVidService { + private static final String AUTH_TYPE_CODE_SUFFIX = "-AUTH"; + private static final String GENRATED_ON_TIMESTAMP = "genratedOnTimestamp"; private static final String EXPIRY_TIMESTAMP = "expiryTimestamp"; @@ -262,9 +264,10 @@ public Tuple2, String> generateVidV2(BaseVidRequ responseDto.setResponse(vidResponseDto); if(Utility.isSecureSession()) { - residentTransactionEntity.setRefId(utility.convertToMaskDataFormat(vidResponseDto.getVid())); + residentTransactionEntity.setRefId(utility.convertToMaskData(vidResponseDto.getVid())); residentTransactionEntity.setStatusCode(EventStatusSuccess.VID_GENERATED.name()); residentTransactionEntity.setStatusComment(EventStatusSuccess.VID_GENERATED.name()); + residentTransactionEntity.setRequestSummary(String.format("%s - %s", RequestType.GENERATE_VID.getName(), ResidentConstants.SUCCESS)); } } catch (JsonProcessingException e) { @@ -293,10 +296,12 @@ public Tuple2, String> generateVidV2(BaseVidRequ notifyVidCreationFailureAndThrowException(requestDto, isV2Request, notificationRequestDto, eventId, residentTransactionEntity, e); } finally { if (Utility.isSecureSession() && residentTransactionEntity != null) { - //if the status code will come as null, it will set it as failed. - if(residentTransactionEntity.getStatusCode()==null) { + //if the status code or request summary will come as null, it will set it as failed. + if(residentTransactionEntity.getStatusCode() == null || residentTransactionEntity.getRequestSummary() == null) { residentTransactionEntity.setStatusCode(EventStatusFailure.FAILED.name()); - residentTransactionEntity.setRequestSummary("failed"); + residentTransactionEntity.setStatusComment(ResidentConstants.FAILED); + residentTransactionEntity + .setRequestSummary(String.format("%s - %s", RequestType.GENERATE_VID.getName(), ResidentConstants.FAILED)); } residentTransactionRepository.save(residentTransactionEntity); } @@ -381,7 +386,7 @@ private VidPolicy getVidPolicyAsVidPolicyDto() throws ResidentServiceCheckedExce } private Tuple2 getNumberOfPerpetualVidFromUin(String individualId) throws ResidentServiceCheckedException, ApisResourceAccessException { - ResponseWrapper>> vids = retrieveVids(individualId , ResidentConstants.UTC_TIMEZONE_OFFSET); + ResponseWrapper>> vids = retrieveVids(individualId , ResidentConstants.UTC_TIMEZONE_OFFSET, null); List> vidList = vids.getResponse().stream().filter(map -> map.containsKey(TemplateVariablesConstants.VID_TYPE) && String.valueOf(map.get(TemplateVariablesConstants.VID_TYPE)).equalsIgnoreCase((ResidentConstants.PERPETUAL))) .collect(Collectors.toList()); @@ -392,13 +397,11 @@ private Tuple2 getNumberOfPerpetualVidFromUin(String individual } private ResidentTransactionEntity createResidentTransactionEntity(BaseVidRequestDto requestDto) throws ApisResourceAccessException, ResidentServiceCheckedException { - ResidentTransactionEntity residentTransactionEntity=utility.createEntity(); + ResidentTransactionEntity residentTransactionEntity=utility.createEntity(RequestType.GENERATE_VID); residentTransactionEntity.setEventId(utility.createEventId()); - residentTransactionEntity.setRequestTypeCode(RequestType.GENERATE_VID.name()); residentTransactionEntity.setIndividualId(identityServiceImpl.getResidentIndvidualIdFromSession()); residentTransactionEntity.setTokenId(identityServiceImpl.getResidentIdaToken()); residentTransactionEntity.setAuthTypeCode(identityServiceImpl.getResidentAuthenticationMode()); - residentTransactionEntity.setRequestSummary(EventStatusSuccess.VID_GENERATED.name()); residentTransactionEntity.setRefIdType(requestDto.getVidType().toUpperCase()); return residentTransactionEntity; } @@ -516,6 +519,7 @@ public Tuple2, String> revokeVidV2(BaseVid if(idaTokenForVid == null || !idaTokenForIndividualId.equalsIgnoreCase(idaTokenForVid)) { if(Utility.isSecureSession()) { residentTransactionEntity.setStatusCode(EventStatusFailure.FAILED.name()); + residentTransactionEntity.setRequestSummary(String.format("%s - %s", RequestType.REVOKE_VID.getName(), ResidentConstants.FAILED)); residentTransactionRepository.save(residentTransactionEntity); throw new ResidentServiceCheckedException(ResidentErrorCode.VID_NOT_BELONG_TO_SESSION, Map.of(ResidentConstants.EVENT_ID, eventId)); @@ -576,6 +580,7 @@ public Tuple2, String> revokeVidV2(BaseVid if(Utility.isSecureSession()) { residentTransactionEntity.setStatusCode(EventStatusSuccess.VID_REVOKED.name()); residentTransactionEntity.setStatusComment(EventStatusSuccess.VID_REVOKED.name()); + residentTransactionEntity.setRequestSummary(String.format("%s - %s", RequestType.REVOKE_VID.getName(), ResidentConstants.SUCCESS)); } } catch (JsonProcessingException e) { audit.setAuditRequestDto(EventEnum.getEventEnumWithValue(EventEnum.VID_JSON_PARSING_EXCEPTION, @@ -591,10 +596,12 @@ public Tuple2, String> revokeVidV2(BaseVid notifyVidRevokeFailureAndThrowException(requestDto, isV2Request, notificationRequestDto, eventId, residentTransactionEntity, e); } finally { if (Utility.isSecureSession() && residentTransactionEntity != null) { - //if the status code will come as null, it will set it as failed. - if(residentTransactionEntity.getStatusCode()==null) { + //if the status code or request summary will come as null, it will set it as failed. + if(residentTransactionEntity.getStatusCode() == null || residentTransactionEntity.getRequestSummary() == null) { residentTransactionEntity.setStatusCode(EventStatusFailure.FAILED.name()); - residentTransactionEntity.setRequestSummary("failed"); + residentTransactionEntity.setStatusComment(ResidentConstants.FAILED); + residentTransactionEntity + .setRequestSummary(String.format("%s - %s", RequestType.REVOKE_VID.getName(), ResidentConstants.FAILED)); } residentTransactionRepository.save(residentTransactionEntity); } @@ -620,12 +627,23 @@ public Tuple2, String> revokeVidV2(BaseVid private void notifyVidCreationFailureAndThrowException(BaseVidRequestDto requestDto, boolean isV2Request, NotificationRequestDto notificationRequestDto, String eventId, ResidentTransactionEntity residentTransactionEntity, E e) - throws ResidentServiceCheckedException, VidCreationException { - notifyFailureAndThrowException(requestDto, isV2Request, notificationRequestDto, eventId, - residentTransactionEntity, e, RequestType.GENERATE_VID, NotificationTemplateCode.RS_VIN_GEN_FAILURE, - "Request to generate VID", this::createVidGenerateException, VidCreationException.class); + throws ResidentServiceCheckedException, VidAlreadyPresentException { + if(e instanceof VidAlreadyPresentException) { + notifyFailureAndThrowException(requestDto, isV2Request, notificationRequestDto, eventId, + residentTransactionEntity, e, RequestType.GENERATE_VID, NotificationTemplateCode.RS_VIN_GEN_FAILURE, + "Request to generate VID", this::createVidAlreadyPresentException, VidAlreadyPresentException.class); + } else{ + notifyFailureAndThrowException(requestDto, isV2Request, notificationRequestDto, eventId, + residentTransactionEntity, e, RequestType.GENERATE_VID, NotificationTemplateCode.RS_VIN_GEN_FAILURE, + "Request to generate VID", this::createVidCreationException, VidCreationException.class); + } + } + + private VidCreationException createVidCreationException(String eventId, Throwable rootCause) { + return eventId == null ? new VidCreationException(rootCause.getMessage(), rootCause): new VidCreationException(rootCause.getMessage(), rootCause, Map.of(ResidentConstants.EVENT_ID, eventId)); } + private void notifyVidRevokeFailureAndThrowException(BaseVidRevokeRequestDTO requestDto, boolean isV2Request, NotificationRequestDto notificationRequestDto, String eventId, ResidentTransactionEntity residentTransactionEntity, E e) @@ -664,6 +682,8 @@ private void notifyFailure(ObjectWithTransactionID reques requestDto.getTransactionID(), auditEventName)); if(Utility.isSecureSession()) { residentTransactionEntity.setStatusCode(EventStatusFailure.FAILED.name()); + residentTransactionEntity.setStatusComment(ResidentConstants.FAILED); + residentTransactionEntity.setRequestSummary(String.format("%s - %s", requestType.getName(), ResidentConstants.FAILED)); throw targetExceptionCreator.apply(eventId, e); } } @@ -688,29 +708,27 @@ private VidRevocationException createVidRevocationException(String eventId, Thro return eventId == null ? new VidRevocationException(rootCause.getMessage(), rootCause): new VidRevocationException(rootCause.getMessage(), rootCause, Map.of(ResidentConstants.EVENT_ID, eventId)); } - private VidCreationException createVidGenerateException(String eventId, Throwable rootCause) { - return eventId == null ? new VidCreationException(rootCause.getMessage(), rootCause): new VidCreationException(rootCause.getMessage(), rootCause, Map.of(ResidentConstants.EVENT_ID, eventId)); + private VidAlreadyPresentException createVidAlreadyPresentException(String eventId, Throwable rootCause) { + return eventId == null ? new VidAlreadyPresentException(rootCause.getMessage(), rootCause): new VidAlreadyPresentException(rootCause.getMessage(), rootCause, Map.of(ResidentConstants.EVENT_ID, eventId)); } - private ResidentTransactionEntity createResidentTransEntity(String vid, String indivudalId) throws ApisResourceAccessException, ResidentServiceCheckedException { - ResidentTransactionEntity residentTransactionEntity=utility.createEntity(); + private ResidentTransactionEntity createResidentTransEntity(String vid, String individualId) throws ApisResourceAccessException, ResidentServiceCheckedException { + ResidentTransactionEntity residentTransactionEntity=utility.createEntity(RequestType.REVOKE_VID); residentTransactionEntity.setEventId(utility.createEventId()); - residentTransactionEntity.setRequestTypeCode(RequestType.REVOKE_VID.name()); - residentTransactionEntity.setRefId(utility.convertToMaskDataFormat(vid)); + residentTransactionEntity.setRefId(utility.convertToMaskData(vid)); residentTransactionEntity.setIndividualId(identityServiceImpl.getResidentIndvidualIdFromSession()); try { - residentTransactionEntity.setRefIdType(getVidTypeFromVid(vid, indivudalId)); + residentTransactionEntity.setRefIdType(getVidTypeFromVid(vid, individualId)); } catch (Exception exception){ residentTransactionEntity.setRefIdType(""); } residentTransactionEntity.setTokenId(identityServiceImpl.getResidentIdaToken()); residentTransactionEntity.setAuthTypeCode(identityServiceImpl.getResidentAuthenticationMode()); - residentTransactionEntity.setRequestSummary(EventStatusSuccess.VID_REVOKED.name()); return residentTransactionEntity; } private String getVidTypeFromVid(String vid, String indivudalId) throws ResidentServiceCheckedException, ApisResourceAccessException { - ResponseWrapper>> vids = retrieveVids(indivudalId, ResidentConstants.UTC_TIMEZONE_OFFSET); + ResponseWrapper>> vids = retrieveVids(indivudalId, ResidentConstants.UTC_TIMEZONE_OFFSET, null); return vids.getResponse().stream() .filter(map -> ((String)map.get(TemplateVariablesConstants.VID)).equals(vid)) .map(map -> (String)map.get(TemplateVariablesConstants.VID_TYPE)) @@ -787,14 +805,14 @@ public String getVidPolicy() throws ResidentServiceCheckedException { } @Override - public ResponseWrapper>> retrieveVids(String residentIndividualId, int timeZoneOffset) throws ResidentServiceCheckedException, ApisResourceAccessException { + public ResponseWrapper>> retrieveVids(String residentIndividualId, int timeZoneOffset, String locale) throws ResidentServiceCheckedException, ApisResourceAccessException { IdentityDTO identityDTO = identityServiceImpl.getIdentity(residentIndividualId); String uin = identityDTO.getUIN(); - return retrieveVidsfromUin(uin, timeZoneOffset); + return retrieveVidsfromUin(uin, timeZoneOffset, locale); } @Override - public ResponseWrapper>> retrieveVidsfromUin(String uin, int timeZoneOffset) throws ResidentServiceCheckedException, ApisResourceAccessException { + public ResponseWrapper>> retrieveVidsfromUin(String uin, int timeZoneOffset, String locale) throws ResidentServiceCheckedException, ApisResourceAccessException { ResponseWrapper response; try { response = (ResponseWrapper) residentServiceRestClient.getApi( @@ -811,10 +829,11 @@ public ResponseWrapper>> retrieveVidsfromUin(String uin, int LinkedHashMap lhm = new LinkedHashMap(map); getMaskedVid(lhm); getRefIdHash(lhm); - normalizeTime(EXPIRY_TIMESTAMP, lhm, timeZoneOffset); - normalizeTime(GENRATED_ON_TIMESTAMP, lhm, timeZoneOffset); + normalizeTime(EXPIRY_TIMESTAMP, lhm, timeZoneOffset, locale); + normalizeTime(GENRATED_ON_TIMESTAMP, lhm, timeZoneOffset, locale); return lhm; }) + .filter(map1 -> map1.get(TRANSACTIONS_LEFT_COUNT) == null || (int) map1.get(TRANSACTIONS_LEFT_COUNT) > 0) .collect(Collectors.toList()); ResponseWrapper>> res = new ResponseWrapper>>(); res.setId(residentVidGetId); @@ -825,7 +844,7 @@ public ResponseWrapper>> retrieveVidsfromUin(String uin, int } - private void normalizeTime(String attributeName, LinkedHashMap lhm, int timeZoneOffset) { + private void normalizeTime(String attributeName, LinkedHashMap lhm, int timeZoneOffset, String locale) { Object timeObject = lhm.get(attributeName); if(timeObject instanceof String) { String timeStr = String.valueOf(timeObject); @@ -834,30 +853,31 @@ private void normalizeTime(String attributeName, LinkedHashMap l if(localDateTime.getYear() >= 9999) { lhm.put(attributeName, null); } else { - lhm.put(attributeName, utility.formatWithOffsetForUI(timeZoneOffset, localDateTime)) ; + lhm.put(attributeName, utility.formatWithOffsetForUI(timeZoneOffset, locale, localDateTime)) ; } } } private Map getMaskedVid(Map map) { - String maskedvid = utility.convertToMaskDataFormat(map.get(VID).toString()); + String maskedvid = utility.convertToMaskData(map.get(VID).toString()); map.put(MASKED_VID, maskedvid); return map; } private Map getRefIdHash(Map map) { try { - String hashrefid = HMACUtils2.digestAsPlainText(map.get(VID).toString().getBytes()); - int countdb = residentTransactionRepository.findByrefIdandauthtype(hashrefid); if(map.get(TRANSACTION_LIMIT) != null) { + String hashrefid = HMACUtils2.digestAsPlainText(map.get(VID).toString().getBytes()); + int countdb = residentTransactionRepository.findByRefIdAndAuthTypeCodeLike(hashrefid, AUTH_TYPE_CODE_SUFFIX); int limitCount = (int) map.get(TRANSACTION_LIMIT); int leftcount = limitCount - countdb; - map.put(TRANSACTIONS_LEFT_COUNT, leftcount); if(leftcount < 0) { map.put(TRANSACTIONS_LEFT_COUNT, 0); + } else { + map.put(TRANSACTIONS_LEFT_COUNT, leftcount); } - }else { - map.put(TRANSACTIONS_LEFT_COUNT, map.get(TRANSACTION_LIMIT)); + } else { + map.put(TRANSACTIONS_LEFT_COUNT, map.get(TRANSACTION_LIMIT)); } map.remove(HASH_ATTRIBUTES); } catch (NoSuchAlgorithmException e) { @@ -868,7 +888,7 @@ private Map getRefIdHash(Map map) { } public Optional getPerpatualVid(String uin) throws ResidentServiceCheckedException, ApisResourceAccessException { - ResponseWrapper>> vidResp = retrieveVidsfromUin(uin, ResidentConstants.UTC_TIMEZONE_OFFSET); + ResponseWrapper>> vidResp = retrieveVidsfromUin(uin, ResidentConstants.UTC_TIMEZONE_OFFSET, null); List> vids = vidResp.getResponse(); if(vids != null && !vids.isEmpty()) { return vids.stream() diff --git a/resident/resident-service/src/main/java/io/mosip/resident/service/impl/WebSubCredentialStatusUpdateServiceImpl.java b/resident/resident-service/src/main/java/io/mosip/resident/service/impl/WebSubCredentialStatusUpdateServiceImpl.java new file mode 100644 index 00000000000..db7860e53b2 --- /dev/null +++ b/resident/resident-service/src/main/java/io/mosip/resident/service/impl/WebSubCredentialStatusUpdateServiceImpl.java @@ -0,0 +1,68 @@ +package io.mosip.resident.service.impl; + +import java.util.Map; +import java.util.Map.Entry; +import java.util.Optional; +import java.util.stream.Collectors; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import io.mosip.kernel.core.logger.spi.Logger; +import io.mosip.resident.config.LoggerConfiguration; +import io.mosip.resident.entity.ResidentTransactionEntity; +import io.mosip.resident.exception.ApisResourceAccessException; +import io.mosip.resident.exception.ResidentServiceCheckedException; +import io.mosip.resident.helper.CredentialStatusUpdateHelper; +import io.mosip.resident.repository.ResidentTransactionRepository; +import io.mosip.resident.service.WebSubCredentialStatusUpdateService; + +/** + * Service Implementation to update the resident transaction status from the credential status + * update in the websub event. + * + * @author Loganathan S + * + */ +@Service +public class WebSubCredentialStatusUpdateServiceImpl implements WebSubCredentialStatusUpdateService { + + private static final String REQUEST_ID = "requestId"; + + private static final Logger logger = LoggerConfiguration.logConfig(WebSubCredentialStatusUpdateServiceImpl.class); + + @Autowired + private CredentialStatusUpdateHelper credentialStatusUpdateHelper; + + @Autowired + private ResidentTransactionRepository repo; + + @Override + public void updateCredentialStatus(Map eventModel) + throws ResidentServiceCheckedException, ApisResourceAccessException { + logger.debug("Inside WebSubCredentialStatusUpdateServiceImpl.updateCredentialStatus"); + logger.debug("event: " + eventModel); + Map credentialTransactionDetails = Optional.ofNullable(eventModel.get("event")) + .filter(obj -> obj instanceof Map) + .map(obj -> (Map) obj) + .map(map -> map.entrySet() + .stream() + .filter(entry -> entry.getValue() != null) + .collect(Collectors.toMap(Entry::getKey, entry -> String.valueOf(entry.getValue())))) + .orElseGet(() -> Map.of()); + Object requestIdObj = credentialTransactionDetails.get(REQUEST_ID); + if(requestIdObj instanceof String) { + String requestId = (String) requestIdObj; + logger.info(String.format("Updating the status of credential request ID: %s", requestId)); + Optional entityOpt = repo.findOneByCredentialRequestId(requestId); + if(entityOpt.isPresent()) { + credentialStatusUpdateHelper.updateStatus(entityOpt.get(), credentialTransactionDetails); + } else { + logger.debug(String.format("Could not find the resident transaction with credential request ID: %s ; ignoring..", + requestId)); + } + } + logger.debug("Exiting WebSubCredentialStatusUpdateServiceImpl.updateCredentialStatus"); + } + +} diff --git a/resident/resident-service/src/main/java/io/mosip/resident/service/impl/WebSubUpdateAuthTypeServiceImpl.java b/resident/resident-service/src/main/java/io/mosip/resident/service/impl/WebSubUpdateAuthTypeServiceImpl.java index ce80f1afbae..dbd4e203dd6 100644 --- a/resident/resident-service/src/main/java/io/mosip/resident/service/impl/WebSubUpdateAuthTypeServiceImpl.java +++ b/resident/resident-service/src/main/java/io/mosip/resident/service/impl/WebSubUpdateAuthTypeServiceImpl.java @@ -1,16 +1,19 @@ package io.mosip.resident.service.impl; -import java.util.ArrayList; import java.util.List; import java.util.Map; +import java.util.Objects; +import java.util.stream.Collectors; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import io.mosip.kernel.core.logger.spi.Logger; -import io.mosip.kernel.core.websub.model.EventModel; +import io.mosip.kernel.core.util.DateUtils; +import io.mosip.kernel.core.util.StringUtils; import io.mosip.resident.config.LoggerConfiguration; +import io.mosip.resident.constant.EventStatusSuccess; import io.mosip.resident.constant.LoggerFileConstant; import io.mosip.resident.constant.RequestType; import io.mosip.resident.constant.ResidentConstants; @@ -26,6 +29,7 @@ import io.mosip.resident.service.WebSubUpdateAuthTypeService; import io.mosip.resident.util.AuditUtil; import io.mosip.resident.util.EventEnum; +import io.mosip.resident.util.Utility; import reactor.util.function.Tuple2; import reactor.util.function.Tuples; @@ -45,25 +49,32 @@ public class WebSubUpdateAuthTypeServiceImpl implements WebSubUpdateAuthTypeServ @Autowired private ResidentTransactionRepository residentTransactionRepository; + + @Autowired + private Utility utility; @Value("${ida.online-verification-partner-id}") private String onlineVerificationPartnerId; @Override - public void updateAuthTypeStatus(EventModel eventModel) throws ResidentServiceCheckedException, ApisResourceAccessException { + public void updateAuthTypeStatus(Map eventModel) throws ResidentServiceCheckedException, ApisResourceAccessException { logger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), "WebSubUpdateAuthTypeServiceImpl::updateAuthTypeStatus()::entry"); auditUtil.setAuditRequestDto(EventEnum.UPDATE_AUTH_TYPE_STATUS); try{ logger.info("WebSubUpdateAuthTypeServiceImpl::updateAuthTypeStatus()::partnerId"); - Tuple2 tupleResponse = updateInResidentTransactionTable(eventModel, "COMPLETED"); - sendNotificationV2(TemplateType.SUCCESS, tupleResponse.getT1(), tupleResponse.getT2()); + Tuple2 tupleResponse = updateInResidentTransactionTable(eventModel, EventStatusSuccess.COMPLETED.name()); + // only if the event belongs to the current online verification partner, the + // individualId will not be blank, and hence the notification will be sent + if(!StringUtils.isBlank(tupleResponse.getT1()) && !StringUtils.isBlank(tupleResponse.getT2())) { + sendNotificationV2(TemplateType.SUCCESS, tupleResponse.getT1(), tupleResponse.getT2()); + } } catch (Exception e) { logger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), "WebSubUpdateAuthTypeServiceImpl::updateAuthTypeStatus()::exception"); - Tuple2 tupleResponse = updateInResidentTransactionTable(eventModel, "FAILED"); + Tuple2 tupleResponse = updateInResidentTransactionTable(eventModel, EventStatusSuccess.COMPLETED.name()); sendNotificationV2(TemplateType.FAILURE, tupleResponse.getT1(), tupleResponse.getT2()); throw new ResidentServiceCheckedException( ResidentErrorCode.RESIDENT_WEBSUB_UPDATE_AUTH_TYPE_FAILED.getErrorCode(), @@ -71,37 +82,56 @@ public void updateAuthTypeStatus(EventModel eventModel) throws ResidentServiceCh } } - private Tuple2 updateInResidentTransactionTable(EventModel eventModel, String status) { + private Tuple2 updateInResidentTransactionTable(Map eventModel, String status) { logger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), "WebSubUpdateAuthTypeServiceImpl::insertInResidentTransactionTable()::entry"); String eventId = ""; String individualId = ""; - List residentTransactionEntities = new ArrayList<>(); - try { - List> authTypeStatusList = (List>) eventModel.getEvent().getData().get(AUTH_TYPES); - for(Map authType:authTypeStatusList){ - residentTransactionEntities = residentTransactionRepository.findByCredentialRequestId((String)authType.get(REQUEST_ID)); - if(residentTransactionEntities!=null){ - residentTransactionEntities.stream().forEach(residentTransactionEntity -> { - residentTransactionEntity.setStatusCode(status); - residentTransactionEntity.setReadStatus(false); - }); - } - } - residentTransactionRepository.saveAll(residentTransactionEntities); - if (residentTransactionEntities != null && !residentTransactionEntities.isEmpty()) { - eventId = residentTransactionEntities.stream() - .filter(entity -> entity.getOlvPartnerId().equals(onlineVerificationPartnerId)) - .map(entity -> entity.getEventId()) - .findAny() - .orElse(ResidentConstants.NOT_AVAILABLE); - - individualId = residentTransactionEntities.stream() - .filter(entity -> entity.getOlvPartnerId().equals(onlineVerificationPartnerId)) - .map(entity -> entity.getIndividualId()) - .findAny() - .orElse(ResidentConstants.NOT_AVAILABLE); + List residentTransactionEntities = List.of(); + try { + Object eventObj = eventModel.get("event"); + if (eventObj instanceof Map) { + Map eventMap = (Map) eventObj; + Object dataObject = eventMap.get("data"); + if (dataObject instanceof Map) { + Map dataMap = (Map) dataObject; + Object authStatusListObj = (List>) dataMap.get(AUTH_TYPES); + if (authStatusListObj instanceof List) { + List> authTypeStatusList = (List>) authStatusListObj; + residentTransactionEntities = authTypeStatusList.stream() + .map(authTypeStatus -> (String) authTypeStatus.get(REQUEST_ID)) + .filter(Objects::nonNull) + .distinct() + .flatMap(authTypeStatusStr -> residentTransactionRepository + .findByRequestTrnId(authTypeStatusStr).stream()) + .collect(Collectors.toList()); + // Get the values before saving, otherwise individual ID will be updated in + // encrypted format in the entity + if (residentTransactionEntities != null && !residentTransactionEntities.isEmpty()) { + eventId = residentTransactionEntities.stream() + .filter(entity -> entity.getOlvPartnerId().equals(onlineVerificationPartnerId)) + .map(entity -> entity.getEventId()).findAny() + .orElse(ResidentConstants.NOT_AVAILABLE); + + individualId = residentTransactionEntities.stream() + .filter(entity -> entity.getOlvPartnerId().equals(onlineVerificationPartnerId)) + .map(entity -> entity.getIndividualId()).findAny() + .orElse(ResidentConstants.NOT_AVAILABLE); + + // Update status + residentTransactionEntities.stream().forEach(residentTransactionEntity -> { + residentTransactionEntity.setStatusCode(status); + residentTransactionEntity.setReadStatus(false); + residentTransactionEntity.setUpdBy(utility.getSessionUserName()); + residentTransactionEntity.setUpdDtimes(DateUtils.getUTCCurrentDateTime()); + }); + residentTransactionRepository.saveAll(residentTransactionEntities); + } else { + logger.debug("No records found to update."); + } + } + } } } catch (Exception e) { diff --git a/resident/resident-service/src/main/java/io/mosip/resident/util/AuditUtil.java b/resident/resident-service/src/main/java/io/mosip/resident/util/AuditUtil.java index 169e330cf3a..e98f2bf1556 100644 --- a/resident/resident-service/src/main/java/io/mosip/resident/util/AuditUtil.java +++ b/resident/resident-service/src/main/java/io/mosip/resident/util/AuditUtil.java @@ -3,6 +3,7 @@ import java.io.IOException; import java.net.InetAddress; import java.net.UnknownHostException; +import java.security.NoSuchAlgorithmException; import java.util.List; import javax.annotation.PostConstruct; @@ -28,13 +29,18 @@ import io.mosip.kernel.core.http.ResponseWrapper; import io.mosip.kernel.core.logger.spi.Logger; import io.mosip.kernel.core.util.DateUtils; +import io.mosip.kernel.core.util.HMACUtils2; import io.mosip.resident.config.LoggerConfiguration; import io.mosip.resident.constant.LoggerFileConstant; import io.mosip.resident.constant.ResidentConstants; +import io.mosip.resident.constant.ResidentErrorCode; import io.mosip.resident.dto.AuditRequestDTO; import io.mosip.resident.exception.ApisResourceAccessException; +import io.mosip.resident.exception.ResidentServiceException; import io.mosip.resident.exception.ValidationException; import io.mosip.resident.service.impl.IdentityServiceImpl; +import reactor.util.function.Tuple2; +import reactor.util.function.Tuples; @Component public class AuditUtil { @@ -120,9 +126,8 @@ public void setAuditRequestDto(EventEnum eventEnum) { auditRequestDto.setModuleId(eventEnum.getModuleId()); auditRequestDto.setModuleName(eventEnum.getModuleName()); auditRequestDto.setEventId(eventEnum.getEventId()); - auditRequestDto.setId(eventEnum.getId()); - auditRequestDto.setIdType(eventEnum.getIdType()); - auditRequestDto.setCreatedBy(ResidentConstants.RESIDENT); + auditRequestDto.setId(getRefIdandType().getT1()); + auditRequestDto.setIdType(getRefIdandType().getT2()); callAuditManager(auditRequestDto); } @@ -167,5 +172,22 @@ private AuditResponseDto getAuditDetailsFromResponse(String responseBody) throws return auditResponseDto; } + + public Tuple2 getRefIdandType() { + String refId = null; + String refIdType = null; + try { + String individualId = identityService.getResidentIndvidualIdFromSession(); + if (individualId == null || individualId.isEmpty()) { + return Tuples.of(ResidentConstants.NO_ID, ResidentConstants.NO_ID_TYPE); + } + refId = HMACUtils2.digestAsPlainText(individualId.getBytes()); + refIdType = identityService.getIndividualIdType(individualId); + } catch (ApisResourceAccessException | NoSuchAlgorithmException e) { + throw new ResidentServiceException(ResidentErrorCode.API_RESOURCE_ACCESS_EXCEPTION.getErrorCode(), + ResidentErrorCode.API_RESOURCE_ACCESS_EXCEPTION.getErrorMessage(), e); + } + return Tuples.of(refId, refIdType); + } } diff --git a/resident/resident-service/src/main/java/io/mosip/resident/util/EventEnum.java b/resident/resident-service/src/main/java/io/mosip/resident/util/EventEnum.java index e00c42ff369..51a6f980ebc 100644 --- a/resident/resident-service/src/main/java/io/mosip/resident/util/EventEnum.java +++ b/resident/resident-service/src/main/java/io/mosip/resident/util/EventEnum.java @@ -7,87 +7,96 @@ public enum EventEnum { RID_STATUS("RES-SER-101", RegistrationConstants.SYSTEM, "Checking RID status", "Request for checking RID status", "RES-SER", "Residence service", "RS-RID", "RID Status", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - RID_STATUS_RESPONSE("RES-SER-111", RegistrationConstants.SYSTEM, "Checking RID status", "RID status is %s", + RID_STATUS_RESPONSE("RES-SER-111", RegistrationConstants.SYSTEM, "RID status response", "RID status is %s", "RES-SER", "Residence service", "RS-RID", "RID Status", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - RID_STATUS_SUCCESS("RES-SER-200", RegistrationConstants.SYSTEM, "Checking RID status", + RID_STATUS_SUCCESS("RES-SER-200", RegistrationConstants.SYSTEM, "RID status: Success", "Request for checking RID status is success", "RES-SER", "Residence service", "RS-RID", "RID Status", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), + RID_STATUS_FAILURE("RES-SER-302", RegistrationConstants.SYSTEM, "RID status: Failed", + "Request for checking RID status failed", "RES-SER", "Residence service", "RS-RID", "RID Status", + RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), REQ_EUIN("RES-SER-102", RegistrationConstants.SYSTEM, "Request EUIN", "Requesting euin for transaction id %s", "RES-SER", "Residence service", "RS-UIN", "UIN", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - REQ_EUIN_SUCCESS("RES-SER-210", RegistrationConstants.SYSTEM, "Request EUIN", + REQ_EUIN_SUCCESS("RES-SER-319", RegistrationConstants.SYSTEM, "Request EUIN: Success", "Requesting euin for transaction id %s is success", "RES-SER", "Residence service", "RS-UIN", "UIN", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - REQ_PRINTUIN("RES-SER-103", RegistrationConstants.SYSTEM, "Request to print UIN", + REQ_PRINTUIN("RES-SER-103", RegistrationConstants.SYSTEM, "Request print UIN", "Requesting print uin for transaction id %s", "RES-SER", "Residence service", "RS-UIN", "UIN", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - REQ_PRINTUIN_SUCCESS("RES-SER-201", RegistrationConstants.SYSTEM, "Request to print UIN", + REQ_PRINTUIN_SUCCESS("RES-SER-201", RegistrationConstants.SYSTEM, "Request print UIN: Success", "Requesting print uin api for transaction id %s is success", "RES-SER", "Residence service", "RS-UIN", "UIN", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), REQ_AUTH_LOCK("RES-SER-104", RegistrationConstants.SYSTEM, "Request auth lock", "Requesting auth lock for transaction id %s", "RES-SER", "Residence service", "RS-AUTH_LOCK_UNLOCK", "Auth lock/unlock", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - REQ_AUTH_LOCK_SUCCESS("RES-SER-202", RegistrationConstants.SYSTEM, "Request auth lock success", + REQ_AUTH_LOCK_SUCCESS("RES-SER-202", RegistrationConstants.SYSTEM, "Request auth lock: Success", "Requesting auth lock api for transaction id %s is success", "RES-SER", "Residence service", "RS-AUTH_LOCK_UNLOCK", "Auth lock/unlock", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), REQ_AUTH_UNLOCK("RES-SER-105", RegistrationConstants.SYSTEM, "Request auth unlock", "Requesting auth unlock for transaction id %s", "RES-SER", "Residence service", "RS-AUTH_LOCK_UNLOCK", "Auth lock/unlock", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - REQ_AUTH_UNLOCK_SUCCESS("RES-SER-203", RegistrationConstants.SYSTEM, "Request auth unlock", + REQ_AUTH_UNLOCK_SUCCESS("RES-SER-203", RegistrationConstants.SYSTEM, "Request auth unlock: Success", "Requesting auth unlock api for transaction id %s is success", "RES-SER", "Residence service", "RS-AUTH_LOCK_UNLOCK", "Auth lock/unlock", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), REQ_AUTH_HISTORY("RES-SER-106", RegistrationConstants.SYSTEM, "Request auth history", "Requesting auth history for transaction id %s", "RES-SER", "Residence service", "RS-AUTH_HIST", "Auth history", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - REQ_AUTH_HISTORY_SUCCESS("RES-SER-204", RegistrationConstants.SYSTEM, "Request auth history", + REQ_AUTH_HISTORY_SUCCESS("RES-SER-204", RegistrationConstants.SYSTEM, "Request auth history: Success", "Requesting auth history api for transaction id %s is success", "RES-SER", "Residence service", "RS-AUTH_HIST", "Auth history", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), UPDATE_UIN("RES-SER-107", RegistrationConstants.SYSTEM, "Request update uin", "Requesting update uin api for transaction id %s", "RES-SER", "Residence service", "RS-UIN", "UIN", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - UPDATE_UIN_SUCCESS("RES-SER-205", RegistrationConstants.SYSTEM, "Request update uin success", + UPDATE_UIN_SUCCESS("RES-SER-205", RegistrationConstants.SYSTEM, "Request update uin: Success", "Requesting update uin api for transaction id %s is success", "RES-SER", "Residence service", "RS-UIN", "UIN", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), + UPDATE_UIN_FAILURE("RES-SER-305", RegistrationConstants.SYSTEM, "Request update uin: Failed", + "Requesting update uin failed", "RES-SER", "Residence service", "RS-UIN", "UIN", + RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), GENERATE_VID("RES-SER-108", RegistrationConstants.SYSTEM, "Request for generating VID", "Request for generating VID for transaction id %s", "RES-SER", "Residence service", "RS-GEN_REV_VID", "Generate/Revoke VID", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - GENERATE_VID_SUCCESS("RES-SER-206", RegistrationConstants.SYSTEM, "Request for generating VID success", + GENERATE_VID_SUCCESS("RES-SER-206", RegistrationConstants.SYSTEM, "Request for generating VID: Success", "Request for generating VID for transaction id %s is success", "RES-SER", "Residence service", "RS-GEN_REV_VID", "Generate/Revoke VID", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), REVOKE_VID("RES-SER-109", RegistrationConstants.SYSTEM, "Request for revoking VID", "Request for revoking VID for transaction id %s", "RES-SER", "Residence service", "RS-GEN_REV_VID", "Generate/Revoke VID", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - REVOKE_VID_SUCCESS("RES-SER-207", RegistrationConstants.SYSTEM, "Request for revoking VID success", + REVOKE_VID_SUCCESS("RES-SER-207", RegistrationConstants.SYSTEM, "Request for revoking VID: Success", "Request for revoking VID for transaction id %s is success", "RES-SER", "Residence service", "RS-GEN_REV_VID", "Generate/Revoke VID", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), VALIDATE_REQUEST("RES-SER-110", RegistrationConstants.SYSTEM, "Validating input request", "Validating input request of %s", "RES-SER", "Residence service", "RS-VAL_REQ", "Validate request", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - SEND_NOTIFICATION_SUCCESS("RES-SER-208", RegistrationConstants.SYSTEM, "%s", + SEND_NOTIFICATION_SUCCESS("RES-SER-208", RegistrationConstants.SYSTEM, "Send notification: Success", "Sending notification for transaction id %s", "RES-SER", "Residence service", "RS-NOT", "Notification section", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - VALIDATE_OTP("RES-SER-113", RegistrationConstants.SYSTEM, "%s", "Validate OTP for %s", "RES-SER", + VALIDATE_OTP("RES-SER-113", RegistrationConstants.SYSTEM, "validate otp", "Validate OTP for %s", "RES-SER", "Residence service", "RS-OTP", "Otp section", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - VALIDATE_OTP_SUCCESS("RES-SER-209", RegistrationConstants.SYSTEM, "%s", + VALIDATE_OTP_SUCCESS("RES-SER-209", RegistrationConstants.SYSTEM, "Validate otp: Success", "Validating OTP for transaction id %s is success", "RES-SER", "Residence service", "RS-OTP", "Otp section", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), + VALIDATE_OTP_FAILURE("RES-SER-301", RegistrationConstants.SYSTEM, "Validate otp: Failed", + "OTP vaildation for transaction id %s is failed", "RES-SER", "Residence service", "RS-OTP", "Otp section", + RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), GETTING_RID_STATUS("RES-SER-116", RegistrationConstants.SYSTEM, "Checking RID status", "Getting RID status based on individual id", "RES-SER", "Residence service", "RS-RID", "RID section", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - SEND_NOTIFICATION_FAILURE("RES-SER-403", RegistrationConstants.SYSTEM, "%s", + SEND_NOTIFICATION_FAILURE("RES-SER-403", RegistrationConstants.SYSTEM, "Send notification: Failed", "Failure notification sent for transaction id %s", "RES-SER", "Residence service", "RS-NOT", "Notification section", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), @@ -101,38 +110,38 @@ public enum EventEnum { VID_GENERATED("RES-SER-117", RegistrationConstants.SYSTEM, "Request to generate VID", "VID generated for transaction id %s", "RES-SER", "Residence service", "RS-VID_GEN", "VID generation", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - VID_ALREADY_EXISTS("RES-SER-405", RegistrationConstants.SYSTEM, "Request to generate VID", + VID_ALREADY_EXISTS("RES-SER-405", RegistrationConstants.SYSTEM, "VID already exists", "VID already exists for transaction id %s", "RES-SER", "Residence service", "RS-VID_GEN", "VID generation", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - VID_GENERATION_FAILURE("RES-SER-406", RegistrationConstants.SYSTEM, "Request to generate VID", + VID_GENERATION_FAILURE("RES-SER-406", RegistrationConstants.SYSTEM, "Request to generate VID: Failed", "VID generated failed for transaction id %s", "RES-SER", "Residence service", "RS-VID_GEN", "VID generation", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - VID_JSON_PARSING_EXCEPTION("RES-SER-404", RegistrationConstants.SYSTEM, "%s", + VID_JSON_PARSING_EXCEPTION("RES-SER-404", RegistrationConstants.SYSTEM, "Json parsing exception", "JSON parsing exception for transaction id %s while generating VID", "RES-SER", "Residence service", "RS-VID", "VID section", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - DEACTIVATED_VID("RES-SER-210", RegistrationConstants.SYSTEM, "Request to revoke VID", + DEACTIVATED_VID("RES-SER-320", RegistrationConstants.SYSTEM, "Request to revoke VID", "Deactivated VID for transaction id %s while generating VID", "RES-SER", "Residence service", "RS_VID_REV", "Revoke vid", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - VID_REVOKE_EXCEPTION("RES-SER-407", RegistrationConstants.SYSTEM, "Request to revoke VID", + VID_REVOKE_EXCEPTION("RES-SER-407", RegistrationConstants.SYSTEM, "Request to revoke VID: Exception", "Revoking VID failed for transaction id %s", "RES-SER", "Residence service", "RS_VID_REV", "Revoke vid", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - RID_NOT_FOUND("RES-SER-408", RegistrationConstants.SYSTEM, "Checking RID status", + RID_NOT_FOUND("RES-SER-408", RegistrationConstants.SYSTEM, "Checking RID status: Not found", "RID not found while checking for RID status", "RES-SER", "Residence service", "RS-RID", "RID section", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - TOKEN_GENERATION_FAILED("RES-SER-409", RegistrationConstants.SYSTEM, "Generating token", "Token generation failed", + TOKEN_GENERATION_FAILED("RES-SER-409", RegistrationConstants.SYSTEM, "Generating token: Failed", "Token generation failed", "RES-SER", "Residence service", "RS-TOK", "Token generation", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - INPUT_INVALID("RES-SER-410", RegistrationConstants.SYSTEM, "%s", "Invalid input parameter %s", "RES-SER", + INPUT_INVALID("RES-SER-410", RegistrationConstants.SYSTEM, "Invalid input", "Invalid input parameter %s", "RES-SER", "Residence service", "RS-VAL", "Validation section", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - API_NOT_AVAILABLE("RES-SER-411", RegistrationConstants.SYSTEM, "%s", "API not available for transaction id %s", + API_NOT_AVAILABLE("RES-SER-411", RegistrationConstants.SYSTEM, "API not available", "API not available for transaction id %s", "RES-SER", "Residence service", "RS-API", "API section", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - API_RESOURCE_UNACCESS("RES-SER-412", RegistrationConstants.SYSTEM, "%s", + API_RESOURCE_UNACCESS("RES-SER-412", RegistrationConstants.SYSTEM, "API resource unaccess", "Unable to access API resource for transaction id %s", "RES-SER", "Residence service", "RS-API", "API section", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - RID_INVALID("RES-SER-413", RegistrationConstants.SYSTEM, "Check RID", "RID is invalid", "RES-SER", + RID_INVALID("RES-SER-413", RegistrationConstants.SYSTEM, "Check RID: Invalid", "RID is invalid", "RES-SER", "Residence service", "RS-RID", "RID section", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), INPUT_DOESNT_EXISTS("RES-SER-414", RegistrationConstants.SYSTEM, "Validating request", "Request does not exists", @@ -141,46 +150,46 @@ public enum EventEnum { TEMPLATE_EXCEPTION("RES-SER-415", RegistrationConstants.SYSTEM, "Get template", "Template Exception", "RES-SER", "Residence service", "RS-TEMP", "Template section", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - TEMPLATE_SUBJECT_EXCEPTION("RES-SER-416", RegistrationConstants.SYSTEM, "Get template", + TEMPLATE_SUBJECT_EXCEPTION("RES-SER-416", RegistrationConstants.SYSTEM, "Get template Subject", "Template subject exception", "RES-SER", "Residence service", "RS-TEMP", "Template section", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - NOTIFICATION_FAILED("RES-SER-417", RegistrationConstants.SYSTEM, "%s", "Notification failed for transaction id %s", + NOTIFICATION_FAILED("RES-SER-417", RegistrationConstants.SYSTEM, "Notification failed", "Notification failed for transaction id %s", "RES-SER", "Residence service", "RS-NOT", "Notification section", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - BAD_REQUEST("RES-SER-418", RegistrationConstants.SYSTEM, "%s", "Bad request", "RES-SER", "Residence service", + BAD_REQUEST("RES-SER-418", RegistrationConstants.SYSTEM, "Bad request", "Bad request", "RES-SER", "Residence service", "RS-REQ", "Bad request", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - INVALID_API_RESPONSE("RES-SER-419", RegistrationConstants.SYSTEM, "Checking RID status", + INVALID_API_RESPONSE("RES-SER-419", RegistrationConstants.SYSTEM, "Checking RID status: Invalid API response", "Invalid api response while checking RID status", "RES-SER", "Residence service", "RS-API", "API section", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - IO_EXCEPTION("RES-SER-420", RegistrationConstants.SYSTEM, "%s", "IO exception for transaction id %s", "RES-SER", + IO_EXCEPTION("RES-SER-420", RegistrationConstants.SYSTEM, "IO Exception", "IO exception for transaction id %s", "RES-SER", "Residence service", "RS-EXCE", "Exception", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - JSON_PARSING_EXCEPTION("RES-SER-421", RegistrationConstants.SYSTEM, "Request for UIN update", + JSON_PARSING_EXCEPTION("RES-SER-421", RegistrationConstants.SYSTEM, "Request for UIN update: Exception", "JSON parsing exception for transaction id %s", "RES-SER", "Residence service", "RS-EXCE", "Exception", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - OTP_VALIDATION_FAILED("RES-SER-422", RegistrationConstants.SYSTEM, "%s", - "OTP validation failed for transaction id %s", "RES-SER", "Residence service", "RS-OTP", "Otp section", + OTP_VALIDATION_FAILED("RES-SER-422", RegistrationConstants.SYSTEM, "OTP validation: Failed", + "OTP validation failed for user Id: %s", "RES-SER", "Residence service", "RS-OTP", "Otp section", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - BASE_EXCEPTION("RES-SER-401", RegistrationConstants.SYSTEM, "%s", "Base exception for transaction id %s", "RES-SER", + BASE_EXCEPTION("RES-SER-401", RegistrationConstants.SYSTEM, "Base Exception", "Base exception for transaction id %s", "RES-SER", "Residence service", "RS-EXCE", "Exception", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - REQUEST_FAILED("RES-SER-402", RegistrationConstants.SYSTEM, "%s", "Request failed for transaction id %s", "RES-SER", + REQUEST_FAILED("RES-SER-402", RegistrationConstants.SYSTEM, "Request failed", "Request failed for transaction id %s", "RES-SER", "Residence service", "RS-REQ", "Request", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), CREATE_PACKET("RES-SER-118", RegistrationConstants.SYSTEM, "Request to create packet", "Started packet creation", "RES-SER", "Residence service", "RS-PACK", "Packet creation", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - UNKNOWN_EXCEPTION("RES-SER-423", RegistrationConstants.SYSTEM, "Request to create packet", + UNKNOWN_EXCEPTION("RES-SER-423", RegistrationConstants.SYSTEM, "Request to create packet: Exception", "Unknown exception occured", "RES-SER", "Residence service", "RS-EXCE", "Exception", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), PACKET_CREATED("RES-SER-119", RegistrationConstants.SYSTEM, "Request to upload UIN packet", "Uploading UIN packet", "RES-SER", "Residence service", "RS-PACK", "Packet creation", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - PACKET_CREATED_FAILURE("RES-SER-425", RegistrationConstants.SYSTEM, "Request to upload UIN packet", - "Packet sync failure", "RES-SER", "Residence service", "RS-PACK", "Packet creation", + PACKET_CREATED_FAILURE("RES-SER-425", RegistrationConstants.SYSTEM, "Request to upload UIN packet: Failed", + "Packet sync Failure", "RES-SER", "Residence service", "RS-PACK", "Packet creation", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - PACKET_CREATED_EXCEPTION("RES-SER-424", RegistrationConstants.SYSTEM, "Request to create packet", + PACKET_CREATED_EXCEPTION("RES-SER-424", RegistrationConstants.SYSTEM, "Request to create packet: Exception", "Exception while creating packet", "RES-SER", "Residence service", "RS-PACK", "Packet creation", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), PACKET_SYNC("RES-SER-120", RegistrationConstants.SYSTEM, "Request to upload UIN packet", "Sync packet", "RES-SER", @@ -190,70 +199,70 @@ public enum EventEnum { OTP_GEN("RES-SER-121", RegistrationConstants.SYSTEM, "generating otp", "Request for generating otp", "RES-SER", "Residence service", "RS-OTP-GEN", "Otp generation", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - OTP_GEN_SUCCESS("RES-SER-122", RegistrationConstants.SYSTEM, "generating otp", "otp generation is success", + OTP_GEN_SUCCESS("RES-SER-122", RegistrationConstants.SYSTEM, "generating otp: Success", "otp generation is success", "RES-SER", "Residence service", "RS-OTP-GEN", "Otp generation", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - OTP_GEN_EXCEPTION("RES-SER-123", RegistrationConstants.SYSTEM, "generating otp", "otp generation is failed", + OTP_GEN_EXCEPTION("RES-SER-123", RegistrationConstants.SYSTEM, "generating otp: Exception", "otp generation is failed", "RES-SER", "Residence service", "RS-OTP-GEN", "Otp generation", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), CREDENTIAL_REQ("RES-SER-124", RegistrationConstants.SYSTEM, "Sharing credential to partner", "Sharing credential to partner", "RES-SER", "Residence service", "RS-CRED", "Credential request", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - CREDENTIAL_REQ_SUCCESS("RES-SER-125", RegistrationConstants.SYSTEM, "Sharing credential to partner success", + CREDENTIAL_REQ_SUCCESS("RES-SER-125", RegistrationConstants.SYSTEM, "Sharing credential to partner: Success", "Sharing credential to partner is succeded", "RES-SER", "Residence service", "RS-CRED_REQ", "Credential request", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - CREDENTIAL_REQ_EXCEPTION("RES-SER-126", RegistrationConstants.SYSTEM, "Sharing credential to partner failure", + CREDENTIAL_REQ_EXCEPTION("RES-SER-126", RegistrationConstants.SYSTEM, "Sharing credential to partner: Failed", "Sharing credential to partner is failed", "RES-SER", "Residence service", "RS-CRED_REQ", "Credential request", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), CREDENTIAL_REQ_STATUS("RES-SER-127", RegistrationConstants.SYSTEM, "credential status", "request for credential status", "RES-SER", "Residence service", "RS-CRED_REQ", "Credential request", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - CREDENTIAL_REQ_STATUS_SUCCESS("RES-SER-128", RegistrationConstants.SYSTEM, "credential status", + CREDENTIAL_REQ_STATUS_SUCCESS("RES-SER-128", RegistrationConstants.SYSTEM, "credential status: Success", "credential req status is success", "RES-SER", "Residence service", "RS-CRED_REQ", "Credential request", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - CREDENTIAL_REQ_STATUS_EXCEPTION("RES-SER-129", RegistrationConstants.SYSTEM, "credential status", + CREDENTIAL_REQ_STATUS_EXCEPTION("RES-SER-129", RegistrationConstants.SYSTEM, "credential status: Exception", "credential req status is failed", "RES-SER", "Residence service", "RS-CRED_REQ", "Credential request", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), CREDENTIAL_CANCEL_REQ("RES-SER-130", RegistrationConstants.SYSTEM, "credential cancel request", "credential cancel request", "RES-SER", "Residence service", "RS-CRED_REQ", "Credential request", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - CREDENTIAL_CANCEL_REQ_SUCCESS("RES-SER-131", RegistrationConstants.SYSTEM, "credential cancel request", + CREDENTIAL_CANCEL_REQ_SUCCESS("RES-SER-131", RegistrationConstants.SYSTEM, "credential cancel request: Success", "credential cancel request success", "RES-SER", "Residence service", "RS-CRED_REQ", "Credential request", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - CREDENTIAL_CANCEL_REQ_EXCEPTION("RES-SER-132", RegistrationConstants.SYSTEM, "credential cancel request", + CREDENTIAL_CANCEL_REQ_EXCEPTION("RES-SER-132", RegistrationConstants.SYSTEM, "credential cancel request: Exception", "credential cancel request failed", "RES-SER", "Residence service", "RS-CRED_REQ", "Credential request", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), CREDENTIAL_TYPES("RES-SER-133", RegistrationConstants.SYSTEM, "credential types", "credential types", "RES-SER", "Residence service", "RS-CRED_TYP", "Credential type", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - CREDENTIAL_TYPES_SUCCESS("RES-SER-134", RegistrationConstants.SYSTEM, "credential types", + CREDENTIAL_TYPES_SUCCESS("RES-SER-134", RegistrationConstants.SYSTEM, "credential types: Success", "fetch credential type success", "RES-SER", "Residence service", "RS-CRED_TYP", "Credential type", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - CREDENTIAL_TYPES_EXCEPTION("RES-SER-135", RegistrationConstants.SYSTEM, "credential request", + CREDENTIAL_TYPES_EXCEPTION("RES-SER-135", RegistrationConstants.SYSTEM, "credential types: Exception", "fetch credential types failed", "RES-SER", "Residence service", "RS-CRED_TYP", "Credential type", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), REQ_CARD("RES-SER-136", RegistrationConstants.SYSTEM, "request for card", "request for card", "RES-SER", "Residence service", "RS-CARD", "Request card", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - REQ_CARD_SUCCESS("RES-SER-137", RegistrationConstants.SYSTEM, "request for card", "request for card is success", + REQ_CARD_SUCCESS("RES-SER-137", RegistrationConstants.SYSTEM, "request for card: Success", "request for card is success", "RES-SER", "Residence service", "RS-CARD", "Request card", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - REQ_CARD_EXCEPTION("RES-SER-138", RegistrationConstants.SYSTEM, "request for card", "request for card is failed", + REQ_CARD_EXCEPTION("RES-SER-138", RegistrationConstants.SYSTEM, "request for card: Exception", "request for card is failed", "RES-SER", "Residence service", "RS-CARD", "Request card", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), REQ_POLICY("RES-SER-139", RegistrationConstants.SYSTEM, "request for policy", "request for policy", "RES-SER", "Residence service", "RS-POL", "Request policy", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - REQ_POLICY_SUCCESS("RES-SER-140", RegistrationConstants.SYSTEM, "request for policy", + REQ_POLICY_SUCCESS("RES-SER-140", RegistrationConstants.SYSTEM, "request for policy: Success", "request for policy is success", "RES-SER", "Residence service", "RS-POL", "Request policy", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - REQ_POLICY_EXCEPTION("RES-SER-141", RegistrationConstants.SYSTEM, "request for policy", + REQ_POLICY_EXCEPTION("RES-SER-141", RegistrationConstants.SYSTEM, "request for policy: Exception", "request for policy is failed", "RES-SER", "Residence service", "RS-POL", "Request policy", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), @@ -264,40 +273,40 @@ public enum EventEnum { GET_VALID_DOCUMENT("RES-SER-143", RegistrationConstants.SYSTEM, "get valid documents", "get valid documents by lang code", "RES-SER", "Residence service", "RS-DOC", "Document", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - GET_VALID_DOCUMENT_SUCCESS("RES-SER-144", RegistrationConstants.SYSTEM, "get valid documents", + GET_VALID_DOCUMENT_SUCCESS("RES-SER-144", RegistrationConstants.SYSTEM, "get valid documents: Success", "get valid documents by lang code is succeed", "RES-SER", "Residence service", "RS-DOC", "Document", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - GET_VALID_DOCUMENT_EXCEPTION("RES-SER-145", RegistrationConstants.SYSTEM, "get valid documents", + GET_VALID_DOCUMENT_EXCEPTION("RES-SER-145", RegistrationConstants.SYSTEM, "get valid documents: Exception", "get valid documents by lang code is failed", "RES-SER", "Residence service", "RS-DOC", "Document", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), GET_LOCATION_HIERARCHY_LEVEL("RES-SER-146", RegistrationConstants.SYSTEM, "get location hierarchy levels", "get location hierarchy level by lang code", "RES-SER", "Residence service", "RS-LOC", "Location", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - GET_LOCATION_HIERARCHY_LEVEL_SUCCESS("RES-SER-147", RegistrationConstants.SYSTEM, "get location hierarchy levels", + GET_LOCATION_HIERARCHY_LEVEL_SUCCESS("RES-SER-147", RegistrationConstants.SYSTEM, "get location hierarchy levels: Success", "get location hierarchy level by lang code is succeed", "RES-SER", "Residence service", "RS-LOC", "Location", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - GET_LOCATION_HIERARCHY_LEVEL_EXCEPTION("RES-SER-148", RegistrationConstants.SYSTEM, "get location hierarchy levels", + GET_LOCATION_HIERARCHY_LEVEL_EXCEPTION("RES-SER-148", RegistrationConstants.SYSTEM, "get location hierarchy levels: Failed", "get location hierarchy level by lang code is failed", "RES-SER", "Residence service", "RS-LOC", "Location", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), GET_IMMEDIATE_CHILDREN("RES-SER-149", RegistrationConstants.SYSTEM, "get immediate children", "get immediate children by location code and lang code", "RES-SER", "Residence service", "RS-CHILD", "Immediate children", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - GET_IMMEDIATE_CHILDREN_SUCCESS("RES-SER-150", RegistrationConstants.SYSTEM, "get immediate children", + GET_IMMEDIATE_CHILDREN_SUCCESS("RES-SER-150", RegistrationConstants.SYSTEM, "get immediate children: Success", "get immediate children by location code and lang code is succeed", "RES-SER", "Residence service", "RS-CHILD", "Immediate children", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - GET_IMMEDIATE_CHILDREN_EXCEPTION("RES-SER-151", RegistrationConstants.SYSTEM, "get immediate children", + GET_IMMEDIATE_CHILDREN_EXCEPTION("RES-SER-151", RegistrationConstants.SYSTEM, "get immediate children: Exception", "get immediate children by location code and lang code is failed", "RES-SER", "Residence service", "RS-CHILD", "Immediate children", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), GET_LOCATION_DETAILS("RES-SER-152", RegistrationConstants.SYSTEM, "get location details", "get location details by location code and lang code", "RES-SER", "Residence service", "RS-LOC", "Location", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - GET_LOCATION_DETAILS_SUCCESS("RES-SER-153", RegistrationConstants.SYSTEM, "get location details", + GET_LOCATION_DETAILS_SUCCESS("RES-SER-153", RegistrationConstants.SYSTEM, "get location details: Success", "get location details by location code and lang code is succeed", "RES-SER", "Residence service", "RS-LOC", "Location", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - GET_LOCATION_DETAILS_EXCEPTION("RES-SER-154", RegistrationConstants.SYSTEM, "get location details", + GET_LOCATION_DETAILS_EXCEPTION("RES-SER-154", RegistrationConstants.SYSTEM, "get location details: Exception", "get location details by location code and lang code is failed", "RES-SER", "Residence service", "RS-LOC", "Location", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), @@ -306,21 +315,21 @@ public enum EventEnum { "Residence service", "RS-REG", "Registration center", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), GET_COORDINATE_SPECIFIC_REG_CENTERS_SUCCESS("RES-SER-156", RegistrationConstants.SYSTEM, - "get coordinate specific registration centers", "get coordinate specific registration centers is succeed", + "get coordinate specific registration centers", "get coordinate specific registration centers: Success", "RES-SER", "Residence service", "RS-REG", "Registration center", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), GET_COORDINATE_SPECIFIC_REG_CENTERS_EXCEPTION("RES-SER-157", RegistrationConstants.SYSTEM, - "get coordinate specific registration centers", "get coordinate specific registration centers is failed", + "get coordinate specific registration centers", "get coordinate specific registration centers: Failed", "RES-SER", "Residence service", "RS-REG", "Registration center", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), GET_APPLICANT_VALID_DOCUMENT("RES-SER-158", RegistrationConstants.SYSTEM, "get applicant valid documents", "get applicant valid documents", "RES-SER", "Residence service", "RS-DOC", "Document section", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - GET_APPLICANT_VALID_DOCUMENT_SUCCESS("RES-SER-159", RegistrationConstants.SYSTEM, "get applicant valid documents", + GET_APPLICANT_VALID_DOCUMENT_SUCCESS("RES-SER-159", RegistrationConstants.SYSTEM, "get applicant valid documents: Success", "get applicant valid documents is succeed", "RES-SER", "Residence service", "RS-DOC", "Document", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - GET_APPLICANT_VALID_DOCUMENT_EXCEPTION("RES-SER-160", RegistrationConstants.SYSTEM, "get applicant valid documents", + GET_APPLICANT_VALID_DOCUMENT_EXCEPTION("RES-SER-160", RegistrationConstants.SYSTEM, "get applicant valid documents: Exception", "get applicant valid documents is failed", "RES-SER", "Residence service", "RS-DOC", "Document", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), @@ -329,22 +338,22 @@ public enum EventEnum { "Residence service", "RS-REG_LOC", "Registration center location", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), GET_REG_CENTERS_FOR_LOCATION_CODE_SUCCESS("RES-SER-162", RegistrationConstants.SYSTEM, - "get registration centers for location code", "get registration centers for location code is succeed", + "get registration centers for location code", "get registration centers for location code: Success", "RES-SER", "Residence service", "RS-REG_LOC", "Registration center location", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), GET_REG_CENTERS_FOR_LOCATION_CODE_EXCEPTION("RES-SER-163", RegistrationConstants.SYSTEM, - "get registration centers for location code", "get registration centers for location code is failed", + "get registration centers for location code", "get registration centers for location code: Failed", "RES-SER", "Residence service", "RS-REG_LOC", "Registration center location", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), GET_REG_CENTERS_PAGINATED("RES-SER-164", RegistrationConstants.SYSTEM, "get registration centers paginated", "get registration centers paginated", "RES-SER", "Residence service", "RS-REG", "Registration center", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - GET_REG_CENTERS_PAGINATED_SUCCESS("RES-SER-165", RegistrationConstants.SYSTEM, "get registration centers paginated", + GET_REG_CENTERS_PAGINATED_SUCCESS("RES-SER-165", RegistrationConstants.SYSTEM, "get registration centers paginated: Success", "get registration centers paginated is succeed", "RES-SER", "Residence service", "RS-REG", "Registration center", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), GET_REG_CENTERS_PAGINATED_EXCEPTION("RES-SER-166", RegistrationConstants.SYSTEM, - "get registration centers paginated", "get registration centers paginated is failed", "RES-SER", + "get registration centers paginated", "get registration centers paginated: Failed", "RES-SER", "Residence service", "RS-REG", "Registration center", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), @@ -352,11 +361,11 @@ public enum EventEnum { "get resident configuration properties", "RES-SER", "Residence service", "RS-CONF", "Config properties", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), GET_CONFIGURATION_PROPERTIES_SUCCESS("RES-SER-168", RegistrationConstants.SYSTEM, - "get resident configuration properties success", "get resident configuration properties is succeeded", "RES-SER", + "get resident configuration properties success", "get resident configuration properties: Success", "RES-SER", "Residence service", "RS-CONF", "Config properties", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), GET_CONFIGURATION_PROPERTIES_EXCEPTION("RES-SER-169", RegistrationConstants.SYSTEM, - "get resident configuration properties failure", "get resident configuration properties is failed", "RES-SER", + "get resident configuration properties failure", "get resident configuration properties: Failed", "RES-SER", "Residence service", "RS-CONF", "Config properties", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), @@ -364,61 +373,61 @@ public enum EventEnum { "get registration center working days", "RES-SER", "Residence service", "RS-REG", "Registration center", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), GET_REG_CENTER_WORKING_DAYS_SUCCESS("RES-SER-171", RegistrationConstants.SYSTEM, - "get registration center working days success", "get registration center working days is succeeded", "RES-SER", + "get registration center working days success", "get registration center working days: Success", "RES-SER", "Residence service", "RS-REG", "Registration center", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), GET_REG_CENTER_WORKING_DAYS_EXCEPTION("RES-SER-172", RegistrationConstants.SYSTEM, - "get registration center working days failure", "get registration center working days is failed", "RES-SER", + "get registration center working days failure", "get registration center working days: Failed", "RES-SER", "Residence service", "RS-REG", "Registration center", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), GET_LATEST_ID_SCHEMA("RES-SER-173", RegistrationConstants.SYSTEM, "get latest id schema", "get latest id schema", "RES-SER", "Residence service", "RS-ID_SCH", "ID schema", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - GET_LATEST_ID_SCHEMA_SUCCESS("RES-SER-174", RegistrationConstants.SYSTEM, "get latest id schema success", + GET_LATEST_ID_SCHEMA_SUCCESS("RES-SER-174", RegistrationConstants.SYSTEM, "get latest id schema: Success", "get latest id schema is succeeded", "RES-SER", "Residence service", "RS-ID_SCH", "ID schema", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - GET_LATEST_ID_SCHEMA_EXCEPTION("RES-SER-175", RegistrationConstants.SYSTEM, "get latest id schema failure", + GET_LATEST_ID_SCHEMA_EXCEPTION("RES-SER-175", RegistrationConstants.SYSTEM, "get latest id schema: Failed", "get latest id schema is failed", "RES-SER", "Residence service", "RS-ID_SCH", "ID schema", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), UPLOAD_DOCUMENT("RES-SER-176", RegistrationConstants.SYSTEM, "Request document upload", "Requesting document upload api for transaction id %s", "RES-SER", "Residence service", "RS-DOC", "Document", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - UPLOAD_DOCUMENT_SUCCESS("RES-SER-177", RegistrationConstants.SYSTEM, "Document upload success", + UPLOAD_DOCUMENT_SUCCESS("RES-SER-177", RegistrationConstants.SYSTEM, "Document upload: Success", "document upload success for transaction id %s", "RES-SER", "Residence service", "RS-DOC", "Document", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - UPLOAD_DOCUMENT_FAILED("RES-SER-178", RegistrationConstants.SYSTEM, "Document upload failed", + UPLOAD_DOCUMENT_FAILED("RES-SER-178", RegistrationConstants.SYSTEM, "Document upload: Failed", "document upload failed for transaction id %s", "RES-SER", "Residence service", "RS-DOC", "Document", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), GET_DOCUMENTS_METADATA("RES-SER-179", RegistrationConstants.SYSTEM, "Request get documents", "Requesting get documents api for transaction id %s", "RES-SER", "Residence service", "RS-DOC", "Document", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - GET_DOCUMENTS_METADATA_SUCCESS("RES-SER-180", RegistrationConstants.SYSTEM, "Get documents success", + GET_DOCUMENTS_METADATA_SUCCESS("RES-SER-180", RegistrationConstants.SYSTEM, "Get documents: Success", "get documents success for transaction id %s", "RES-SER", "Residence service", "RS-DOC", "Document", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - GET_DOCUMENTS_METADATA_FAILED("RES-SER-181", RegistrationConstants.SYSTEM, "Get documents failed", + GET_DOCUMENTS_METADATA_FAILED("RES-SER-181", RegistrationConstants.SYSTEM, "Get documents: Failed", "Get documents failed for transaction id %s", "RES-SER", "Residence service", "RS-DOC", "Document", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), REQ_AUTH_LOCK_STATUS("RES-SER-182", RegistrationConstants.SYSTEM, "Request auth lock status", "Requesting auth lock status for transaction id %s", "RES-SER", "Residence service", "RS-AUTH_LOCK", "Auth lock", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - REQ_AUTH_LOCK_STATUS_SUCCESS("RES-SER-183", RegistrationConstants.SYSTEM, "Request auth lock status success", + REQ_AUTH_LOCK_STATUS_SUCCESS("RES-SER-183", RegistrationConstants.SYSTEM, "Request auth lock status: Success", "Requesting auth lock status api for transaction id %s is success", "RES-SER", "Residence service", "RS-AUTH_LOCK", "Auth lock", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - REQ_AUTH_LOCK_STATUS_FAILED("RES-SER-184", RegistrationConstants.SYSTEM, "Request auth lock status failure", + REQ_AUTH_LOCK_STATUS_FAILED("RES-SER-184", RegistrationConstants.SYSTEM, "Request auth lock status: Failed", "Requesting auth lock status api for transaction id %s failed", "RES-SER", "Residence service", "RS-AUTH_LOCK", "Auth lock", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - AUTH_TYPE_CALL_BACK("RES-SER-182", RegistrationConstants.SYSTEM, "Request auth type call back url", + AUTH_TYPE_CALL_BACK("RES-SER-322", RegistrationConstants.SYSTEM, "Request auth type call back url", "Requesting auth type call back url for transaction id %s", "RES-SER", "Residence service", "RS-AUTH_TYP", "Auth type", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - AUTH_TYPE_CALL_BACK_SUCCESS("RES-SER-183", RegistrationConstants.SYSTEM, "Auth type call back success", + AUTH_TYPE_CALL_BACK_SUCCESS("RES-SER-323", RegistrationConstants.SYSTEM, "Auth type call back: Success", "auth type call back success for transaction id %s", "RES-SER", "Residence service", "RS-AUTH_TYP", "Auth type", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - AUTH_TYPE_CALL_BACK_FAILURE("RES-SER-184", RegistrationConstants.SYSTEM, "Auth type call back failure", + AUTH_TYPE_CALL_BACK_FAILURE("RES-SER-324", RegistrationConstants.SYSTEM, "Auth type call back: Failed", "auth type call back failure for transaction id %s", "RES-SER", "Residence service", "RS-AUTH_TYP", "Auth type", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), @@ -429,17 +438,17 @@ public enum EventEnum { GET_PARTNERS_BY_PARTNER_TYPE("RES-SER-186", RegistrationConstants.SYSTEM, "get partners by partner type", "get partners by partner type", "RES-SER", "Residence service", "RS-PARTN", "Partner section", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - GET_PARTNERS_BY_PARTNER_TYPE_SUCCESS("RES-SER-187", RegistrationConstants.SYSTEM, "get partners by partner type success", + GET_PARTNERS_BY_PARTNER_TYPE_SUCCESS("RES-SER-187", RegistrationConstants.SYSTEM, "get partners by partner type: Success", "get partners by partner type is succeeded", "RES-SER", "Residence service", "RS-PARTN", "Partner section", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - GET_PARTNERS_BY_PARTNER_TYPE_EXCEPTION("RES-SER-188", RegistrationConstants.SYSTEM, "get partners by partner type failure", + GET_PARTNERS_BY_PARTNER_TYPE_EXCEPTION("RES-SER-188", RegistrationConstants.SYSTEM, "get partners by partner type: Failed", "get partners by partner type is failed", "RES-SER", "Residence service", "RS-PARTN", "Partner section", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), REQ_AUTH_TXN_DETAILS("RES-SER-189", RegistrationConstants.SYSTEM, "Request auth transaction details", "Requesting auth transaction details for individual id %s", "RES-SER", "Residence service", "RS-AUTH_TXN", "Auth transaction", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - REQ_AUTH_TXN_DETAILS_FAILURE("RES-SER-190", RegistrationConstants.SYSTEM, "Request auth transaction details failure", + REQ_AUTH_TXN_DETAILS_FAILURE("RES-SER-190", RegistrationConstants.SYSTEM, "Request auth transaction details: Failed", "Requesting auth transaction details for individual id %s failed", "RES-SER", "Residence service", "RS-AUTH_TXN", "Auth transaction", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), @@ -447,21 +456,21 @@ public enum EventEnum { "get vids", "RES-SER", "Residence service", "RS-VID", "VID", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), GET_VIDS_SUCCESS("RES-SER-192", RegistrationConstants.SYSTEM, - "get vids success", "get vids is succeeded", "RES-SER", + "get vids success", "get vids: Success", "RES-SER", "Residence service", "RS-VID", "VID", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), GET_VIDS_EXCEPTION("RES-SER-193", RegistrationConstants.SYSTEM, - "get vids failure", "get vids is failed", "RES-SER", + "get vids failure", "get vids: Failed", "RES-SER", "Residence service", "RS-VID", "VID", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), OTP_INDIVIDUALID_GEN("RES-SER-194", RegistrationConstants.SYSTEM, "generating otp for Individual ID", "Request for generating otp for Individual ID", "RES-SER", "Residence service", "RS-OTP_GEN", "Otp generation", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - OTP_INDIVIDUALID_GEN_SUCCESS("RES-SER-195", RegistrationConstants.SYSTEM, "generating otp for Individual ID success", "otp generation for Individual ID is success", + OTP_INDIVIDUALID_GEN_SUCCESS("RES-SER-195", RegistrationConstants.SYSTEM, "generating otp for Individual ID: Success", "otp generation for Individual ID is success", "RES-SER", "Residence service", "RS-OTP_GEN", "Otp generation", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - OTP_AID_GEN_EXCEPTION("RES-SER-196", RegistrationConstants.SYSTEM, "generating otp for aid failure", "otp generation for aid is failed", + OTP_AID_GEN_EXCEPTION("RES-SER-196", RegistrationConstants.SYSTEM, "generating otp for aid: Failed", "otp generation for aid is failed", "RES-SER", "Residence service", "RS-OTP_GEN", "Otp generation", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), @@ -469,27 +478,30 @@ public enum EventEnum { "get identity attributes invoked", "RES-SER", "Residence service", "RS-INP_ATTR", "Input attribute", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), GET_INPUT_ATTRIBUTES_SUCCESS("RES-SER-198", RegistrationConstants.SYSTEM, - "get identity attributes success", "get identity attributes is succeeded", "RES-SER", + "get identity attributes success", "get identity attributes: Success", "RES-SER", "Residence service", "RS-INP_ATTR", "Input attribute", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), GET_INPUT_ATTRIBUTES_EXCEPTION("RES-SER-199", RegistrationConstants.SYSTEM, - "get identity attributes failure", "get identity attributes has failed", "RES-SER", + "get identity attributes failure", "get identity attributes: Failed", "RES-SER", "Residence service", "RS-INP_ATTR", "Input attribute", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), AID_STATUS("RES-SER-210", RegistrationConstants.SYSTEM, "Checking AID status", "Request for checking AID status", "RES-SER", "Residence service", "RS-AID", "AID status", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - INDIVIDUALID_STATUS("RES-SER-210", RegistrationConstants.SYSTEM, "Checking Individual ID status", "Request for checking Individual ID status", + INDIVIDUALID_STATUS("RES-SER-321", RegistrationConstants.SYSTEM, "Checking Individual ID status", "Request for checking Individual ID status", "RES-SER", "Residence service", "RS-AID", "AID status", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), AID_STATUS_RESPONSE("RES-SER-211", RegistrationConstants.SYSTEM, "Checking AID status Response", "AID status is %s", "RES-SER", "Residence service", "RS-AID", "AID status", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - AID_STATUS_SUCCESS("RES-SER-212", RegistrationConstants.SYSTEM, "Checking AID status Success", + AID_STATUS_SUCCESS("RES-SER-212", RegistrationConstants.SYSTEM, "Checking AID status: Success", "Request for checking AID status is success", "RES-SER", "Residence service", "RS-AID", "AID status", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - INDIVIDUALID_STATUS_SUCCESS("RES-SER-212", RegistrationConstants.SYSTEM, "Checking Individual ID status Success", + AID_STATUS_FAILURE("RES-SER-308", RegistrationConstants.SYSTEM, "Checking AID status: Failed", + "Request for checking AID status failed", "RES-SER", "Residence service", "RS-AID", "AID status", + RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), + INDIVIDUALID_STATUS_SUCCESS("RES-SER-325", RegistrationConstants.SYSTEM, "Checking Individual ID status: Success", "Request for checking Individual ID status is success", "RES-SER", "Residence service", "RS-IND_ID", "Indiviudal id status", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), REQ_AUTH_TYPE_LOCK("RES-SER-213", RegistrationConstants.SYSTEM, "Request auth type lock", @@ -498,10 +510,16 @@ public enum EventEnum { GET_SERVICE_HISTORY("RES-SER-214", RegistrationConstants.SYSTEM, "get service history", "get service history", "RES-SER", "Residence service", "RS-SERV_HIS", "Service history", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), + GET_SERVICE_HISTORY_SUCCESS("RES-SER-303", RegistrationConstants.SYSTEM, "get service history: Success", + "get service history is success", "RES-SER", "Residence service", "RS-SERV_HIS", "Service history", + RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), + GET_SERVICE_HISTORY_FAILURE("RES-SER-304", RegistrationConstants.SYSTEM, "get service history: Failed", + "get service history failed", "RES-SER", "Residence service", "RS-SERV_HIS", "Service history", + RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), REQ_SERVICE_REQUEST_UPDATE("RES-SER-215", RegistrationConstants.SYSTEM, "Request service request update", "Requesting service request update is success", "RES-SER", "Residence service", "RS-SER_HIS", "Service history", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - REQ_SERVICE_REQUEST_UPDATE_SUCCESS("RES-SER-216", RegistrationConstants.SYSTEM, "Request service request update Success", + REQ_SERVICE_REQUEST_UPDATE_SUCCESS("RES-SER-216", RegistrationConstants.SYSTEM, "Request service request update: Success", "Requesting service request update is success", "RES-SER", "Residence service", "RS-SER_HIS", "Service history", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), IDA_TOKEN_NOT_FOUND("RES-SER-217", RegistrationConstants.SYSTEM, "IDA token not found", @@ -511,30 +529,30 @@ public enum EventEnum { REQ_CUSTOM_CREDENTIAL("RES-SER-218", RegistrationConstants.SYSTEM, "Custom Credential Request", "Custom Credential Request", "RES-SER", "Residence service", "RES-CUS_CRED", "Custom credential", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - REQ_CUSTOM_CREDENTIAL_SUCCESS("RES-SER-219", RegistrationConstants.SYSTEM, "Custom Credential Request Success", + REQ_CUSTOM_CREDENTIAL_SUCCESS("RES-SER-219", RegistrationConstants.SYSTEM, "Custom Credential Request: Success", "Custom Credential Request is success", "RES-SER", "Residence service", "RES-CUS_CRED", "Custom credential", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - REQ_CUSTOM_CREDENTIAL_FAILURE("RES-SER-220", RegistrationConstants.SYSTEM, "Custom Credential Request Failure", + REQ_CUSTOM_CREDENTIAL_FAILURE("RES-SER-220", RegistrationConstants.SYSTEM, "Custom Credential Request: Failed", "Custom Credential Request has failed", "RES-SER", "Residence service", "RES-CUS_CRED", "Custom credential", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), CHANNEL_VERIFICATION_STATUS("RES-SER-221", RegistrationConstants.SYSTEM, "Check Channel Verification status Request", "Check Channel Verification status Request", "RES-SER", "Residence service", "RS-CHAN_VER", "Channel verification", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - CHANNEL_VERIFICATION_STATUS_SUCCESS("RES-SER-222", RegistrationConstants.SYSTEM, "Check Channel Verification status Request Success", + CHANNEL_VERIFICATION_STATUS_SUCCESS("RES-SER-222", RegistrationConstants.SYSTEM, "Check Channel Verification status Request: Success", "Check Channel Verification status Request is success", "RES-SER", "Residence service", "RS-CHAN_VER", "Channel verification", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - CHANNEL_VERIFICATION_STATUS_FAILURE("RES-SER-223", RegistrationConstants.SYSTEM, "Custom Credential Request Failure", + CHANNEL_VERIFICATION_STATUS_FAILURE("RES-SER-223", RegistrationConstants.SYSTEM, "Custom Credential Request: Failed", "Custom Credential Request has failed", "RES-SER", "Residence service", "RS-CHAN_VER", "Channel verification", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), GET_VID_POLICY("RES-SER-224", RegistrationConstants.SYSTEM, "Get VID Policy Request", "Get VID Policy Request", "RES-SER", "Residence service", "RS-VID", "VID", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - GET_VID_POLICY_SUCCESS("RES-SER-225", RegistrationConstants.SYSTEM, "Get VID Policy Request Success", + GET_VID_POLICY_SUCCESS("RES-SER-225", RegistrationConstants.SYSTEM, "Get VID Policy Request: Success", "Get VID Policy Request is success", "RES-SER", "Residence service", "RS-VID", "VID", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - GET_VID_POLICY_FAILURE("RES-SER-226", RegistrationConstants.SYSTEM, "Get VID Policy Request Failure", + GET_VID_POLICY_FAILURE("RES-SER-226", RegistrationConstants.SYSTEM, "Get VID Policy Request: Failed", "Get VID Policy Request has failed", "RES-SER", "Residence service", "RS-VID", "VID", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), @@ -542,34 +560,34 @@ public enum EventEnum { "get identity mapping json", "RES-SER", "Residence service", "RS-ID_MAP", "ID mapping", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), GET_IDMAPPING_SUCCESS("RES-SER-228", RegistrationConstants.SYSTEM, - "get identity mapping json success", "get identity mapping json is succeeded", "RES-SER", + "get identity mapping json success", "get identity mapping json: Success", "RES-SER", "Residence service", "RS-ID_MAP", "ID mapping", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), GET_IDMAPPING_EXCEPTION("RES-SER-229", RegistrationConstants.SYSTEM, - "get identity mapping json failure", "get identity mapping json is failed", "RES-SER", + "get identity mapping json failure", "get identity mapping json: Failed", "RES-SER", "Residence service", "RS-ID_MAP", "ID mapping", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - RID_DIGITAL_CARD_REQ("RES-SER-230", RegistrationConstants.SYSTEM, "RID digital card request", - "Request for downloading digital card based on RID", "RES-SER", "Residence service", "RS-RID_CARD", + RID_DIGITAL_CARD_REQ("RES-SER-230", RegistrationConstants.SYSTEM, "Download digital card request", + "Download digital card request", "RES-SER", "Residence service", "RS-RID_CARD", "RID digital card", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - RID_DIGITAL_CARD_REQ_SUCCESS("RES-SER-231", RegistrationConstants.SYSTEM, "RID digital card request", - "Downloading digital card based on RID success", "RES-SER", "Residence service", "RS-RID_CARD", "NO_ID_TYPE", + RID_DIGITAL_CARD_REQ_SUCCESS("RES-SER-231", RegistrationConstants.SYSTEM, "Download digital card request: Success", + "Download digital card request is succeeded", "RES-SER", "Residence service", "RS-RID_CARD", "NO_ID_TYPE", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - RID_DIGITAL_CARD_REQ_FAILURE("RES-SER-231", RegistrationConstants.SYSTEM, "RID digital card request", - "Downloading digital card based on RID failed", "RES-SER", "Residence service", "RS-RID_CARD", "RID digital card", + RID_DIGITAL_CARD_REQ_FAILURE("RES-SER-232", RegistrationConstants.SYSTEM, "Download digital card request: Failed", + "Download digital card request is failed", "RES-SER", "Residence service", "RS-RID_CARD", "RID digital card", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - RID_DIGITAL_CARD_REQ_EXCEPTION("RES-SER-232", RegistrationConstants.SYSTEM, "RID digital card request", - "Downloading digital card based on RID failed", "RES-SER", "Residence service", "RS-RID_CARD", "RID digital card", + RID_DIGITAL_CARD_REQ_EXCEPTION("RES-SER-326", RegistrationConstants.SYSTEM, "Download digital card request: Exception", + "Download digital card request is failed", "RES-SER", "Residence service", "RS-RID_CARD", "RID digital card", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), CHECK_AID_STATUS_REQUEST("RES-SER-233", RegistrationConstants.SYSTEM, "Request Application status", "Requesting application status", "RES-SER", "Residence service", "RS-AID", "AID status", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - CHECK_AID_STATUS_REQUEST_SUCCESS("RES-SER-234", RegistrationConstants.SYSTEM, "Request credential request status success", + CHECK_AID_STATUS_REQUEST_SUCCESS("RES-SER-234", RegistrationConstants.SYSTEM, "Request credential request status: Success", "Requesting credential request status is success", "RES-SER", "Residence service", "RS-AID", "AID status", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - CHECK_AID_STATUS_REQUEST_FAILED("RES-SER-279", RegistrationConstants.SYSTEM, "Request credential request status failed", + CHECK_AID_STATUS_REQUEST_FAILED("RES-SER-279", RegistrationConstants.SYSTEM, "Request credential request status: Failed", "Requesting credential request status failed", "RES-SER", "Residence service", "RS-AID", "AID status", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), @@ -579,38 +597,38 @@ public enum EventEnum { SEND_PHYSICAL_CARD("RES-SER-236", RegistrationConstants.SYSTEM, "send a physical card", "send a physical card", "RES-SER", "Residence service", "RS-PHYS_CARD", "Physical card", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - SEND_PHYSICAL_CARD_SUCCESS("RES-SER-237", RegistrationConstants.SYSTEM, "send a physical card", + SEND_PHYSICAL_CARD_SUCCESS("RES-SER-237", RegistrationConstants.SYSTEM, "send a physical card: Success", "send a physical card is succeeded", "RES-SER", "Residence service", "RS-PHYS_CARD", "Physical card", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - SEND_PHYSICAL_CARD_EXCEPTION("RES-SER-238", RegistrationConstants.SYSTEM, "send a physical card", + SEND_PHYSICAL_CARD_EXCEPTION("RES-SER-238", RegistrationConstants.SYSTEM, "send a physical card: Exception", "send a physical card is failed", "RES-SER", "Residence service", "RS-PHYS_CARD", "Physical card", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), GET_DOCUMENT_BY_DOC_ID("RES-SER-239", RegistrationConstants.SYSTEM, "get document by doc id", "get document by doc id", "RES-SER", "Residence service", "RS-DOC", "Document by docid", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - GET_DOCUMENT_BY_DOC_ID_SUCCESS("RES-SER-240", RegistrationConstants.SYSTEM, "get document by doc id", + GET_DOCUMENT_BY_DOC_ID_SUCCESS("RES-SER-240", RegistrationConstants.SYSTEM, "get document by doc id: Success", "get document by doc id is succeeded", "RES-SER", "Residence service", "RS-DOC", "Document", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - GET_DOCUMENT_BY_DOC_ID_FAILED("RES-SER-241", RegistrationConstants.SYSTEM, "get document by doc id", + GET_DOCUMENT_BY_DOC_ID_FAILED("RES-SER-241", RegistrationConstants.SYSTEM, "get document by doc id: Failed", "get document by doc id is failed", "RES-SER", "Residence service", "RS-DOC", "Document", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), DELETE_DOCUMENT("RES-SER-242", RegistrationConstants.SYSTEM, "delete document", "delete document", "RES-SER", "Residence service", "RS-DOC", "NO_ID_TYPE", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - DELETE_DOCUMENT_SUCCESS("RES-SER-243", RegistrationConstants.SYSTEM, "delete document Success", + DELETE_DOCUMENT_SUCCESS("RES-SER-243", RegistrationConstants.SYSTEM, "delete document: Success", "delete document is succeeded", "RES-SER", "Residence service", "RS-DOC", "Document", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - DELETE_DOCUMENT_FAILED("RES-SER-244", RegistrationConstants.SYSTEM, "delete document Failed", + DELETE_DOCUMENT_FAILED("RES-SER-244", RegistrationConstants.SYSTEM, "delete document: Failed", "delete document is failed", "RES-SER", "Residence service", "RS-DOC", "Document", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), GET_TEMPLATES("RES-SER-245", RegistrationConstants.SYSTEM, "get templates", "get templates by langCode and templateTypeCode", "RES-SER", "Residence service", "RS-TEMP", "Templates section", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - GET_TEMPLATES_SUCCESS("RES-SER-246", RegistrationConstants.SYSTEM, "get templates success", + GET_TEMPLATES_SUCCESS("RES-SER-246", RegistrationConstants.SYSTEM, "get templates: Success", "get templates by langCode and templateTypeCode is succeeded", "RES-SER", "Residence service", "RS-TEMP", "Templates section", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - GET_TEMPLATES_EXCEPTION("RES-SER-247", RegistrationConstants.SYSTEM, "get templates failure", + GET_TEMPLATES_EXCEPTION("RES-SER-247", RegistrationConstants.SYSTEM, "get templates: Failed", "get templates by langCode and templateTypeCode is failed", "RES-SER", "Residence service", "RS-TEMP", "Templates section", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), INVALID_LANGUAGE_CODE("RES-SER-500", RegistrationConstants.SYSTEM, "Invalid language code", @@ -620,58 +638,63 @@ public enum EventEnum { GET_IDENTITY_UPDATE_COUNT("RES-SER-248", RegistrationConstants.SYSTEM, "get identity update count", "retrieve remaining update counts for each id attributes for a UIN/VID", "RES-SER", "Residence service", "RS-IDEN_COUN", "Identity count", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - GET_IDENTITY_UPDATE_COUNT_SUCCESS("RES-SER-249", RegistrationConstants.SYSTEM, "get identity update count success", + GET_IDENTITY_UPDATE_COUNT_SUCCESS("RES-SER-249", RegistrationConstants.SYSTEM, "get identity update count: Success", "retrieve remaining update counts for each id attributes for a UIN/VID is succeeded", "RES-SER", "Residence service", "RS-IDEN_COUN", "Identity count", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - GET_IDENTITY_UPDATE_COUNT_EXCEPTION("RES-SER-250", RegistrationConstants.SYSTEM, "get identity update count failure", + GET_IDENTITY_UPDATE_COUNT_EXCEPTION("RES-SER-250", RegistrationConstants.SYSTEM, "get identity update count: Failed", "retrieve remaining update counts for each id attributes for a UIN/VID is failed", "RES-SER", "Residence service", "RS-IDEN_COUN", "Identity count", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), PIN_STATUS("RES-SER-251", RegistrationConstants.SYSTEM, "pin status", "pin status based on event id", "RES-SER", "Resident service", "RS-PIN", "Pin status", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - PIN_STATUS_SUCCESS("RES-SER-252", RegistrationConstants.SYSTEM, "pin status success", "pin status success based on event id", "RES-SER", + PIN_STATUS_SUCCESS("RES-SER-252", RegistrationConstants.SYSTEM, "pin status success", "pin status success based on event id: Success", "RES-SER", "Resident service", "RS-PIN", "Pin status", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - PIN_STATUS_FAILURE("RES-SER-253", RegistrationConstants.SYSTEM, "pin status", "pin status failure based on event id", "RES-SER", + PIN_STATUS_FAILURE("RES-SER-253", RegistrationConstants.SYSTEM, "pin status", "pin status failure based on event id: Failed", "RES-SER", "Resident service", "RS-PIN", "Pin status", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), UN_PIN_STATUS("RES-SER-254", RegistrationConstants.SYSTEM, "un pin status", "un pin status based on event id", "RES-SER", "Resident service", "RS-PIN", "Pin status", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - UN_PIN_STATUS_SUCCESS("RES-SER-255", RegistrationConstants.SYSTEM, "un pin status success", "un pin status success based on event id", "RES-SER", + UN_PIN_STATUS_SUCCESS("RES-SER-255", RegistrationConstants.SYSTEM, "un pin status: Success", "un pin status success based on event id", "RES-SER", "Resident service", "RS-PIN", "Pin status", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - UN_PIN_STATUS_FAILURE("RES-SER-256", RegistrationConstants.SYSTEM, "un pin status failure", "un pin status failure based on event id", "RES-SER", + UN_PIN_STATUS_FAILURE("RES-SER-256", RegistrationConstants.SYSTEM, "un pin status: Failed", "un pin status failure based on event id", "RES-SER", "Resident service", "RS-PIN", "Pin statusE", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), GET_ACKNOWLEDGEMENT_DOWNLOAD_URL("RES-SER-257", RegistrationConstants.SYSTEM, "get acknowledgement download url", "get acknowledgement download url", "RES-SER", "Residence service", "RS-ACK_DOWN", "Acknowledgement download", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - GET_ACKNOWLEDGEMENT_DOWNLOAD_URL_SUCCESS("RES-SER-258", RegistrationConstants.SYSTEM, "get acknowledgement download url success", + GET_ACKNOWLEDGEMENT_DOWNLOAD_URL_SUCCESS("RES-SER-258", RegistrationConstants.SYSTEM, "get acknowledgement download url: Success", "get acknowledgement download url is succeeded", "RES-SER", "Residence service", "RS-ACK_DOWN", "Acknowledgement download", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - GET_ACKNOWLEDGEMENT_DOWNLOAD_URL_FAILURE("RES-SER-258", RegistrationConstants.SYSTEM, "get acknowledgement download url failed", + GET_ACKNOWLEDGEMENT_DOWNLOAD_URL_FAILURE("RES-SER-327", RegistrationConstants.SYSTEM, "get acknowledgement download url: Failed", "get acknowledgement download url failed", "RES-SER", "Residence service", "RS-ACK_DOWN", "Acknowledgement download", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - - SEND_OTP_FAILURE("RES-SER-259", RegistrationConstants.SYSTEM, "send otp failure", - "send otp is failed", "RES-SER", "Residence service", "RS-OTP", "Otp section", + + SEND_OTP_SUCCESS("RES-SER-259", RegistrationConstants.SYSTEM, "send otp: Success", + "send otp is success for userId: %s", "RES-SER", "Residence service", "RS-OTP", "Otp section", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - SEND_OTP_SUCCESS("RES-SER-259", RegistrationConstants.SYSTEM, "send otp success", - "send otp is success", "RES-SER", "Residence service", "RS-OTP", "Otp section", + SEND_OTP_FAILURE("RES-SER-290", RegistrationConstants.SYSTEM, "send otp: Failed", + "send otp is failed for userId: %s", "RES-SER", "Residence service", "RS-OTP", "Otp section", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - DOWNLOAD_SERVICE_HISTORY("RES-SER-260", RegistrationConstants.SYSTEM, "download service histor", + DOWNLOAD_SERVICE_HISTORY("RES-SER-260", RegistrationConstants.SYSTEM, "download service history", "get service history pdf", "RES-SER", "Residence service", "RS-DOWN_SER", "Download service history", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - - DOWNLOAD_SERVICE_HISTORY_SUCCESS("RES-SER-266", RegistrationConstants.SYSTEM, "download service history success", "download service history success based on language code", "RES-SER", - "Resident service", "RS-DOWN_SER", "Download service history", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - GET_GENDER_TYPES("RES-SER-261", RegistrationConstants.SYSTEM, "get gender types", - "get gender types by langCode", "RES-SER", "Residence service", "RS-GEND", "Gender", + DOWNLOAD_SERVICE_HISTORY_SUCCESS("RES-SER-266", RegistrationConstants.SYSTEM, "download service history: Success", + "download service history success based on language code", "RES-SER", "Resident service", "RS-DOWN_SER", + "Download service history", RegistrationConstants.RESIDENT_APPLICATION_ID, + RegistrationConstants.RESIDENT_APPLICATION_NAME), + DOWNLOAD_SERVICE_HISTORY_FAILURE("RES-SER-313", RegistrationConstants.SYSTEM, "download service history: Failed", + "download service history failed", "RES-SER", "Resident service", "RS-DOWN_SER", "Download service history", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - GET_GENDER_TYPES_SUCCESS("RES-SER-262", RegistrationConstants.SYSTEM, "get gender types success", + + GET_DYNAMIC_FIELD_BASED_ON_LANG_CODE_AND_FIELD_NAME("RES-SER-261", RegistrationConstants.SYSTEM, "get dynamic field based on lang code and field name", + "get dynamic field based on langCode and field name", "RES-SER", "Residence service", "RS-GEND", "Dynamic Field", + RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), + GET_GENDER_TYPES_SUCCESS("RES-SER-262", RegistrationConstants.SYSTEM, "get gender types: Success", "get gender types by langCode is succeeded", "RES-SER", "Residence service", "RS-GEND", "Gender", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - GET_GENDER_TYPES_EXCEPTION("RES-SER-263", RegistrationConstants.SYSTEM, "get gender types failure", + GET_GENDER_TYPES_EXCEPTION("RES-SER-263", RegistrationConstants.SYSTEM, "get gender types: Failed", "get gender types by langCode is failed", "RES-SER", "Residence service", "RS-GEND", "Gender", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), INVALID_REQUEST_TYPE_CODE("RES-SER-267", RegistrationConstants.SYSTEM, "Invalid request type code", "\"Invalid Request Type. Please input eventId only for VID_CARD_DOWNLOAD,\" +\n" + @@ -679,69 +702,94 @@ public enum EventEnum { "Resident service", "RS-VAL", "Validation", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), DOWNLOAD_PERSONALIZED_CARD("RES-SER-268", RegistrationConstants.SYSTEM, "Download personalized card", - "Download card Html to pdf", "RES-SER", - "Resident service", "RS-DOWN_CARD", "Download card", RegistrationConstants.RESIDENT_APPLICATION_ID, + "Download card Html to pdf", "RES-SER", "Resident service", "RS-DOWN_CARD", "Download card", + RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), + DOWNLOAD_PERSONALIZED_CARD_FAILURE("RES-SER-291", RegistrationConstants.SYSTEM, + "Download personalized card: Failed", "Download card Html to pdf failed", "RES-SER", "Resident service", + "RS-DOWN_CARD", "Download card", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), + DOWNLOAD_REGISTRATION_CENTER("RES-SER-269", RegistrationConstants.SYSTEM, "download registration center", "download registration center", "RES-SER", "Residence service", "RS-DOWN_CARD", "Download card", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - + DOWNLOAD_REGISTRATION_CENTER_SUCCESS("RES-SER-270", RegistrationConstants.SYSTEM, - "download registration center success", + "download registration center: Success", "download registration center success based on language code and hierarchy level", "RES-SER", "Resident service", "RS-DOWN_CARD", "Download card", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - - DOWNLOAD_SUPPORTING_DOCS("RES-SER-271", RegistrationConstants.SYSTEM, "download supporting docs", - "ownload supporting docs", "RES-SER", "Residence service", "RS-DOWN_CARD", "Download card", + + DOWNLOAD_REGISTRATION_CENTER_FAILURE("RES-SER-295", RegistrationConstants.SYSTEM, + "Download registration center: Failed", "Download registration center is failed", "RES-SER", + "Resident service", "RS-DOWN_CARD", "Download card", RegistrationConstants.RESIDENT_APPLICATION_ID, + RegistrationConstants.RESIDENT_APPLICATION_NAME), + + DOWNLOAD_SUPPORTING_DOCS("RES-SER-271", RegistrationConstants.SYSTEM, "Download supporting docs", + "Download supporting docs", "RES-SER", "Residence service", "RS-DOWN_CARD", "Download card", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - DOWNLOAD_SUPPORTING_DOCS_SUCCESS("RES-SER-272", RegistrationConstants.SYSTEM, "download supporting docs success", - "download supporting docs success based on language code", "RES-SER", "Resident service", "RS-DOWN_CARD", - "Download card", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), + DOWNLOAD_SUPPORTING_DOCS_SUCCESS("RES-SER-272", RegistrationConstants.SYSTEM, "Download supporting docs: Success", + "Download supporting docs success based on language code", "RES-SER", "Resident service", "RS-DOWN_CARD", + "Download card", RegistrationConstants.RESIDENT_APPLICATION_ID, + RegistrationConstants.RESIDENT_APPLICATION_NAME), + + DOWNLOAD_SUPPORTING_DOCS_FAILURE("RES-SER-296", RegistrationConstants.SYSTEM, "Download supporting docs: Failed", + "Download supporting docs failed", "RES-SER", "Resident service", "RS-DOWN_CARD", "Download card", + RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), + + DOWNLOAD_REGISTRATION_CENTER_NEAREST("RES-SER-297", RegistrationConstants.SYSTEM, + "Download nearest registration center", + "Download nearest registration center based on language code,longitude,latitude and distance", "RES-SER", + "Resident service", "RS-DOWN_CARD", "Download card", RegistrationConstants.RESIDENT_APPLICATION_ID, + RegistrationConstants.RESIDENT_APPLICATION_NAME), DOWNLOAD_REGISTRATION_CENTER_NEAREST_SUCCESS("RES-SER-273", RegistrationConstants.SYSTEM, - "download registration center success", - "download registration center success based on language code,longitude,latitude and distance", "RES-SER", + "Download nearest registration center: Success", + "Download nearest registration center success based on language code,longitude,latitude and distance", + "RES-SER", "Resident service", "RS-DOWN_CARD", "Download card", + RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), + + DOWNLOAD_REGISTRATION_CENTER_NEAREST_FAILURE("RES-SER-298", RegistrationConstants.SYSTEM, + "Download nearest registration center: Failed", "Download nearest registration center failed", "RES-SER", "Resident service", "RS-DOWN_CARD", "Download card", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - GRIEVANCE_TICKET_REQUEST("RES-SER-273", RegistrationConstants.SYSTEM, + GRIEVANCE_TICKET_REQUEST("RES-SER-328", RegistrationConstants.SYSTEM, "Grievance ticket request", "Grievance ticket request", "RES-SER", "Resident service", "RS-GRIEV", "Grievance ticket", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - GRIEVANCE_TICKET_REQUEST_SUCCESS("RES-SER-273", RegistrationConstants.SYSTEM, - "Grievance ticket request success", + GRIEVANCE_TICKET_REQUEST_SUCCESS("RES-SER-329", RegistrationConstants.SYSTEM, + "Grievance ticket request: Success", "Grievance ticket request success", "RES-SER", "Resident service", "RS-GRIEV", "Grievance ticket", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), GRIEVANCE_TICKET_REQUEST_FAILED("RES-SER-280", RegistrationConstants.SYSTEM, - "Grievance ticket request failed", + "Grievance ticket request: Failed", "Grievance ticket request failed", "RES-SER", "Resident service", "RS-GRIEV", "Grievance ticket", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), GET_DOCUMENT_TYPES("RES-SER-274", RegistrationConstants.SYSTEM, "get document types", "get document types by documentCode and langCode", "RES-SER", "Residence service", "RS-DOC", "Document", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - GET_DOCUMENT_TYPES_SUCCESS("RES-SER-275", RegistrationConstants.SYSTEM, "get document types success", + GET_DOCUMENT_TYPES_SUCCESS("RES-SER-275", RegistrationConstants.SYSTEM, "get document types: Success", "get document types by documentCode and langCode is succeeded", "RES-SER", "Residence service", "RS-DOC", "Document", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - GET_DOCUMENT_TYPES_EXCEPTION("RES-SER-276", RegistrationConstants.SYSTEM, "get document types failure", + GET_DOCUMENT_TYPES_EXCEPTION("RES-SER-276", RegistrationConstants.SYSTEM, "get document types: Failed", "get document types by documentCode and langCode is failed", "RES-SER", "Residence service", "RS-DOC", "Document", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), GET_GENDER_CODE("RES-SER-277", RegistrationConstants.SYSTEM, "get gender code", "get gender code by genderName and langCode", "RES-SER", "Residence service", "RS-GEND", "Gender", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - GET_GENDER_CODE_SUCCESS("RES-SER-278", RegistrationConstants.SYSTEM, "get gender code success", + GET_GENDER_CODE_SUCCESS("RES-SER-278", RegistrationConstants.SYSTEM, "get gender code: Success", "get gender code by genderName and langCode is succeeded", "RES-SER", "Residence service", "RS-GEND", "Gender", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - INVALID_PAGE_START_VALUE("RES-SER-446", RegistrationConstants.SYSTEM, "%s", + INVALID_PAGE_START_VALUE("RES-SER-446", RegistrationConstants.SYSTEM, "Invalid page start value", "Invalid page start value %s", "RES-SER", "Residence service", "RS-VAL", "Validation", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), - INVALID_PAGE_FETCH_VALUE("RES-SER-447", RegistrationConstants.SYSTEM, "%s", + INVALID_PAGE_FETCH_VALUE("RES-SER-447", RegistrationConstants.SYSTEM, "Invalid page fetch value", "Invalid page fetch value %s", "RES-SER", "Residence service", "RS-VAL", "Validation", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), @@ -752,13 +800,13 @@ public enum EventEnum { RegistrationConstants.RESIDENT_APPLICATION_NAME), LOGIN_REQ_SUCCESS("RES-SER-282", RegistrationConstants.SYSTEM, - "Login Request Success", + "Login Request: Success", "Login request is success", "RES-SER", "Resident service", "RS-LOGN", "Login req", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), LOGIN_REQ_FAILURE("RES-SER-283", RegistrationConstants.SYSTEM, - "Login Request Failed", + "Login Request: Failed", "Login request is failed", "RES-SER", "Resident service", "RS-LOGN", "Login req", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), @@ -770,28 +818,88 @@ public enum EventEnum { RegistrationConstants.RESIDENT_APPLICATION_NAME), LOGOUT_REQ_SUCCESS("RES-SER-285", RegistrationConstants.SYSTEM, - "Logout Request Success", + "Logout Request: Success", "Logout request is success", "RES-SER", "Resident service", "RS-LOGO", "Logout req", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), LOGOUT_REQ_FAILURE("RES-SER-286", RegistrationConstants.SYSTEM, - "Logout Request Failed", + "Logout Request: Failed", "Logout request is failed", "RES-SER", "Resident service", "RS-LOGO", "Logout req", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), VALIDATE_TOKEN_SUCCESS("RES-SER-287", RegistrationConstants.SYSTEM, - "Validate Token Success", + "Validate Token: Success", "Validate token is success", "RES-SER", "Resident service", "RS-VAL", "Validate token", RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), VALIDATE_TOKEN_FAILURE("RES-SER-288", RegistrationConstants.SYSTEM, - "Validate Token Failed", + "Validate Token: Failed", "Validate token is failed", "RES-SER", "Resident service", "RS-VAL", "Validate token", RegistrationConstants.RESIDENT_APPLICATION_ID, - RegistrationConstants.RESIDENT_APPLICATION_NAME); + RegistrationConstants.RESIDENT_APPLICATION_NAME), + + CREDENTIAL_STATUS_UPDATE_CALL_BACK("RES-SER-289", RegistrationConstants.SYSTEM, + "Request credential status update call back url", + "Requesting credential status update call back url for transaction id %s", "RES-SER", "Residence service", + "RS-CRED_STAT_UPD", "Credential status update", RegistrationConstants.RESIDENT_APPLICATION_ID, + RegistrationConstants.RESIDENT_APPLICATION_NAME), + CREDENTIAL_STATUS_UPDATE_CALL_BACK_SUCCESS("RES-SER-299", RegistrationConstants.SYSTEM, + "Credential status update call back: Success", + "credential status update call back success for transaction id %s", "RES-SER", "Residence service", + "RS-CRED_STAT_UPD", "Credential status update", RegistrationConstants.RESIDENT_APPLICATION_ID, + RegistrationConstants.RESIDENT_APPLICATION_NAME), + CREDENTIAL_STATUS_UPDATE_CALL_BACK_FAILURE("RES-SER-300", RegistrationConstants.SYSTEM, + "Credential status update call back: Failed", + "credential status update call back failure for transaction id %s", "RES-SER", "Residence service", + "RS-CRED_STAT_UPD", "Credential status update", RegistrationConstants.RESIDENT_APPLICATION_ID, + RegistrationConstants.RESIDENT_APPLICATION_NAME), + + AID_STAGE("RES-SER-292", RegistrationConstants.SYSTEM, "Check AID stage status", "Check AID stage status", + "RES-SER", "Residence service", "RS-AID_STAGE", "AID stage", RegistrationConstants.RESIDENT_APPLICATION_ID, + RegistrationConstants.RESIDENT_APPLICATION_NAME), + AID_STAGE_SUCCESS("RES-SER-293", RegistrationConstants.SYSTEM, "Check AID stage status: Success", + "Check AID stage status is success", "RES-SER", "Residence service", "RS-AID_STAGE", "AID stage", + RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), + AID_STAGE_FAILURE("RES-SER-294", RegistrationConstants.SYSTEM, "Check AID stage status: Failed", + "Check AID stage status is failed", "RES-SER", "Residence service", "RS-AID_STAGE", "AID stage", + RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), + UNREAD_NOTIF_COUNT_SUCCESS("RES-SER-306", RegistrationConstants.SYSTEM, "Unread notification count: Success", + "Unread notification count is success", "RES-SER", "Residence service", "RS-NOT", "Notification section", + RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), + UNREAD_NOTIF_COUNT_FAILURE("RES-SER-307", RegistrationConstants.SYSTEM, "Unread notification count: Failed", + "Unread notification count failed", "RES-SER", "Residence service", "RS-NOT", "Notification section", + RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), + GET_NOTIFICATION_SUCCESS("RES-SER-309", RegistrationConstants.SYSTEM, "Get notification: Success", + "Get notification is Success", "RES-SER", "Residence service", "RS-NOT", "Notification section", + RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), + GET_NOTIFICATION_FAILURE("RES-SER-310", RegistrationConstants.SYSTEM, "Get notification: Failed", + "Get notification failed", "RES-SER", "Residence service", "RS-NOT", "Notification section", + RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), + GET_NOTIF_CLICK_SUCCESS("RES-SER-311", RegistrationConstants.SYSTEM, "Get notification click: Success", + "Get notification click is Success", "RES-SER", "Residence service", "RS-NOT", "Notification section", + RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), + GET_NOTIF_CLICK_FAILURE("RES-SER-312", RegistrationConstants.SYSTEM, "Get notification click: Failed", + "Get notification click failed", "RES-SER", "Residence service", "RS-NOT", "Notification section", + RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), + GET_PROFILE_SUCCESS("RES-SER-314", RegistrationConstants.SYSTEM, "Get profile: Success", + "Get profile is Success", "RES-SER", "Residence service", "RS-PROF", "Profile section", + RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), + GET_PROFILE_FAILURE("RES-SER-315", RegistrationConstants.SYSTEM, "Get profile: Failed", + "Get profile failed", "RES-SER", "Residence service", "RS-PROF", "Profile section", + RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), + TRANSLITERATION_FAILURE("RES-SER-316", RegistrationConstants.SYSTEM, "Transliteration: Failed", + "Transliteration failed", "RES-SER", "Residence service", "RS-TRAN", "Transliteration section", + RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), + VERIFICATION_STATUS_SUCCESS("RES-SER-317", RegistrationConstants.SYSTEM, "Verification status: Success", + "Verification status is success", "RES-SER", "Residence service", "RS-VER", "Verification section", + RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), + VERIFICATION_STATUS_FAILURE("RES-SER-318", RegistrationConstants.SYSTEM, "Verification status: Failed", + "Verification status is failed", "RES-SER", "Residence service", "RS-VER", "Verification section", + RegistrationConstants.RESIDENT_APPLICATION_ID, RegistrationConstants.RESIDENT_APPLICATION_NAME), + ; @@ -803,31 +911,30 @@ public enum EventEnum { private String description; - private String moduleId; + private String refId; - private String moduleName; + private String refIdType; - private String id; + private String moduleId; - private String idType; + private String moduleName; private String applicationId; private String applicationName; - private EventEnum(String eventId, String type, String name, String description, String moduleId, String moduleName, - String id, String idType, String applicationId, String applicationName) { + private EventEnum(String eventId, String type, String name, String description, String refId, String refIdType, + String moduleId, String moduleName, String applicationId, String applicationName) { this.eventId = eventId; this.type = type; this.name = name; this.description = description; + this.refId = refId; + this.refIdType = refIdType; this.moduleId = moduleId; this.moduleName = moduleName; - this.id = id; - this.idType = idType; this.applicationId = applicationId; this.applicationName = applicationName; - } public String getEventId() { @@ -854,12 +961,12 @@ public String getModuleName() { return moduleName; } - public String getId() { - return id; + public String getRefId() { + return refId; } - public String getIdType() { - return idType; + public String getRefIdType() { + return refIdType; } public void setDescription(String des) { @@ -871,7 +978,7 @@ public String getApplicationId() { } public void setId(String id) { - this.id = id; + this.refId = id; } public void setName(String name) { @@ -888,7 +995,7 @@ public String getApplicationName() { public static EventEnum getEventEnumWithValue(EventEnum e, String s) { e.setDescription(String.format(e.getDescription(), s)); - String id = e.getId(); + String id = e.getRefId(); if (id!=null && id.equalsIgnoreCase("%s")){ e.setId(s); } @@ -901,7 +1008,7 @@ public static EventEnum getEventEnumWithValue(EventEnum e, String s) { */ public static EventEnum getEventEnumWithValue(EventEnum e, String edescription, String ename) { e.setDescription(String.format(e.getDescription(), edescription)); - String id = e.getId(); + String id = e.getRefId(); if (id!=null && id.equalsIgnoreCase("%s")) e.setId(edescription); e.setName(String.format(e.getName(), ename)); diff --git a/resident/resident-service/src/main/java/io/mosip/resident/util/ResidentServiceRestClient.java b/resident/resident-service/src/main/java/io/mosip/resident/util/ResidentServiceRestClient.java index 8cc48290dfb..956290b23fa 100644 --- a/resident/resident-service/src/main/java/io/mosip/resident/util/ResidentServiceRestClient.java +++ b/resident/resident-service/src/main/java/io/mosip/resident/util/ResidentServiceRestClient.java @@ -216,7 +216,7 @@ public T getApi(ApiName apiName, Map pathsegments, List q public T postApi(String uri, MediaType mediaType, Object requestType, Class responseClass) throws ApisResourceAccessException { try { - logger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), + logger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), uri); T response = (T) residentRestTemplate.postForObject(uri, setRequestHeader(requestType, mediaType), responseClass); @@ -244,7 +244,7 @@ public T patchApi(String uri, MediaType mediaType, Object requestType, Class throws ApisResourceAccessException { T result = null; try { - logger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), + logger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), uri); result = (T) residentRestTemplate.patchForObject(uri, setRequestHeader(requestType, mediaType), @@ -281,7 +281,7 @@ public T putApi(String uri, Object requestType, Class responseClass, Medi T result = null; ResponseEntity response = null; try { - logger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), + logger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), uri); response = (ResponseEntity) residentRestTemplate.exchange(uri, HttpMethod.PUT, diff --git a/resident/resident-service/src/main/java/io/mosip/resident/util/TemplateUtil.java b/resident/resident-service/src/main/java/io/mosip/resident/util/TemplateUtil.java index cac35e2b264..a504b3f276c 100644 --- a/resident/resident-service/src/main/java/io/mosip/resident/util/TemplateUtil.java +++ b/resident/resident-service/src/main/java/io/mosip/resident/util/TemplateUtil.java @@ -9,6 +9,7 @@ import java.util.Map; import java.util.Objects; import java.util.Optional; +import java.util.stream.Collectors; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; @@ -19,225 +20,296 @@ import io.mosip.kernel.core.logger.spi.Logger; import io.mosip.kernel.core.util.DateUtils; import io.mosip.resident.config.LoggerConfiguration; -import io.mosip.resident.constant.AttributeNameEnum; import io.mosip.resident.constant.AuthenticationModeEnum; -import io.mosip.resident.constant.EventStatus; import io.mosip.resident.constant.EventStatusFailure; import io.mosip.resident.constant.EventStatusInProgress; import io.mosip.resident.constant.EventStatusSuccess; import io.mosip.resident.constant.RequestType; import io.mosip.resident.constant.ResidentConstants; import io.mosip.resident.constant.ResidentErrorCode; +import io.mosip.resident.constant.ServiceType; import io.mosip.resident.constant.TemplateType; import io.mosip.resident.constant.TemplateVariablesConstants; +import io.mosip.resident.constant.UISchemaTypes; import io.mosip.resident.dto.NotificationTemplateVariableDTO; import io.mosip.resident.entity.ResidentTransactionEntity; import io.mosip.resident.exception.ApisResourceAccessException; import io.mosip.resident.exception.ResidentServiceCheckedException; import io.mosip.resident.exception.ResidentServiceException; +import io.mosip.resident.handler.service.ResidentConfigService; import io.mosip.resident.repository.ResidentTransactionRepository; import io.mosip.resident.service.ProxyMasterdataService; import io.mosip.resident.service.impl.IdentityServiceImpl; import io.mosip.resident.service.impl.ProxyPartnerManagementServiceImpl; -import io.mosip.resident.service.impl.ResidentCredentialServiceImpl; import io.mosip.resident.service.impl.ResidentServiceImpl; -import io.mosip.resident.service.impl.UISchemaTypes; import reactor.util.function.Tuple2; import reactor.util.function.Tuples; /** * The Class TemplateUtil. + * * @author Kamesh Shekhar Prasad */ @Component - public class TemplateUtil { +public class TemplateUtil { - private static final String LOGO_URL = "logoUrl"; - private static final CharSequence GENERATED = "generated"; - private static final CharSequence REVOKED = "revoked"; + private static final String DEFAULT = "default"; + private static final String RESIDENT_TEMPLATE_PROPERTY_ATTRIBUTE_LIST = "resident.%s.template.property.attribute.list"; + private static final String LOGO_URL = "logoUrl"; + private static final CharSequence GENERATED = "generated"; + private static final CharSequence REVOKED = "revoked"; + private static final String UNKNOWN = "Unknown"; - @Autowired - private ResidentTransactionRepository residentTransactionRepository; + @Autowired + private ResidentTransactionRepository residentTransactionRepository; - @Autowired - private IdentityServiceImpl identityServiceImpl; - - @Autowired - private ProxyPartnerManagementServiceImpl proxyPartnerManagementServiceImpl; - - @Autowired - private Utility utility; + @Autowired + private IdentityServiceImpl identityServiceImpl; - @Autowired - private ResidentServiceImpl residentService; + @Autowired + private ProxyPartnerManagementServiceImpl proxyPartnerManagementServiceImpl; - @Autowired Environment env; + @Autowired + private Utility utility; - @Autowired - private ProxyMasterdataService proxyMasterdataService; + @Autowired + private ResidentServiceImpl residentService; - @Autowired - private ResidentCredentialServiceImpl residentCredentialServiceImpl; - - @Value("${resident.template.date.pattern}") - private String templateDatePattern; - - @Value("${resident.template.time.pattern}") - private String templateTimePattern; + @Autowired + Environment env; - private static final Logger logger = LoggerConfiguration.logConfig(TemplateUtil.class); - - /** - * Gets the ack template variables for authentication request. - * - * @param eventId the event id - * @return the ack template variables for authentication request - */ - - public Tuple2, ResidentTransactionEntity> getCommonTemplateVariables(String eventId, String languageCode, Integer timeZoneOffset) { - Map templateVariables = new HashMap<>(); - templateVariables.put(TemplateVariablesConstants.EVENT_ID, eventId); - ResidentTransactionEntity residentTransactionEntity = getEntityFromEventId(eventId); - templateVariables.put(TemplateVariablesConstants.EVENT_TYPE, - RequestType.valueOf(residentTransactionEntity.getRequestTypeCode()).getName()); - templateVariables.put(TemplateVariablesConstants.EVENT_STATUS, - getEventStatusForRequestType(residentTransactionEntity.getStatusCode())); - templateVariables.put(TemplateVariablesConstants.SUMMARY, replaceNullWithEmptyString( - residentTransactionEntity.getRequestSummary())); - templateVariables.put(TemplateVariablesConstants.TIMESTAMP, - utility.formatWithOffsetForUI(timeZoneOffset, residentTransactionEntity.getCrDtimes())); - templateVariables.put(TemplateVariablesConstants.TRACK_SERVICE_REQUEST_LINK, utility.createTrackServiceRequestLink(eventId)); - templateVariables.put(TemplateVariablesConstants.TRACK_SERVICE_LINK, utility.createTrackServiceRequestLink(eventId)); - templateVariables.put(TemplateVariablesConstants.PURPOSE, residentTransactionEntity.getPurpose()); - templateVariables.put(TemplateVariablesConstants.ATTRIBUTE_LIST, getAttributesDisplayText(replaceNullWithEmptyString( - residentTransactionEntity.getAttributeList()), languageCode)); - templateVariables.put(TemplateVariablesConstants.AUTHENTICATION_MODE, - getAuthTypeCodeTemplateValue(replaceNullWithEmptyString(residentTransactionEntity.getAuthTypeCode()), languageCode)); - try { - templateVariables.put(TemplateVariablesConstants.INDIVIDUAL_ID, getIndividualIdType()); - } catch (ApisResourceAccessException e) { - logger.error(ResidentErrorCode.API_RESOURCE_ACCESS_EXCEPTION.getErrorCode(),e); - templateVariables.put(TemplateVariablesConstants.INDIVIDUAL_ID, ""); - } - return Tuples.of(templateVariables, residentTransactionEntity); - } + @Autowired + private ProxyMasterdataService proxyMasterdataService; - /** - * This method accepts a string having comma-separated attributes with camel case convention - * and splits it by a comma. - * Then it takes each attribute value from the template in logged-in language and appends it to a string - * with comma-separated value. - * @param attributes attribute values having comma separated attributes. - * @param languageCode logged in language code. - * @return attribute value stored in the template. - */ - private String getAttributesDisplayText(String attributes, String languageCode) { - String phoneAttributeName = this.env.getProperty(ResidentConstants.PHOTO_ATTRIBUTE_NAME); - List attributeListTemplateValue = new ArrayList<>(); - if (attributes != null && attributes.contains(Objects.requireNonNull(phoneAttributeName))) { - attributes = attributes.replace(phoneAttributeName, ""); - } - if (attributes != null) { - List attributeList = List.of(attributes.trim().split(ResidentConstants.COMMA)); - for (String attribute : attributeList) { - attribute = attribute.trim(); - attributeListTemplateValue.add(getTemplateValueFromTemplateTypeCodeAndLangCode(languageCode, - AttributeNameEnum.getTemplatePropertyName(attribute))); - } - } - if(attributeListTemplateValue.isEmpty()){ - return ""; - } else { - return String.join(ResidentConstants.COMMA, attributeListTemplateValue); - } + @Autowired + private ResidentConfigService residentConfigService; - } + @Value("${resident.template.date.pattern}") + private String templateDatePattern; - private String getAuthTypeCodeTemplateValue(String authenticationMode, String languageCode) { - return getTemplateValueFromTemplateTypeCodeAndLangCode - (languageCode, AuthenticationModeEnum.getTemplatePropertyName(authenticationMode, env)); - } + @Value("${resident.template.time.pattern}") + private String templateTimePattern; - public String getTemplateValueFromTemplateTypeCodeAndLangCode(String languageCode, String templateTypeCode){ - ResponseWrapper proxyResponseWrapper = null; - try { - proxyResponseWrapper = proxyMasterdataService - .getAllTemplateBylangCodeAndTemplateTypeCode(languageCode, templateTypeCode); - } catch (ResidentServiceCheckedException e) { - throw new RuntimeException(e); - } - Map templateResponse = new LinkedHashMap<>( - (Map) proxyResponseWrapper.getResponse()); - return templateResponse.get(ResidentConstants.FILE_TEXT); - } + private static final Logger logger = LoggerConfiguration.logConfig(TemplateUtil.class); + + /** + * Gets the ack template variables for authentication request. + * + * @param eventId the event id + * @return the ack template variables for authentication request + */ + + public Tuple2, ResidentTransactionEntity> getCommonTemplateVariables(String eventId, String languageCode, Integer timeZoneOffset, String locale) { + Map templateVariables = new HashMap<>(); + templateVariables.put(TemplateVariablesConstants.EVENT_ID, eventId); + ResidentTransactionEntity residentTransactionEntity = getEntityFromEventId(eventId); + String statusCode = residentService.getEventStatusCode(residentTransactionEntity.getStatusCode()); + RequestType requestType = RequestType.getRequestTypeFromString(residentTransactionEntity.getRequestTypeCode()); + Optional serviceType = ServiceType.getServiceTypeFromRequestType(requestType); + templateVariables.put(TemplateVariablesConstants.EVENT_TYPE, requestType.getName()); + templateVariables.put(TemplateVariablesConstants.EVENT_STATUS, statusCode); + if (serviceType.isPresent()) { + if (!serviceType.get().equals(ServiceType.ALL.name())) { + templateVariables.put(TemplateVariablesConstants.SUMMARY, + getSummaryFromResidentTransactionEntityLangCode(residentTransactionEntity, languageCode, + statusCode, requestType)); + } + } else { + templateVariables.put(TemplateVariablesConstants.SUMMARY, requestType.name()); + } + templateVariables.put(TemplateVariablesConstants.TIMESTAMP, + utility.formatWithOffsetForUI(timeZoneOffset, locale, residentTransactionEntity.getCrDtimes())); + templateVariables.put(TemplateVariablesConstants.TRACK_SERVICE_REQUEST_LINK, + utility.createTrackServiceRequestLink(eventId)); + templateVariables.put(TemplateVariablesConstants.PURPOSE, residentTransactionEntity.getPurpose()); + templateVariables.put(TemplateVariablesConstants.ATTRIBUTE_LIST, getAttributesDisplayText( + replaceNullWithEmptyString(residentTransactionEntity.getAttributeList()), languageCode, requestType)); + String authenticationMode = getAuthTypeCodeTemplateValue( + replaceNullWithEmptyString(residentTransactionEntity.getAuthTypeCode()), languageCode); + if (authenticationMode.equalsIgnoreCase(UNKNOWN)) { + templateVariables.put(TemplateVariablesConstants.AUTHENTICATION_MODE, + replaceNullWithEmptyString(residentTransactionEntity.getAuthTypeCode())); + } else { + templateVariables.put(TemplateVariablesConstants.AUTHENTICATION_MODE, authenticationMode); + } + try { + templateVariables.put(TemplateVariablesConstants.INDIVIDUAL_ID, getIndividualIdType()); + } catch (ApisResourceAccessException e) { + logger.error(ResidentErrorCode.API_RESOURCE_ACCESS_EXCEPTION.getErrorCode(), e); + templateVariables.put(TemplateVariablesConstants.INDIVIDUAL_ID, ""); + } + return Tuples.of(templateVariables, residentTransactionEntity); + } + /** + * This method accepts a string having comma-separated attributes with camel + * case convention and splits it by a comma. Then it takes each attribute value + * from the template in logged-in language and appends it to a string with + * comma-separated value. + * + * @param attributesFromDB attribute values having comma separated attributes. + * @param languageCode logged in language code. + * @return attribute value stored in the template. + */ + private String getAttributesDisplayText(String attributesFromDB, String languageCode, RequestType requestType) { + List attributeListTemplateValue = new ArrayList<>(); + if (attributesFromDB != null && !attributesFromDB.isEmpty()) { + Optional schemaType = UISchemaTypes.getUISchemaTypeFromRequestTypeCode(requestType); + if (schemaType.isPresent() && attributesFromDB.contains(ResidentConstants.SEMI_COLON)) { +// Cacheable UI Schema data + Map> uiSchemaDataMap = residentConfigService + .getUISchemaCacheableData(schemaType.get()).get(languageCode); + List attributeListFromDB = List.of(attributesFromDB.split(ResidentConstants.SEMI_COLON)); + attributeListTemplateValue = attributeListFromDB.stream().map(attribute -> { + String[] attrArray = attribute.trim().split(ResidentConstants.COLON); + String attr = attrArray[0]; + if (uiSchemaDataMap.containsKey(attr)) { + Map attributeDataFromUISchema = (Map) uiSchemaDataMap.get(attr); + attr = (String) attributeDataFromUISchema.get(ResidentConstants.LABEL); + if (attrArray.length > 1) { + String formatAttr = attrArray[1]; + Map formatDataMapFromUISchema = (Map) attributeDataFromUISchema + .get(ResidentConstants.FORMAT_OPTION); + List formatAttrList = List + .of(formatAttr.split(ResidentConstants.ATTRIBUTE_LIST_DELIMITER)).stream() + .map(String::trim).map(format -> formatDataMapFromUISchema.get(format)) + .collect(Collectors.toList()); + if (!formatAttrList.contains(null)) { + return String.format("%s%s%s%s", attr, ResidentConstants.OPEN_PARENTHESIS, + formatAttrList.stream().collect( + Collectors.joining(ResidentConstants.UI_ATTRIBUTE_DATA_DELIMITER)), + ResidentConstants.CLOSE_PARENTHESIS); + } + } + } + return attr; + }).collect(Collectors.toList()); + } else { + List attributeListFromDB = List + .of(attributesFromDB.split(ResidentConstants.ATTRIBUTE_LIST_DELIMITER)); + for (String attribute : attributeListFromDB) { + attributeListTemplateValue.add(getTemplateValueFromTemplateTypeCodeAndLangCode(languageCode, + getAttributeListTemplateTypeCode(attribute.trim()))); + } + } + } + if (attributeListTemplateValue.isEmpty()) { + return ""; + } else { + return attributeListTemplateValue.stream() + .collect(Collectors.joining(ResidentConstants.UI_ATTRIBUTE_DATA_DELIMITER)); + } + } - public String getDescriptionTemplateVariablesForAuthenticationRequest(String eventId, String fileText, String languageCode){ - return fileText; - } + private String getAuthTypeCodeTemplateValue(String authenticationMode, String languageCode) { + return getTemplateValueFromTemplateTypeCodeAndLangCode(languageCode, + AuthenticationModeEnum.getTemplatePropertyName(authenticationMode, env)); + } - public String getDescriptionTemplateVariablesForShareCredential(String eventId, String fileText, String languageCode) { - ResidentTransactionEntity residentTransactionEntity =getEntityFromEventId(eventId); - return residentCredentialServiceImpl.prepareReqSummaryMsg(Collections.singletonList( - residentTransactionEntity.getAttributeList())); - } + public String getTemplateValueFromTemplateTypeCodeAndLangCode(String languageCode, String templateTypeCode) { + try { + ResponseWrapper proxyResponseWrapper = proxyMasterdataService + .getAllTemplateBylangCodeAndTemplateTypeCode(languageCode, templateTypeCode); + logger.debug(String.format("Template data from DB:- %s", proxyResponseWrapper.getResponse())); + Map templateResponse = new LinkedHashMap<>( + (Map) proxyResponseWrapper.getResponse()); + return templateResponse.get(ResidentConstants.FILE_TEXT); + } catch (ResidentServiceCheckedException e) { + throw new ResidentServiceException(ResidentErrorCode.TEMPLATE_EXCEPTION, e); + } + } - public String getDescriptionTemplateVariablesForDownloadPersonalizedCard(String eventId, String fileText, String languageCode){ - return addAttributeInPurpose(fileText, getEntityFromEventId(eventId).getAttributeList(), languageCode); - } + public String getDescriptionTemplateVariablesForAuthenticationRequest( + ResidentTransactionEntity residentTransactionEntity, String fileText, String languageCode) { + return residentTransactionEntity.getStatusComment(); + } - public String getDescriptionTemplateVariablesForOrderPhysicalCard(String eventId, String fileText, String languageCode){ - return fileText; - } + public String getDescriptionTemplateVariablesForShareCredential(ResidentTransactionEntity residentTransactionEntity, + String fileText, String languageCode) { + return addAttributeListInPurpose(fileText, residentTransactionEntity.getAttributeList(), languageCode); + } - public String getDescriptionTemplateVariablesForGetMyId(String eventId, String fileText, String languageCode){ - return fileText; - } + public String getDescriptionTemplateVariablesForDownloadPersonalizedCard( + ResidentTransactionEntity residentTransactionEntity, String fileText, String languageCode) { + return addAttributeListInPurpose(fileText, residentTransactionEntity.getAttributeList(), languageCode); + } - public String getDescriptionTemplateVariablesForUpdateMyUin(String eventId, String fileText, String languageCode){ - return fileText; - } + public String getDescriptionTemplateVariablesForOrderPhysicalCard( + ResidentTransactionEntity residentTransactionEntity, String fileText, String languageCode) { + return fileText; + } - public String getDescriptionTemplateVariablesForManageMyVid(String eventId, String fileText, String languageCode) { - ResidentTransactionEntity residentTransactionEntity = getEntityFromEventId(eventId); - fileText = fileText.replace(ResidentConstants.DOLLAR + ResidentConstants.VID_TYPE, - replaceNullWithEmptyString(residentTransactionEntity.getRefIdType())); - fileText = fileText.replace(ResidentConstants.MASKED_VID, replaceNullWithEmptyString( - residentTransactionEntity.getRefId())); - String requestType = residentTransactionEntity.getRequestTypeCode(); - if (requestType.equalsIgnoreCase(RequestType.GENERATE_VID.name())) { - fileText = fileText.replace(ResidentConstants.DOLLAR + ResidentConstants.ACTION_PERFORMED, GENERATED); - } else if (requestType.equalsIgnoreCase(RequestType.REVOKE_VID.name())) { - fileText = fileText.replace(ResidentConstants.DOLLAR + ResidentConstants.ACTION_PERFORMED, REVOKED); - } - return fileText; - } + public String getDescriptionTemplateVariablesForGetMyId(ResidentTransactionEntity residentTransactionEntity, + String fileText, String languageCode) { + return fileText; + } - public String getDescriptionTemplateVariablesForVidCardDownload(String eventId, String fileText, String languageCode){ - return fileText; - } + public String getDescriptionTemplateVariablesForUpdateMyUin(ResidentTransactionEntity residentTransactionEntity, + String fileText, String languageCode) { + return addAttributeListInPurpose(fileText, residentTransactionEntity.getAttributeList(), languageCode); + } - public String getDescriptionTemplateVariablesForValidateOtp(String eventId, String fileText, String languageCode) { - ResidentTransactionEntity residentTransactionEntity = getEntityFromEventId(eventId); - String purpose = residentTransactionEntity.getPurpose(); - if (purpose != null && !purpose.isEmpty()) { - fileText = fileText.replace(ResidentConstants.DOLLAR + ResidentConstants.CHANNEL, - purpose); - } - return fileText; - } + public String getDescriptionTemplateVariablesForManageMyVid(ResidentTransactionEntity residentTransactionEntity, + String fileText, String languageCode) { + fileText = fileText.replace(ResidentConstants.DOLLAR + ResidentConstants.VID_TYPE, + replaceNullWithEmptyString(residentTransactionEntity.getRefIdType())); + fileText = fileText.replace(ResidentConstants.MASKED_VID, + replaceNullWithEmptyString(residentTransactionEntity.getRefId())); + String requestType = residentTransactionEntity.getRequestTypeCode(); + if (requestType.equalsIgnoreCase(RequestType.GENERATE_VID.name())) { + fileText = fileText.replace(ResidentConstants.DOLLAR + ResidentConstants.ACTION_PERFORMED, GENERATED); + } else if (requestType.equalsIgnoreCase(RequestType.REVOKE_VID.name())) { + fileText = fileText.replace(ResidentConstants.DOLLAR + ResidentConstants.ACTION_PERFORMED, REVOKED); + } + return fileText; + } - public String getDescriptionTemplateVariablesForSecureMyId(String eventId, String fileText, String languageCode){ - ResidentTransactionEntity residentTransactionEntity = getEntityFromEventId(eventId); - String purpose = residentTransactionEntity.getPurpose(); - if (purpose != null && !purpose.isEmpty()) - return purpose; - return fileText; - } + public String getDescriptionTemplateVariablesForVidCardDownload(ResidentTransactionEntity residentTransactionEntity, + String fileText, String languageCode) { + return fileText; + } + + public String getDescriptionTemplateVariablesForValidateOtp(ResidentTransactionEntity residentTransactionEntity, + String fileText, String languageCode) { + String channels = residentTransactionEntity.getPurpose(); + if (channels != null && !channels.isEmpty()) { + fileText = fileText.replace(ResidentConstants.DOLLAR + ResidentConstants.CHANNEL, channels); + } + return fileText; + } - public Tuple2, String> getDefaultTemplateVariables(String eventId, String languageCode, Integer timeZoneOffset){ - return Tuples.of(getCommonTemplateVariables(eventId, languageCode, timeZoneOffset).getT1(), ""); + public String getDescriptionTemplateVariablesForSecureMyId(ResidentTransactionEntity residentTransactionEntity, + String fileText, String languageCode) { + if (residentTransactionEntity.getPurpose() != null && !residentTransactionEntity.getPurpose().isEmpty()) { + List authTypeListFromEntity = List + .of(residentTransactionEntity.getPurpose().split(ResidentConstants.ATTRIBUTE_LIST_DELIMITER)); + return authTypeListFromEntity.stream().map(authType -> { + String fileTextTemplate = fileText; + String templateData = ""; + if (authType.contains(EventStatusSuccess.UNLOCKED.name())) { + templateData = getTemplateValueFromTemplateTypeCodeAndLangCode(languageCode, + getAttributeListTemplateTypeCode(EventStatusSuccess.UNLOCKED.name())); + fileTextTemplate = fileTextTemplate.replace(ResidentConstants.DOLLAR + ResidentConstants.STATUS, + templateData); + } else { + templateData = getTemplateValueFromTemplateTypeCodeAndLangCode(languageCode, + getAttributeListTemplateTypeCode(EventStatusSuccess.LOCKED.name())); + fileTextTemplate = fileTextTemplate.replace(ResidentConstants.DOLLAR + ResidentConstants.STATUS, + templateData); + } + templateData = getTemplateValueFromTemplateTypeCodeAndLangCode(languageCode, + getAttributeListTemplateTypeCode(authType.split(ResidentConstants.COLON)[0].trim())); + fileTextTemplate = fileTextTemplate.replace(ResidentConstants.DOLLAR + ResidentConstants.AUTH_TYPE, + templateData); + return fileTextTemplate; + }).collect(Collectors.joining(ResidentConstants.UI_ATTRIBUTE_DATA_DELIMITER)); + } + return fileText; + } + + public Tuple2, String> getDefaultTemplateVariables(String eventId, String languageCode, Integer timeZoneOffset, String locale){ + return Tuples.of(getCommonTemplateVariables(eventId, languageCode, timeZoneOffset, locale).getT1(), ""); } public String replaceNullWithEmptyString(String input) { @@ -254,338 +326,384 @@ private ResidentTransactionEntity getEntityFromEventId(String eventId) { } } - public String getFeatureName(String eventId){ - Tuple2, ResidentTransactionEntity> tupleResponse = getCommonTemplateVariables(eventId, - this.env.getProperty(ResidentConstants.MANDATORY_LANGUAGE), ResidentConstants.UTC_TIMEZONE_OFFSET); - Map templateVariables = tupleResponse.getT1(); - return templateVariables.get(TemplateVariablesConstants.EVENT_TYPE); - } + public String getFeatureName(String eventId, String locale) { + Tuple2, ResidentTransactionEntity> tupleResponse = getCommonTemplateVariables(eventId, + this.env.getProperty(ResidentConstants.MANDATORY_LANGUAGE), ResidentConstants.UTC_TIMEZONE_OFFSET, null); + Map templateVariables = tupleResponse.getT1(); + return templateVariables.get(TemplateVariablesConstants.EVENT_TYPE); + } - public String getIndividualIdType() throws ApisResourceAccessException { - String individualId= identityServiceImpl.getResidentIndvidualIdFromSession(); - return identityServiceImpl.getIndividualIdType(individualId); - } + public String getIndividualIdType() throws ApisResourceAccessException { + String individualId = identityServiceImpl.getResidentIndvidualIdFromSession(); + return identityServiceImpl.getIndividualIdType(individualId); + } - private String getEventStatusForRequestType(String requestType) { - String eventStatus = ""; - if(EventStatusSuccess.containsStatus(requestType)){ - eventStatus = EventStatus.SUCCESS.getStatus(); - } else if(EventStatusFailure.containsStatus(requestType)){ - eventStatus = EventStatus.FAILED.getStatus(); - } else { - eventStatus = EventStatus.IN_PROGRESS.getStatus(); - } - return eventStatus; - } + public Tuple2, String> getAckTemplateVariablesForCredentialShare(String eventId, + String languageCode, Integer timeZoneOffset, String locale) { + Tuple2, ResidentTransactionEntity> tupleResponse = getCommonTemplateVariables(eventId, + languageCode, timeZoneOffset, locale); + Map templateVariables = tupleResponse.getT1(); + ResidentTransactionEntity residentTransactionEntity = tupleResponse.getT2(); + templateVariables.put(TemplateVariablesConstants.PARTNER_NAME, + residentTransactionEntity.getRequestedEntityName()); + templateVariables.put(TemplateVariablesConstants.PARTNER_LOGO, + getPartnerLogo(residentTransactionEntity.getRequestedEntityId())); + return Tuples.of(templateVariables, + Objects.requireNonNull(this.env.getProperty(ResidentConstants.ACK_SHARE_CREDENTIAL_TEMPLATE_PROPERTY))); + } - public Tuple2, String> getAckTemplateVariablesForCredentialShare(String eventId, String languageCode, Integer timeZoneOffset) { - Tuple2, ResidentTransactionEntity> tupleResponse = getCommonTemplateVariables(eventId, languageCode, timeZoneOffset); - Map templateVariables = tupleResponse.getT1(); - ResidentTransactionEntity residentTransactionEntity = tupleResponse.getT2(); - templateVariables.put(TemplateVariablesConstants.PARTNER_NAME, residentTransactionEntity.getRequestedEntityName()); - templateVariables.put(TemplateVariablesConstants.PARTNER_LOGO, getPartnerLogo(residentTransactionEntity.getRequestedEntityId())); - return Tuples.of(templateVariables, Objects.requireNonNull( - this.env.getProperty(ResidentConstants.ACK_SHARE_CREDENTIAL_TEMPLATE_PROPERTY))); - } + public Tuple2, String> getAckTemplateVariablesForAuthenticationRequest(String eventId, + String languageCode, Integer timeZoneOffset, String locale) { + Tuple2, ResidentTransactionEntity> tupleResponse = getCommonTemplateVariables(eventId, + languageCode, timeZoneOffset, locale); + Map templateVariables = tupleResponse.getT1(); + ResidentTransactionEntity residentTransactionEntity = tupleResponse.getT2(); + templateVariables.put(TemplateVariablesConstants.PARTNER_NAME, + residentTransactionEntity.getRequestedEntityName()); + templateVariables.put(TemplateVariablesConstants.PARTNER_LOGO, + getPartnerLogo(residentTransactionEntity.getRequestedEntityId())); + return Tuples.of(templateVariables, Objects + .requireNonNull(this.env.getProperty(ResidentConstants.ACK_AUTHENTICATION_REQUEST_TEMPLATE_PROPERTY))); + } - public Tuple2, String> getAckTemplateVariablesForAuthenticationRequest(String eventId, String languageCode, Integer timeZoneOffset) { - Tuple2, ResidentTransactionEntity> tupleResponse = getCommonTemplateVariables(eventId, languageCode, timeZoneOffset); - Map templateVariables = tupleResponse.getT1(); - ResidentTransactionEntity residentTransactionEntity = tupleResponse.getT2(); - templateVariables.put(TemplateVariablesConstants.PARTNER_NAME, residentTransactionEntity.getRequestedEntityName()); - templateVariables.put(TemplateVariablesConstants.PARTNER_LOGO, getPartnerLogo(residentTransactionEntity.getRequestedEntityId())); - return Tuples.of(templateVariables, Objects.requireNonNull( - this.env.getProperty(ResidentConstants.ACK_AUTHENTICATION_REQUEST_TEMPLATE_PROPERTY))); - } - - public Tuple2, String> getAckTemplateVariablesForDownloadPersonalizedCard(String eventId, String languageCode, Integer timeZoneOffset) { - Tuple2, ResidentTransactionEntity> tupleResponse = getCommonTemplateVariables(eventId, languageCode, timeZoneOffset); - Map templateVariables = tupleResponse.getT1(); - ResidentTransactionEntity residentTransactionEntity = tupleResponse.getT2(); - templateVariables.put(TemplateVariablesConstants.PURPOSE, addAttributeInPurpose(getPurposeFromResidentTransactionEntityLangCode( - residentTransactionEntity, languageCode), getEntityFromEventId(eventId).getPurpose(), languageCode)); - return Tuples.of(templateVariables, Objects.requireNonNull( - this.env.getProperty(ResidentConstants.ACK_DOWNLOAD_PERSONALIZED_CARD_TEMPLATE_PROPERTY))); - } + public Tuple2, String> getAckTemplateVariablesForDownloadPersonalizedCard(String eventId, + String languageCode, Integer timeZoneOffset, String locale) { + Tuple2, ResidentTransactionEntity> tupleResponse = getCommonTemplateVariables(eventId, + languageCode, timeZoneOffset, locale); + Map templateVariables = tupleResponse.getT1(); + ResidentTransactionEntity residentTransactionEntity = tupleResponse.getT2(); + templateVariables.put(TemplateVariablesConstants.PURPOSE, + getPurposeFromResidentTransactionEntityLangCode(residentTransactionEntity, languageCode)); + return Tuples.of(templateVariables, Objects.requireNonNull( + this.env.getProperty(ResidentConstants.ACK_DOWNLOAD_PERSONALIZED_CARD_TEMPLATE_PROPERTY))); + } - /** - * This method will replace attribute placeholder in template and add attribute list into it. - * @param fileText This contains value of template. - * @param purpose This contains purpose of request type stored in template. - * @param languageCode This contains logged-in language code. - * @return purpose after adding attributes. - */ - private String addAttributeInPurpose(String fileText, String purpose, - String languageCode) { - if(fileText!=null && - fileText.contains(ResidentConstants.ATTRIBUTES)){ - fileText = fileText.replace( - ResidentConstants.DOLLAR+ResidentConstants.ATTRIBUTES, getAttributesDisplayText(purpose, - languageCode) - ); - } - return fileText; - } + /** + * This method will replace attribute placeholder in template and add attribute + * list into it. + * + * @param fileText This contains value of template. + * @param attributes This contains attributes of request type stored in + * template. + * @param languageCode This contains logged-in language code. + * @return purpose after adding attributes. + */ + private String addAttributeListInPurpose(String fileText, String attributes, String languageCode) { + if (fileText != null && fileText.contains(ResidentConstants.ATTRIBUTES)) { + fileText = fileText.replace(ResidentConstants.DOLLAR + ResidentConstants.ATTRIBUTES, + getAttributesDisplayText(attributes, languageCode, RequestType.DEFAULT)); + } + return fileText; + } - public Tuple2, String> getAckTemplateVariablesForOrderPhysicalCard(String eventId, String languageCode, Integer timeZoneOffset) { - Tuple2, ResidentTransactionEntity> tupleResponse = getCommonTemplateVariables(eventId, languageCode, timeZoneOffset); - Map templateVariables = tupleResponse.getT1(); - ResidentTransactionEntity residentTransactionEntity = tupleResponse.getT2(); - templateVariables.put(TemplateVariablesConstants.PURPOSE, getPurposeFromResidentTransactionEntityLangCode( - residentTransactionEntity, languageCode)); - templateVariables.put(TemplateVariablesConstants.TRACKING_ID, residentTransactionEntity.getTrackingId()); - templateVariables.put(TemplateVariablesConstants.ORDER_TRACKING_LINK, residentTransactionEntity.getReferenceLink()); - templateVariables.put(TemplateVariablesConstants.PARTNER_NAME, residentTransactionEntity.getRequestedEntityName()); - templateVariables.put(TemplateVariablesConstants.PARTNER_LOGO, getPartnerLogo(residentTransactionEntity.getRequestedEntityId())); - templateVariables.put(TemplateVariablesConstants.PAYMENT_STATUS, getPaymentStatus(residentTransactionEntity.getStatusCode())); - templateVariables.put(TemplateVariablesConstants.DOWNLOAD_CARD_LINK, residentTransactionEntity.getReferenceLink()); - return Tuples.of(templateVariables, Objects.requireNonNull( - this.env.getProperty(ResidentConstants.ACK_ORDER_PHYSICAL_CARD_TEMPLATE_PROPERTY))); - } - - public Tuple2, String> getAckTemplateVariablesForGetMyId(String eventId, String languageCode, Integer timeZoneOffset) { - Tuple2, ResidentTransactionEntity> tupleResponse = getCommonTemplateVariables(eventId, languageCode, timeZoneOffset); - Map templateVariables = tupleResponse.getT1(); - ResidentTransactionEntity residentTransactionEntity = tupleResponse.getT2(); - templateVariables.put(TemplateVariablesConstants.PURPOSE, getPurposeFromResidentTransactionEntityLangCode( - residentTransactionEntity, languageCode)); - templateVariables.remove(TemplateVariablesConstants.ATTRIBUTE_LIST); - return Tuples.of(templateVariables, Objects.requireNonNull( - this.env.getProperty(ResidentConstants.ACK_GET_MY_ID_TEMPLATE_PROPERTY))); - } + public Tuple2, String> getAckTemplateVariablesForOrderPhysicalCard(String eventId, + String languageCode, Integer timeZoneOffset, String locale) { + Tuple2, ResidentTransactionEntity> tupleResponse = getCommonTemplateVariables(eventId, + languageCode, timeZoneOffset, locale); + Map templateVariables = tupleResponse.getT1(); + ResidentTransactionEntity residentTransactionEntity = tupleResponse.getT2(); + templateVariables.put(TemplateVariablesConstants.PURPOSE, + getPurposeFromResidentTransactionEntityLangCode(residentTransactionEntity, languageCode)); + templateVariables.put(TemplateVariablesConstants.TRACKING_ID, residentTransactionEntity.getTrackingId()); + templateVariables.put(TemplateVariablesConstants.ORDER_TRACKING_LINK, + residentTransactionEntity.getReferenceLink()); + templateVariables.put(TemplateVariablesConstants.PARTNER_NAME, + residentTransactionEntity.getRequestedEntityName()); + templateVariables.put(TemplateVariablesConstants.PARTNER_LOGO, + getPartnerLogo(residentTransactionEntity.getRequestedEntityId())); + templateVariables.put(TemplateVariablesConstants.PAYMENT_STATUS, + getPaymentStatus(residentTransactionEntity.getStatusCode())); + templateVariables.put(TemplateVariablesConstants.DOWNLOAD_CARD_LINK, + residentTransactionEntity.getReferenceLink()); + return Tuples.of(templateVariables, Objects + .requireNonNull(this.env.getProperty(ResidentConstants.ACK_ORDER_PHYSICAL_CARD_TEMPLATE_PROPERTY))); + } + + public Tuple2, String> getAckTemplateVariablesForGetMyId(String eventId, String languageCode, + Integer timeZoneOffset, String locale) { + Tuple2, ResidentTransactionEntity> tupleResponse = getCommonTemplateVariables(eventId, + languageCode, timeZoneOffset, locale); + Map templateVariables = tupleResponse.getT1(); + ResidentTransactionEntity residentTransactionEntity = tupleResponse.getT2(); + templateVariables.put(TemplateVariablesConstants.PURPOSE, + getPurposeFromResidentTransactionEntityLangCode(residentTransactionEntity, languageCode)); + templateVariables.remove(TemplateVariablesConstants.ATTRIBUTE_LIST); + return Tuples.of(templateVariables, + Objects.requireNonNull(this.env.getProperty(ResidentConstants.ACK_GET_MY_ID_TEMPLATE_PROPERTY))); + } + + public Tuple2, String> getAckTemplateVariablesForBookAnAppointment(String eventId, + String languageCode, Integer timeZoneOffset, String locale) { + return Tuples.of(Collections.emptyMap(), ""); + } - public Tuple2, String> getAckTemplateVariablesForBookAnAppointment(String eventId, String languageCode, Integer timeZoneOffset) { - return Tuples.of(Collections.emptyMap(), ""); - } - - public Tuple2, String> getAckTemplateVariablesForUpdateMyUin(String eventId, String languageCode, Integer timeZoneOffset) { - Tuple2, ResidentTransactionEntity> tupleResponse = getCommonTemplateVariables(eventId, languageCode, timeZoneOffset); - Map templateVariables = tupleResponse.getT1(); - ResidentTransactionEntity residentTransactionEntity = tupleResponse.getT2(); - templateVariables.put(TemplateVariablesConstants.PURPOSE, getPurposeFromResidentTransactionEntityLangCode( - residentTransactionEntity, languageCode)); - templateVariables.put(TemplateVariablesConstants.DOWNLOAD_LINK, + public Tuple2, String> getAckTemplateVariablesForUpdateMyUin(String eventId, + String languageCode, Integer timeZoneOffset, String locale) { + Tuple2, ResidentTransactionEntity> tupleResponse = getCommonTemplateVariables(eventId, + languageCode, timeZoneOffset, locale); + Map templateVariables = tupleResponse.getT1(); + ResidentTransactionEntity residentTransactionEntity = tupleResponse.getT2(); + templateVariables.put(TemplateVariablesConstants.PURPOSE, + getPurposeFromResidentTransactionEntityLangCode(residentTransactionEntity, languageCode)); + templateVariables.put(TemplateVariablesConstants.DOWNLOAD_LINK, (!residentTransactionEntity.getStatusCode().equals(EventStatusSuccess.CARD_DOWNLOADED.name()) && !residentTransactionEntity.getStatusCode().equals(EventStatusFailure.FAILED.name())) ? utility.createDownloadCardLinkFromEventId(residentTransactionEntity) : ResidentConstants.NOT_AVAILABLE); - return Tuples.of(templateVariables, Objects.requireNonNull( - this.env.getProperty(ResidentConstants.ACK_UPDATE_MY_UIN_TEMPLATE_PROPERTY))); - } + return Tuples.of(templateVariables, + Objects.requireNonNull(this.env.getProperty(ResidentConstants.ACK_UPDATE_MY_UIN_TEMPLATE_PROPERTY))); + } - public Tuple2, String> getAckTemplateVariablesForGenerateVid(String eventId, String languageCode, Integer timeZoneOffset) { - Tuple2, ResidentTransactionEntity> tupleResponse = getCommonTemplateVariables(eventId, languageCode, timeZoneOffset); - Map templateVariables = tupleResponse.getT1(); - ResidentTransactionEntity residentTransactionEntity = tupleResponse.getT2(); - templateVariables.put(TemplateVariablesConstants.PURPOSE, getPurposeFromResidentTransactionEntityLangCode( - residentTransactionEntity, languageCode)); - templateVariables.remove(TemplateVariablesConstants.ATTRIBUTE_LIST); - templateVariables.put(TemplateVariablesConstants.VID_TYPE, residentTransactionEntity.getRefIdType()); - templateVariables.put(TemplateVariablesConstants.VID, residentTransactionEntity.getRefId()); - return Tuples.of(templateVariables, Objects.requireNonNull( - this.env.getProperty(ResidentConstants.ACK_MANAGE_MY_VID_TEMPLATE_PROPERTY))); - } + public Tuple2, String> getAckTemplateVariablesForGenerateVid(String eventId, + String languageCode, Integer timeZoneOffset, String locale) { + Tuple2, ResidentTransactionEntity> tupleResponse = getCommonTemplateVariables(eventId, + languageCode, timeZoneOffset, locale); + Map templateVariables = tupleResponse.getT1(); + ResidentTransactionEntity residentTransactionEntity = tupleResponse.getT2(); + templateVariables.put(TemplateVariablesConstants.PURPOSE, + getPurposeFromResidentTransactionEntityLangCode(residentTransactionEntity, languageCode)); + templateVariables.remove(TemplateVariablesConstants.ATTRIBUTE_LIST); + templateVariables.put(TemplateVariablesConstants.VID_TYPE, residentTransactionEntity.getRefIdType()); + templateVariables.put(TemplateVariablesConstants.VID, residentTransactionEntity.getRefId()); + return Tuples.of(templateVariables, + Objects.requireNonNull(this.env.getProperty(ResidentConstants.ACK_MANAGE_MY_VID_TEMPLATE_PROPERTY))); + } - public String getPurposeFromResidentTransactionEntityLangCode(ResidentTransactionEntity residentTransactionEntity, String languageCode){ - String purpose = ""; - try { - purpose = residentService.getSummaryForLangCode(languageCode, residentService.getEventStatusCode( - residentTransactionEntity.getStatusCode()), - RequestType.valueOf(residentTransactionEntity.getRequestTypeCode().trim()), residentTransactionEntity.getEventId()); - } catch (ResidentServiceCheckedException e) { - return ""; - } - return purpose; - } + public String getPurposeFromResidentTransactionEntityLangCode(ResidentTransactionEntity residentTransactionEntity, + String languageCode) { + String purpose = ""; + try { + purpose = residentService.getDescriptionForLangCode(residentTransactionEntity, languageCode, + residentService.getEventStatusCode(residentTransactionEntity.getStatusCode()), + RequestType.getRequestTypeFromString(residentTransactionEntity.getRequestTypeCode())); + } catch (ResidentServiceCheckedException e) { + return ""; + } + return purpose; + } - public Tuple2, String> getAckTemplateVariablesForRevokeVid(String eventId, String languageCode, Integer timeZoneOffset) { - Tuple2, ResidentTransactionEntity> tupleResponse = getCommonTemplateVariables(eventId, languageCode, timeZoneOffset); - Map templateVariables = tupleResponse.getT1(); - ResidentTransactionEntity residentTransactionEntity = tupleResponse.getT2(); - templateVariables.put(TemplateVariablesConstants.PURPOSE, getPurposeFromResidentTransactionEntityLangCode( - residentTransactionEntity, languageCode)); - templateVariables.put(TemplateVariablesConstants.VID_TYPE, residentTransactionEntity.getRefIdType()); - templateVariables.put(TemplateVariablesConstants.VID, residentTransactionEntity.getRefId()); - return Tuples.of(templateVariables, Objects.requireNonNull( - this.env.getProperty(ResidentConstants.ACK_MANAGE_MY_VID_TEMPLATE_PROPERTY))); - } + public String getSummaryFromResidentTransactionEntityLangCode(ResidentTransactionEntity residentTransactionEntity, + String languageCode, String statusCode, RequestType requestType) { + try { + return residentService.getSummaryForLangCode(residentTransactionEntity, languageCode, statusCode, + requestType); + } catch (ResidentServiceCheckedException e) { + return requestType.name(); + } + } - public Map getAckTemplateVariablesForVerifyPhoneEmail(String eventId, Integer timeZoneOffset) { - return getCommonTemplateVariables(eventId, "", timeZoneOffset).getT1(); - } + public Tuple2, String> getAckTemplateVariablesForRevokeVid(String eventId, String languageCode, + Integer timeZoneOffset, String locale) { + Tuple2, ResidentTransactionEntity> tupleResponse = getCommonTemplateVariables(eventId, + languageCode, timeZoneOffset, locale); + Map templateVariables = tupleResponse.getT1(); + ResidentTransactionEntity residentTransactionEntity = tupleResponse.getT2(); + templateVariables.put(TemplateVariablesConstants.PURPOSE, + getPurposeFromResidentTransactionEntityLangCode(residentTransactionEntity, languageCode)); + templateVariables.put(TemplateVariablesConstants.VID_TYPE, residentTransactionEntity.getRefIdType()); + templateVariables.put(TemplateVariablesConstants.VID, residentTransactionEntity.getRefId()); + return Tuples.of(templateVariables, + Objects.requireNonNull(this.env.getProperty(ResidentConstants.ACK_MANAGE_MY_VID_TEMPLATE_PROPERTY))); + } + + public Map getAckTemplateVariablesForVerifyPhoneEmail(String eventId, Integer timeZoneOffset, String locale) { + return getCommonTemplateVariables(eventId, "", timeZoneOffset, locale).getT1(); + } - public Tuple2, String> getAckTemplateVariablesForAuthTypeLockUnlock(String eventId, String languageCode, Integer timeZoneOffset) { - Tuple2, ResidentTransactionEntity> tupleResponse = getCommonTemplateVariables(eventId, languageCode, timeZoneOffset); - Map templateVariables = tupleResponse.getT1(); - templateVariables.remove(TemplateVariablesConstants.ATTRIBUTE_LIST); - templateVariables.put(ResidentConstants.AUTH_TYPE, templateVariables.get(TemplateVariablesConstants.PURPOSE)); - return Tuples.of(templateVariables, Objects.requireNonNull( - this.env.getProperty(ResidentConstants.ACK_AUTH_TYPE_LOCK_UNLOCK_TEMPLATE_PROPERTY))); - } - - public Tuple2, String> getAckTemplateVariablesForVidCardDownload(String eventId, String languageCode, Integer timeZoneOffset) { - Tuple2, ResidentTransactionEntity> tupleResponse = getCommonTemplateVariables(eventId, languageCode, timeZoneOffset); - Map templateVariables = tupleResponse.getT1(); - ResidentTransactionEntity residentTransactionEntity = tupleResponse.getT2(); - templateVariables.put(TemplateVariablesConstants.PURPOSE, getPurposeFromResidentTransactionEntityLangCode( - residentTransactionEntity, languageCode)); - templateVariables.put(TemplateVariablesConstants.DOWNLOAD_LINK, + public Tuple2, String> getAckTemplateVariablesForAuthTypeLockUnlock(String eventId, + String languageCode, Integer timeZoneOffset, String locale) { + Tuple2, ResidentTransactionEntity> tupleResponse = getCommonTemplateVariables(eventId, + languageCode, timeZoneOffset, locale); + Map templateVariables = tupleResponse.getT1(); + templateVariables.remove(TemplateVariablesConstants.ATTRIBUTE_LIST); + templateVariables.put(ResidentConstants.AUTH_TYPE, templateVariables.get(TemplateVariablesConstants.PURPOSE)); + return Tuples.of(templateVariables, Objects + .requireNonNull(this.env.getProperty(ResidentConstants.ACK_AUTH_TYPE_LOCK_UNLOCK_TEMPLATE_PROPERTY))); + } + + public Tuple2, String> getAckTemplateVariablesForVidCardDownload(String eventId, + String languageCode, Integer timeZoneOffset, String locale) { + Tuple2, ResidentTransactionEntity> tupleResponse = getCommonTemplateVariables(eventId, + languageCode, timeZoneOffset, locale); + Map templateVariables = tupleResponse.getT1(); + ResidentTransactionEntity residentTransactionEntity = tupleResponse.getT2(); + templateVariables.put(TemplateVariablesConstants.PURPOSE, + getPurposeFromResidentTransactionEntityLangCode(residentTransactionEntity, languageCode)); + templateVariables.put(TemplateVariablesConstants.DOWNLOAD_LINK, (!residentTransactionEntity.getStatusCode().equals(EventStatusSuccess.CARD_DOWNLOADED.name()) && !residentTransactionEntity.getStatusCode().equals(EventStatusFailure.FAILED.name())) ? utility.createDownloadCardLinkFromEventId(residentTransactionEntity) : ResidentConstants.NOT_AVAILABLE); - templateVariables.remove(TemplateVariablesConstants.ATTRIBUTE_LIST); - return Tuples.of(templateVariables, Objects.requireNonNull( - this.env.getProperty(ResidentConstants.ACK_VID_CARD_DOWNLOAD_TEMPLATE_PROPERTY))); - } - - public Tuple2, String> getAckTemplateVariablesForSendOtp(String eventId, String languageCode, Integer timeZoneOffset) { - return Tuples.of(getCommonTemplateVariables(eventId, languageCode, timeZoneOffset).getT1(), ""); - } - - public Tuple2, String> getAckTemplateVariablesForValidateOtp(String eventId, String languageCode, Integer timeZoneOffset) { - Tuple2, ResidentTransactionEntity> tupleResponse = getCommonTemplateVariables(eventId, languageCode, timeZoneOffset); - Map templateVariables = tupleResponse.getT1(); - ResidentTransactionEntity residentTransactionEntity = tupleResponse.getT2(); - templateVariables.put(ResidentConstants.CHANNEL, replaceNullWithEmptyString( - residentTransactionEntity.getAttributeList())); - return Tuples.of(templateVariables, Objects.requireNonNull( - this.env.getProperty(ResidentConstants.ACK_VERIFY_PHONE_EMAIL_TEMPLATE_PROPERTY))); - } - - public Map getNotificationCommonTemplateVariables(NotificationTemplateVariableDTO dto) { - Map templateVariables = new HashMap<>(); - templateVariables.put(TemplateVariablesConstants.EVENT_ID, dto.getEventId()); - templateVariables.put(TemplateVariablesConstants.NAME, getName(dto.getLangCode(), dto.getEventId())); - templateVariables.put(TemplateVariablesConstants.EVENT_DETAILS, dto.getRequestType().getName()); - templateVariables.put(TemplateVariablesConstants.DATE, getDate()); - templateVariables.put(TemplateVariablesConstants.TIME, getTime()); - templateVariables.put(TemplateVariablesConstants.STATUS, dto.getTemplateType().getType()); - templateVariables.put(TemplateVariablesConstants.TRACK_SERVICE_REQUEST_LINK, utility.createTrackServiceRequestLink(dto.getEventId())); - return templateVariables; - } - - public Map getNotificationSendOtpVariables(NotificationTemplateVariableDTO dto){ - Map templateVariables = getNotificationCommonTemplateVariables(dto); - templateVariables.put(TemplateVariablesConstants.OTP, dto.getOtp()); - return templateVariables; - } - - private String getTime() { - return DateUtils.getUTCCurrentDateTimeString(templateTimePattern); - } - - private String getDate() { - return DateUtils.getUTCCurrentDateTimeString(templateDatePattern); - } - - private String getName(String language, String eventId) { - String name = ""; - String individualId = ""; - try { + templateVariables.remove(TemplateVariablesConstants.ATTRIBUTE_LIST); + return Tuples.of(templateVariables, Objects + .requireNonNull(this.env.getProperty(ResidentConstants.ACK_VID_CARD_DOWNLOAD_TEMPLATE_PROPERTY))); + } + + public Tuple2, String> getAckTemplateVariablesForSendOtp(String eventId, String languageCode, + Integer timeZoneOffset, String locale) { + return Tuples.of(getCommonTemplateVariables(eventId, languageCode, timeZoneOffset, locale).getT1(), ""); + } + + public Tuple2, String> getAckTemplateVariablesForValidateOtp(String eventId, + String languageCode, Integer timeZoneOffset, String locale) { + Tuple2, ResidentTransactionEntity> tupleResponse = getCommonTemplateVariables(eventId, + languageCode, timeZoneOffset, locale); + Map templateVariables = tupleResponse.getT1(); + ResidentTransactionEntity residentTransactionEntity = tupleResponse.getT2(); + templateVariables.put(ResidentConstants.CHANNEL, + replaceNullWithEmptyString(residentTransactionEntity.getAttributeList())); + return Tuples.of(templateVariables, Objects + .requireNonNull(this.env.getProperty(ResidentConstants.ACK_VERIFY_PHONE_EMAIL_TEMPLATE_PROPERTY))); + } + + public Map getNotificationCommonTemplateVariables(NotificationTemplateVariableDTO dto) { + Map templateVariables = new HashMap<>(); + templateVariables.put(TemplateVariablesConstants.EVENT_ID, dto.getEventId()); + templateVariables.put(TemplateVariablesConstants.NAME, getName(dto.getLangCode(), dto.getEventId())); + templateVariables.put(TemplateVariablesConstants.EVENT_DETAILS, dto.getRequestType().getName()); + templateVariables.put(TemplateVariablesConstants.DATE, getDate()); + templateVariables.put(TemplateVariablesConstants.TIME, getTime()); + templateVariables.put(TemplateVariablesConstants.STATUS, dto.getTemplateType().getType()); + templateVariables.put(TemplateVariablesConstants.TRACK_SERVICE_REQUEST_LINK, + utility.createTrackServiceRequestLink(dto.getEventId())); + return templateVariables; + } + + public Map getNotificationSendOtpVariables(NotificationTemplateVariableDTO dto) { + Map templateVariables = getNotificationCommonTemplateVariables(dto); + templateVariables.put(TemplateVariablesConstants.OTP, dto.getOtp()); + return templateVariables; + } + + private String getTime() { + return DateUtils.getUTCCurrentDateTimeString(templateTimePattern); + } + + private String getDate() { + return DateUtils.getUTCCurrentDateTimeString(templateDatePattern); + } + + private String getName(String language, String eventId) { + String name = ""; + String individualId = ""; + try { if (Utility.isSecureSession()) { individualId = identityServiceImpl.getResidentIndvidualIdFromSession(); } else { individualId = getEntityFromEventId(eventId).getIndividualId(); } - + if (individualId != null && !individualId.isEmpty()) { - Map idMap = identityServiceImpl.getIdentityAttributes(individualId, UISchemaTypes.UPDATE_DEMOGRAPHICS.getFileIdentifier()); - name=identityServiceImpl.getNameForNotification(idMap, language); + Map idMap = identityServiceImpl.getIdentityAttributes(individualId, + UISchemaTypes.UPDATE_DEMOGRAPHICS.getFileIdentifier()); + name = identityServiceImpl.getNameForNotification(idMap, language); } - } catch (ApisResourceAccessException | ResidentServiceCheckedException | IOException | ResidentServiceException e) { - logger.error(String.format("Error occured while getting individualId: %s : %s : %s", e.getClass().getSimpleName(), e.getMessage(), - (e.getCause() != null ? "rootcause: " + e.getCause().getMessage() : ""))); - } - return name; - } - - public Map getNotificationTemplateVariablesForGenerateOrRevokeVid(NotificationTemplateVariableDTO dto) { - Map templateVariables = getNotificationCommonTemplateVariables(dto); - return templateVariables; - } - - public Map getNotificationTemplateVariablesForAuthTypeLockUnlock(NotificationTemplateVariableDTO dto) { - Map templateVariables = getNotificationCommonTemplateVariables(dto); - return templateVariables; - } - - public Map getNotificationTemplateVariablesForUpdateMyUin(NotificationTemplateVariableDTO dto) { - Map templateVariables = getNotificationCommonTemplateVariables(dto); - if(TemplateType.SUCCESS.getType().equals(dto.getTemplateType().getType())) { - templateVariables.put(TemplateVariablesConstants.DOWNLOAD_LINK, utility.createTrackServiceRequestLink(dto.getEventId())); - } - return templateVariables; - } - - public Map getNotificationTemplateVariablesForVerifyPhoneEmail(NotificationTemplateVariableDTO dto) { - Map templateVariables = getNotificationCommonTemplateVariables(dto); - return templateVariables; - } - - public Map getNotificationTemplateVariablesForGetMyId(NotificationTemplateVariableDTO dto) { - Map templateVariables = getNotificationCommonTemplateVariables(dto); - return templateVariables; - } - - public Map getNotificationTemplateVariablesForDownloadPersonalizedCard(NotificationTemplateVariableDTO dto) { - Map templateVariables = getNotificationCommonTemplateVariables(dto); - if(TemplateType.SUCCESS.getType().equals(dto.getTemplateType().getType())) { - templateVariables.put(TemplateVariablesConstants.DOWNLOAD_LINK, utility.createTrackServiceRequestLink(dto.getEventId())); - } - return templateVariables; - } - - public Map getNotificationTemplateVariablesForOrderPhysicalCard(NotificationTemplateVariableDTO dto) { - Map templateVariables = getNotificationCommonTemplateVariables(dto); - if(TemplateType.SUCCESS.getType().equals(dto.getTemplateType().getType())) { - templateVariables.put(TemplateVariablesConstants.DOWNLOAD_LINK, utility.createTrackServiceRequestLink(dto.getEventId())); - } - return templateVariables; - } - - public Map getNotificationTemplateVariablesForShareCredentialWithPartner(NotificationTemplateVariableDTO dto) { - Map templateVariables = getNotificationCommonTemplateVariables(dto); - return templateVariables; - } - - public Map getNotificationTemplateVariablesForVidCardDownload(NotificationTemplateVariableDTO dto) { - Map templateVariables = getNotificationCommonTemplateVariables(dto); - return templateVariables; - } - - public String getEmailSubjectTemplateTypeCode(RequestType requestType, TemplateType templateType) { - String emailSubjectTemplateCodeProperty = requestType.getEmailSubjectTemplateCodeProperty(templateType); - return getTemplateTypeCode(emailSubjectTemplateCodeProperty); - } - - public String getEmailContentTemplateTypeCode(RequestType requestType, TemplateType templateType) { - String emailContentTemplateCodeProperty = requestType.getEmailContentTemplateCodeProperty(templateType); - return getTemplateTypeCode(emailContentTemplateCodeProperty); - } - - public String getSmsTemplateTypeCode(RequestType requestType, TemplateType templateType) { - String smsTemplateCodeProperty = requestType.getSmsTemplateCodeProperty(templateType); - return getTemplateTypeCode(smsTemplateCodeProperty); - } - - public String getBellIconTemplateTypeCode(RequestType requestType, TemplateType templateType) { - String bellIconTemplateCodeProperty = requestType.getBellIconTemplateCodeProperty(templateType); - return getTemplateTypeCode(bellIconTemplateCodeProperty); - } - - public String getPurposeTemplateTypeCode(RequestType requestType, TemplateType templateType) { - String purposeTemplateCodeProperty = requestType.getPurposeTemplateCodeProperty(templateType); - return getTemplateTypeCode(purposeTemplateCodeProperty); - } - - public String getSummaryTemplateTypeCode(RequestType requestType, TemplateType templateType) { - String summaryTemplateCodeProperty = requestType.getSummaryTemplateCodeProperty(templateType); - return getTemplateTypeCode(summaryTemplateCodeProperty); - } - - private String getTemplateTypeCode(String templateCodeProperty) { - return env.getProperty(templateCodeProperty); + } catch (ApisResourceAccessException | ResidentServiceCheckedException | IOException + | ResidentServiceException e) { + logger.error(String.format("Error occured while getting individualId: %s : %s : %s", + e.getClass().getSimpleName(), e.getMessage(), + (e.getCause() != null ? "rootcause: " + e.getCause().getMessage() : ""))); + } + return name; + } + + public Map getNotificationTemplateVariablesForGenerateOrRevokeVid( + NotificationTemplateVariableDTO dto) { + Map templateVariables = getNotificationCommonTemplateVariables(dto); + return templateVariables; + } + + public Map getNotificationTemplateVariablesForAuthTypeLockUnlock( + NotificationTemplateVariableDTO dto) { + Map templateVariables = getNotificationCommonTemplateVariables(dto); + return templateVariables; + } + + public Map getNotificationTemplateVariablesForUpdateMyUin(NotificationTemplateVariableDTO dto) { + Map templateVariables = getNotificationCommonTemplateVariables(dto); + return templateVariables; + } + + public Map getNotificationTemplateVariablesForVerifyPhoneEmail( + NotificationTemplateVariableDTO dto) { + Map templateVariables = getNotificationCommonTemplateVariables(dto); + return templateVariables; + } + + public Map getNotificationTemplateVariablesForGetMyId(NotificationTemplateVariableDTO dto) { + Map templateVariables = getNotificationCommonTemplateVariables(dto); + return templateVariables; + } + + public Map getNotificationTemplateVariablesForDownloadPersonalizedCard( + NotificationTemplateVariableDTO dto) { + Map templateVariables = getNotificationCommonTemplateVariables(dto); + return templateVariables; + } + + public Map getNotificationTemplateVariablesForOrderPhysicalCard( + NotificationTemplateVariableDTO dto) { + Map templateVariables = getNotificationCommonTemplateVariables(dto); + return templateVariables; + } + + public Map getNotificationTemplateVariablesForShareCredentialWithPartner( + NotificationTemplateVariableDTO dto) { + Map templateVariables = getNotificationCommonTemplateVariables(dto); + if (TemplateType.SUCCESS.getType().equals(dto.getTemplateType().getType())) { + templateVariables.put(TemplateVariablesConstants.PARTNER_ID, + getEntityFromEventId(dto.getEventId()).getRequestedEntityId()); + } + return templateVariables; + } + + public Map getNotificationTemplateVariablesForVidCardDownload(NotificationTemplateVariableDTO dto) { + Map templateVariables = getNotificationCommonTemplateVariables(dto); + return templateVariables; + } + + public String getEmailSubjectTemplateTypeCode(RequestType requestType, TemplateType templateType) { + String emailSubjectTemplateCodeProperty = requestType.getEmailSubjectTemplateCodeProperty(templateType); + return getTemplateTypeCode(emailSubjectTemplateCodeProperty); + } + + public String getEmailContentTemplateTypeCode(RequestType requestType, TemplateType templateType) { + String emailContentTemplateCodeProperty = requestType.getEmailContentTemplateCodeProperty(templateType); + return getTemplateTypeCode(emailContentTemplateCodeProperty); + } + + public String getSmsTemplateTypeCode(RequestType requestType, TemplateType templateType) { + String smsTemplateCodeProperty = requestType.getSmsTemplateCodeProperty(templateType); + return getTemplateTypeCode(smsTemplateCodeProperty); + } + + public String getBellIconTemplateTypeCode(RequestType requestType, TemplateType templateType) { + String bellIconTemplateCodeProperty = requestType.getBellIconTemplateCodeProperty(templateType); + return getTemplateTypeCode(bellIconTemplateCodeProperty); + } + + public String getPurposeTemplateTypeCode(RequestType requestType, TemplateType templateType) { + String purposeTemplateCodeProperty = requestType.getPurposeTemplateCodeProperty(templateType); + return getTemplateTypeCode(purposeTemplateCodeProperty); + } + + public String getSummaryTemplateTypeCode(RequestType requestType, TemplateType templateType) { + String summaryTemplateCodeProperty = requestType.getSummaryTemplateCodeProperty(templateType); + return getTemplateTypeCode(summaryTemplateCodeProperty); + } + + public String getAttributeListTemplateTypeCode(String attributeName) { + String templateTypeCode = getTemplateTypeCode( + String.format(RESIDENT_TEMPLATE_PROPERTY_ATTRIBUTE_LIST, attributeName)); + if (templateTypeCode != null && !templateTypeCode.isEmpty()) { + return templateTypeCode; + } else { + return getTemplateTypeCode(String.format(RESIDENT_TEMPLATE_PROPERTY_ATTRIBUTE_LIST, DEFAULT)); + } + } + + private String getTemplateTypeCode(String templateCodeProperty) { + return env.getProperty(templateCodeProperty); } private String getPaymentStatus(String statusCode) { @@ -597,14 +715,14 @@ private String getPaymentStatus(String statusCode) { } private String getPartnerLogo(String partnerId) { - Map partnerDetail = new HashMap<>(); - try { - partnerDetail = proxyPartnerManagementServiceImpl.getPartnerDetailFromPartnerId(partnerId); - }catch (Exception exception){ - logger.error(ResidentErrorCode.PARTNER_SERVICE_EXCEPTION.getErrorCode(), exception); - return ""; - } - return (String) partnerDetail.get(LOGO_URL); + Map partnerDetail = new HashMap<>(); + try { + partnerDetail = proxyPartnerManagementServiceImpl.getPartnerDetailFromPartnerId(partnerId); + } catch (Exception exception) { + logger.error(ResidentErrorCode.PARTNER_SERVICE_EXCEPTION.getErrorCode(), exception); + return ""; + } + return (String) partnerDetail.get(LOGO_URL); } - } +} diff --git a/resident/resident-service/src/main/java/io/mosip/resident/util/Utilities.java b/resident/resident-service/src/main/java/io/mosip/resident/util/Utilities.java index 6d86b303bd9..3023530f42f 100644 --- a/resident/resident-service/src/main/java/io/mosip/resident/util/Utilities.java +++ b/resident/resident-service/src/main/java/io/mosip/resident/util/Utilities.java @@ -237,52 +237,57 @@ public String getRidByIndividualId(String individualId) throws ApisResourceAcces return rid; } - public ArrayList getRidStatus(String rid) throws ApisResourceAccessException, IOException { + public ArrayList getRidStatus(String rid) throws ApisResourceAccessException, IOException, ResidentServiceCheckedException { logger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), "", "Utilities::getRidStatus():: entry"); Map pathsegments = new HashMap(); pathsegments.put("rid", rid); logger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), "", "Stage::methodname():: RETRIEVEIUINBYVID GET service call Started"); - ResponseWrapper response = (ResponseWrapper)residentServiceRestClient.getApi(ApiName.GET_RID_STATUS, + ResponseWrapper responseWrapper = (ResponseWrapper)residentServiceRestClient.getApi(ApiName.GET_RID_STATUS, pathsegments, ResponseWrapper.class); + if (responseWrapper.getErrors() != null && !responseWrapper.getErrors().isEmpty()) { + logger.debug(responseWrapper.getErrors().get(0).toString()); + throw new ResidentServiceCheckedException(ResidentErrorCode.RID_NOT_FOUND.getErrorCode(), + responseWrapper.getErrors().get(0).getMessage()); + } logger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.UIN.toString(), "", "Utilities::getRidByIndividualId():: GET_RID_BY_INDIVIDUAL_ID GET service call ended successfully"); - ArrayList objectArrayList = objMapper.readValue( - objMapper.writeValueAsString(response.getResponse()), ArrayList.class); + ArrayList objectArrayList = objMapper.readValue( + objMapper.writeValueAsString(responseWrapper.getResponse()), ArrayList.class); return objectArrayList; } - public HashMap getPacketStatus(String rid) throws ApisResourceAccessException, IOException { - String aidStatus=""; - String transactionTypeCode=""; - HashMap packetStatusMap = new HashMap<>(); - ArrayList regTransactionResponseDTO = getRidStatus(rid); - for(Object object : regTransactionResponseDTO){ - HashMap packetStatus = (HashMap) object; - String statusCode = (String) packetStatus.get(STATUS_CODE); - String packetStatusCode = PacketStatus.getStatusCode(statusCode); - if(!packetStatusCode.isEmpty()){ - aidStatus = packetStatusCode; - transactionTypeCode = getTransactionTypeCode(regTransactionResponseDTO); - packetStatusMap.put(AID_STATUS, aidStatus); - packetStatusMap.put(TRANSACTION_TYPE_CODE, transactionTypeCode); - return packetStatusMap; + public Map getPacketStatus(String rid) + throws ApisResourceAccessException, IOException, ResidentServiceCheckedException { + Map packetStatusMap = new HashMap<>(); + ArrayList regTransactionList = getRidStatus(rid); + for (Object object : regTransactionList) { + if (object instanceof Map) { + Map packetData = (Map) object; + Optional packetStatusCode = getPacketStatusCode(packetData); + Optional transactionTypeCode = getTransactionTypeCode(packetData); + if (packetStatusCode.isPresent() && transactionTypeCode.isPresent()) { + packetStatusMap.put(AID_STATUS, packetStatusCode.get()); + packetStatusMap.put(TRANSACTION_TYPE_CODE, transactionTypeCode.get()); + return packetStatusMap; + } } } - return packetStatusMap; + throw new ResidentServiceCheckedException(ResidentErrorCode.UNKNOWN_EXCEPTION.getErrorCode(), + String.format("%s - Unable to get the RID status from Reg-proc", + ResidentErrorCode.UNKNOWN_EXCEPTION.getErrorMessage())); } - private String getTransactionTypeCode(ArrayList regTransactionResponseDTO) { - String typeCode=""; - for(Object object : regTransactionResponseDTO){ - HashMap packetStatus = (HashMap) object; - String transactionTypeCode = (String) packetStatus.get(TRANSACTION_TYPE_CODE); - typeCode = TransactionStage.getTypeCode(transactionTypeCode); - if(!typeCode.isEmpty()){ - break; - } - } + private Optional getPacketStatusCode(Map packetData) { + String statusCode = (String) packetData.get(STATUS_CODE); + Optional packetStatusCode = PacketStatus.getStatusCode(statusCode, env); + return packetStatusCode; + } + + private Optional getTransactionTypeCode(Map packetData) { + String transactionTypeCode = (String) packetData.get(TRANSACTION_TYPE_CODE); + Optional typeCode = TransactionStage.getTypeCode(transactionTypeCode, env); return typeCode; } diff --git a/resident/resident-service/src/main/java/io/mosip/resident/util/Utility.java b/resident/resident-service/src/main/java/io/mosip/resident/util/Utility.java index 0a03e4965e3..13b410e463d 100644 --- a/resident/resident-service/src/main/java/io/mosip/resident/util/Utility.java +++ b/resident/resident-service/src/main/java/io/mosip/resident/util/Utility.java @@ -3,7 +3,6 @@ import static io.mosip.resident.constant.MappingJsonConstants.EMAIL; import static io.mosip.resident.constant.MappingJsonConstants.PHONE; import static io.mosip.resident.constant.RegistrationConstants.DATETIME_PATTERN; -import static io.mosip.resident.constant.ResidentConstants.RESIDENT_SERVICES; import java.io.ByteArrayOutputStream; import java.io.IOException; @@ -13,17 +12,23 @@ import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.time.LocalDateTime; +import java.time.chrono.Chronology; import java.time.format.DateTimeFormatter; +import java.time.format.FormatStyle; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; +import java.util.Locale; import java.util.Map; +import java.util.Map.Entry; import java.util.Objects; import java.util.Optional; import java.util.Set; +import java.util.stream.Collectors; +import java.util.stream.Stream; import javax.annotation.PostConstruct; import javax.servlet.http.HttpServletRequest; @@ -39,6 +44,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; +import org.springframework.cache.annotation.Cacheable; import org.springframework.core.env.Environment; import org.springframework.core.io.Resource; import org.springframework.http.MediaType; @@ -51,6 +57,9 @@ import org.springframework.web.client.HttpServerErrorException; import org.springframework.web.client.RestTemplate; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.nimbusds.jose.util.IOUtils; @@ -71,7 +80,10 @@ import io.mosip.resident.constant.RequestType; import io.mosip.resident.constant.ResidentConstants; import io.mosip.resident.constant.ResidentErrorCode; +import io.mosip.resident.constant.ServiceType; import io.mosip.resident.constant.TemplateVariablesConstants; +import io.mosip.resident.dto.DynamicFieldCodeValueDTO; +import io.mosip.resident.dto.DynamicFieldConsolidateResponseDto; import io.mosip.resident.dto.IdRepoResponseDto; import io.mosip.resident.dto.IdentityDTO; import io.mosip.resident.dto.JsonValue; @@ -80,7 +92,7 @@ import io.mosip.resident.exception.IdRepoAppException; import io.mosip.resident.exception.ResidentServiceCheckedException; import io.mosip.resident.exception.ResidentServiceException; -import io.mosip.resident.repository.ResidentTransactionRepository; +import io.mosip.resident.service.ProxyMasterdataService; import io.mosip.resident.service.impl.IdentityServiceImpl; /** @@ -91,6 +103,8 @@ @Component public class Utility { + private static final String MEDIUM = "MEDIUM"; + private static final String EVENT_ID_PLACEHOLDER = "{eventId}"; private static final Logger logger = LoggerConfiguration.logConfig(Utility.class); @@ -104,6 +118,9 @@ public class Utility { @Value("${registration.processor.identityjson}") private String residentIdentityJson; + @Value("${"+ResidentConstants.PREFERRED_LANG_PROPERTY+":false}") + private boolean isPreferedLangFlagEnabled; + @Autowired @Qualifier("selfTokenRestTemplate") private RestTemplate residentRestTemplate; @@ -122,6 +139,7 @@ public class Utility { private static final String IDENTITY = "identity"; private static final String VALUE = "value"; + private static final String ACR_AMR = "acr_amr"; private static String regProcessorIdentityJson = ""; private static String ANONYMOUS_USER = "anonymousUser"; @@ -144,19 +162,69 @@ public class Utility { @Value("${mosip.resident.download-card.url}") private String downloadCardUrl; + + @Value("${resident.date.time.replace.special.chars:{}}") + private String specialCharsReplacement; + + @Autowired + private IdentityServiceImpl identityService; @Autowired - private ResidentTransactionRepository residentTransactionRepository; + private ProxyMasterdataService proxyMasterdataService; @Autowired - private IdentityServiceImpl identityService; + private ObjectMapper mapper; + + /** The acr-amr mapping json file. */ + @Value("${amr-acr.json.filename}") + private String amrAcrJsonFile; + + @Value("${resident.date.time.formmatting.style:" + MEDIUM + "}") + private String formattingStyle; + + private Map specialCharsReplacementMap; @PostConstruct private void loadRegProcessorIdentityJson() { regProcessorIdentityJson = residentRestTemplate.getForObject(configServerFileStorageURL + residentIdentityJson, String.class); logger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), "loadRegProcessorIdentityJson completed successfully"); - } + try { + specialCharsReplacementMap = ((Map)mapper.readValue(specialCharsReplacement, Map.class)) + .entrySet() + .stream() + .collect(Collectors.toUnmodifiableMap(Entry::getKey, entry -> String.valueOf(entry.getValue()))); + } catch (JsonProcessingException e) { + logger.error("Error parsing special chars map used for replacement in timestamp in filename."); + specialCharsReplacementMap = Map.of(); + } + } + + @Cacheable(value = "amr-acr-mapping") + public Map getAmrAcrMapping() throws ResidentServiceCheckedException { + String amrAcrJson = residentRestTemplate.getForObject(configServerFileStorageURL + amrAcrJsonFile, + String.class); + Map amrAcrMap = Map.of(); + try { + if (amrAcrJson != null) { + amrAcrMap = objectMapper.readValue(amrAcrJson.getBytes(StandardCharsets.UTF_8), Map.class); + } + } catch (IOException e) { + throw new ResidentServiceCheckedException(ResidentErrorCode.RESIDENT_SYS_EXCEPTION.getErrorCode(), + ResidentErrorCode.RESIDENT_SYS_EXCEPTION.getErrorMessage(), e); + } + Object obj = amrAcrMap.get(ACR_AMR); + Map map = (Map) obj; + Map acrAmrMap = map.entrySet().stream().collect( + Collectors.toMap(entry -> entry.getKey(), entry -> (String) ((ArrayList) entry.getValue()).get(0))); + return acrAmrMap; + } + + public String getAuthTypeCodefromkey(String reqTypeCode) throws ResidentServiceCheckedException { + Map map = getAmrAcrMapping(); + String authTypeCode = map.get(reqTypeCode); + return authTypeCode; + } @SuppressWarnings("unchecked") public JSONObject retrieveIdrepoJson(String id) throws ResidentServiceCheckedException { @@ -290,16 +358,49 @@ private Set getPreferredLanguage(JSONObject demographicIdentity) { preferredLang = String.valueOf(object); if(preferredLang.contains(ResidentConstants.COMMA)){ String[] preferredLangArray = preferredLang.split(ResidentConstants.COMMA); - return Set.of(preferredLangArray); + return Stream.of(preferredLangArray) + .map(lang -> getPreferredLanguageCodeForLanguageNameBasedOnFlag(preferredLangAttribute, lang)) + .collect(Collectors.toSet()); } } } if(preferredLang!=null){ - return Set.of(preferredLang); + String preferredLanguage=getPreferredLanguageCodeForLanguageNameBasedOnFlag(preferredLangAttribute, preferredLang); + if(preferredLanguage==null || preferredLanguage.isEmpty()){ + return Set.of(); + } + return Set.of(preferredLanguage); } return Set.of(); } + public String getPreferredLanguageCodeForLanguageNameBasedOnFlag(String fieldName, String preferredLang) { + if(isPreferedLangFlagEnabled){ + try { + ResponseWrapper responseWrapper = (ResponseWrapper) + proxyMasterdataService.getDynamicFieldBasedOnLangCodeAndFieldName(fieldName, + env.getProperty(ResidentConstants.MANDATORY_LANGUAGE), true); + DynamicFieldConsolidateResponseDto dynamicFieldConsolidateResponseDto = mapper.readValue( + mapper.writeValueAsString(responseWrapper.getResponse()), + DynamicFieldConsolidateResponseDto.class); + return dynamicFieldConsolidateResponseDto.getValues() + .stream() + .filter(dynamicFieldCodeValueDTO -> preferredLang.equalsIgnoreCase(dynamicFieldCodeValueDTO.getValue())) + .findAny() + .map(DynamicFieldCodeValueDTO::getCode) + .orElse(null); + } catch (ResidentServiceCheckedException e) { + throw new RuntimeException(e); + } catch (JsonMappingException e) { + throw new RuntimeException(e); + } catch (JsonProcessingException e) { + throw new RuntimeException(e); + } + } + return preferredLang; + + } + private Set getDataCapturedLanguages(JSONObject mapperIdentity, JSONObject demographicIdentity) throws ReflectiveOperationException { Set dataCapturedLangauges = new HashSet(); @@ -372,7 +473,7 @@ public String maskPhone(String phone) { return maskData(phone, phoneMaskFunction); } - public String convertToMaskDataFormat(String maskData) { + public String convertToMaskData(String maskData) { return maskData(maskData, maskingFunction); } @@ -386,15 +487,19 @@ public String getPassword(List attributeValues) { return MVEL.executeExpression(serializable, context, myVarFactory, String.class); } - - public ResidentTransactionEntity createEntity() { + public ResidentTransactionEntity createEntity(RequestType requestType){ ResidentTransactionEntity residentTransactionEntity = new ResidentTransactionEntity(); residentTransactionEntity.setRequestDtimes(DateUtils.getUTCCurrentDateTime()); residentTransactionEntity.setResponseDtime(DateUtils.getUTCCurrentDateTime()); - residentTransactionEntity.setCrBy(RESIDENT_SERVICES); + residentTransactionEntity.setCrBy(getSessionUserName()); residentTransactionEntity.setCrDtimes(DateUtils.getUTCCurrentDateTime()); // Initialize with true, so that it is updated as false in later when needed for notification - residentTransactionEntity.setReadStatus(true); + if(ServiceType.ASYNC.getRequestTypes().contains(requestType)){ + residentTransactionEntity.setReadStatus(false); + }else { + residentTransactionEntity.setReadStatus(true); + } + residentTransactionEntity.setRequestTypeCode(requestType.name()); return residentTransactionEntity; } @@ -472,16 +577,43 @@ public byte[] signPdf(InputStream in, String password) { return pdfSignatured; } - public String getFileName(String eventId, String propertyName, int timeZoneOffset){ + public String getFileName(String eventId, String propertyName, int timeZoneOffset, String locale){ if(eventId!=null && propertyName.contains("{" + TemplateVariablesConstants.EVENT_ID + "}")){ propertyName = propertyName.replace("{" +TemplateVariablesConstants.EVENT_ID+ "}", eventId); } if(propertyName.contains("{" + TemplateVariablesConstants.TIMESTAMP + "}")){ - propertyName = propertyName.replace("{" +TemplateVariablesConstants.TIMESTAMP+ "}", formatWithOffsetForFileName(timeZoneOffset, DateUtils.getUTCCurrentDateTime())); + String dateTimeFormat = formatWithOffsetForFileName(timeZoneOffset, locale, DateUtils.getUTCCurrentDateTime()); + propertyName = propertyName.replace("{" +TemplateVariablesConstants.TIMESTAMP+ "}", dateTimeFormat); + } + return propertyName; + } + + public String getFileNameforId(String id, String propertyName, int timeZoneOffset, String locale){ + if(id!=null && propertyName.contains("{" + TemplateVariablesConstants.ID + "}")){ + propertyName = propertyName.replace("{" +TemplateVariablesConstants.ID+ "}", id); + } + if(propertyName.contains("{" + TemplateVariablesConstants.TIMESTAMP + "}")){ + propertyName = propertyName.replace("{" +TemplateVariablesConstants.TIMESTAMP+ "}", formatWithOffsetForFileName(timeZoneOffset, locale, DateUtils.getUTCCurrentDateTime())); } return propertyName; } + private String replaceSpecialChars(String fileName) { + if(!specialCharsReplacementMap.isEmpty()) { + StringBuilder stringBuilder = new StringBuilder(fileName); + specialCharsReplacementMap.entrySet().forEach(entry -> { + String key = entry.getKey(); + String value = entry.getValue(); + int index; + while((index = stringBuilder.indexOf(key)) != -1) { + stringBuilder.replace(index, index + key.length(), value); + } + }); + return stringBuilder.toString(); + } + return fileName; + } + public String getIdForResidentTransaction(String individualId, List channel) throws ResidentServiceCheckedException, NoSuchAlgorithmException { IdentityDTO identityDTO = identityService.getIdentity(individualId); String uin =""; @@ -507,7 +639,7 @@ public String getIdForResidentTransaction(String individualId, List chan return HMACUtils2.digestAsPlainText(id.getBytes()); } - public String getFileNameAck(String featureName, String eventId, String propertyName, int timeZoneOffset) { + public String getFileNameAck(String featureName, String eventId, String propertyName, int timeZoneOffset, String locale) { if (eventId != null && propertyName.contains("{" + TemplateVariablesConstants.FEATURE_NAME + "}")) { propertyName = propertyName.replace("{" + TemplateVariablesConstants.FEATURE_NAME + "}", featureName); } @@ -516,38 +648,66 @@ public String getFileNameAck(String featureName, String eventId, String property } if (propertyName.contains("{" + TemplateVariablesConstants.TIMESTAMP + "}")) { propertyName = propertyName.replace("{" + TemplateVariablesConstants.TIMESTAMP + "}", - formatWithOffsetForFileName(timeZoneOffset, DateUtils.getUTCCurrentDateTime())); + formatWithOffsetForFileName(timeZoneOffset, locale, DateUtils.getUTCCurrentDateTime())); } return propertyName; } - public String getFileNameAsPerFeatureName(String eventId, String featureName, int timeZoneOffset) { + public String getFileNameAsPerFeatureName(String eventId, String featureName, int timeZoneOffset, String locale) { String namingProperty = RequestType.getRequestTypeByName(featureName).getNamingProperty(); if (namingProperty == null) { namingProperty = ResidentConstants.ACK_NAMING_CONVENTION_PROPERTY; } return getFileNameAck(featureName, eventId, Objects.requireNonNull(this.env.getProperty(namingProperty)), - timeZoneOffset); + timeZoneOffset, locale); } public String getRefIdHash(String individualId) throws NoSuchAlgorithmException { return HMACUtils2.digestAsPlainText(individualId.getBytes()); } - private String formatDateTimeForPattern(LocalDateTime localDateTime, String dateTimePattern) { - return localDateTime == null ? null : localDateTime.format(DateTimeFormatter.ofPattern(dateTimePattern)); + private String formatDateTimeForPattern(LocalDateTime localDateTime, String locale, String defaultDateTimePattern, int timeZoneOffset) { + return localDateTime == null ? null : formatToLocaleDateTime(locale, defaultDateTimePattern, localDateTime); } - public String formatWithOffsetForUI(int timeZoneOffset, LocalDateTime localDateTime) { - return formatDateTimeForPattern(applyTimeZoneOffsetOnDateTime(timeZoneOffset, localDateTime), Objects.requireNonNull(env.getProperty(ResidentConstants.UI_DATE_TIME_PATTERN))); + public String formatWithOffsetForUI(int timeZoneOffset, String locale, LocalDateTime localDateTime) { + return formatDateTimeForPattern(applyTimeZoneOffsetOnDateTime(timeZoneOffset, localDateTime), locale, Objects.requireNonNull(env.getProperty(ResidentConstants.UI_DATE_TIME_PATTERN_DEFAULT)), timeZoneOffset); } + public String formatWithOffsetForFileName(int timeZoneOffset, String locale, LocalDateTime localDateTime) { + return replaceSpecialChars(formatDateTimeForPattern(applyTimeZoneOffsetOnDateTime(timeZoneOffset, localDateTime), locale, Objects.requireNonNull(env.getProperty(ResidentConstants.FILENAME_DATETIME_PATTERN_DEFAULT)), timeZoneOffset)); + } + public LocalDateTime applyTimeZoneOffsetOnDateTime(int timeZoneOffset, LocalDateTime localDateTime) { return localDateTime == null ? null : localDateTime.minusMinutes(timeZoneOffset); //Converting UTC to local time zone } - public String formatWithOffsetForFileName(int timeZoneOffset, LocalDateTime localDateTime) { - return formatDateTimeForPattern(applyTimeZoneOffsetOnDateTime(timeZoneOffset, localDateTime), Objects.requireNonNull(env.getProperty(ResidentConstants.FILENAME_DATETIME_PATTERN))); + private String formatToLocaleDateTime(String localeStr, String defaultDateTimePattern, LocalDateTime localDateTime) { + Locale locale = null; + if (localeStr != null && !localeStr.isEmpty()) { + String[] localeElements = localeStr.replace('-', '_').split("_"); + if (localeElements.length == 1) { + locale = new Locale.Builder().setLanguage(localeElements[0].toLowerCase()).build(); + } else if (localeElements.length >= 2) { + locale = new Locale.Builder().setLanguage(localeElements[0]).setRegion(localeElements[1].toUpperCase()) + .build(); + } + } + + if(locale == null && defaultDateTimePattern == null) { + locale = Locale.getDefault(); + } + + if(locale != null) { + Chronology chronology = Chronology.ofLocale(locale); + DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.valueOf(formattingStyle)).withLocale( locale ).withChronology( chronology ) ; + String dateTime = localDateTime.format(formatter); + return dateTime; + } else { + DateTimeFormatter formatter = DateTimeFormatter.ofPattern(defaultDateTimePattern); + String dateTime = localDateTime.format(formatter); + return dateTime; + } } public String getClientIp(HttpServletRequest req) { @@ -579,4 +739,32 @@ public String getClientIp(HttpServletRequest req) { return req.getRemoteAddr(); } + public String getCardOrderTrackingId(String transactionId, String individualId) + throws ResidentServiceCheckedException, ApisResourceAccessException { + Object object = residentServiceRestClient.getApi(ApiName.GET_ORDER_STATUS_URL, RequestType.getAllNewOrInprogressStatusList(env), + List.of(TemplateVariablesConstants.TRANSACTION_ID, TemplateVariablesConstants.INDIVIDUAL_ID), + List.of(transactionId, individualId), ResponseWrapper.class); + ResponseWrapper> responseWrapper = JsonUtil.convertValue(object, + new TypeReference>>() { + }); + if (Objects.nonNull(responseWrapper.getErrors()) && !responseWrapper.getErrors().isEmpty()) { + logger.error("ORDER_STATUS_URL returned error " + responseWrapper.getErrors()); + throw new ResidentServiceCheckedException(ResidentErrorCode.UNKNOWN_EXCEPTION); + } + return responseWrapper.getResponse().get(TemplateVariablesConstants.TRACKING_ID); + } + + public String getSessionUserName() { + String name = null; + try { + name = identityService.getAvailableclaimValue(this.env.getProperty(ResidentConstants.NAME_FROM_PROFILE)); + if (name == null || name.trim().isEmpty()) { + name = ResidentConstants.UNKNOWN; + } + } catch (ApisResourceAccessException e) { + throw new RuntimeException(e); + } + return name; + } + } diff --git a/resident/resident-service/src/main/java/io/mosip/resident/validator/RequestValidator.java b/resident/resident-service/src/main/java/io/mosip/resident/validator/RequestValidator.java index ffe47127513..738c33643a2 100644 --- a/resident/resident-service/src/main/java/io/mosip/resident/validator/RequestValidator.java +++ b/resident/resident-service/src/main/java/io/mosip/resident/validator/RequestValidator.java @@ -1,11 +1,11 @@ package io.mosip.resident.validator; -import static io.mosip.resident.constant.RegistrationConstants.ID; import static io.mosip.resident.constant.RegistrationConstants.MESSAGE_CODE; -import static io.mosip.resident.constant.RegistrationConstants.VERSION; import static io.mosip.resident.service.impl.ResidentOtpServiceImpl.EMAIL_CHANNEL; import static io.mosip.resident.service.impl.ResidentOtpServiceImpl.PHONE_CHANNEL; +import java.io.IOException; +import java.time.Instant; import java.time.LocalDate; import java.util.ArrayList; import java.util.Arrays; @@ -13,17 +13,23 @@ import java.util.EnumMap; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Optional; import java.util.stream.Collectors; +import java.util.stream.Stream; import javax.annotation.PostConstruct; import javax.validation.Valid; +import org.json.simple.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; +import com.fasterxml.jackson.databind.ObjectMapper; + +import io.mosip.kernel.core.http.ResponseWrapper; import io.mosip.kernel.core.idvalidator.exception.InvalidIDException; import io.mosip.kernel.core.idvalidator.spi.RidValidator; import io.mosip.kernel.core.idvalidator.spi.UinValidator; @@ -31,6 +37,7 @@ import io.mosip.kernel.core.util.CryptoUtil; import io.mosip.kernel.core.util.DateUtils; import io.mosip.kernel.core.util.StringUtils; +import io.mosip.preregistration.application.dto.TransliterationRequestDTO; import io.mosip.resident.constant.AuthTypeStatus; import io.mosip.resident.constant.CardType; import io.mosip.resident.constant.EventStatus; @@ -40,6 +47,7 @@ import io.mosip.resident.constant.ResidentErrorCode; import io.mosip.resident.constant.ServiceType; import io.mosip.resident.constant.TemplateVariablesConstants; +import io.mosip.resident.constant.UISchemaTypes; import io.mosip.resident.dto.AidStatusRequestDTO; import io.mosip.resident.dto.AuthHistoryRequestDTO; import io.mosip.resident.dto.AuthLockOrUnLockRequestDto; @@ -53,6 +61,7 @@ import io.mosip.resident.dto.EuinRequestDTO; import io.mosip.resident.dto.GrievanceRequestDTO; import io.mosip.resident.dto.IVidRequestDto; +import io.mosip.resident.dto.IdentityDTO; import io.mosip.resident.dto.IndividualIdOtpRequestDTO; import io.mosip.resident.dto.MainRequestDTO; import io.mosip.resident.dto.OtpRequestDTOV2; @@ -73,17 +82,24 @@ import io.mosip.resident.exception.ResidentServiceCheckedException; import io.mosip.resident.exception.ResidentServiceException; import io.mosip.resident.repository.ResidentTransactionRepository; +import io.mosip.resident.service.ProxyMasterdataService; import io.mosip.resident.service.impl.IdentityServiceImpl; +import io.mosip.resident.service.impl.ResidentConfigServiceImpl; import io.mosip.resident.service.impl.ResidentServiceImpl; -import io.mosip.resident.service.impl.UISchemaTypes; import io.mosip.resident.util.AuditUtil; import io.mosip.resident.util.EventEnum; +import io.mosip.resident.util.Utilities; @Component public class RequestValidator { + private static final String ID = "id"; + private static final String VERSION = "version"; + private static final String REQUESTTIME = "requesttime"; private static final String REQUEST = "request"; private static final String VALIDATE_EVENT_ID = "Validating Event Id."; + private static final String ID_SCHEMA_VERSION = "IDSchemaVersion"; + @Autowired private UinValidator uinValidator; @@ -102,9 +118,15 @@ public class RequestValidator { @Autowired private IdentityServiceImpl identityService; + @Autowired + private ResidentConfigServiceImpl residentConfigService; + @Autowired private ResidentTransactionRepository residentTransactionRepository; + @Autowired + private Utilities utilities; + private String euinId; private String reprintId; @@ -116,6 +138,10 @@ public class RequestValidator { private String authLockId; private String uinUpdateId; + @Autowired + private ProxyMasterdataService proxyMasterdataService; + @Autowired + private ObjectMapper objectMapper; @Value("${resident.updateuin.id}") public void setUinUpdateId(String uinUpdateId) { @@ -244,7 +270,10 @@ public void setReprintId(String reprintId) { @Value("${resident.validation.event-id.regex}") private String eventIdRegex; - + + @Value("${resident.attribute.names.without.documents.required}") + private String attributeNamesWithoutDocumentsRequired; + @PostConstruct public void setMap() { map = new EnumMap<>(RequestIdType.class); @@ -265,23 +294,23 @@ public void validateVidCreateRequest(IVidRequestDto DateUtils.parseToLocalDateTime(requestDto.getRequesttime()); } catch (Exception e) { audit.setAuditRequestDto( - EventEnum.getEventEnumWithValue(EventEnum.INPUT_INVALID, "requesttime", "Request to generate VID")); + EventEnum.getEventEnumWithValue(EventEnum.INPUT_INVALID, REQUESTTIME, "Request to generate VID")); - throw new InvalidInputException("requesttime"); + throw new InvalidInputException(REQUESTTIME); } if (StringUtils.isEmpty(requestDto.getId()) || !requestDto.getId().equalsIgnoreCase(id)) { audit.setAuditRequestDto( - EventEnum.getEventEnumWithValue(EventEnum.INPUT_INVALID, "id", "Request to generate VID")); + EventEnum.getEventEnumWithValue(EventEnum.INPUT_INVALID, ID, "Request to generate VID")); - throw new InvalidInputException("id"); + throw new InvalidInputException(ID); } if (StringUtils.isEmpty(requestDto.getVersion()) || !requestDto.getVersion().equalsIgnoreCase(version)) { audit.setAuditRequestDto( - EventEnum.getEventEnumWithValue(EventEnum.INPUT_INVALID, "version", "Request to generate VID")); + EventEnum.getEventEnumWithValue(EventEnum.INPUT_INVALID, VERSION, "Request to generate VID")); - throw new InvalidInputException("version"); + throw new InvalidInputException(VERSION); } if (requestDto.getRequest() == null) { @@ -320,9 +349,9 @@ public void validateVidCreateV2Request(IVidRequestDto request,String msg try { DateUtils.parseToLocalDateTime(request.getRequesttime()); } catch (Exception e) { - audit.setAuditRequestDto(EventEnum.getEventEnumWithValue(EventEnum.INPUT_INVALID, "requesttime", msg)); - throw new InvalidInputException("requesttime"); + audit.setAuditRequestDto(EventEnum.getEventEnumWithValue(EventEnum.INPUT_INVALID, REQUESTTIME, msg)); + throw new InvalidInputException(REQUESTTIME); } if (StringUtils.isEmpty(request.getVersion()) || !request.getVersion().equalsIgnoreCase(version)) { - audit.setAuditRequestDto(EventEnum.getEventEnumWithValue(EventEnum.INPUT_INVALID, "version", msg)); - throw new InvalidInputException("version"); + audit.setAuditRequestDto(EventEnum.getEventEnumWithValue(EventEnum.INPUT_INVALID, VERSION, msg)); + throw new InvalidInputException(VERSION); } if (request.getRequest() == null) { audit.setAuditRequestDto(EventEnum.INPUT_DOESNT_EXISTS); @@ -709,58 +738,36 @@ public void validateVidRevokeV2Request(RequestWrapper request,String msg) { + public void validateRevokeVidV2RequestWrapper(RequestWrapper requestWrapper,String msg) { - if (StringUtils.isEmpty(request.getId()) || !request.getId().equalsIgnoreCase(revokeVidIdNew)) { + if (StringUtils.isEmpty(requestWrapper.getId()) || !requestWrapper.getId().equalsIgnoreCase(revokeVidIdNew)) { audit.setAuditRequestDto(EventEnum.getEventEnumWithValue(EventEnum.INPUT_INVALID, "revokeVidIdNew", msg)); throw new InvalidInputException("revokeVidIdNew"); } try { - DateUtils.parseToLocalDateTime(request.getRequesttime()); + DateUtils.parseToLocalDateTime(requestWrapper.getRequesttime()); } catch (Exception e) { - audit.setAuditRequestDto(EventEnum.getEventEnumWithValue(EventEnum.INPUT_INVALID, "requesttime", msg)); - throw new InvalidInputException("requesttime"); + audit.setAuditRequestDto(EventEnum.getEventEnumWithValue(EventEnum.INPUT_INVALID, REQUESTTIME, msg)); + throw new InvalidInputException(REQUESTTIME); } - if (StringUtils.isEmpty(request.getVersion()) || !request.getVersion().equalsIgnoreCase(revokeVidVersion)) { + if (StringUtils.isEmpty(requestWrapper.getVersion()) || !requestWrapper.getVersion().equalsIgnoreCase(revokeVidVersion)) { audit.setAuditRequestDto(EventEnum.getEventEnumWithValue(EventEnum.INPUT_INVALID, "revokeVidVersion", msg)); throw new InvalidInputException("revokeVidVersion"); } - if (request.getRequest() == null) { - audit.setAuditRequestDto(EventEnum.INPUT_DOESNT_EXISTS); - throw new InvalidInputException(REQUEST); - } + validateAPIRequestToCheckNull(requestWrapper); } public boolean validateRequest(RequestWrapper request, RequestIdType requestIdType) { if (StringUtils.isEmpty(request.getId()) || !request.getId().equals(map.get(requestIdType))) - throw new InvalidInputException("id"); + throw new InvalidInputException(ID); try { DateUtils.parseToLocalDateTime(request.getRequesttime()); } catch (Exception e) { - throw new InvalidInputException("requesttime"); + throw new InvalidInputException(REQUESTTIME); } if (StringUtils.isEmpty(request.getVersion()) || !request.getVersion().equals(version)) - throw new InvalidInputException("version"); - - if (request.getRequest() == null) { - audit.setAuditRequestDto(EventEnum.INPUT_DOESNT_EXISTS); - throw new InvalidInputException(REQUEST); - } - return true; - - } - - public boolean validateAidStatusRequest(RequestWrapper request, RequestIdType requestIdType) { - if (StringUtils.isEmpty(request.getId()) || !request.getId().equals(map.get(requestIdType))) - throw new InvalidInputException("id"); - try { - DateUtils.parseToLocalDateTime(request.getRequesttime()); - } catch (Exception e) { - throw new InvalidInputException("requesttime"); - } - if (StringUtils.isEmpty(request.getVersion()) || !request.getVersion().equals(newVersion)) - throw new InvalidInputException("version"); + throw new InvalidInputException(VERSION); if (request.getRequest() == null) { audit.setAuditRequestDto(EventEnum.INPUT_DOESNT_EXISTS); @@ -807,7 +814,7 @@ public void validateReprintRequest(RequestWrapper req } } - public void validateUpdateRequest(RequestWrapper requestDTO, boolean isPatch) { + public void validateUpdateRequest(RequestWrapper requestDTO, boolean isPatch) throws ApisResourceAccessException, IOException, ResidentServiceCheckedException { if (!isPatch) { validateRequest(requestDTO, RequestIdType.RES_UPDATE); validateIndividualIdType(requestDTO.getRequest().getIndividualIdType(), "Request for update uin"); @@ -820,6 +827,8 @@ public void validateUpdateRequest(RequestWrapper reque } else { validateRequestNewApi(requestDTO, RequestIdType.RES_UPDATE); validateIndividualIdvIdWithoutIdType(requestDTO.getRequest().getIndividualId()); + validateAttributeName(requestDTO.getRequest().getIdentity()); + validateLanguageCodeInIdentityJson(requestDTO.getRequest().getIdentity()); } if (!isPatch && StringUtils.isEmpty(requestDTO.getRequest().getOtp())) { audit.setAuditRequestDto( @@ -827,10 +836,39 @@ public void validateUpdateRequest(RequestWrapper reque throw new InvalidInputException("otp"); } - if (StringUtils.isEmpty(requestDTO.getRequest().getTransactionID())) { - audit.setAuditRequestDto(EventEnum.getEventEnumWithValue(EventEnum.INPUT_INVALID, "transactionID", - "Request for update uin")); - throw new InvalidInputException("transactionID"); + if(requestDTO.getRequest().getIdentity()!=null) { + List attributesWithoutDocumentsRequired = new ArrayList<>(); + try { + Map identityMappingMap = residentConfigService.getIdentityMappingMap(); + if (attributeNamesWithoutDocumentsRequired != null) { + attributesWithoutDocumentsRequired = Stream + .of(attributeNamesWithoutDocumentsRequired + .split(ResidentConstants.ATTRIBUTE_LIST_DELIMITER)) + .filter(attribute -> identityMappingMap.containsKey(attribute)) + .map(attribute -> String + .valueOf(((Map) identityMappingMap.get(attribute)).get(ResidentConstants.VALUE))) + .collect(Collectors.toList()); + } + + } catch (ResidentServiceCheckedException | IOException e) { + throw new RuntimeException(e); + } + Map identityDataFromRequest = requestDTO.getRequest().getIdentity(); + List attributeKeysFromRequest = identityDataFromRequest.keySet().stream().collect(Collectors.toList()); + // checking if the attributes coming from request body present in attributes list coming from properties + if(!attributesWithoutDocumentsRequired.containsAll(attributeKeysFromRequest)) { + if (StringUtils.isEmpty(requestDTO.getRequest().getTransactionID())) { + audit.setAuditRequestDto(EventEnum.getEventEnumWithValue(EventEnum.INPUT_INVALID, "transactionID", + "Request for update uin")); + throw new InvalidInputException("transactionID"); + } + } + } else { + if (StringUtils.isEmpty(requestDTO.getRequest().getTransactionID())) { + audit.setAuditRequestDto(EventEnum.getEventEnumWithValue(EventEnum.INPUT_INVALID, "transactionID", + "Request for update uin")); + throw new InvalidInputException("transactionID"); + } } if(!isPatch) { @@ -842,6 +880,57 @@ public void validateUpdateRequest(RequestWrapper reque } } + private void validateAttributeName(JSONObject identity) throws ApisResourceAccessException, IOException, ResidentServiceCheckedException { + JSONObject idRepoJson = utilities.retrieveIdrepoJson(identityService.getResidentIndvidualIdFromSession()); + String idSchemaVersionStr = String.valueOf(idRepoJson.get(ID_SCHEMA_VERSION)); + Double idSchemaVersion = Double.parseDouble(idSchemaVersionStr); + ResponseWrapper idSchemaResponse = proxyMasterdataService.getLatestIdSchema(idSchemaVersion, null, null); + Object idSchema = idSchemaResponse.getResponse(); + Map map = objectMapper.convertValue(idSchema, Map.class); + String schemaJson = ((String) map.get("schemaJson")); + boolean status = false; + if (identity != null) { + status = identity.keySet().stream() + .filter(key -> !Objects.equals(key, ID_SCHEMA_VERSION)) + .anyMatch(key -> schemaJson.contains(key.toString())); + } + if (!status) { + audit.setAuditRequestDto( + EventEnum.getEventEnumWithValue(EventEnum.INPUT_INVALID, + "identityJson", "Request for update uin")); + throw new InvalidInputException("identity"); + } + + } + + + private void validateLanguageCodeInIdentityJson(JSONObject identity) { + if(identity!=null) { + // Get a set of entries + for (Map.Entry entry : (Iterable) identity.entrySet()) { + // Retrieve the key and value of each entry + String key = (String) entry.getKey(); + Object value = entry.getValue(); + if (value instanceof ArrayList) { + ArrayList valueArray = (ArrayList) value; + for (Object valueInList : valueArray) { + if (valueInList instanceof Map) { + Map valueInListMap = (Map ) valueInList; + if (valueInListMap.containsKey(ResidentConstants.LANGUAGE)) { + String languageCode = valueInListMap.get(ResidentConstants.LANGUAGE); + validateMissingInputParameter(languageCode, ResidentConstants.LANGUAGE, EventEnum.INPUT_INVALID.getName()); + validateLanguageCode(languageCode); + String valueOfLanguageCode = valueInListMap.get(ResidentConstants.VALUE); + validateMissingInputParameter(valueOfLanguageCode, key+" "+languageCode+ " "+ + ResidentConstants.LANGUAGE +" "+ ResidentConstants.VALUE, EventEnum.INPUT_INVALID.getName()); + } + } + } + } + } + } + } + public void validateRidCheckStatusRequestDTO(RequestWrapper requestDTO) { validateRequest(requestDTO, RequestIdType.CHECK_STATUS); @@ -922,15 +1011,15 @@ private void validateUnlockForSeconds(Long unlockForSeconds, String message) { } private boolean validateIndividualIdvIdWithoutIdType(String individualId) { - try { - return this.validateUin(individualId) || this.validateVid(individualId) || this.validateRid(individualId); - } catch (InvalidIDException e) { - return false; - } + return this.validateUin(individualId) || this.validateVid(individualId) || this.validateRid(individualId); + } + + private boolean validateUinOrVid(String individualId) { + return this.validateUin(individualId) || this.validateVid(individualId); } public void validateAidStatusRequestDto(RequestWrapper reqDto) throws ResidentServiceCheckedException { - validateAidStatusRequest(reqDto, RequestIdType.CHECK_STATUS); + validateRequestNewApi(reqDto, RequestIdType.CHECK_STATUS); validateTransactionId(reqDto.getRequest().getTransactionId()); if(reqDto.getRequest().getIndividualId() == null) { throw new InvalidInputException("individualId"); @@ -945,10 +1034,11 @@ public void validateChannelVerificationStatus(String channel, String individualI EventEnum.getEventEnumWithValue(EventEnum.INPUT_INVALID, "channel", "Request channel verification API")); throw new InvalidInputException("channel"); } - if (StringUtils.isEmpty(individualId) || !validateIndividualIdvIdWithoutIdType(individualId)) { + if (StringUtils.isEmpty(individualId) || !validateUinOrVid(individualId)) { audit.setAuditRequestDto( EventEnum.getEventEnumWithValue(EventEnum.INPUT_INVALID, "individualId", "Request channel verification API")); - throw new InvalidInputException("individualId"); + throw new ResidentServiceException(ResidentErrorCode.INVALID_UIN_VID_ENTERED.getErrorCode(), + ResidentErrorCode.INVALID_UIN_VID_ENTERED.getErrorMessage()); } if (!individualId.matches(idAllowedSpecialCharRegex)) { throw new ResidentServiceException(ResidentErrorCode.CONTAINS_SPECIAL_CHAR.getErrorCode(), @@ -981,7 +1071,9 @@ public void validateSearchText(String searchText) { } public void validateFromDateTimeToDateTime(LocalDate fromDateTime, LocalDate toDateTime, String request_service_history_api) { - if(fromDateTime == null && toDateTime != null) { + + if(fromDateTime == null && toDateTime != null || + fromDateTime!=null && toDateTime!=null && fromDateTime.isAfter(toDateTime)) { audit.setAuditRequestDto(EventEnum.getEventEnumWithValue(EventEnum.INPUT_INVALID, ResidentConstants.FROM_DATE_TIME, request_service_history_api)); throw new InvalidInputException(ResidentConstants.FROM_DATE_TIME); @@ -1095,6 +1187,21 @@ private void validateLanguageCode(String languageCode) { } } + public void validateId(io.mosip.preregistration.core.common.dto.MainRequestDTO requestDTO) { + if (Objects.nonNull(requestDTO.getId())) { + if (!requestDTO.getId().equals(transliterateId)) { + audit.setAuditRequestDto(EventEnum.getEventEnumWithValue(EventEnum.INPUT_INVALID, ID, "Invalid Transliterate id")); + throw new InvalidInputException(ID); + } + } else { + audit.setAuditRequestDto(EventEnum.getEventEnumWithValue(EventEnum.INPUT_INVALID, ID, "id is null")); + throw new InvalidInputException(ID); + } + if (requestDTO.getRequest().getFromFieldLang().equalsIgnoreCase(requestDTO.getRequest().getToFieldLang())) { + throw new InvalidInputException("'from' and 'to' languages cannot be same"); + } + } + public List validateUserIdAndTransactionId(String userId, String transactionID) { validateTransactionId(transactionID); List list = new ArrayList<>(); @@ -1128,11 +1235,34 @@ private boolean isDataValidWithRegex(String inputData, String regex) { return inputData.matches(regex); } - public void validateProxySendOtpRequest(MainRequestDTO userOtpRequest) { + public void validateProxySendOtpRequest(MainRequestDTO userOtpRequest) throws ApisResourceAccessException { validateRequestType(userOtpRequest.getId(), this.environment.getProperty(ResidentConstants.RESIDENT_CONTACT_DETAILS_SEND_OTP_ID), ID); validateVersion(userOtpRequest.getVersion()); validateDate(userOtpRequest.getRequesttime()); validateUserIdAndTransactionId(userOtpRequest.getRequest().getUserId(), userOtpRequest.getRequest().getTransactionId()); + validateSameUserId(userOtpRequest.getRequest().getUserId()); + } + + private void validateSameUserId(String userId) throws ApisResourceAccessException { + try { + IdentityDTO identityDTO = identityService.getIdentity(identityService.getResidentIndvidualIdFromSession()); + if(phoneValidator(userId)){ + String phone = identityDTO.getPhone(); + if(phone!=null && phone.equalsIgnoreCase(userId)) { + throw new ResidentServiceException(ResidentErrorCode.SAME_PHONE_ERROR, + ResidentErrorCode.SAME_PHONE_ERROR.getErrorMessage()); + } + } else { + String email = identityDTO.getEmail(); + if(email!=null && email.equalsIgnoreCase(userId)){ + throw new ResidentServiceException(ResidentErrorCode.SAME_EMAIL_ERROR, + ResidentErrorCode.SAME_EMAIL_ERROR.getErrorMessage()); + } + } + } catch (ResidentServiceCheckedException e) { + throw new ResidentServiceException(ResidentErrorCode.CLAIM_NOT_AVAILABLE.getErrorCode(), + ResidentErrorCode.CLAIM_NOT_AVAILABLE.getErrorMessage(), e); + } } public void validateUpdateDataRequest(MainRequestDTO userIdOtpRequest) { @@ -1140,11 +1270,24 @@ public void validateUpdateDataRequest(MainRequestDTO userIdOtpR String requestIdStoredInProperty = this.environment.getProperty(ResidentConstants.RESIDENT_CONTACT_DETAILS_UPDATE_ID); validateRequestType(inputRequestId, requestIdStoredInProperty, ID); validateVersion(userIdOtpRequest.getVersion()); - validateDate(userIdOtpRequest.getRequesttime()); + validateRequestTime(userIdOtpRequest.getRequesttime()); validateUserIdAndTransactionId(userIdOtpRequest.getRequest().getUserId(), userIdOtpRequest.getRequest().getTransactionId()); validateOTP(userIdOtpRequest.getRequest().getOtp()); } + public void validateRequestTime(Date requestTime) { + String localDateTime =DateUtils.getUTCCurrentDateTimeString(); + Date afterDate = Date.from(Instant.parse(localDateTime).plusSeconds(Long.parseLong( + Objects.requireNonNull(this.environment.getProperty(ResidentConstants.RESIDENT_FUTURE_TIME_LIMIT))))); + Date beforeDate = Date.from(Instant.parse(localDateTime).minusSeconds(Long.parseLong( + Objects.requireNonNull(this.environment.getProperty(ResidentConstants.RESIDENT_PAST_TIME_LIMIT))))); + if(requestTime==null || requestTime.after(afterDate) || requestTime.before(beforeDate)) { + audit.setAuditRequestDto( + EventEnum.getEventEnumWithValue(EventEnum.INPUT_INVALID, REQUESTTIME, "Request time invalid")); + throw new InvalidInputException(REQUESTTIME); + } + } + public void validateOTP(String otp) { if(otp==null){ audit.setAuditRequestDto(EventEnum.getEventEnumWithValue(EventEnum.INPUT_INVALID, @@ -1172,8 +1315,8 @@ public void validateRequestType(String inputRequestType, String requestTypeStore public void validateDate(Date requesttime) { if(requesttime==null) { audit.setAuditRequestDto( - EventEnum.getEventEnumWithValue(EventEnum.INPUT_INVALID, "requesttime", "Request time invalid")); - throw new InvalidInputException("requesttime"); + EventEnum.getEventEnumWithValue(EventEnum.INPUT_INVALID, REQUESTTIME, "Request time invalid")); + throw new InvalidInputException(REQUESTTIME); } } @@ -1204,14 +1347,14 @@ public void validateDownloadPersonalizedCard(MainRequestDTO attributes) { - if(attributes.isEmpty()){ + if (attributes == null || attributes.isEmpty()) { throw new InvalidInputException(TemplateVariablesConstants.ATTRIBUTES); } } public void validateVersion(String requestVersion) { if (StringUtils.isEmpty(requestVersion) || !requestVersion.equals(reqResVersion)) - throw new InvalidInputException("version"); + throw new InvalidInputException(VERSION); } private void validateEncodedString(String html) { @@ -1231,22 +1374,22 @@ private void validateString(String string, String variableName) { } public void validateDownloadCardVid(String vid) { - if(!validateVid(vid)){ - audit.setAuditRequestDto(EventEnum.INPUT_INVALID); + if (!validateVid(vid)) { + audit.setAuditRequestDto(EventEnum.getEventEnumWithValue(EventEnum.INPUT_INVALID, "VID")); throw new InvalidInputException("VID"); } } public boolean validateRequestNewApi(RequestWrapper requestWrapper, RequestIdType requestIdType) { if (StringUtils.isEmpty(requestWrapper.getId()) || !requestWrapper.getId().equals(map.get(requestIdType))) - throw new InvalidInputException("id"); + throw new InvalidInputException(ID); try { DateUtils.parseToLocalDateTime(requestWrapper.getRequesttime()); } catch (Exception e) { - throw new InvalidInputException("requesttime"); + throw new InvalidInputException(REQUESTTIME); } if (StringUtils.isEmpty(requestWrapper.getVersion()) || !requestWrapper.getVersion().equals(reqResVersion)) - throw new InvalidInputException("version"); + throw new InvalidInputException(VERSION); validateAPIRequestToCheckNull(requestWrapper); return true; @@ -1344,15 +1487,16 @@ public void validateReqOtp(IndividualIdOtpRequestDTO individualIdRequestDto) { validateIndividualIdV2(individualIdRequestDto.getIndividualId()); validateTransactionId(individualIdRequestDto.getTransactionId()); } - public void validatePurpose(String purpose) { validateMissingInputParameter(purpose, TemplateVariablesConstants.PURPOSE, "Validating purpose"); if (purpose.length() > purposeCharsLimit) { + audit.setAuditRequestDto(EventEnum.CREDENTIAL_REQ_EXCEPTION); throw new ResidentServiceException(ResidentErrorCode.CHAR_LIMIT_EXCEEDS.getErrorCode(), ResidentErrorCode.CHAR_LIMIT_EXCEEDS.getErrorMessage()); } if (!purpose.matches(purposeAllowedSpecialCharRegex)) { + audit.setAuditRequestDto(EventEnum.CREDENTIAL_REQ_EXCEPTION); throw new ResidentServiceException(ResidentErrorCode.CONTAINS_SPECIAL_CHAR.getErrorCode(), String.format(ResidentErrorCode.CONTAINS_SPECIAL_CHAR.getErrorMessage(), purpose)); } @@ -1366,11 +1510,10 @@ public void validateSharableAttributes(List sharableAttri } } - public void validateName(List name) throws ResidentServiceCheckedException { - if (name == null || name.isEmpty()) { + public void validateName(String name) throws ResidentServiceCheckedException { + if (StringUtils.isBlank(name)) { throw new ResidentServiceCheckedException(ResidentErrorCode.INVALID_REG_CENTER_NAME.getErrorCode(), ResidentErrorCode.INVALID_REG_CENTER_NAME.getErrorMessage()); } - } } \ No newline at end of file diff --git a/resident/resident-service/src/main/resources/application-local.properties b/resident/resident-service/src/main/resources/application-local.properties index a02c437390e..e54600c5681 100644 --- a/resident/resident-service/src/main/resources/application-local.properties +++ b/resident/resident-service/src/main/resources/application-local.properties @@ -53,6 +53,7 @@ resident.vid.version.new=1.0 mosip.resident.checkstatus.individualid.id=mosip.resident.check-stage-status resident.version.new=1.0 mosip.resident.api.id.otp.request=mosip.identity.otp.internal +resident.attribute.names.without.documents.required=preferredLanguage,email,phone #-----------------------------RID Properties--------------------------------------- # length of the rid mosip.kernel.rid.length=29 @@ -297,3 +298,10 @@ resident.id.allowed.special.char.regex=^[0-9]+$ auth.token.header=Authorization +# amr-acr JSON file name +amr-acr.json.filename=amr-acr-mapping.json + +mosip.resident.authentication.mode.property=authenticationMode +mosip.resident.download.card.naming.convention=Get_my_UIN + + diff --git a/resident/resident-service/src/test/java/io/mosip/resident/aspect/LoginCheckTest.java b/resident/resident-service/src/test/java/io/mosip/resident/aspect/LoginCheckTest.java new file mode 100644 index 00000000000..4436143d9e4 --- /dev/null +++ b/resident/resident-service/src/test/java/io/mosip/resident/aspect/LoginCheckTest.java @@ -0,0 +1,201 @@ +package io.mosip.resident.aspect; + +import java.util.ArrayList; +import java.util.Collection; + +import javax.servlet.http.Cookie; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; +import org.springframework.cloud.context.config.annotation.RefreshScope; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.util.ReflectionTestUtils; + +import io.mosip.resident.exception.ApisResourceAccessException; +import io.mosip.resident.exception.ResidentServiceCheckedException; +import io.mosip.resident.repository.ResidentSessionRepository; +import io.mosip.resident.repository.ResidentUserRepository; +import io.mosip.resident.service.impl.IdentityServiceImpl; +import io.mosip.resident.util.AuditUtil; +import io.mosip.resident.util.Utility; + +/** + * Aspect test class for login redirect API + * + * @author Ritik Jain + */ +@RunWith(MockitoJUnitRunner.class) +@RefreshScope +@ContextConfiguration +public class LoginCheckTest { + + @InjectMocks + private LoginCheck loginCheck; + + @Mock + private ResidentUserRepository residentUserRepository; + + @Mock + private IdentityServiceImpl identityServiceImpl; + + @Mock + private Utility utility; + + @Mock + private HttpServletRequest request; + + @Mock + private HttpServletResponse response; + + @Mock + private ResidentSessionRepository residentSessionRepository; + + @Mock + private AuditUtil audit; + + @Before + public void setup() throws ResidentServiceCheckedException, ApisResourceAccessException { + request = Mockito.mock(HttpServletRequest.class); + response = Mockito.mock(HttpServletResponse.class); + Collection cookies = new ArrayList<>(); + cookies.add( + "Authorization=eyJhbGciOiJSUzI1NiIsInR5cCIgO; Max-Age=1800000; Expires=Thu, 10-Nov-2022 05:05:02 GMT; Path=/; HttpOnly"); + cookies.add("id_token=eyJhbGciOiJSUzI1NiIsInR5cCIg; Path=/; Secure; HttpOnly"); + Mockito.when(response.getHeaders(Mockito.anyString())).thenReturn(cookies); + Cookie[] requestCookies = new Cookie[1]; + Cookie cookie = new Cookie("Authorization", "eyJhbGciOiJSUzI1NiIsInR5cCIgO"); + requestCookies[0] = cookie; + Mockito.when(request.getCookies()).thenReturn(requestCookies); + Mockito.when(request.getHeader(Mockito.anyString())).thenReturn("User-Agent:WINDOWS"); + Mockito.when(identityServiceImpl.getResidentIdaTokenFromAccessToken(Mockito.anyString())).thenReturn("282452929935769234295"); + ReflectionTestUtils.setField(loginCheck, "authTokenHeader", "Authorization"); + Mockito.when(identityServiceImpl.createSessionId()).thenReturn("123"); +// Mockito.when(residentUserRepository.findById(Mockito.anyString())) +// .thenReturn(Optional.of(new ResidentUserEntity())); + } + + @Test + public void tearDown() throws ResidentServiceCheckedException, ApisResourceAccessException { + Mockito.when(identityServiceImpl.createSessionId()).thenReturn(null); + loginCheck.getUserDetails("aHR0cHM6Ly9yZXNpZGVudC5kZ", "ce0dfae2-5dc3-4c2b", "733d8aa0-a53b-42e1", + "51a3f4c2-c029-490b.730-0c60476d94f2", "ce0dfae2-5dc3-4c2b", request, response); + } + + @Test + public void tearDownFailure() throws ResidentServiceCheckedException, ApisResourceAccessException { + loginCheck.getUserDetails("aHR0cHM6Ly9yZXNpZGVudC5kZ", "ce0dfae2-5dc3-4c2b", "733d8aa0-a53b-42e1", + "51a3f4c2-c029-490b.730-0c60476d94f2", "ce0dfae2-5dc3-4c2b", request, response); + } + @Test + public void testGetUserDetailsWithMac() throws ResidentServiceCheckedException, ApisResourceAccessException { + Mockito.when(request.getHeader(Mockito.anyString())).thenReturn("User-Agent:Mac"); + loginCheck.getUserDetails("aHR0cHM6Ly9yZXNpZGVudC5kZ", "ce0dfae2-5dc3-4c2b", "733d8aa0-a53b-42e1", + "51a3f4c2-c029-490b.730-0c60476d94f2", "ce0dfae2-5dc3-4c2b", request, response); + } + + @Test + public void testGetUserDetailsWithX11() throws ResidentServiceCheckedException, ApisResourceAccessException { + Mockito.when(request.getHeader(Mockito.anyString())).thenReturn("User-Agent:x11"); + loginCheck.getUserDetails("aHR0cHM6Ly9yZXNpZGVudC5kZ", "ce0dfae2-5dc3-4c2b", "733d8aa0-a53b-42e1", + "51a3f4c2-c029-490b.730-0c60476d94f2", "ce0dfae2-5dc3-4c2b", request, response); + } + + @Test + public void testGetUserDetailsWithAndroid() throws ResidentServiceCheckedException, ApisResourceAccessException { + Mockito.when(request.getHeader(Mockito.anyString())).thenReturn("User-Agent:Android"); + loginCheck.getUserDetails("aHR0cHM6Ly9yZXNpZGVudC5kZ", "ce0dfae2-5dc3-4c2b", "733d8aa0-a53b-42e1", + "51a3f4c2-c029-490b.730-0c60476d94f2", "ce0dfae2-5dc3-4c2b", request, response); + } + + @Test + public void testGetUserDetailsWithIPhone() throws ResidentServiceCheckedException, ApisResourceAccessException { + Mockito.when(request.getHeader(Mockito.anyString())).thenReturn("User-Agent:IPhone"); + loginCheck.getUserDetails("aHR0cHM6Ly9yZXNpZGVudC5kZ", "ce0dfae2-5dc3-4c2b", "733d8aa0-a53b-42e1", + "51a3f4c2-c029-490b.730-0c60476d94f2", "ce0dfae2-5dc3-4c2b", request, response); + } + + @Test + public void testGetUserDetailsWithUnKnownDevice() throws ResidentServiceCheckedException, ApisResourceAccessException { + Mockito.when(request.getHeader(Mockito.anyString())).thenReturn("User-Agent:Unknown"); + loginCheck.getUserDetails("aHR0cHM6Ly9yZXNpZGVudC5kZ", "ce0dfae2-5dc3-4c2b", "733d8aa0-a53b-42e1", + "51a3f4c2-c029-490b.730-0c60476d94f2", "ce0dfae2-5dc3-4c2b", request, response); + } + + @Test + public void testOnLoginReqFailure(){ + loginCheck.onLoginReqFailure(null); + } + + @Test + public void testLogin(){ + loginCheck.login(); + } + + @Test + public void testLogoutUser(){ + loginCheck.logoutUser(); + } + + @Test + public void testValidateAdminToken(){ + loginCheck.validateAdminToken(); + } + + @Test + public void testOnValidateTokenFailureFailed(){ + loginCheck.onValidateTokenFailure(new RuntimeException()); + } + + @Test + public void testLoginRedirect(){ + loginCheck.loginRedirect(); + } + + @Test + public void testOnLoginReqSuccess(){ + loginCheck.onLoginReq(null, null, null, response); + } + + @Test + public void testOnLoginReq(){ + response.setStatus(300); + loginCheck.onLoginReq(null, null, null, response); + } + + @Test + public void testOnLoginFailure() { + loginCheck.onLoginFailure(null); + } + + @Test + public void testOnLogoutSuccess() { + loginCheck.onLogoutSuccess(null, null, response); + } + + @Test + public void testOnLogoutFailure() { + loginCheck.onLogoutFailure(new RuntimeException()); + } + + @Test + public void testOnValidateTokenSuccess() { + loginCheck.onValidateTokenSuccess(request, response); + } + + @Test + public void testOnValidateTokenFailure() { + Cookie[] cookies1 = new Cookie[1]; + Cookie cookie = new Cookie("id_token", "eyJhbGciOiJSUzI1NiIsInR5cCIgO"); + cookies1[0] = cookie; + Mockito.when(request.getCookies()).thenReturn(cookies1); + loginCheck.onValidateTokenSuccess(request, response); + } + +} diff --git a/resident/resident-service/src/test/java/io/mosip/resident/batch/CredentialStatusUpdateBatchJobTest.java b/resident/resident-service/src/test/java/io/mosip/resident/batch/CredentialStatusUpdateBatchJobTest.java index f69a461fce9..9fc522d006b 100644 --- a/resident/resident-service/src/test/java/io/mosip/resident/batch/CredentialStatusUpdateBatchJobTest.java +++ b/resident/resident-service/src/test/java/io/mosip/resident/batch/CredentialStatusUpdateBatchJobTest.java @@ -1,19 +1,21 @@ package io.mosip.resident.batch; -import static io.mosip.resident.constant.EventStatusFailure.FAILED; -import static io.mosip.resident.constant.EventStatusInProgress.IN_TRANSIT; -import static io.mosip.resident.constant.EventStatusInProgress.ISSUED; -import static io.mosip.resident.constant.EventStatusInProgress.NEW; -import static io.mosip.resident.constant.EventStatusInProgress.PAYMENT_CONFIRMED; -import static io.mosip.resident.constant.EventStatusInProgress.PRINTING; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyList; -import static org.mockito.Mockito.when; - -import java.util.List; -import java.util.Map; -import java.util.UUID; - +import io.mosip.kernel.core.exception.ServiceError; +import io.mosip.kernel.core.http.ResponseWrapper; +import io.mosip.resident.constant.RequestType; +import io.mosip.resident.constant.ResidentErrorCode; +import io.mosip.resident.controller.ResidentController; +import io.mosip.resident.dto.IdentityDTO; +import io.mosip.resident.dto.RegStatusCheckResponseDTO; +import io.mosip.resident.entity.ResidentTransactionEntity; +import io.mosip.resident.exception.ApisResourceAccessException; +import io.mosip.resident.exception.ResidentServiceCheckedException; +import io.mosip.resident.helper.CredentialStatusUpdateHelper; +import io.mosip.resident.repository.ResidentTransactionRepository; +import io.mosip.resident.service.IdentityService; +import io.mosip.resident.service.NotificationService; +import io.mosip.resident.service.ResidentService; +import io.mosip.resident.util.ResidentServiceRestClient; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -30,21 +32,19 @@ import org.springframework.test.util.ReflectionTestUtils; import org.springframework.web.context.WebApplicationContext; -import io.mosip.kernel.core.exception.ServiceError; -import io.mosip.kernel.core.http.ResponseWrapper; -import io.mosip.resident.constant.RequestType; -import io.mosip.resident.constant.ResidentErrorCode; -import io.mosip.resident.controller.ResidentController; -import io.mosip.resident.dto.IdentityDTO; -import io.mosip.resident.dto.RegStatusCheckResponseDTO; -import io.mosip.resident.entity.ResidentTransactionEntity; -import io.mosip.resident.exception.ApisResourceAccessException; -import io.mosip.resident.exception.ResidentServiceCheckedException; -import io.mosip.resident.repository.ResidentTransactionRepository; -import io.mosip.resident.service.IdentityService; -import io.mosip.resident.service.NotificationService; -import io.mosip.resident.service.ResidentService; -import io.mosip.resident.util.ResidentServiceRestClient; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import static io.mosip.resident.constant.EventStatusFailure.FAILED; +import static io.mosip.resident.constant.EventStatusInProgress.IN_TRANSIT; +import static io.mosip.resident.constant.EventStatusInProgress.ISSUED; +import static io.mosip.resident.constant.EventStatusInProgress.NEW; +import static io.mosip.resident.constant.EventStatusInProgress.PAYMENT_CONFIRMED; +import static io.mosip.resident.constant.EventStatusInProgress.PRINTING; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyList; +import static org.mockito.Mockito.when; /** * @author Kamesh Shekhar Prasad @@ -79,11 +79,14 @@ public class CredentialStatusUpdateBatchJobTest { @Mock private ResidentService residentService; + @Mock + private CredentialStatusUpdateHelper credentialStatusUpdateHelper; + @Before public void init() { - ReflectionTestUtils.setField(job, "publicUrl", "http://localhost"); - ReflectionTestUtils.setField(job, "statusCodes", "NEW,ISSUED,RECEIVED,PRINTING,FAILED,CARD_DELIVERED"); - ReflectionTestUtils.setField(job, "requestTypeCodes", "VID_CARD_DOWNLOAD,ORDER_PHYSICAL_CARD"); + //ReflectionTestUtils.setField(job, "publicUrl", "http://localhost"); + ReflectionTestUtils.setField(job, "env", env); + ReflectionTestUtils.setField(job, "requestTypeCodesToProcessInBatchJob", List.of("UPDATE_MY_UIN")); } @Test @@ -99,7 +102,7 @@ public void testTrackAndUpdateNewOrIssuedStatusWithoutRID() throws ResidentServi ResponseWrapper> responseWrapper = new ResponseWrapper<>(); responseWrapper.setResponse(Map.of("requestId", "requestId", "id", "id", "statusCode", "statusCode", "url", "url")); when(residentServiceRestClient.getApi(any(), anyList(), anyList(), anyList(), any())).thenReturn(responseWrapper); - when(repo.findByStatusCodeInAndRequestTypeCodeInOrderByCrDtimesAsc(anyList(), anyList())).thenReturn(List.of(txn)); + when(repo.findByStatusCodeInAndRequestTypeCodeInAndCredentialRequestIdIsNotNullOrderByCrDtimesAsc(anyList(), anyList())).thenReturn(List.of(txn)); job.scheduleCredentialStatusUpdateJob(); } @@ -116,7 +119,7 @@ public void testTrackAndUpdateNewOrIssuedStatusWithoutRIDException() throws Resi ResponseWrapper> responseWrapper = new ResponseWrapper<>(); responseWrapper.setResponse(Map.of("requestId", "requestId", "id", "id", "statusCode", "statusCode", "url", "url")); when(residentServiceRestClient.getApi(any(), anyList(), anyList(), anyList(), any())).thenThrow(new ApisResourceAccessException()); - when(repo.findByStatusCodeInAndRequestTypeCodeInOrderByCrDtimesAsc(anyList(), anyList())).thenReturn(List.of(txn)); + when(repo.findByStatusCodeInAndRequestTypeCodeInAndCredentialRequestIdIsNotNullOrderByCrDtimesAsc(anyList(), anyList())).thenReturn(List.of(txn)); job.scheduleCredentialStatusUpdateJob(); } @@ -132,7 +135,7 @@ public void testScheduleCredentialStatusUpdateJobVidCardDownload() throws ApisRe ResponseWrapper> responseWrapper = new ResponseWrapper<>(); responseWrapper.setResponse(Map.of("requestId", "requestId", "id", "id", "statusCode", "statusCode", "url", "url")); when(residentServiceRestClient.getApi(any(), anyList(), anyList(), anyList(), any())).thenReturn(responseWrapper); - when(repo.findByStatusCodeInAndRequestTypeCodeInOrderByCrDtimesAsc(anyList(), anyList())).thenReturn(List.of(txn)); + when(repo.findByStatusCodeInAndRequestTypeCodeInAndCredentialRequestIdIsNotNullOrderByCrDtimesAsc(anyList(), anyList())).thenReturn(List.of(txn)); job.scheduleCredentialStatusUpdateJob(); } @@ -149,7 +152,7 @@ public void testScheduleCredentialStatusUpdateJobVidCardDownloadFailed() throws responseWrapper.setErrors(List.of(new ServiceError(ResidentErrorCode.UNKNOWN_EXCEPTION.getErrorCode(), ResidentErrorCode.UNKNOWN_EXCEPTION.getErrorMessage()))); when(residentServiceRestClient.getApi(any(), anyList(), anyList(), anyList(), any())).thenReturn(responseWrapper); - when(repo.findByStatusCodeInAndRequestTypeCodeInOrderByCrDtimesAsc(anyList(), anyList())).thenReturn(List.of(txn)); + when(repo.findByStatusCodeInAndRequestTypeCodeInAndCredentialRequestIdIsNotNullOrderByCrDtimesAsc(anyList(), anyList())).thenReturn(List.of(txn)); job.scheduleCredentialStatusUpdateJob(); } @@ -165,7 +168,7 @@ public void testScheduleCredentialStatusUpdateJobVidCardDownloadFailedApiResourc ResponseWrapper> responseWrapper = new ResponseWrapper<>(); responseWrapper.setResponse(Map.of("requestId", "requestId", "id", "id", "statusCode", "statusCode", "url", "url")); when(residentServiceRestClient.getApi(any(), anyList(), anyList(), anyList(), any())).thenThrow(new ApisResourceAccessException()); - when(repo.findByStatusCodeInAndRequestTypeCodeInOrderByCrDtimesAsc(anyList(), anyList())).thenReturn(List.of(txn)); + when(repo.findByStatusCodeInAndRequestTypeCodeInAndCredentialRequestIdIsNotNullOrderByCrDtimesAsc(anyList(), anyList())).thenReturn(List.of(txn)); job.scheduleCredentialStatusUpdateJob(); } @@ -181,7 +184,7 @@ public void updateOrderPhysicalCardTxnStatusTest() throws ApisResourceAccessExce ResponseWrapper> responseWrapper = new ResponseWrapper<>(); responseWrapper.setResponse(Map.of("requestId", "requestId", "id", "id", "statusCode", "statusCode", "url", "url")); when(residentServiceRestClient.getApi(any(), anyList(), anyList(), anyList(), any())).thenReturn(responseWrapper); - when(repo.findByStatusCodeInAndRequestTypeCodeInOrderByCrDtimesAsc(anyList(), anyList())).thenReturn(List.of(txn)); + when(repo.findByStatusCodeInAndRequestTypeCodeInAndCredentialRequestIdIsNotNullOrderByCrDtimesAsc(anyList(), anyList())).thenReturn(List.of(txn)); job.scheduleCredentialStatusUpdateJob(); } @@ -199,7 +202,7 @@ public void updateOrderPhysicalCardTxnStatusCodePrintingTest() throws ApisResour ResponseWrapper> responseWrapper = new ResponseWrapper<>(); responseWrapper.setResponse(Map.of("requestId", "requestId", "id", "id", "statusCode", "statusCode", "url", "url")); when(residentServiceRestClient.getApi(any(), anyList(), anyList(), anyList(), any())).thenReturn(responseWrapper); - when(repo.findByStatusCodeInAndRequestTypeCodeInOrderByCrDtimesAsc(anyList(), anyList())).thenReturn(List.of(txn)); + when(repo.findByStatusCodeInAndRequestTypeCodeInAndCredentialRequestIdIsNotNullOrderByCrDtimesAsc(anyList(), anyList())).thenReturn(List.of(txn)); job.scheduleCredentialStatusUpdateJob(); } @@ -217,7 +220,7 @@ public void updateOrderPhysicalCardTxnStatusCodeFailedTest() throws ApisResource ResponseWrapper> responseWrapper = new ResponseWrapper<>(); responseWrapper.setResponse(Map.of("requestId", "requestId", "id", "id", "statusCode", FAILED.name(), "url", "url")); when(residentServiceRestClient.getApi(any(), anyList(), anyList(), anyList(), any())).thenReturn(responseWrapper); - when(repo.findByStatusCodeInAndRequestTypeCodeInOrderByCrDtimesAsc(anyList(), anyList())).thenReturn(List.of(txn)); + when(repo.findByStatusCodeInAndRequestTypeCodeInAndCredentialRequestIdIsNotNullOrderByCrDtimesAsc(anyList(), anyList())).thenReturn(List.of(txn)); job.scheduleCredentialStatusUpdateJob(); } @@ -235,7 +238,7 @@ public void updateOrderPhysicalCardTxnStatusCodeFailedTestApiResourceException() ResponseWrapper> responseWrapper = new ResponseWrapper<>(); responseWrapper.setResponse(Map.of("requestId", "requestId", "id", "id", "statusCode", FAILED.name(), "url", "url")); when(residentServiceRestClient.getApi(any(), anyList(), anyList(), anyList(), any())).thenThrow(new ApisResourceAccessException()); - when(repo.findByStatusCodeInAndRequestTypeCodeInOrderByCrDtimesAsc(anyList(), anyList())).thenReturn(List.of(txn)); + when(repo.findByStatusCodeInAndRequestTypeCodeInAndCredentialRequestIdIsNotNullOrderByCrDtimesAsc(anyList(), anyList())).thenReturn(List.of(txn)); job.scheduleCredentialStatusUpdateJob(); } @@ -254,7 +257,7 @@ public void updateOrderPhysicalCardTxnStatusCodeFailedTest1() throws ApisResourc responseWrapper.setErrors(List.of(new ServiceError(ResidentErrorCode.UNKNOWN_EXCEPTION.getErrorCode(), ResidentErrorCode.UNKNOWN_EXCEPTION.getErrorMessage()))); when(residentServiceRestClient.getApi(any(), anyList(), anyList(), anyList(), any())).thenReturn(responseWrapper); - when(repo.findByStatusCodeInAndRequestTypeCodeInOrderByCrDtimesAsc(anyList(), anyList())).thenReturn(List.of(txn)); + when(repo.findByStatusCodeInAndRequestTypeCodeInAndCredentialRequestIdIsNotNullOrderByCrDtimesAsc(anyList(), anyList())).thenReturn(List.of(txn)); job.scheduleCredentialStatusUpdateJob(); } @@ -272,7 +275,7 @@ public void testUpdateShareCredentialWithPartnerTxnStatus() throws ApisResourceA ResponseWrapper> responseWrapper = new ResponseWrapper<>(); responseWrapper.setResponse(Map.of("requestId", "requestId", "id", "id", "statusCode", "statusCode", "url", "url")); when(residentServiceRestClient.getApi(any(), anyList(), anyList(), anyList(), any())).thenReturn(responseWrapper); - when(repo.findByStatusCodeInAndRequestTypeCodeInOrderByCrDtimesAsc(anyList(), anyList())).thenReturn(List.of(txn)); + when(repo.findByStatusCodeInAndRequestTypeCodeInAndCredentialRequestIdIsNotNullOrderByCrDtimesAsc(anyList(), anyList())).thenReturn(List.of(txn)); job.scheduleCredentialStatusUpdateJob(); } @@ -290,7 +293,7 @@ public void testUpdateShareCredentialWithPartnerTxnStatusFailed() throws ApisRes ResponseWrapper> responseWrapper = new ResponseWrapper<>(); responseWrapper.setResponse(Map.of("requestId", "requestId", "id", "id", "statusCode", FAILED.name(), "url", "url")); when(residentServiceRestClient.getApi(any(), anyList(), anyList(), anyList(), any())).thenReturn(responseWrapper); - when(repo.findByStatusCodeInAndRequestTypeCodeInOrderByCrDtimesAsc(anyList(), anyList())).thenReturn(List.of(txn)); + when(repo.findByStatusCodeInAndRequestTypeCodeInAndCredentialRequestIdIsNotNullOrderByCrDtimesAsc(anyList(), anyList())).thenReturn(List.of(txn)); job.scheduleCredentialStatusUpdateJob(); } @@ -303,12 +306,12 @@ public void testUpdateShareCredentialWithPartnerTxnStatusFailedApiResourceExcept txn.setStatusCode(FAILED.name()); txn.setRequestTrnId("123"); txn.setIndividualId("123"); - txn.setRequestTypeCode(RequestType.SHARE_CRED_WITH_PARTNER.name()); + txn.setRequestTypeCode(RequestType.UPDATE_MY_UIN.name()); txn.setCredentialRequestId(UUID.randomUUID().toString()); ResponseWrapper> responseWrapper = new ResponseWrapper<>(); responseWrapper.setResponse(Map.of("requestId", "requestId", "id", "id", "statusCode", FAILED.name(), "url", "url")); when(residentServiceRestClient.getApi(any(), anyList(), anyList(), anyList(), any())).thenThrow(new ApisResourceAccessException()); - when(repo.findByStatusCodeInAndRequestTypeCodeInOrderByCrDtimesAsc(anyList(), anyList())).thenReturn(List.of(txn)); + when(repo.findByStatusCodeInAndRequestTypeCodeInAndCredentialRequestIdIsNotNullOrderByCrDtimesAsc(anyList(), anyList())).thenReturn(List.of(txn)); job.scheduleCredentialStatusUpdateJob(); } @@ -326,16 +329,18 @@ public void testUpdateUinDemoDataUpdateTxnStatus() throws ApisResourceAccessExce txn.setCredentialRequestId(UUID.randomUUID().toString()); ResponseWrapper> responseWrapper = new ResponseWrapper<>(); responseWrapper.setResponse(Map.of("requestId", "requestId", "id", "id", "statusCode", "statusCode", "url", "url")); + responseWrapper.setErrors(List.of(new ServiceError(ResidentErrorCode.TEMPLATE_EXCEPTION.getErrorCode(), + ResidentErrorCode.TEMPLATE_EXCEPTION.getErrorMessage()))); when(residentServiceRestClient.getApi(any(), anyList(), anyList(), anyList(), any())).thenReturn(responseWrapper); IdentityDTO identityDTO = new IdentityDTO(); identityDTO.setFullName("kamesh"); when(identityService.getIdentity(Mockito.anyString())).thenReturn(identityDTO); - when(repo.findByStatusCodeInAndRequestTypeCodeInOrderByCrDtimesAsc(anyList(), anyList())).thenReturn(List.of(txn)); + when(repo.findByStatusCodeInAndRequestTypeCodeInAndCredentialRequestIdIsNotNullOrderByCrDtimesAsc(anyList(), anyList())).thenReturn(List.of(txn)); job.scheduleCredentialStatusUpdateJob(); } @Test - public void testUpdateUinDemoDataUpdateTxnStatusNullAid() throws ApisResourceAccessException, ResidentServiceCheckedException { + public void testUpdateUinDemoDataSuccess() throws ApisResourceAccessException, ResidentServiceCheckedException { ResidentTransactionEntity txn = new ResidentTransactionEntity(); txn.setAid("aid"); txn.setEventId("eventId"); @@ -355,7 +360,31 @@ public void testUpdateUinDemoDataUpdateTxnStatusNullAid() throws ApisResourceAcc RegStatusCheckResponseDTO regStatusCheckResponseDTO = new RegStatusCheckResponseDTO(); regStatusCheckResponseDTO.setRidStatus("123"); when(residentService.getRidStatus(Mockito.anyString())).thenReturn(regStatusCheckResponseDTO); - when(repo.findByStatusCodeInAndRequestTypeCodeInOrderByCrDtimesAsc(anyList(), anyList())).thenReturn(List.of(txn)); + when(repo.findByStatusCodeInAndRequestTypeCodeInAndCredentialRequestIdIsNotNullOrderByCrDtimesAsc(anyList(), anyList())).thenReturn(List.of(txn)); + job.scheduleCredentialStatusUpdateJob(); + } + + @Test + public void testUpdateUinDemoDataFailure() throws ApisResourceAccessException, ResidentServiceCheckedException { + ResidentTransactionEntity txn = new ResidentTransactionEntity(); + txn.setAid("aid"); + txn.setEventId("eventId"); + txn.setRefIdType("UIN"); + txn.setStatusCode(NEW.name()); + txn.setRequestTrnId("123"); + txn.setIndividualId("123"); + txn.setAid("123"); + txn.setRequestTypeCode(RequestType.UPDATE_MY_UIN.name()); + ResponseWrapper> responseWrapper = new ResponseWrapper<>(); + responseWrapper.setResponse(Map.of("requestId", "requestId", "id", "id", "statusCode", "statusCode", "url", "url")); + when(residentServiceRestClient.getApi(any(), anyList(), anyList(), anyList(), any())).thenReturn(responseWrapper); + IdentityDTO identityDTO = new IdentityDTO(); + identityDTO.setFullName("kamesh"); + when(identityService.getIdentity(Mockito.anyString())).thenThrow(new ResidentServiceCheckedException()); + RegStatusCheckResponseDTO regStatusCheckResponseDTO = new RegStatusCheckResponseDTO(); + regStatusCheckResponseDTO.setRidStatus("123"); + when(residentService.getRidStatus(Mockito.anyString())).thenReturn(regStatusCheckResponseDTO); + when(repo.findByStatusCodeInAndRequestTypeCodeInAndCredentialRequestIdIsNotNullOrderByCrDtimesAsc(anyList(), anyList())).thenReturn(List.of(txn)); job.scheduleCredentialStatusUpdateJob(); } } diff --git a/resident/resident-service/src/test/java/io/mosip/resident/test/config/ResidentServiceConfigTest.java b/resident/resident-service/src/test/java/io/mosip/resident/config/ResidentServiceConfigTest.java similarity index 81% rename from resident/resident-service/src/test/java/io/mosip/resident/test/config/ResidentServiceConfigTest.java rename to resident/resident-service/src/test/java/io/mosip/resident/config/ResidentServiceConfigTest.java index 11ffde0b3c0..f329a7762fd 100644 --- a/resident/resident-service/src/test/java/io/mosip/resident/test/config/ResidentServiceConfigTest.java +++ b/resident/resident-service/src/test/java/io/mosip/resident/config/ResidentServiceConfigTest.java @@ -1,4 +1,4 @@ -package io.mosip.resident.test.config; +package io.mosip.resident.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.mock.mockito.MockBean; @@ -18,6 +18,8 @@ import io.mosip.kernel.idvalidator.rid.impl.RidValidatorImpl; import io.mosip.kernel.idvalidator.uin.impl.UinValidatorImpl; import io.mosip.kernel.idvalidator.vid.impl.VidValidatorImpl; +import io.mosip.preregistration.application.service.TransliterationService; +import io.mosip.preregistration.application.service.util.TransliterationServiceUtil; import io.mosip.resident.repository.ResidentTransactionRepository; @Configuration @@ -34,6 +36,12 @@ public class ResidentServiceConfigTest { @MockBean private PacketWriter packetWriter; + @MockBean + private TransliterationService transliterationService; + + @MockBean + private TransliterationServiceUtil transliterationServiceUtil; + @Bean @Primary public VidValidator vidValidator1() { diff --git a/resident/resident-service/src/test/java/io/mosip/resident/test/config/TestSecurityConfig.java b/resident/resident-service/src/test/java/io/mosip/resident/config/TestSecurityConfig.java similarity index 96% rename from resident/resident-service/src/test/java/io/mosip/resident/test/config/TestSecurityConfig.java rename to resident/resident-service/src/test/java/io/mosip/resident/config/TestSecurityConfig.java index 0fa5a8e420c..65b2b197889 100644 --- a/resident/resident-service/src/test/java/io/mosip/resident/test/config/TestSecurityConfig.java +++ b/resident/resident-service/src/test/java/io/mosip/resident/config/TestSecurityConfig.java @@ -1,4 +1,10 @@ -package io.mosip.resident.test.config; +package io.mosip.resident.config; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import javax.servlet.http.HttpServletResponse; import java.util.ArrayList; import java.util.Arrays; diff --git a/resident/resident-service/src/test/java/io/mosip/resident/controller/AcknowledgmentControllerTest.java b/resident/resident-service/src/test/java/io/mosip/resident/controller/AcknowledgmentControllerTest.java new file mode 100644 index 00000000000..697e7a5eb5a --- /dev/null +++ b/resident/resident-service/src/test/java/io/mosip/resident/controller/AcknowledgmentControllerTest.java @@ -0,0 +1,137 @@ +package io.mosip.resident.controller; + +import static org.junit.Assert.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.when; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.nio.charset.StandardCharsets; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.core.io.InputStreamResource; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.util.ReflectionTestUtils; +import org.springframework.web.client.RestTemplate; + +import io.mosip.resident.constant.RequestType; +import io.mosip.resident.constant.ResidentErrorCode; +import io.mosip.resident.exception.InvalidInputException; +import io.mosip.resident.exception.ResidentServiceCheckedException; +import io.mosip.resident.exception.ResidentServiceException; +import io.mosip.resident.helper.ObjectStoreHelper; +import io.mosip.resident.service.AcknowledgementService; +import io.mosip.resident.service.IdAuthService; +import io.mosip.resident.service.impl.IdentityServiceImpl; +import io.mosip.resident.service.impl.ResidentVidServiceImpl; +import io.mosip.resident.util.AuditUtil; +import io.mosip.resident.util.TemplateUtil; +import io.mosip.resident.util.Utility; +import io.mosip.resident.validator.RequestValidator; + +/** + * Acknowledgment Controller Test + * Note: This class is used to test the Acknowledgment Controller + * @author Kamesh Shekhar Prasad + */ + +@RunWith(MockitoJUnitRunner.class) +@ContextConfiguration +public class AcknowledgmentControllerTest { + private static final String LOCALE_EN_US = "en-US"; + + @InjectMocks + private AcknowledgementController acknowledgementController; + + @Mock + private AuditUtil auditUtil; + + @Mock + private RequestValidator requestValidator; + + @Mock + private AcknowledgementService acknowledgementService; + + @Mock + private IdentityServiceImpl identityService; + + @Mock + private ObjectStoreHelper objectStore; + + @Mock + private ResidentVidServiceImpl residentVidService; + + @Mock + private TemplateUtil templateUtil; + + @MockBean + @Qualifier("selfTokenRestTemplate") + private RestTemplate residentRestTemplate; + + @Mock + private IdAuthService idAuthService; + + @Mock + private Utility utility; + + private ResponseEntity responseEntity; + + @Before + public void setup() throws Exception { + String eventId = "bf42d76e-b02e-48c8-a17a-6bb842d85ea9"; + byte[] pdfBytes = "test".getBytes(StandardCharsets.UTF_8); + InputStreamResource resource = new InputStreamResource(new ByteArrayInputStream(pdfBytes)); + responseEntity = ResponseEntity.ok().contentType(MediaType.parseMediaType("application/pdf")) + .header("Content-Disposition", "attachment; filename=\"" + + eventId + ".pdf\"") + .body(resource); + } + + @Test + public void testCreateRequestGenerationSuccess() throws Exception { + when(templateUtil.getFeatureName(anyString(), anyString())).thenReturn(RequestType.AUTHENTICATION_REQUEST.toString()); + when(acknowledgementService.getAcknowledgementPDF(anyString(), anyString(), Mockito.anyInt(), anyString())).thenReturn("test".getBytes()); + ResponseEntity response = acknowledgementController.getAcknowledgement("bf42d76e-b02e-48c8-a17a-6bb842d85ea9", "eng", 0, LOCALE_EN_US); + assertEquals(response.getStatusCode(), responseEntity.getStatusCode()); + } + + @Test(expected = ResidentServiceCheckedException.class) + public void testGetAcknowledgementFailure() throws ResidentServiceCheckedException, IOException { + ReflectionTestUtils.setField(acknowledgementController, "ackDownloadId", "ack.id"); + when(acknowledgementService.getAcknowledgementPDF(anyString(), anyString(), Mockito.anyInt(), anyString())) + .thenThrow(new ResidentServiceCheckedException(ResidentErrorCode.EVENT_STATUS_NOT_FOUND)); + ResponseEntity response = acknowledgementController.getAcknowledgement("bf42d76e-b02e-48c8-a17a-6bb842d85ea9", "eng", 0, LOCALE_EN_US); + assertEquals(response.getStatusCode(), responseEntity.getStatusCode()); + } + + @Test(expected = ResidentServiceException.class) + public void testGetAcknowledgementFailureResidentServiceException() throws ResidentServiceCheckedException, IOException { + doThrow(new ResidentServiceException("error", "Error message")). + when(requestValidator).validateEventIdLanguageCode(any(), any()); + ReflectionTestUtils.setField(acknowledgementController, "ackDownloadId", "ack.id"); + ResponseEntity response = acknowledgementController.getAcknowledgement("bf42d76e-b02e-48c8-a17a-6bb842d85ea9", "eng", 0, LOCALE_EN_US); + assertEquals(response.getStatusCode(), responseEntity.getStatusCode()); + } + + @Test(expected = ResidentServiceException.class) + public void testGetAcknowledgementFailureInvalidInputException() throws ResidentServiceCheckedException, IOException { + doThrow(new InvalidInputException()). + when(requestValidator).validateEventIdLanguageCode(any(), any()); + ReflectionTestUtils.setField(acknowledgementController, "ackDownloadId", "ack.id"); + ResponseEntity response = acknowledgementController.getAcknowledgement("bf42d76e-b02e-48c8-a17a-6bb842d85ea9", "eng", 0, LOCALE_EN_US); + assertEquals(response.getStatusCode(), responseEntity.getStatusCode()); + } + +} diff --git a/resident/resident-service/src/test/java/io/mosip/resident/controller/AuthTransactionCallbackControllerTest.java b/resident/resident-service/src/test/java/io/mosip/resident/controller/AuthTransactionCallbackControllerTest.java new file mode 100644 index 00000000000..f054bacbd54 --- /dev/null +++ b/resident/resident-service/src/test/java/io/mosip/resident/controller/AuthTransactionCallbackControllerTest.java @@ -0,0 +1,140 @@ +package io.mosip.resident.controller; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.verify; + +import java.time.LocalDateTime; +import java.util.Map; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.http.MediaType; +import org.springframework.test.context.TestPropertySource; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.client.RestTemplate; + +import com.fasterxml.jackson.databind.ObjectMapper; + +import io.mosip.kernel.core.websub.model.Event; +import io.mosip.kernel.core.websub.model.EventModel; +import io.mosip.resident.exception.ResidentServiceCheckedException; +import io.mosip.resident.exception.ResidentServiceException; +import io.mosip.resident.helper.ObjectStoreHelper; +import io.mosip.resident.service.AuthTransactionCallBackService; +import io.mosip.resident.service.DocumentService; +import io.mosip.resident.service.IdAuthService; +import io.mosip.resident.service.ProxyIdRepoService; +import io.mosip.resident.service.ResidentVidService; +import io.mosip.resident.service.VerificationService; +import io.mosip.resident.service.impl.ResidentServiceImpl; +import io.mosip.resident.test.ResidentTestBootApplication; +import io.mosip.resident.util.AuditUtil; + +/** + * Web-Sub Update Controller Test Note: This class is used to test the Auth + * transaction callback controller + * + * @author Kamesh Shekhar Prasad + */ + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = ResidentTestBootApplication.class) +@AutoConfigureMockMvc +@TestPropertySource(locations = "classpath:application.properties") +public class AuthTransactionCallbackControllerTest { + + @MockBean + @Qualifier("selfTokenRestTemplate") + private RestTemplate residentRestTemplate; + + @Mock + private AuditUtil audit; + + @InjectMocks + AuthTransactionCallbackController authTransactionCallbackController; + + @MockBean + private AuthTransactionCallBackService authTransactionCallBackService; + + @Autowired + private MockMvc mockMvc; + + @MockBean + private VerificationService verificationService; + + @MockBean + private IdAuthService idAuthService; + + @MockBean + private ResidentVidService vidService; + + @MockBean + private DocumentService docService; + + @MockBean + private ObjectStoreHelper objectStore; + + @MockBean + private ResidentServiceImpl residentService; + + @MockBean + private ProxyIdRepoService proxyIdRepoService; + + @InjectMocks + VerificationController verificationController; + + @Autowired + private ObjectMapper objectMapper; + + private EventModel eventModel; + + @Before + public void setup() throws Exception { + + MockitoAnnotations.initMocks(this); + this.mockMvc = MockMvcBuilders.standaloneSetup(authTransactionCallbackController).build(); + eventModel = new EventModel(); + Event event = new Event(); + event.setTransactionId("1234"); + Map partnerIdMap = new java.util.HashMap<>(); + partnerIdMap.put("olv_partner_id", "mpartner-default-auth"); + event.setData(partnerIdMap); + + eventModel.setEvent(event); + eventModel.setTopic("AUTH_TYPE_STATUS_UPDATE_ACK"); + eventModel.setPublishedOn(String.valueOf(LocalDateTime.now())); + eventModel.setPublisher("AUTH_TYPE_STATUS_UPDATE_ACK"); + } + + @Test + public void testCreateRequestGenerationSuccess() throws Exception { + authTransactionCallbackController.authTransactionCallback(objectMapper.convertValue(eventModel, Map.class)); + mockMvc.perform((MockMvcRequestBuilders.post("/callback/authTransaction")) + .contentType(MediaType.APPLICATION_JSON).content(eventModel.toString())).andReturn(); + verify(authTransactionCallBackService).updateAuthTransactionCallBackService(any()); + } + + @Test(expected = ResidentServiceException.class) + public void testCreateRequestGenerationFailure() throws Exception { + doThrow(new ResidentServiceCheckedException("error", "Error message")).when(authTransactionCallBackService) + .updateAuthTransactionCallBackService(any()); + authTransactionCallbackController.authTransactionCallback(objectMapper.convertValue(eventModel, Map.class)); + mockMvc.perform((MockMvcRequestBuilders.post("/callback/authTransaction")) + .contentType(MediaType.APPLICATION_JSON).content(eventModel.toString())).andReturn(); + verify(authTransactionCallBackService).updateAuthTransactionCallBackService(any()); + } + +} diff --git a/resident/resident-service/src/test/java/io/mosip/resident/controller/DocumentControllerTest.java b/resident/resident-service/src/test/java/io/mosip/resident/controller/DocumentControllerTest.java index ef72b323715..a766b3a4ef2 100644 --- a/resident/resident-service/src/test/java/io/mosip/resident/controller/DocumentControllerTest.java +++ b/resident/resident-service/src/test/java/io/mosip/resident/controller/DocumentControllerTest.java @@ -1,7 +1,10 @@ package io.mosip.resident.controller; +import static io.mosip.resident.constant.ResidentErrorCode.VIRUS_SCAN_FAILED; import static org.junit.Assert.assertEquals; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.when; import java.io.IOException; @@ -21,7 +24,9 @@ import io.mosip.resident.dto.DocumentDTO; import io.mosip.resident.dto.DocumentResponseDTO; import io.mosip.resident.dto.ResponseDTO; +import io.mosip.resident.exception.InvalidInputException; import io.mosip.resident.exception.ResidentServiceCheckedException; +import io.mosip.resident.exception.ResidentServiceException; import io.mosip.resident.service.DocumentService; import io.mosip.resident.util.AuditUtil; import io.mosip.resident.validator.DocumentValidator; @@ -57,12 +62,29 @@ public void testUploadDocumentsSuccess() throws ResidentServiceCheckedException, } @Test - public void testUploadDocumentsFailed() throws ResidentServiceCheckedException, IOException { + public void testUploadDocumentsFailedResidentServiceCheckedException() throws ResidentServiceCheckedException, IOException { when(service.uploadDocument(any(), any(), any())).thenThrow(new ResidentServiceCheckedException("", "")); ResponseWrapper uploadDocuments = controller.uploadDocuments("", new MockMultipartFile("name", "abc".getBytes()), "poi", "proof", "eng", "abc123"); assertEquals(uploadDocuments.getErrors().get(0).getErrorCode(), ""); assertEquals(uploadDocuments.getErrors().get(0).getMessage(), ""); } + + @Test + public void testUploadDocumentsFailedResidentServiceException() throws IOException { + doThrow(new ResidentServiceException(VIRUS_SCAN_FAILED.getErrorCode(), + VIRUS_SCAN_FAILED.getErrorMessage())).when(validator).scanForViruses(any()); + ResponseWrapper uploadDocuments = controller.uploadDocuments("", new MockMultipartFile("name", "abc".getBytes()), "poi", "proof", "eng", "abc123"); + assertEquals(uploadDocuments.getErrors().get(0).getErrorCode(), uploadDocuments.getErrors().get(0).getErrorCode()); + assertEquals(uploadDocuments.getErrors().get(0).getMessage(), uploadDocuments.getErrors().get(0).getMessage()); + } + + @Test + public void testUploadDocumentsFailedInvalidInputException() throws IOException, ResidentServiceCheckedException { + doThrow(new InvalidInputException()).when(validator).validateRequest(anyString(), anyString(), anyString(), anyString()); + ResponseWrapper uploadDocuments = controller.uploadDocuments("", new MockMultipartFile("name", "abc".getBytes()), "poi", "proof", "eng", "abc123"); + assertEquals(uploadDocuments.getErrors().get(0).getErrorCode(), uploadDocuments.getErrors().get(0).getErrorCode()); + assertEquals(uploadDocuments.getErrors().get(0).getMessage(), uploadDocuments.getErrors().get(0).getMessage()); + } @Test public void testGetDocumentsByTransactionIdSuccess() throws ResidentServiceCheckedException { @@ -84,6 +106,14 @@ public void testGetDocumentsByTransactionIdFailed() throws ResidentServiceChecke assertEquals(documentsByTransactionId.getErrors().get(0).getMessage(), ""); } + @Test + public void testGetDocumentsByTransactionIdFailedInvalidInputException() throws IOException, ResidentServiceCheckedException { + doThrow(new InvalidInputException()).when(validator).validateTransactionIdForDocument(anyString()); + ResponseWrapper> documentsByTransactionId = controller.getDocumentsByTransactionId(""); + assertEquals(documentsByTransactionId.getErrors().get(0).getErrorCode(), documentsByTransactionId.getErrors().get(0).getErrorCode()); + assertEquals(documentsByTransactionId.getErrors().get(0).getMessage(), documentsByTransactionId.getErrors().get(0).getMessage()); + } + @Test public void testGetDocumentByDocumentIdSuccess() throws ResidentServiceCheckedException { DocumentDTO response = new DocumentDTO(); @@ -105,6 +135,14 @@ public void testGetDocumentByDocumentIdFailed() throws ResidentServiceCheckedExc assertEquals(documentByDocumentId.getErrors().get(0).getMessage(), ""); } + @Test + public void testGetDocumentByDocumentIdFailedInvalidInputException() { + doThrow(new InvalidInputException()).when(validator).validateDocumentIdAndTransactionId(anyString(), anyString()); + ResponseWrapper documentByDocumentId = controller.getDocumentByDocumentId("", ""); + assertEquals(documentByDocumentId.getErrors().get(0).getErrorCode(), documentByDocumentId.getErrors().get(0).getErrorCode()); + assertEquals(documentByDocumentId.getErrors().get(0).getMessage(), documentByDocumentId.getErrors().get(0).getMessage()); + } + @Test public void testDeleteDocumentsByDocumentIdSuccess() throws ResidentServiceCheckedException { ResponseDTO response = new ResponseDTO(); @@ -120,4 +158,12 @@ public void testDeleteDocumentsByDocumentIdFailed() throws ResidentServiceChecke assertEquals(deleteDocumentsByDocumentId.getErrors().get(0).getErrorCode(), ""); assertEquals(deleteDocumentsByDocumentId.getErrors().get(0).getMessage(), ""); } + + @Test + public void testDeleteDocumentsByDocumentIdFailedInvalidInputException() { + doThrow(new InvalidInputException()).when(validator).validateDocumentIdAndTransactionId(anyString(), anyString()); + ResponseWrapper deleteDocumentsByDocumentId = controller.deleteDocument("", ""); + assertEquals(deleteDocumentsByDocumentId.getErrors().get(0).getErrorCode(), deleteDocumentsByDocumentId.getErrors().get(0).getErrorCode()); + assertEquals(deleteDocumentsByDocumentId.getErrors().get(0).getMessage(), deleteDocumentsByDocumentId.getErrors().get(0).getMessage()); + } } diff --git a/resident/resident-service/src/test/java/io/mosip/resident/controller/DownloadCardControllerTest.java b/resident/resident-service/src/test/java/io/mosip/resident/controller/DownloadCardControllerTest.java new file mode 100644 index 00000000000..dda60562a6a --- /dev/null +++ b/resident/resident-service/src/test/java/io/mosip/resident/controller/DownloadCardControllerTest.java @@ -0,0 +1,234 @@ +package io.mosip.resident.controller; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doThrow; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import java.security.PrivateKey; +import java.security.PublicKey; + +import javax.crypto.SecretKey; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.core.env.Environment; +import org.springframework.http.MediaType; +import org.springframework.test.context.TestPropertySource; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.client.RestTemplate; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +import io.mosip.kernel.core.crypto.spi.CryptoCoreSpec; +import io.mosip.resident.dto.CheckStatusResponseDTO; +import io.mosip.resident.dto.DownloadCardRequestDTO; +import io.mosip.resident.dto.DownloadPersonalizedCardDto; +import io.mosip.resident.dto.MainRequestDTO; +import io.mosip.resident.dto.ResponseWrapper; +import io.mosip.resident.dto.VidDownloadCardResponseDto; +import io.mosip.resident.exception.InvalidInputException; +import io.mosip.resident.helper.ObjectStoreHelper; +import io.mosip.resident.service.DownloadCardService; +import io.mosip.resident.service.ResidentVidService; +import io.mosip.resident.service.impl.IdentityServiceImpl; +import io.mosip.resident.service.impl.ResidentServiceImpl; +import io.mosip.resident.test.ResidentTestBootApplication; +import io.mosip.resident.util.AuditUtil; +import io.mosip.resident.util.Utility; +import io.mosip.resident.validator.RequestValidator; +import reactor.util.function.Tuples; + +/** + * @author Kamesh Shekhar Prasad + * This class is used to test download card api. + */ +@RunWith(SpringRunner.class) +@SpringBootTest(classes = ResidentTestBootApplication.class) +@AutoConfigureMockMvc +@TestPropertySource(locations = "classpath:application.properties") +public class DownloadCardControllerTest { + + @MockBean + private RequestValidator validator; + + @Mock + private AuditUtil audit; + + @Mock + private Environment environment; + + @Mock + private Utility utility; + + @MockBean + private ObjectStoreHelper objectStore; + + + @MockBean + @Qualifier("selfTokenRestTemplate") + private RestTemplate residentRestTemplate; + + @InjectMocks + DownloadCardController downloadCardController; + + @MockBean + DownloadCardService downloadCardService; + + @MockBean + IdentityServiceImpl identityService; + + @Autowired + private MockMvc mockMvc; + + @MockBean + private ResidentVidService vidService; + + @MockBean + private ResidentServiceImpl residentService; + + @MockBean + private CryptoCoreSpec encryptor; + + Gson gson = new GsonBuilder().serializeNulls().create(); + + String reqJson; + + byte[] pdfbytes; + + @Before + public void setup() throws Exception { + MockitoAnnotations.initMocks(this); + this.mockMvc = MockMvcBuilders.standaloneSetup(downloadCardController).build(); + MainRequestDTO downloadCardRequestDTOMainRequestDTO = new MainRequestDTO<>(); + DownloadCardRequestDTO downloadCardRequestDTO = new DownloadCardRequestDTO(); + downloadCardRequestDTO.setIndividualId("7841261580"); + downloadCardRequestDTO.setOtp("111111"); + downloadCardRequestDTO.setTransactionId("1234567890"); + downloadCardRequestDTOMainRequestDTO.setRequest(downloadCardRequestDTO); + downloadCardRequestDTOMainRequestDTO.setId("mosip.resident.download.uin.card"); + reqJson = gson.toJson(downloadCardRequestDTOMainRequestDTO); + pdfbytes = "uin".getBytes(); + Mockito.when(utility.getFileName(Mockito.anyString(), Mockito.anyString(), Mockito.anyInt(), Mockito.anyString())).thenReturn("file"); + Mockito.when(environment.getProperty(Mockito.anyString())).thenReturn("property"); + } + + @Test + public void testGetCardSuccess() throws Exception { + Mockito.when(downloadCardService.getDownloadCardPDF(Mockito.any())).thenReturn(Tuples.of(pdfbytes, "12345")); + mockMvc.perform(MockMvcRequestBuilders.post("/download-card").contentType(MediaType.APPLICATION_JSON_VALUE) + .content(reqJson.getBytes())).andExpect(status().isOk()); + } + + @Test(expected = Exception.class) + public void testGetCardFailed() throws Exception { + pdfbytes = "".getBytes(); + Mockito.when(downloadCardService.getDownloadCardPDF(Mockito.any())).thenReturn(Tuples.of(pdfbytes, "")); + mockMvc.perform(MockMvcRequestBuilders.post("/download-card").contentType(MediaType.APPLICATION_JSON_VALUE) + .content(reqJson.getBytes())).andExpect(status().isOk()); + } + + @Test + public void testDownloadPersonalizedCard() throws Exception { + Mockito.when(downloadCardService.downloadPersonalizedCard(Mockito.any(), Mockito.anyInt(), Mockito.nullable(String.class))).thenReturn(Tuples.of(pdfbytes, "12345")); + MainRequestDTO downloadPersonalizedCardMainRequestDTO = + new MainRequestDTO<>(); + DownloadPersonalizedCardDto downloadPersonalizedCardDto = + new DownloadPersonalizedCardDto(); + downloadPersonalizedCardDto.setHtml("PGh0bWw+PGhlYWQ+PC9oZWFkPjxib2R5Pjx0YWJsZT48dHI+PHRkPk5hbWU8L3RkPjx0ZD5GUjwvdGQ+PC90cj48dHI+PHRkPkRPQjwvdGQ+PHRkPjE5OTIvMDQvMTU8L3RkPjwvdHI+PHRyPjx0ZD5QaG9uZSBOdW1iZXI8L3RkPjx0ZD45ODc2NTQzMjEwPC90ZD48L3RyPjwvdGFibGU+PC9ib2R5PjwvaHRtbD4="); + downloadPersonalizedCardMainRequestDTO.setRequest(downloadPersonalizedCardDto); + reqJson = gson.toJson(downloadPersonalizedCardMainRequestDTO); + mockMvc.perform(MockMvcRequestBuilders.post("/download/personalized-card").contentType(MediaType.APPLICATION_JSON_VALUE) + .content(reqJson.getBytes())).andExpect(status().isOk()); + } + + @Test + public void testDownloadPersonalizedCardFailed() throws Exception { + pdfbytes = "".getBytes(); + Mockito.when(downloadCardService.downloadPersonalizedCard(Mockito.any(), Mockito.anyInt(), Mockito.nullable(String.class))).thenReturn(Tuples.of(pdfbytes, "")); + MainRequestDTO downloadPersonalizedCardMainRequestDTO = + new MainRequestDTO<>(); + DownloadPersonalizedCardDto downloadPersonalizedCardDto = + new DownloadPersonalizedCardDto(); + downloadPersonalizedCardDto.setHtml("PGh0bWw+PGhlYWQ+PC9oZWFkPjxib2R5Pjx0YWJsZT48dHI+PHRkPk5hbWU8L3RkPjx0ZD5GUjwvdGQ+PC90cj48dHI+PHRkPkRPQjwvdGQ+PHRkPjE5OTIvMDQvMTU8L3RkPjwvdHI+PHRyPjx0ZD5QaG9uZSBOdW1iZXI8L3RkPjx0ZD45ODc2NTQzMjEwPC90ZD48L3RyPjwvdGFibGU+PC9ib2R5PjwvaHRtbD4="); + downloadPersonalizedCardMainRequestDTO.setRequest(downloadPersonalizedCardDto); + reqJson = gson.toJson(downloadPersonalizedCardMainRequestDTO); + mockMvc.perform(MockMvcRequestBuilders.post("/download/personalized-card").contentType(MediaType.APPLICATION_JSON_VALUE) + .content(reqJson.getBytes())).andExpect(status().isBadRequest()); + } + + @Test(expected = Exception.class) + public void testDownloadPersonalizedCardInvalidInputException() throws Exception { + doThrow(new InvalidInputException()). + when(validator).validateDownloadPersonalizedCard(any()); + MainRequestDTO downloadPersonalizedCardMainRequestDTO = + new MainRequestDTO<>(); + DownloadPersonalizedCardDto downloadPersonalizedCardDto = + new DownloadPersonalizedCardDto(); + downloadPersonalizedCardDto.setHtml("PGh0bWw+PGhlYWQ+PC9oZWFkPjxib2R5Pjx0YWJsZT48dHI+PHRkPk5hbWU8L3RkPjx0ZD5GUjwvdGQ+PC90cj48dHI+PHRkPkRPQjwvdGQ+PHRkPjE5OTIvMDQvMTU8L3RkPjwvdHI+PHRyPjx0ZD5QaG9uZSBOdW1iZXI8L3RkPjx0ZD45ODc2NTQzMjEwPC90ZD48L3RyPjwvdGFibGU+PC9ib2R5PjwvaHRtbD4="); + downloadPersonalizedCardMainRequestDTO.setRequest(downloadPersonalizedCardDto); + reqJson = gson.toJson(downloadPersonalizedCardMainRequestDTO); + mockMvc.perform(MockMvcRequestBuilders.post("/download/personalized-card").contentType(MediaType.APPLICATION_JSON_VALUE) + .content(reqJson.getBytes())).andExpect(status().isOk()); + } + + @Test + public void testRequestVidCard() throws Exception { + ResponseWrapper vidDownloadCardResponseDtoResponseWrapper = new ResponseWrapper<>(); + VidDownloadCardResponseDto vidDownloadCardResponseDto = new VidDownloadCardResponseDto(); + vidDownloadCardResponseDto.setStatus("success"); + vidDownloadCardResponseDtoResponseWrapper.setResponse(vidDownloadCardResponseDto); + Mockito.when(downloadCardService.getVidCardEventId(Mockito.any(), Mockito.anyInt(), Mockito.nullable(String.class))) + .thenReturn(Tuples.of(vidDownloadCardResponseDtoResponseWrapper, "12345")); + mockMvc.perform(MockMvcRequestBuilders.get("/request-card/vid/9086273859467431")).andExpect(status().isOk()); + } + + @Test(expected = Exception.class) + public void testRequestVidCardFailed() throws Exception { + doThrow(new InvalidInputException()). + when(validator).validateDownloadCardVid(any()); + ResponseWrapper vidDownloadCardResponseDtoResponseWrapper = new ResponseWrapper<>(); + VidDownloadCardResponseDto vidDownloadCardResponseDto = new VidDownloadCardResponseDto(); + vidDownloadCardResponseDto.setStatus("success"); + vidDownloadCardResponseDtoResponseWrapper.setResponse(vidDownloadCardResponseDto); + Mockito.when(downloadCardService.getVidCardEventId(Mockito.any(), Mockito.anyInt(), Mockito.anyString())) + .thenReturn(Tuples.of(vidDownloadCardResponseDtoResponseWrapper, "12345")); + mockMvc.perform(MockMvcRequestBuilders.get("/request-card/vid/9086273859467431")).andExpect(status().isOk()); + } + + @Test + public void testGetStatus() throws Exception { + ResponseWrapper responseWrapper = new ResponseWrapper<>(); + CheckStatusResponseDTO checkStatusResponseDTO = new CheckStatusResponseDTO(); + checkStatusResponseDTO.setAidStatus("process"); + responseWrapper.setResponse(checkStatusResponseDTO); + Mockito.when(downloadCardService.getIndividualIdStatus(Mockito.any())) + .thenReturn(responseWrapper); + mockMvc.perform(MockMvcRequestBuilders.get("/aid-stage/12345")).andExpect(status().isOk()); + } + + @Test(expected = Exception.class) + public void testGetStatusFailed() throws Exception { + ResponseWrapper responseWrapper = new ResponseWrapper<>(); + CheckStatusResponseDTO checkStatusResponseDTO = new CheckStatusResponseDTO(); + checkStatusResponseDTO.setAidStatus("process"); + responseWrapper.setResponse(checkStatusResponseDTO); + Mockito.when(downloadCardService.getIndividualIdStatus(Mockito.any())) + .thenThrow(new InvalidInputException()); + mockMvc.perform(MockMvcRequestBuilders.get("/aid-stage/12345")).andExpect(status().isOk()); + } + +} diff --git a/resident/resident-service/src/test/java/io/mosip/resident/controller/DownloadMasterdataControllerTest.java b/resident/resident-service/src/test/java/io/mosip/resident/controller/DownloadMasterdataControllerTest.java new file mode 100644 index 00000000000..5335d40f0e7 --- /dev/null +++ b/resident/resident-service/src/test/java/io/mosip/resident/controller/DownloadMasterdataControllerTest.java @@ -0,0 +1,184 @@ +package io.mosip.resident.controller; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doThrow; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import java.io.ByteArrayInputStream; +import java.security.PrivateKey; +import java.security.PublicKey; + +import javax.crypto.SecretKey; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.core.env.Environment; +import org.springframework.test.context.TestPropertySource; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.client.RestTemplate; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +import io.mosip.kernel.core.crypto.spi.CryptoCoreSpec; +import io.mosip.resident.dto.DownloadCardRequestDTO; +import io.mosip.resident.dto.MainRequestDTO; +import io.mosip.resident.exception.InvalidInputException; +import io.mosip.resident.helper.ObjectStoreHelper; +import io.mosip.resident.service.DownLoadMasterDataService; +import io.mosip.resident.service.ResidentVidService; +import io.mosip.resident.service.impl.IdentityServiceImpl; +import io.mosip.resident.service.impl.ResidentServiceImpl; +import io.mosip.resident.test.ResidentTestBootApplication; +import io.mosip.resident.util.AuditUtil; +import io.mosip.resident.util.Utility; +import io.mosip.resident.validator.RequestValidator; + +/** + * @author Kamesh Shekhar Prasad + * This class is used to test download master data controller api. + */ +@RunWith(SpringRunner.class) +@SpringBootTest(classes = ResidentTestBootApplication.class) +@AutoConfigureMockMvc +@TestPropertySource(locations = "classpath:application.properties") +public class DownloadMasterdataControllerTest { + + @MockBean + private RequestValidator validator; + + @Mock + private AuditUtil audit; + + @MockBean + private ObjectStoreHelper objectStore; + + + @MockBean + @Qualifier("selfTokenRestTemplate") + private RestTemplate residentRestTemplate; + + @InjectMocks + DownLoadMasterDataController downLoadMasterDataController; + + @MockBean + DownLoadMasterDataService downLoadMasterDataService; + + @MockBean + IdentityServiceImpl identityService; + + @Autowired + private MockMvc mockMvc; + + @MockBean + private ResidentVidService vidService; + + @MockBean + private CryptoCoreSpec encryptor; + + @MockBean + private AuditUtil auditUtil; + + @MockBean + private ResidentServiceImpl residentService; + + @Mock + private Utility utility; + + @Mock + private Environment environment; + + Gson gson = new GsonBuilder().serializeNulls().create(); + + String reqJson; + + byte[] pdfbytes; + + @Before + public void setup() throws Exception { + MockitoAnnotations.initMocks(this); + this.mockMvc = MockMvcBuilders.standaloneSetup(downLoadMasterDataController).build(); + MainRequestDTO downloadCardRequestDTOMainRequestDTO = new MainRequestDTO<>(); + DownloadCardRequestDTO downloadCardRequestDTO = new DownloadCardRequestDTO(); + downloadCardRequestDTO.setIndividualId("7841261580"); + downloadCardRequestDTO.setOtp("111111"); + downloadCardRequestDTO.setTransactionId("1234567890"); + downloadCardRequestDTOMainRequestDTO.setRequest(downloadCardRequestDTO); + downloadCardRequestDTOMainRequestDTO.setId("mosip.resident.download.uin.card"); + reqJson = gson.toJson(downloadCardRequestDTOMainRequestDTO); + pdfbytes = "uin".getBytes(); + Mockito.when(utility.getFileName(Mockito.anyString(), Mockito.anyString(), Mockito.anyInt(), Mockito.anyString())).thenReturn("fileName"); + Mockito.when(environment.getProperty(Mockito.anyString())).thenReturn("property"); + } + + @Test + public void testDownloadRegistrationCentersByHierarchyLevel() throws Exception { + Mockito.when(downLoadMasterDataService.downloadRegistrationCentersByHierarchyLevel(Mockito.any(), + Mockito.any(), Mockito.any())).thenReturn( new ByteArrayInputStream(pdfbytes)); + mockMvc.perform(MockMvcRequestBuilders.get("/download/registration-centers-list?langcode=eng&hierarchylevel=5&name=14022")). + andExpect(status().isOk()); + } + + @Test(expected = Exception.class) + public void testDownloadRegistrationCentersByHierarchyLevelInvalidInputException() throws Exception { + doThrow(new InvalidInputException()). + when(validator).validateOnlyLanguageCode(any()); + Mockito.when(downLoadMasterDataService.downloadRegistrationCentersByHierarchyLevel(Mockito.any(), + Mockito.any(), Mockito.any())).thenReturn( new ByteArrayInputStream(pdfbytes)); + mockMvc.perform(MockMvcRequestBuilders.get("/download/registration-centers-list?langcode=eng&hierarchylevel=5&name=14022")). + andExpect(status().isOk()); + } + + @Test + public void testDownloadNearestRegistrationCenters() throws Exception { + Mockito.when(downLoadMasterDataService.getNearestRegistrationcenters(Mockito.anyString(), + Mockito.anyDouble(), Mockito.anyDouble(), Mockito.anyInt())).thenReturn( new ByteArrayInputStream(pdfbytes)); + mockMvc.perform(MockMvcRequestBuilders.get + ("/download/nearestRegistrationcenters?langcode=eng&longitude=1&latitude=1&proximitydistance=1")). + andExpect(status().isOk()); + } + + @Test(expected = Exception.class) + public void testDownloadNearestRegistrationCentersFailed() throws Exception { + doThrow(new InvalidInputException()). + when(validator).validateOnlyLanguageCode(any()); + Mockito.when(downLoadMasterDataService.getNearestRegistrationcenters(Mockito.anyString(), + Mockito.anyDouble(), Mockito.anyDouble(), Mockito.anyInt())).thenReturn( new ByteArrayInputStream(pdfbytes)); + mockMvc.perform(MockMvcRequestBuilders.get + ("/download/nearestRegistrationcenters?langcode=eng&longitude=1&latitude=1&proximitydistance=1")). + andExpect(status().isOk()); + } + + @Test + public void testDownloadSupportingDocsByLanguage() throws Exception { + Mockito.when(downLoadMasterDataService.downloadSupportingDocsByLanguage(Mockito.anyString())). + thenReturn( new ByteArrayInputStream(pdfbytes)); + mockMvc.perform(MockMvcRequestBuilders.get + ("/download/supporting-documents?langcode=eng")). + andExpect(status().isOk()); + } + + @Test(expected = Exception.class) + public void testDownloadSupportingDocsByLanguageFailed() throws Exception { + doThrow(new InvalidInputException()). + when(validator).validateOnlyLanguageCode(any()); + Mockito.when(downLoadMasterDataService.downloadSupportingDocsByLanguage(Mockito.anyString())). + thenReturn( new ByteArrayInputStream(pdfbytes)); + mockMvc.perform(MockMvcRequestBuilders.get + ("/download/supporting-documents?langcode=eng")). + andExpect(status().isOk()); + } +} diff --git a/resident/resident-service/src/test/java/io/mosip/resident/controller/GrievanceControllerTest.java b/resident/resident-service/src/test/java/io/mosip/resident/controller/GrievanceControllerTest.java new file mode 100644 index 00000000000..ba1dd60fce8 --- /dev/null +++ b/resident/resident-service/src/test/java/io/mosip/resident/controller/GrievanceControllerTest.java @@ -0,0 +1,154 @@ +package io.mosip.resident.controller; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doThrow; + +import java.security.PrivateKey; +import java.security.PublicKey; +import java.util.HashMap; +import java.util.UUID; + +import javax.crypto.SecretKey; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.core.env.Environment; +import org.springframework.test.context.TestPropertySource; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.web.client.RestTemplate; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +import io.mosip.kernel.core.crypto.spi.CryptoCoreSpec; +import io.mosip.kernel.core.http.ResponseWrapper; +import io.mosip.kernel.core.util.DateUtils; +import io.mosip.resident.dto.GrievanceRequestDTO; +import io.mosip.resident.dto.MainRequestDTO; +import io.mosip.resident.exception.InvalidInputException; +import io.mosip.resident.helper.ObjectStoreHelper; +import io.mosip.resident.service.GrievanceService; +import io.mosip.resident.service.ResidentVidService; +import io.mosip.resident.service.impl.IdentityServiceImpl; +import io.mosip.resident.service.impl.ResidentServiceImpl; +import io.mosip.resident.test.ResidentTestBootApplication; +import io.mosip.resident.util.AuditUtil; +import io.mosip.resident.util.Utility; +import io.mosip.resident.validator.RequestValidator; + +/** + * @author Kamesh Shekhar Prasad + * This class is used to test Grievance controller api. + */ +@RunWith(SpringRunner.class) +@SpringBootTest(classes = ResidentTestBootApplication.class) +@AutoConfigureMockMvc +@TestPropertySource(locations = "classpath:application.properties") +public class GrievanceControllerTest { + + @Mock + private RequestValidator validator; + + @Mock + private AuditUtil audit; + + @Mock + private Environment environment; + + @Mock + private Utility utility; + + @MockBean + private ObjectStoreHelper objectStore; + + + @MockBean + @Qualifier("selfTokenRestTemplate") + private RestTemplate residentRestTemplate; + + @InjectMocks + GrievanceController grievanceController; + + @Mock + GrievanceService grievanceService; + + @MockBean + IdentityServiceImpl identityService; + + @Autowired + private MockMvc mockMvc; + + @MockBean + private ResidentVidService vidService; + + @MockBean + private ResidentServiceImpl residentService; + + @MockBean + private CryptoCoreSpec encryptor; + + Gson gson = new GsonBuilder().serializeNulls().create(); + + String reqJson; + + byte[] pdfbytes; + + private MainRequestDTO + grievanceRequestDTOMainRequestDTO; + + @Before + public void setup() throws Exception { + grievanceRequestDTOMainRequestDTO = new MainRequestDTO<>(); + GrievanceRequestDTO grievanceRequestDTO = new GrievanceRequestDTO(); + grievanceRequestDTO.setEventId("7256338756236957"); + grievanceRequestDTO.setMessage("sharing"); + grievanceRequestDTOMainRequestDTO.setRequest(grievanceRequestDTO); + grievanceRequestDTOMainRequestDTO.setId("mosip.resident.grievance.ticket.request"); + reqJson = gson.toJson(grievanceRequestDTOMainRequestDTO); + pdfbytes = "uin".getBytes(); + Mockito.when(utility.getFileName(Mockito.anyString(), Mockito.anyString(), Mockito.anyInt(), Mockito.anyString())).thenReturn("file"); + Mockito.when(environment.getProperty(Mockito.anyString())).thenReturn("property"); + } + + @Test + public void testGetCardSuccess() throws Exception { + io.mosip.kernel.core.http.ResponseWrapper responseWrapper = new io.mosip.kernel.core.http.ResponseWrapper<>(); + HashMap response = new HashMap<>(); + String ticketId = UUID.randomUUID().toString(); + response.put("ticketId", ticketId); + responseWrapper.setResponse(response); + responseWrapper.setId("mosip.resident.grievance.ticket.request"); + responseWrapper.setResponsetime(DateUtils.getUTCCurrentDateTime()); + Mockito.when(grievanceService.getGrievanceTicket(any())).thenReturn(responseWrapper); + ResponseWrapper responseWrapper1 = grievanceController.grievanceTicket(grievanceRequestDTOMainRequestDTO); + Assert.assertEquals("mosip.resident.grievance.ticket.request", responseWrapper1.getId()); + } + + @Test(expected = Exception.class) + public void testGetCardFailed() throws Exception { + doThrow(new InvalidInputException()). + when(validator).validateGrievanceRequestDto(any()); + io.mosip.kernel.core.http.ResponseWrapper responseWrapper = new io.mosip.kernel.core.http.ResponseWrapper<>(); + HashMap response = new HashMap<>(); + String ticketId = UUID.randomUUID().toString(); + response.put("ticketId", ticketId); + responseWrapper.setResponse(response); + responseWrapper.setId("mosip.resident.grievance.ticket.request"); + responseWrapper.setResponsetime(DateUtils.getUTCCurrentDateTime()); + Mockito.when(grievanceService.getGrievanceTicket(any())).thenReturn(responseWrapper); + ResponseWrapper responseWrapper1 = grievanceController.grievanceTicket(grievanceRequestDTOMainRequestDTO); + Assert.assertEquals("mosip.resident.grievance.ticket.request", responseWrapper1.getId()); + } + +} diff --git a/resident/resident-service/src/test/java/io/mosip/resident/controller/IdAuthControllerTest.java b/resident/resident-service/src/test/java/io/mosip/resident/controller/IdAuthControllerTest.java new file mode 100644 index 00000000000..e00d3c0a430 --- /dev/null +++ b/resident/resident-service/src/test/java/io/mosip/resident/controller/IdAuthControllerTest.java @@ -0,0 +1,115 @@ +package io.mosip.resident.controller; + +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.http.MediaType; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.client.RestTemplate; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +import io.mosip.resident.dto.IdAuthRequestDto; +import io.mosip.resident.dto.RequestWrapper; +import io.mosip.resident.exception.OtpValidationFailedException; +import io.mosip.resident.helper.ObjectStoreHelper; +import io.mosip.resident.service.DocumentService; +import io.mosip.resident.service.ProxyIdRepoService; +import io.mosip.resident.service.ResidentVidService; +import io.mosip.resident.service.impl.IdAuthServiceImpl; +import io.mosip.resident.service.impl.ResidentServiceImpl; +import io.mosip.resident.test.ResidentTestBootApplication; +import io.mosip.resident.util.AuditUtil; +import reactor.util.function.Tuples; + +/** + * Resident IdAuth controller test class. + * + * @author Ritik Jain + */ +@RunWith(SpringRunner.class) +@SpringBootTest(classes = ResidentTestBootApplication.class) +@AutoConfigureMockMvc +public class IdAuthControllerTest { + + @MockBean + private ProxyIdRepoService proxyIdRepoService; + + @MockBean + private IdAuthServiceImpl idAuthService; + + @Mock + private AuditUtil auditUtil; + + @MockBean + @Qualifier("selfTokenRestTemplate") + private RestTemplate residentRestTemplate; + + @MockBean + private ResidentVidService vidService; + + @InjectMocks + private IdAuthController idAuthController; + + @Autowired + private MockMvc mockMvc; + + @MockBean + private DocumentService docService; + + @MockBean + private ObjectStoreHelper objectStore; + + @MockBean + private ResidentServiceImpl residentService; + + Gson gson = new GsonBuilder().serializeNulls().create(); + + String reqJson; + + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + this.mockMvc = MockMvcBuilders.standaloneSetup(idAuthController).build(); + RequestWrapper requestWrapper = new RequestWrapper(); + IdAuthRequestDto idAuthRequestDto = new IdAuthRequestDto(); + idAuthRequestDto.setTransactionId("1234567890"); + idAuthRequestDto.setIndividualId("8251649601"); + idAuthRequestDto.setOtp("111111"); + requestWrapper.setRequest(idAuthRequestDto); + reqJson = gson.toJson(requestWrapper); + Mockito.doNothing().when(auditUtil).setAuditRequestDto(Mockito.any()); + } + + @Test + public void testValidateOtp() throws Exception { + Mockito.when(idAuthService.validateOtpV1(Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + .thenReturn(Tuples.of(true, "12345")); + mockMvc.perform(MockMvcRequestBuilders.post("/validate-otp").contentType(MediaType.APPLICATION_JSON_VALUE) + .content(reqJson.getBytes())).andExpect(status().isOk()); + } + + @Test(expected = Exception.class) + public void testValidateOtpFailed() throws Exception { + Mockito.when(idAuthService.validateOtpV1(Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + .thenThrow(new OtpValidationFailedException()); + mockMvc.perform(MockMvcRequestBuilders.post("/validate-otp").contentType(MediaType.APPLICATION_JSON_VALUE) + .content(reqJson.getBytes())).andExpect(status().isOk()); + } + +} diff --git a/resident/resident-service/src/test/java/io/mosip/resident/controller/IdentityControllerTest.java b/resident/resident-service/src/test/java/io/mosip/resident/controller/IdentityControllerTest.java new file mode 100644 index 00000000000..8224cb34f8b --- /dev/null +++ b/resident/resident-service/src/test/java/io/mosip/resident/controller/IdentityControllerTest.java @@ -0,0 +1,132 @@ +package io.mosip.resident.controller; + +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import java.io.IOException; +import java.security.PrivateKey; +import java.security.PublicKey; +import java.util.LinkedHashMap; +import java.util.Map; + +import javax.crypto.SecretKey; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.util.ReflectionTestUtils; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.client.RestTemplate; + +import io.mosip.kernel.core.crypto.spi.CryptoCoreSpec; +import io.mosip.kernel.core.http.ResponseWrapper; +import io.mosip.resident.exception.ApisResourceAccessException; +import io.mosip.resident.exception.InvalidInputException; +import io.mosip.resident.exception.ResidentServiceCheckedException; +import io.mosip.resident.exception.ResidentServiceException; +import io.mosip.resident.helper.ObjectStoreHelper; +import io.mosip.resident.service.ProxyIdRepoService; +import io.mosip.resident.service.ResidentVidService; +import io.mosip.resident.service.impl.IdentityServiceImpl; +import io.mosip.resident.service.impl.ResidentServiceImpl; +import io.mosip.resident.test.ResidentTestBootApplication; +import io.mosip.resident.util.AuditUtil; +import io.mosip.resident.validator.RequestValidator; + +/** + * Resident identity controller test class. + * + * @author Ritik Jain + */ +@RunWith(SpringRunner.class) +@SpringBootTest(classes = ResidentTestBootApplication.class) +@AutoConfigureMockMvc +public class IdentityControllerTest { + + @MockBean + private ProxyIdRepoService proxyIdRepoService; + + @InjectMocks + private IdentityController identityController; + + @MockBean + private IdentityServiceImpl idServiceImpl; + + @MockBean + private ResidentVidService vidService; + + @Mock + private AuditUtil auditUtil; + + @Mock + private RequestValidator validator; + + @MockBean + @Qualifier("selfTokenRestTemplate") + private RestTemplate residentRestTemplate; + + @MockBean + private DocumentController documentController; + + @MockBean + private IdAuthController idAuthController; + + @MockBean + private ObjectStoreHelper objectStore; + + @MockBean + private CryptoCoreSpec encryptor; + + @Autowired + private MockMvc mockMvc; + + @MockBean + private ResidentServiceImpl residentService; + + private ResponseWrapper responseWrapper; + + private Map identityMap; + + @Before + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + this.mockMvc = MockMvcBuilders.standaloneSetup(identityController).build(); + Mockito.doNothing().when(auditUtil).setAuditRequestDto(Mockito.any()); + + identityMap = new LinkedHashMap(); + identityMap.put("UIN", "8251649601"); + identityMap.put("email", "manojvsp12@gmail.com"); + identityMap.put("phone", "9395910872"); + identityMap.put("dateOfBirth", "1970/11/16"); + + responseWrapper = new ResponseWrapper<>(); + responseWrapper.setVersion("v1"); + responseWrapper.setId("1"); + responseWrapper.setResponse(identityMap); + ReflectionTestUtils.setField(identityController, "residentIdentityInfoId", "identity.id"); + } + + @Test + public void testGetInputAttributeValues() throws Exception { + Mockito.when(idServiceImpl.getIdentityAttributes(Mockito.anyString(),Mockito.anyString())).thenReturn(identityMap); + mockMvc.perform(MockMvcRequestBuilders.get("/identity/info/type/schemaType")).andExpect(status().isOk()); + } + + @Test(expected = ResidentServiceException.class) + public void testGetInputAttributeValuesWithInvalidInputException() + throws ApisResourceAccessException, ResidentServiceCheckedException, IOException { + Mockito.doThrow(new InvalidInputException()).when(validator).validateSchemaType(Mockito.anyString()); + identityController.getInputAttributeValues("schema-type"); + } +} diff --git a/resident/resident-service/src/test/java/io/mosip/resident/controller/OrderCardControllerTest.java b/resident/resident-service/src/test/java/io/mosip/resident/controller/OrderCardControllerTest.java new file mode 100644 index 00000000000..55dc2ed7804 --- /dev/null +++ b/resident/resident-service/src/test/java/io/mosip/resident/controller/OrderCardControllerTest.java @@ -0,0 +1,152 @@ +package io.mosip.resident.controller; + +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import java.security.PrivateKey; +import java.security.PublicKey; + +import javax.crypto.SecretKey; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.http.MediaType; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.client.RestTemplate; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +import io.mosip.kernel.core.crypto.spi.CryptoCoreSpec; +import io.mosip.kernel.core.http.ResponseWrapper; +import io.mosip.resident.controller.AuthTransactionCallbackController; +import io.mosip.resident.controller.DocumentController; +import io.mosip.resident.controller.IdAuthController; +import io.mosip.resident.controller.IdentityController; +import io.mosip.resident.controller.OrderCardController; +import io.mosip.resident.dto.RequestWrapper; +import io.mosip.resident.dto.ResidentCredentialRequestDto; +import io.mosip.resident.dto.ResidentCredentialResponseDto; +import io.mosip.resident.helper.ObjectStoreHelper; +import io.mosip.resident.service.OrderCardService; +import io.mosip.resident.service.ProxyIdRepoService; +import io.mosip.resident.service.ResidentVidService; +import io.mosip.resident.service.impl.IdentityServiceImpl; +import io.mosip.resident.service.impl.ResidentServiceImpl; +import io.mosip.resident.test.ResidentTestBootApplication; +import io.mosip.resident.util.AuditUtil; + +/** + * Resident order card controller test class. + * + * @author Ritik Jain + */ +@RunWith(SpringRunner.class) +@SpringBootTest(classes = ResidentTestBootApplication.class) +@AutoConfigureMockMvc +public class OrderCardControllerTest { + + @MockBean + private ProxyIdRepoService proxyIdRepoService; + + @InjectMocks + private OrderCardController orderCardController; + + @MockBean + private OrderCardService orderCardService; + + @MockBean + private ResidentVidService vidService; + + @Mock + private AuditUtil auditUtil; + + @MockBean + @Qualifier("selfTokenRestTemplate") + private RestTemplate residentRestTemplate; + + @MockBean + private AuthTransactionCallbackController authTransactionCallbackController; + + @MockBean + private DocumentController documentController; + + @MockBean + private IdAuthController idAuthController; + + @MockBean + private IdentityController identityController; + + @MockBean + private ObjectStoreHelper objectStore; + + @MockBean + private CryptoCoreSpec encryptor; + + @MockBean + private ResidentServiceImpl residentService; + + @Autowired + private MockMvc mockMvc; + + private ResponseWrapper responseWrapper; + + @MockBean + private IdentityServiceImpl identityServiceImpl; + + Gson gson = new GsonBuilder().serializeNulls().create(); + + String reqJson; + + @Before + public void setUp() throws Exception { + responseWrapper = new ResponseWrapper<>(); + responseWrapper.setVersion("v1"); + responseWrapper.setId("1"); + RequestWrapper requestWrapper = new RequestWrapper(); + ResidentCredentialRequestDto residentCredentialRequestDto = new ResidentCredentialRequestDto(); + residentCredentialRequestDto.setTransactionID("1234567890"); + residentCredentialRequestDto.setIndividualId("8251649601"); + requestWrapper.setRequest(residentCredentialRequestDto); + reqJson = gson.toJson(requestWrapper); + MockitoAnnotations.initMocks(this); + this.mockMvc = MockMvcBuilders.standaloneSetup(orderCardController).build(); + Mockito.doNothing().when(auditUtil).setAuditRequestDto(Mockito.any()); + Mockito.when(identityServiceImpl.getResidentIndvidualIdFromSession()).thenReturn("1234Id"); + } + + @Test + public void testSendPhysicalCard() throws Exception { + Mockito.when(orderCardService.sendPhysicalCard(Mockito.any())) + .thenReturn((ResidentCredentialResponseDto) responseWrapper.getResponse()); + mockMvc.perform(MockMvcRequestBuilders.post("/sendCard").contentType(MediaType.APPLICATION_JSON_VALUE) + .content(reqJson.getBytes())).andExpect(status().isOk()); + } + + @Test + public void testPhysicalCardOrder() throws Exception { + Mockito.when(orderCardService.getRedirectUrl(Mockito.any(),Mockito.any())).thenReturn("URL"); + mockMvc.perform(MockMvcRequestBuilders.get("/physical-card/order?partnerId=mosip_partnerorg1667786709933&redirectUri=vdsvdvds")).andExpect(status().isFound()); + } + + @Test + public void testPhysicalCardOrderRedirect() throws Exception { + Mockito.when(orderCardService.physicalCardOrder(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), + Mockito.any(), Mockito.any(), Mockito.any())).thenReturn("URL"); + mockMvc.perform(MockMvcRequestBuilders.get( + "/physical-card/order-redirect?redirectUrl=aHR0cHM6Ly93d3cubWFkZWludGV4dC5jb20v&paymentTransactionId=12345dsvdvds&eventId=123456&residentFullAddress=fgfhfghgf")).andExpect(status().isFound()); + } + +} \ No newline at end of file diff --git a/resident/resident-service/src/test/java/io/mosip/resident/controller/PinStatusControllerTest.java b/resident/resident-service/src/test/java/io/mosip/resident/controller/PinStatusControllerTest.java new file mode 100644 index 00000000000..f52d045edf6 --- /dev/null +++ b/resident/resident-service/src/test/java/io/mosip/resident/controller/PinStatusControllerTest.java @@ -0,0 +1,83 @@ +package io.mosip.resident.controller; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; +import org.springframework.core.env.Environment; +import org.springframework.http.HttpStatus; +import org.springframework.test.context.ContextConfiguration; + +import io.mosip.kernel.core.http.ResponseWrapper; +import io.mosip.resident.dto.ResponseDTO; +import io.mosip.resident.exception.ResidentServiceCheckedException; +import io.mosip.resident.service.PinUnpinStatusService; +import io.mosip.resident.util.AuditUtil; +import io.mosip.resident.validator.RequestValidator; + +/** + * This class is used to test pin or unpin status api based on event id. + * @Author Kamesh Shekhar Prasad + */ + +@RunWith(MockitoJUnitRunner.class) +@ContextConfiguration +public class PinStatusControllerTest { + + @InjectMocks + PinStatusController pinStatusController; + + @Mock + private AuditUtil audit; + + @Mock + private RequestValidator requestValidator; + + @Mock + private PinUnpinStatusService pinUnpinStatusService; + + @Mock + private Environment env; + + @Test + public void pinStatusControllerTest() throws ResidentServiceCheckedException{ + ResponseWrapper responseWrapper = new ResponseWrapper<>(); + ResponseDTO responseDTO = new ResponseDTO(); + responseDTO.setStatus(HttpStatus.OK.toString()); + responseWrapper.setResponse(responseDTO); + Mockito.when(pinUnpinStatusService.pinStatus(Mockito.anyString(), Mockito.anyBoolean())).thenReturn(responseWrapper); + ResponseWrapper resultResponseDTO = pinStatusController.pinStatus("eventId"); + assertEquals(resultResponseDTO.getResponse().getStatus(), HttpStatus.OK.toString()); + } + + @Test(expected = Exception.class) + public void pinStatusControllerWithExceptionTest() throws ResidentServiceCheckedException { + Mockito.when(env.getProperty(Mockito.anyString())).thenReturn("property"); + Mockito.when(pinUnpinStatusService.pinStatus(Mockito.anyString(), Mockito.anyBoolean())) + .thenThrow(new ResidentServiceCheckedException()); + pinStatusController.pinStatus("eventId"); + } + + @Test + public void unPinStatusControllerTest() throws ResidentServiceCheckedException{ + ResponseWrapper responseWrapper = new ResponseWrapper<>(); + ResponseDTO responseDTO = new ResponseDTO(); + responseDTO.setStatus(HttpStatus.OK.toString()); + responseWrapper.setResponse(responseDTO); + Mockito.when(pinUnpinStatusService.pinStatus(Mockito.anyString(), Mockito.anyBoolean())).thenReturn(responseWrapper); + ResponseWrapper responseEntity = pinStatusController.unPinStatus("eventId"); + assertEquals(responseEntity.getResponse().getStatus(), HttpStatus.OK.toString()); + } + + @Test(expected = Exception.class) + public void unPinStatusControllerWithExceptionTest() throws ResidentServiceCheckedException { + Mockito.when(env.getProperty(Mockito.anyString())).thenReturn("property"); + Mockito.when(pinUnpinStatusService.pinStatus(Mockito.anyString(), Mockito.anyBoolean())) + .thenThrow(new ResidentServiceCheckedException()); + pinStatusController.unPinStatus("eventId"); + } +} diff --git a/resident/resident-service/src/test/java/io/mosip/resident/controller/ProxyAuditControllerTest.java b/resident/resident-service/src/test/java/io/mosip/resident/controller/ProxyAuditControllerTest.java new file mode 100644 index 00000000000..45f408e8de4 --- /dev/null +++ b/resident/resident-service/src/test/java/io/mosip/resident/controller/ProxyAuditControllerTest.java @@ -0,0 +1,140 @@ +package io.mosip.resident.controller; + +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import java.security.PrivateKey; +import java.security.PublicKey; + +import javax.crypto.SecretKey; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.http.MediaType; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.client.RestTemplate; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +import io.mosip.kernel.core.crypto.spi.CryptoCoreSpec; +import io.mosip.resident.dto.AuthenticatedAuditRequestDto; +import io.mosip.resident.dto.UnauthenticatedAuditRequestDto; +import io.mosip.resident.helper.ObjectStoreHelper; +import io.mosip.resident.service.IdentityService; +import io.mosip.resident.service.ProxyIdRepoService; +import io.mosip.resident.service.ResidentVidService; +import io.mosip.resident.service.impl.ResidentServiceImpl; +import io.mosip.resident.test.ResidentTestBootApplication; +import io.mosip.resident.util.AuditUtil; +import io.mosip.resident.util.Utility; + +/** + * Resident proxy audit controller test class. + * + * @author Ritik Jain + */ +@RunWith(SpringRunner.class) +@SpringBootTest(classes = ResidentTestBootApplication.class) +@AutoConfigureMockMvc +public class ProxyAuditControllerTest { + + @MockBean + private ProxyIdRepoService proxyIdRepoService; + + @InjectMocks + private ProxyAuditController proxyAuditController; + + @Mock + private AuditUtil auditUtil; + + @Mock + private IdentityService identityService; + + @Mock + private Utility utility; + + @MockBean + private ResidentServiceImpl residentService; + + @MockBean + @Qualifier("selfTokenRestTemplate") + private RestTemplate residentRestTemplate; + + @MockBean + private AuthTransactionCallbackController authTransactionCallbackController; + + @MockBean + private DocumentController documentController; + + @MockBean + private ObjectStoreHelper objectStore; + + @MockBean + private IdAuthController idAuthController; + + @MockBean + private ResidentVidService vidService; + + @MockBean + private CryptoCoreSpec encryptor; + + private AuthenticatedAuditRequestDto authenticatedAuditRequestDto; + + private UnauthenticatedAuditRequestDto unauthenticatedAuditRequestDto; + + @Autowired + private MockMvc mockMvc; + + Gson gson = new GsonBuilder().serializeNulls().create(); + + String reqJson; + + @Before + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + this.mockMvc = MockMvcBuilders.standaloneSetup(proxyAuditController).build(); + authenticatedAuditRequestDto = new AuthenticatedAuditRequestDto(); + authenticatedAuditRequestDto.setAuditEventId("RES-SER-1111"); + authenticatedAuditRequestDto.setModuleId("RES-SER"); + authenticatedAuditRequestDto.setModuleName("Residence service"); + unauthenticatedAuditRequestDto = new UnauthenticatedAuditRequestDto(); + unauthenticatedAuditRequestDto.setAuditEventId("RES-SER-1111"); + unauthenticatedAuditRequestDto.setModuleId("RES-SER"); + unauthenticatedAuditRequestDto.setModuleName("Residence service"); + } + + @Test + public void testAuthAuditLog() throws Exception { + reqJson = gson.toJson(authenticatedAuditRequestDto); + mockMvc.perform(MockMvcRequestBuilders.post("/auth-proxy/audit/log").contentType(MediaType.APPLICATION_JSON_VALUE) + .content(reqJson.getBytes())).andExpect(status().isOk()); + } + + @Test + public void testAuditLogWithId() throws Exception { + unauthenticatedAuditRequestDto.setId("23456"); + reqJson = gson.toJson(unauthenticatedAuditRequestDto); + mockMvc.perform(MockMvcRequestBuilders.post("/proxy/audit/log").contentType(MediaType.APPLICATION_JSON_VALUE) + .content(reqJson.getBytes())).andExpect(status().isOk()); + } + + @Test + public void testAuditLogWithNullId() throws Exception { + reqJson = gson.toJson(unauthenticatedAuditRequestDto); + mockMvc.perform(MockMvcRequestBuilders.post("/proxy/audit/log").contentType(MediaType.APPLICATION_JSON_VALUE) + .content(reqJson.getBytes())).andExpect(status().isOk()); + } + +} diff --git a/resident/resident-service/src/test/java/io/mosip/resident/controller/ProxyConfigControllerTest.java b/resident/resident-service/src/test/java/io/mosip/resident/controller/ProxyConfigControllerTest.java new file mode 100644 index 00000000000..b373845f26b --- /dev/null +++ b/resident/resident-service/src/test/java/io/mosip/resident/controller/ProxyConfigControllerTest.java @@ -0,0 +1,117 @@ +package io.mosip.resident.controller; + +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import java.security.PrivateKey; +import java.security.PublicKey; + +import javax.crypto.SecretKey; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.client.RestTemplate; + +import io.mosip.kernel.core.crypto.spi.CryptoCoreSpec; +import io.mosip.kernel.core.http.ResponseWrapper; +import io.mosip.resident.helper.ObjectStoreHelper; +import io.mosip.resident.service.ProxyIdRepoService; +import io.mosip.resident.service.ResidentVidService; +import io.mosip.resident.service.impl.ResidentConfigServiceImpl; +import io.mosip.resident.service.impl.ResidentServiceImpl; +import io.mosip.resident.test.ResidentTestBootApplication; +import io.mosip.resident.util.AuditUtil; + +/** + * Resident proxy config controller test class. + * + * @author Ritik Jain + */ +@RunWith(SpringRunner.class) +@SpringBootTest(classes = ResidentTestBootApplication.class) +@AutoConfigureMockMvc +public class ProxyConfigControllerTest { + + @MockBean + private ProxyIdRepoService proxyIdRepoService; + + @MockBean + private ResidentConfigServiceImpl residentConfigService; + + @MockBean + private AuditUtil auditUtil; + + @InjectMocks + private ProxyConfigController proxyConfigController; + + @MockBean + private DocumentController documentController; + + @MockBean + private IdAuthController idAuthController; + + @MockBean + private IdentityController identityController; + + @MockBean + private ResidentController residentController; + + @MockBean + private ResidentVidService vidService; + + @MockBean + private ResidentServiceImpl residentService; + + @MockBean + private CryptoCoreSpec encryptor; + + @MockBean + @Qualifier("selfTokenRestTemplate") + private RestTemplate residentRestTemplate; + + @MockBean + private ObjectStoreHelper objectStore; + + @Autowired + private MockMvc mockMvc; + + private ResponseWrapper responseWrapper; + + @Before + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + this.mockMvc = MockMvcBuilders.standaloneSetup(proxyConfigController).build(); + Mockito.doNothing().when(auditUtil).setAuditRequestDto(Mockito.any()); + } + + @Test + public void testGetResidentProperties() throws Exception { + Mockito.when(residentConfigService.getUIProperties()).thenReturn(responseWrapper); + mockMvc.perform(MockMvcRequestBuilders.get("/proxy/config/ui-properties")).andExpect(status().isOk()); + } + + @Test + public void testGetResidentUISchema() throws Exception { + Mockito.when(residentConfigService.getUISchema("update-demographics")).thenReturn("ui-schema-json"); + mockMvc.perform(MockMvcRequestBuilders.get("/auth-proxy/config/ui-schema/update-demographics")).andExpect(status().isOk()); + } + + @Test + public void testGetIdentityMapping() throws Exception { + Mockito.when(residentConfigService.getIdentityMapping()).thenReturn("identity-mapping-json"); + mockMvc.perform(MockMvcRequestBuilders.get("/auth-proxy/config/identity-mapping")).andExpect(status().isOk()); + } + +} \ No newline at end of file diff --git a/resident/resident-service/src/test/java/io/mosip/resident/controller/ProxyMasterdataControllerTest.java b/resident/resident-service/src/test/java/io/mosip/resident/controller/ProxyMasterdataControllerTest.java new file mode 100644 index 00000000000..1d382e15492 --- /dev/null +++ b/resident/resident-service/src/test/java/io/mosip/resident/controller/ProxyMasterdataControllerTest.java @@ -0,0 +1,218 @@ +package io.mosip.resident.controller; + +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import java.security.PrivateKey; +import java.security.PublicKey; + +import javax.crypto.SecretKey; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.client.RestTemplate; + +import io.mosip.kernel.core.crypto.spi.CryptoCoreSpec; +import io.mosip.kernel.core.http.ResponseWrapper; +import io.mosip.resident.helper.ObjectStoreHelper; +import io.mosip.resident.service.DocumentService; +import io.mosip.resident.service.ProxyIdRepoService; +import io.mosip.resident.service.ProxyMasterdataService; +import io.mosip.resident.service.ResidentVidService; +import io.mosip.resident.service.impl.AcknowledgementServiceImpl; +import io.mosip.resident.service.impl.ResidentServiceImpl; +import io.mosip.resident.test.ResidentTestBootApplication; +import io.mosip.resident.util.AuditUtil; + +/** + * Resident proxy masterdata controller test class. + * + * @author Ritik Jain + */ +@RunWith(SpringRunner.class) +@SpringBootTest(classes = ResidentTestBootApplication.class) +@AutoConfigureMockMvc +public class ProxyMasterdataControllerTest { + + @MockBean + private ProxyIdRepoService proxyIdRepoService; + + @MockBean + private ProxyMasterdataService proxyMasterdataService; + + @Mock + private AuditUtil auditUtil; + + @MockBean + @Qualifier("selfTokenRestTemplate") + private RestTemplate residentRestTemplate; + + @MockBean + private ResidentVidService vidService; + + @MockBean + private AcknowledgementController acknowledgementController; + + @MockBean + private AcknowledgementServiceImpl acknowledgementService; + + @MockBean + private CryptoCoreSpec encryptor; + + @InjectMocks + private ProxyMasterdataController proxyMasterdataController; + + @MockBean + private DocumentService docService; + + @MockBean + private ObjectStoreHelper objectStore; + + @MockBean + private ResidentServiceImpl residentService; + + @Autowired + private MockMvc mockMvc; + + private ResponseWrapper responseWrapper; + + @Before + public void setUp() throws Exception { + responseWrapper = new ResponseWrapper<>(); + responseWrapper.setVersion("v1"); + responseWrapper.setId("1"); + MockitoAnnotations.initMocks(this); + this.mockMvc = MockMvcBuilders.standaloneSetup(proxyMasterdataController).build(); + Mockito.doNothing().when(auditUtil).setAuditRequestDto(Mockito.any()); + } + + @Test + public void testGetValidDocumentByLangCode() throws Exception { + Mockito.when(proxyMasterdataService.getValidDocumentByLangCode(Mockito.anyString())) + .thenReturn(responseWrapper); + mockMvc.perform(MockMvcRequestBuilders.get("/proxy/masterdata/validdocuments/langCode")) + .andExpect(status().isOk()); + } + + @Test + public void testGetLocationHierarchyLevelByLangCode() throws Exception { + Mockito.when(proxyMasterdataService.getLocationHierarchyLevelByLangCode(Mockito.anyString())) + .thenReturn(responseWrapper); + mockMvc.perform(MockMvcRequestBuilders.get("/proxy/masterdata/locationHierarchyLevels/langcode")) + .andExpect(status().isOk()); + } + + @Test + public void testGetImmediateChildrenByLocCodeAndLangCode() throws Exception { + Mockito.when(proxyMasterdataService.getImmediateChildrenByLocCodeAndLangCode(Mockito.anyString(), + Mockito.anyString())).thenReturn(responseWrapper); + mockMvc.perform( + MockMvcRequestBuilders.get("/proxy/masterdata/locations/immediatechildren/locationcode/langcode")) + .andExpect(status().isOk()); + } + + @Test + public void testGetLocationDetailsByLocCodeAndLangCode() throws Exception { + Mockito.when( + proxyMasterdataService.getLocationDetailsByLocCodeAndLangCode(Mockito.anyString(), Mockito.anyString())) + .thenReturn(responseWrapper); + mockMvc.perform(MockMvcRequestBuilders.get("/proxy/masterdata/locations/info/locationcode/langcode")) + .andExpect(status().isOk()); + } + + @Test + public void testGetCoordinateSpecificRegistrationCenters() throws Exception { + Mockito.when(proxyMasterdataService.getCoordinateSpecificRegistrationCenters(Mockito.anyString(), + Mockito.anyDouble(), Mockito.anyDouble(), Mockito.anyInt())).thenReturn(responseWrapper); + mockMvc.perform(MockMvcRequestBuilders + .get("/proxy/masterdata/getcoordinatespecificregistrationcenters/langcode/33.4/43.5/200")) + .andExpect(status().isOk()); + } + + @Test + public void testGetApplicantValidDocument() throws Exception { + Mockito.when(proxyMasterdataService.getApplicantValidDocument(Mockito.anyString(), Mockito.anyList())) + .thenReturn(responseWrapper); + mockMvc.perform( + MockMvcRequestBuilders.get("/proxy/masterdata/applicanttype/applicantId/languages?languages=eng")) + .andExpect(status().isOk()); + } + + @Test + public void testGetRegistrationCentersByHierarchyLevel() throws Exception { + Mockito.when(proxyMasterdataService.getRegistrationCentersByHierarchyLevel(Mockito.anyString(), + Mockito.anyShort(), Mockito.anyList())).thenReturn(responseWrapper); + mockMvc.perform(MockMvcRequestBuilders.get("/proxy/masterdata/registrationcenters/langcode/5/names?name=14110")) + .andExpect(status().isOk()); + } + + @Test + public void testGetRegistrationCenterByHierarchyLevelAndTextPaginated() throws Exception { + Mockito.when(proxyMasterdataService.getRegistrationCenterByHierarchyLevelAndTextPaginated(Mockito.anyString(), + Mockito.anyShort(), Mockito.anyString(), Mockito.anyInt(), Mockito.anyInt(), Mockito.any(), + Mockito.anyString())).thenReturn(responseWrapper); + mockMvc.perform(MockMvcRequestBuilders.get( + "/proxy/masterdata/registrationcenters/page/langcode/5/name?pageNumber=0&pageSize=10&orderBy=desc&sortBy=createdDateTime")) + .andExpect(status().isOk()); + } + + @Test + public void testGetRegistrationCenterWorkingDays() throws Exception { + Mockito.when(proxyMasterdataService.getRegistrationCenterWorkingDays(Mockito.anyString(), Mockito.anyString())) + .thenReturn(responseWrapper); + mockMvc.perform(MockMvcRequestBuilders.get("/proxy/masterdata/workingdays/registrationCenterID/langCode")) + .andExpect(status().isOk()); + } + + @Test + public void testGetLatestIdSchema() throws Exception { + Mockito.when( + proxyMasterdataService.getLatestIdSchema(Mockito.anyDouble(), Mockito.anyString(), Mockito.anyString())) + .thenReturn(responseWrapper); + mockMvc.perform(MockMvcRequestBuilders.get("/proxy/masterdata/idschema/latest?schemaVersion=&domain=&type=")) + .andExpect(status().isOk()); + } + + @Test + public void testGetAllTemplateBylangCodeAndTemplateTypeCode() throws Exception { + Mockito.when(proxyMasterdataService.getAllTemplateBylangCodeAndTemplateTypeCode(Mockito.anyString(), + Mockito.anyString())).thenReturn(responseWrapper); + mockMvc.perform(MockMvcRequestBuilders.get("/auth-proxy/masterdata/templates/eng/OTP-sms-template")) + .andExpect(status().isOk()); + } + + @Test + public void testGetGenderTypesByLangCode() throws Exception { + Mockito.when(proxyMasterdataService.getDynamicFieldBasedOnLangCodeAndFieldName(Mockito.anyString(), Mockito.anyString(), Mockito.anyBoolean())).thenReturn(responseWrapper); + mockMvc.perform(MockMvcRequestBuilders.get("/auth-proxy/masterdata/dynamicfields/gender/eng?withValue=true")) + .andExpect(status().isOk()); + } + + @Test + public void testGetDocumentTypesByDocumentCategoryCodeAndLangCode() throws Exception { + Mockito.when(proxyMasterdataService.getDocumentTypesByDocumentCategoryAndLangCode(Mockito.anyString(),Mockito.anyString())).thenReturn(responseWrapper); + mockMvc.perform(MockMvcRequestBuilders.get("/proxy/masterdata/documenttypes/documentcategorycode/langcode")) + .andExpect(status().isOk()); + } + + @Test + public void testGetGenderCodeByGenderTypeAndLangCode() throws Exception { + Mockito.when(proxyMasterdataService.getGenderCodeByGenderTypeAndLangCode(Mockito.anyString(),Mockito.anyString())).thenReturn(responseWrapper); + mockMvc.perform(MockMvcRequestBuilders.get("/proxy/masterdata/gendercode/gendertype/langcode")) + .andExpect(status().isOk()); + } + +} diff --git a/resident/resident-service/src/test/java/io/mosip/resident/controller/ProxyOtpControllerTest.java b/resident/resident-service/src/test/java/io/mosip/resident/controller/ProxyOtpControllerTest.java new file mode 100644 index 00000000000..de8f09772bb --- /dev/null +++ b/resident/resident-service/src/test/java/io/mosip/resident/controller/ProxyOtpControllerTest.java @@ -0,0 +1,183 @@ +package io.mosip.resident.controller; + +import static org.mockito.Mockito.doThrow; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import java.security.PrivateKey; +import java.security.PublicKey; + +import javax.crypto.SecretKey; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.core.env.Environment; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.test.context.TestPropertySource; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.client.RestTemplate; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +import io.mosip.kernel.core.authmanager.model.AuthNResponse; +import io.mosip.kernel.core.crypto.spi.CryptoCoreSpec; +import io.mosip.preregistration.application.constant.PreRegLoginConstant; +import io.mosip.resident.dto.MainRequestDTO; +import io.mosip.resident.dto.MainResponseDTO; +import io.mosip.resident.dto.OtpRequestDTOV2; +import io.mosip.resident.dto.OtpRequestDTOV3; +import io.mosip.resident.exception.ApisResourceAccessException; +import io.mosip.resident.exception.InvalidInputException; +import io.mosip.resident.exception.ResidentServiceException; +import io.mosip.resident.helper.ObjectStoreHelper; +import io.mosip.resident.service.ProxyOtpService; +import io.mosip.resident.service.ResidentVidService; +import io.mosip.resident.service.impl.IdentityServiceImpl; +import io.mosip.resident.service.impl.ResidentServiceImpl; +import io.mosip.resident.test.ResidentTestBootApplication; +import io.mosip.resident.util.AuditUtil; +import io.mosip.resident.util.Utility; +import io.mosip.resident.validator.RequestValidator; +import reactor.util.function.Tuples; + +/** + * @author Kamesh Shekhar Prasad + * This class is used to test proxy otp controller. + */ +@RunWith(SpringRunner.class) +@SpringBootTest(classes = ResidentTestBootApplication.class) +@AutoConfigureMockMvc +@TestPropertySource(locations = "classpath:application.properties") +public class ProxyOtpControllerTest { + + @MockBean + private RequestValidator validator; + + @Mock + private AuditUtil audit; + + @MockBean + private ObjectStoreHelper objectStore; + + + @MockBean + @Qualifier("selfTokenRestTemplate") + private RestTemplate residentRestTemplate; + + @InjectMocks + ProxyOtpController proxyOtpController; + + @MockBean + ProxyOtpService proxyOtpService; + + @MockBean + IdentityServiceImpl identityService; + + @Autowired + private MockMvc mockMvc; + + @MockBean + private ResidentVidService vidService; + + @MockBean + private CryptoCoreSpec encryptor; + + @MockBean + private AuditUtil auditUtil; + + @MockBean + private ResidentServiceImpl residentService; + + @Mock + private Utility utility; + + @Mock + private Environment environment; + + Gson gson = new GsonBuilder().serializeNulls().create(); + + private MainRequestDTO userOtpRequest; + + private MainRequestDTO userIdOtpRequest; + + String reqJson; + + byte[] pdfbytes; + + private ResponseEntity> responseEntity; + + private MainResponseDTO response; + + @Before + public void setup() throws Exception { + MockitoAnnotations.initMocks(this); + this.mockMvc = MockMvcBuilders.standaloneSetup(proxyOtpController).build(); + userOtpRequest = new MainRequestDTO<>(); + userIdOtpRequest = new MainRequestDTO<>(); + OtpRequestDTOV2 otpRequestDTOV2 = new OtpRequestDTOV2(); + otpRequestDTOV2.setUserId("8809909090"); + otpRequestDTOV2.setTransactionId("1234343434"); + userOtpRequest.setRequest(otpRequestDTOV2); + userOtpRequest.setId("mosip.resident.contact.details.send.otp.id"); + OtpRequestDTOV3 otpRequestDTOV3 = new OtpRequestDTOV3(); + otpRequestDTOV3.setOtp("111"); + otpRequestDTOV3.setUserId("8809909090"); + otpRequestDTOV3.setTransactionId("1234343434"); + userIdOtpRequest.setRequest(otpRequestDTOV3); + userIdOtpRequest.setId("mosip.resident.contact.details.update.id"); + reqJson = gson.toJson(userOtpRequest); + AuthNResponse authNResponse = new AuthNResponse(PreRegLoginConstant.EMAIL_SUCCESS, PreRegLoginConstant.SUCCESS); + response = new MainResponseDTO<>(); + response.setResponse(authNResponse); + responseEntity = new ResponseEntity<>(HttpStatus.OK); + Mockito.when(environment.getProperty(Mockito.anyString())).thenReturn("property"); + } + + @Test + public void testSendOtp() throws Exception { + Mockito.when(proxyOtpService.sendOtp(Mockito.any())).thenReturn(responseEntity); + mockMvc.perform(MockMvcRequestBuilders.post("/contact-details/send-otp").contentType(MediaType.APPLICATION_JSON_VALUE) + .content(reqJson.getBytes())).andExpect(status().isOk()); + } + + @Test(expected = ResidentServiceException.class) + public void testSendOtpException() throws Exception { + doThrow(new InvalidInputException("error message")).when(validator).validateProxySendOtpRequest(Mockito.any()); + proxyOtpController.sendOTP(userOtpRequest); + } + + @Test(expected = ApisResourceAccessException.class) + public void testSendOtpExceptionApiResourceException() throws Exception { + doThrow(new ApisResourceAccessException()).when(validator).validateProxySendOtpRequest(Mockito.any()); + proxyOtpController.sendOTP(userOtpRequest); + } + + @Test + public void testValidateOtp() throws Exception { + Mockito.when(proxyOtpService.validateWithUserIdOtp(Mockito.any())).thenReturn(Tuples.of(response, "12345")); + mockMvc.perform(MockMvcRequestBuilders.post("/contact-details/update-data").contentType(MediaType.APPLICATION_JSON_VALUE) + .content(reqJson.getBytes())).andExpect(status().isOk()); + } + + @Test(expected = ResidentServiceException.class) + public void testValidateOtpException() throws Exception { + doThrow(new InvalidInputException("error message")).when(validator).validateUpdateDataRequest(Mockito.any()); + proxyOtpController.validateWithUserIdOtp(userIdOtpRequest); + } + +} diff --git a/resident/resident-service/src/test/java/io/mosip/resident/controller/ProxyPartnerManagementControllerTest.java b/resident/resident-service/src/test/java/io/mosip/resident/controller/ProxyPartnerManagementControllerTest.java new file mode 100644 index 00000000000..342133a488a --- /dev/null +++ b/resident/resident-service/src/test/java/io/mosip/resident/controller/ProxyPartnerManagementControllerTest.java @@ -0,0 +1,113 @@ +package io.mosip.resident.controller; + +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import java.security.PrivateKey; +import java.security.PublicKey; + +import javax.crypto.SecretKey; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.core.env.Environment; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.client.RestTemplate; + +import io.mosip.kernel.core.crypto.spi.CryptoCoreSpec; +import io.mosip.kernel.core.http.ResponseWrapper; +import io.mosip.resident.exception.ResidentServiceCheckedException; +import io.mosip.resident.helper.ObjectStoreHelper; +import io.mosip.resident.service.DocumentService; +import io.mosip.resident.service.ProxyIdRepoService; +import io.mosip.resident.service.ResidentVidService; +import io.mosip.resident.service.impl.ProxyPartnerManagementServiceImpl; +import io.mosip.resident.service.impl.ResidentServiceImpl; +import io.mosip.resident.test.ResidentTestBootApplication; +import io.mosip.resident.util.AuditUtil; + +/** + * Resident proxy partner management controller test class. + * + * @author Ritik Jain + */ +@RunWith(SpringRunner.class) +@SpringBootTest(classes = ResidentTestBootApplication.class) +@AutoConfigureMockMvc +public class ProxyPartnerManagementControllerTest { + + @MockBean + private ProxyIdRepoService proxyIdRepoService; + + @MockBean + private ProxyPartnerManagementServiceImpl proxyPartnerManagementService; + + @Mock + private AuditUtil auditUtil; + + @MockBean + @Qualifier("selfTokenRestTemplate") + private RestTemplate residentRestTemplate; + + @InjectMocks + private ProxyPartnerManagementController proxyPartnerManagementController; + + @MockBean + private DocumentService docService; + + @MockBean + private ObjectStoreHelper objectStore; + + @MockBean + private CryptoCoreSpec encryptor; + + @MockBean + private ResidentVidService vidService; + + @MockBean + private ResidentServiceImpl residentService; + + @Mock + private Environment env; + + @Autowired + private MockMvc mockMvc; + + private ResponseWrapper responseWrapper; + + @Before + public void setUp() throws Exception { + responseWrapper = new ResponseWrapper<>(); + responseWrapper.setVersion("v1"); + responseWrapper.setId("1"); + MockitoAnnotations.initMocks(this); + this.mockMvc = MockMvcBuilders.standaloneSetup(proxyPartnerManagementController).build(); + Mockito.doNothing().when(auditUtil).setAuditRequestDto(Mockito.any()); + } + + @Test + public void testGetPartnersByPartnerType() throws Exception { + Mockito.when(proxyPartnerManagementService.getPartnersByPartnerType(Mockito.any())).thenReturn(responseWrapper); + mockMvc.perform(MockMvcRequestBuilders.get("/auth-proxy/partners?partnerType=")).andExpect(status().isOk()); + } + + @Test(expected = Exception.class) + public void testGetPartnersByPartnerTypeWithException() throws Exception { + Mockito.when(env.getProperty(Mockito.anyString())).thenReturn("property"); + Mockito.when(proxyPartnerManagementService.getPartnersByPartnerType(Mockito.any())) + .thenThrow(new ResidentServiceCheckedException()); + mockMvc.perform(MockMvcRequestBuilders.get("/auth-proxy/partners?partnerType=")).andExpect(status().isOk()); + } +} diff --git a/resident/resident-service/src/test/java/io/mosip/resident/test/controller/ResidentControllerTest.java b/resident/resident-service/src/test/java/io/mosip/resident/controller/ResidentControllerTest.java similarity index 66% rename from resident/resident-service/src/test/java/io/mosip/resident/test/controller/ResidentControllerTest.java rename to resident/resident-service/src/test/java/io/mosip/resident/controller/ResidentControllerTest.java index 2b13e1447af..0c582385b8d 100644 --- a/resident/resident-service/src/test/java/io/mosip/resident/test/controller/ResidentControllerTest.java +++ b/resident/resident-service/src/test/java/io/mosip/resident/controller/ResidentControllerTest.java @@ -1,9 +1,13 @@ -package io.mosip.resident.test.controller; +package io.mosip.resident.controller; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; @@ -34,12 +38,14 @@ import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.core.env.Environment; import org.springframework.core.io.InputStreamResource; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.security.test.context.support.WithUserDetails; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.util.ReflectionTestUtils; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; @@ -54,10 +60,10 @@ import io.mosip.kernel.core.http.ResponseWrapper; import io.mosip.kernel.core.util.DateUtils; import io.mosip.kernel.openid.bridge.api.service.validator.ScopeValidator; +import io.mosip.resident.constant.EventStatus; import io.mosip.resident.constant.IdType; import io.mosip.resident.constant.ResidentErrorCode; import io.mosip.resident.constant.ServiceType; -import io.mosip.resident.controller.ResidentController; import io.mosip.resident.dto.AidStatusRequestDTO; import io.mosip.resident.dto.AidStatusResponseDTO; import io.mosip.resident.dto.AuthHistoryRequestDTO; @@ -65,6 +71,7 @@ import io.mosip.resident.dto.AuthLockOrUnLockRequestDto; import io.mosip.resident.dto.AuthLockOrUnLockRequestDtoV2; import io.mosip.resident.dto.AuthTypeStatusDtoV2; +import io.mosip.resident.dto.BellNotificationDto; import io.mosip.resident.dto.EuinRequestDTO; import io.mosip.resident.dto.PageDto; import io.mosip.resident.dto.RegStatusCheckResponseDTO; @@ -80,9 +87,13 @@ import io.mosip.resident.dto.ResponseDTO; import io.mosip.resident.dto.ServiceHistoryResponseDto; import io.mosip.resident.dto.SortType; +import io.mosip.resident.dto.UnreadNotificationDto; import io.mosip.resident.dto.UserInfoDto; import io.mosip.resident.exception.ApisResourceAccessException; +import io.mosip.resident.exception.CardNotReadyException; +import io.mosip.resident.exception.InvalidInputException; import io.mosip.resident.exception.ResidentServiceCheckedException; +import io.mosip.resident.exception.ResidentServiceException; import io.mosip.resident.helper.ObjectStoreHelper; import io.mosip.resident.service.DocumentService; import io.mosip.resident.service.ProxyIdRepoService; @@ -93,6 +104,7 @@ import io.mosip.resident.test.ResidentTestBootApplication; import io.mosip.resident.util.AuditUtil; import io.mosip.resident.util.JsonUtil; +import io.mosip.resident.util.Utility; import io.mosip.resident.validator.RequestValidator; import reactor.util.function.Tuples; @@ -107,6 +119,8 @@ @TestPropertySource(locations = "classpath:application.properties") public class ResidentControllerTest { + private static final String LOCALE_EN_US = "en-US"; + @MockBean private ProxyIdRepoService proxyIdRepoService; @@ -140,6 +154,12 @@ public class ResidentControllerTest { @Mock private AuditUtil audit; + @Mock + private Utility utility; + + @Mock + private Environment environment; + @MockBean private CryptoCoreSpec encryptor; @@ -195,7 +215,6 @@ public void setUp() throws ApisResourceAccessException { authTypeStatusRequest.setRequesttime(LocalDateTime.now().toString()); authTypeStatusRequest.setVersion("v1"); authTypeStatusRequest.setId("io.mosip.resident.authHistory"); - gson = new GsonBuilder().serializeNulls().create(); authLockRequestToJson = gson.toJson(authLockRequest); euinRequestToJson = gson.toJson(euinRequest); @@ -204,6 +223,8 @@ public void setUp() throws ApisResourceAccessException { Mockito.doNothing().when(audit).setAuditRequestDto(Mockito.any()); when(identityServiceImpl.getResidentIndvidualIdFromSession()).thenReturn("5734728510"); + when(identityServiceImpl.getIndividualIdType(Mockito.any())).thenReturn("UIN"); + when(environment.getProperty(anyString())).thenReturn("property"); } @Test @@ -353,10 +374,10 @@ public void testRequestAuthUnLockBadRequest() throws Exception { public void testGetServiceHistorySuccess() throws Exception { ResponseWrapper> response = new ResponseWrapper<>(); Mockito.when(residentService.getServiceHistory(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), - Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.anyInt())).thenReturn(response); + Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.anyInt(), Mockito.any())).thenReturn(response); residentController.getServiceHistory("eng", 1, 12, LocalDate.parse("2022-06-10"), LocalDate.parse("2022-06-10"), SortType.ASC.toString(), - ServiceType.AUTHENTICATION_REQUEST.name(), null, null, 0); + ServiceType.AUTHENTICATION_REQUEST.name(), null, null, 0, LOCALE_EN_US); mockMvc.perform(MockMvcRequestBuilders.get("/service-history/eng").contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(status().isOk()); } @@ -494,7 +515,75 @@ public void testDownloadCardIndividualId() throws Exception { byte[] bytes = "abc".getBytes(StandardCharsets.UTF_8); when(residentService.downloadCard(Mockito.anyString())).thenReturn(bytes); ResponseEntity resultRequestWrapper = residentController - .downloadCard("9876543210", 0); + .downloadCard("9876543210", 0, LOCALE_EN_US); + assertEquals(responseEntity.getStatusCode(), resultRequestWrapper.getStatusCode()); + } + + @Test(expected = CardNotReadyException.class) + @WithUserDetails("reg-admin") + public void testDownloadCardIndividualIdCardNotReadyException() throws Exception { + ResponseEntity responseEntity; + byte[] pdfBytes = "test".getBytes(StandardCharsets.UTF_8); + InputStreamResource resource = new InputStreamResource(new ByteArrayInputStream(pdfBytes)); + responseEntity = ResponseEntity.ok().contentType(MediaType.parseMediaType("application/pdf")) + .header("Content-Disposition", "attachment; filename=\"" + + "abc" + ".pdf\"") + .body(resource); + ResponseWrapper responseWrapper = new ResponseWrapper<>(); + responseWrapper.setResponsetime(null); + ResponseWrapper objectResponseWrapper = new ResponseWrapper<>(); + responseWrapper.setResponse(objectResponseWrapper); + ResponseWrapper> resultResponseWrapper = new ResponseWrapper<>(); + + List list = new ArrayList<>(); + ResidentServiceHistoryResponseDto dto = new ResidentServiceHistoryResponseDto(); + dto.setId("12345"); + dto.setCardUrl("http://localhost:8080/mosip/resident/download-card/12345"); + dto.setRequestId("12345"); + dto.setStatusCode("200"); + list.add(dto); + resultResponseWrapper.setResponse(list); + resultResponseWrapper.setResponsetime(null); + byte[] bytes = "".getBytes(StandardCharsets.UTF_8); + ReflectionTestUtils.setField(residentController, "downloadCardEventidId", "id"); + when(residentService.downloadCard(Mockito.anyString())).thenReturn(bytes); + ResponseEntity resultRequestWrapper = residentController + .downloadCard("9876543210", 0, LOCALE_EN_US); + assertEquals(responseEntity.getStatusCode(), resultRequestWrapper.getStatusCode()); + } + + @Test(expected = ResidentServiceException.class) + @WithUserDetails("reg-admin") + public void testDownloadCardIndividualIdInvalidInputException() throws Exception { + doThrow(new InvalidInputException()). + when(validator).validateEventId(any()); + ResponseEntity responseEntity; + byte[] pdfBytes = "test".getBytes(StandardCharsets.UTF_8); + InputStreamResource resource = new InputStreamResource(new ByteArrayInputStream(pdfBytes)); + responseEntity = ResponseEntity.ok().contentType(MediaType.parseMediaType("application/pdf")) + .header("Content-Disposition", "attachment; filename=\"" + + "abc" + ".pdf\"") + .body(resource); + ResponseWrapper responseWrapper = new ResponseWrapper<>(); + responseWrapper.setResponsetime(null); + ResponseWrapper objectResponseWrapper = new ResponseWrapper<>(); + responseWrapper.setResponse(objectResponseWrapper); + ResponseWrapper> resultResponseWrapper = new ResponseWrapper<>(); + + List list = new ArrayList<>(); + ResidentServiceHistoryResponseDto dto = new ResidentServiceHistoryResponseDto(); + dto.setId("12345"); + dto.setCardUrl("http://localhost:8080/mosip/resident/download-card/12345"); + dto.setRequestId("12345"); + dto.setStatusCode("200"); + list.add(dto); + resultResponseWrapper.setResponse(list); + resultResponseWrapper.setResponsetime(null); + byte[] bytes = "a".getBytes(StandardCharsets.UTF_8); + ReflectionTestUtils.setField(residentController, "downloadCardEventidId", "id"); + when(residentService.downloadCard(Mockito.anyString())).thenReturn(bytes); + ResponseEntity resultRequestWrapper = residentController + .downloadCard("9876543210", 0, LOCALE_EN_US); assertEquals(responseEntity.getStatusCode(), resultRequestWrapper.getStatusCode()); } @@ -509,7 +598,7 @@ public void testCheckAidStatus() throws Exception { requestWrapper.setRequest(aidStatusRequestDTO); requestWrapper.setId("mosip.resident.uin"); requestWrapper.setVersion("1.0"); - Mockito.when(residentService.getAidStatus(Mockito.any())).thenReturn(new AidStatusResponseDTO()); + Mockito.when(residentService.getAidStatus(Mockito.any(), Mockito.anyBoolean())).thenReturn(new AidStatusResponseDTO()); String requestAsString = gson.toJson(requestWrapper); this.mockMvc .perform( @@ -520,12 +609,18 @@ public void testCheckAidStatus() throws Exception { @Test @WithUserDetails("reg-admin") public void testGetCredentialRequestStatusSuccess() throws Exception { - residentController.checkAidStatus("17", "eng", 0); - when(residentService.checkAidStatus("17")).thenReturn("PROCESSED"); + residentController.checkEventIdStatus("17", "eng", 0, LOCALE_EN_US); this.mockMvc.perform(get("/events/86c2ad43-e2a4-4952-bafc-d97ad1e5e453/?langCode=eng")) .andExpect(status().isOk()); } - + + @Test(expected = Exception.class) + @WithUserDetails("reg-admin") + public void testCheckEventIdStatusWithException() throws Exception { + when(residentService.getEventStatus(anyString(), anyString(), anyInt(), anyString())).thenThrow(new ResidentServiceCheckedException()); + residentController.checkEventIdStatus("17", "eng", 0, LOCALE_EN_US); + } + @Test @WithUserDetails("reg-admin") public void testGetUserInfo() throws Exception { @@ -533,9 +628,125 @@ public void testGetUserInfo() throws Exception { user.setFullName("name"); ResponseWrapper response = new ResponseWrapper<>(); response.setResponse(user); - residentController.userinfo(0); - Mockito.when(residentService.getUserinfo(Mockito.any(), Mockito.anyInt())).thenReturn(response); + residentController.userinfo(0, LOCALE_EN_US); + Mockito.when(residentService.getUserinfo(Mockito.any(), Mockito.anyInt(), Mockito.anyString())).thenReturn(response); this.mockMvc.perform(get("/profile")) .andExpect(status().isOk()); } + + @Test(expected = Exception.class) + @WithUserDetails("reg-admin") + public void testGetUserInfoWithException() throws Exception { + Mockito.when(residentService.getUserinfo(Mockito.any(), Mockito.anyInt(), Mockito.anyString())).thenThrow(new ApisResourceAccessException()); + residentController.userinfo(0, LOCALE_EN_US); + } + + @Test + @WithUserDetails("reg-admin") + public void testBellClickdttimes() throws Exception { + BellNotificationDto dto = new BellNotificationDto(); + dto.setLastbellnotifclicktime(LocalDateTime.now()); + ResponseWrapper response = new ResponseWrapper<>(); + response.setResponse(dto); + Mockito.when(residentService.getbellClickdttimes(Mockito.anyString())).thenReturn(response); + residentController.bellClickdttimes(); + } + + @Test(expected = Exception.class) + @WithUserDetails("reg-admin") + public void testBellClickdttimesWithException() throws Exception { + when(identityServiceImpl.getResidentIdaToken()).thenThrow(new ApisResourceAccessException()); + residentController.bellClickdttimes(); + } + + @Test + @WithUserDetails("reg-admin") + public void testNotificationCount() throws Exception { + UnreadNotificationDto dto = new UnreadNotificationDto(); + dto.setUnreadCount(10L); + ResponseWrapper response = new ResponseWrapper<>(); + response.setResponse(dto); + Mockito.when(residentService.getnotificationCount(Mockito.anyString())).thenReturn(response); + residentController.notificationCount(); + } + + @Test + @WithUserDetails("reg-admin") + public void testBellupdateClickdttimes() throws Exception { + int response = 10; + Mockito.when(residentService.updatebellClickdttimes(Mockito.anyString())).thenReturn(response); + residentController.bellupdateClickdttimes(); + } + + @Test + @WithUserDetails("reg-admin") + public void testGetNotificationsList() throws Exception { + PageDto dto = new PageDto(); + dto.setData(List.of()); + ResponseWrapper> response = new ResponseWrapper<>(); + response.setResponse(dto); + Mockito.when(residentService.getNotificationList(Mockito.anyInt(), Mockito.anyInt(), Mockito.anyString(), + Mockito.anyString(), Mockito.anyInt(), Mockito.anyString())).thenReturn(response); + residentController.getNotificationsList("eng", 0, 10, 0, LOCALE_EN_US); + } + + @Test(expected = Exception.class) + @WithUserDetails("reg-admin") + public void testGetNotificationsListWithException() throws Exception { + when(identityServiceImpl.getResidentIdaToken()).thenThrow(new ApisResourceAccessException()); + residentController.getNotificationsList("eng", 0, 10, 0, LOCALE_EN_US); + } + + @Test + @WithUserDetails("reg-admin") + public void testDownLoadServiceHistory() throws Exception { + ReflectionTestUtils.setField(residentController, "maxEventsServiceHistoryPageSize", 10); + ServiceHistoryResponseDto serviceHistoryResponseDto = new ServiceHistoryResponseDto(); + serviceHistoryResponseDto.setEventId("1234567890"); + serviceHistoryResponseDto.setEventStatus("Success"); + PageDto dto = new PageDto<>(); + dto.setData(List.of(serviceHistoryResponseDto)); + dto.setPageNo(0); + dto.setPageSize(10); + ResponseWrapper> response = new ResponseWrapper<>(); + response.setResponse(dto); + Mockito.when(residentService.getServiceHistory(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), + Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.anyInt(), + Mockito.any())).thenReturn(response); + Mockito.when(utility.getFileName(Mockito.anyString(), Mockito.anyString(), Mockito.anyInt(), Mockito.anyString())).thenReturn("filename"); + byte[] bytes = "abc".getBytes(StandardCharsets.UTF_8); + Mockito.when( + residentService.downLoadServiceHistory(Mockito.any(), Mockito.anyString(), Mockito.any(), Mockito.any(), + Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyInt(), Mockito.anyString())) + .thenReturn(bytes); + residentController.downLoadServiceHistory(LocalDateTime.now(), LocalDate.now(), LocalDate.now(), SortType.ASC.name(), + ServiceType.ID_MANAGEMENT_REQUEST.name(), EventStatus.SUCCESS.getStatus(), "", "eng", 0, LOCALE_EN_US); + } + + @Test(expected = Exception.class) + @WithUserDetails("reg-admin") + public void testDownLoadServiceHistoryWithException() throws Exception { + ReflectionTestUtils.setField(residentController, "maxEventsServiceHistoryPageSize", 10); + Mockito.when(residentService.getServiceHistory(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), + Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.anyInt(), + Mockito.any())).thenThrow(new ApisResourceAccessException()); + residentController.downLoadServiceHistory(LocalDateTime.now(), LocalDate.now(), LocalDate.now(), SortType.ASC.name(), + ServiceType.ID_MANAGEMENT_REQUEST.name(), EventStatus.SUCCESS.getStatus(), "", "eng", 0, LOCALE_EN_US); + } + + @Test(expected = ResidentServiceException.class) + @WithUserDetails("reg-admin") + public void testCheckAidStatusWithException() throws Exception { + ReflectionTestUtils.setField(residentController, "checkStatusId", "id"); + AidStatusRequestDTO aidStatusRequestDTO = new AidStatusRequestDTO(); + aidStatusRequestDTO.setIndividualId("5734728510"); + aidStatusRequestDTO.setOtp("111111"); + aidStatusRequestDTO.setTransactionId("1234567890"); + RequestWrapper reqDto = new RequestWrapper<>(); + reqDto.setRequest(aidStatusRequestDTO); + AidStatusResponseDTO response = new AidStatusResponseDTO(); + response.setAidStatus("uin generator"); + Mockito.when(residentService.getAidStatus(Mockito.any(), Mockito.anyBoolean())).thenThrow(new ResidentServiceCheckedException("res-ser", "error")); + residentController.checkAidStatus(reqDto); + } } diff --git a/resident/resident-service/src/test/java/io/mosip/resident/test/controller/ResidentCredentialControllerTest.java b/resident/resident-service/src/test/java/io/mosip/resident/controller/ResidentCredentialControllerTest.java similarity index 98% rename from resident/resident-service/src/test/java/io/mosip/resident/test/controller/ResidentCredentialControllerTest.java rename to resident/resident-service/src/test/java/io/mosip/resident/controller/ResidentCredentialControllerTest.java index 0d8a034ac30..ea3088ee31c 100644 --- a/resident/resident-service/src/test/java/io/mosip/resident/test/controller/ResidentCredentialControllerTest.java +++ b/resident/resident-service/src/test/java/io/mosip/resident/controller/ResidentCredentialControllerTest.java @@ -1,4 +1,4 @@ -package io.mosip.resident.test.controller; +package io.mosip.resident.controller; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @@ -33,7 +33,6 @@ import io.mosip.kernel.cbeffutil.impl.CbeffImpl; import io.mosip.kernel.core.crypto.spi.CryptoCoreSpec; -import io.mosip.resident.controller.ResidentCredentialController; import io.mosip.resident.dto.CredentialCancelRequestResponseDto; import io.mosip.resident.dto.CredentialRequestStatusResponseDto; import io.mosip.resident.dto.PartnerCredentialTypePolicyDto; @@ -203,7 +202,7 @@ public void testPartnerIdCredentialType() throws Exception { @Test public void testRequestShareCredWithPartner() throws Exception { - Mockito.when(residentCredentialService.shareCredential(Mockito.any(), Mockito.anyString(), Mockito.anyString())) + Mockito.when(residentCredentialService.shareCredential(Mockito.any(), Mockito.anyString(), Mockito.any())) .thenReturn(Tuples.of(dtoV2, "12345")); ShareCredentialRequestDto request = new ShareCredentialRequestDto(); SharableAttributesDTO attr = new SharableAttributesDTO(); diff --git a/resident/resident-service/src/test/java/io/mosip/resident/test/controller/ResidentOtpControllerTest.java b/resident/resident-service/src/test/java/io/mosip/resident/controller/ResidentOtpControllerTest.java similarity index 74% rename from resident/resident-service/src/test/java/io/mosip/resident/test/controller/ResidentOtpControllerTest.java rename to resident/resident-service/src/test/java/io/mosip/resident/controller/ResidentOtpControllerTest.java index 292a0b1c26f..5c1e5e747bb 100644 --- a/resident/resident-service/src/test/java/io/mosip/resident/test/controller/ResidentOtpControllerTest.java +++ b/resident/resident-service/src/test/java/io/mosip/resident/controller/ResidentOtpControllerTest.java @@ -1,10 +1,11 @@ -package io.mosip.resident.test.controller; +package io.mosip.resident.controller; import static org.junit.Assert.assertNotNull; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doThrow; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import org.junit.Before; -import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; @@ -29,11 +30,12 @@ import com.google.gson.Gson; import com.google.gson.GsonBuilder; -import io.mosip.resident.controller.ResidentOtpController; import io.mosip.resident.dto.IndividualIdOtpRequestDTO; import io.mosip.resident.dto.IndividualIdResponseDto; import io.mosip.resident.dto.OtpRequestDTO; import io.mosip.resident.dto.OtpResponseDTO; +import io.mosip.resident.exception.InvalidInputException; +import io.mosip.resident.exception.ResidentServiceCheckedException; import io.mosip.resident.handler.service.ResidentUpdateService; import io.mosip.resident.handler.service.UinCardRePrintService; import io.mosip.resident.helper.ObjectStoreHelper; @@ -146,18 +148,45 @@ public void createRequestGenerationSuccessTest() throws Exception { .perform(MockMvcRequestBuilders.post("/req/otp").contentType(MediaType.APPLICATION_JSON).content(json)) .andExpect(status().isOk());// .andExpect(jsonPath("$.response.vid", is("12345"))) } - - @Ignore + @Test public void reqOtpForAidTest() throws Exception { IndividualIdOtpRequestDTO individualIdOtpRequestDTO = new IndividualIdOtpRequestDTO(); individualIdOtpRequestDTO.setIndividualId("123456789"); - Mockito.when(residentOtpService.generateOtp(otpRequestDTO)).thenReturn(otpResponseDTO); + IndividualIdResponseDto individualIdResponseDto = new IndividualIdResponseDto(); + individualIdResponseDto.setTransactionId("12345678"); + Mockito.when(residentOtpService.generateOtpForIndividualId(individualIdOtpRequestDTO)).thenReturn(individualIdResponseDto); Gson gson = new GsonBuilder().serializeNulls().create(); String json = gson.toJson(individualIdOtpRequestDTO); this.mockMvc.perform( MockMvcRequestBuilders.post("/individualId/otp").contentType(MediaType.APPLICATION_JSON).content(json)) - .andExpect(status().isOk());// .andExpect(jsonPath("$.response.vid", is("12345"))) + .andExpect(status().isOk()); + } + + @Test(expected = Exception.class) + public void reqOtpForAidTestResidentServiceCheckedException() throws Exception { + IndividualIdOtpRequestDTO individualIdOtpRequestDTO = new IndividualIdOtpRequestDTO(); + individualIdOtpRequestDTO.setIndividualId("123456789"); + IndividualIdResponseDto individualIdResponseDto = new IndividualIdResponseDto(); + individualIdResponseDto.setTransactionId("12345678"); + Mockito.when(residentOtpService.generateOtpForIndividualId(individualIdOtpRequestDTO)).thenThrow(new ResidentServiceCheckedException("res-ser", "error thrown")); + Gson gson = new GsonBuilder().serializeNulls().create(); + String json = gson.toJson(individualIdOtpRequestDTO); + this.mockMvc.perform( + MockMvcRequestBuilders.post("/individualId/otp").contentType(MediaType.APPLICATION_JSON).content(json)) + .andExpect(status().isOk()); + } + + @Test(expected = Exception.class) + public void reqOtpForAidTestInvalidInputException() throws Exception { + doThrow(new InvalidInputException()).when(validator).validateReqOtp(any()); + IndividualIdOtpRequestDTO individualIdOtpRequestDTO = new IndividualIdOtpRequestDTO(); + individualIdOtpRequestDTO.setIndividualId("123456789"); + Gson gson = new GsonBuilder().serializeNulls().create(); + String json = gson.toJson(individualIdOtpRequestDTO); + this.mockMvc.perform( + MockMvcRequestBuilders.post("/individualId/otp").contentType(MediaType.APPLICATION_JSON).content(json)) + .andExpect(status().isOk()); } @WithUserDetails("resident") diff --git a/resident/resident-service/src/test/java/io/mosip/resident/controller/ResidentVerificationControllerTest.java b/resident/resident-service/src/test/java/io/mosip/resident/controller/ResidentVerificationControllerTest.java new file mode 100644 index 00000000000..9ebeb54e1ec --- /dev/null +++ b/resident/resident-service/src/test/java/io/mosip/resident/controller/ResidentVerificationControllerTest.java @@ -0,0 +1,114 @@ +package io.mosip.resident.controller; + +import static org.mockito.Mockito.doThrow; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.test.context.TestPropertySource; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.client.RestTemplate; + +import io.mosip.resident.dto.VerificationResponseDTO; +import io.mosip.resident.exception.ResidentServiceCheckedException; +import io.mosip.resident.helper.ObjectStoreHelper; +import io.mosip.resident.service.DocumentService; +import io.mosip.resident.service.IdAuthService; +import io.mosip.resident.service.ProxyIdRepoService; +import io.mosip.resident.service.ResidentVidService; +import io.mosip.resident.service.VerificationService; +import io.mosip.resident.service.impl.ResidentServiceImpl; +import io.mosip.resident.test.ResidentTestBootApplication; +import io.mosip.resident.util.AuditUtil; +import io.mosip.resident.validator.RequestValidator; + +/** + * Resident Verification Controller Test Note: This class is used to test the + * Resident Verification Controller + * + * @author Kamesh Shekhar Prasad + */ + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = ResidentTestBootApplication.class) +@AutoConfigureMockMvc +@TestPropertySource(locations = "classpath:application.properties") +public class ResidentVerificationControllerTest { + + @MockBean + private ProxyIdRepoService proxyIdRepoService; + + @MockBean + private VerificationService verificationService; + + @MockBean + private IdAuthService idAuthService; + + @MockBean + private ResidentVidService vidService; + + @MockBean + private DocumentService docService; + + @MockBean + private ObjectStoreHelper objectStore; + + @MockBean + private RequestValidator requestValidator; + + @MockBean + @Qualifier("selfTokenRestTemplate") + private RestTemplate residentRestTemplate; + + @MockBean + private ResidentServiceImpl residentService; + + @Mock + private AuditUtil audit; + + @InjectMocks + VerificationController verificationController; + + @Autowired + private MockMvc mockMvc; + + VerificationResponseDTO verificationResponseDTO; + + @Before + public void setup() throws Exception { + verificationResponseDTO = new VerificationResponseDTO(); + MockitoAnnotations.initMocks(this); + this.mockMvc = MockMvcBuilders.standaloneSetup(verificationController).build(); + } + + @Test + public void testCreateRequestGenerationSuccess() throws Exception { + Mockito.when(verificationService.checkChannelVerificationStatus(Mockito.any(), Mockito.any())) + .thenReturn(verificationResponseDTO); + mockMvc.perform( + MockMvcRequestBuilders.get("/channel/verification-status/?channel=EMAIL&individualId=8251649601")) + .andExpect(status().isOk()); + } + + @Test(expected = Exception.class) + public void testGetChannelVerificationStatusWithException() throws Exception { + doThrow(new ResidentServiceCheckedException()).when(verificationService) + .checkChannelVerificationStatus(Mockito.anyString(), Mockito.anyString()); + mockMvc.perform( + MockMvcRequestBuilders.get("/channel/verification-status/?channel=EMAIL&individualId=8251649601")) + .andExpect(status().isOk()); + } +} diff --git a/resident/resident-service/src/test/java/io/mosip/resident/test/controller/ResidentVidControllerTest.java b/resident/resident-service/src/test/java/io/mosip/resident/controller/ResidentVidControllerTest.java similarity index 80% rename from resident/resident-service/src/test/java/io/mosip/resident/test/controller/ResidentVidControllerTest.java rename to resident/resident-service/src/test/java/io/mosip/resident/controller/ResidentVidControllerTest.java index a0c2963b346..c155e492cc6 100644 --- a/resident/resident-service/src/test/java/io/mosip/resident/test/controller/ResidentVidControllerTest.java +++ b/resident/resident-service/src/test/java/io/mosip/resident/controller/ResidentVidControllerTest.java @@ -1,4 +1,4 @@ -package io.mosip.resident.test.controller; +package io.mosip.resident.controller; import static org.hamcrest.CoreMatchers.is; import static org.mockito.ArgumentMatchers.any; @@ -9,9 +9,13 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import java.util.List; +import java.util.Map; + import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; +import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; @@ -26,7 +30,6 @@ import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.RequestBuilder; import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.web.client.RestTemplate; @@ -38,10 +41,13 @@ import io.mosip.resident.dto.BaseVidRequestDto; import io.mosip.resident.dto.RequestWrapper; import io.mosip.resident.dto.ResidentVidRequestDto; +import io.mosip.resident.dto.ResidentVidRequestDtoV2; import io.mosip.resident.dto.ResponseWrapper; import io.mosip.resident.dto.VidRequestDto; +import io.mosip.resident.dto.VidRequestDtoV2; import io.mosip.resident.dto.VidResponseDto; import io.mosip.resident.dto.VidRevokeRequestDTO; +import io.mosip.resident.dto.VidRevokeRequestDTOV2; import io.mosip.resident.dto.VidRevokeResponseDTO; import io.mosip.resident.exception.ApisResourceAccessException; import io.mosip.resident.exception.OtpValidationFailedException; @@ -58,6 +64,8 @@ import io.mosip.resident.test.ResidentTestBootApplication; import io.mosip.resident.util.AuditUtil; import io.mosip.resident.util.ResidentServiceRestClient; +import io.mosip.resident.validator.RequestValidator; +import reactor.util.function.Tuples; @RunWith(SpringRunner.class) @SpringBootTest(classes = ResidentTestBootApplication.class) @@ -71,6 +79,9 @@ public class ResidentVidControllerTest { @MockBean private ResidentVidServiceImpl residentVidService; + @InjectMocks + private ResidentVidController residentVidController; + @MockBean private IdAuthServiceImpl idAuthService; @@ -103,6 +114,9 @@ public class ResidentVidControllerTest { @Mock private AuditUtil audit; + @Mock + private RequestValidator validator; + @Before public void setup() throws ApisResourceAccessException { MockitoAnnotations.initMocks(this); @@ -155,7 +169,7 @@ public void vidCreationFailureTest() throws Exception { String json = gson.toJson(getRequest()); this.mockMvc.perform(post("/vid").contentType(MediaType.APPLICATION_JSON).content(json)) - .andExpect(status().isOk()).andExpect(jsonPath("$.errors[0].errorCode", is("RES-SER-418"))); + .andExpect(status().isOk()).andExpect(jsonPath("$.errors[0].errorCode", is("RES-SER-406"))); } @Test @@ -239,27 +253,16 @@ public void invalidOtp() throws Exception { @Test @WithUserDetails("resident") - public void vidRevokingFailureTest() throws Exception { - + public void vidRevokingSuccessTest() throws Exception { VidRevokeResponseDTO dto = new VidRevokeResponseDTO(); dto.setMessage("Successful"); - ResponseWrapper responseWrapper = new ResponseWrapper<>(); responseWrapper.setResponse(dto); - Mockito.when(residentVidService.revokeVid(Mockito.any(VidRevokeRequestDTO.class), Mockito.anyString(), Mockito.anyString())) + Mockito.when(residentVidService.revokeVid(Mockito.any(), Mockito.anyString(), Mockito.anyString())) .thenReturn(responseWrapper); - Gson gson = new GsonBuilder().serializeNulls().create(); - String json = gson.toJson(getRevokeRequest()); - - RequestBuilder builder = MockMvcRequestBuilders.patch("/vid/{vid}", "2038096257310540").content(json) - .contentType(MediaType.APPLICATION_JSON_VALUE).accept(MediaType.APPLICATION_JSON_VALUE) - .characterEncoding("UTF-8"); - - this.mockMvc.perform(builder).andExpect(status().isOk()); - // .andExpect(jsonPath("$.response.message", is("Successful"))); - + residentVidController.revokeVid(getRevokeRequest(), "123457987765422"); } @Test @@ -277,7 +280,7 @@ public void vidRevokingFailureTest2() throws Exception { .characterEncoding("UTF-8"); this.mockMvc.perform(builder).andExpect(status().isOk()) - .andExpect(jsonPath("$.errors[0].errorCode", is("RES-SER-418"))); + .andExpect(jsonPath("$.errors[0].errorCode", is("RES-SER-407"))); } @@ -485,26 +488,73 @@ public void vidCreationV2SuccessTest() throws Exception { @Test @WithUserDetails("reg-admin") public void vidRevokingV2SuccessTest() throws Exception { - + Mockito.when(identityServiceImpl.getResidentIndvidualIdFromSession()).thenReturn("12345678"); VidRevokeResponseDTO dto = new VidRevokeResponseDTO(); dto.setMessage("Successful"); ResponseWrapper responseWrapper = new ResponseWrapper<>(); responseWrapper.setResponse(dto); - Mockito.when(residentVidService.revokeVid(Mockito.any(VidRevokeRequestDTO.class), any(), Mockito.anyString())) + Mockito.when(residentVidService.revokeVidV2(Mockito.any(), Mockito.anyString(), Mockito.anyString())) + .thenReturn(Tuples.of(responseWrapper, "12345")); + + VidRevokeRequestDTOV2 vidRevokeRequestDTOV2 = new VidRevokeRequestDTOV2(); + vidRevokeRequestDTOV2.setTransactionID("1234567890"); + vidRevokeRequestDTOV2.setVidStatus("revoked"); + RequestWrapper requestDto = new RequestWrapper<>(); + requestDto.setRequest(vidRevokeRequestDTOV2); + residentVidController.revokeVidV2(requestDto, "1234567432456"); + } + + @Test(expected = ResidentServiceCheckedException.class) + @WithUserDetails("reg-admin") + public void testRevokeVidV2() throws Exception { + Mockito.when(identityServiceImpl.getResidentIndvidualIdFromSession()).thenReturn("1234567432456"); + VidRevokeRequestDTOV2 vidRevokeRequestDTOV2 = new VidRevokeRequestDTOV2(); + vidRevokeRequestDTOV2.setTransactionID("1234567890"); + vidRevokeRequestDTOV2.setVidStatus("revoked"); + RequestWrapper requestDto = new RequestWrapper<>(); + requestDto.setRequest(vidRevokeRequestDTOV2); + residentVidController.revokeVidV2(requestDto, "1234567432456"); + } + + @Test + @WithUserDetails("reg-admin") + public void testRetrieveVids() throws Exception { + ResponseWrapper>> responseWrapper = new ResponseWrapper<>(); + Mockito.when(identityServiceImpl.getResidentIndvidualIdFromSession()).thenReturn("12345678"); + Mockito.when(residentVidService.retrieveVids(Mockito.anyString(), Mockito.anyInt(), Mockito.anyString())) .thenReturn(responseWrapper); + residentVidController.retrieveVids(0, "En-us"); + } - Gson gson = new GsonBuilder().serializeNulls().create(); - String json = gson.toJson(getRevokeRequest()); + @Test(expected = Exception.class) + @WithUserDetails("reg-admin") + public void testRetrieveVidsWithException() throws Exception { + Mockito.when(identityServiceImpl.getResidentIndvidualIdFromSession()).thenReturn("12345678"); + Mockito.when(residentVidService.retrieveVids(Mockito.anyString(), Mockito.anyInt(), Mockito.nullable(String.class))) + .thenThrow(new ApisResourceAccessException()); + residentVidController.retrieveVids(0, "En-us"); + } - RequestBuilder builder = MockMvcRequestBuilders.patch("/revoke-vid/{vid}", "2038096257310540").content(json) - .contentType(MediaType.APPLICATION_JSON_VALUE).accept(MediaType.APPLICATION_JSON_VALUE) - .characterEncoding("UTF-8"); + @Test + @WithUserDetails("resident") + public void testGenerateVidV2() throws Exception { + Mockito.when(identityServiceImpl.getResidentIndvidualIdFromSession()).thenReturn("12345678"); + VidResponseDto dto = new VidResponseDto(); + dto.setVid("12345"); + dto.setMessage("Successful"); + ResponseWrapper responseWrapper = new ResponseWrapper<>(); + responseWrapper.setResponse(dto); - this.mockMvc.perform(builder).andExpect(status().isOk()); - // .andExpect(jsonPath("$.response.message", is("Successful"))); + Mockito.when(residentVidService.generateVidV2(Mockito.any(), Mockito.anyString())).thenReturn(Tuples.of(responseWrapper, "12345")); + VidRequestDtoV2 vidRequestDtoV2 = new VidRequestDtoV2(); + vidRequestDtoV2.setTransactionID("1234567890"); + vidRequestDtoV2.setVidType("perpetual"); + vidRequestDtoV2.setChannels(List.of("email")); + ResidentVidRequestDtoV2 requestDto = new ResidentVidRequestDtoV2(); + requestDto.setRequest(vidRequestDtoV2); + residentVidController.generateVidV2(requestDto); } - } diff --git a/resident/resident-service/src/test/java/io/mosip/resident/controller/TransliterationControllerTest.java b/resident/resident-service/src/test/java/io/mosip/resident/controller/TransliterationControllerTest.java new file mode 100644 index 00000000000..7c9391a9b71 --- /dev/null +++ b/resident/resident-service/src/test/java/io/mosip/resident/controller/TransliterationControllerTest.java @@ -0,0 +1,86 @@ +package io.mosip.resident.controller; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.web.client.RestTemplate; + +import io.mosip.preregistration.application.dto.TransliterationRequestDTO; +import io.mosip.preregistration.application.dto.TransliterationResponseDTO; +import io.mosip.preregistration.application.service.TransliterationService; +import io.mosip.preregistration.core.common.dto.MainRequestDTO; +import io.mosip.preregistration.core.common.dto.MainResponseDTO; +import io.mosip.resident.helper.ObjectStoreHelper; +import io.mosip.resident.service.IdAuthService; +import io.mosip.resident.service.impl.IdentityServiceImpl; +import io.mosip.resident.service.impl.ResidentVidServiceImpl; +import io.mosip.resident.util.AuditUtil; +import io.mosip.resident.validator.RequestValidator; + +/** + * Acknowledgment Controller Test + * Note: This class is used to test the Acknowledgment Controller + * @author Kamesh Shekhar Prasad + */ + +@RunWith(MockitoJUnitRunner.class) +@ContextConfiguration +public class TransliterationControllerTest { + @InjectMocks + private TransliterationController transliterationController; + + @Mock + private AuditUtil auditUtil; + + @Mock + private RequestValidator requestValidator; + + @Mock + private TransliterationService transliterationService; + + @Mock + private IdentityServiceImpl identityService; + + @Mock + private ObjectStoreHelper objectStore; + + @Mock + private ResidentVidServiceImpl residentVidService; + + @MockBean + @Qualifier("selfTokenRestTemplate") + private RestTemplate residentRestTemplate; + + @Mock + private IdAuthService idAuthService; + + private ResponseEntity> response; + + @Test + public void testCreateRequestGenerationSuccess() throws Exception { + MainResponseDTO response = new MainResponseDTO<>(); + TransliterationResponseDTO dto = new TransliterationResponseDTO(); + response.setResponse(dto); + MainRequestDTO requestDTO = new MainRequestDTO<>(); + TransliterationRequestDTO transliterationRequestDTO = new TransliterationRequestDTO(); + transliterationRequestDTO.setFromFieldLang("eng"); + transliterationRequestDTO.setFromFieldValue("cat"); + transliterationRequestDTO.setToFieldLang("hin"); + requestDTO.setRequest(transliterationRequestDTO); + Mockito.when(transliterationService.translitratorService(Mockito.any())).thenReturn(response); + + ResponseEntity> responseEntity = transliterationController.translitrator(requestDTO); + assertEquals(responseEntity.getStatusCode(), HttpStatus.OK); + } + +} diff --git a/resident/resident-service/src/test/java/io/mosip/resident/controller/WebSubCredentialStatusUpdateControllerTest.java b/resident/resident-service/src/test/java/io/mosip/resident/controller/WebSubCredentialStatusUpdateControllerTest.java new file mode 100644 index 00000000000..5f6a5ecf044 --- /dev/null +++ b/resident/resident-service/src/test/java/io/mosip/resident/controller/WebSubCredentialStatusUpdateControllerTest.java @@ -0,0 +1,138 @@ +package io.mosip.resident.controller; + +import static org.mockito.ArgumentMatchers.anyMap; +import static org.mockito.Mockito.doThrow; + +import java.time.LocalDateTime; +import java.util.Map; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.http.MediaType; +import org.springframework.test.context.TestPropertySource; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.client.RestTemplate; + +import com.fasterxml.jackson.databind.ObjectMapper; + +import io.mosip.kernel.core.websub.model.Event; +import io.mosip.kernel.core.websub.model.EventModel; +import io.mosip.resident.exception.ResidentServiceCheckedException; +import io.mosip.resident.exception.ResidentServiceException; +import io.mosip.resident.helper.ObjectStoreHelper; +import io.mosip.resident.service.DocumentService; +import io.mosip.resident.service.IdAuthService; +import io.mosip.resident.service.ProxyIdRepoService; +import io.mosip.resident.service.ResidentVidService; +import io.mosip.resident.service.VerificationService; +import io.mosip.resident.service.WebSubCredentialStatusUpdateService; +import io.mosip.resident.service.impl.ResidentServiceImpl; +import io.mosip.resident.test.ResidentTestBootApplication; +import io.mosip.resident.util.AuditUtil; + +/** + * Web-Sub Credential Status Update Controller Test Note: This class is used to + * test the Web-Sub Credential Status Update Controller + * + * @author Ritik Jain + */ + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = ResidentTestBootApplication.class) +@AutoConfigureMockMvc +@TestPropertySource(locations = "classpath:application.properties") +public class WebSubCredentialStatusUpdateControllerTest { + + @MockBean + private ProxyIdRepoService proxyIdRepoService; + + @MockBean + @Qualifier("selfTokenRestTemplate") + private RestTemplate residentRestTemplate; + + @Mock + private AuditUtil audit; + + @InjectMocks + WebSubCredentialStatusUpdateController webSubCredentialStatusUpdateController; + + @MockBean + WebSubCredentialStatusUpdateService webSubCredentialStatusUpdateService; + + @Autowired + private MockMvc mockMvc; + + @MockBean + private VerificationService verificationService; + + @MockBean + private IdAuthService idAuthService; + + @MockBean + private ResidentVidService vidService; + + @MockBean + private DocumentService docService; + + @MockBean + private ObjectStoreHelper objectStore; + + @MockBean + VerificationController verificationController; + + @MockBean + private ResidentServiceImpl residentService; + + @Autowired + private ObjectMapper objectMapper; + + @Before + public void setup() throws Exception { + + MockitoAnnotations.initMocks(this); + this.mockMvc = MockMvcBuilders.standaloneSetup(webSubCredentialStatusUpdateController).build(); + } + + @Test + public void testCredentialStatusUpdateCallback() throws Exception { + + EventModel eventModel = new EventModel(); + Event event = new Event(); + event.setTransactionId("1234"); + event.setId("8251649601"); + Map partnerIdMap = new java.util.HashMap<>(); + partnerIdMap.put("olv_partner_id", "mpartner-default-auth"); + event.setData(partnerIdMap); + + eventModel.setEvent(event); + eventModel.setTopic("CREDENTIAL_STATUS_UPDATE_CALL_BACK"); + eventModel.setPublishedOn(String.valueOf(LocalDateTime.now())); + eventModel.setPublisher("CREDENTIAL_STATUS_UPDATE_CALL_BACK"); + webSubCredentialStatusUpdateController + .credentialStatusUpdateCallback(objectMapper.convertValue(eventModel, Map.class)); + + mockMvc.perform((MockMvcRequestBuilders.post("/callback/credentialStatusUpdate")) + .contentType(MediaType.APPLICATION_JSON).content(eventModel.toString())).andReturn(); + } + + @Test(expected = ResidentServiceException.class) + public void testCredentialStatusUpdateCallbackWithException() throws Exception { + EventModel eventModel = new EventModel(); + doThrow(new ResidentServiceCheckedException()).when(webSubCredentialStatusUpdateService) + .updateCredentialStatus(anyMap()); + webSubCredentialStatusUpdateController + .credentialStatusUpdateCallback(objectMapper.convertValue(eventModel, Map.class)); + } +} diff --git a/resident/resident-service/src/test/java/io/mosip/resident/controller/WebSubUpdateAuthTypeControllerTest.java b/resident/resident-service/src/test/java/io/mosip/resident/controller/WebSubUpdateAuthTypeControllerTest.java new file mode 100644 index 00000000000..eaf0bc2969a --- /dev/null +++ b/resident/resident-service/src/test/java/io/mosip/resident/controller/WebSubUpdateAuthTypeControllerTest.java @@ -0,0 +1,135 @@ +package io.mosip.resident.controller; + +import static org.mockito.ArgumentMatchers.anyMap; +import static org.mockito.Mockito.doThrow; + +import java.time.LocalDateTime; +import java.util.Map; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.http.MediaType; +import org.springframework.test.context.TestPropertySource; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.client.RestTemplate; + +import com.fasterxml.jackson.databind.ObjectMapper; + +import io.mosip.kernel.core.websub.model.Event; +import io.mosip.kernel.core.websub.model.EventModel; +import io.mosip.resident.exception.ResidentServiceCheckedException; +import io.mosip.resident.exception.ResidentServiceException; +import io.mosip.resident.helper.ObjectStoreHelper; +import io.mosip.resident.service.DocumentService; +import io.mosip.resident.service.IdAuthService; +import io.mosip.resident.service.ProxyIdRepoService; +import io.mosip.resident.service.ResidentVidService; +import io.mosip.resident.service.VerificationService; +import io.mosip.resident.service.WebSubUpdateAuthTypeService; +import io.mosip.resident.service.impl.ResidentServiceImpl; +import io.mosip.resident.test.ResidentTestBootApplication; +import io.mosip.resident.util.AuditUtil; + +/** + * Web-Sub Update Controller Test Note: This class is used to test the Web-Sub + * Update Controller + * + * @author Kamesh Shekhar Prasad + */ + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = ResidentTestBootApplication.class) +@AutoConfigureMockMvc +@TestPropertySource(locations = "classpath:application.properties") +public class WebSubUpdateAuthTypeControllerTest { + + @MockBean + private ProxyIdRepoService proxyIdRepoService; + + @MockBean + @Qualifier("selfTokenRestTemplate") + private RestTemplate residentRestTemplate; + + @Mock + private AuditUtil audit; + + @InjectMocks + WebSubUpdateAuthTypeController webSubUpdateAuthTypeController; + + @MockBean + WebSubUpdateAuthTypeService webSubUpdateAuthTypeService; + + @Autowired + private MockMvc mockMvc; + + @MockBean + private VerificationService verificationService; + + @MockBean + private IdAuthService idAuthService; + + @MockBean + private ResidentVidService vidService; + + @MockBean + private DocumentService docService; + + @MockBean + private ObjectStoreHelper objectStore; + + @MockBean + VerificationController verificationController; + + @MockBean + private ResidentServiceImpl residentService; + + @Autowired + private ObjectMapper objectMapper; + + @Before + public void setup() throws Exception { + + MockitoAnnotations.initMocks(this); + this.mockMvc = MockMvcBuilders.standaloneSetup(webSubUpdateAuthTypeController).build(); + } + + @Test + public void testCreateRequestGenerationSuccess() throws Exception { + + EventModel eventModel = new EventModel(); + Event event = new Event(); + event.setTransactionId("1234"); + event.setId("8251649601"); + Map partnerIdMap = new java.util.HashMap<>(); + partnerIdMap.put("olv_partner_id", "mpartner-default-auth"); + event.setData(partnerIdMap); + + eventModel.setEvent(event); + eventModel.setTopic("AUTH_TYPE_STATUS_UPDATE_ACK"); + eventModel.setPublishedOn(String.valueOf(LocalDateTime.now())); + eventModel.setPublisher("AUTH_TYPE_STATUS_UPDATE_ACK"); + webSubUpdateAuthTypeController.authTypeCallback(objectMapper.convertValue(eventModel, Map.class)); + + mockMvc.perform((MockMvcRequestBuilders.post("/callback/authTypeCallback")) + .contentType(MediaType.APPLICATION_JSON).content(eventModel.toString())).andReturn(); + } + + @Test(expected = ResidentServiceException.class) + public void testAuthTypeCallbackWithException() throws Exception { + EventModel eventModel = new EventModel(); + doThrow(new ResidentServiceCheckedException()).when(webSubUpdateAuthTypeService).updateAuthTypeStatus(anyMap()); + webSubUpdateAuthTypeController.authTypeCallback(objectMapper.convertValue(eventModel, Map.class)); + } +} diff --git a/resident/resident-service/src/test/java/io/mosip/resident/test/handler/ResidentUpdateServiceTest.java b/resident/resident-service/src/test/java/io/mosip/resident/handler/service/ResidentUpdateServiceTest.java similarity index 94% rename from resident/resident-service/src/test/java/io/mosip/resident/test/handler/ResidentUpdateServiceTest.java rename to resident/resident-service/src/test/java/io/mosip/resident/handler/service/ResidentUpdateServiceTest.java index 3a36989ef92..961dacf90c2 100644 --- a/resident/resident-service/src/test/java/io/mosip/resident/test/handler/ResidentUpdateServiceTest.java +++ b/resident/resident-service/src/test/java/io/mosip/resident/handler/service/ResidentUpdateServiceTest.java @@ -1,4 +1,4 @@ -package io.mosip.resident.test.handler; +package io.mosip.resident.handler.service; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; @@ -40,8 +40,6 @@ import io.mosip.resident.dto.ResidentUpdateDto; import io.mosip.resident.dto.ResponseWrapper; import io.mosip.resident.exception.ApisResourceAccessException; -import io.mosip.resident.handler.service.ResidentUpdateService; -import io.mosip.resident.handler.service.SyncAndUploadService; import io.mosip.resident.util.AuditUtil; import io.mosip.resident.util.IdSchemaUtil; import io.mosip.resident.util.ResidentServiceRestClient; @@ -92,7 +90,7 @@ public class ResidentUpdateServiceTest { @Before public void setup() throws Exception { - ReflectionTestUtils.setField(residentUpdateService, "idschemaVersion", "0.1"); + ReflectionTestUtils.setField(residentUpdateService, "defaultIdSchemaVersion", "0.1"); residentUpdateDto = new ResidentUpdateDto(); residentUpdateDto.setIdValue("5984924027"); diff --git a/resident/resident-service/src/test/java/io/mosip/resident/test/handler/SyncAndUploadServiceTest.java b/resident/resident-service/src/test/java/io/mosip/resident/handler/service/SyncAndUploadServiceTest.java similarity index 98% rename from resident/resident-service/src/test/java/io/mosip/resident/test/handler/SyncAndUploadServiceTest.java rename to resident/resident-service/src/test/java/io/mosip/resident/handler/service/SyncAndUploadServiceTest.java index 1bf958e8bb2..c27de24bcc6 100644 --- a/resident/resident-service/src/test/java/io/mosip/resident/test/handler/SyncAndUploadServiceTest.java +++ b/resident/resident-service/src/test/java/io/mosip/resident/handler/service/SyncAndUploadServiceTest.java @@ -1,4 +1,4 @@ -package io.mosip.resident.test.handler; +package io.mosip.resident.handler.service; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; @@ -34,7 +34,6 @@ import io.mosip.resident.dto.RegistrationType; import io.mosip.resident.dto.SyncResponseDto; import io.mosip.resident.exception.ApisResourceAccessException; -import io.mosip.resident.handler.service.SyncAndUploadService; import io.mosip.resident.service.ProxyIdRepoService; import io.mosip.resident.util.AuditUtil; import io.mosip.resident.util.EncryptorUtil; diff --git a/resident/resident-service/src/test/java/io/mosip/resident/test/handler/UinCardRePrintServiceTest.java b/resident/resident-service/src/test/java/io/mosip/resident/handler/service/UinCardRePrintServiceTest.java similarity index 96% rename from resident/resident-service/src/test/java/io/mosip/resident/test/handler/UinCardRePrintServiceTest.java rename to resident/resident-service/src/test/java/io/mosip/resident/handler/service/UinCardRePrintServiceTest.java index 5d45f8433c8..528c78c26eb 100644 --- a/resident/resident-service/src/test/java/io/mosip/resident/test/handler/UinCardRePrintServiceTest.java +++ b/resident/resident-service/src/test/java/io/mosip/resident/handler/service/UinCardRePrintServiceTest.java @@ -1,4 +1,4 @@ -package io.mosip.resident.test.handler; +package io.mosip.resident.handler.service; import static org.junit.Assert.assertTrue; @@ -47,8 +47,6 @@ import io.mosip.resident.dto.VidResDTO; import io.mosip.resident.dto.VidResponseDTO1; import io.mosip.resident.exception.ApisResourceAccessException; -import io.mosip.resident.handler.service.SyncAndUploadService; -import io.mosip.resident.handler.service.UinCardRePrintService; import io.mosip.resident.service.ProxyIdRepoService; import io.mosip.resident.util.AuditUtil; import io.mosip.resident.util.IdSchemaUtil; diff --git a/resident/resident-service/src/test/java/io/mosip/resident/helper/CredentialStatusUpdateHelperTest.java b/resident/resident-service/src/test/java/io/mosip/resident/helper/CredentialStatusUpdateHelperTest.java new file mode 100644 index 00000000000..3aa61c32fb5 --- /dev/null +++ b/resident/resident-service/src/test/java/io/mosip/resident/helper/CredentialStatusUpdateHelperTest.java @@ -0,0 +1,77 @@ +package io.mosip.resident.helper; + +import io.mosip.resident.entity.ResidentTransactionEntity; +import io.mosip.resident.exception.ApisResourceAccessException; +import io.mosip.resident.exception.ResidentServiceCheckedException; +import io.mosip.resident.repository.ResidentTransactionRepository; +import io.mosip.resident.service.NotificationService; +import io.mosip.resident.util.Utility; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.springframework.core.env.Environment; + +import java.util.HashMap; +import java.util.Map; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.when; + +/** + * @author Kamesh Shekhar Prasad + */ +@RunWith(MockitoJUnitRunner.class) +public class CredentialStatusUpdateHelperTest { + + @Mock + private Environment env; + + @Mock + private NotificationService notificationService; + + @Mock + private ResidentTransactionRepository repo; + + @Mock + private Utility utility; + + @InjectMocks + private CredentialStatusUpdateHelper helper; + + private ResidentTransactionEntity txn; + + @Before + public void setup() { + txn = new ResidentTransactionEntity(); + txn.setEventId("event123"); + txn.setStatusCode("INITIAL"); + } + + @Test + public void testUpdateStatus_NewStatusAndReferenceLink() throws ResidentServiceCheckedException, ApisResourceAccessException { + Map credentialStatus = new HashMap<>(); + credentialStatus.put("status", "SUCCESS"); + credentialStatus.put("url", "https://example.com"); + when(env.getProperty(any(String.class))).thenReturn("SUCCESS"); + helper.updateStatus(txn, credentialStatus); + } + + @Test + public void testUpdateStatus_NoNewStatus() throws ResidentServiceCheckedException, ApisResourceAccessException { + Map credentialStatus = new HashMap<>(); + credentialStatus.put("status", "INITIAL"); + helper.updateStatus(txn, credentialStatus); + } + + @Test + public void testUpdateStatus_NoNotificationSent() throws ResidentServiceCheckedException, ApisResourceAccessException { + Map credentialStatus = new HashMap<>(); + credentialStatus.put("status", "IN_PROGRESS"); + when(env.getProperty(any(String.class))).thenReturn(null); + helper.updateStatus(txn, credentialStatus); + } +} + diff --git a/resident/resident-service/src/test/java/io/mosip/resident/test/service/IdAuthServiceTest.java b/resident/resident-service/src/test/java/io/mosip/resident/service/impl/IdAuthServiceTest.java similarity index 98% rename from resident/resident-service/src/test/java/io/mosip/resident/test/service/IdAuthServiceTest.java rename to resident/resident-service/src/test/java/io/mosip/resident/service/impl/IdAuthServiceTest.java index 4f120ec9e03..6683464f5c8 100644 --- a/resident/resident-service/src/test/java/io/mosip/resident/test/service/IdAuthServiceTest.java +++ b/resident/resident-service/src/test/java/io/mosip/resident/service/impl/IdAuthServiceTest.java @@ -1,10 +1,11 @@ -package io.mosip.resident.test.service; +package io.mosip.resident.service.impl; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyList; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.when; @@ -59,10 +60,10 @@ import io.mosip.resident.exception.ResidentServiceCheckedException; import io.mosip.resident.repository.ResidentTransactionRepository; import io.mosip.resident.service.IdAuthService; +import io.mosip.resident.service.NotificationService; import io.mosip.resident.service.ProxyIdRepoService; -import io.mosip.resident.service.impl.IdAuthServiceImpl; -import io.mosip.resident.service.impl.IdentityServiceImpl; import io.mosip.resident.util.ResidentServiceRestClient; +import io.mosip.resident.util.Utility; @RunWith(MockitoJUnitRunner.class) @RefreshScope @@ -101,6 +102,12 @@ public class IdAuthServiceTest { @Mock private IdentityServiceImpl identityService; + @Mock + private NotificationService notificationService; + + @Mock + private Utility utility; + @Before public void setup() { @@ -223,8 +230,8 @@ public void validateOtpSuccessTest() throws IOException, ApisResourceAccessExcep when(restClient.postApi(any(), any(), any(), any(Class.class))).thenReturn(response); when(identityService.getIDATokenForIndividualId(anyString())).thenReturn("346697314566835424394775924659202696"); - when(residentTransactionRepository.findTopByRequestTrnIdAndTokenIdAndStatusCodeOrderByCrDtimesDesc(anyString(), - anyString(), anyString())).thenReturn(residentTransactionEntity); + when(residentTransactionRepository.findTopByRequestTrnIdAndTokenIdAndStatusCodeInOrderByCrDtimesDesc(anyString(), + anyString(), anyList())).thenReturn(residentTransactionEntity); boolean result = idAuthService.validateOtp(transactionID, individualId, otp); diff --git a/resident/resident-service/src/test/java/io/mosip/resident/test/service/NotificationServiceTest.java b/resident/resident-service/src/test/java/io/mosip/resident/service/impl/NotificationServiceTest.java similarity index 97% rename from resident/resident-service/src/test/java/io/mosip/resident/test/service/NotificationServiceTest.java rename to resident/resident-service/src/test/java/io/mosip/resident/service/impl/NotificationServiceTest.java index b74d0c59a73..40628ced8c9 100644 --- a/resident/resident-service/src/test/java/io/mosip/resident/test/service/NotificationServiceTest.java +++ b/resident/resident-service/src/test/java/io/mosip/resident/service/impl/NotificationServiceTest.java @@ -1,4 +1,4 @@ -package io.mosip.resident.test.service; +package io.mosip.resident.service.impl; import static org.junit.Assert.assertEquals; diff --git a/resident/resident-service/src/test/java/io/mosip/resident/service/impl/OTPManagerServiceImplTest.java b/resident/resident-service/src/test/java/io/mosip/resident/service/impl/OTPManagerServiceImplTest.java new file mode 100644 index 00000000000..e4547b5e238 --- /dev/null +++ b/resident/resident-service/src/test/java/io/mosip/resident/service/impl/OTPManagerServiceImplTest.java @@ -0,0 +1,184 @@ +package io.mosip.resident.service.impl; + +import static org.junit.Assert.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.powermock.api.mockito.PowerMockito.when; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentMatchers; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.mockito.junit.MockitoJUnitRunner; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.cloud.context.config.annotation.RefreshScope; +import org.springframework.core.env.Environment; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.client.RestTemplate; + +import io.mosip.kernel.core.http.ResponseWrapper; +import io.mosip.kernel.core.util.DateUtils; +import io.mosip.resident.dto.MainRequestDTO; +import io.mosip.resident.dto.NotificationResponseDTO; +import io.mosip.resident.dto.OtpRequestDTOV2; +import io.mosip.resident.entity.OtpTransactionEntity; +import io.mosip.resident.exception.ApisResourceAccessException; +import io.mosip.resident.exception.ResidentServiceCheckedException; +import io.mosip.resident.exception.ResidentServiceException; +import io.mosip.resident.repository.OtpTransactionRepository; +import io.mosip.resident.repository.ResidentTransactionRepository; +import io.mosip.resident.service.NotificationService; +import io.mosip.resident.service.ResidentService; +import io.mosip.resident.util.AuditUtil; +import io.mosip.resident.util.ResidentServiceRestClient; +import io.mosip.resident.util.TemplateUtil; +import io.mosip.resident.validator.RequestValidator; + +/** + * This class is used to test Otp Manger service impl class. + * @author Kamesh Shekhar Prasad + */ +@RunWith(MockitoJUnitRunner.class) +@RefreshScope +@ContextConfiguration +public class OTPManagerServiceImplTest { + + @Mock + private ResidentServiceRestClient residentServiceRestClient; + + @Mock + Environment env; + + @Mock + private AuditUtil audit; + + @InjectMocks + private OtpManagerServiceImpl otpManagerService; + + @Mock + private IdentityServiceImpl identityServiceImpl; + + @Mock + @Qualifier("selfTokenRestTemplate") + private RestTemplate restTemplate; + + @Mock + private ResidentTransactionRepository residentTransactionRepository; + + @Autowired + private MockMvc mockMvc; + + @Mock + private NotificationService notificationService; + + private NotificationResponseDTO notificationResponseDTO; + + private MainRequestDTO requestDTO; + + private OtpRequestDTOV2 otpRequestDTOV2; + + + @Mock + private OtpTransactionRepository otpTransactionRepository; + + private ResponseWrapper> response; + + @Mock + private Environment environment; + + private ResponseEntity response1; + + @Mock + private TemplateUtil templateUtil; + + @Mock + private RequestValidator requestValidator; + + @Mock + private ResidentService residentService; + + @Before + public void setup() throws ApisResourceAccessException, ResidentServiceCheckedException { + MockitoAnnotations.initMocks(this); + this.mockMvc = MockMvcBuilders.standaloneSetup(otpManagerService).build(); + response = new ResponseWrapper<>(); + Map responseMap = new HashMap<>(); + responseMap.put("otp", "111111"); + responseMap.put("status", "PASSED"); + response.setResponse(responseMap); + otpRequestDTOV2 = new OtpRequestDTOV2(); + requestDTO = new MainRequestDTO<>(); + otpRequestDTOV2.setTransactionId("1234567891"); + otpRequestDTOV2.setUserId("kamesh@gmail.com"); + requestDTO.setRequest(otpRequestDTOV2); + Mockito.when(identityServiceImpl.getResidentIndvidualIdFromSession()).thenReturn("2123456"); + when(otpTransactionRepository.checkotpsent(any(), any(), any(), any())).thenReturn(0); + ResponseWrapper> responseMap1=new ResponseWrapper<>(); + responseMap1.setResponse(responseMap); + response1 = new ResponseEntity<>(responseMap1, HttpStatus.ACCEPTED); + Mockito.when(environment.getProperty(Mockito.any())).thenReturn("https://dev.mosip.net/v1/otpmanager/otp/generate"); + Mockito.when(restTemplate.exchange(ArgumentMatchers.anyString(), + ArgumentMatchers.any(HttpMethod.class), + ArgumentMatchers.any(), + Mockito.eq(ResponseWrapper.class))) + .thenReturn(response1); + Mockito.when(environment.getProperty(any())).thenReturn("http://localhost:8099"); + Mockito.when(environment.getProperty("otp.request.flooding.duration", Long.class)).thenReturn(45L); + Mockito.when(environment.getProperty("mosip.kernel.otp.expiry-time", Long.class)).thenReturn(45L); + Mockito.when(environment.getProperty("otp.request.flooding.max-count", Integer.class)).thenReturn(8); +} + + @Test + public void testSendOtpSuccess() throws ResidentServiceCheckedException, IOException, ApisResourceAccessException { + assertEquals(true, otpManagerService.sendOtp(requestDTO, "EMAIL", "eng")); + } + + @Test(expected = ResidentServiceCheckedException.class) + public void testSendOtpAlreadyOtpSendError() throws ResidentServiceCheckedException, IOException, ApisResourceAccessException { + when(otpTransactionRepository.checkotpsent(any(), any(), any(), any())).thenReturn(9); + assertEquals(true, otpManagerService.sendOtp(requestDTO, "EMAIL", "eng")); + } + + @Test + public void testSendOtpOtpSendWithinLessTime() throws ResidentServiceCheckedException, IOException, ApisResourceAccessException { + OtpTransactionEntity otpTransactionEntity = new OtpTransactionEntity(); + assertEquals(true, otpManagerService.sendOtp(requestDTO, "EMAIL", "eng")); + } + + @Test + public void testSendOtpPhoneSuccess() throws ResidentServiceCheckedException, IOException, ApisResourceAccessException { + assertEquals(true, otpManagerService.sendOtp(requestDTO, "PHONE", "eng")); + } + + @Test + public void testValidateOtpSuccess() throws ResidentServiceCheckedException, ApisResourceAccessException { + when(otpTransactionRepository.existsByOtpHashAndStatusCode(Mockito.anyString(), Mockito.anyString())).thenReturn(true); + OtpTransactionEntity otpTransactionEntity = new OtpTransactionEntity(); + otpTransactionEntity.setExpiryDtimes(DateUtils.getUTCCurrentDateTime().plusSeconds(120)); + when(otpTransactionRepository.findTopByOtpHashAndStatusCode(Mockito.anyString(), Mockito.anyString())).thenReturn(otpTransactionEntity); + assertEquals(true, otpManagerService.validateOtp("111111", "kamesh@gmail.com", "1234565656")); + } + + @Test(expected = ResidentServiceException.class) + public void testValidateOtpFailure() throws ResidentServiceCheckedException, ApisResourceAccessException { + when(otpTransactionRepository.existsByOtpHashAndStatusCode(Mockito.anyString(), Mockito.anyString())).thenReturn(true); + OtpTransactionEntity otpTransactionEntity = new OtpTransactionEntity(); + otpTransactionEntity.setExpiryDtimes(DateUtils.getUTCCurrentDateTime()); + when(otpTransactionRepository.findTopByOtpHashAndStatusCode(Mockito.anyString(), Mockito.anyString())).thenReturn(otpTransactionEntity); + assertEquals(true, otpManagerService.validateOtp("111111", "kamesh@gmail.com", "1234565656")); + } + +} \ No newline at end of file diff --git a/resident/resident-service/src/test/java/io/mosip/resident/service/impl/ProxyOtpServiceImpllTest.java b/resident/resident-service/src/test/java/io/mosip/resident/service/impl/ProxyOtpServiceImpllTest.java new file mode 100644 index 00000000000..f589ddfcd0a --- /dev/null +++ b/resident/resident-service/src/test/java/io/mosip/resident/service/impl/ProxyOtpServiceImpllTest.java @@ -0,0 +1,271 @@ +package io.mosip.resident.service.impl; + +import static org.junit.Assert.assertEquals; +import static org.mockito.ArgumentMatchers.any; + +import java.io.IOException; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.mockito.junit.MockitoJUnitRunner; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.cloud.context.config.annotation.RefreshScope; +import org.springframework.core.env.Environment; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.util.ReflectionTestUtils; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.web.client.HttpServerErrorException; +import org.springframework.web.client.RestTemplate; + +import io.mosip.kernel.core.authmanager.model.AuthNResponse; +import io.mosip.kernel.core.http.ResponseWrapper; +import io.mosip.preregistration.application.constant.PreRegLoginConstant; +import io.mosip.resident.constant.ResidentErrorCode; +import io.mosip.resident.dto.MainRequestDTO; +import io.mosip.resident.dto.MainResponseDTO; +import io.mosip.resident.dto.NotificationResponseDTO; +import io.mosip.resident.dto.OtpRequestDTOV2; +import io.mosip.resident.dto.OtpRequestDTOV3; +import io.mosip.resident.exception.ApisResourceAccessException; +import io.mosip.resident.exception.ResidentServiceCheckedException; +import io.mosip.resident.exception.ResidentServiceException; +import io.mosip.resident.repository.OtpTransactionRepository; +import io.mosip.resident.repository.ResidentTransactionRepository; +import io.mosip.resident.service.NotificationService; +import io.mosip.resident.service.OtpManager; +import io.mosip.resident.service.ResidentService; +import io.mosip.resident.util.AuditUtil; +import io.mosip.resident.util.ResidentServiceRestClient; +import io.mosip.resident.util.TemplateUtil; +import io.mosip.resident.util.Utility; +import io.mosip.resident.validator.RequestValidator; +import reactor.util.function.Tuples; + +/** + * This class is used to test proxy otp service impl class. + * @author Kamesh Shekhar Prasad + */ +@RunWith(MockitoJUnitRunner.class) +@RefreshScope +@ContextConfiguration +public class ProxyOtpServiceImpllTest { + + @Mock + private ResidentServiceRestClient residentServiceRestClient; + + @Mock + Environment env; + + @Mock + private AuditUtil audit; + + @InjectMocks + private ProxyOtpServiceImpl proxyOtpService; + + @Mock + private IdentityServiceImpl identityServiceImpl; + + @Mock + private Utility utility; + + @Mock + @Qualifier("selfTokenRestTemplate") + private RestTemplate restTemplate; + + @Mock + private ResidentTransactionRepository residentTransactionRepository; + + @Autowired + private MockMvc mockMvc; + + @Mock + private NotificationService notificationService; + + private NotificationResponseDTO notificationResponseDTO; + + private MainRequestDTO requestDTO; + + private OtpRequestDTOV2 otpRequestDTOV2; + + + @Mock + private OtpTransactionRepository otpTransactionRepository; + + private ResponseWrapper> response; + + @Mock + private Environment environment; + + private ResponseEntity response1; + + @Mock + private TemplateUtil templateUtil; + + @Mock + private RequestValidator requestValidator; + + @Mock + private ResidentService residentService; + + @Mock + private OtpManager otpManager; + + private ResponseEntity> responseEntity; + + @Before + public void setup() throws ApisResourceAccessException, ResidentServiceCheckedException, IOException { + MockitoAnnotations.initMocks(this); + this.mockMvc = MockMvcBuilders.standaloneSetup(proxyOtpService).build(); + response = new ResponseWrapper<>(); + Map responseMap = new HashMap<>(); + responseMap.put("otp", "111111"); + responseMap.put("status", "PASSED"); + response.setResponse(responseMap); + otpRequestDTOV2 = new OtpRequestDTOV2(); + requestDTO = new MainRequestDTO<>(); + otpRequestDTOV2.setTransactionId("1234567891"); + otpRequestDTOV2.setUserId("kamesh@gmail.com"); + requestDTO.setRequest(otpRequestDTOV2); + ResponseWrapper> responseMap1 = new ResponseWrapper<>(); + responseMap1.setResponse(responseMap); + response1 = new ResponseEntity<>(responseMap1, HttpStatus.ACCEPTED); + Mockito.when(requestValidator.validateUserIdAndTransactionId(Mockito.anyString(), Mockito.anyString())).thenReturn(List.of("EMAIL")); + ReflectionTestUtils.setField(proxyOtpService, "mandatoryLanguage", "eng"); + Mockito.when(otpManager.sendOtp(any(), any(), any())).thenReturn(true); + AuthNResponse authNResponse = new AuthNResponse(PreRegLoginConstant.EMAIL_SUCCESS, PreRegLoginConstant.SUCCESS); + MainResponseDTO response = new MainResponseDTO<>(); + response.setResponse(authNResponse); + responseEntity = new ResponseEntity<>(HttpStatus.OK); + } + + @Test + public void testSendOtpEmailSuccess() { + assertEquals(responseEntity.getStatusCode(), proxyOtpService.sendOtp(requestDTO).getStatusCode()); + } + + @Test + public void testSendOtpPhoneSuccess() { + otpRequestDTOV2.setUserId("8809463737"); + requestDTO.setRequest(otpRequestDTOV2); + Mockito.when(requestValidator.validateUserIdAndTransactionId(Mockito.anyString(), + Mockito.anyString())).thenReturn(List.of("PHONE")); + assertEquals(responseEntity.getStatusCode(), proxyOtpService.sendOtp(requestDTO).getStatusCode()); + } + + @Test + public void testSendOtpFailure() throws ResidentServiceCheckedException, IOException, ApisResourceAccessException { + Mockito.when(otpManager.sendOtp(any(), any(), any())).thenReturn(false); + assertEquals(responseEntity.getStatusCode(), proxyOtpService.sendOtp(requestDTO).getStatusCode()); + } + + @Test(expected = ResidentServiceException.class) + public void testHttpServerErrorException() throws ResidentServiceCheckedException, IOException, ApisResourceAccessException { + Mockito.when(otpManager.sendOtp(any(), any(), any())).thenThrow(new HttpServerErrorException(HttpStatus.BAD_GATEWAY)); + assertEquals(responseEntity.getStatusCode(), proxyOtpService.sendOtp(requestDTO).getStatusCode()); + } + + @Test(expected = ResidentServiceException.class) + public void testHttpClientErrorException() throws ResidentServiceCheckedException, IOException, ApisResourceAccessException { + Mockito.when(otpManager.sendOtp(any(), any(), any())).thenThrow(new HttpClientErrorException(HttpStatus.BAD_GATEWAY)); + assertEquals(responseEntity.getStatusCode(), proxyOtpService.sendOtp(requestDTO).getStatusCode()); + } + + @Test(expected = ResidentServiceException.class) + public void testResidentServiceException() throws ResidentServiceCheckedException, IOException, ApisResourceAccessException { + Mockito.when(otpManager.sendOtp(any(), any(), any())) + .thenThrow(new ResidentServiceException(ResidentErrorCode.SEND_OTP_FAILED.getErrorCode(), + ResidentErrorCode.SEND_OTP_FAILED.getErrorMessage())); + assertEquals(responseEntity.getStatusCode(), proxyOtpService.sendOtp(requestDTO).getStatusCode()); + } + + @Test(expected = ResidentServiceException.class) + public void testValidateOtpFailure() { + MainRequestDTO requestDTO1 = new MainRequestDTO<>(); + OtpRequestDTOV3 otpRequestDTOV3 = new OtpRequestDTOV3(); + otpRequestDTOV3.setOtp("11111"); + otpRequestDTOV3.setUserId("ka@gm.com"); + otpRequestDTOV3.setTransactionId("122222222"); + requestDTO1.setRequest(otpRequestDTOV3); + assertEquals("12345", proxyOtpService.validateWithUserIdOtp(requestDTO1).getT2()); + } + + @Test + public void testValidateOtpSuccess() throws ResidentServiceCheckedException, ApisResourceAccessException, IOException { + MainRequestDTO requestDTO1 = new MainRequestDTO<>(); + OtpRequestDTOV3 otpRequestDTOV3 = new OtpRequestDTOV3(); + otpRequestDTOV3.setOtp("11111"); + otpRequestDTOV3.setUserId("ka@gm.com"); + otpRequestDTOV3.setTransactionId("122222222"); + requestDTO1.setRequest(otpRequestDTOV3); + Mockito.when(otpManager.validateOtp(Mockito.anyString(), Mockito.anyString(), Mockito.anyString())).thenReturn(true); + Mockito.when(otpManager.updateUserId(Mockito.anyString(), Mockito.anyString())).thenReturn(Tuples.of(new Object(), "12345")); + assertEquals("12345", proxyOtpService.validateWithUserIdOtp(requestDTO1).getT2()); + } + + @Test(expected = ResidentServiceException.class) + public void testValidateOtpFailureResidentServiceException() throws ResidentServiceCheckedException, ApisResourceAccessException { + MainRequestDTO requestDTO1 = new MainRequestDTO<>(); + OtpRequestDTOV3 otpRequestDTOV3 = new OtpRequestDTOV3(); + otpRequestDTOV3.setOtp("11111"); + otpRequestDTOV3.setUserId("ka@gm.com"); + otpRequestDTOV3.setTransactionId("122222222"); + requestDTO1.setRequest(otpRequestDTOV3); + Mockito.when(otpManager.validateOtp(Mockito.anyString(), Mockito.anyString(), Mockito.anyString())). + thenThrow(new ResidentServiceException(ResidentErrorCode.OTP_VALIDATION_FAILED.getErrorCode(), + ResidentErrorCode.OTP_VALIDATION_FAILED.getErrorMessage())); + assertEquals("12345", proxyOtpService.validateWithUserIdOtp(requestDTO1).getT2()); + } + + @Test(expected = ResidentServiceException.class) + public void testValidateOtpFailureRuntimeException() throws ResidentServiceCheckedException, ApisResourceAccessException { + MainRequestDTO requestDTO1 = new MainRequestDTO<>(); + OtpRequestDTOV3 otpRequestDTOV3 = new OtpRequestDTOV3(); + otpRequestDTOV3.setOtp("11111"); + otpRequestDTOV3.setUserId("ka@gm.com"); + otpRequestDTOV3.setTransactionId("122222222"); + requestDTO1.setRequest(otpRequestDTOV3); + Mockito.when(otpManager.validateOtp(Mockito.anyString(), Mockito.anyString(), Mockito.anyString())). + thenThrow(new RuntimeException()); + assertEquals("12345", proxyOtpService.validateWithUserIdOtp(requestDTO1).getT2()); + } + + @Test(expected = ResidentServiceException.class) + public void testValidateOtpFailureResidentServiceCheckedException() throws ResidentServiceCheckedException, ApisResourceAccessException { + MainRequestDTO requestDTO1 = new MainRequestDTO<>(); + OtpRequestDTOV3 otpRequestDTOV3 = new OtpRequestDTOV3(); + otpRequestDTOV3.setOtp("11111"); + otpRequestDTOV3.setUserId("ka@gm.com"); + otpRequestDTOV3.setTransactionId("122222222"); + requestDTO1.setRequest(otpRequestDTOV3); + Mockito.when(otpManager.validateOtp(Mockito.anyString(), Mockito.anyString(), Mockito.anyString())). + thenThrow(new ResidentServiceCheckedException()); + assertEquals("12345", proxyOtpService.validateWithUserIdOtp(requestDTO1).getT2()); + } + + @Test(expected = ResidentServiceException.class) + public void testValidateOtpFailureApiResourceException() throws ResidentServiceCheckedException, ApisResourceAccessException { + MainRequestDTO requestDTO1 = new MainRequestDTO<>(); + OtpRequestDTOV3 otpRequestDTOV3 = new OtpRequestDTOV3(); + otpRequestDTOV3.setOtp("11111"); + otpRequestDTOV3.setUserId("ka@gm.com"); + otpRequestDTOV3.setTransactionId("122222222"); + requestDTO1.setRequest(otpRequestDTOV3); + Mockito.when(otpManager.validateOtp(Mockito.anyString(), Mockito.anyString(), Mockito.anyString())). + thenThrow(new ApisResourceAccessException()); + assertEquals("12345", proxyOtpService.validateWithUserIdOtp(requestDTO1).getT2()); + } + +} \ No newline at end of file diff --git a/resident/resident-service/src/test/java/io/mosip/resident/service/impl/ResidentConfigServiceImplTest.java b/resident/resident-service/src/test/java/io/mosip/resident/service/impl/ResidentConfigServiceImplTest.java index d5d3e5a8db4..86c8c83b3ae 100644 --- a/resident/resident-service/src/test/java/io/mosip/resident/service/impl/ResidentConfigServiceImplTest.java +++ b/resident/resident-service/src/test/java/io/mosip/resident/service/impl/ResidentConfigServiceImplTest.java @@ -1,11 +1,11 @@ package io.mosip.resident.service.impl; -import static junit.framework.TestCase.assertNull; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.when; import java.io.ByteArrayInputStream; +import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -26,10 +26,16 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.util.ReflectionTestUtils; +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import io.mosip.kernel.core.http.ResponseWrapper; +import io.mosip.resident.constant.MappingJsonConstants; +import io.mosip.resident.constant.ResidentConstants; +import io.mosip.resident.dto.SharableAttributesDTO; import io.mosip.resident.exception.ResidentServiceException; +import io.mosip.resident.util.AuditUtil; @RunWith(MockitoJUnitRunner.class) @RefreshScope @@ -41,7 +47,7 @@ public class ResidentConfigServiceImplTest { @Mock private Environment env; - + @Mock private ResourceLoader resourceLoader; @@ -53,20 +59,54 @@ public class ResidentConfigServiceImplTest { @Mock private ObjectMapper objectMapper; - + + @Mock + private AuditUtil auditUtil; + Resource resource; + private String identityMapping; + private String uiSchema; + private Map uiSchemaMap; @Before public void setUp() throws Exception { + identityMapping = "{\"name\":\"identity-mapping\"}"; Mockito.when(identityMappingJsonFile.getInputStream()) - .thenReturn(new ByteArrayInputStream("{\"name\":\"identity-mapping\"}".getBytes())); + .thenReturn(new ByteArrayInputStream(identityMapping.getBytes())); ReflectionTestUtils.setField(configServiceImpl, "resourceLoader", resourceLoader); ReflectionTestUtils.setField(configServiceImpl, "residentUiSchemaJsonFilePrefix", "classpath:resident-ui"); resource = Mockito.mock(Resource.class); Mockito.when(resourceLoader.getResource(Mockito.anyString())).thenReturn(resource); when(resource.exists()).thenReturn(true); - String uiSchema = "{\"name\":\"ui-schema\"}"; + + // getUISchemaData() + uiSchema = "{\"name\":\"ui-schema\"}"; when(resource.getInputStream()).thenReturn(new ByteArrayInputStream(uiSchema.getBytes())); + uiSchemaMap = new HashMap<>(); + List> uiSchemaInputAttributes = new ArrayList<>(); + Map map1 = new HashMap<>(); + map1.put(ResidentConstants.LABEL, "Full Name"); + map1.put(ResidentConstants.VALUE, "fullName"); + List> list = new ArrayList<>(); + list.add(map1); + Map mapFormat = new HashMap<>(); + mapFormat.put("eng", list); + Map uiSchemaInputAttribute1 = new HashMap<>(); + uiSchemaInputAttribute1.put(ResidentConstants.ATTRIBUTE_NAME, "fullName"); + uiSchemaInputAttribute1.put(ResidentConstants.MASK_REQUIRED, false); + uiSchemaInputAttribute1.put(ResidentConstants.LABEL, Map.of("eng", "Name")); + uiSchemaInputAttribute1.put(ResidentConstants.FORMAT_REQUIRED, true); + uiSchemaInputAttribute1.put(ResidentConstants.FORMAT_OPTION, mapFormat); + uiSchemaInputAttributes.add(uiSchemaInputAttribute1); + Map uiSchemaInputAttribute2 = new HashMap<>(); + uiSchemaInputAttribute2.put(ResidentConstants.ATTRIBUTE_NAME, "UIN"); + uiSchemaInputAttribute2.put(ResidentConstants.MASK_REQUIRED, true); + uiSchemaInputAttribute2.put(ResidentConstants.MASK_ATTRIBUTE_NAME, "masked_UIN"); + uiSchemaInputAttribute2.put(ResidentConstants.LABEL, Map.of("eng", "UIN")); + uiSchemaInputAttribute2.put(ResidentConstants.FORMAT_REQUIRED, false); + uiSchemaInputAttributes.add(uiSchemaInputAttribute2); + uiSchemaMap.put(MappingJsonConstants.IDENTITY, uiSchemaInputAttributes); + Mockito.when(objectMapper.readValue(uiSchema.getBytes(), Map.class)).thenReturn(uiSchemaMap); } private ResidentConfigServiceImpl createTestSubject() { @@ -114,23 +154,26 @@ public void testGetUISchemaElse() throws Exception { testSubject.getUISchema("update-demographics"); } - @Test - public void testGetIdentityMapping() throws Exception { - ResidentConfigServiceImpl testSubject; - - testSubject = createTestSubject(); - String identityMapping = "identity-mapping-json"; + private void getIdentityMappingMap(ResidentConfigServiceImpl testSubject) + throws IOException, JsonParseException, JsonMappingException { ReflectionTestUtils.setField(testSubject, "identityMapping", identityMapping); - String result = testSubject.getIdentityMapping(); - assertTrue(result.contains(identityMapping)); + Map identityDataMap = new HashMap<>(); + Map identityAttributeMap1 = new HashMap<>(); + identityAttributeMap1.put(MappingJsonConstants.VALUE, "fullName"); + identityDataMap.put("name", identityAttributeMap1); + Map identityAttributeMap2 = new HashMap<>(); + identityAttributeMap2.put(MappingJsonConstants.VALUE, "UIN"); + identityDataMap.put("uin", identityAttributeMap2); + Map identityMappingMap = new HashMap<>(); + identityMappingMap.put(MappingJsonConstants.IDENTITY, identityDataMap); + Mockito.when(objectMapper.readValue(identityMapping.getBytes(), Map.class)).thenReturn(identityMappingMap); } @Test public void testGetIdentityMappingTry() throws Exception { ResidentConfigServiceImpl testSubject; - testSubject = createTestSubject(); - String identityMapping = null; + identityMapping = null; ReflectionTestUtils.setField(testSubject, "identityMapping", identityMapping); identityMapping = "{\"name\":\"identity-mapping\"}"; String result = testSubject.getIdentityMapping(); @@ -138,34 +181,56 @@ public void testGetIdentityMappingTry() throws Exception { } @Test - public void testGetUiSchemaFilteredInputAttributes() throws Exception{ + public void testGetUiSchemaFilteredInputAttributes() throws Exception { ResidentConfigServiceImpl testSubject; List result; - Map uiSchema = new HashMap<>(); - List> uiSchemaInputAttributes = new ArrayList<>(); - Map uiSchemaInputAttribute = new HashMap<>(); - uiSchemaInputAttribute.put("inputRequired", "firstName"); - uiSchemaInputAttribute.put("controlType", "text"); - uiSchemaInputAttribute.put("id", "1234"); - uiSchemaInputAttributes.add(uiSchemaInputAttribute); - uiSchema.put("identity", uiSchemaInputAttributes); - byte[] src = "{\"name\":\"ui-schema\"}".getBytes(); - Mockito.when(objectMapper.readValue(src, Map.class)).thenReturn(uiSchema); testSubject = createTestSubject(); result = testSubject.getUiSchemaFilteredInputAttributes("update-demographics"); assertNotNull(result); } + @Test(expected = ResidentServiceException.class) + public void testGetUiSchemaFilteredInputAttributesNotNull() throws Exception { + ResidentConfigServiceImpl testSubject; + uiSchemaMap.put(MappingJsonConstants.IDENTITY, null); + Mockito.when(objectMapper.readValue(uiSchema.getBytes(), Map.class)).thenReturn(uiSchemaMap); + testSubject = createTestSubject(); + testSubject.getUiSchemaFilteredInputAttributes("update-demographics"); + } + + @Test(expected = ResidentServiceException.class) + public void testGetUiSchemaFilteredInputAttributesWithException() throws Exception { + ResidentConfigServiceImpl testSubject; + Mockito.when(objectMapper.readValue(uiSchema.getBytes(), Map.class)).thenThrow(new IOException()); + testSubject = createTestSubject(); + testSubject.getUiSchemaFilteredInputAttributes("update-demographics"); + } + @Test - public void testGetUiSchemaFilteredInputAttributesNotNull() throws Exception{ + public void testGetSharableAttributesList() throws Exception { ResidentConfigServiceImpl testSubject; - List result; - Map uiSchema = new HashMap<>(); - uiSchema.put("identity", null); - byte[] src = "{\"name\":\"ui-schema\"}".getBytes(); - Mockito.when(objectMapper.readValue(src, Map.class)).thenReturn(uiSchema); testSubject = createTestSubject(); - result = testSubject.getUiSchemaFilteredInputAttributes("update-demographics"); - assertNull(result); + getIdentityMappingMap(testSubject); + Mockito.when(env.getProperty(Mockito.anyString())).thenReturn(ResidentConstants.ATTRIBUTE_NAME); + SharableAttributesDTO sharableAttributesDTO1 = new SharableAttributesDTO(); + sharableAttributesDTO1.setAttributeName("name"); + sharableAttributesDTO1.setFormat("fullName"); + SharableAttributesDTO sharableAttributesDTO2 = new SharableAttributesDTO(); + sharableAttributesDTO2.setAttributeName("uin"); + SharableAttributesDTO sharableAttributesDTO3 = new SharableAttributesDTO(); + sharableAttributesDTO3.setAttributeName("dob"); + sharableAttributesDTO3.setFormat(""); + List sharableAttrList = new ArrayList<>(); + sharableAttrList.add(sharableAttributesDTO1); + sharableAttrList.add(sharableAttributesDTO2); + sharableAttrList.add(sharableAttributesDTO3); + testSubject.getSharableAttributesList(sharableAttrList, "update-demographics"); + } + + @Test + public void testGetUISchemaCacheableData() throws Exception { + ResidentConfigServiceImpl testSubject; + testSubject = createTestSubject(); + testSubject.getUISchemaCacheableData("update-demographics"); } } diff --git a/resident/resident-service/src/test/java/io/mosip/resident/test/service/ResidentCredentialServiceTest.java b/resident/resident-service/src/test/java/io/mosip/resident/service/impl/ResidentCredentialServiceTest.java similarity index 87% rename from resident/resident-service/src/test/java/io/mosip/resident/test/service/ResidentCredentialServiceTest.java rename to resident/resident-service/src/test/java/io/mosip/resident/service/impl/ResidentCredentialServiceTest.java index 9998285a9b7..35b95bea369 100644 --- a/resident/resident-service/src/test/java/io/mosip/resident/test/service/ResidentCredentialServiceTest.java +++ b/resident/resident-service/src/test/java/io/mosip/resident/service/impl/ResidentCredentialServiceTest.java @@ -1,4 +1,4 @@ -package io.mosip.resident.test.service; +package io.mosip.resident.service.impl; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; @@ -18,6 +18,7 @@ import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; +import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; import org.springframework.cloud.context.config.annotation.RefreshScope; import org.springframework.core.env.Environment; @@ -57,9 +58,6 @@ import io.mosip.resident.service.IdAuthService; import io.mosip.resident.service.NotificationService; import io.mosip.resident.service.ResidentCredentialService; -import io.mosip.resident.service.impl.IdentityServiceImpl; -import io.mosip.resident.service.impl.ProxyPartnerManagementServiceImpl; -import io.mosip.resident.service.impl.ResidentCredentialServiceImpl; import io.mosip.resident.util.AuditUtil; import io.mosip.resident.util.ResidentServiceRestClient; import io.mosip.resident.util.Utility; @@ -130,7 +128,7 @@ public void setup() throws IOException, ResidentServiceCheckedException, ApisRes residentCredentialRequestDto.setConsent("Accepted"); ResidentTransactionEntity residentTransactionEntity = new ResidentTransactionEntity(); residentTransactionEntity.setEventId("e65c86f5-8929-4547-a156-9b349c29ab8b"); - when(utility.createEntity()).thenReturn(residentTransactionEntity); + when(utility.createEntity(Mockito.any())).thenReturn(residentTransactionEntity); when(identityServiceImpl.getResidentIndvidualIdFromSession()).thenReturn("1234567890"); when(utility.createEventId()).thenReturn("1111111111111111"); } @@ -237,35 +235,6 @@ public void testGenerateCredentialWithIOException() throws OtpValidationFailedEx residentCredentialService.reqCredential(residentCredentialRequestDto); } - - @Test - public void testShareCredential() throws IOException, ApisResourceAccessException, ResidentServiceCheckedException { - ResidentCredentialResponseDto residentCredentialResponseDto = new ResidentCredentialResponseDto(); - residentCredentialResponseDto.setRequestId("10001100010006920211220064226"); - ResponseWrapper response = new ResponseWrapper<>(); - response.setResponsetime(DateUtils.getCurrentDateTimeString()); - response.setResponse(residentCredentialResponseDto); - String valueAsString = objectMapper.writeValueAsString(residentCredentialResponseDto); - - PartnerResponseDto partnerResponseDto = new PartnerResponseDto(); - partnerResponseDto.setOrganizationName("MOSIP"); - ResponseWrapper partnerResponseDtoResponseWrapper = new ResponseWrapper<>(); - partnerResponseDtoResponseWrapper.setResponse(partnerResponseDto); - - RequestWrapper requestDto = new RequestWrapper<>(); - requestDto.setId("mosip.credential.request.service.id"); - requestDto.setRequest(new CredentialReqestDto()); - requestDto.setRequesttime(DateUtils.getUTCCurrentDateTimeString()); - requestDto.setVersion("1.0"); - - String partnerUrl = env.getProperty(ApiName.PARTNER_API_URL.name()) + "/" + residentCredentialRequestDto.getIssuer(); - URI partnerUri = URI.create(partnerUrl); - when(residentServiceRestClient.getApi(partnerUri, ResponseWrapper.class)).thenReturn(partnerResponseDtoResponseWrapper); - when(residentServiceRestClient.postApi(any(), any(), any(), any())).thenReturn(response); - - Tuple2 credentialResponseDto = residentCredentialService.shareCredential(residentCredentialRequestDto,"SHARE_CRED_WITH_PARTNER"); - assertNotNull(credentialResponseDto.getT1().getStatus()); - } @Test public void testShareCredentialPurpose() throws IOException, ApisResourceAccessException, ResidentServiceCheckedException { @@ -292,42 +261,20 @@ public void testShareCredentialPurpose() throws IOException, ApisResourceAccessE when(residentServiceRestClient.getApi(partnerUri, ResponseWrapper.class)).thenReturn(partnerResponseDtoResponseWrapper); when(residentServiceRestClient.postApi(any(), any(), any(), any())).thenReturn(response); - Tuple2 credentialResponseDto = residentCredentialService.shareCredential(residentCredentialRequestDto,"SHARE_CRED_WITH_PARTNER","Banking"); + Tuple2 credentialResponseDto = residentCredentialService.shareCredential(residentCredentialRequestDto, "Banking", List.of()); assertNotNull(credentialResponseDto.getT1().getStatus()); } - @Test - public void testShareCredentialWithEncryptionKeyNull() throws IOException, ApisResourceAccessException, ResidentServiceCheckedException { - residentCredentialRequestDto.setEncryptionKey(null); - ResidentCredentialResponseDto residentCredentialResponseDto = new ResidentCredentialResponseDto(); - residentCredentialResponseDto.setRequestId("10001100010006920211220064226"); - ResponseWrapper response = new ResponseWrapper<>(); - response.setResponsetime(DateUtils.getCurrentDateTimeString()); - response.setResponse(residentCredentialResponseDto); - String valueAsString = objectMapper.writeValueAsString(residentCredentialResponseDto); - - PartnerResponseDto partnerResponseDto = new PartnerResponseDto(); - partnerResponseDto.setOrganizationName("MOSIP"); - ResponseWrapper partnerResponseDtoResponseWrapper = new ResponseWrapper<>(); - partnerResponseDtoResponseWrapper.setResponse(partnerResponseDto); - - RequestWrapper requestDto = new RequestWrapper<>(); - requestDto.setId("mosip.credential.request.service.id"); - requestDto.setRequest(new CredentialReqestDto()); - requestDto.setRequesttime(DateUtils.getUTCCurrentDateTimeString()); - requestDto.setVersion("1.0"); - - String partnerUrl = env.getProperty(ApiName.PARTNER_API_URL.name()) + "/" + residentCredentialRequestDto.getIssuer(); - URI partnerUri = URI.create(partnerUrl); - when(residentServiceRestClient.getApi(partnerUri, ResponseWrapper.class)).thenReturn(partnerResponseDtoResponseWrapper); - when(residentServiceRestClient.postApi(any(), any(), any(), any())).thenReturn(response); - - Tuple2 credentialResponseDto = residentCredentialService.shareCredential(residentCredentialRequestDto,"SHARE_CRED_WITH_PARTNER"); - assertNotNull(credentialResponseDto.getT1().getStatus()); + @Test(expected = ResidentServiceException.class) + public void testShareCredentialConsentNull() throws IOException, ApisResourceAccessException, ResidentServiceCheckedException { + residentCredentialRequestDto.setConsent(null); + residentCredentialService.shareCredential(residentCredentialRequestDto, "Banking", List.of()); } @Test(expected = ResidentCredentialServiceException.class) public void testShareCredentialWithApisResourceAccessException() throws Exception{ + residentCredentialRequestDto.setEncryptionKey(null); + residentCredentialRequestDto.setSharableAttributes(null); ResidentCredentialResponseDto residentCredentialResponseDto = new ResidentCredentialResponseDto(); residentCredentialResponseDto.setRequestId("10001100010006920211220064226"); ResponseWrapper response = new ResponseWrapper<>(); @@ -350,7 +297,7 @@ public void testShareCredentialWithApisResourceAccessException() throws Exceptio URI partnerUri = URI.create(partnerUrl); when(residentServiceRestClient.getApi(partnerUri, ResponseWrapper.class)).thenReturn(partnerResponseDtoResponseWrapper); when(residentServiceRestClient.postApi(any(), any(), any(), any())).thenThrow(ApisResourceAccessException.class); - residentCredentialService.shareCredential(residentCredentialRequestDto,"SHARE_CRED_WITH_PARTNER"); + residentCredentialService.shareCredential(residentCredentialRequestDto, null, List.of()); } @Test(expected = ResidentCredentialServiceException.class) @@ -376,8 +323,7 @@ public void testShareCredentialWithIOException() throws ResidentServiceCheckedEx URI partnerUri = URI.create(partnerUrl); when(residentServiceRestClient.getApi(partnerUri, ResponseWrapper.class)).thenReturn(partnerResponseDtoResponseWrapper); when(residentServiceRestClient.postApi(any(), any(), any(), any())).thenReturn(partnerResponseDtoResponseWrapper); - - residentCredentialService.shareCredential(residentCredentialRequestDto,"SHARE_CRED_WITH_PARTNER"); + residentCredentialService.shareCredential(residentCredentialRequestDto, null, List.of()); } @Test diff --git a/resident/resident-service/src/test/java/io/mosip/resident/service/impl/ResidentOtpServiceImplTest.java b/resident/resident-service/src/test/java/io/mosip/resident/service/impl/ResidentOtpServiceImplTest.java index 8a49ab4d9a9..37bffe7b716 100644 --- a/resident/resident-service/src/test/java/io/mosip/resident/service/impl/ResidentOtpServiceImplTest.java +++ b/resident/resident-service/src/test/java/io/mosip/resident/service/impl/ResidentOtpServiceImplTest.java @@ -85,7 +85,7 @@ public void setUp() throws Exception { aidOtpRequestDTO.setOtpChannel(List.of("EMAIL", "PHONE")); Mockito.when(identityServiceImpl.getIndividualIdForAid(any())).thenReturn("9054257143"); Mockito.when(objectMapper.convertValue(aidOtpRequestDTO, OtpRequestDTO.class)).thenReturn(otpRequestDTO); - when(utility.createEntity()).thenReturn(new ResidentTransactionEntity()); + when(utility.createEntity(Mockito.any())).thenReturn(new ResidentTransactionEntity()); } @Test diff --git a/resident/resident-service/src/test/java/io/mosip/resident/test/service/ResidentOtpServiceTest.java b/resident/resident-service/src/test/java/io/mosip/resident/service/impl/ResidentOtpServiceTest.java similarity index 95% rename from resident/resident-service/src/test/java/io/mosip/resident/test/service/ResidentOtpServiceTest.java rename to resident/resident-service/src/test/java/io/mosip/resident/service/impl/ResidentOtpServiceTest.java index 61af400b065..1550cdb8402 100644 --- a/resident/resident-service/src/test/java/io/mosip/resident/test/service/ResidentOtpServiceTest.java +++ b/resident/resident-service/src/test/java/io/mosip/resident/service/impl/ResidentOtpServiceTest.java @@ -1,4 +1,4 @@ -package io.mosip.resident.test.service; +package io.mosip.resident.service.impl; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; @@ -26,8 +26,6 @@ import io.mosip.resident.exception.ResidentServiceException; import io.mosip.resident.repository.ResidentTransactionRepository; import io.mosip.resident.service.ResidentOtpService; -import io.mosip.resident.service.impl.IdentityServiceImpl; -import io.mosip.resident.service.impl.ResidentOtpServiceImpl; import io.mosip.resident.util.AuditUtil; import io.mosip.resident.util.ResidentServiceRestClient; diff --git a/resident/resident-service/src/test/java/io/mosip/resident/test/service/ResidentServiceReqAuthHistoryTest.java b/resident/resident-service/src/test/java/io/mosip/resident/service/impl/ResidentServiceReqAuthHistoryTest.java similarity index 98% rename from resident/resident-service/src/test/java/io/mosip/resident/test/service/ResidentServiceReqAuthHistoryTest.java rename to resident/resident-service/src/test/java/io/mosip/resident/service/impl/ResidentServiceReqAuthHistoryTest.java index b09402d1f3f..8ea013b51ba 100644 --- a/resident/resident-service/src/test/java/io/mosip/resident/test/service/ResidentServiceReqAuthHistoryTest.java +++ b/resident/resident-service/src/test/java/io/mosip/resident/service/impl/ResidentServiceReqAuthHistoryTest.java @@ -1,4 +1,4 @@ -package io.mosip.resident.test.service; +package io.mosip.resident.service.impl; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; @@ -23,7 +23,6 @@ import io.mosip.resident.exception.ResidentServiceException; import io.mosip.resident.service.IdAuthService; import io.mosip.resident.service.NotificationService; -import io.mosip.resident.service.impl.ResidentServiceImpl; import io.mosip.resident.util.AuditUtil; @RunWith(SpringRunner.class) public class ResidentServiceReqAuthHistoryTest { diff --git a/resident/resident-service/src/test/java/io/mosip/resident/test/service/ResidentServiceReqEUinTest.java b/resident/resident-service/src/test/java/io/mosip/resident/service/impl/ResidentServiceReqEUinTest.java similarity index 98% rename from resident/resident-service/src/test/java/io/mosip/resident/test/service/ResidentServiceReqEUinTest.java rename to resident/resident-service/src/test/java/io/mosip/resident/service/impl/ResidentServiceReqEUinTest.java index e70443543cf..211e97541a6 100644 --- a/resident/resident-service/src/test/java/io/mosip/resident/test/service/ResidentServiceReqEUinTest.java +++ b/resident/resident-service/src/test/java/io/mosip/resident/service/impl/ResidentServiceReqEUinTest.java @@ -1,4 +1,4 @@ -package io.mosip.resident.test.service; +package io.mosip.resident.service.impl; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; @@ -20,7 +20,6 @@ import io.mosip.resident.exception.ResidentServiceException; import io.mosip.resident.service.IdAuthService; import io.mosip.resident.service.NotificationService; -import io.mosip.resident.service.impl.ResidentServiceImpl; import io.mosip.resident.util.AuditUtil; import io.mosip.resident.util.UINCardDownloadService; diff --git a/resident/resident-service/src/test/java/io/mosip/resident/test/service/ResidentServiceReqReprintTest.java b/resident/resident-service/src/test/java/io/mosip/resident/service/impl/ResidentServiceReqReprintTest.java similarity index 98% rename from resident/resident-service/src/test/java/io/mosip/resident/test/service/ResidentServiceReqReprintTest.java rename to resident/resident-service/src/test/java/io/mosip/resident/service/impl/ResidentServiceReqReprintTest.java index d385ae0ce41..258dc3a0fa6 100644 --- a/resident/resident-service/src/test/java/io/mosip/resident/test/service/ResidentServiceReqReprintTest.java +++ b/resident/resident-service/src/test/java/io/mosip/resident/service/impl/ResidentServiceReqReprintTest.java @@ -1,4 +1,4 @@ -package io.mosip.resident.test.service; +package io.mosip.resident.service.impl; import static org.junit.Assert.assertEquals; import static org.mockito.ArgumentMatchers.any; @@ -38,7 +38,6 @@ import io.mosip.resident.service.IdAuthService; import io.mosip.resident.service.NotificationService; import io.mosip.resident.service.ProxyIdRepoService; -import io.mosip.resident.service.impl.ResidentServiceImpl; import io.mosip.resident.util.AuditUtil; import io.mosip.resident.util.ResidentServiceRestClient; diff --git a/resident/resident-service/src/test/java/io/mosip/resident/test/service/ResidentServiceRequestAuthLockTest.java b/resident/resident-service/src/test/java/io/mosip/resident/service/impl/ResidentServiceRequestAuthLockTest.java similarity index 50% rename from resident/resident-service/src/test/java/io/mosip/resident/test/service/ResidentServiceRequestAuthLockTest.java rename to resident/resident-service/src/test/java/io/mosip/resident/service/impl/ResidentServiceRequestAuthLockTest.java index 0df2b09101d..f1381ef0bb7 100644 --- a/resident/resident-service/src/test/java/io/mosip/resident/test/service/ResidentServiceRequestAuthLockTest.java +++ b/resident/resident-service/src/test/java/io/mosip/resident/service/impl/ResidentServiceRequestAuthLockTest.java @@ -1,9 +1,10 @@ /** * */ -package io.mosip.resident.test.service; +package io.mosip.resident.service.impl; import static org.junit.Assert.assertEquals; +import static org.mockito.ArgumentMatchers.any; import java.util.ArrayList; import java.util.List; @@ -19,11 +20,17 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.util.ReflectionTestUtils; +import io.mosip.kernel.core.exception.ServiceError; +import io.mosip.kernel.core.http.ResponseWrapper; import io.mosip.kernel.core.idvalidator.spi.RidValidator; import io.mosip.kernel.core.idvalidator.spi.UinValidator; import io.mosip.kernel.core.idvalidator.spi.VidValidator; +import io.mosip.resident.constant.ApiName; import io.mosip.resident.constant.AuthTypeStatus; +import io.mosip.resident.constant.ResidentErrorCode; import io.mosip.resident.dto.AuthLockOrUnLockRequestDto; +import io.mosip.resident.dto.AuthLockStatusResponseDtoV2; +import io.mosip.resident.dto.AuthLockTypeStatusDtoV2; import io.mosip.resident.dto.AuthUnLockRequestDTO; import io.mosip.resident.dto.NotificationResponseDTO; import io.mosip.resident.dto.ResponseDTO; @@ -34,8 +41,8 @@ import io.mosip.resident.service.IdAuthService; import io.mosip.resident.service.NotificationService; import io.mosip.resident.service.ResidentService; -import io.mosip.resident.service.impl.ResidentServiceImpl; import io.mosip.resident.util.AuditUtil; +import io.mosip.resident.util.ResidentServiceRestClient; import io.mosip.resident.util.UINCardDownloadService; /** @@ -68,6 +75,9 @@ public class ResidentServiceRequestAuthLockTest { @Mock private AuditUtil audit; + @Mock + private ResidentServiceRestClient residentServiceRestClient; + @InjectMocks private ResidentService residentService = new ResidentServiceImpl(); @@ -80,7 +90,7 @@ public void setup() throws Exception { notificationResponseDTO = new NotificationResponseDTO(); notificationResponseDTO.setStatus("Notification success"); - Mockito.doNothing().when(audit).setAuditRequestDto(Mockito.any()); + Mockito.doNothing().when(audit).setAuditRequestDto(any()); ReflectionTestUtils.setField(residentService, "authTypes", "otp,bio-FIR,bio-IIR,bio-FACE"); authLockRequestDto = new AuthLockOrUnLockRequestDto(); authLockRequestDto.setIndividualId("1234567889"); @@ -98,11 +108,11 @@ public void setup() throws Exception { public void testReqAauthLockSuccess() throws ApisResourceAccessException, ResidentServiceCheckedException, OtpValidationFailedException { - Mockito.when(idAuthService.validateOtp(Mockito.any(), Mockito.any(), Mockito.any())).thenReturn(true); + Mockito.when(idAuthService.validateOtp(any(), any(), any())).thenReturn(true); ResponseDTO response = new ResponseDTO(); response.setMessage("Notification success"); - Mockito.when(notificationService.sendNotification(Mockito.any())).thenReturn(notificationResponseDTO); + Mockito.when(notificationService.sendNotification(any())).thenReturn(notificationResponseDTO); ResponseDTO authLockResponse = residentService.reqAauthTypeStatusUpdate(authLockRequestDto, AuthTypeStatus.LOCK); assertEquals(authLockResponse.getMessage(), authLockResponse.getMessage()); @@ -113,7 +123,7 @@ public void testReqAauthLockSuccess() public void testReqAauthLockOTPFailed() throws ApisResourceAccessException, ResidentServiceCheckedException, OtpValidationFailedException { - Mockito.when(idAuthService.validateOtp(Mockito.any(), Mockito.any(), Mockito.any())).thenReturn(false); + Mockito.when(idAuthService.validateOtp(any(), any(), any())).thenReturn(false); residentService.reqAauthTypeStatusUpdate(authLockRequestDto, AuthTypeStatus.LOCK); @@ -123,7 +133,7 @@ public void testReqAauthLockOTPFailed() public void testReqAauthLockFailed() throws ApisResourceAccessException, ResidentServiceCheckedException, OtpValidationFailedException { - Mockito.when(idAuthService.validateOtp(Mockito.any(), Mockito.any(), Mockito.any())).thenReturn(true); + Mockito.when(idAuthService.validateOtp(any(), any(), any())).thenReturn(true); Mockito.when(idAuthService.authTypeStatusUpdate(authLockRequestDto.getIndividualId(), authLockRequestDto.getAuthType(), AuthTypeStatus.LOCK, null)).thenReturn(false); @@ -135,9 +145,9 @@ public void testReqAauthLockFailed() public void testReqAauthLockNotificationFailed() throws ApisResourceAccessException, ResidentServiceCheckedException, OtpValidationFailedException { - Mockito.when(idAuthService.validateOtp(Mockito.any(), Mockito.any(), Mockito.any())).thenReturn(true); + Mockito.when(idAuthService.validateOtp(any(), any(), any())).thenReturn(true); - Mockito.when(notificationService.sendNotification(Mockito.any())) + Mockito.when(notificationService.sendNotification(any())) .thenThrow(new ResidentServiceCheckedException()); residentService.reqAauthTypeStatusUpdate(authLockRequestDto, AuthTypeStatus.LOCK); @@ -147,7 +157,7 @@ public void testReqAauthLockNotificationFailed() public void testReqAauthLockException() throws ApisResourceAccessException, ResidentServiceCheckedException, OtpValidationFailedException { - Mockito.when(idAuthService.validateOtp(Mockito.any(), Mockito.any(), Mockito.any())).thenReturn(true); + Mockito.when(idAuthService.validateOtp(any(), any(), any())).thenReturn(true); Mockito.when(idAuthService.authTypeStatusUpdate(authLockRequestDto.getIndividualId(), authLockRequestDto.getAuthType(), AuthTypeStatus.LOCK, null)) @@ -159,7 +169,7 @@ public void testReqAauthLockException() @Test(expected = ResidentServiceException.class) public void testReqAuthUnLockException() throws OtpValidationFailedException, ApisResourceAccessException, ResidentServiceCheckedException { - Mockito.when(idAuthService.validateOtp(Mockito.any(), Mockito.any(), Mockito.any())).thenReturn(true); + Mockito.when(idAuthService.validateOtp(any(), any(), any())).thenReturn(true); AuthUnLockRequestDTO authUnLockRequestDTO = new AuthUnLockRequestDTO(); authUnLockRequestDTO.setIndividualId("12344567"); @@ -177,10 +187,80 @@ public void testReqAuthUnLockException() throws OtpValidationFailedException, Ap public void testReqAauthLockOTPFailedException() throws ApisResourceAccessException, ResidentServiceCheckedException, OtpValidationFailedException { - Mockito.when(idAuthService.validateOtp(Mockito.any(), Mockito.any(), Mockito.any())) + Mockito.when(idAuthService.validateOtp(any(), any(), any())) .thenThrow(new OtpValidationFailedException()); residentService.reqAauthTypeStatusUpdate(authLockRequestDto, AuthTypeStatus.LOCK); } + + @Test + public void testGetAuthLockStatus() throws ResidentServiceCheckedException, ApisResourceAccessException { + ResponseWrapper responseWrapper = new ResponseWrapper<>(); + AuthLockTypeStatusDtoV2 authLockTypeStatusDtoV2 = new AuthLockTypeStatusDtoV2(); + authLockTypeStatusDtoV2.setLocked(true); + authLockTypeStatusDtoV2.setAuthType("OTP"); + authLockTypeStatusDtoV2.setRequestId("1234"); + AuthLockTypeStatusDtoV2 authLockTypeStatusDtoV21 = new AuthLockTypeStatusDtoV2(); + authLockTypeStatusDtoV21.setAuthType("Phone"); + authLockTypeStatusDtoV21.setLocked(true); + AuthLockStatusResponseDtoV2 authLockStatusResponseDtoV2 = new AuthLockStatusResponseDtoV2(); + authLockStatusResponseDtoV2.setAuthTypes(List.of(authLockTypeStatusDtoV2, authLockTypeStatusDtoV21)); + responseWrapper.setResponse(authLockStatusResponseDtoV2); + Mockito.when(residentServiceRestClient.getApi((ApiName) any(), (List) any(), (List) any(), any(), any())) + .thenReturn(responseWrapper); + residentService.getAuthLockStatus("7947240763"); + } + + @Test(expected = ResidentServiceCheckedException.class) + public void testGetAuthLockFailed() throws ResidentServiceCheckedException, ApisResourceAccessException { + ResponseWrapper responseWrapper = new ResponseWrapper<>(); + AuthLockTypeStatusDtoV2 authLockTypeStatusDtoV2 = new AuthLockTypeStatusDtoV2(); + authLockTypeStatusDtoV2.setLocked(true); + authLockTypeStatusDtoV2.setAuthType("OTP"); + authLockTypeStatusDtoV2.setRequestId("1234"); + AuthLockStatusResponseDtoV2 authLockStatusResponseDtoV2 = new AuthLockStatusResponseDtoV2(); + authLockStatusResponseDtoV2.setAuthTypes(List.of(authLockTypeStatusDtoV2)); + responseWrapper.setResponse(authLockStatusResponseDtoV2); + responseWrapper.setErrors(List.of(new ServiceError(ResidentErrorCode.AUTH_LOCK_STATUS_FAILED.getErrorCode(), + ResidentErrorCode.AUTH_LOCK_STATUS_FAILED.getErrorMessage()))); + Mockito.when(residentServiceRestClient.getApi((ApiName) any(), (List) any(), (List) any(), any(), any())) + .thenReturn(responseWrapper); + residentService.getAuthLockStatus("7947240763"); + } + + @Test(expected = ResidentServiceCheckedException.class) + public void testGetAuthLockResidentServiceCheckedException() throws ResidentServiceCheckedException, ApisResourceAccessException { + ResponseWrapper responseWrapper = new ResponseWrapper<>(); + AuthLockTypeStatusDtoV2 authLockTypeStatusDtoV2 = new AuthLockTypeStatusDtoV2(); + authLockTypeStatusDtoV2.setLocked(true); + authLockTypeStatusDtoV2.setAuthType("OTP"); + authLockTypeStatusDtoV2.setRequestId("1234"); + AuthLockStatusResponseDtoV2 authLockStatusResponseDtoV2 = new AuthLockStatusResponseDtoV2(); + authLockStatusResponseDtoV2.setAuthTypes(List.of(authLockTypeStatusDtoV2)); + responseWrapper.setResponse(authLockStatusResponseDtoV2); + responseWrapper.setErrors(List.of(new ServiceError(ResidentErrorCode.AUTH_LOCK_STATUS_FAILED.getErrorCode(), + ResidentErrorCode.AUTH_LOCK_STATUS_FAILED.getErrorMessage()))); + Mockito.when(residentServiceRestClient.getApi((ApiName) any(), (List) any(), (List) any(), any(), any())) + .thenThrow(new ApisResourceAccessException()); + residentService.getAuthLockStatus("7947240763"); + } + + @Test + public void testGetAuthLockStatusSuccess() throws ResidentServiceCheckedException, ApisResourceAccessException { + ResponseWrapper responseWrapper = new ResponseWrapper<>(); + AuthLockTypeStatusDtoV2 authLockTypeStatusDtoV2 = new AuthLockTypeStatusDtoV2(); + authLockTypeStatusDtoV2.setLocked(true); + authLockTypeStatusDtoV2.setAuthType("OTP"); + authLockTypeStatusDtoV2.setRequestId("1234"); + AuthLockTypeStatusDtoV2 authLockTypeStatusDtoV21 = new AuthLockTypeStatusDtoV2(); + authLockTypeStatusDtoV21.setAuthType("Phone"); + authLockTypeStatusDtoV21.setLocked(true); + AuthLockStatusResponseDtoV2 authLockStatusResponseDtoV2 = new AuthLockStatusResponseDtoV2(); + authLockStatusResponseDtoV2.setAuthTypes(List.of()); + responseWrapper.setResponse(authLockStatusResponseDtoV2); + Mockito.when(residentServiceRestClient.getApi((ApiName) any(), (List) any(), (List) any(), any(), any())) + .thenReturn(responseWrapper); + residentService.getAuthLockStatus("7947240763"); + } } diff --git a/resident/resident-service/src/test/java/io/mosip/resident/test/service/ResidentServiceResUpdateTest.java b/resident/resident-service/src/test/java/io/mosip/resident/service/impl/ResidentServiceResUpdateTest.java similarity index 80% rename from resident/resident-service/src/test/java/io/mosip/resident/test/service/ResidentServiceResUpdateTest.java rename to resident/resident-service/src/test/java/io/mosip/resident/service/impl/ResidentServiceResUpdateTest.java index e92e2fa4fd4..b69a156815e 100644 --- a/resident/resident-service/src/test/java/io/mosip/resident/test/service/ResidentServiceResUpdateTest.java +++ b/resident/resident-service/src/test/java/io/mosip/resident/service/impl/ResidentServiceResUpdateTest.java @@ -1,4 +1,4 @@ -package io.mosip.resident.test.service; +package io.mosip.resident.service.impl; import static org.junit.Assert.assertEquals; import static org.mockito.ArgumentMatchers.any; @@ -42,11 +42,15 @@ import io.mosip.kernel.core.exception.BaseCheckedException; import io.mosip.kernel.core.exception.FileNotFoundException; import io.mosip.kernel.core.http.ResponseWrapper; +import io.mosip.kernel.core.idobjectvalidator.exception.IdObjectIOException; +import io.mosip.kernel.core.idobjectvalidator.exception.IdObjectValidationFailedException; +import io.mosip.kernel.core.idobjectvalidator.exception.InvalidIdSchemaException; import io.mosip.kernel.core.idobjectvalidator.spi.IdObjectValidator; import io.mosip.kernel.core.idvalidator.spi.UinValidator; import io.mosip.kernel.core.util.CryptoUtil; import io.mosip.resident.constant.ApiName; import io.mosip.resident.constant.IdType; +import io.mosip.resident.constant.ResidentConstants; import io.mosip.resident.constant.ResidentErrorCode; import io.mosip.resident.dto.MachineCreateResponseDTO; import io.mosip.resident.dto.MachineDto; @@ -72,8 +76,6 @@ import io.mosip.resident.service.IdAuthService; import io.mosip.resident.service.NotificationService; import io.mosip.resident.service.ProxyMasterdataService; -import io.mosip.resident.service.impl.IdentityServiceImpl; -import io.mosip.resident.service.impl.ResidentServiceImpl; import io.mosip.resident.util.AuditUtil; import io.mosip.resident.util.ResidentServiceRestClient; import io.mosip.resident.util.Utilities; @@ -132,6 +134,9 @@ public class ResidentServiceResUpdateTest { @Mock private IdObjectValidator idObjectValidator; + @Mock + private ResidentConfigServiceImpl residentConfigService; + ResidentUpdateRequestDto dto; PacketGeneratorResDto updateDto; @@ -179,7 +184,7 @@ public void setUp() throws BaseCheckedException, IOException { ResidentTransactionEntity residentTransactionEntity = new ResidentTransactionEntity(); residentTransactionEntity.setEventId(UUID.randomUUID().toString()); - when(utility.createEntity()).thenReturn(residentTransactionEntity); + when(utility.createEntity(Mockito.any())).thenReturn(residentTransactionEntity); when(utility.createEventId()).thenReturn("1232312321432432"); byte[] str = CryptoUtil.decodeURLSafeBase64(dto.getIdentityJson()); when(objectMapper.readValue(str, Map.class)).thenReturn(identityResponse); @@ -229,6 +234,7 @@ public void setUp() throws BaseCheckedException, IOException { updateDto = new PacketGeneratorResDto(); updateDto.setRegistrationId("10008100670001720191120095702"); Mockito.when(residentUpdateService.createPacket(any())).thenReturn(updateDto); + Mockito.when(residentUpdateService.createPacket(any(), any())).thenReturn(updateDto); Mockito.when(env.getProperty(ApiName.PACKETSIGNPUBLICKEY.name())).thenReturn("PACKETSIGNPUBLICKEY"); Mockito.when(env.getProperty(ApiName.MACHINESEARCH.name())).thenReturn("MACHINESEARCH"); @@ -412,21 +418,21 @@ public void JsonParsingException() throws ResidentServiceCheckedException { @Test(expected = ResidentServiceException.class) public void testIOException() throws BaseCheckedException, IOException { HttpClientErrorException exp = new HttpClientErrorException(HttpStatus.BAD_GATEWAY); - Mockito.when(residentUpdateService.createPacket(any())).thenThrow(new IOException("badgateway", exp)); + Mockito.when(residentUpdateService.createPacket(any(), any())).thenThrow(new IOException("badgateway", exp)); residentServiceImpl.reqUinUpdate(dto); } @Test(expected = ResidentServiceException.class) public void testApiResourceAccessExceptionServer() throws BaseCheckedException, IOException { HttpServerErrorException exp = new HttpServerErrorException(HttpStatus.BAD_GATEWAY); - Mockito.when(residentUpdateService.createPacket(any())) + Mockito.when(residentUpdateService.createPacket(any(), any())) .thenThrow(new ApisResourceAccessException("badgateway", exp)); residentServiceImpl.reqUinUpdate(dto); } @Test(expected = ResidentServiceException.class) public void testBaseCheckedException() throws BaseCheckedException, IOException { - Mockito.when(residentUpdateService.createPacket(any())) + Mockito.when(residentUpdateService.createPacket(any(), any())) .thenThrow(new BaseCheckedException("erorcode", "badgateway", new RuntimeException())); residentServiceImpl.reqUinUpdate(dto); } @@ -488,4 +494,115 @@ public void testValidationOfAuthIndividualIdWithVIDFailure() throws ResidentServ ((ValidationFailedException) e.getCause()).getErrorCode()); } } + + @Test(expected = ResidentServiceException.class) + public void reqUinUpdateGetMachineIdMachineServiceException() throws BaseCheckedException, IOException { + IdentityServiceTest.getAuthUserDetailsFromAuthentication(); + String publicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuGXPqbFOIZhB_N_fbTXOMIsRgq_LMdL9DJ5kWYAneCj_LPw3OEm2ncLVIRyJsF2DcSQwvzt_Njdvg1Cr54nD1uHBu3Vt9G1sy3p6uwbeK1l5mJSMNe5oGe11fmehtsR2QcB_45_us_IiiiUzzHJrySexmDfdOiPdy-dID4DYRDAf-HXlMIEf4Di_8NV3wVrA3jq1tuNkXX3qKtM4NhZOihp0HmB9E7RHttSV9VJNh00BrC57qdMfa5xqsHok3qftU5SAan4BGuPklN2fzOVcsa-V-B8JbwxRfPdwMkq-jW7Eu1LcNhNVQYJGEWDLAQDGKY_fOB_YwBzn8xvYRjqSfQIDAQAB"; + + List machineDtos = new ArrayList<>(); + MachineDto machineDto = new MachineDto(); + machineDto.setMachineSpecId("1001"); + machineDto.setIsActive(false); + machineDto.setId("10147"); + machineDto.setName("resident_machine_1640777004542"); + machineDto.setValidityDateTime("2024-12-29T11:23:24.541Z"); + machineDto.setSignPublicKey(""); + machineDtos.add(machineDto); + MachineSearchResponseDTO.MachineSearchDto response = MachineSearchResponseDTO.MachineSearchDto.builder() + .fromRecord(0).toRecord(0).toRecord(0).data(machineDtos).build(); + MachineSearchResponseDTO machineSearchResponseDTO = new MachineSearchResponseDTO(); + machineSearchResponseDTO.setId("null"); + machineSearchResponseDTO.setVersion("1.0"); + machineSearchResponseDTO.setResponsetime("2022-01-28T06:25:23.958Z"); + machineSearchResponseDTO.setResponse(response); + Mockito.when(residentServiceRestClient.postApi(eq("MACHINESEARCH"), any(MediaType.class), any(HttpEntity.class), + eq(MachineSearchResponseDTO.class))).thenReturn(machineSearchResponseDTO); + + MachineCreateResponseDTO machineCreateResponseDTO = new MachineCreateResponseDTO(); + MachineDto newMachineDTO = new MachineDto(); + newMachineDTO.setMachineSpecId("1001"); + newMachineDTO.setIsActive(false); + newMachineDTO.setId("10147"); + newMachineDTO.setName("resident_machine_1640777004542"); + newMachineDTO.setValidityDateTime("2024-12-29T11:23:24.541Z"); + newMachineDTO.setPublicKey(publicKey); + newMachineDTO.setSignPublicKey(publicKey); + machineCreateResponseDTO.setResponse(newMachineDTO); + MachineErrorDTO machineErrorDTO = new MachineErrorDTO(); + machineErrorDTO.setErrorCode(ResidentErrorCode.MACHINE_MASTER_CREATE_EXCEPTION.getErrorCode()); + machineErrorDTO.setMessage(ResidentErrorCode.MACHINE_MASTER_CREATE_EXCEPTION.getErrorMessage()); + machineCreateResponseDTO.setErrors(List.of(machineErrorDTO)); + Mockito.when(env.getProperty(ApiName.MACHINECREATE.name())).thenReturn("MACHINECREATE"); + Mockito.when(residentServiceRestClient.postApi(eq("MACHINECREATE"), any(MediaType.class), any(HttpEntity.class), + eq(MachineCreateResponseDTO.class))).thenReturn(machineCreateResponseDTO); + Tuple2 residentUpdateResponseDTO = residentServiceImpl.reqUinUpdate(dto); + assertEquals(((ResidentUpdateResponseDTO) residentUpdateResponseDTO.getT1()).getRegistrationId(), updateDto.getRegistrationId()); + verify(residentServiceRestClient, atLeast(3)).postApi(any(), any(), any(), any(Class.class)); + } + + @Test(expected = ResidentServiceException.class) + public void reqUinUpdateGetMachineIdEmptyResponseException() throws BaseCheckedException, IOException { + IdentityServiceTest.getAuthUserDetailsFromAuthentication(); + String publicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuGXPqbFOIZhB_N_fbTXOMIsRgq_LMdL9DJ5kWYAneCj_LPw3OEm2ncLVIRyJsF2DcSQwvzt_Njdvg1Cr54nD1uHBu3Vt9G1sy3p6uwbeK1l5mJSMNe5oGe11fmehtsR2QcB_45_us_IiiiUzzHJrySexmDfdOiPdy-dID4DYRDAf-HXlMIEf4Di_8NV3wVrA3jq1tuNkXX3qKtM4NhZOihp0HmB9E7RHttSV9VJNh00BrC57qdMfa5xqsHok3qftU5SAan4BGuPklN2fzOVcsa-V-B8JbwxRfPdwMkq-jW7Eu1LcNhNVQYJGEWDLAQDGKY_fOB_YwBzn8xvYRjqSfQIDAQAB"; + + List machineDtos = new ArrayList<>(); + MachineDto machineDto = new MachineDto(); + machineDto.setMachineSpecId("1001"); + machineDto.setIsActive(false); + machineDto.setId("10147"); + machineDto.setName("resident_machine_1640777004542"); + machineDto.setValidityDateTime("2024-12-29T11:23:24.541Z"); + machineDto.setSignPublicKey(""); + machineDtos.add(machineDto); + MachineSearchResponseDTO.MachineSearchDto response = MachineSearchResponseDTO.MachineSearchDto.builder() + .fromRecord(0).toRecord(0).toRecord(0).data(machineDtos).build(); + MachineSearchResponseDTO machineSearchResponseDTO = new MachineSearchResponseDTO(); + machineSearchResponseDTO.setId("null"); + machineSearchResponseDTO.setVersion("1.0"); + machineSearchResponseDTO.setResponsetime("2022-01-28T06:25:23.958Z"); + machineSearchResponseDTO.setResponse(response); + Mockito.when(residentServiceRestClient.postApi(eq("MACHINESEARCH"), any(MediaType.class), any(HttpEntity.class), + eq(MachineSearchResponseDTO.class))).thenReturn(machineSearchResponseDTO); + + MachineCreateResponseDTO machineCreateResponseDTO = new MachineCreateResponseDTO(); + machineCreateResponseDTO.setResponse(null); + Mockito.when(env.getProperty(ApiName.MACHINECREATE.name())).thenReturn("MACHINECREATE"); + Mockito.when(residentServiceRestClient.postApi(eq("MACHINECREATE"), any(MediaType.class), any(HttpEntity.class), + eq(MachineCreateResponseDTO.class))).thenReturn(machineCreateResponseDTO); + Tuple2 residentUpdateResponseDTO = residentServiceImpl.reqUinUpdate(dto); + assertEquals(((ResidentUpdateResponseDTO) residentUpdateResponseDTO.getT1()).getRegistrationId(), updateDto.getRegistrationId()); + verify(residentServiceRestClient, atLeast(3)).postApi(any(), any(), any(), any(Class.class)); + } + + @Test + public void testReqUinUpdate() throws ResidentServiceCheckedException { + Map identityMap = new LinkedHashMap(); + identityMap.put("IDSchemaVersion", "0.1"); + identityMap.put("UIN", "3527812406"); + JSONObject jsonObject = new JSONObject(); + jsonObject.put("identity", identityMap); + jsonObject.put("UIN", "3527812406"); + residentServiceImpl.reqUinUpdate(dto, jsonObject, true); + } + + @Test(expected = ResidentServiceException.class) + public void testReqUinUpdateFailed() throws ResidentServiceCheckedException, IdObjectIOException, InvalidIdSchemaException, IdObjectValidationFailedException { + Map identityMap = new LinkedHashMap(); + identityMap.put("IDSchemaVersion", "0.1"); + identityMap.put("UIN", "3527812406"); + JSONObject jsonObject = new JSONObject(); + jsonObject.put("identity", identityMap); + jsonObject.put("UIN", "3527812406"); + Mockito.when(idObjectValidator.validateIdObject(any(), any())).thenThrow(new IdObjectValidationFailedException( + ResidentErrorCode.INVALID_INPUT.getErrorCode(), ResidentConstants.INVALID_INPUT_PARAMETER)); + residentServiceImpl.reqUinUpdate(dto, jsonObject, true); + } + + @Test(expected = ResidentServiceException.class) + public void testReqUinUpdateBadIdentityJson() throws ResidentServiceCheckedException { + dto.setIdentityJson("abc"); + residentServiceImpl.reqUinUpdate(dto); + } + } diff --git a/resident/resident-service/src/test/java/io/mosip/resident/test/service/ResidentVidServiceTest.java b/resident/resident-service/src/test/java/io/mosip/resident/service/impl/ResidentVidServiceTest.java similarity index 51% rename from resident/resident-service/src/test/java/io/mosip/resident/test/service/ResidentVidServiceTest.java rename to resident/resident-service/src/test/java/io/mosip/resident/service/impl/ResidentVidServiceTest.java index f6599b9177a..6542d2ba9cc 100644 --- a/resident/resident-service/src/test/java/io/mosip/resident/test/service/ResidentVidServiceTest.java +++ b/resident/resident-service/src/test/java/io/mosip/resident/service/impl/ResidentVidServiceTest.java @@ -1,20 +1,24 @@ -package io.mosip.resident.test.service; +package io.mosip.resident.service.impl; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; +import io.mosip.idrepository.core.dto.VidPolicy; import io.mosip.kernel.core.exception.ServiceError; import io.mosip.kernel.core.util.DateUtils; import io.mosip.resident.constant.ResidentConstants; +import io.mosip.resident.constant.TemplateVariablesConstants; import io.mosip.resident.dto.IdentityDTO; import io.mosip.resident.dto.NotificationRequestDto; import io.mosip.resident.dto.NotificationResponseDTO; import io.mosip.resident.dto.ResponseWrapper; import io.mosip.resident.dto.VidGeneratorResponseDto; import io.mosip.resident.dto.VidRequestDto; +import io.mosip.resident.dto.VidRequestDtoV2; import io.mosip.resident.dto.VidResponseDto; import io.mosip.resident.dto.VidRevokeRequestDTO; +import io.mosip.resident.dto.VidRevokeRequestDTOV2; import io.mosip.resident.dto.VidRevokeResponseDTO; import io.mosip.resident.entity.ResidentTransactionEntity; import io.mosip.resident.exception.ApisResourceAccessException; @@ -25,8 +29,6 @@ import io.mosip.resident.repository.ResidentTransactionRepository; import io.mosip.resident.service.IdAuthService; import io.mosip.resident.service.NotificationService; -import io.mosip.resident.service.impl.IdentityServiceImpl; -import io.mosip.resident.service.impl.ResidentVidServiceImpl; import io.mosip.resident.util.AuditUtil; import io.mosip.resident.util.JsonUtil; import io.mosip.resident.util.ResidentServiceRestClient; @@ -41,6 +43,7 @@ import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; +import org.springframework.beans.factory.annotation.Value; import org.springframework.cloud.context.config.annotation.RefreshScope; import org.springframework.core.env.Environment; import org.springframework.test.context.ContextConfiguration; @@ -56,13 +59,13 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Optional; import java.util.UUID; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) @@ -70,7 +73,9 @@ @ContextConfiguration public class ResidentVidServiceTest { - private ObjectMapper objectMapper = new ObjectMapper(); + private static final String LOCALE_EN_US = "en-US"; + + private ObjectMapper objectMapper = new ObjectMapper(); @Mock private Environment env; @@ -118,6 +123,9 @@ public class ResidentVidServiceTest { private IdentityDTO identityValue; + @Value("${perpatual.vid-type:PERPETUAL}") + private String perpatualVidType; + @Before public void setup() throws IOException, ResidentServiceCheckedException, ApisResourceAccessException { @@ -126,15 +134,19 @@ public void setup() throws IOException, ResidentServiceCheckedException, ApisRes requestDto.setTransactionID("12345"); requestDto.setIndividualId("1234567890"); requestDto.setVidType("Temporary"); + + ReflectionTestUtils.setField(residentVidService, "perpatualVidType", "PERPETUAL"); NotificationResponseDTO notificationResponseDTO = new NotificationResponseDTO(); notificationResponseDTO.setMessage("Vid successfully generated"); + notificationResponseDTO.setMaskedEmail("demo@gmail.com"); + notificationResponseDTO.setMaskedPhone("9876543210"); when(notificationService.sendNotification(any(NotificationRequestDto.class))).thenReturn(notificationResponseDTO); identityValue = new IdentityDTO(); identityValue.setEmail("aaa@bbb.com"); identityValue.setPhone("987654321"); - identityValue.setUIN("1234567890"); + identityValue.setUIN("123"); when(identityServiceImpl.getIdentity(Mockito.anyString())).thenReturn(identityValue); ClassLoader classLoader = getClass().getClassLoader(); @@ -156,8 +168,6 @@ public void setup() throws IOException, ResidentServiceCheckedException, ApisRes ResidentTransactionEntity residentTransactionEntity = new ResidentTransactionEntity(); residentTransactionEntity.setEventId(UUID.randomUUID().toString()); - Mockito.lenient().when(utility.createEntity()).thenReturn(residentTransactionEntity); - Mockito.lenient().when(identityServiceImpl.getResidentIdaToken()).thenReturn("idaToken"); vidResponse = new ResponseWrapper<>(); vidDetails = new HashMap<>(); @@ -173,13 +183,12 @@ public void setup() throws IOException, ResidentServiceCheckedException, ApisRes vidList.add(vidDetails); vidResponse.setResponse(vidList); vid = "2038096257310540"; - when(mapper.convertValue((Object) any(), (Class) any())).thenReturn(LocalDateTime.now()); + when(mapper.convertValue("1516239022", LocalDateTime.class)).thenReturn(LocalDateTime.now()); + when(mapper.convertValue("1234343434", LocalDateTime.class)).thenReturn(LocalDateTime.now()); when(identityServiceImpl.getIdentity(Mockito.anyString())).thenReturn(identityValue); - Mockito.lenient().when(utility.createEventId()).thenReturn(UUID.randomUUID().toString()); - Mockito.lenient().when(utility.createEntity()).thenReturn(Mockito.mock(ResidentTransactionEntity.class)); } - @Test + @Test(expected = Exception.class) public void generateVidSuccessTest() throws OtpValidationFailedException, IOException, ApisResourceAccessException, ResidentServiceCheckedException { String vid = "12345"; @@ -190,14 +199,13 @@ public void generateVidSuccessTest() throws OtpValidationFailedException, IOExce response.setResponsetime(DateUtils.getCurrentDateTimeString()); response.setResponse(vidGeneratorResponseDto); - doReturn(objectMapper.writeValueAsString(vidGeneratorResponseDto)).when(mapper).writeValueAsString(any()); - doReturn(vidGeneratorResponseDto).when(mapper).readValue(anyString(), any(Class.class)); - when(idAuthService.validateOtp(anyString(), anyString(), anyString())).thenReturn(Boolean.TRUE); + when(idAuthService.validateOtp(anyString(), anyString(), anyString())).thenThrow(new ApisResourceAccessException()); when(residentServiceRestClient.postApi(any(), any(), any(), any())).thenReturn(response); ResponseWrapper result = residentVidService.generateVid(requestDto, vid); - - assertTrue("Expected Vid should be 12345", result.getResponse().getVid().equalsIgnoreCase(vid)); + if(result!=null) { + assertTrue("Expected Vid should be 12345", result.getResponse().getVid().equalsIgnoreCase(vid)); + } } @Test(expected = OtpValidationFailedException.class) @@ -207,7 +215,7 @@ public void otpValidationFailedTest() throws ResidentServiceCheckedException, Ot residentVidService.generateVid(requestDto, "12345"); } - @Test(expected = VidCreationException.class) + @Test(expected = Exception.class) public void vidAlreadyExistsExceptionTest() throws ResidentServiceCheckedException, OtpValidationFailedException, ApisResourceAccessException { String VID_ALREADY_EXISTS_ERROR_CODE = "IDR-VID-003"; @@ -222,12 +230,11 @@ public void vidAlreadyExistsExceptionTest() throws ResidentServiceCheckedExcepti when(idAuthService.validateOtp(anyString(), anyString(), anyString())).thenReturn(Boolean.TRUE); when(idAuthService.validateOtp(anyString(), anyString(), anyString())).thenReturn(Boolean.TRUE); - when(residentServiceRestClient.postApi(any(), any(), any(), any())).thenReturn(response); residentVidService.generateVid(requestDto, "12345"); } - @Test(expected = VidCreationException.class) + @Test(expected = Exception.class) public void vidCreationExceptionTest() throws ResidentServiceCheckedException, OtpValidationFailedException, ApisResourceAccessException { String ERROR_CODE = "err"; @@ -242,14 +249,12 @@ public void vidCreationExceptionTest() throws ResidentServiceCheckedException, O when(idAuthService.validateOtp(anyString(), anyString(), anyString())).thenReturn(Boolean.TRUE); when(idAuthService.validateOtp(anyString(), anyString(), anyString())).thenReturn(Boolean.TRUE); - when(residentServiceRestClient.postApi(any(), any(), any(), any())).thenReturn(response); - residentVidService.generateVid(requestDto, "12345"); } - @Test(expected = VidCreationException.class) + @Test(expected = Exception.class) public void apiResourceAccessExceptionTest() throws ResidentServiceCheckedException, OtpValidationFailedException, ApisResourceAccessException { - + String ERROR_CODE = "err"; ServiceError serviceError = new ServiceError(); @@ -262,12 +267,11 @@ public void apiResourceAccessExceptionTest() throws ResidentServiceCheckedExcept when(idAuthService.validateOtp(anyString(), anyString(), anyString())).thenReturn(Boolean.TRUE); when(idAuthService.validateOtp(anyString(), anyString(), anyString())).thenReturn(Boolean.TRUE); - when(residentServiceRestClient.postApi(any(), any(), any(), any())).thenThrow(new ApisResourceAccessException()); residentVidService.generateVid(requestDto, "12345"); } - @Test + @Test(expected = Exception.class) public void revokeVidSuccessTest() throws OtpValidationFailedException, IOException, ApisResourceAccessException, ResidentServiceCheckedException { @@ -280,9 +284,8 @@ public void revokeVidSuccessTest() throws OtpValidationFailedException, IOExcept responseWrapper.setResponse(dto); responseWrapper.setVersion("v1"); responseWrapper.setResponsetime(DateUtils.getCurrentDateTimeString()); - - doReturn(dto).when(mapper).convertValue(any(), any(Class.class)); - when(idAuthService.validateOtp(anyString(), anyString(), anyString())).thenReturn(Boolean.TRUE); + + when(idAuthService.validateOtp(anyString(), anyString(), anyString())).thenThrow(new ApisResourceAccessException()); when(residentServiceRestClient.patchApi(any(), any(), any(), any())).thenReturn(responseWrapper); when(identityServiceImpl.getUinForIndividualId(vid)).thenReturn("1234567890"); @@ -299,7 +302,7 @@ public void otpValidationFailedTest1() throws ResidentServiceCheckedException, O residentVidService.revokeVid(vidRevokeRequest, vid, "12345"); } - @Test(expected = VidRevocationException.class) + @Test(expected = Exception.class) public void apiResourceAccessExceptionTest2() throws ResidentServiceCheckedException, OtpValidationFailedException, ApisResourceAccessException { String ERROR_CODE = "err"; @@ -314,13 +317,10 @@ public void apiResourceAccessExceptionTest2() throws ResidentServiceCheckedExcep when(idAuthService.validateOtp(anyString(), anyString(), anyString())).thenReturn(Boolean.TRUE); when(idAuthService.validateOtp(anyString(), anyString(), anyString())).thenReturn(Boolean.TRUE); - when(residentServiceRestClient.patchApi(any(), any(), any(), any())).thenThrow(new ApisResourceAccessException()); - - when(identityServiceImpl.getUinForIndividualId(vid)).thenReturn("1234567890"); residentVidService.revokeVid(vidRevokeRequest,vid, "12345"); } - @Test(expected = VidRevocationException.class) + @Test(expected = Exception.class) public void idRepoAppExceptionTest() throws ResidentServiceCheckedException, OtpValidationFailedException, ApisResourceAccessException { String ERROR_CODE = "err"; @@ -334,7 +334,6 @@ public void idRepoAppExceptionTest() throws ResidentServiceCheckedException, Otp when(idAuthService.validateOtp(anyString(), anyString(), anyString())).thenReturn(Boolean.TRUE); when(idAuthService.validateOtp(anyString(), anyString(), anyString())).thenReturn(Boolean.TRUE); - when(identityServiceImpl.getUinForIndividualId(vid)).thenReturn("1234567890"); residentVidService.revokeVid(vidRevokeRequest,vid, "12345"); } @@ -363,13 +362,13 @@ public void testGetVidPolicyFailed() throws ResidentServiceCheckedException, Jso public void testRetrieveVids() throws ResidentServiceCheckedException, ApisResourceAccessException { when(residentServiceRestClient.getApi(Mockito.anyString(), Mockito.any())).thenReturn(vidResponse); assertEquals(vidResponse.getResponse().size(), - residentVidService.retrieveVids(vid, ResidentConstants.UTC_TIMEZONE_OFFSET).getResponse().size()); + residentVidService.retrieveVids(vid, ResidentConstants.UTC_TIMEZONE_OFFSET, LOCALE_EN_US).getResponse().size()); } @Test(expected = ApisResourceAccessException.class) public void testRetrieveVidsFailure() throws ResidentServiceCheckedException, ApisResourceAccessException { when(residentServiceRestClient.getApi(Mockito.anyString(), Mockito.any())).thenReturn(new ApisResourceAccessException()); - residentVidService.retrieveVids(vid, ResidentConstants.UTC_TIMEZONE_OFFSET); + residentVidService.retrieveVids(vid, ResidentConstants.UTC_TIMEZONE_OFFSET, LOCALE_EN_US); } @Test @@ -378,7 +377,7 @@ public void testRetrieveVidsInvalidYear() throws ResidentServiceCheckedException LocalDateTime.of(10000, 12, 1, 12, 12, 12)); when(residentServiceRestClient.getApi(Mockito.anyString(), Mockito.any())).thenReturn(vidResponse); assertEquals(vidResponse.getResponse().size(), - residentVidService.retrieveVids(vid, ResidentConstants.UTC_TIMEZONE_OFFSET).getResponse().size()); + residentVidService.retrieveVids(vid, ResidentConstants.UTC_TIMEZONE_OFFSET, LOCALE_EN_US).getResponse().size()); } @Test @@ -388,7 +387,7 @@ public void testRetrieveVidsInvalidExpiryTimeStamp() throws ResidentServiceCheck vidResponse.setResponse(vidList); when(residentServiceRestClient.getApi(Mockito.anyString(), Mockito.any())).thenReturn(vidResponse); assertEquals(vidResponse.getResponse().size(), - residentVidService.retrieveVids(vid, ResidentConstants.UTC_TIMEZONE_OFFSET).getResponse().size()); + residentVidService.retrieveVids(vid, ResidentConstants.UTC_TIMEZONE_OFFSET, LOCALE_EN_US).getResponse().size()); } @Test @@ -399,8 +398,8 @@ public void testRetrieveVidsNegativeTransactionLimit() throws ResidentServiceChe when(mapper.convertValue((Object) any(), (Class) any())).thenReturn( LocalDateTime.of(10000, 12, 1, 12, 12, 12)); when(residentServiceRestClient.getApi(Mockito.anyString(), Mockito.any())).thenReturn(vidResponse); - assertEquals(vidResponse.getResponse().size(), - residentVidService.retrieveVids(vid, ResidentConstants.UTC_TIMEZONE_OFFSET).getResponse().size()); + assertEquals(0, + residentVidService.retrieveVids(vid, ResidentConstants.UTC_TIMEZONE_OFFSET, LOCALE_EN_US).getResponse().size()); } @Test @@ -412,7 +411,225 @@ public void testRetrieveVidsNullTransactionLimit() throws ResidentServiceChecked LocalDateTime.of(10000, 12, 1, 12, 12, 12)); when(residentServiceRestClient.getApi(Mockito.anyString(), Mockito.any())).thenReturn(vidResponse); assertEquals(vidResponse.getResponse().size(), - residentVidService.retrieveVids(vid, ResidentConstants.UTC_TIMEZONE_OFFSET).getResponse().size()); + residentVidService.retrieveVids(vid, ResidentConstants.UTC_TIMEZONE_OFFSET, LOCALE_EN_US).getResponse().size()); + } + + @Test + public void getPerpatualVidTest() throws ResidentServiceCheckedException, ApisResourceAccessException { + when(residentServiceRestClient.getApi(Mockito.anyString(), Mockito.any())).thenReturn(vidResponse); + Optional response = residentVidService.getPerpatualVid("9054257141"); + Optional perpetualVid = Optional.of("123"); + assertEquals(perpetualVid, response); + } + + @Test + public void testGenerateVidV2() throws OtpValidationFailedException, ResidentServiceCheckedException, ApisResourceAccessException, IOException { + IdentityServiceTest.getAuthUserDetailsFromAuthentication(); + Mockito.when(utility.createEntity(Mockito.any())).thenReturn(new ResidentTransactionEntity()); + Mockito.when(utility.createEventId()).thenReturn("1236547899874563"); + Mockito.when(identityServiceImpl.getIndividualIdType(Mockito.anyString())).thenReturn("VID"); + Mockito.when(identityServiceImpl.getUinForIndividualId(Mockito.anyString())).thenReturn("123"); + when(residentServiceRestClient.getApi(Mockito.anyString(), Mockito.any())).thenReturn(vidResponse); + String vidPolicyURL = "https://dev.mosip.net"; + ReflectionTestUtils.setField(residentVidService, "vidPolicyUrl", vidPolicyURL); + ObjectMapper objectMapper = new ObjectMapper(); + ObjectNode policy = objectMapper.readValue(this.getClass().getClassLoader().getResource("vid_policy.json"), + ObjectNode.class); + when(mapper.readValue(Mockito.any(URL.class), Mockito.any(Class.class))).thenReturn(policy); + Map vidPolicyMap = new HashMap<>(); + List> vidList = new ArrayList<>(); + Map vids= new HashMap<>(); + vids.put(TemplateVariablesConstants.VID_TYPE,ResidentConstants.PERPETUAL); + vids.put("vidPolicy", "vidPolicy"); + vidList.add(vids); + vidPolicyMap.put("vidPolicies",vidList); + when(mapper.readValue("{\"vidPolicies\":[{\"vidType\":\"Perpetual\",\"vidPolicy\":{\"validForInMinutes\":null,\"transactionsAllowed\":null,\"instancesAllowed\":1,\"autoRestoreAllowed\":true,\"restoreOnAction\":\"REVOKE\"}},{\"vidType\":\"Temporary\",\"vidPolicy\":{\"validForInMinutes\":30,\"transactionsAllowed\":1,\"instancesAllowed\":5,\"autoRestoreAllowed\":false,\"restoreOnAction\":\"REGENERATE\"}}]}", + Map.class)).thenReturn(vidPolicyMap); + VidPolicy vidPolicy = new VidPolicy(); + vidPolicy.setAllowedInstances(1); + vidPolicy.setAutoRestoreAllowed(true); + vidPolicy.setRestoreOnAction("true"); + + when(mapper.convertValue("vidPolicy", VidPolicy.class)).thenReturn(vidPolicy); + when(env.getProperty(Mockito.anyString())).thenReturn("false"); + + String vid = "12345"; + VidGeneratorResponseDto vidGeneratorResponseDto = new VidGeneratorResponseDto(); + vidGeneratorResponseDto.setVidStatus("Active"); + vidGeneratorResponseDto.setVID(vid); + ResponseWrapper response = new ResponseWrapper<>(); + response.setResponsetime(DateUtils.getCurrentDateTimeString()); + response.setResponse(vidGeneratorResponseDto); + when(mapper.writeValueAsString(Mockito.any())).thenReturn("response"); + when(mapper.readValue("response", VidGeneratorResponseDto.class)).thenReturn(vidGeneratorResponseDto); + when(residentServiceRestClient.postApi(any(), any(), any(), any())).thenReturn(response); + NotificationResponseDTO notificationResponseDTO = new NotificationResponseDTO(); + notificationResponseDTO.setMaskedEmail("Ka**g.com"); + notificationResponseDTO.setMaskedPhone("88**09"); + notificationResponseDTO.setStatus("SUCCESS"); + notificationResponseDTO.setMessage("SUCCESS"); + when(notificationService.sendNotification(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())).thenReturn(notificationResponseDTO); + VidRequestDtoV2 vidRequestDtoV2 = new VidRequestDtoV2(); + vidRequestDtoV2.setVidType("PERPETUAL"); + vidRequestDtoV2.setChannels(List.of("EMAIL")); + vidRequestDtoV2.setTransactionID("3434232323"); + assertEquals("12345",residentVidService. + generateVid(vidRequestDtoV2, "123232323").getResponse().getVid()); + } + + @Test(expected = ResidentServiceCheckedException.class) + public void testRevokeVidV2Failed() throws OtpValidationFailedException, ResidentServiceCheckedException, ApisResourceAccessException { + IdentityServiceTest.getAuthUserDetailsFromAuthentication(); + Mockito.when(utility.createEntity(Mockito.any())).thenReturn(new ResidentTransactionEntity()); + Mockito.when(utility.createEventId()).thenReturn("1236547899874563"); + when(residentServiceRestClient.getApi(Mockito.anyString(), Mockito.any())).thenReturn(vidResponse); + VidRevokeRequestDTOV2 vidRevokeRequestDTOV2 = new VidRevokeRequestDTOV2(); + vidRevokeRequestDTOV2.setTransactionID("1234567896"); + vidRevokeRequestDTOV2.setVidStatus("Active"); + residentVidService.revokeVid(vidRevokeRequestDTOV2, "2076439409167031", "2037293183 "); + } + + @Test(expected = VidRevocationException.class) + public void testRevokeVidV2VidRevocationException() throws OtpValidationFailedException, ResidentServiceCheckedException, ApisResourceAccessException { + IdentityServiceTest.getAuthUserDetailsFromAuthentication(); + Mockito.when(utility.createEntity(Mockito.any())).thenReturn(new ResidentTransactionEntity()); + Mockito.when(utility.createEventId()).thenReturn("1236547899874563"); + Mockito.when(identityServiceImpl.getResidentIdaToken()).thenReturn("123456789"); + Mockito.when(identityServiceImpl.getIDATokenForIndividualId(Mockito.any())).thenReturn("123456789"); + when(residentServiceRestClient.getApi(Mockito.anyString(), Mockito.any())).thenReturn(vidResponse); + VidRevokeRequestDTOV2 vidRevokeRequestDTOV2 = new VidRevokeRequestDTOV2(); + vidRevokeRequestDTOV2.setTransactionID("1234567896"); + vidRevokeRequestDTOV2.setVidStatus("Active"); + residentVidService.revokeVid(vidRevokeRequestDTOV2, "2076439409167031", "2037293183 "); + } + + @Test + public void testRevokeVidV2Success() throws OtpValidationFailedException, ResidentServiceCheckedException, ApisResourceAccessException { + IdentityServiceTest.getAuthUserDetailsFromAuthentication(); + ResponseWrapper responseWrapper = new ResponseWrapper<>(); + VidGeneratorResponseDto dto = new VidGeneratorResponseDto(); + dto.setVidStatus("Deactive"); + responseWrapper.setResponse(dto); + responseWrapper.setVersion("v1"); + responseWrapper.setResponsetime(DateUtils.getCurrentDateTimeString()); + when(residentServiceRestClient.patchApi(any(), any(), any(), any())).thenReturn(responseWrapper); + Mockito.when(utility.createEntity(Mockito.any())).thenReturn(new ResidentTransactionEntity()); + Mockito.when(utility.createEventId()).thenReturn("1236547899874563"); + Mockito.when(identityServiceImpl.getResidentIdaToken()).thenReturn("123456789"); + Mockito.when(identityServiceImpl.getIDATokenForIndividualId(Mockito.any())).thenReturn("123456789"); + when(residentServiceRestClient.getApi(Mockito.anyString(), Mockito.any())).thenReturn(vidResponse); + VidRevokeRequestDTOV2 vidRevokeRequestDTOV2 = new VidRevokeRequestDTOV2(); + vidRevokeRequestDTOV2.setTransactionID("1234567896"); + vidRevokeRequestDTOV2.setVidStatus("Active"); + assertEquals("Vid successfully generated", + residentVidService.revokeVid(vidRevokeRequestDTOV2, "2076439409167031", "2037293183 ").getResponse().getMessage()); + } + + @Test + public void testGenerateVidV2NullNotificationResponse() throws OtpValidationFailedException, ResidentServiceCheckedException, ApisResourceAccessException, IOException { + IdentityServiceTest.getAuthUserDetailsFromAuthentication(); + Mockito.when(utility.createEntity(Mockito.any())).thenReturn(new ResidentTransactionEntity()); + Mockito.when(utility.createEventId()).thenReturn("1236547899874563"); + Mockito.when(identityServiceImpl.getIndividualIdType(Mockito.anyString())).thenReturn("VID"); + Mockito.when(identityServiceImpl.getUinForIndividualId(Mockito.anyString())).thenReturn("123"); + when(residentServiceRestClient.getApi(Mockito.anyString(), Mockito.any())).thenReturn(vidResponse); + String vidPolicyURL = "https://dev.mosip.net"; + ReflectionTestUtils.setField(residentVidService, "vidPolicyUrl", vidPolicyURL); + ObjectMapper objectMapper = new ObjectMapper(); + ObjectNode policy = objectMapper.readValue(this.getClass().getClassLoader().getResource("vid_policy.json"), + ObjectNode.class); + when(mapper.readValue(Mockito.any(URL.class), Mockito.any(Class.class))).thenReturn(policy); + Map vidPolicyMap = new HashMap<>(); + List> vidList = new ArrayList<>(); + Map vids= new HashMap<>(); + vids.put(TemplateVariablesConstants.VID_TYPE,ResidentConstants.PERPETUAL); + vids.put("vidPolicy", "vidPolicy"); + vidList.add(vids); + vidPolicyMap.put("vidPolicies",vidList); + when(mapper.readValue("{\"vidPolicies\":[{\"vidType\":\"Perpetual\",\"vidPolicy\":{\"validForInMinutes\":null,\"transactionsAllowed\":null,\"instancesAllowed\":1,\"autoRestoreAllowed\":true,\"restoreOnAction\":\"REVOKE\"}},{\"vidType\":\"Temporary\",\"vidPolicy\":{\"validForInMinutes\":30,\"transactionsAllowed\":1,\"instancesAllowed\":5,\"autoRestoreAllowed\":false,\"restoreOnAction\":\"REGENERATE\"}}]}", + Map.class)).thenReturn(vidPolicyMap); + VidPolicy vidPolicy = new VidPolicy(); + vidPolicy.setAllowedInstances(1); + vidPolicy.setAutoRestoreAllowed(true); + vidPolicy.setRestoreOnAction("true"); + + when(mapper.convertValue("vidPolicy", VidPolicy.class)).thenReturn(vidPolicy); + when(env.getProperty(Mockito.anyString())).thenReturn("false"); + + String vid = "12345"; + VidGeneratorResponseDto vidGeneratorResponseDto = new VidGeneratorResponseDto(); + vidGeneratorResponseDto.setVidStatus("Active"); + vidGeneratorResponseDto.setVID(vid); + ResponseWrapper response = new ResponseWrapper<>(); + response.setResponsetime(DateUtils.getCurrentDateTimeString()); + response.setResponse(vidGeneratorResponseDto); + when(mapper.writeValueAsString(Mockito.any())).thenReturn("response"); + when(mapper.readValue("response", VidGeneratorResponseDto.class)).thenReturn(vidGeneratorResponseDto); + when(residentServiceRestClient.postApi(any(), any(), any(), any())).thenReturn(response); + NotificationResponseDTO notificationResponseDTO = new NotificationResponseDTO(); + notificationResponseDTO.setMaskedEmail(null); + notificationResponseDTO.setMaskedPhone(null); + notificationResponseDTO.setStatus("SUCCESS"); + notificationResponseDTO.setMessage("SUCCESS"); + when(notificationService.sendNotification(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())).thenReturn(notificationResponseDTO); + VidRequestDtoV2 vidRequestDtoV2 = new VidRequestDtoV2(); + vidRequestDtoV2.setVidType("PERPETUAL"); + vidRequestDtoV2.setChannels(List.of("EMAIL")); + vidRequestDtoV2.setTransactionID("3434232323"); + assertEquals("12345",residentVidService. + generateVid(vidRequestDtoV2, "123232323").getResponse().getVid()); + } + + @Test(expected = VidCreationException.class) + public void testGenerateVidV2NullNotificationResponseApiResourceException() throws OtpValidationFailedException, ResidentServiceCheckedException, ApisResourceAccessException, IOException { + IdentityServiceTest.getAuthUserDetailsFromAuthentication(); + Mockito.when(utility.createEntity(Mockito.any())).thenReturn(new ResidentTransactionEntity()); + Mockito.when(utility.createEventId()).thenReturn("1236547899874563"); + Mockito.when(identityServiceImpl.getIndividualIdType(Mockito.anyString())).thenReturn("VID"); + Mockito.when(identityServiceImpl.getUinForIndividualId(Mockito.anyString())).thenReturn("123"); + when(residentServiceRestClient.getApi(Mockito.anyString(), Mockito.any())).thenReturn(vidResponse); + String vidPolicyURL = "https://dev.mosip.net"; + ReflectionTestUtils.setField(residentVidService, "vidPolicyUrl", vidPolicyURL); + ObjectMapper objectMapper = new ObjectMapper(); + ObjectNode policy = objectMapper.readValue(this.getClass().getClassLoader().getResource("vid_policy.json"), + ObjectNode.class); + when(mapper.readValue(Mockito.any(URL.class), Mockito.any(Class.class))).thenReturn(policy); + Map vidPolicyMap = new HashMap<>(); + List> vidList = new ArrayList<>(); + Map vids= new HashMap<>(); + vids.put(TemplateVariablesConstants.VID_TYPE,ResidentConstants.PERPETUAL); + vids.put("vidPolicy", "vidPolicy"); + vidList.add(vids); + vidPolicyMap.put("vidPolicies",vidList); + when(mapper.readValue("{\"vidPolicies\":[{\"vidType\":\"Perpetual\",\"vidPolicy\":{\"validForInMinutes\":null,\"transactionsAllowed\":null,\"instancesAllowed\":1,\"autoRestoreAllowed\":true,\"restoreOnAction\":\"REVOKE\"}},{\"vidType\":\"Temporary\",\"vidPolicy\":{\"validForInMinutes\":30,\"transactionsAllowed\":1,\"instancesAllowed\":5,\"autoRestoreAllowed\":false,\"restoreOnAction\":\"REGENERATE\"}}]}", + Map.class)).thenReturn(vidPolicyMap); + VidPolicy vidPolicy = new VidPolicy(); + vidPolicy.setAllowedInstances(1); + vidPolicy.setAutoRestoreAllowed(true); + vidPolicy.setRestoreOnAction("true"); + + when(mapper.convertValue("vidPolicy", VidPolicy.class)).thenReturn(vidPolicy); + when(env.getProperty(Mockito.anyString())).thenReturn("false"); + + String vid = "12345"; + VidGeneratorResponseDto vidGeneratorResponseDto = new VidGeneratorResponseDto(); + vidGeneratorResponseDto.setVidStatus("Active"); + vidGeneratorResponseDto.setVID(vid); + ResponseWrapper response = new ResponseWrapper<>(); + response.setResponsetime(DateUtils.getCurrentDateTimeString()); + response.setResponse(vidGeneratorResponseDto); + when(residentServiceRestClient.postApi(any(), any(), any(), any())).thenThrow(new ApisResourceAccessException()); + NotificationResponseDTO notificationResponseDTO = new NotificationResponseDTO(); + notificationResponseDTO.setMaskedEmail(null); + notificationResponseDTO.setMaskedPhone(null); + notificationResponseDTO.setStatus("SUCCESS"); + notificationResponseDTO.setMessage("SUCCESS"); + VidRequestDtoV2 vidRequestDtoV2 = new VidRequestDtoV2(); + vidRequestDtoV2.setVidType("PERPETUAL"); + vidRequestDtoV2.setChannels(List.of("EMAIL")); + vidRequestDtoV2.setTransactionID("3434232323"); + assertEquals("12345",residentVidService. + generateVid(vidRequestDtoV2, "123232323").getResponse().getVid()); } } diff --git a/resident/resident-service/src/test/java/io/mosip/resident/test/service/RidStatusServiceTest.java b/resident/resident-service/src/test/java/io/mosip/resident/service/impl/RidStatusServiceTest.java similarity index 98% rename from resident/resident-service/src/test/java/io/mosip/resident/test/service/RidStatusServiceTest.java rename to resident/resident-service/src/test/java/io/mosip/resident/service/impl/RidStatusServiceTest.java index b1382f33c8d..9a47ef9cb58 100644 --- a/resident/resident-service/src/test/java/io/mosip/resident/test/service/RidStatusServiceTest.java +++ b/resident/resident-service/src/test/java/io/mosip/resident/service/impl/RidStatusServiceTest.java @@ -1,4 +1,4 @@ -package io.mosip.resident.test.service; +package io.mosip.resident.service.impl; import static org.junit.Assert.assertEquals; import static org.mockito.ArgumentMatchers.any; @@ -29,7 +29,6 @@ import io.mosip.resident.exception.RIDInvalidException; import io.mosip.resident.exception.ResidentServiceException; import io.mosip.resident.service.NotificationService; -import io.mosip.resident.service.impl.ResidentServiceImpl; import io.mosip.resident.util.AuditUtil; import io.mosip.resident.util.ResidentServiceRestClient; diff --git a/resident/resident-service/src/test/java/io/mosip/resident/test/service/AcknowledgmentServiceTest.java b/resident/resident-service/src/test/java/io/mosip/resident/test/service/AcknowledgmentServiceTest.java deleted file mode 100644 index 1da772e60ad..00000000000 --- a/resident/resident-service/src/test/java/io/mosip/resident/test/service/AcknowledgmentServiceTest.java +++ /dev/null @@ -1,217 +0,0 @@ -package io.mosip.resident.test.service; - -import static org.junit.Assert.assertNotNull; -import static org.mockito.ArgumentMatchers.any; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.nio.charset.StandardCharsets; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Optional; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; -import org.springframework.cloud.context.config.annotation.RefreshScope; -import org.springframework.core.env.Environment; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.util.ReflectionTestUtils; - -import com.fasterxml.jackson.databind.ObjectMapper; - -import io.mosip.kernel.core.http.ResponseWrapper; -import io.mosip.kernel.core.pdfgenerator.spi.PDFGenerator; -import io.mosip.kernel.core.templatemanager.spi.TemplateManager; -import io.mosip.kernel.signature.dto.SignatureResponseDto; -import io.mosip.kernel.templatemanager.velocity.builder.TemplateManagerBuilderImpl; -import io.mosip.resident.constant.RequestType; -import io.mosip.resident.constant.ResidentConstants; -import io.mosip.resident.entity.ResidentTransactionEntity; -import io.mosip.resident.exception.ResidentServiceCheckedException; -import io.mosip.resident.repository.ResidentTransactionRepository; -import io.mosip.resident.service.AcknowledgementService; -import io.mosip.resident.service.impl.AcknowledgementServiceImpl; -import io.mosip.resident.service.impl.ProxyMasterdataServiceImpl; -import io.mosip.resident.util.ResidentServiceRestClient; -import io.mosip.resident.util.TemplateUtil; -import io.mosip.resident.util.Utility; -import reactor.util.function.Tuples; - -/** - * This class is used to create service class test for getting acknowledgement API. - * @Author Kamesh Shekhar Prasad - */ -@RunWith(MockitoJUnitRunner.class) -@RefreshScope -@ContextConfiguration -public class AcknowledgmentServiceTest { - - @InjectMocks - private AcknowledgementService acknowledgementService = new AcknowledgementServiceImpl(); - - @Mock - private ResidentTransactionRepository residentTransactionRepository; - - @Mock - private ProxyMasterdataServiceImpl proxyMasterdataServiceImpl; - - @Mock - private TemplateUtil templateUtil; - - @InjectMocks - private TemplateManagerBuilderImpl templateManagerBuilder; - - @Mock - private PDFGenerator pdfGenerator; - - @Mock - private Environment environment; - - @Mock - private ObjectMapper objectMapper; - - @Mock - private ResidentServiceRestClient residentServiceRestClient; - - @Mock - private Utility utility; - - private byte[] result; - private String eventId; - private String languageCode; - private Optional residentTransactionEntity; - private Map templateResponse; - private ResponseWrapper responseWrapper; - private Map templateVariables; - - @Mock - private TemplateManager templateManager; - private static final String CLASSPATH = "classpath"; - private static final String ENCODE_TYPE = "UTF-8"; - private Map values; - - @Before - public void setup() throws Exception { - templateResponse = new LinkedHashMap<>(); - templateVariables = new LinkedHashMap<>(); - values = new LinkedHashMap<>(); - values.put("test", String.class); - templateVariables.put("eventId", eventId); - responseWrapper = new ResponseWrapper<>(); - templateResponse.put(ResidentConstants.FILE_TEXT, "test"); - responseWrapper.setResponse(templateResponse); - result = "test".getBytes(StandardCharsets.UTF_8); - eventId = "bf42d76e-b02e-48c8-a17a-6bb842d85ea9"; - languageCode = "eng"; - residentTransactionEntity = Optional.of(new ResidentTransactionEntity()); - residentTransactionEntity.get().setEventId(eventId); - residentTransactionEntity.get().setRequestTypeCode(RequestType.SHARE_CRED_WITH_PARTNER.toString()); - Mockito.when(residentTransactionRepository.findById(Mockito.anyString())).thenReturn(residentTransactionEntity); - Mockito.when(proxyMasterdataServiceImpl.getAllTemplateBylangCodeAndTemplateTypeCode(Mockito.anyString(), Mockito.anyString())).thenReturn(responseWrapper); - Mockito.when(RequestType.SHARE_CRED_WITH_PARTNER.getAckTemplateVariables(templateUtil, eventId, languageCode, 0)). - thenReturn(Tuples.of(templateVariables, "acknowledgement-order-a-physical-card")); - ReflectionTestUtils.setField(acknowledgementService, "templateManagerBuilder", templateManagerBuilder); - templateManagerBuilder.encodingType(ENCODE_TYPE).enableCache(false).resourceLoader(CLASSPATH).build(); - InputStream stream = new ByteArrayInputStream("test".getBytes(StandardCharsets.UTF_8)); - Mockito.when(templateManager.merge(any(), Mockito.anyMap())).thenReturn(stream); - OutputStream outputStream = new ByteArrayOutputStream(1024); - outputStream.write("test".getBytes(StandardCharsets.UTF_8)); - SignatureResponseDto signatureResponseDto = new SignatureResponseDto(); - signatureResponseDto.setData("data"); - ResponseWrapper responseWrapper = new ResponseWrapper<>(); - responseWrapper.setResponse(signatureResponseDto); - Mockito.when(utility.signPdf(Mockito.any(), Mockito.any())).thenReturn("data".getBytes()); - } - - @Test - public void testAcknowledgementServiceTest() throws ResidentServiceCheckedException, IOException { - byte[] actualResult = acknowledgementService.getAcknowledgementPDF(eventId, languageCode, 0); - assertNotNull(actualResult); - } - - @Test - public void testAcknowledgementServiceRequestTypeGenerateVidTest() throws ResidentServiceCheckedException, IOException { - Mockito.when(RequestType.GENERATE_VID.getAckTemplateVariables(templateUtil, eventId, languageCode, 0)). - thenReturn(Tuples.of(templateVariables, "acknowledgement-order-a-physical-card")); - residentTransactionEntity.get().setRequestTypeCode(RequestType.GENERATE_VID.toString()); - Mockito.when(residentTransactionRepository.findById(Mockito.anyString())).thenReturn(residentTransactionEntity); - byte[] actualResult = acknowledgementService.getAcknowledgementPDF(eventId, languageCode, 0); - assertNotNull(actualResult); - } - - @Test - public void testAcknowledgementServiceRequestTypeRevokeVidTest() throws ResidentServiceCheckedException, IOException { - Mockito.when(RequestType.REVOKE_VID.getAckTemplateVariables(templateUtil, eventId, languageCode, 0)). - thenReturn(Tuples.of(templateVariables, "acknowledgement-order-a-physical-card")); - residentTransactionEntity.get().setRequestTypeCode(RequestType.REVOKE_VID.toString()); - Mockito.when(residentTransactionRepository.findById(Mockito.anyString())).thenReturn(residentTransactionEntity); - byte[] actualResult = acknowledgementService.getAcknowledgementPDF(eventId, languageCode, 0); - assertNotNull(actualResult); - } - - @Test - public void testAcknowledgementServiceRequestTypeOrderPhysicalCardTest() throws ResidentServiceCheckedException, IOException { - Mockito.when(RequestType.ORDER_PHYSICAL_CARD.getAckTemplateVariables(templateUtil, eventId, languageCode, 0)). - thenReturn(Tuples.of(templateVariables, "acknowledgement-order-a-physical-card")); - residentTransactionEntity.get().setRequestTypeCode(RequestType.ORDER_PHYSICAL_CARD.toString()); - Mockito.when(residentTransactionRepository.findById(Mockito.anyString())).thenReturn(residentTransactionEntity); - byte[] actualResult = acknowledgementService.getAcknowledgementPDF(eventId, languageCode, 0); - assertNotNull(actualResult); - } - - @Test - public void testAcknowledgementServiceRequestTypeDownloadPersonalizedCardTest() throws ResidentServiceCheckedException, IOException { - Mockito.when(RequestType.DOWNLOAD_PERSONALIZED_CARD.getAckTemplateVariables(templateUtil, eventId, languageCode, 0)). - thenReturn(Tuples.of(templateVariables, "acknowledgement-order-a-physical-card")); - residentTransactionEntity.get().setRequestTypeCode(RequestType.DOWNLOAD_PERSONALIZED_CARD.toString()); - Mockito.when(residentTransactionRepository.findById(Mockito.anyString())).thenReturn(residentTransactionEntity); - byte[] actualResult = acknowledgementService.getAcknowledgementPDF(eventId, languageCode, 0); - assertNotNull(actualResult); - } - - @Test - public void testAcknowledgementServiceRequestTypeUpdateMyUinTest() throws ResidentServiceCheckedException, IOException { - Mockito.when(RequestType.UPDATE_MY_UIN.getAckTemplateVariables(templateUtil, eventId, languageCode, 0)). - thenReturn(Tuples.of(templateVariables, "acknowledgement-order-a-physical-card")); - residentTransactionEntity.get().setRequestTypeCode(RequestType.UPDATE_MY_UIN.toString()); - Mockito.when(residentTransactionRepository.findById(Mockito.anyString())).thenReturn(residentTransactionEntity); - byte[] actualResult = acknowledgementService.getAcknowledgementPDF(eventId, languageCode, 0); - assertNotNull(actualResult); - } - - @Test - public void testAcknowledgementServiceRequestTypeSecureMyIdTest() throws ResidentServiceCheckedException, IOException { - Mockito.when(RequestType.AUTH_TYPE_LOCK_UNLOCK.getAckTemplateVariables(templateUtil, eventId, languageCode, 0)). - thenReturn(Tuples.of(templateVariables, "acknowledgement-order-a-physical-card")); - residentTransactionEntity.get().setRequestTypeCode(RequestType.AUTH_TYPE_LOCK_UNLOCK.toString()); - Mockito.when(residentTransactionRepository.findById(Mockito.anyString())).thenReturn(residentTransactionEntity); - byte[] actualResult = acknowledgementService.getAcknowledgementPDF(eventId, languageCode, 0); - assertNotNull(actualResult); - } - - @Test(expected = ResidentServiceCheckedException.class) - public void testAcknowledgmentBadEventIdTest() throws ResidentServiceCheckedException, IOException { - residentTransactionEntity = Optional.empty(); - Mockito.when(residentTransactionRepository.findById(Mockito.anyString())).thenReturn(residentTransactionEntity); - byte[] actualResult = acknowledgementService.getAcknowledgementPDF(eventId, languageCode, 0); - assertNotNull(actualResult); - } - - @Test(expected = ResidentServiceCheckedException.class) - public void testAcknowledgmentBadRequestTypeTest() throws ResidentServiceCheckedException, IOException { - Mockito.when(RequestType.GET_MY_ID.getAckTemplateVariables(templateUtil, eventId, languageCode, 0)). - thenReturn(Tuples.of(templateVariables, "acknowledgement-order-a-physical-card")); - residentTransactionEntity.get().setRequestTypeCode(RequestType.GET_MY_ID.toString()); - Mockito.when(residentTransactionRepository.findById(Mockito.anyString())).thenReturn(Optional.empty()); - byte[] actualResult = acknowledgementService.getAcknowledgementPDF(eventId, languageCode, 0); - assertNotNull(actualResult); - } -} \ No newline at end of file diff --git a/resident/resident-service/src/test/java/io/mosip/resident/test/service/AuthTransactionCallbackServiceTest.java b/resident/resident-service/src/test/java/io/mosip/resident/test/service/AuthTransactionCallbackServiceTest.java deleted file mode 100644 index f49b7e2836a..00000000000 --- a/resident/resident-service/src/test/java/io/mosip/resident/test/service/AuthTransactionCallbackServiceTest.java +++ /dev/null @@ -1,113 +0,0 @@ -package io.mosip.resident.test.service; - -import static org.powermock.api.mockito.PowerMockito.mock; - -import java.security.NoSuchAlgorithmException; -import java.time.LocalDateTime; -import java.util.Map; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; -import org.mockito.junit.MockitoJUnitRunner; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.cloud.context.config.annotation.RefreshScope; -import org.springframework.core.env.Environment; -import org.springframework.http.HttpHeaders; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.setup.MockMvcBuilders; - -import io.mosip.kernel.core.websub.model.Event; -import io.mosip.kernel.core.websub.model.EventModel; -import io.mosip.kernel.core.websub.spi.PublisherClient; -import io.mosip.kernel.core.websub.spi.SubscriptionClient; -import io.mosip.kernel.websub.api.model.SubscriptionChangeRequest; -import io.mosip.kernel.websub.api.model.SubscriptionChangeResponse; -import io.mosip.kernel.websub.api.model.UnsubscriptionRequest; -import io.mosip.resident.entity.ResidentTransactionEntity; -import io.mosip.resident.exception.ApisResourceAccessException; -import io.mosip.resident.exception.ResidentServiceCheckedException; -import io.mosip.resident.repository.ResidentTransactionRepository; -import io.mosip.resident.service.impl.AuthTransactionCallBackServiceImpl; -import io.mosip.resident.service.impl.IdentityServiceImpl; -import io.mosip.resident.util.AuditUtil; -import io.mosip.resident.util.ResidentServiceRestClient; -import io.mosip.resident.util.Utility; - -@RunWith(MockitoJUnitRunner.class) -@RefreshScope -@ContextConfiguration -public class AuthTransactionCallbackServiceTest { - - @Mock - private ResidentServiceRestClient residentServiceRestClient; - - @Mock - Environment env; - - @Mock - private AuditUtil audit; - - @InjectMocks - private AuthTransactionCallBackServiceImpl authTransactionCallBackService; - - @Mock - private IdentityServiceImpl identityServiceImpl; - - @Mock - private Utility utility; - - @Mock - private ResidentTransactionRepository residentTransactionRepository; - - @Autowired - private MockMvc mockMvc; - - @Mock - private PublisherClient publisher; - - @Mock - SubscriptionClient subscribe; - - EventModel eventModel; - - @Before - public void setup() throws ApisResourceAccessException { - MockitoAnnotations.initMocks(this); - this.mockMvc = MockMvcBuilders.standaloneSetup(authTransactionCallBackService).build(); - eventModel=new EventModel(); - Event event=new Event(); - event.setTransactionId("1234"); - event.setTimestamp(LocalDateTime.now().toString()); - event.setId("12345"); - Map partnerIdMap = new java.util.HashMap<>(); - partnerIdMap.put("olv_partner_id", "mpartner-default-auth"); - event.setData(partnerIdMap); - - eventModel.setEvent(event); - eventModel.setTopic("AUTH_TYPE_STATUS_UPDATE_ACK"); - eventModel.setPublishedOn(String.valueOf(LocalDateTime.now())); - eventModel.setPublisher("AUTH_TYPE_STATUS_UPDATE_ACK"); - Mockito.lenient().when(utility.createEntity()).thenReturn(new ResidentTransactionEntity()); - } - - @Test - public void testAuthTransactionCallBackService() throws ResidentServiceCheckedException, ApisResourceAccessException, NoSuchAlgorithmException { - authTransactionCallBackService.updateAuthTransactionCallBackService(eventModel); - authTransactionCallBackService = mock(AuthTransactionCallBackServiceImpl.class); - Mockito.lenient().doNothing().when(authTransactionCallBackService).updateAuthTransactionCallBackService(Mockito.any()); - } - - @Test - public void testAuthTransactionCallBackServiceException() throws ResidentServiceCheckedException, ApisResourceAccessException, NoSuchAlgorithmException { - authTransactionCallBackService.updateAuthTransactionCallBackService(eventModel); - authTransactionCallBackService = mock(AuthTransactionCallBackServiceImpl.class); - Mockito.lenient().doThrow(ResidentServiceCheckedException.class).when(authTransactionCallBackService).updateAuthTransactionCallBackService(Mockito.any()); - } - -} diff --git a/resident/resident-service/src/test/java/io/mosip/resident/test/service/BaseWebSubInitializerTest.java b/resident/resident-service/src/test/java/io/mosip/resident/test/service/BaseWebSubInitializerTest.java deleted file mode 100644 index 480bb45397b..00000000000 --- a/resident/resident-service/src/test/java/io/mosip/resident/test/service/BaseWebSubInitializerTest.java +++ /dev/null @@ -1,160 +0,0 @@ -package io.mosip.resident.test.service; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.context.event.ApplicationReadyEvent; -import org.springframework.http.HttpHeaders; -import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.util.ReflectionTestUtils; - -import io.mosip.kernel.core.websub.spi.PublisherClient; -import io.mosip.kernel.core.websub.spi.SubscriptionClient; -import io.mosip.kernel.websub.api.model.SubscriptionChangeRequest; -import io.mosip.kernel.websub.api.model.SubscriptionChangeResponse; -import io.mosip.kernel.websub.api.model.UnsubscriptionRequest; -import io.mosip.resident.service.impl.BaseWebSubInitializer; - -@RunWith(MockitoJUnitRunner.class) -@ContextConfiguration -public class BaseWebSubInitializerTest { - - @Mock - private PublisherClient publisher; - - @Mock - SubscriptionClient subscribe; - - @Mock - ThreadPoolTaskScheduler taskScheduler; - - @Mock - BaseWebSubInitializer baseWebSubInitializer; - - public ThreadPoolTaskScheduler threadPoolTaskScheduler() { - ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler(); - threadPoolTaskScheduler.setPoolSize(5); - threadPoolTaskScheduler.setThreadNamePrefix("ThreadPoolTaskScheduler"); - return threadPoolTaskScheduler; - } - - @Value("${resident.websub.callback.authtype-status.url}") - private String callbackUrl; - - @Value("${resident.websub.callback.authTransaction-status.url}") - private String callbackAuthTransactionUrl; - - @Value("${resident.websub.authTransaction-status.topic}") - private String authTransactionTopic; - - @Value("${resident.websub.authTransaction-status.secret}") - private String authTransactionSecret; - - @Before - public void setUp() throws Exception { - ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler(); - taskScheduler.setPoolSize(5); - taskScheduler.setThreadNamePrefix("ThreadPoolTaskScheduler"); - ReflectionTestUtils.setField(baseWebSubInitializer, "authTransactionSecret", "authTransactionSecret"); - ReflectionTestUtils.setField(baseWebSubInitializer, "authTransactionTopic", - "AUTHENTICATION_TRANSACTION_STATUS"); - ReflectionTestUtils.setField(baseWebSubInitializer, "callbackAuthTransactionUrl", - "resident.websub.callback.authTransaction-status.relative.url"); - ReflectionTestUtils.setField(baseWebSubInitializer, "hubUrl", "https://dev2.mosip.net/lib"); - } - - @After - public void tearDown() throws Exception { - - } - - @Test - public void testApplicationEvent() { - BaseWebSubInitializer baseWebSubInitializer = new BaseWebSubInitializer(); - ReflectionTestUtils.setField(baseWebSubInitializer, "taskScheduler", - Mockito.mock(ThreadPoolTaskScheduler.class)); - ApplicationReadyEvent applicationReadyEvent = null; - baseWebSubInitializer.onApplicationEvent(applicationReadyEvent); - } - - @Test - public void applicationEventTest() { - BaseWebSubInitializer baseWebSubInitializer = new BaseWebSubInitializer(); - ReflectionTestUtils.setField(baseWebSubInitializer, "taskScheduler", - Mockito.mock(ThreadPoolTaskScheduler.class)); - ApplicationReadyEvent applicationReadyEvent = null; - ReflectionTestUtils.setField(baseWebSubInitializer, "topic", "AUTH_TYPE_STATUS_UPDATE_ACK"); - ReflectionTestUtils.setField(baseWebSubInitializer, "authTransactionTopic", - "AUTHENTICATION_TRANSACTION_STATUS"); - baseWebSubInitializer.onApplicationEvent(applicationReadyEvent); - } - - @Test(expected = Exception.class) - public void authTransactionSubscriptionTest() { - BaseWebSubInitializer baseWebSubInitializer = new BaseWebSubInitializer(); - ReflectionTestUtils.setField(baseWebSubInitializer, "authTransactionSecret", "authTransactionSecret"); - ReflectionTestUtils.setField(baseWebSubInitializer, "authTransactionTopic", - "AUTHENTICATION_TRANSACTION_STATUS"); - ReflectionTestUtils.setField(baseWebSubInitializer, "callbackAuthTransactionUrl", - "resident.websub.callback.authTransaction-status.relative.url"); - ReflectionTestUtils.setField(baseWebSubInitializer, "hubUrl", "https://dev2.mosip.net/lib"); - baseWebSubInitializer.authTransactionSubscription(); - } - - @Test - public void testAuthTransactionSubcription() { - BaseWebSubInitializer baseWebSubInitializer = new BaseWebSubInitializer(); - ReflectionTestUtils.setField(baseWebSubInitializer, "authTransactionSecret", "authTransactionSecret"); - ReflectionTestUtils.setField(baseWebSubInitializer, "authTransactionTopic", - "AUTHENTICATION_TRANSACTION_STATUS"); - ReflectionTestUtils.setField(baseWebSubInitializer, "callbackAuthTransactionUrl", - "resident.websub.callback.authTransaction-status.relative.url"); - ReflectionTestUtils.setField(baseWebSubInitializer, "hubUrl", "https://dev2.mosip.net/lib"); - ReflectionTestUtils.setField(baseWebSubInitializer, "subscribe", subscribe); - baseWebSubInitializer.authTransactionSubscription(); - } - - @Test - public void testTryRegisterTopicEventFailed() { - BaseWebSubInitializer baseWebSubInitializer = new BaseWebSubInitializer(); - ReflectionTestUtils.setField(baseWebSubInitializer, "taskScheduler", - Mockito.mock(ThreadPoolTaskScheduler.class)); - ReflectionTestUtils.invokeMethod(baseWebSubInitializer, "tryRegisterTopicEvent", "AUTH_TYPE_STATUS_UPDATE_ACK"); - } - - @Test - public void testTryRegisterTopicEvent() { - BaseWebSubInitializer baseWebSubInitializer = new BaseWebSubInitializer(); - ReflectionTestUtils.setField(baseWebSubInitializer, "publishUrl", "https://dev2.mosip.net/lib"); - ReflectionTestUtils.setField(baseWebSubInitializer, "publisher", publisher); - ReflectionTestUtils.invokeMethod(baseWebSubInitializer, "tryRegisterTopicEvent", "AUTH_TYPE_STATUS_UPDATE_ACK"); - } - - @Test - public void testInitSubsription() { - BaseWebSubInitializer baseWebSubInitializer = new BaseWebSubInitializer(); - ReflectionTestUtils.setField(baseWebSubInitializer, "authTransactionSecret", "authTransactionSecret"); - ReflectionTestUtils.setField(baseWebSubInitializer, "authTransactionTopic", - "AUTHENTICATION_TRANSACTION_STATUS"); - ReflectionTestUtils.setField(baseWebSubInitializer, "callbackAuthTransactionUrl", - "resident.websub.callback.authTransaction-status.relative.url"); - ReflectionTestUtils.setField(baseWebSubInitializer, "subscribe", subscribe); - ReflectionTestUtils.setField(baseWebSubInitializer, "hubUrl", "https://dev2.mosip.net/lib"); - ReflectionTestUtils.invokeMethod(baseWebSubInitializer, "initSubsriptions"); - } - - private BaseWebSubInitializer testTaskScheduler() { - BaseWebSubInitializer baseWebSubInitializer = new BaseWebSubInitializer() { - }; - ReflectionTestUtils.setField(baseWebSubInitializer, "taskScheduler", - Mockito.mock(ThreadPoolTaskScheduler.class)); - return baseWebSubInitializer; - } - -} \ No newline at end of file diff --git a/resident/resident-service/src/test/java/io/mosip/resident/test/service/DownloadCardServiceTest.java b/resident/resident-service/src/test/java/io/mosip/resident/test/service/DownloadCardServiceTest.java deleted file mode 100644 index 50fd9c0c3e8..00000000000 --- a/resident/resident-service/src/test/java/io/mosip/resident/test/service/DownloadCardServiceTest.java +++ /dev/null @@ -1,367 +0,0 @@ -package io.mosip.resident.test.service; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.isNull; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; -import org.springframework.cloud.context.config.annotation.RefreshScope; -import org.springframework.core.env.Environment; -import org.springframework.test.context.ContextConfiguration; - -import io.mosip.kernel.core.exception.BaseCheckedException; -import io.mosip.kernel.core.exception.ServiceError; -import io.mosip.resident.constant.PacketStatus; -import io.mosip.resident.constant.ResidentConstants; -import io.mosip.resident.constant.ResidentErrorCode; -import io.mosip.resident.constant.TransactionStage; -import io.mosip.resident.dto.CheckStatusResponseDTO; -import io.mosip.resident.dto.DigitalCardStatusResponseDto; -import io.mosip.resident.dto.DownloadCardRequestDTO; -import io.mosip.resident.dto.DownloadPersonalizedCardDto; -import io.mosip.resident.dto.MainRequestDTO; -import io.mosip.resident.dto.ResidentCredentialResponseDto; -import io.mosip.resident.dto.ResponseWrapper; -import io.mosip.resident.dto.VidDownloadCardResponseDto; -import io.mosip.resident.entity.ResidentTransactionEntity; -import io.mosip.resident.exception.ApisResourceAccessException; -import io.mosip.resident.exception.OtpValidationFailedException; -import io.mosip.resident.exception.ResidentServiceCheckedException; -import io.mosip.resident.exception.ResidentServiceException; -import io.mosip.resident.repository.ResidentTransactionRepository; -import io.mosip.resident.service.DownloadCardService; -import io.mosip.resident.service.IdAuthService; -import io.mosip.resident.service.NotificationService; -import io.mosip.resident.service.ResidentCredentialService; -import io.mosip.resident.service.ResidentVidService; -import io.mosip.resident.service.impl.DownloadCardServiceImpl; -import io.mosip.resident.service.impl.IdentityServiceImpl; -import io.mosip.resident.util.AuditUtil; -import io.mosip.resident.util.ResidentServiceRestClient; -import io.mosip.resident.util.Utilities; -import io.mosip.resident.util.Utility; -import reactor.util.function.Tuple2; - -/** - * This class is used to create service class test for getting acknowledgement API. - * @Author Kamesh Shekhar Prasad - */ -@RunWith(MockitoJUnitRunner.class) -@RefreshScope -@ContextConfiguration -public class DownloadCardServiceTest { - - @InjectMocks - private DownloadCardService downloadCardService = new DownloadCardServiceImpl(); - - @Mock - private IdAuthService idAuthService; - - @Mock - private Utilities utilities; - - @Mock - private Environment environment; - - @Mock - private ResidentServiceRestClient residentServiceRestClient; - - @Mock - private AuditUtil auditUtil; - - @Mock - private ResidentCredentialService residentCredentialService; - - @Mock - private IdentityServiceImpl identityService; - - @Mock - private NotificationService notificationService; - - @Mock - private Utility utility; - - @Mock - private ResidentTransactionRepository residentTransactionRepository; - - @Mock - private ResidentVidService vidService; - - private MainRequestDTO downloadCardRequestDTOMainRequestDTO; - - private String result; - - byte[] pdfbytes; - - DigitalCardStatusResponseDto digitalCardStatusResponseDto; - - private MainRequestDTO downloadPersonalizedCardMainRequestDTO; - - private Map identityMap; - - @Before - public void setup() throws Exception { - downloadCardRequestDTOMainRequestDTO = new MainRequestDTO<>(); - DownloadCardRequestDTO downloadCardRequestDTO = new DownloadCardRequestDTO(); - downloadCardRequestDTO.setTransactionId("1234567890"); - downloadCardRequestDTO.setOtp("111111"); - downloadCardRequestDTO.setIndividualId("7841261580"); - downloadCardRequestDTOMainRequestDTO.setRequest(downloadCardRequestDTO); - result = "result"; - pdfbytes = result.getBytes(); - Mockito.when(utility.signPdf(Mockito.any(), Mockito.any())).thenReturn(pdfbytes); - Mockito.when(idAuthService.validateOtpv2(Mockito.anyString(), Mockito.anyString(), Mockito.anyString())).thenReturn(true); - Mockito.when(utilities.getRidByIndividualId(Mockito.anyString())).thenReturn("1234567890"); - Mockito.when(residentCredentialService.getCard(Mockito.anyString(), isNull(), isNull())).thenReturn(pdfbytes); - Mockito.when(identityService.getIndividualIdType(Mockito.anyString())).thenReturn("UIN"); - Mockito.when(identityService.getIndividualIdForAid(Mockito.anyString())).thenReturn("7841261580"); - Mockito.when(utility.createEntity()).thenReturn(new ResidentTransactionEntity()); - Mockito.when(utility.createEventId()).thenReturn("12345"); - - ResidentTransactionEntity residentTransactionEntity = new ResidentTransactionEntity(); - residentTransactionEntity.setEventId("12345"); - downloadPersonalizedCardMainRequestDTO= - new MainRequestDTO<>(); - DownloadPersonalizedCardDto downloadPersonalizedCardDto = new DownloadPersonalizedCardDto(); - downloadPersonalizedCardDto.setHtml("PGh0bWw+PGhlYWQ+PC9oZWFkPjxib2R5Pjx0YWJsZT48dHI+PHRkPk5hbWU8L3RkPjx0ZD5GUjwvdGQ+PC90cj48dHI+PHRkPkRPQjwvdGQ+PHRkPjE5OTIvMDQvMTU8L3RkPjwvdHI+PHRyPjx0ZD5QaG9uZSBOdW1iZXI8L3RkPjx0ZD45ODc2NTQzMjEwPC90ZD48L3RyPjwvdGFibGU+PC9ib2R5PjwvaHRtbD4="); - downloadPersonalizedCardMainRequestDTO.setRequest(downloadPersonalizedCardDto); - Mockito.when(environment.getProperty(ResidentConstants.IS_PASSWORD_FLAG_ENABLED)).thenReturn(String.valueOf(false)); - Mockito.when(environment.getProperty(ResidentConstants.PASSWORD_ATTRIBUTE)).thenReturn("dateOfBirth"); - Mockito.when(environment.getProperty(ResidentConstants.MOSIP_CREDENTIAL_TYPE_PROPERTY)).thenReturn("credentialType"); - Mockito.when(environment.getProperty(ResidentConstants.CREDENTIAL_ISSUER)).thenReturn("credentialType"); - Mockito.when(environment.getProperty(ResidentConstants.CREDENTIAL_ENCRYPTION_FLAG)).thenReturn("true"); - Mockito.when(environment.getProperty(ResidentConstants.CREDENTIAL_ENCRYPTION_KEY)).thenReturn("true"); - Mockito.when(identityService.getResidentIndvidualIdFromSession()).thenReturn("1234567890"); - Mockito.when(identityService.getUinForIndividualId(Mockito.anyString())).thenReturn("3425636374"); - Mockito.when(utilities.getUinByVid(Mockito.anyString())).thenReturn("3425636374"); - identityMap = new LinkedHashMap(); - identityMap.put("UIN", "8251649601"); - identityMap.put("email", "manojvsp12@gmail.com"); - identityMap.put("phone", "9395910872"); - identityMap.put("dateOfBirth", "1970"); - } - - @Test - public void testDownloadCardServiceTest() { - Tuple2 actualResult = downloadCardService.getDownloadCardPDF(downloadCardRequestDTOMainRequestDTO); - assertEquals(pdfbytes, actualResult.getT1()); - } - - @Test - public void testGetDownloadCardPdfVID(){ - Mockito.when(identityService.getIndividualIdType(Mockito.anyString())).thenReturn("VID"); - Tuple2 actualResult = downloadCardService.getDownloadCardPDF(downloadCardRequestDTOMainRequestDTO); - assertNotNull(actualResult); - } - - @Test - public void testGetDownloadCardPdfAID() throws ApisResourceAccessException, IOException { - String rid = "7841261580"; - HashMap hashMap = new HashMap<>(); - hashMap.put(ResidentConstants.AID_STATUS, "SUCCESS"); - hashMap.put(ResidentConstants.TRANSACTION_TYPE_CODE, TransactionStage.CARD_READY_TO_DOWNLOAD.getName()); - Mockito.when(utilities.getPacketStatus(rid)).thenReturn(hashMap); - Mockito.when(identityService.getIndividualIdType(Mockito.anyString())).thenReturn("AID"); - Tuple2 actualResult = downloadCardService.getDownloadCardPDF(downloadCardRequestDTOMainRequestDTO); - assertNotNull(actualResult.getT1()); - } - - @Test(expected = ResidentServiceException.class) - public void testGetDownloadCardPdfResidentServiceExceptionTest() throws ResidentServiceCheckedException, ApisResourceAccessException { - Mockito.when(identityService.getIndividualIdForAid(Mockito.anyString())).thenThrow( - new ResidentServiceCheckedException()); - Mockito.when(identityService.getIndividualIdType(Mockito.anyString())).thenReturn("AID"); - Tuple2 actualResult = downloadCardService.getDownloadCardPDF(downloadCardRequestDTOMainRequestDTO); - assertEquals(pdfbytes, actualResult.getT1()); - } - - @Test(expected = ResidentServiceException.class) - public void testGetDownloadCardPdfApisResourceAccessExceptionTest() throws ResidentServiceCheckedException, ApisResourceAccessException { - Mockito.when(identityService.getIndividualIdForAid(Mockito.anyString())).thenThrow( - new ApisResourceAccessException()); - Mockito.when(identityService.getIndividualIdType(Mockito.anyString())).thenReturn("AID"); - Tuple2 actualResult = downloadCardService.getDownloadCardPDF(downloadCardRequestDTOMainRequestDTO); - assertEquals(pdfbytes, actualResult.getT1()); - } - - @Test(expected = ResidentServiceException.class) - public void testGetDownloadCardPdfOtpValidationFailedTest() throws ResidentServiceCheckedException, ApisResourceAccessException, OtpValidationFailedException { - Mockito.when(idAuthService.validateOtpv2(Mockito.anyString(), Mockito.anyString(), Mockito.anyString())).thenReturn(false); - Tuple2 actualResult = downloadCardService.getDownloadCardPDF(downloadCardRequestDTOMainRequestDTO); - assertEquals(pdfbytes, actualResult.getT1()); - } - - @Test(expected = ResidentServiceException.class) - public void testGetDownloadCardPdfApiResourceException() throws OtpValidationFailedException, ApisResourceAccessException, ResidentServiceCheckedException { - Mockito.when(idAuthService.validateOtpv2(Mockito.anyString(), Mockito.anyString(), Mockito.anyString())).thenReturn(true); - Mockito.when(utilities.getRidByIndividualId(Mockito.anyString())).thenThrow(new ApisResourceAccessException()); - Tuple2 actualResult = downloadCardService.getDownloadCardPDF(downloadCardRequestDTOMainRequestDTO); - assertEquals(pdfbytes, actualResult.getT1()); - } - - @Test(expected = ResidentServiceException.class) - public void testGetDownloadCardPdfOtpValidationException() throws OtpValidationFailedException, ApisResourceAccessException, ResidentServiceCheckedException { - Mockito.when(idAuthService.validateOtpv2(Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenThrow(new OtpValidationFailedException()); - Tuple2 actualResult = downloadCardService.getDownloadCardPDF(downloadCardRequestDTOMainRequestDTO); - assertEquals(pdfbytes, actualResult.getT1()); - } - - @Test - public void testDownloadPersonalizedCardSuccess() { - Tuple2 actualResult = downloadCardService.downloadPersonalizedCard(downloadPersonalizedCardMainRequestDTO, 0); - assertEquals(pdfbytes, actualResult.getT1()); - } - - @Test - public void testDownloadPersonalizedCardSuccessWithListAttributes() throws ResidentServiceCheckedException, IOException { - Mockito.when(environment.getProperty(ResidentConstants.PASSWORD_ATTRIBUTE)).thenReturn("firstName"); - Map name = new HashMap<>(); - name.put("language", "eng"); - name.put("value", "kamesh"); - identityMap.put("firstName", List.of(name)); - Tuple2 actualResult = downloadCardService.downloadPersonalizedCard(downloadPersonalizedCardMainRequestDTO, 0); - assertEquals(pdfbytes, actualResult.getT1()); - } - - @Test - public void testDownloadPersonalizedCardPassword(){ - Mockito.when(environment.getProperty(ResidentConstants.IS_PASSWORD_FLAG_ENABLED)).thenReturn(String.valueOf(true)); - Tuple2 actualResult = downloadCardService.downloadPersonalizedCard(downloadPersonalizedCardMainRequestDTO, 0); - assertEquals(pdfbytes, actualResult.getT1()); - } - - @Test(expected = ResidentServiceException.class) - public void testDownloadPersonalizedCardPasswordFailed(){ - Mockito.when(environment.getProperty(ResidentConstants.IS_PASSWORD_FLAG_ENABLED)).thenReturn(String.valueOf(true)); - Mockito.when(utility.getPassword(Mockito.anyList())).thenThrow( - new ResidentServiceException(ResidentErrorCode.DOWNLOAD_PERSONALIZED_CARD)); - Tuple2 actualResult = downloadCardService.downloadPersonalizedCard(downloadPersonalizedCardMainRequestDTO, 0); - assertEquals(pdfbytes, actualResult.getT1()); - } - - @Test(expected = ResidentServiceException.class) - public void testDownloadPersonalizedCardResidentServiceCheckedException() throws ResidentServiceCheckedException, IOException { - Mockito.when(identityService.getIdentityAttributes(Mockito.anyString(), Mockito.isNull())).thenThrow( - new ResidentServiceCheckedException()); - Tuple2 actualResult = downloadCardService.downloadPersonalizedCard(downloadPersonalizedCardMainRequestDTO, 0); - assertEquals(pdfbytes, actualResult.getT1()); - } - - @Test(expected = ResidentServiceException.class) - public void testDownloadPersonalizedCardIOException() throws ResidentServiceCheckedException, IOException { - Mockito.when(identityService.getIdentityAttributes(Mockito.anyString(), Mockito.isNull())).thenThrow( - new IOException()); - Tuple2 actualResult = downloadCardService.downloadPersonalizedCard(downloadPersonalizedCardMainRequestDTO, 0); - assertEquals(pdfbytes, actualResult.getT1()); - } - - @Test - public void testGetVidCardEventId() throws BaseCheckedException { - ResponseWrapper vidDownloadCardResponseDtoResponseWrapper = new ResponseWrapper<>(); - VidDownloadCardResponseDto vidDownloadCardResponseDto = new VidDownloadCardResponseDto(); - vidDownloadCardResponseDto.setStatus("success"); - vidDownloadCardResponseDtoResponseWrapper.setResponse(vidDownloadCardResponseDto); - ResponseWrapper responseWrapper = new ResponseWrapper<>(); - ResidentCredentialResponseDto residentCredentialResponseDto = new ResidentCredentialResponseDto(); - residentCredentialResponseDto.setId("123"); - residentCredentialResponseDto.setRequestId("123"); - responseWrapper.setResponse(residentCredentialResponseDto); - Mockito.when(residentServiceRestClient.postApi(any(), any(), any(), any())).thenReturn(responseWrapper); - assertEquals("12345", downloadCardService.getVidCardEventId("123", 0).getT2()); - } - - @Test(expected = ResidentServiceCheckedException.class) - public void testGetVidCardEventIdNestedIf() throws BaseCheckedException, IOException { - Mockito.when(utilities.getUinByVid(Mockito.anyString())).thenReturn("123456789"); - downloadCardService.getVidCardEventId("123", 0); - } - - @Test(expected = ResidentServiceCheckedException.class) - public void testGetVidCardEventIdFailed() throws BaseCheckedException { - ResponseWrapper vidDownloadCardResponseDtoResponseWrapper = new ResponseWrapper<>(); - VidDownloadCardResponseDto vidDownloadCardResponseDto = new VidDownloadCardResponseDto(); - vidDownloadCardResponseDtoResponseWrapper.setResponse(vidDownloadCardResponseDto); - ResponseWrapper responseWrapper = new ResponseWrapper<>(); - ResidentCredentialResponseDto residentCredentialResponseDto = new ResidentCredentialResponseDto(); - residentCredentialResponseDto.setId("123"); - residentCredentialResponseDto.setRequestId("123"); - responseWrapper.setErrors(List.of(new ServiceError(ResidentErrorCode.VID_REQUEST_CARD_FAILED.getErrorCode(), - ResidentErrorCode.VID_REQUEST_CARD_FAILED.getErrorMessage()))); - responseWrapper.setResponse(residentCredentialResponseDto); - Mockito.when(residentServiceRestClient.postApi(any(), any(), any(), any())).thenReturn(responseWrapper); - downloadCardService.getVidCardEventId("123", 0); - } - - @Test(expected = ApisResourceAccessException.class) - public void testGetVidCardEventIdApisResourceAccessException() throws BaseCheckedException { - ResponseWrapper vidDownloadCardResponseDtoResponseWrapper = new ResponseWrapper<>(); - VidDownloadCardResponseDto vidDownloadCardResponseDto = new VidDownloadCardResponseDto(); - vidDownloadCardResponseDtoResponseWrapper.setResponse(vidDownloadCardResponseDto); - Mockito.when(residentServiceRestClient.postApi(any(), any(), any(), any())).thenThrow(new ApisResourceAccessException()); - downloadCardService.getVidCardEventId("123", 0); - } - - @Test(expected = BaseCheckedException.class) - public void testGetVidCardEventIdResidentServiceCheckedException() throws BaseCheckedException, IOException { - ResponseWrapper vidDownloadCardResponseDtoResponseWrapper = new ResponseWrapper<>(); - VidDownloadCardResponseDto vidDownloadCardResponseDto = new VidDownloadCardResponseDto(); - vidDownloadCardResponseDtoResponseWrapper.setResponse(vidDownloadCardResponseDto); - Mockito.when(utilities.getUinByVid(Mockito.anyString())).thenThrow(new IOException()); - downloadCardService.getVidCardEventId("123", 0); - } - - @Test - public void testGetVidCardEventIdWithVidDetails() throws BaseCheckedException { - ResponseWrapper vidDownloadCardResponseDtoResponseWrapper = new ResponseWrapper<>(); - VidDownloadCardResponseDto vidDownloadCardResponseDto = new VidDownloadCardResponseDto(); - vidDownloadCardResponseDto.setStatus("success"); - vidDownloadCardResponseDtoResponseWrapper.setResponse(vidDownloadCardResponseDto); - ResponseWrapper responseWrapper = new ResponseWrapper<>(); - ResidentCredentialResponseDto residentCredentialResponseDto = new ResidentCredentialResponseDto(); - residentCredentialResponseDto.setId("123"); - residentCredentialResponseDto.setRequestId("123"); - responseWrapper.setResponse(residentCredentialResponseDto); - Mockito.when(residentServiceRestClient.postApi(any(), any(), any(), any())).thenReturn(responseWrapper); - ResponseWrapper>> vidResponse = new ResponseWrapper<>(); - Map vidDetails = new HashMap<>(); - vidDetails.put("vidType", "perpetual"); - List> vidList = new ArrayList<>(); - vidDetails.put("vid", "123"); - vidDetails.put("maskedVid", "1******4"); - vidDetails.put("expiryTimeStamp", "1234343434"); - vidDetails.put("expiryTimeStamp", "1234343434"); - vidDetails.put("genratedOnTimestamp", "1234343434"); - vidDetails.put("transactionLimit", "1234343434"); - vidDetails.put("transactionCount", "1234343434"); - vidList.add(vidDetails); - vidResponse.setResponse(vidList); - Mockito.when(vidService.retrieveVids(Mockito.anyString(), Mockito.anyInt())).thenReturn(vidResponse); - assertEquals("12345", downloadCardService.getVidCardEventId("123", 0).getT2()); - } - - @Test - public void testGetIndividualIdStatus() throws ApisResourceAccessException, IOException { - HashMap packetStatusMap = new HashMap<>(); - packetStatusMap.put(ResidentConstants.AID_STATUS, PacketStatus.SUCCESS.name()); - packetStatusMap.put(ResidentConstants.TRANSACTION_TYPE_CODE, TransactionStage.CARD_READY_TO_DOWNLOAD.name()); - Mockito.when(utilities.getPacketStatus(Mockito.anyString())).thenReturn(packetStatusMap); - ResponseWrapper getIndividualIdStatus = downloadCardService.getIndividualIdStatus("3425636374"); - assertEquals(PacketStatus.SUCCESS.name(),getIndividualIdStatus.getResponse().getAidStatus()); - } - -} \ No newline at end of file diff --git a/resident/resident-service/src/test/java/io/mosip/resident/test/service/DownloadmasterDataServiceImplTest.java b/resident/resident-service/src/test/java/io/mosip/resident/test/service/DownloadmasterDataServiceImplTest.java deleted file mode 100644 index ae12ac79df4..00000000000 --- a/resident/resident-service/src/test/java/io/mosip/resident/test/service/DownloadmasterDataServiceImplTest.java +++ /dev/null @@ -1,186 +0,0 @@ -package io.mosip.resident.test.service; - -import static org.junit.Assert.assertNotNull; -import static org.mockito.ArgumentMatchers.any; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.InputStream; -import java.io.OutputStream; -import java.nio.charset.StandardCharsets; -import java.time.LocalTime; -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Optional; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; -import org.springframework.cloud.context.config.annotation.RefreshScope; -import org.springframework.core.env.Environment; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.util.ReflectionTestUtils; - -import com.fasterxml.jackson.databind.ObjectMapper; - -import io.mosip.kernel.core.http.ResponseWrapper; -import io.mosip.kernel.core.pdfgenerator.spi.PDFGenerator; -import io.mosip.kernel.core.templatemanager.spi.TemplateManager; -import io.mosip.kernel.signature.dto.SignatureResponseDto; -import io.mosip.kernel.templatemanager.velocity.builder.TemplateManagerBuilderImpl; -import io.mosip.resident.constant.ResidentConstants; -import io.mosip.resident.dto.RegistrationCenterDto; -import io.mosip.resident.dto.WorkingDaysDto; -import io.mosip.resident.dto.WorkingDaysResponseDto; -import io.mosip.resident.entity.ResidentTransactionEntity; -import io.mosip.resident.repository.ResidentTransactionRepository; -import io.mosip.resident.service.ProxyMasterdataService; -import io.mosip.resident.service.impl.DownLoadMasterDataServiceImpl; -import io.mosip.resident.util.ResidentServiceRestClient; -import io.mosip.resident.util.TemplateUtil; -import io.mosip.resident.util.Utility; - -/** - * This class is used to create service class test for download master data service impl. - * @Author Kamesh Shekhar Prasad - */ -@RunWith(MockitoJUnitRunner.class) -@RefreshScope -@ContextConfiguration -public class DownloadmasterDataServiceImplTest { - - @InjectMocks - private DownLoadMasterDataServiceImpl downLoadMasterDataService = new DownLoadMasterDataServiceImpl(); - - @Mock - private ResidentTransactionRepository residentTransactionRepository; - - @Mock - private TemplateUtil templateUtil; - - @Mock - private ProxyMasterdataService proxyMasterdataService; - - @InjectMocks - private TemplateManagerBuilderImpl templateManagerBuilder; - - @Mock - private PDFGenerator pdfGenerator; - - @Mock - private Environment environment; - - @Mock - private ObjectMapper objectMapper; - - @Mock - private ResidentServiceRestClient residentServiceRestClient; - - @Mock - private Utility utility; - - private byte[] result; - private String eventId; - private String languageCode; - private Optional residentTransactionEntity; - private Map templateResponse; - private ResponseWrapper responseWrapper; - private Map templateVariables; - - @Mock - private TemplateManager templateManager; - private static final String CLASSPATH = "classpath"; - private static final String ENCODE_TYPE = "UTF-8"; - private Map values; - - private String langCode; - private Short hierarchyLevel; - private List name; - - @Before - public void setup() throws Exception { - templateResponse = new LinkedHashMap<>(); - templateVariables = new LinkedHashMap<>(); - values = new LinkedHashMap<>(); - values.put("test", String.class); - templateVariables.put("eventId", eventId); - responseWrapper = new ResponseWrapper<>(); - templateResponse.put(ResidentConstants.FILE_TEXT, "test"); - responseWrapper.setResponse(templateResponse); - result = "test".getBytes(StandardCharsets.UTF_8); - eventId = "bf42d76e-b02e-48c8-a17a-6bb842d85ea9"; - languageCode = "eng"; - - Mockito.when(proxyMasterdataService.getAllTemplateBylangCodeAndTemplateTypeCode(Mockito.anyString(), Mockito.anyString())). - thenReturn(responseWrapper); - ReflectionTestUtils.setField(downLoadMasterDataService, "templateManagerBuilder", templateManagerBuilder); - templateManagerBuilder.encodingType(ENCODE_TYPE).enableCache(false).resourceLoader(CLASSPATH).build(); - InputStream stream = new ByteArrayInputStream("test".getBytes(StandardCharsets.UTF_8)); - Mockito.when(templateManager.merge(any(), Mockito.anyMap())).thenReturn(stream); - OutputStream outputStream = new ByteArrayOutputStream(1024); - outputStream.write("test".getBytes(StandardCharsets.UTF_8)); - SignatureResponseDto signatureResponseDto = new SignatureResponseDto(); - signatureResponseDto.setData("data"); - ResponseWrapper responseWrapper = new ResponseWrapper<>(); - responseWrapper.setResponse(signatureResponseDto); - Mockito.when(utility.signPdf(Mockito.any(), Mockito.any())).thenReturn("data".getBytes()); - Mockito.when(environment.getProperty(Mockito.anyString())).thenReturn("supporting-docs-list"); - langCode="eng"; - hierarchyLevel=4; - name = new ArrayList<>(); - name.add("name1"); - } - - @Test - public void testDownloadRegistrationCentersByHierarchyLevel() throws Exception { - byte[] actualResult = downLoadMasterDataService.downloadRegistrationCentersByHierarchyLevel(langCode, hierarchyLevel, name).readAllBytes(); - assertNotNull(actualResult); - } - - @Test - public void testGetNearestRegistrationcenters() throws Exception { - byte[] actualResult = downLoadMasterDataService.getNearestRegistrationcenters(langCode, 4L, 4L,3).readAllBytes(); - assertNotNull(actualResult); - } - - @Test - public void testDownloadSupportingDocsByLanguage() throws Exception { - byte[] actualResult = downLoadMasterDataService.downloadSupportingDocsByLanguage(langCode).readAllBytes(); - assertNotNull(actualResult); - } - - @Test - public void testgetTime() throws Exception { - RegistrationCenterDto registrationCenterDto = new RegistrationCenterDto(); - registrationCenterDto.setCenterTypeCode("Ind"); - WorkingDaysResponseDto workingDaysResponseDto = new WorkingDaysResponseDto(); - WorkingDaysDto workingDaysDto = new WorkingDaysDto(); - workingDaysDto.setCode("123"); - workingDaysResponseDto.setWorkingdays(List.of(workingDaysDto)); - ResponseWrapper responseWrapper1 = new ResponseWrapper<>(); - responseWrapper1.setResponse(workingDaysResponseDto); - ReflectionTestUtils.invokeMethod(downLoadMasterDataService, "getTime", - String.valueOf(LocalTime.of(12,2,2))); - - } - - @Test - public void testgetTimeFailed() throws Exception { - RegistrationCenterDto registrationCenterDto = new RegistrationCenterDto(); - registrationCenterDto.setCenterTypeCode("Ind"); - WorkingDaysResponseDto workingDaysResponseDto = new WorkingDaysResponseDto(); - WorkingDaysDto workingDaysDto = new WorkingDaysDto(); - workingDaysDto.setCode("123"); - workingDaysResponseDto.setWorkingdays(List.of(workingDaysDto)); - ResponseWrapper responseWrapper1 = new ResponseWrapper<>(); - responseWrapper1.setResponse(workingDaysResponseDto); - ReflectionTestUtils.invokeMethod(downLoadMasterDataService, "getTime", "123"); - - } -} \ No newline at end of file diff --git a/resident/resident-service/src/test/java/io/mosip/resident/test/service/GrievanceServiceImplTest.java b/resident/resident-service/src/test/java/io/mosip/resident/test/service/GrievanceServiceImplTest.java deleted file mode 100644 index 69d303f1db2..00000000000 --- a/resident/resident-service/src/test/java/io/mosip/resident/test/service/GrievanceServiceImplTest.java +++ /dev/null @@ -1,74 +0,0 @@ -package io.mosip.resident.test.service; - -import static org.junit.Assert.assertNotNull; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; -import org.springframework.cloud.context.config.annotation.RefreshScope; -import org.springframework.core.env.Environment; -import org.springframework.test.context.ContextConfiguration; - -import io.mosip.kernel.core.http.ResponseWrapper; -import io.mosip.resident.dto.GrievanceRequestDTO; -import io.mosip.resident.dto.MainRequestDTO; -import io.mosip.resident.exception.ApisResourceAccessException; -import io.mosip.resident.repository.ResidentGrievanceRepository; -import io.mosip.resident.service.impl.GrievanceServiceImpl; -import io.mosip.resident.service.impl.IdentityServiceImpl; -import io.mosip.resident.util.AuditUtil; - -/** - * This class is used to create service class test for grievance API. - * @Author Kamesh Shekhar Prasad - */ -@RunWith(MockitoJUnitRunner.class) -@RefreshScope -@ContextConfiguration -public class GrievanceServiceImplTest { - - @InjectMocks - private GrievanceServiceImpl grievanceService = new GrievanceServiceImpl(); - - @Mock - private Environment environment; - - @Mock - private IdentityServiceImpl identityService; - - @Mock - private ResidentGrievanceRepository residentGrievanceRepository; - - @Mock - private AuditUtil auditUtil; - - private MainRequestDTO grievanceRequestDTOMainRequestDTO; - - @Before - public void setup() throws Exception { - grievanceRequestDTOMainRequestDTO = new MainRequestDTO<>(); - GrievanceRequestDTO grievanceRequestDTO = new GrievanceRequestDTO(); - grievanceRequestDTO.setEventId("12121212121212"); - grievanceRequestDTO.setMessage("message"); - grievanceRequestDTOMainRequestDTO.setRequest(grievanceRequestDTO); - Mockito.when(environment.getProperty(Mockito.anyString())).thenReturn("Kamesh"); - Mockito.when(identityService.getAvailableclaimValue(Mockito.anyString())).thenReturn("kamesh"); - } - - @Test - public void testGetGrievanceTicket() throws ApisResourceAccessException { - ResponseWrapper actualResult = grievanceService.getGrievanceTicket(grievanceRequestDTOMainRequestDTO); - assertNotNull(actualResult); - } - - @Test(expected = ApisResourceAccessException.class) - public void testGetGrievanceTicketFailed() throws ApisResourceAccessException { - Mockito.when(identityService.getAvailableclaimValue(Mockito.anyString())).thenThrow(new ApisResourceAccessException()); - ResponseWrapper actualResult = grievanceService.getGrievanceTicket(grievanceRequestDTOMainRequestDTO); - assertNotNull(actualResult); - } -} \ No newline at end of file diff --git a/resident/resident-service/src/test/java/io/mosip/resident/test/service/IdentityServiceTest.java b/resident/resident-service/src/test/java/io/mosip/resident/test/service/IdentityServiceTest.java deleted file mode 100644 index 8ab7c659e15..00000000000 --- a/resident/resident-service/src/test/java/io/mosip/resident/test/service/IdentityServiceTest.java +++ /dev/null @@ -1,618 +0,0 @@ -package io.mosip.resident.test.service; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyList; -import static org.mockito.ArgumentMatchers.anyMap; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.when; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.net.URI; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Optional; - -import org.apache.commons.io.IOUtils; -import org.apache.commons.lang3.tuple.ImmutablePair; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; -import org.springframework.cloud.context.config.annotation.RefreshScope; -import org.springframework.core.env.Environment; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.context.SecurityContext; -import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.util.ReflectionTestUtils; -import org.springframework.util.LinkedMultiValueMap; -import org.springframework.util.MultiValueMap; - -import com.fasterxml.jackson.databind.ObjectMapper; - -import io.mosip.idrepository.core.util.TokenIDGenerator; -import io.mosip.kernel.authcodeflowproxy.api.validator.ValidateTokenUtil; -import io.mosip.kernel.biometrics.spi.CbeffUtil; -import io.mosip.kernel.core.exception.ServiceError; -import io.mosip.kernel.core.http.ResponseWrapper; -import io.mosip.kernel.core.util.CryptoUtil; -import io.mosip.kernel.openid.bridge.api.constants.AuthErrorCode; -import io.mosip.kernel.openid.bridge.model.AuthUserDetails; -import io.mosip.kernel.openid.bridge.model.MosipUserDto; -import io.mosip.resident.constant.ApiName; -import io.mosip.resident.constant.IdType; -import io.mosip.resident.dto.IdentityDTO; -import io.mosip.resident.exception.ApisResourceAccessException; -import io.mosip.resident.exception.ResidentServiceCheckedException; -import io.mosip.resident.exception.ResidentServiceException; -import io.mosip.resident.exception.VidCreationException; -import io.mosip.resident.handler.service.ResidentConfigService; -import io.mosip.resident.helper.ObjectStoreHelper; -import io.mosip.resident.service.IdentityService; -import io.mosip.resident.service.ResidentVidService; -import io.mosip.resident.service.impl.IdentityServiceImpl; -import io.mosip.resident.util.AuditUtil; -import io.mosip.resident.util.ResidentServiceRestClient; -import io.mosip.resident.util.Utilities; -import io.mosip.resident.util.Utility; -import io.mosip.resident.validator.RequestValidator; -import reactor.util.function.Tuple3; -import reactor.util.function.Tuples; - -@RunWith(MockitoJUnitRunner.Silent.class) -@RefreshScope -@ContextConfiguration -public class IdentityServiceTest { - - @InjectMocks - private IdentityService identityService = new IdentityServiceImpl(); - - @Mock - private AuditUtil auditUtil; - - @Mock - private Utility utility; - - @Mock - private CbeffUtil cbeffUtil; - - @Mock - private TokenIDGenerator tokenIDGenerator; - - @Mock - private ResidentVidService residentVidService; - - @Mock - private ResidentServiceRestClient restClientWithSelfTOkenRestTemplate; - - @Mock - private ResidentServiceRestClient restClientWithPlainRestTemplate; - - @Mock - private ResidentConfigService residentConfigService; - - @Mock - private Environment env; - - @Mock - private RequestValidator requestValidator; - - @Mock - private ObjectStoreHelper objectStoreHelper; - - @Mock - private Utilities utilities; - - @Mock - private ValidateTokenUtil tokenValidationHelper; - - private ResponseWrapper responseWrapper; - - private Map responseMap; - - private Map bdbFaceMap; - - private ObjectMapper objectMapper = new ObjectMapper(); - - private static String token; - - - @Before - public void setUp() throws Exception { - ReflectionTestUtils.setField(identityService, "dateFormat", "yyyy/MM/dd"); - ReflectionTestUtils.setField(identityService, "objectMapper", objectMapper); - - Map identityMap = new LinkedHashMap(); - identityMap.put("UIN", "8251649601"); - identityMap.put("email", "manojvsp12@gmail.com"); - identityMap.put("phone", "9395910872"); - identityMap.put("dateOfBirth", "1970/11/16"); - - List fNameList = new ArrayList(); - Map fNameMap = new LinkedHashMap(); - fNameMap.put("language", "eng"); - fNameMap.put("value", "Rahul"); - fNameList.add(fNameMap); - identityMap.put("firstName", fNameList); - - List mNameList = new ArrayList(); - Map mNameMap = new LinkedHashMap(); - mNameMap.put("language", "eng"); - mNameMap.put("value", "Kumar"); - mNameList.add(mNameMap); - identityMap.put("middleName", mNameList); - - List lNameList = new ArrayList(); - Map lNameMap = new LinkedHashMap(); - lNameMap.put("language", "eng"); - lNameMap.put("value", "Singh"); - lNameList.add(lNameMap); - identityMap.put("lastName", lNameList); - - responseMap = new LinkedHashMap(); - responseMap.put("identity", identityMap); - - List docList = new ArrayList(); - Map docMap = new LinkedHashMap(); - docMap.put("category", "individualBiometrics"); - docMap.put("value", "encodedValue"); - docList.add(docMap); - responseMap.put("documents", docList); - - bdbFaceMap = new HashMap(); - bdbFaceMap.put("face", "this is a face biometric key"); - - responseWrapper = new ResponseWrapper<>(); - responseWrapper.setVersion("v1"); - responseWrapper.setId("1"); - responseWrapper.setResponse(responseMap); - responseWrapper.setErrors(null); - - when(restClientWithSelfTOkenRestTemplate.getApi((ApiName) any(), anyMap(), anyList(), anyList(), any())) - .thenReturn(responseWrapper); - when(residentConfigService.getUiSchemaFilteredInputAttributes(anyString())) - .thenReturn(List.of("UIN", "email", "phone", "dateOfBirth", "firstName", "middleName", "lastName", "perpetualVID")); - - Mockito.when(requestValidator.validateUin(Mockito.anyString())).thenReturn(true); - Mockito.when(requestValidator.validateRid(Mockito.anyString())).thenReturn(true); - token = "eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJubEpTaUExM2tPUWhZQ0JxMEVKSkRlWnFTOGsybDB3MExUbmQ1WFBCZ20wIn0." + - "eyJleHAiOjE2NzIxMjU0NjEsImlhdCI6MTY3MjAzOTA2MSwianRpIjoiODc5YTdmYTItZWZhYy00YTQwLTkxODQtNzZiM2FhMWJiODg0IiwiaXNzIjoiaHR0c" + - "HM6Ly9pYW0uZGV2Lm1vc2lwLm5ldC9hdXRoL3JlYWxtcy9tb3NpcCIsImF1ZCI6ImFjY291bnQiLCJzdWIiOiJiNTc3NjkzYi0xOWI1LTRlYTktYWEzNy1kMT" + - "EzMjdkOGRkNzkiLCJ0eXAiOiJCZWFyZXIiLCJhenAiOiJtb3NpcC1yZXNpZGVudC1jbGllbnQiLCJzZXNzaW9uX3N0YXRlIjoiNWNmZWIzNTgtNGY1Ni00NjM" + - "0LTg3NmQtNGFjNzk1OTYyYWRkIiwiYWNyIjoiMSIsInJlYWxtX2FjY2VzcyI6eyJyb2xlcyI6WyJvZmZsaW5lX2FjY2VzcyIsInVtYV9hdXRob3JpemF0aW9u" + - "IiwiZGVmYXVsdC1yb2xlcy1tb3NpcCJdfSwicmVzb3VyY2VfYWNjZXNzIjp7ImFjY291bnQiOnsicm9sZXMiOlsibWFuYWdlLWFjY291bnQiLCJtYW5hZ2UtYW" + - "Njb3VudC1saW5rcyIsInZpZXctcHJvZmlsZSJdfX0sInNjb3BlIjoid2FsbGV0X2JpbmRpbmcgYXV0aC5oaXN0b3J5LnJlYWRvbmx5IG1pY3JvcHJvZmlsZS1q" + - "d3QgaWRlbnRpdHkucmVhZG9ubHkgaWRhX3Rva2VuIG9mZmxpbmVfYWNjZXNzIGFkZHJlc3MgdXBkYXRlX29pZGNfY2xpZW50IGNyZWRlbnRpYWwubWFuYWdlIH" + - "ZpZC5tYW5hZ2UgZ2V0X2NlcnRpZmljYXRlIGFkZF9vaWRjX2NsaWVudCB2aWQucmVhZG9ubHkgaWRlbnRpdHkudXBkYXRlIG5vdGlmaWNhdGlvbnMubWFuYWdl" + - "IGVtYWlsIHVwbG9hZF9jZXJ0aWZpY2F0ZSBhdXRoLnJlYWRvbmx5IGF1dGgubWV0aG9kLm1hbmFnZSBub3RpZmljYXRpb25zLnJlYWRvbmx5IGluZGl2aWR1YWxf" + - "aWQgYXV0aC5oaXN0b3J5Lm1hbmFnZSB0ZXN0IHByb2ZpbGUgY2FyZC5tYW5hZ2Ugc2VuZF9iaW5kaW5nX290cCIsInNpZCI6IjVjZmViMzU4LTRmNTYtNDYzNC0" + - "4NzZkLTRhYzc5NTk2MmFkZCIsInVwbiI6ImthbWVzaCIsImFkZHJlc3MiOnt9LCJlbWFpbF92ZXJpZmllZCI6ZmFsc2UsIm5hbWUiOiJLYW1lc2ggU2hla2hh" + - "ciIsImdyb3VwcyI6WyJvZmZsaW5lX2FjY2VzcyIsInVtYV9hdXRob3JpemF0aW9uIiwiZGVmYXVsdC1yb2xlcy1tb3NpcCJdLCJwcmVmZXJyZWRfdXNlcm5hb" + - "WUiOiJrYW1lc2giLCJnaXZlbl9uYW1lIjoiS2FtZXNoIiwiZmFtaWx5X25hbWUiOiJTaGVraGFyIiwicGljdHVyZSI6ImlWQk9SdzBLR2dvQUFBQU5TVWhFVW" + - "dBQUFBb0FBQUFLQ0FJQUFBQUNVRmpxQUFBQUFYTlNSMElBcnM0YzZRQUFBQVJuUVUxQkFBQ3hqd3Y4WVFVQUFBQUpjRWhaY3dBQUZpVUFBQllsQVVsU0pQQUF" + - "BQUJDU1VSQlZDaFRiWXRCRWdBZ0NBTDcvNmVOaEJ5MDlxRGk2Z3BqWFpTeFVVOG8vanJmcERtY21ZMVFBT1doZ1Rzd3Y2c1NtOHpWaFVMbGdzdCsrOFQ1MUlq" + - "WU5VSGRJKzRYWkhvQUFBQUFTVVZPUks1Q1lJST0iLCJlbWFpbCI6ImthbWVzaHNyMTMzOEBnbWFpbC5jb20ifQ.YLddWNd7ldiMvPhDK0HhXaKjEmeOE0T6wS" + - "CjfN3mlwxDxHm2DzMHnwbKR5orEm1NRyCnUfGGm5IMVTdDnXz1iUAsU7zeKA2XOdH3zQgMUu-vqJpgRWRG-XJHakSyblfAFIVAILRi7rwJQjL7X1lhm1ZAqUX" + - "Soh6kZBoOeYd_29RQQzFQNzpn_Ahk4GxQu_TLyvoWeNXpfx94om7TqrZYghtTg5_svku2P0NuFxzbWysPMjaHrEff0idKY94sKJ6eNpLXRXbJCPkAHtfVY0U3" + - "YDQqWUpYjE3hQCZz0u_L8sieJIN3mYtjd12rfOrjEKu2fFGu5UbJRVqkmOw0egVGHw"; - when(env.getProperty("mosip.resident.photo.attribute.name")).thenReturn("photo"); - when(env.getProperty("resident.additional.identity.attribute.to.fetch")).thenReturn("UIN,email,phone,dateOfBirth,fullName"); - when(env.getProperty("mosip.resident.photo.token.claim-photo")).thenReturn("picture"); - } - - private void fileLoadMethod() throws Exception { - ClassLoader classLoader = getClass().getClassLoader(); - File idJson = new File(classLoader.getResource("IdentityMapping.json").getFile()); - InputStream is = new FileInputStream(idJson); - String mappingJson = IOUtils.toString(is, "UTF-8"); - when(utility.getMappingJson()).thenReturn(mappingJson); - } - - @Test - public void testGetIdentityLangCodeNull() throws Exception { - getAuthUserDetailsFromAuthentication(); - Tuple3, Map> tuple3 = loadUserInfoMethod(); - tuple3.getT3().put("photo", "NGFjNzk1OTYyYWRkIiwiYWNyIjoiMSIsInJlYWxtX2FjY2VzcyI6eyJyb2xlcyI6WyJ"); - when(restClientWithPlainRestTemplate.getApi(tuple3.getT1(), String.class, tuple3.getT2())) - .thenReturn(objectMapper.writeValueAsString(tuple3.getT3())); - fileLoadMethod(); - IdentityDTO result = identityService.getIdentity("6"); - assertNotNull(result); - assertEquals("8251649601", result.getUIN()); - } - - @Test(expected = ResidentServiceCheckedException.class) - public void testGetIdentityAttributesIf() throws Exception { - ServiceError error = new ServiceError(); - error.setErrorCode("101"); - error.setMessage("errors"); - - List errorList = new ArrayList(); - errorList.add(error); - - responseWrapper.setErrors(errorList); - identityService.getIdentity("6"); - } - - @Test(expected = ResidentServiceCheckedException.class) - public void testGetIdentityAttributesWithApisResourceAccessException() throws Exception { - when(restClientWithSelfTOkenRestTemplate.getApi((ApiName) any(), anyMap(), anyList(), anyList(), any())) - .thenThrow(new ApisResourceAccessException()); - identityService.getIdentity("6"); - } - - @Test(expected = ResidentServiceCheckedException.class) - public void testGetMappingValueIf() throws Exception { - Tuple3, Map> tuple3 = loadUserInfoMethod(); - tuple3.getT3().put("photo", "NGFjNzk1OTYyYWRkIiwiYWNyIjoiMSIsInJlYWxtX2FjY2VzcyI6eyJyb2xlcyI6WyJ"); - when(restClientWithPlainRestTemplate.getApi(tuple3.getT1(), String.class, tuple3.getT2())) - .thenReturn(objectMapper.writeValueAsString(tuple3.getT3())); - identityService.getIdentity("6"); - } - - @Test - public void testGetUinForIndividualId() throws Exception{ - String id = "123456789"; - fileLoadMethod(); - String result = identityService.getUinForIndividualId(id); - assertEquals("123456789", result); - } - - @Test - public void testGetIDATokenForIndividualId() throws Exception{ - String id = "123456789"; - String token = "1234"; - ReflectionTestUtils.setField(identityService, "onlineVerificationPartnerId", "m-partner-default-auth"); - when(tokenIDGenerator.generateTokenID(anyString(), anyString())).thenReturn(token); - fileLoadMethod(); - String result = identityService.getIDATokenForIndividualId(id); - assertEquals(token, result); - } - - @Test(expected = ResidentServiceException.class) - public void testGetClaimFromUserInfoFailure(){ - Map userInfo = new HashMap<>(); - ReflectionTestUtils.invokeMethod(identityService, "getClaimFromUserInfo", userInfo, "claim"); - } - - @Test - public void testGetClaimFromUserInfoSuccess() { - Map userInfo = new HashMap<>(); - userInfo.put("claim", "value"); - String result = ReflectionTestUtils.invokeMethod(identityService, "getClaimFromUserInfo", userInfo, "claim"); - assertEquals("value", result); - } - - private Tuple3, Map> loadUserInfoMethod() throws Exception { - ReflectionTestUtils.setField(identityService, "usefInfoEndpointUrl", "http://localhost:8080/userinfo"); - Map userInfo = new HashMap<>(); - userInfo.put("claim", "value"); - URI uri = URI.create("http://localhost:8080/userinfo"); - MultiValueMap headers = new LinkedMultiValueMap<>(); - headers.add("Authorization", "Bearer " + token); - return Tuples.of(uri, headers, userInfo); - } - - @Test - public void testGetUserInfoSuccess() throws Exception { - Tuple3, Map> tuple3 = loadUserInfoMethod(); - when(restClientWithPlainRestTemplate.getApi(tuple3.getT1(), String.class, tuple3.getT2())) - .thenReturn(objectMapper.writeValueAsString(tuple3.getT3())); - Map result = ReflectionTestUtils.invokeMethod(identityService, "getUserInfo", token); - assertEquals("value", result.get("claim")); - } - - @Test - public void testGetIndividualIdForAid() throws Exception{ - Tuple3, Map> tuple3 = loadUserInfoMethod(); - tuple3.getT3().put("photo", "NGFjNzk1OTYyYWRkIiwiYWNyIjoiMSIsInJlYWxtX2FjY2VzcyI6eyJyb2xlcyI6WyJ"); - when(restClientWithPlainRestTemplate.getApi(tuple3.getT1(), String.class, tuple3.getT2())) - .thenReturn(objectMapper.writeValueAsString(tuple3.getT3())); - String aid = "123456789"; - fileLoadMethod(); - String result = ReflectionTestUtils.invokeMethod(identityService, "getIndividualIdForAid", aid); - assertEquals("8251649601", result); - } - - @Test - public void testGetIndividualIdForAidUseVidOnlyTrue() throws Exception{ - Tuple3, Map> tuple3 = loadUserInfoMethod(); - tuple3.getT3().put("photo", "NGFjNzk1OTYyYWRkIiwiYWNyIjoiMSIsInJlYWxtX2FjY2VzcyI6eyJyb2xlcyI6WyJ"); - when(restClientWithPlainRestTemplate.getApi(tuple3.getT1(), String.class, tuple3.getT2())) - .thenReturn(objectMapper.writeValueAsString(tuple3.getT3())); - String aid = "123456789"; - Optional perpVid = Optional.of("8251649601"); - when(residentVidService.getPerpatualVid(anyString())).thenReturn(perpVid); - ReflectionTestUtils.setField(identityService,"useVidOnly", true); - fileLoadMethod(); - String result = ReflectionTestUtils.invokeMethod(identityService, "getIndividualIdForAid", aid); - assertEquals("8251649601", result); - } - - @Test - public void testGetIndividualIdTypeUin(){ - assertEquals(IdType.UIN.toString(), identityService.getIndividualIdType("2476302389")); - } - - @Test - public void testGetIndividualIdTypeVid(){ - assertEquals(IdType.UIN.toString(), identityService.getIndividualIdType("2476302389")); - } - - @Test - public void testDecryptPayload(){ - Mockito.when(env.getProperty(Mockito.anyString())).thenReturn("RESIDENT"); - Mockito.when(objectStoreHelper.decryptData(Mockito.anyString(), Mockito.anyString(), Mockito.anyString())).thenReturn("payload"); - assertEquals("payload", ReflectionTestUtils.invokeMethod(identityService, "decryptPayload", "payload")); - } - - @Test - public void testDecodeString(){ - String encodedString = "c3RyaW5n"; - assertEquals("string", ReflectionTestUtils.invokeMethod(identityService, "decodeString", encodedString)); - } - - @Test - public void testGetClaimValueFromJwtToken(){ - assertEquals("account", ReflectionTestUtils.invokeMethod(identityService, "getClaimValueFromJwtToken", - token, "aud")); - } - - @Test - public void testGetClaimValueFromJwtTokenNullToken(){ - token = null; - assertEquals("", ReflectionTestUtils.invokeMethod(identityService, "getClaimValueFromJwtToken", - token, "aud")); - } - - @Test(expected = RuntimeException.class) - public void testGetClaimValueFromJwtTokenDecryptedTokenFailed(){ - token = "c3RyaW5n"; - assertEquals("", ReflectionTestUtils.invokeMethod(identityService, "getClaimValueFromJwtToken", - token, "aud")); - } - - @Test(expected = RuntimeException.class) - public void testGetClaimValueFromJwtTokenDecryptedToken(){ - token = "YLddWNd7ldiMvPhDK0HhXaKjEmeOE0T6wSCjfN3mlwxDxHm2DzMHnwbKR5orEm1NRyCnUfGGm5IMVTdDnXz1iUAsU7zeKA2XOdH3zQgMUu" + - "-vqJpgRWRG-XJHakSyblfAFIVAILRi7rwJQjL7X1lhm1ZAqUXSoh6kZBoOeYd_29RQQzFQNzpn_Ahk4GxQu_TLyvoWeNXpfx94om7TqrZYghtTg" + - "5_svku2P0NuFxzbWysPMjaHrEff0idKY94sKJ6eNpLXRXbJCPkAHtfVY0U3YDQqWUpYjE3hQCZz0u_L8sieJIN3mYtjd12rfOrjEKu2fFGu5UbJRV" + - "qkmOw0egVGHw"; - assertEquals("", ReflectionTestUtils.invokeMethod(identityService, "getClaimValueFromJwtToken", - token, "aud")); - } - - @Test - public void testGetClaimValueFromJwtTokenNullClaim() throws ResidentServiceCheckedException { - assertEquals("2476302389",identityService.getUinForIndividualId("2476302389")); - } - - @Test(expected = ResidentServiceCheckedException.class) - public void testGetMappingValueNullIoException() throws Exception { - Tuple3, Map> tuple3 = loadUserInfoMethod(); - tuple3.getT3().put("photo", "NGFjNzk1OTYyYWRkIiwiYWNyIjoiMSIsInJlYWxtX2FjY2VzcyI6eyJyb2xlcyI6WyJ"); - when(restClientWithPlainRestTemplate.getApi(tuple3.getT1(), String.class, tuple3.getT2())) - .thenReturn(objectMapper.writeValueAsString(tuple3.getT3())); - String mappingJson = "mappingJson"; - when(utility.getMappingJson()).thenReturn(mappingJson); - IdentityDTO result = identityService.getIdentity("6", false, "eng"); - assertNotNull(result); - assertEquals("6", result.getUIN()); - } - - @Test - public void testGetMappingValueInvalidPerpetualVid() throws Exception { - Tuple3, Map> tuple3 = loadUserInfoMethod(); - tuple3.getT3().put("photo", "NGFjNzk1OTYyYWRkIiwiYWNyIjoiMSIsInJlYWxtX2FjY2VzcyI6eyJyb2xlcyI6WyJ"); - when(restClientWithPlainRestTemplate.getApi(tuple3.getT1(), String.class, tuple3.getT2())) - .thenReturn(objectMapper.writeValueAsString(tuple3.getT3())); - fileLoadMethod(); - IdentityDTO result = identityService.getIdentity("6", false, "eng"); - assertNotNull(result); - assertEquals("8251649601", result.getUIN()); - } - - @Test - public void testGetMappingValueValidPerpetualVid() throws Exception { - Tuple3, Map> tuple3 = loadUserInfoMethod(); - tuple3.getT3().put("photo", "NGFjNzk1OTYyYWRkIiwiYWNyIjoiMSIsInJlYWxtX2FjY2VzcyI6eyJyb2xlcyI6WyJ"); - when(restClientWithPlainRestTemplate.getApi(tuple3.getT1(), String.class, tuple3.getT2())) - .thenReturn(objectMapper.writeValueAsString(tuple3.getT3())); - when(residentVidService.getPerpatualVid(Mockito.anyString())).thenReturn(Optional.of("4069341201794732")); - fileLoadMethod(); - String str = CryptoUtil.encodeToURLSafeBase64("response return".getBytes()); - IdentityDTO result = identityService.getIdentity("6", false, "eng"); - assertNotNull(result); - assertEquals("8251649601", result.getUIN()); - } - - @Test(expected = ResidentServiceException.class) - public void testGetMappingValueValidPerpetualVidResidentServiceCheckedException() throws Exception { - fileLoadMethod(); - when(env.getProperty("resident.additional.identity.attribute.to.fetch")).thenReturn("UIN,email,phone,dateOfBirth,fullName,perpetualVID"); - when(residentVidService.getPerpatualVid(Mockito.anyString())).thenThrow(new ResidentServiceCheckedException()); - IdentityDTO result = identityService.getIdentity("6", false, "eng"); - assertNotNull(result); - assertEquals("6", result.getUIN()); - } - - @Test(expected = ResidentServiceException.class) - public void testGetMappingValueValidPerpetualVidApisResourceAccessException() throws Exception { - when(residentVidService.getPerpatualVid(Mockito.anyString())).thenThrow(new ApisResourceAccessException()); - when(env.getProperty("resident.additional.identity.attribute.to.fetch")).thenReturn("UIN,email,phone,dateOfBirth,fullName,perpetualVID"); - fileLoadMethod(); - IdentityDTO result = identityService.getIdentity("6", false, "eng"); - assertNotNull(result); - assertEquals("6", result.getUIN()); - } - - @Test - public void testGetNameForNotification() throws Exception { - fileLoadMethod(); - Map identity = new HashMap<>(); - identity.put("name", "Kamesh"); - ReflectionTestUtils.invokeMethod(identityService, "getNameForNotification", - identity, "eng"); - } - - @Test - public void testGetUinForIndividualIdVId() throws ResidentServiceCheckedException, ApisResourceAccessException, IOException { - Mockito.when(requestValidator.validateUin(Mockito.anyString())).thenReturn(false); - Mockito.when(utilities.getUinByVid(Mockito.anyString())).thenReturn("2476302389"); - assertEquals("2476302389",identityService.getUinForIndividualId("2476302389")); - } - - @Test(expected = ResidentServiceCheckedException.class) - public void testGetUinForIndividualIdVIdCreationException() throws ResidentServiceCheckedException, ApisResourceAccessException, IOException { - Mockito.when(requestValidator.validateUin(Mockito.anyString())).thenReturn(false); - Mockito.when(utilities.getUinByVid(Mockito.anyString())).thenThrow(new VidCreationException()); - assertEquals("2476302389",identityService.getUinForIndividualId("2476302389")); - } - - @Test(expected = ResidentServiceCheckedException.class) - public void testGetUinForIndividualIdApisResourceAccessException() throws ResidentServiceCheckedException, ApisResourceAccessException, IOException { - Mockito.when(requestValidator.validateUin(Mockito.anyString())).thenReturn(false); - Mockito.when(utilities.getUinByVid(Mockito.anyString())).thenThrow(new ApisResourceAccessException()); - assertEquals("2476302389",identityService.getUinForIndividualId("2476302389")); - } - - @Test(expected = ResidentServiceCheckedException.class) - public void testGetUinForIndividualIdIOException() throws ResidentServiceCheckedException, ApisResourceAccessException, IOException { - Mockito.when(requestValidator.validateUin(Mockito.anyString())).thenReturn(false); - Mockito.when(utilities.getUinByVid(Mockito.anyString())).thenThrow(new IOException()); - assertEquals("2476302389",identityService.getUinForIndividualId("2476302389")); - } - - public static void getAuthUserDetailsFromAuthentication() { - Authentication authentication= Mockito.mock(Authentication.class); - SecurityContext securityContext = Mockito.mock(SecurityContext.class); - SecurityContextHolder.setContext(securityContext); - when(securityContext.getAuthentication()).thenReturn(authentication); - - MosipUserDto mosipUserDto = new MosipUserDto(); - mosipUserDto.setToken(token); - // test the case where the principal is an AuthUserDetails object - AuthUserDetails authUserDetails = new AuthUserDetails(mosipUserDto, token); - when(authentication.getPrincipal()).thenReturn(authUserDetails); - } - - @Test - public void testGetAuthUserDetails() { - getAuthUserDetailsFromAuthentication(); - assertNotNull(ReflectionTestUtils.invokeMethod(identityService, "getAuthUserDetails")); - } - - @Test - public void testGetAuthUserDetailsPrincipalNull() { - Authentication authentication= Mockito.mock(Authentication.class); - SecurityContext securityContext = Mockito.mock(SecurityContext.class); - SecurityContextHolder.setContext(securityContext); - when(securityContext.getAuthentication()).thenReturn(authentication); - - MosipUserDto mosipUserDto = new MosipUserDto(); - mosipUserDto.setToken(token); - // test the case where the principal is an AuthUserDetails object - assertNull(ReflectionTestUtils.invokeMethod(identityService, "getAuthUserDetails")); - } - - @Test(expected = Exception.class) - public void testGetResidentIndividualIdInvalidToken() throws Exception { - Tuple3, Map> tuple3 = loadUserInfoMethod(); - - when(restClientWithPlainRestTemplate.getApi(tuple3.getT1(), String.class, tuple3.getT2())) - .thenReturn(objectMapper.writeValueAsString(tuple3.getT3())); - getAuthUserDetailsFromAuthentication(); - assertEquals("3956038419",identityService.getResidentIndvidualIdFromSession()); - } - - @Test(expected = Exception.class) - public void testGetResidentIndividualIdValidToken() throws Exception { - ImmutablePair verifySignagure = new ImmutablePair<>(true, AuthErrorCode.UNAUTHORIZED); - //Mockito.when(tokenValidationHelper.verifyJWTSignagure(Mockito.any())).thenReturn(verifySignagure); - //Mockito.when(objectStoreHelper.decryptData(Mockito.anyString(), Mockito.anyString(), Mockito.anyString())).thenReturn("Value"); - Tuple3, Map> tuple3 = loadUserInfoMethod(); - - when(restClientWithPlainRestTemplate.getApi(tuple3.getT1(), String.class, tuple3.getT2())) - .thenReturn(token); - getAuthUserDetailsFromAuthentication(); - assertEquals("3956038419",identityService.getResidentIndvidualIdFromSession()); - } - - @Test(expected = Exception.class) - public void testGetResidentIndividualIdValidTokenVerifySignatureFalse() throws Exception { - ImmutablePair verifySignagure = new ImmutablePair<>(false, AuthErrorCode.UNAUTHORIZED); - //Mockito.when(tokenValidationHelper.verifyJWTSignagure(Mockito.any())).thenReturn(verifySignagure); - Tuple3, Map> tuple3 = loadUserInfoMethod(); - - when(restClientWithPlainRestTemplate.getApi(tuple3.getT1(), String.class, tuple3.getT2())) - .thenReturn(token); - getAuthUserDetailsFromAuthentication(); - assertEquals("3956038419",identityService.getResidentIndvidualIdFromSession()); - } - - @Test - public void testGetResidentIndividualIdValidTokenSucess() throws Exception { - Tuple3, Map> tuple3 = loadUserInfoMethod(); - tuple3.getT3().put("individual_id", "3956038419"); - when(restClientWithPlainRestTemplate.getApi(tuple3.getT1(), String.class, tuple3.getT2())) - .thenReturn(objectMapper.writeValueAsString(tuple3.getT3())); - getAuthUserDetailsFromAuthentication(); - assertEquals("3956038419",identityService.getResidentIndvidualIdFromSession()); - } - - @Test - public void testGetResidentAuthenticationMode() throws Exception { - Tuple3, Map> tuple3 = loadUserInfoMethod(); - tuple3.getT3().put("individual_id", "3956038419"); - getAuthUserDetailsFromAuthentication(); - assertEquals("",ReflectionTestUtils.invokeMethod(identityService, - "getResidentAuthenticationMode")); - } - - @Test - public void testGetClaimFromAccessToken() throws Exception { - Tuple3, Map> tuple3 = loadUserInfoMethod(); - tuple3.getT3().put("individual_id", "3956038419"); - getAuthUserDetailsFromAuthentication(); - ReflectionTestUtils.invokeMethod(identityService, - "getClaimFromAccessToken", "value"); - } - - @Test - public void testGetIndividualIdTypeVidPassed(){ - Mockito.when(requestValidator.validateUin(Mockito.anyString())).thenReturn(false); - Mockito.when(requestValidator.validateVid(Mockito.anyString())).thenReturn(true); - assertEquals(IdType.VID.toString(), identityService.getIndividualIdType("2476302389")); - } - - @Test - public void testGetClaimValueFromJwtTokenFailed(){ - String claim = null; - assertEquals("", ReflectionTestUtils.invokeMethod(identityService, "getClaimValueFromJwtToken", - token, claim)); - } - - @Test(expected = Exception.class) - public void testGetIndividualIdForAidFailed() throws Exception{ - String aid = "123456789"; - Mockito.when(residentVidService.getPerpatualVid(Mockito.anyString())).thenReturn(Optional.empty()); - ReflectionTestUtils.setField(identityService, "useVidOnly", true); - fileLoadMethod(); - String result = ReflectionTestUtils.invokeMethod(identityService, "getIndividualIdForAid", aid); - assertEquals("123456789", result); - } - - -} diff --git a/resident/resident-service/src/test/java/io/mosip/resident/test/service/OrderCardServiceTest.java b/resident/resident-service/src/test/java/io/mosip/resident/test/service/OrderCardServiceTest.java deleted file mode 100644 index 39fe16885e0..00000000000 --- a/resident/resident-service/src/test/java/io/mosip/resident/test/service/OrderCardServiceTest.java +++ /dev/null @@ -1,174 +0,0 @@ -package io.mosip.resident.test.service; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.when; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; -import org.springframework.cloud.context.config.annotation.RefreshScope; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.util.ReflectionTestUtils; - -import io.mosip.kernel.core.http.ResponseWrapper; -import io.mosip.resident.constant.ApiName; -import io.mosip.resident.dto.NotificationResponseDTO; -import io.mosip.resident.dto.ResidentCredentialRequestDto; -import io.mosip.resident.dto.ResidentCredentialResponseDto; -import io.mosip.resident.dto.UrlRedirectRequestDTO; -import io.mosip.resident.entity.ResidentTransactionEntity; -import io.mosip.resident.exception.ApisResourceAccessException; -import io.mosip.resident.exception.ResidentServiceCheckedException; -import io.mosip.resident.repository.ResidentTransactionRepository; -import io.mosip.resident.service.NotificationService; -import io.mosip.resident.service.OrderCardService; -import io.mosip.resident.service.ResidentCredentialService; -import io.mosip.resident.service.impl.IdentityServiceImpl; -import io.mosip.resident.service.impl.OrderCardServiceImpl; -import io.mosip.resident.service.impl.ProxyPartnerManagementServiceImpl; -import io.mosip.resident.util.AuditUtil; -import io.mosip.resident.util.ResidentServiceRestClient; -import io.mosip.resident.util.Utility; - -/** - * Resident order card service test class. - * - * @author Ritik Jain - */ -@RunWith(MockitoJUnitRunner.class) -@RefreshScope -@ContextConfiguration -public class OrderCardServiceTest { - - @InjectMocks - private OrderCardService orderCardService = new OrderCardServiceImpl(); - - @Mock - private AuditUtil auditUtil; - - @Mock - private Utility utility; - - @Mock - private IdentityServiceImpl identityServiceImpl; - - @Mock - private ResidentTransactionRepository residentTransactionRepository; - - @Mock - private ResidentServiceRestClient restClientWithSelfTOkenRestTemplate; - - @Mock - private ResidentCredentialService residentCredentialService; - - @Mock - private NotificationService notificationService; - - @Mock - private ProxyPartnerManagementServiceImpl proxyPartnerManagementServiceImpl; - - private ResponseWrapper responseWrapper; - - private ResidentCredentialResponseDto residentCredentialResponseDto; - - private ResidentCredentialRequestDto residentCredentialRequestDto; - - private NotificationResponseDTO notificationResponseDTO; - - private Map partnerDetail = new HashMap<>(); - - private UrlRedirectRequestDTO urlRedirectRequestDTO; - - - @Before - public void setUp() throws Exception { - ReflectionTestUtils.setField(orderCardService, "isPaymentEnabled", true); - responseWrapper = new ResponseWrapper<>(); - responseWrapper.setVersion("v1"); - responseWrapper.setId("1"); - urlRedirectRequestDTO = new UrlRedirectRequestDTO(); - urlRedirectRequestDTO.setTrackingId("tracking123456"); - responseWrapper.setResponse(urlRedirectRequestDTO); - ResidentTransactionEntity residentTransactionEntity = new ResidentTransactionEntity(); - residentTransactionEntity.setEventId("5092d4bf-8f77-4608-a167-76371cc38b5d"); - when(utility.createEntity()).thenReturn(residentTransactionEntity); - when(identityServiceImpl.getResidentIndvidualIdFromSession()).thenReturn("8251649601"); - notificationResponseDTO = new NotificationResponseDTO(); - notificationResponseDTO.setStatus("Notification success"); - when(notificationService.sendNotification(Mockito.any())).thenReturn(notificationResponseDTO); - - residentCredentialRequestDto = new ResidentCredentialRequestDto(); - residentCredentialRequestDto.setTransactionID("1234327890"); - residentCredentialRequestDto.setConsent("Accepted"); - residentCredentialRequestDto.setSharableAttributes(List.of("firstName")); - residentCredentialResponseDto = new ResidentCredentialResponseDto(); - residentCredentialResponseDto.setId("8251649601"); - residentCredentialResponseDto.setRequestId("effc56cd-cf3b-4042-ad48-7277cf90f763"); - - } - - @Test - public void testSendPhysicalCard() throws Exception { - ReflectionTestUtils.setField(orderCardService, "isPaymentEnabled", false); - when(residentCredentialService.reqCredential(any(), any())).thenReturn(residentCredentialResponseDto); - ResidentCredentialResponseDto result = orderCardService.sendPhysicalCard(residentCredentialRequestDto); - assertEquals("effc56cd-cf3b-4042-ad48-7277cf90f763", result.getRequestId()); - } - - @Test - public void testSendPhysicalCardIf() throws Exception { - when(restClientWithSelfTOkenRestTemplate.getApi((ApiName) any(), (List) any(), (List) any(), - any(), any())).thenReturn(responseWrapper); - when(residentCredentialService.reqCredential(any(), any())).thenReturn(residentCredentialResponseDto); - - ResidentCredentialResponseDto result = orderCardService.sendPhysicalCard(residentCredentialRequestDto); - assertEquals("effc56cd-cf3b-4042-ad48-7277cf90f763", result.getRequestId()); - } - - @Test(expected = ResidentServiceCheckedException.class) - public void testCheckOrderStatusWithApisResourceAccessException() throws Exception { - when(restClientWithSelfTOkenRestTemplate.getApi((ApiName) any(), (List) any(), (List) any(), - any(), any())).thenThrow(new ApisResourceAccessException()); - orderCardService.sendPhysicalCard(residentCredentialRequestDto); - } - - @Test - public void testGetRedirectUrl() throws Exception { - Map detail = new HashMap<>(); - detail.put("orderRedirectUrl", "http://resident-partner-details.com"); - partnerDetail.put("additionalInfo", List.of(detail)); - when(proxyPartnerManagementServiceImpl.getPartnerDetailFromPartnerId(anyString())).thenReturn(partnerDetail); - String result = orderCardService.getRedirectUrl("12345","URI"); - assertNotNull(result); - } - - - @Test(expected = ResidentServiceCheckedException.class) - public void testGetRedirectUrlNull() throws Exception { - Map detail = new HashMap<>(); - detail.put("orderRedirectUrl", ""); - partnerDetail.put("additionalInfo", List.of(detail)); - when(proxyPartnerManagementServiceImpl.getPartnerDetailFromPartnerId(anyString())).thenReturn(partnerDetail); - orderCardService.getRedirectUrl("12345","URI"); - - } - - @Test(expected = ResidentServiceCheckedException.class) - public void testGetRedirectUrlEmpty() throws Exception { - when(proxyPartnerManagementServiceImpl.getPartnerDetailFromPartnerId(anyString())).thenReturn(partnerDetail); - orderCardService.getRedirectUrl("12345","URI"); - - } - -} \ No newline at end of file diff --git a/resident/resident-service/src/test/java/io/mosip/resident/test/service/PartnerServiceImplTest.java b/resident/resident-service/src/test/java/io/mosip/resident/test/service/PartnerServiceImplTest.java deleted file mode 100644 index 9e06784395c..00000000000 --- a/resident/resident-service/src/test/java/io/mosip/resident/test/service/PartnerServiceImplTest.java +++ /dev/null @@ -1,96 +0,0 @@ -package io.mosip.resident.test.service; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.when; - -import java.net.URI; -import java.net.URISyntaxException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.cloud.context.config.annotation.RefreshScope; -import org.springframework.core.env.Environment; -import org.springframework.http.HttpHeaders; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.util.ReflectionTestUtils; -import org.springframework.test.web.servlet.MockMvc; - -import io.mosip.kernel.core.http.ResponseWrapper; -import io.mosip.kernel.core.websub.spi.PublisherClient; -import io.mosip.kernel.core.websub.spi.SubscriptionClient; -import io.mosip.kernel.websub.api.model.SubscriptionChangeRequest; -import io.mosip.kernel.websub.api.model.SubscriptionChangeResponse; -import io.mosip.kernel.websub.api.model.UnsubscriptionRequest; -import io.mosip.resident.exception.ApisResourceAccessException; -import io.mosip.resident.exception.ResidentServiceCheckedException; -import io.mosip.resident.service.impl.IdentityServiceImpl; -import io.mosip.resident.service.impl.PartnerServiceImpl; -import io.mosip.resident.util.AuditUtil; -import io.mosip.resident.util.ResidentServiceRestClient; - -@RunWith(MockitoJUnitRunner.class) -@RefreshScope -@ContextConfiguration -public class PartnerServiceImplTest { - - @Mock - private ResidentServiceRestClient residentServiceRestClient; - - @Mock - Environment env; - - @Mock - private AuditUtil audit; - - @InjectMocks - private PartnerServiceImpl partnerService; - - @Mock - private IdentityServiceImpl identityServiceImpl; - - @Autowired - private MockMvc mockMvc; - - @Mock - private PublisherClient publisher; - - @Mock - SubscriptionClient subscribe; - - private ResponseWrapper> responseWrapper; - - @Before - public void setup() { - responseWrapper = new ResponseWrapper>(); - responseWrapper.setVersion("v1"); - responseWrapper.setId("1"); - Map partners = new HashMap<>(); - ArrayList partnerList = new ArrayList<>(); - Map individualPartner = new HashMap<>(); - individualPartner.put("partnerID", "1"); - partnerList.add(individualPartner); - partners.put("partners", partnerList); - responseWrapper.setResponse(partners); - } - - @Test - public void testPartnerService() throws ResidentServiceCheckedException, ApisResourceAccessException, URISyntaxException { - String partnerId = "Online_Verification_Partner"; - ArrayList partnerIds; - - ReflectionTestUtils.setField(partnerService, "partnerServiceUrl", "https://dev.mosip.net/v1/partnermanager/partners?partnerType=Online_Verification_Partner"); - URI uri = new URI("https://dev.mosip.net/v1/partnermanager/partners?partnerType=Online_Verification_Partner"); - when(residentServiceRestClient.getApi(uri, ResponseWrapper.class)) - .thenReturn(responseWrapper); - partnerIds=partnerService.getPartnerDetails(partnerId); - assertEquals(1, partnerIds.size()); - } -} \ No newline at end of file diff --git a/resident/resident-service/src/test/java/io/mosip/resident/test/service/PinUnpinStatusServiceTest.java b/resident/resident-service/src/test/java/io/mosip/resident/test/service/PinUnpinStatusServiceTest.java deleted file mode 100644 index c029b1ab93d..00000000000 --- a/resident/resident-service/src/test/java/io/mosip/resident/test/service/PinUnpinStatusServiceTest.java +++ /dev/null @@ -1,83 +0,0 @@ -package io.mosip.resident.test.service; - -import static org.junit.Assert.assertEquals; - -import java.util.Optional; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; -import org.springframework.cloud.context.config.annotation.RefreshScope; -import org.springframework.http.HttpStatus; -import org.springframework.test.context.ContextConfiguration; - -import io.mosip.kernel.core.http.ResponseWrapper; -import io.mosip.resident.constant.ResidentErrorCode; -import io.mosip.resident.dto.ResponseDTO; -import io.mosip.resident.entity.ResidentTransactionEntity; -import io.mosip.resident.repository.ResidentTransactionRepository; -import io.mosip.resident.service.PinUnpinStatusService; -import io.mosip.resident.service.impl.PinUnpinStatusServiceImpl; -import io.mosip.resident.util.AuditUtil; - -/** - * This class is used to test service class of pin or unpin status api based on event id. - * @Author Kamesh Shekhar Prasad - */ - -@RunWith(MockitoJUnitRunner.class) -@RefreshScope -@ContextConfiguration -public class PinUnpinStatusServiceTest { - - @InjectMocks - PinUnpinStatusService pinUnpinStatusService = new PinUnpinStatusServiceImpl(); - - @Mock - AuditUtil auditUtil; - - @Mock - ResidentTransactionRepository residentTransactionRepository; - - Optional residentTransactionEntity; - @Before - public void setup(){ - residentTransactionEntity = Optional.of(new ResidentTransactionEntity()); - residentTransactionEntity.get().setEventId("eventId"); - residentTransactionEntity.get().setPinnedStatus(true); - Mockito.when(residentTransactionRepository.findById(Mockito.anyString())).thenReturn(residentTransactionEntity); - } - - @Test - public void pinStatusSuccessTest(){ - ResponseWrapper responseDTO = pinUnpinStatusService.pinStatus("eventId", true); - assertEquals(responseDTO.getResponse().getStatus(), HttpStatus.OK.toString()); - } - - @Test - public void pinStatusFailureTest(){ - residentTransactionEntity = Optional.empty(); - Mockito.when(residentTransactionRepository.findById(Mockito.anyString())).thenReturn(residentTransactionEntity); - ResponseWrapper responseDTO = pinUnpinStatusService.pinStatus("eventId", true); - assertEquals(responseDTO.getErrors().get(0).getErrorCode(), ResidentErrorCode.EVENT_STATUS_NOT_FOUND.getErrorCode()); - } - - @Test - public void unPinStatusSuccessTest(){ - ResponseWrapper responseDTO = pinUnpinStatusService.pinStatus("eventId", false); - assertEquals(responseDTO.getResponse().getStatus(), HttpStatus.OK.toString()); - } - - @Test - public void unPinStatusFailureTest(){ - residentTransactionEntity = Optional.empty(); - Mockito.when(residentTransactionRepository.findById(Mockito.anyString())).thenReturn(residentTransactionEntity); - ResponseWrapper responseDTO = pinUnpinStatusService.pinStatus("eventId", false); - assertEquals(responseDTO.getErrors().get(0).getErrorCode(), ResidentErrorCode.EVENT_STATUS_NOT_FOUND.getErrorCode()); - } - -} diff --git a/resident/resident-service/src/test/java/io/mosip/resident/test/service/ProxyIdRepoServiceTest.java b/resident/resident-service/src/test/java/io/mosip/resident/test/service/ProxyIdRepoServiceTest.java deleted file mode 100644 index 3ef03f9b698..00000000000 --- a/resident/resident-service/src/test/java/io/mosip/resident/test/service/ProxyIdRepoServiceTest.java +++ /dev/null @@ -1,66 +0,0 @@ -package io.mosip.resident.test.service; - -import static org.junit.Assert.assertNotNull; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.when; - -import java.util.List; -import java.util.Map; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; -import org.springframework.test.context.ActiveProfiles; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.TestContext; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.web.context.WebApplicationContext; - -import io.mosip.kernel.core.http.ResponseWrapper; -import io.mosip.resident.exception.ApisResourceAccessException; -import io.mosip.resident.exception.ResidentServiceCheckedException; -import io.mosip.resident.service.impl.IdentityServiceImpl; -import io.mosip.resident.service.impl.ProxyIdRepoServiceImpl; -import io.mosip.resident.util.ResidentServiceRestClient; - -@ContextConfiguration(classes = { TestContext.class, WebApplicationContext.class }) -@RunWith(SpringRunner.class) -@WebMvcTest -@ActiveProfiles("test") -public class ProxyIdRepoServiceTest { - - @InjectMocks - private ProxyIdRepoServiceImpl service; - - @Mock - private ResidentServiceRestClient residentServiceRestClient; - - @Mock - private IdentityServiceImpl identityServiceImpl; - - @SuppressWarnings("unchecked") - @Test - public void testGetRemainingUpdateCountByIndividualId() - throws ResidentServiceCheckedException, ApisResourceAccessException { - ResponseWrapper responseWrapper = new ResponseWrapper<>(); - responseWrapper.setVersion("v1"); - responseWrapper.setId("1"); - when(identityServiceImpl.getResidentIndvidualIdFromSession()).thenReturn("8251649601"); - when(residentServiceRestClient.getApi(any(), (Map) any(), (List) any(), any(), any())) - .thenReturn(responseWrapper); - ResponseWrapper response = service.getRemainingUpdateCountByIndividualId(List.of()); - assertNotNull(response); - } - - @SuppressWarnings("unchecked") - @Test(expected = ResidentServiceCheckedException.class) - public void testGetRemainingUpdateCountByIndividualIdException() - throws ResidentServiceCheckedException, ApisResourceAccessException { - when(identityServiceImpl.getResidentIndvidualIdFromSession()).thenReturn("8251649601"); - when(residentServiceRestClient.getApi(any(), (Map) any(), (List) any(), any(), any())) - .thenThrow(new ApisResourceAccessException()); - service.getRemainingUpdateCountByIndividualId(List.of()); - } -} diff --git a/resident/resident-service/src/test/java/io/mosip/resident/test/service/ProxyMasterdataServiceTest.java b/resident/resident-service/src/test/java/io/mosip/resident/test/service/ProxyMasterdataServiceTest.java deleted file mode 100644 index 73180769f53..00000000000 --- a/resident/resident-service/src/test/java/io/mosip/resident/test/service/ProxyMasterdataServiceTest.java +++ /dev/null @@ -1,657 +0,0 @@ -package io.mosip.resident.test.service; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.when; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; -import org.springframework.cloud.context.config.annotation.RefreshScope; -import org.springframework.core.env.Environment; -import org.springframework.test.context.ContextConfiguration; - -import io.mosip.kernel.core.exception.ServiceError; -import io.mosip.kernel.core.http.ResponseWrapper; -import io.mosip.resident.constant.ApiName; -import io.mosip.resident.constant.OrderEnum; -import io.mosip.resident.dto.GenderCodeResponseDTO; -import io.mosip.resident.dto.GenderTypeDTO; -import io.mosip.resident.dto.GenderTypeListDTO; -import io.mosip.resident.dto.TemplateDto; -import io.mosip.resident.dto.TemplateResponseDto; -import io.mosip.resident.exception.ApisResourceAccessException; -import io.mosip.resident.exception.ResidentServiceCheckedException; -import io.mosip.resident.service.ProxyMasterdataService; -import io.mosip.resident.service.impl.ProxyMasterdataServiceImpl; -import io.mosip.resident.util.AuditUtil; -import io.mosip.resident.util.ResidentServiceRestClient; -import reactor.util.function.Tuple2; - -/** - * Resident proxy masterdata service test class. - * - * @author Ritik Jain - */ -@RunWith(MockitoJUnitRunner.class) -@RefreshScope -@ContextConfiguration -public class ProxyMasterdataServiceTest { - - @Mock - private Environment env; - - @Mock - private AuditUtil auditUtil; - - @Mock - private ResidentServiceRestClient residentServiceRestClient; - - @InjectMocks - private ProxyMasterdataService proxyMasterdataService = new ProxyMasterdataServiceImpl(); - - private ResponseWrapper responseWrapper; - - private ResponseWrapper templateWrapper; - - @Before - public void setup() { - responseWrapper = new ResponseWrapper<>(); - responseWrapper.setVersion("v1"); - responseWrapper.setId("1"); - templateWrapper = new ResponseWrapper<>(); - TemplateResponseDto templateResp = new TemplateResponseDto(); - TemplateDto templateDto = new TemplateDto(); - templateDto.setDescription("re print uin"); - templateDto.setFileText( - "Hi $name_eng,Your request for \"Reprint Of UIN\" has been successfully placed. Your RID (Req Number) is $RID."); - List templateList = new ArrayList<>(); - templateList.add(templateDto); - templateResp.setTemplates(templateList); - templateWrapper.setResponse(templateResp); - } - - @Test - public void testGetValidDocumentByLangCode() throws ApisResourceAccessException, ResidentServiceCheckedException { - when(residentServiceRestClient.getApi((ApiName) any(), any(), any())).thenReturn(responseWrapper); - ResponseWrapper result = proxyMasterdataService.getValidDocumentByLangCode("eng"); - assertNotNull(result); - } - - @Test(expected = ResidentServiceCheckedException.class) - public void testGetValidDocumentByLangCodeIf() throws ApisResourceAccessException, ResidentServiceCheckedException { - when(residentServiceRestClient.getApi((ApiName) any(), any(), any())).thenReturn(responseWrapper); - - ServiceError error = new ServiceError(); - error.setErrorCode("101"); - error.setMessage("errors"); - - List errorList = new ArrayList(); - errorList.add(error); - - responseWrapper.setErrors(errorList); - - proxyMasterdataService.getValidDocumentByLangCode("eng"); - } - - @Test - public void testGetValidDocumentByLangCodeElse() - throws ApisResourceAccessException, ResidentServiceCheckedException { - when(residentServiceRestClient.getApi((ApiName) any(), any(), any())).thenReturn(responseWrapper); - - responseWrapper.setErrors(null); - - ResponseWrapper result = proxyMasterdataService.getValidDocumentByLangCode("eng"); - assertNotNull(result); - } - - @Test(expected = ResidentServiceCheckedException.class) - public void testGetValidDocumentByLangCodeWithApisResourceAccessException() - throws ApisResourceAccessException, ResidentServiceCheckedException { - when(residentServiceRestClient.getApi((ApiName) (ApiName) any(), any(), any())) - .thenThrow(new ApisResourceAccessException()); - proxyMasterdataService.getValidDocumentByLangCode("eng"); - } - - @Test - public void testGetValidDocCatAndTypeList() throws ApisResourceAccessException, ResidentServiceCheckedException { - List> docCatList = new ArrayList<>(); - docCatList.add(Map.of("code", "poi", "documenttypes", List.of(Map.of("code", "cob")))); - docCatList.add(Map.of("code", "poa", "documenttypes", List.of(Map.of("code", "coa")))); - responseWrapper.setResponse(Map.of("documentcategories", docCatList)); - when(residentServiceRestClient.getApi((ApiName) any(), any(), any())).thenReturn(responseWrapper); - Tuple2, Map>> result = proxyMasterdataService - .getValidDocCatAndTypeList("eng"); - assertEquals("poi", result.getT1().get(0)); - assertEquals("coa", result.getT2().get("poa").get(0)); - } - - @Test - public void testGetLocationHierarchyLevelByLangCode() - throws ApisResourceAccessException, ResidentServiceCheckedException { - when(residentServiceRestClient.getApi((ApiName) (ApiName) any(), any(), any())).thenReturn(responseWrapper); - ResponseWrapper result = proxyMasterdataService.getLocationHierarchyLevelByLangCode("eng"); - assertNotNull(result); - } - - @Test(expected = ResidentServiceCheckedException.class) - public void testGetLocationHierarchyLevelByLangCodeIf() - throws ResidentServiceCheckedException, ApisResourceAccessException { - when(residentServiceRestClient.getApi((ApiName) (ApiName) any(), any(), any())).thenReturn(responseWrapper); - - ServiceError error = new ServiceError(); - error.setErrorCode("101"); - error.setMessage("errors"); - - List errorList = new ArrayList(); - errorList.add(error); - - responseWrapper.setErrors(errorList); - - proxyMasterdataService.getLocationHierarchyLevelByLangCode("eng"); - } - - @Test - public void testGetLocationHierarchyLevelByLangCodeElse() - throws ApisResourceAccessException, ResidentServiceCheckedException { - when(residentServiceRestClient.getApi((ApiName) (ApiName) any(), any(), any())).thenReturn(responseWrapper); - responseWrapper.setErrors(null); - ResponseWrapper result = proxyMasterdataService.getLocationHierarchyLevelByLangCode("eng"); - assertNotNull(result); - } - - @Test(expected = ResidentServiceCheckedException.class) - public void testGetLocationHierarchyLevelByLangCodeWithApisResourceAccessException() - throws ApisResourceAccessException, ResidentServiceCheckedException { - when(residentServiceRestClient.getApi((ApiName) any(), any(), any())) - .thenThrow(new ApisResourceAccessException()); - proxyMasterdataService.getLocationHierarchyLevelByLangCode("eng"); - } - - @Test - public void testGetImmediateChildrenByLocCodeAndLangCode() - throws ApisResourceAccessException, ResidentServiceCheckedException { - when(residentServiceRestClient.getApi((ApiName) any(), any(), any())).thenReturn(responseWrapper); - ResponseWrapper result = proxyMasterdataService.getImmediateChildrenByLocCodeAndLangCode("MOR", "eng"); - assertNotNull(result); - } - - @Test(expected = ResidentServiceCheckedException.class) - public void testGetImmediateChildrenByLocCodeAndLangCodeIf() - throws ApisResourceAccessException, ResidentServiceCheckedException { - when(residentServiceRestClient.getApi((ApiName) any(), any(), any())).thenReturn(responseWrapper); - - ServiceError error = new ServiceError(); - error.setErrorCode("101"); - error.setMessage("errors"); - - List errorList = new ArrayList(); - errorList.add(error); - - responseWrapper.setErrors(errorList); - - proxyMasterdataService.getImmediateChildrenByLocCodeAndLangCode("MOR", "eng"); - } - - @Test - public void testGetImmediateChildrenByLocCodeAndLangCodeElse() - throws ApisResourceAccessException, ResidentServiceCheckedException { - when(residentServiceRestClient.getApi((ApiName) any(), any(), any())).thenReturn(responseWrapper); - responseWrapper.setErrors(null); - ResponseWrapper result = proxyMasterdataService.getImmediateChildrenByLocCodeAndLangCode("MOR", "eng"); - assertNotNull(result); - } - - @Test(expected = ResidentServiceCheckedException.class) - public void testGetImmediateChildrenByLocCodeAndLangCodeWithApisResourceAccessException() - throws ApisResourceAccessException, ResidentServiceCheckedException { - when(residentServiceRestClient.getApi((ApiName) any(), any(), any())) - .thenThrow(new ApisResourceAccessException()); - proxyMasterdataService.getImmediateChildrenByLocCodeAndLangCode("MOR", "eng"); - } - - @Test - public void testGetLocationDetailsByLocCodeAndLangCode() - throws ApisResourceAccessException, ResidentServiceCheckedException { - when(residentServiceRestClient.getApi((ApiName) any(), any(), any())).thenReturn(responseWrapper); - ResponseWrapper result = proxyMasterdataService.getLocationDetailsByLocCodeAndLangCode("MOR", "eng"); - assertNotNull(result); - } - - @Test(expected = ResidentServiceCheckedException.class) - public void testGetLocationDetailsByLocCodeAndLangCodeIf() - throws ApisResourceAccessException, ResidentServiceCheckedException { - when(residentServiceRestClient.getApi((ApiName) any(), any(), any())).thenReturn(responseWrapper); - ServiceError error = new ServiceError(); - error.setErrorCode("101"); - error.setMessage("errors"); - - List errorList = new ArrayList(); - errorList.add(error); - - responseWrapper.setErrors(errorList); - proxyMasterdataService.getLocationDetailsByLocCodeAndLangCode("MOR", "eng"); - } - - @Test - public void testGetLocationDetailsByLocCodeAndLangCodeElse() - throws ApisResourceAccessException, ResidentServiceCheckedException { - when(residentServiceRestClient.getApi((ApiName) any(), any(), any())).thenReturn(responseWrapper); - responseWrapper.setErrors(null); - ResponseWrapper result = proxyMasterdataService.getLocationDetailsByLocCodeAndLangCode("MOR", "eng"); - assertNotNull(result); - } - - @Test(expected = ResidentServiceCheckedException.class) - public void testGetLocationDetailsByLocCodeAndLangCodeWithApisResourceAccessException() - throws ApisResourceAccessException, ResidentServiceCheckedException { - when(residentServiceRestClient.getApi((ApiName) any(), any(), any())) - .thenThrow(new ApisResourceAccessException()); - proxyMasterdataService.getLocationDetailsByLocCodeAndLangCode("MOR", "eng"); - } - - @Test - public void testGetCoordinateSpecificRegistrationCenters() - throws ApisResourceAccessException, ResidentServiceCheckedException { - when(residentServiceRestClient.getApi((ApiName) any(), any(), any())).thenReturn(responseWrapper); - ResponseWrapper result = proxyMasterdataService.getCoordinateSpecificRegistrationCenters("eng", -6.516428, - 34.287879, 2000); - assertNotNull(result); - } - - @Test(expected = ResidentServiceCheckedException.class) - public void testGetCoordinateSpecificRegistrationCentersIf() - throws ApisResourceAccessException, ResidentServiceCheckedException { - when(residentServiceRestClient.getApi((ApiName) any(), any(), any())).thenReturn(responseWrapper); - ServiceError error = new ServiceError(); - error.setErrorCode("101"); - error.setMessage("errors"); - - List errorList = new ArrayList(); - errorList.add(error); - - responseWrapper.setErrors(errorList); - proxyMasterdataService.getCoordinateSpecificRegistrationCenters("eng", -6.516428, 34.287879, 2000); - } - - @Test - public void testGetCoordinateSpecificRegistrationCentersElse() - throws ApisResourceAccessException, ResidentServiceCheckedException { - when(residentServiceRestClient.getApi((ApiName) any(), any(), any())).thenReturn(responseWrapper); - responseWrapper.setErrors(null); - ResponseWrapper result = proxyMasterdataService.getCoordinateSpecificRegistrationCenters("eng", -6.516428, - 34.287879, 2000); - assertNotNull(result); - } - - @Test(expected = ResidentServiceCheckedException.class) - public void testGetCoordinateSpecificRegistrationCentersWithApisResourceAccessException() - throws ApisResourceAccessException, ResidentServiceCheckedException { - when(residentServiceRestClient.getApi((ApiName) any(), any(), any())) - .thenThrow(new ApisResourceAccessException()); - proxyMasterdataService.getCoordinateSpecificRegistrationCenters("eng", -6.516428, 34.287879, 2000); - } - - @Test - public void testGetApplicantValidDocument() throws ApisResourceAccessException, ResidentServiceCheckedException { - when(residentServiceRestClient.getApi((ApiName) any(), (Map) any(), (List) any(), any(), - any())).thenReturn(responseWrapper); - ResponseWrapper result = proxyMasterdataService.getApplicantValidDocument("002", List.of("eng", "ara")); - assertNotNull(result); - } - - @Test(expected = ResidentServiceCheckedException.class) - public void testGetApplicantValidDocumentIf() throws ApisResourceAccessException, ResidentServiceCheckedException { - when(residentServiceRestClient.getApi((ApiName) any(), (Map) any(), (List) any(), any(), - any())).thenReturn(responseWrapper); - ServiceError error = new ServiceError(); - error.setErrorCode("101"); - error.setMessage("errors"); - - List errorList = new ArrayList(); - errorList.add(error); - - responseWrapper.setErrors(errorList); - proxyMasterdataService.getApplicantValidDocument("002", List.of("eng", "ara")); - } - - @Test - public void testGetApplicantValidDocumentElse() - throws ApisResourceAccessException, ResidentServiceCheckedException { - when(residentServiceRestClient.getApi((ApiName) any(), (Map) any(), (List) any(), any(), - any())).thenReturn(responseWrapper); - responseWrapper.setErrors(null); - ResponseWrapper result = proxyMasterdataService.getApplicantValidDocument("002", List.of("eng", "ara")); - assertNotNull(result); - } - - @Test(expected = ResidentServiceCheckedException.class) - public void testGetApplicantValidDocumentWithApisResourceAccessException() - throws ApisResourceAccessException, ResidentServiceCheckedException { - when(residentServiceRestClient.getApi((ApiName) any(), (Map) any(), (List) any(), any(), - any())).thenThrow(new ApisResourceAccessException()); - proxyMasterdataService.getApplicantValidDocument("002", List.of("eng", "ara")); - } - - @Test - public void testGetRegistrationCentersByHierarchyLevel() - throws ApisResourceAccessException, ResidentServiceCheckedException { - when(residentServiceRestClient.getApi((ApiName) any(), (Map) any(), (List) any(), any(), - any())).thenReturn(responseWrapper); - ResponseWrapper result = proxyMasterdataService.getRegistrationCentersByHierarchyLevel("eng", (short) 5, - List.of("14110", "14080")); - assertNotNull(result); - } - - @Test(expected = ResidentServiceCheckedException.class) - public void testGetRegistrationCentersByHierarchyLevelIf() - throws ApisResourceAccessException, ResidentServiceCheckedException { - when(residentServiceRestClient.getApi((ApiName) any(), (Map) any(), (List) any(), any(), - any())).thenReturn(responseWrapper); - ServiceError error = new ServiceError(); - error.setErrorCode("101"); - error.setMessage("errors"); - - List errorList = new ArrayList(); - errorList.add(error); - - responseWrapper.setErrors(errorList); - proxyMasterdataService.getRegistrationCentersByHierarchyLevel("eng", (short) 5, List.of("14110", "14080")); - } - - @Test - public void testGetRegistrationCentersByHierarchyLevelElse() - throws ApisResourceAccessException, ResidentServiceCheckedException { - when(residentServiceRestClient.getApi((ApiName) any(), (Map) any(), (List) any(), any(), - any())).thenReturn(responseWrapper); - responseWrapper.setErrors(null); - ResponseWrapper result = proxyMasterdataService.getRegistrationCentersByHierarchyLevel("eng", (short) 5, - List.of("14110", "14080")); - assertNotNull(result); - } - - @Test(expected = ResidentServiceCheckedException.class) - public void testGetRegistrationCentersByHierarchyLevelWithApisResourceAccessException() - throws ApisResourceAccessException, ResidentServiceCheckedException { - when(residentServiceRestClient.getApi((ApiName) any(), (Map) any(), (List) any(), any(), - any())).thenThrow(new ApisResourceAccessException()); - proxyMasterdataService.getRegistrationCentersByHierarchyLevel("eng", (short) 5, List.of("14110", "14080")); - } - - @Test - public void testGetRegistrationCenterByHierarchyLevelAndTextPaginated() - throws ApisResourceAccessException, ResidentServiceCheckedException { - when(residentServiceRestClient.getApi((ApiName) any(), (Map) any(), (List) any(), any(), - any())).thenReturn(responseWrapper); - ResponseWrapper result = proxyMasterdataService.getRegistrationCenterByHierarchyLevelAndTextPaginated("eng", - (short) 5, "14110", 0, 10, OrderEnum.desc, "createdDateTime"); - assertNotNull(result); - } - - @Test(expected = ResidentServiceCheckedException.class) - public void testGetRegistrationCenterByHierarchyLevelAndTextPaginatedIf() - throws ApisResourceAccessException, ResidentServiceCheckedException { - when(residentServiceRestClient.getApi((ApiName) any(), (Map) any(), (List) any(), any(), - any())).thenReturn(responseWrapper); - ServiceError error = new ServiceError(); - error.setErrorCode("101"); - error.setMessage("errors"); - - List errorList = new ArrayList(); - errorList.add(error); - - responseWrapper.setErrors(errorList); - proxyMasterdataService.getRegistrationCenterByHierarchyLevelAndTextPaginated("eng", (short) 5, "14110", 0, 10, - OrderEnum.desc, "createdDateTime"); - } - - @Test - public void testGetRegistrationCenterByHierarchyLevelAndTextPaginatedElse() - throws ApisResourceAccessException, ResidentServiceCheckedException { - when(residentServiceRestClient.getApi((ApiName) any(), (Map) any(), (List) any(), any(), - any())).thenReturn(responseWrapper); - responseWrapper.setErrors(null); - ResponseWrapper result = proxyMasterdataService.getRegistrationCenterByHierarchyLevelAndTextPaginated("eng", - (short) 5, "14110", 0, 10, OrderEnum.desc, "createdDateTime"); - assertNotNull(result); - } - - @Test(expected = ResidentServiceCheckedException.class) - public void testGetRegistrationCenterByHierarchyLevelAndTextPaginatedWithApisResourceAccessException() - throws ApisResourceAccessException, ResidentServiceCheckedException { - when(residentServiceRestClient.getApi((ApiName) any(), (Map) any(), (List) any(), any(), - any())).thenThrow(new ApisResourceAccessException()); - proxyMasterdataService.getRegistrationCenterByHierarchyLevelAndTextPaginated("eng", (short) 5, "14110", 0, 10, - OrderEnum.desc, "createdDateTime"); - } - - @Test - public void testGetRegistrationCenterWorkingDays() - throws ApisResourceAccessException, ResidentServiceCheckedException { - when(residentServiceRestClient.getApi((ApiName) any(), any(), any())).thenReturn(responseWrapper); - ResponseWrapper result = proxyMasterdataService.getRegistrationCenterWorkingDays("10002", "eng"); - assertNotNull(result); - } - - @Test(expected = ResidentServiceCheckedException.class) - public void testGetRegistrationCenterWorkingDaysIf() - throws ApisResourceAccessException, ResidentServiceCheckedException { - when(residentServiceRestClient.getApi((ApiName) any(), any(), any())).thenReturn(responseWrapper); - ServiceError error = new ServiceError(); - error.setErrorCode("101"); - error.setMessage("errors"); - - List errorList = new ArrayList(); - errorList.add(error); - - responseWrapper.setErrors(errorList); - proxyMasterdataService.getRegistrationCenterWorkingDays("10002", "eng"); - } - - @Test - public void testGetRegistrationCenterWorkingDaysElse() - throws ApisResourceAccessException, ResidentServiceCheckedException { - when(residentServiceRestClient.getApi((ApiName) any(), any(), any())).thenReturn(responseWrapper); - responseWrapper.setErrors(null); - ResponseWrapper result = proxyMasterdataService.getRegistrationCenterWorkingDays("10002", "eng"); - assertNotNull(result); - } - - @Test(expected = ResidentServiceCheckedException.class) - public void testGetRegistrationCenterWorkingDaysWithApisResourceAccessException() - throws ApisResourceAccessException, ResidentServiceCheckedException { - when(residentServiceRestClient.getApi((ApiName) any(), any(), any())) - .thenThrow(new ApisResourceAccessException()); - proxyMasterdataService.getRegistrationCenterWorkingDays("10002", "eng"); - } - - @Test - public void testGetLatestIdSchema() throws ApisResourceAccessException, ResidentServiceCheckedException { - when(residentServiceRestClient.getApi((ApiName) any(), (List) any(), (List) any(), any(), - any())).thenReturn(responseWrapper); - ResponseWrapper result = proxyMasterdataService.getLatestIdSchema(0, "domain", "type"); - assertNotNull(result); - } - - @Test(expected = ResidentServiceCheckedException.class) - public void testGetLatestIdSchemaIf() throws ApisResourceAccessException, ResidentServiceCheckedException { - when(residentServiceRestClient.getApi((ApiName) any(), (List) any(), (List) any(), any(), - any())).thenReturn(responseWrapper); - ServiceError error = new ServiceError(); - error.setErrorCode("101"); - error.setMessage("errors"); - - List errorList = new ArrayList(); - errorList.add(error); - - responseWrapper.setErrors(errorList); - proxyMasterdataService.getLatestIdSchema(0, "domain", "type"); - } - - @Test - public void testGetLatestIdSchemaElse() throws ApisResourceAccessException, ResidentServiceCheckedException { - when(residentServiceRestClient.getApi((ApiName) any(), (List) any(), (List) any(), any(), - any())).thenReturn(responseWrapper); - responseWrapper.setErrors(null); - ResponseWrapper result = proxyMasterdataService.getLatestIdSchema(0, "domain", "type"); - assertNotNull(result); - } - - @Test(expected = ResidentServiceCheckedException.class) - public void testGetLatestIdSchemaWithApisResourceAccessException() - throws ApisResourceAccessException, ResidentServiceCheckedException { - when(residentServiceRestClient.getApi((ApiName) any(), (List) any(), (List) any(), any(), - any())).thenThrow(new ApisResourceAccessException()); - proxyMasterdataService.getLatestIdSchema(0, "domain", "type"); - } - - @Test - public void testGetAllTemplateBylangCodeAndTemplateTypeCode() - throws ApisResourceAccessException, ResidentServiceCheckedException { - when(residentServiceRestClient.getApi((ApiName) any(), (Map) any(), any())).thenReturn(templateWrapper); - ResponseWrapper result = proxyMasterdataService.getAllTemplateBylangCodeAndTemplateTypeCode("eng", - "otp-template"); - assertNotNull(result); - } - - @Test(expected = ResidentServiceCheckedException.class) - public void testGetAllTemplateBylangCodeAndTemplateTypeCodeIf() - throws ApisResourceAccessException, ResidentServiceCheckedException { - when(residentServiceRestClient.getApi((ApiName) any(), (Map) any(), any())).thenReturn(templateWrapper); - ServiceError error = new ServiceError(); - error.setErrorCode("101"); - error.setMessage("errors"); - - List errorList = new ArrayList(); - errorList.add(error); - - templateWrapper.setErrors(errorList); - proxyMasterdataService.getAllTemplateBylangCodeAndTemplateTypeCode("eng", "otp-template"); - } - - @Test - public void testGetAllTemplateBylangCodeAndTemplateTypeCodeElse() - throws ApisResourceAccessException, ResidentServiceCheckedException { - when(residentServiceRestClient.getApi((ApiName) any(), (Map) any(), any())).thenReturn(templateWrapper); - templateWrapper.setErrors(null); - ResponseWrapper result = proxyMasterdataService.getAllTemplateBylangCodeAndTemplateTypeCode("eng", - "otp-template"); - assertNotNull(result); - } - - @Test(expected = ResidentServiceCheckedException.class) - public void testGetAllTemplateBylangCodeAndTemplateTypeCodeWithApisResourceAccessException() - throws ApisResourceAccessException, ResidentServiceCheckedException { - when(residentServiceRestClient.getApi((ApiName) any(), (Map) any(), any())) - .thenThrow(new ApisResourceAccessException()); - proxyMasterdataService.getAllTemplateBylangCodeAndTemplateTypeCode("eng", "otp-template"); - } - - @Test - public void testGetGenderTypesByLangCode() throws ApisResourceAccessException, ResidentServiceCheckedException { - when(residentServiceRestClient.getApi((ApiName) any(), any(), any())).thenReturn(responseWrapper); - ResponseWrapper result = proxyMasterdataService.getGenderTypesByLangCode("eng"); - assertNotNull(result); - } - - @Test(expected = ResidentServiceCheckedException.class) - public void testGetGenderTypesByLangCodeIf() throws ApisResourceAccessException, ResidentServiceCheckedException { - when(residentServiceRestClient.getApi((ApiName) any(), any(), any())).thenReturn(responseWrapper); - ServiceError error = new ServiceError(); - error.setErrorCode("101"); - error.setMessage("errors"); - - List errorList = new ArrayList(); - errorList.add(error); - - responseWrapper.setErrors(errorList); - proxyMasterdataService.getGenderTypesByLangCode("xyz"); - } - - @Test - public void testGetGenderTypesByLangCodeElse() throws ApisResourceAccessException, ResidentServiceCheckedException { - when(residentServiceRestClient.getApi((ApiName) any(), any(), any())).thenReturn(responseWrapper); - responseWrapper.setErrors(null); - ResponseWrapper result = proxyMasterdataService.getGenderTypesByLangCode("eng"); - assertNotNull(result); - } - - @Test(expected = ResidentServiceCheckedException.class) - public void testGetGenderTypesByLangCodeWithApisResourceAccessException() - throws ApisResourceAccessException, ResidentServiceCheckedException { - when(residentServiceRestClient.getApi((ApiName) any(), any(), any())) - .thenThrow(new ApisResourceAccessException()); - proxyMasterdataService.getGenderTypesByLangCode("eng"); - } - - @Test - public void testGetDocumentTypesByDocumentCategoryAndLangCode() throws ApisResourceAccessException, ResidentServiceCheckedException { - when(residentServiceRestClient.getApi((ApiName) any(), any(), any())).thenReturn(responseWrapper); - ResponseWrapper result = proxyMasterdataService.getDocumentTypesByDocumentCategoryAndLangCode("DOC","eng"); - assertNotNull(result); - } - - @Test(expected = ResidentServiceCheckedException.class) - public void testGetDocumentTypesByDocumentCategoryAndLangCodeIf() throws ApisResourceAccessException, ResidentServiceCheckedException { - when(residentServiceRestClient.getApi((ApiName) any(), any(), any())).thenReturn(responseWrapper); - ServiceError error = new ServiceError(); - error.setErrorCode("101"); - error.setMessage("errors"); - - List errorList = new ArrayList(); - errorList.add(error); - - responseWrapper.setErrors(errorList); - proxyMasterdataService.getDocumentTypesByDocumentCategoryAndLangCode("DOC","xyz"); - } - - @Test - public void testGetDocumentTypesByDocumentCategoryAndLangCodeElse() throws ApisResourceAccessException, ResidentServiceCheckedException { - when(residentServiceRestClient.getApi((ApiName) any(), any(), any())).thenReturn(responseWrapper); - responseWrapper.setErrors(null); - ResponseWrapper result = proxyMasterdataService.getDocumentTypesByDocumentCategoryAndLangCode("DOC","eng"); - assertNotNull(result); - } - - @Test(expected = ResidentServiceCheckedException.class) - public void testGetDocumentTypesByDocumentCategoryAndLangCodeWithApisResourceAccessException() - throws ApisResourceAccessException, ResidentServiceCheckedException { - when(residentServiceRestClient.getApi((ApiName) any(), any(), any())) - .thenThrow(new ApisResourceAccessException()); - proxyMasterdataService.getDocumentTypesByDocumentCategoryAndLangCode("DOC","eng"); - } - - @Test - public void testGetGenderCodeByGenderTypeAndLangCode() - throws ApisResourceAccessException, ResidentServiceCheckedException, IOException { - GenderTypeListDTO response = new GenderTypeListDTO(); - GenderTypeDTO genderTypeDTO = new GenderTypeDTO("MLE","Male","eng","true"); - response.setGenderType(List.of(genderTypeDTO)); - ResponseWrapper res = new ResponseWrapper(); - res.setResponse(response); - when(residentServiceRestClient.getApi((ApiName) any(), any(), any())).thenReturn(res); - ResponseWrapper responseWrapper = proxyMasterdataService.getGenderCodeByGenderTypeAndLangCode("Male", "eng"); - assertEquals(genderTypeDTO.getCode(),responseWrapper.getResponse().getGenderCode()); - } - - @Test - public void testGetGenderCodeByGenderTypeAndLangCodeNoValue() - throws ApisResourceAccessException, ResidentServiceCheckedException, IOException { - GenderTypeListDTO response = new GenderTypeListDTO(); - response.setGenderType(List.of()); - ResponseWrapper res = new ResponseWrapper(); - res.setResponse(response); - when(residentServiceRestClient.getApi((ApiName) any(), any(), any())).thenReturn(res); - ResponseWrapper responseWrapper = proxyMasterdataService.getGenderCodeByGenderTypeAndLangCode("Male", "eng"); - } - -} diff --git a/resident/resident-service/src/test/java/io/mosip/resident/test/service/ProxyPartnerManagementServiceTest.java b/resident/resident-service/src/test/java/io/mosip/resident/test/service/ProxyPartnerManagementServiceTest.java deleted file mode 100644 index ffeef034369..00000000000 --- a/resident/resident-service/src/test/java/io/mosip/resident/test/service/ProxyPartnerManagementServiceTest.java +++ /dev/null @@ -1,116 +0,0 @@ -package io.mosip.resident.test.service; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.when; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Optional; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; -import org.springframework.cloud.context.config.annotation.RefreshScope; -import org.springframework.test.context.ContextConfiguration; - -import io.mosip.kernel.core.exception.ServiceError; -import io.mosip.kernel.core.http.ResponseWrapper; -import io.mosip.resident.exception.ApisResourceAccessException; -import io.mosip.resident.exception.ResidentServiceCheckedException; -import io.mosip.resident.exception.ResidentServiceException; -import io.mosip.resident.service.ProxyPartnerManagementService; -import io.mosip.resident.service.impl.ProxyPartnerManagementServiceImpl; -import io.mosip.resident.util.AuditUtil; -import io.mosip.resident.util.ResidentServiceRestClient; - -/** - * Resident proxy partner management service test class. - * - * @author Ritik Jain - */ -@RunWith(MockitoJUnitRunner.class) -@RefreshScope -@ContextConfiguration -public class ProxyPartnerManagementServiceTest { - - @Mock - private AuditUtil auditUtil; - - @Mock - private ResidentServiceRestClient residentServiceRestClient; - - @InjectMocks - private ProxyPartnerManagementService proxyPartnerManagementService = new ProxyPartnerManagementServiceImpl(); - - private ResponseWrapper responseWrapper; - - @Before - public void setUp() throws Exception { - Map partnerMap=new HashMap<>(); - partnerMap.put("partnerID", "2345671"); - responseWrapper = new ResponseWrapper<>(); - responseWrapper.setVersion("v1"); - responseWrapper.setId("1"); - responseWrapper.setResponse(Map.of("partners",List.of(partnerMap))); - when(residentServiceRestClient.getApi(any(), (List) any(), (List) any(), any(), any())) - .thenReturn(responseWrapper); - } - - @Test - public void testGetPartnersByPartnerType() throws ApisResourceAccessException, ResidentServiceCheckedException { - responseWrapper.setErrors(null); - ResponseWrapper result = proxyPartnerManagementService - .getPartnersByPartnerType(Optional.of("Device_Provider")); - assertNotNull(result); - } - - @Test - public void testGetPartnersByPartnerTypeIf() throws ApisResourceAccessException, ResidentServiceCheckedException { - ResponseWrapper result = proxyPartnerManagementService - .getPartnersByPartnerType(Optional.empty()); - assertNotNull(result); - } - - @Test(expected = ResidentServiceCheckedException.class) - public void testGetPartnersByPartnerTypeNestedIf() - throws ApisResourceAccessException, ResidentServiceCheckedException { - ServiceError error = new ServiceError(); - error.setErrorCode("101"); - error.setMessage("errors"); - - List errorList = new ArrayList(); - errorList.add(error); - - responseWrapper.setErrors(errorList); - proxyPartnerManagementService.getPartnersByPartnerType(Optional.of("Device_Provider")); - } - - @Test(expected = ResidentServiceCheckedException.class) - public void testGetPartnersByPartnerTypeWithApisResourceAccessException() - throws ApisResourceAccessException, ResidentServiceCheckedException { - when(residentServiceRestClient.getApi(any(), (List) any(), (List) any(), any(), any())) - .thenThrow(new ApisResourceAccessException()); - proxyPartnerManagementService.getPartnersByPartnerType(Optional.of("Device_Provider")); - } - - @Test - public void testGetPartnerDetailFromPartnerId() throws ResidentServiceCheckedException { - Map result = proxyPartnerManagementService.getPartnerDetailFromPartnerId("2345671"); - assertEquals("2345671", result.get("partnerID")); - } - - @Test(expected = ResidentServiceException.class) - public void testGetPartnerDetailFromPartnerIdException() throws ResidentServiceCheckedException, ApisResourceAccessException { - when(residentServiceRestClient.getApi(any(), (List) any(), (List) any(), any(), any())) - .thenThrow(new ApisResourceAccessException()); - proxyPartnerManagementService.getPartnerDetailFromPartnerId(""); - } - -} diff --git a/resident/resident-service/src/test/java/io/mosip/resident/test/service/ResidentServiceDownloadCardTest.java b/resident/resident-service/src/test/java/io/mosip/resident/test/service/ResidentServiceDownloadCardTest.java deleted file mode 100644 index 081d5e600db..00000000000 --- a/resident/resident-service/src/test/java/io/mosip/resident/test/service/ResidentServiceDownloadCardTest.java +++ /dev/null @@ -1,386 +0,0 @@ -package io.mosip.resident.test.service; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.when; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.math.BigInteger; -import java.net.URI; -import java.nio.charset.StandardCharsets; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Optional; - -import javax.persistence.EntityManager; -import javax.persistence.Query; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.springframework.core.env.Environment; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.PageImpl; -import org.springframework.http.HttpStatus; -import org.springframework.test.context.junit4.SpringRunner; - -import io.mosip.kernel.core.http.ResponseWrapper; -import io.mosip.kernel.core.templatemanager.spi.TemplateManager; -import io.mosip.resident.constant.ApiName; -import io.mosip.resident.constant.RequestType; -import io.mosip.resident.constant.ResidentConstants; -import io.mosip.resident.dto.BellNotificationDto; -import io.mosip.resident.dto.DigitalCardStatusResponseDto; -import io.mosip.resident.dto.PageDto; -import io.mosip.resident.dto.ServiceHistoryResponseDto; -import io.mosip.resident.dto.UnreadNotificationDto; -import io.mosip.resident.dto.UserInfoDto; -import io.mosip.resident.entity.ResidentSessionEntity; -import io.mosip.resident.entity.ResidentTransactionEntity; -import io.mosip.resident.entity.ResidentUserEntity; -import io.mosip.resident.exception.ApisResourceAccessException; -import io.mosip.resident.exception.EventIdNotPresentException; -import io.mosip.resident.exception.InvalidRequestTypeCodeException; -import io.mosip.resident.exception.ResidentServiceCheckedException; -import io.mosip.resident.exception.ResidentServiceException; -import io.mosip.resident.helper.ObjectStoreHelper; -import io.mosip.resident.repository.ResidentSessionRepository; -import io.mosip.resident.repository.ResidentTransactionRepository; -import io.mosip.resident.repository.ResidentUserRepository; -import io.mosip.resident.service.ProxyMasterdataService; -import io.mosip.resident.service.impl.IdentityServiceImpl; -import io.mosip.resident.service.impl.ResidentCredentialServiceImpl; -import io.mosip.resident.service.impl.ResidentServiceImpl; -import io.mosip.resident.util.AuditUtil; -import io.mosip.resident.util.ResidentServiceRestClient; -import io.mosip.resident.util.TemplateUtil; -import io.mosip.resident.util.Utility; - -/** - * @author Kamesh Shekhar Prasad - * Test class to test download card service method. - */ - -@RunWith(SpringRunner.class) -public class ResidentServiceDownloadCardTest { - - @InjectMocks - private ResidentServiceImpl residentServiceImpl; - @Mock - private ResidentTransactionRepository residentTransactionRepository; - - @Mock - private ResidentCredentialServiceImpl residentCredentialServiceImpl; - - @Mock - private AuditUtil audit; - - @Mock - private Environment environment; - - @Mock - private ResidentServiceRestClient residentServiceRestClient; - - @Mock - private ObjectStoreHelper objectStoreHelper; - - @Mock - private TemplateUtil templateUtil; - - @Mock - private IdentityServiceImpl identityServiceImpl; - - @Mock - private ResidentUserRepository residentUserRepository; - - @Mock - private ResidentSessionRepository residentSessionRepository; - - @Mock - private ProxyMasterdataService proxyMasterdataService; - - @Mock - private TemplateManager templateManager; - - @Mock - private EntityManager entityManager; - - @Mock - private Utility utility; - - private byte[] result; - private String eventId; - private String idType; - private String resultResponse; - - private Query query; - private Optional residentTransactionEntity; - private ResponseWrapper responseDto; - DigitalCardStatusResponseDto digitalCardStatusResponseDto; - - @Before - public void setup() throws Exception { - result = "data".getBytes(); - eventId = "123"; - idType = "RID"; - resultResponse = "[B@3a7e365"; - residentTransactionEntity = Optional.of(new ResidentTransactionEntity()); - residentTransactionEntity.get().setEventId(eventId); - residentTransactionEntity.get().setRequestTypeCode(RequestType.UPDATE_MY_UIN.toString()); - residentTransactionEntity.get().setAid(eventId); - digitalCardStatusResponseDto = new DigitalCardStatusResponseDto(); - responseDto = new ResponseWrapper<>(); - digitalCardStatusResponseDto.setId(eventId); - digitalCardStatusResponseDto.setStatusCode(HttpStatus.OK.toString()); - digitalCardStatusResponseDto.setUrl("http://datashare.datashare/123"); - responseDto.setResponse(digitalCardStatusResponseDto); - responseDto.setVersion("v1"); - responseDto.setId("io.mosip.digital.card"); - Mockito.when(residentTransactionRepository.findById(Mockito.anyString())).thenReturn(residentTransactionEntity); - Mockito.when(residentCredentialServiceImpl.getCard(Mockito.anyString())).thenReturn(result); - Mockito.when(residentCredentialServiceImpl.getCard("123", null, null)).thenReturn(result); - Mockito.when(environment.getProperty(Mockito.anyString())).thenReturn(ApiName.DIGITAL_CARD_STATUS_URL.toString()); - Mockito.when(residentServiceRestClient.getApi((URI)any(), any(Class.class))).thenReturn(responseDto); - Mockito.when(objectStoreHelper.decryptData(Mockito.anyString(), Mockito.anyString(), Mockito.anyString())).thenReturn("ZGF0YQ=="); - query = Mockito.mock(Query.class); - Mockito.when(entityManager.createNativeQuery(Mockito.anyString(), (Class) Mockito.any())).thenReturn(query); - Mockito.when(entityManager.createNativeQuery(Mockito.anyString())).thenReturn(query); - Mockito.when(query.getSingleResult()).thenReturn(BigInteger.valueOf(1)); - } - - @Test - public void testUpdateMyUinSuccess() throws Exception { - residentTransactionEntity = Optional.of(new ResidentTransactionEntity()); - residentTransactionEntity.get().setEventId(eventId); - residentTransactionEntity.get().setRequestTypeCode(RequestType.UPDATE_MY_UIN.name()); - residentTransactionEntity.get().setAid(eventId); - Mockito.when(residentTransactionRepository.findById(Mockito.anyString())).thenReturn(residentTransactionEntity); - digitalCardStatusResponseDto.setStatusCode("AVAILABLE"); - String digitalCardStatusUri= "http://datashare.datashare/123"; - digitalCardStatusResponseDto.setUrl(digitalCardStatusUri); - responseDto.setResponse(digitalCardStatusResponseDto); - responseDto.setVersion("v1"); - responseDto.setId("io.mosip.digital.card"); - Mockito.when(residentTransactionRepository.findById(Mockito.anyString())).thenReturn(residentTransactionEntity); - Mockito.when(residentCredentialServiceImpl.getCard(Mockito.anyString())).thenReturn(result); - Mockito.when(environment.getProperty(Mockito.anyString())).thenReturn(ApiName.DIGITAL_CARD_STATUS_URL.toString()); - when(residentServiceRestClient.getApi(URI.create(ApiName.DIGITAL_CARD_STATUS_URL.name()+eventId),ResponseWrapper.class)).thenReturn(responseDto); - when(residentServiceRestClient.getApi(URI.create(digitalCardStatusUri), byte[].class)) - .thenReturn("data".getBytes()); - byte[] response = residentServiceImpl.downloadCard(eventId); - assertNotNull(response); - } - - @Test(expected = EventIdNotPresentException.class) - public void testEventIdNotPresentException() throws ResidentServiceCheckedException { - Mockito.when(residentTransactionRepository.findById(Mockito.anyString())).thenReturn(Optional.empty()); - byte[] response = residentServiceImpl.downloadCard(eventId); - assertEquals(response, result); - } - - @Test(expected = InvalidRequestTypeCodeException.class) - public void testInvalidRequestTypeCodeException() throws ResidentServiceCheckedException { - residentTransactionEntity = Optional.of(new ResidentTransactionEntity()); - residentTransactionEntity.get().setEventId(eventId); - residentTransactionEntity.get().setRequestTypeCode(RequestType.REVOKE_VID.name()); - residentTransactionEntity.get().setAid(eventId); - Mockito.when(residentTransactionRepository.findById(Mockito.anyString())).thenReturn(residentTransactionEntity); - byte[] response = residentServiceImpl.downloadCard(eventId); - assertEquals(response, result); - } - - @Test - public void testGetUserInfo() throws ApisResourceAccessException{ - Mockito.when(identityServiceImpl.getClaimFromIdToken(Mockito.anyString())).thenReturn("claim"); - ResidentSessionEntity residentUserEntity = new ResidentSessionEntity(); - residentUserEntity.setHost("localhost"); - residentUserEntity.setIdaToken("123"); - residentUserEntity.setIpAddress("http"); - residentUserEntity.setSessionId("123");; - Optional response = Optional.of(residentUserEntity); - Mockito.when(residentSessionRepository.findFirst2ByIdaTokenOrderByLoginDtimesDesc(Mockito.anyString())).thenReturn(List.of(residentUserEntity)); - ResponseWrapper responseWrapper = residentServiceImpl.getUserinfo("123", 0); - assertEquals(responseWrapper.getResponse().getFullName(), responseWrapper.getResponse().getFullName()); - } - - @Test(expected = ResidentServiceException.class) - public void testGetUserInfoFailed() throws ApisResourceAccessException { - Mockito.when(identityServiceImpl.getClaimFromIdToken(Mockito.anyString())).thenReturn("claim"); - Optional response = Optional.empty(); - Mockito.when(residentUserRepository.findById(Mockito.anyString())).thenReturn(response); - ResponseWrapper responseWrapper = residentServiceImpl.getUserinfo("123", 0); - assertEquals(responseWrapper.getResponse().getFullName(), responseWrapper.getResponse().getFullName()); - } - - @Test - public void testDownloadServiceHistory() throws ResidentServiceCheckedException, IOException { - ResponseWrapper> responseWrapper = new ResponseWrapper<>(); - ServiceHistoryResponseDto serviceHistoryResponseDto = new ServiceHistoryResponseDto(); - serviceHistoryResponseDto.setEventId("123"); - PageDto responseDtoPageDto= new PageDto<>(); - responseDtoPageDto.setData(List.of(serviceHistoryResponseDto)); - responseWrapper.setResponse(responseDtoPageDto); - ResponseWrapper responseWrapper1 = new ResponseWrapper<>(); - Map templateResponse = new LinkedHashMap<>(); - templateResponse.put(ResidentConstants.FILE_TEXT, "test"); - responseWrapper1.setResponse(templateResponse); - Mockito.when(proxyMasterdataService.getAllTemplateBylangCodeAndTemplateTypeCode(Mockito.anyString(), Mockito.anyString())) - .thenReturn(responseWrapper1); - Mockito.when(templateManager.merge(any(), any())).thenReturn(new ByteArrayInputStream("pdf".getBytes())); - Mockito.when(utility.signPdf(any(), any())).thenReturn("pdf".getBytes(StandardCharsets.UTF_8)); - byte[] pdfDocument = residentServiceImpl.downLoadServiceHistory(responseWrapper, "eng", - LocalDateTime.now(), LocalDate.now(), LocalDate.now(), - String.valueOf(RequestType.DOWNLOAD_PERSONALIZED_CARD), "SUCCESS", 0); - assertNotNull(pdfDocument); - } - - @Test - public void testDownloadServiceHistorySuccess() throws ResidentServiceCheckedException, IOException { - ResponseWrapper> responseWrapper = new ResponseWrapper<>(); - ServiceHistoryResponseDto serviceHistoryResponseDto = new ServiceHistoryResponseDto(); - serviceHistoryResponseDto.setEventId("123"); - serviceHistoryResponseDto.setDescription(null); - PageDto responseDtoPageDto= new PageDto<>(); - responseDtoPageDto.setData(List.of(serviceHistoryResponseDto)); - responseWrapper.setResponse(responseDtoPageDto); - ResponseWrapper responseWrapper1 = new ResponseWrapper<>(); - Map templateResponse = new LinkedHashMap<>(); - templateResponse.put(ResidentConstants.FILE_TEXT, "test"); - responseWrapper1.setResponse(templateResponse); - Mockito.when(proxyMasterdataService.getAllTemplateBylangCodeAndTemplateTypeCode(Mockito.anyString(), Mockito.anyString())) - .thenReturn(responseWrapper1); - Mockito.when(templateManager.merge(any(), any())).thenReturn(new ByteArrayInputStream("pdf".getBytes())); - Mockito.when(utility.signPdf(any(), any())).thenReturn("pdf".getBytes(StandardCharsets.UTF_8)); - byte[] pdfDocument = residentServiceImpl.downLoadServiceHistory(responseWrapper, "eng", - null, null, null, - null, null, 0); - assertNotNull(pdfDocument); - } - - @Test - public void testDownloadServiceHistoryFail() throws ResidentServiceCheckedException, IOException { - ResponseWrapper> responseWrapper = new ResponseWrapper<>(); - ServiceHistoryResponseDto serviceHistoryResponseDto = new ServiceHistoryResponseDto(); - serviceHistoryResponseDto.setEventId("123"); - PageDto responseDtoPageDto= new PageDto<>(); - responseDtoPageDto.setData(null); - responseWrapper.setResponse(responseDtoPageDto); - ResponseWrapper responseWrapper1 = new ResponseWrapper<>(); - Map templateResponse = new LinkedHashMap<>(); - templateResponse.put(ResidentConstants.FILE_TEXT, "test"); - responseWrapper1.setResponse(templateResponse); - Mockito.when(proxyMasterdataService.getAllTemplateBylangCodeAndTemplateTypeCode(Mockito.anyString(), Mockito.anyString())) - .thenReturn(responseWrapper1); - Mockito.when(templateManager.merge(any(), any())).thenReturn(new ByteArrayInputStream("pdf".getBytes())); - Mockito.when(utility.signPdf(any(), any())).thenReturn("pdf".getBytes(StandardCharsets.UTF_8)); - byte[] pdfDocument = residentServiceImpl.downLoadServiceHistory(responseWrapper, "eng", - LocalDateTime.now(), LocalDate.now(), LocalDate.now(), - String.valueOf(RequestType.DOWNLOAD_PERSONALIZED_CARD), "SUCCESS", 0); - assertNotNull(pdfDocument); - } - - @Test - public void testGetUnreadNotifyList() throws ResidentServiceCheckedException, ApisResourceAccessException{ - Mockito.when(identityServiceImpl.getResidentIdaToken()).thenReturn("123"); - ResidentTransactionEntity residentTransactionEntity1 = new ResidentTransactionEntity(); - residentTransactionEntity1.setEventId("123"); - Page residentTransactionEntityPage = - new PageImpl<>(List.of(residentTransactionEntity1)); - Mockito.when(residentTransactionRepository.findByTokenIdAndRequestTypeCodeInAndOlvPartnerIdIsNullOrOlvPartnerId - (Mockito.any(), Mockito.any(), Mockito.anyString(), Mockito.any())).thenReturn(residentTransactionEntityPage); - ResponseWrapper> responseWrapper = new ResponseWrapper<>(); - ServiceHistoryResponseDto serviceHistoryResponseDto = new ServiceHistoryResponseDto(); - serviceHistoryResponseDto.setEventId("123"); - PageDto responseDtoPageDto= new PageDto<>(); - responseDtoPageDto.setData(List.of(serviceHistoryResponseDto)); - responseWrapper.setResponse(responseDtoPageDto); - ResponseWrapper responseWrapper1 = new ResponseWrapper<>(); - Map templateResponse = new LinkedHashMap<>(); - templateResponse.put(ResidentConstants.FILE_TEXT, "test"); - responseWrapper1.setResponse(templateResponse); - residentServiceImpl.getNotificationList(0,10,"123","eng",0); - } - - @Test - public void testUpdatebellClickdttimes() throws ApisResourceAccessException, ResidentServiceCheckedException{ - ResidentUserEntity residentUserEntity = new ResidentUserEntity(); - residentUserEntity.setIdaToken("123"); - Optional response = Optional.of(residentUserEntity); - Mockito.when(residentUserRepository.findById(Mockito.anyString())).thenReturn(response); - assertEquals(0, residentServiceImpl.updatebellClickdttimes("123")); - } - - @Test - public void testUpdatebellClickdttimesNewRecord() throws ApisResourceAccessException, ResidentServiceCheckedException{ - Optional response = Optional.empty(); - Mockito.when(residentUserRepository.findById(Mockito.anyString())).thenReturn(response); - assertEquals(1, residentServiceImpl.updatebellClickdttimes("123")); - } - - @Test - public void testGetbellClickdttimes(){ - ResidentUserEntity residentUserEntity = new ResidentUserEntity(); - residentUserEntity.setIdaToken("123"); - residentUserEntity.setLastbellnotifDtimes(LocalDateTime.of(2015, 12, 3, 4, 4, 4)); - Optional response = Optional.of(residentUserEntity); - Mockito.when(residentUserRepository.findById(Mockito.anyString())).thenReturn(response); - ResponseWrapper responseWrapper = new ResponseWrapper<>(); - BellNotificationDto bellNotificationDto = new BellNotificationDto(); - bellNotificationDto.setLastbellnotifclicktime(LocalDateTime.now()); - responseWrapper.setResponse(bellNotificationDto); - assertEquals(LocalDateTime.of(2015, 12, 3, 4, 4, 4), - residentServiceImpl.getbellClickdttimes("123").getResponse().getLastbellnotifclicktime()); - } - - @Test - public void testGetnotificationCount() throws ApisResourceAccessException, ResidentServiceCheckedException{ - ResidentSessionEntity residentUserEntity = new ResidentSessionEntity(); - residentUserEntity.setHost("localhost"); - residentUserEntity.setIdaToken("123"); - residentUserEntity.setIpAddress("http"); - residentUserEntity.setLoginDtimes(LocalDateTime.of(2015, 12, 3, 4, 4, 4)); - Optional response = Optional.of(residentUserEntity); - ResponseWrapper responseWrapper = new ResponseWrapper<>(); - UnreadNotificationDto unreadServiceNotificationDto = new UnreadNotificationDto(); - unreadServiceNotificationDto.setUnreadCount(4L); - responseWrapper.setResponse(unreadServiceNotificationDto); - Mockito.when(residentTransactionRepository.countByIdAndUnreadStatusForRequestTypes(Mockito.anyString(), Mockito.anyList())).thenReturn(4L); - assertEquals(Optional. of(4L), Optional.ofNullable(residentServiceImpl. - getnotificationCount("123").getResponse().getUnreadCount())); - } - - @Test - public void testGetnotificationCountLastLoginTime() throws ApisResourceAccessException, ResidentServiceCheckedException{ - ResponseWrapper responseWrapper = new ResponseWrapper<>(); - UnreadNotificationDto unreadServiceNotificationDto = new UnreadNotificationDto(); - unreadServiceNotificationDto.setUnreadCount(4L); - responseWrapper.setResponse(unreadServiceNotificationDto); - ResidentSessionEntity residentUserEntity = new ResidentSessionEntity(); - residentUserEntity.setHost("localhost"); - residentUserEntity.setIdaToken("123"); - residentUserEntity.setIpAddress("http"); - Optional response = Optional.of(residentUserEntity); - ResidentUserEntity residentUserEntity1 = new ResidentUserEntity(); - residentUserEntity1.setLastbellnotifDtimes(LocalDateTime.now()); - residentUserEntity1.setIdaToken("123"); - Mockito.when(residentUserRepository.findById(Mockito.anyString())).thenReturn(Optional.of(residentUserEntity1)); - Mockito.when(residentSessionRepository.findById(Mockito.anyString())).thenReturn(response); - Mockito.when(residentTransactionRepository.countByIdAndUnreadStatusForRequestTypes(Mockito.anyString(), Mockito.anyList())).thenReturn(4L); - assertEquals(Optional. of(0L), Optional.ofNullable(residentServiceImpl. - getnotificationCount("123").getResponse().getUnreadCount())); - } - - @Test(expected = ResidentServiceCheckedException.class) - public void testGetCheckAidStatusFailed() throws ResidentServiceCheckedException { - Mockito.when(identityServiceImpl.getUinForIndividualId(Mockito.anyString())).thenReturn(null); - residentServiceImpl.checkAidStatus("123"); - } -} diff --git a/resident/resident-service/src/test/java/io/mosip/resident/test/service/ResidentServiceGetCredentialRequestTest.java b/resident/resident-service/src/test/java/io/mosip/resident/test/service/ResidentServiceGetCredentialRequestTest.java deleted file mode 100644 index 6d054b8b534..00000000000 --- a/resident/resident-service/src/test/java/io/mosip/resident/test/service/ResidentServiceGetCredentialRequestTest.java +++ /dev/null @@ -1,106 +0,0 @@ -package io.mosip.resident.test.service; - -import static org.junit.Assert.assertEquals; -import static org.mockito.ArgumentMatchers.any; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; -import org.springframework.core.env.Environment; - -import io.mosip.kernel.core.idvalidator.spi.RidValidator; -import io.mosip.resident.dto.RegistrationStatusDTO; -import io.mosip.resident.dto.RegistrationStatusResponseDTO; -import io.mosip.resident.dto.RequestDTO; -import io.mosip.resident.exception.ApisResourceAccessException; -import io.mosip.resident.exception.ResidentServiceCheckedException; -import io.mosip.resident.exception.ResidentServiceException; -import io.mosip.resident.service.NotificationService; -import io.mosip.resident.service.impl.IdentityServiceImpl; -import io.mosip.resident.service.impl.ResidentServiceImpl; -import io.mosip.resident.util.AuditUtil; -import io.mosip.resident.util.ResidentServiceRestClient; - -@RunWith(MockitoJUnitRunner.class) -public class ResidentServiceGetCredentialRequestTest { - - private static final String DATETIME_PATTERN = "mosip.utc-datetime-pattern"; - private static final String STATUS_CHECK_ID = "mosip.resident.service.status.check.id"; - private static final String STATUS_CHECEK_VERSION = "mosip.resident.service.status.check.version"; - private static final String REGISTRATIONSTATUSSEARCH = "REGISTRATIONSTATUSSEARCH"; - @Mock - ResidentServiceRestClient residentServiceRestClient; - - @Mock - Environment env; - - @Mock - NotificationService notificationService; - - @Mock - IdentityServiceImpl identityServiceImpl; - - @Mock - private RidValidator ridValidator; - - @Mock - private AuditUtil audit; - - @InjectMocks - ResidentServiceImpl residentService = new ResidentServiceImpl(); - - private RequestDTO requestDTO; - - private RegistrationStatusResponseDTO responseWrapper; - private RegistrationStatusDTO response; - - @Before - public void setup() throws IOException, ApisResourceAccessException { - requestDTO = new RequestDTO(); - requestDTO.setIndividualId("10006100435989220191202104224"); - requestDTO.setIndividualIdType("RID"); - - Mockito.when(env.getProperty(STATUS_CHECK_ID)).thenReturn("id"); - Mockito.when(env.getProperty(STATUS_CHECEK_VERSION)).thenReturn("version"); - Mockito.when(env.getProperty(DATETIME_PATTERN)).thenReturn("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); - Mockito.when(env.getProperty(REGISTRATIONSTATUSSEARCH)).thenReturn(REGISTRATIONSTATUSSEARCH); - - - responseWrapper = new RegistrationStatusResponseDTO(); - response = new RegistrationStatusDTO(); - response.setRegistrationId("10008100670000320191212101846"); - response.setStatusCode("PROCESSED"); - responseWrapper.setErrors(null); - responseWrapper.setId("mosip.resident.status"); - List list = new ArrayList<>(); - list.add(response); - responseWrapper.setResponse(list); - - Mockito.when(residentServiceRestClient.postApi(any(), any(), any(), any())).thenReturn(responseWrapper); - Mockito.doNothing().when(audit).setAuditRequestDto(Mockito.any()); - } - - @Test - public void getCredentialRequestTest() throws ResidentServiceException, ResidentServiceCheckedException { - Mockito.when(identityServiceImpl.getUinForIndividualId(any())).thenReturn("10006100435989220191202104224"); - String result = residentService.checkAidStatus("10006100435989220191202104224"); - assertEquals("PROCESSED", result); - } - - @Test - public void getAidStatusTest() throws ResidentServiceException, ResidentServiceCheckedException, ApisResourceAccessException { - Mockito.when(identityServiceImpl.getUinForIndividualId(any())).thenReturn("10006100435989220191202104224"); - Mockito.when(identityServiceImpl.getIndividualIdForAid(any())).thenThrow(new ApisResourceAccessException()); - String result = residentService.checkAidStatus("10006100435989220191202104224"); - assertEquals("PROCESSED", result); - } - -} diff --git a/resident/resident-service/src/test/java/io/mosip/resident/test/service/ResidentServiceGetEventStatusTest.java b/resident/resident-service/src/test/java/io/mosip/resident/test/service/ResidentServiceGetEventStatusTest.java deleted file mode 100644 index 3acc2012b50..00000000000 --- a/resident/resident-service/src/test/java/io/mosip/resident/test/service/ResidentServiceGetEventStatusTest.java +++ /dev/null @@ -1,180 +0,0 @@ -package io.mosip.resident.test.service; - -import java.io.IOException; -import java.time.LocalDateTime; -import java.util.Map; -import java.util.Optional; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.springframework.core.env.Environment; -import org.springframework.test.context.junit4.SpringRunner; - -import io.mosip.kernel.core.http.ResponseWrapper; -import io.mosip.resident.constant.EventStatusFailure; -import io.mosip.resident.constant.EventStatusSuccess; -import io.mosip.resident.constant.RequestType; -import io.mosip.resident.dto.EventStatusResponseDTO; -import io.mosip.resident.entity.ResidentTransactionEntity; -import io.mosip.resident.exception.ApisResourceAccessException; -import io.mosip.resident.exception.EidNotBelongToSessionException; -import io.mosip.resident.exception.ResidentServiceCheckedException; -import io.mosip.resident.repository.ResidentTransactionRepository; -import io.mosip.resident.service.ProxyMasterdataService; -import io.mosip.resident.service.ResidentService; -import io.mosip.resident.service.impl.IdentityServiceImpl; -import io.mosip.resident.service.impl.ResidentServiceImpl; -import io.mosip.resident.util.AuditUtil; -import io.mosip.resident.util.ResidentServiceRestClient; -import io.mosip.resident.util.TemplateUtil; -import io.mosip.resident.validator.RequestValidator; -import reactor.util.function.Tuples; - -/** - * This class is used to test the get Status service - * @author Kamesh Shekhar Prasad - */ - -@RunWith(SpringRunner.class) -public class ResidentServiceGetEventStatusTest { - - @Mock - private AuditUtil audit; - - @InjectMocks - private ResidentService residentService = new ResidentServiceImpl(); - - @Mock - private IdentityServiceImpl identityServiceImpl; - - @Mock - private ResidentTransactionRepository residentTransactionRepository; - - @Mock - private RequestValidator validator; - - @Mock - private TemplateUtil templateUtil; - - @Mock - private ResidentServiceRestClient restClient; - - @Mock - private ProxyMasterdataService proxyMasterdataService; - - @Mock - private Environment environment; - - private String eventId; - private String langCode; - private ResponseWrapper responseWrapper; - private EventStatusResponseDTO eventStatusResponseDTO; - private Optional residentTransactionEntity; - private RequestType requestType; - Map templateVariables; - - @Before - public void setup() throws ResidentServiceCheckedException, ApisResourceAccessException, IOException { - eventId = "123456789"; - requestType = RequestType.AUTHENTICATION_REQUEST; - langCode = "eng"; - responseWrapper = new ResponseWrapper<>(); - templateVariables = new java.util.HashMap<>(); - eventStatusResponseDTO = new EventStatusResponseDTO(); - residentTransactionEntity = Optional.of(new ResidentTransactionEntity()); - eventStatusResponseDTO.setEventId("123456789"); - eventStatusResponseDTO.setEventStatus("COMPLETED"); - responseWrapper.setResponse(eventStatusResponseDTO); - residentTransactionEntity.get().setRequestTypeCode(RequestType.AUTHENTICATION_REQUEST.name()); - residentTransactionEntity.get().setStatusCode(EventStatusSuccess.AUTHENTICATION_SUCCESSFUL.name()); - residentTransactionEntity.get().setEventId(eventId); - residentTransactionEntity.get().setLangCode(langCode); - residentTransactionEntity.get().setRequestSummary("requestSummary"); - residentTransactionEntity.get().setRequestTypeCode(requestType.name()); - residentTransactionEntity.get().setCrDtimes(LocalDateTime.now()); - residentTransactionEntity.get().setTokenId("123456789"); - Mockito.when(residentTransactionRepository.findById(Mockito.anyString())).thenReturn(residentTransactionEntity); - templateVariables.put("eventId", eventId); - templateVariables.put("authenticationMode", "OTP"); - templateVariables.put("partnerName", "partnerName"); - templateVariables.put("purpose", "authentication"); - Mockito.when(requestType.getAckTemplateVariables(templateUtil, Mockito.anyString(), Mockito.anyString(), Mockito.anyInt())).thenReturn(Tuples.of(templateVariables, "")); - Mockito.when(identityServiceImpl.getResidentIndvidualIdFromSession()).thenReturn("123456789"); - Mockito.when(identityServiceImpl.getResidentIdaToken()).thenReturn("123456789"); - Mockito.doNothing().when(audit).setAuditRequestDto(Mockito.any()); - Mockito.when(templateUtil.getPurposeTemplateTypeCode(Mockito.any(), Mockito.any())).thenReturn("template-type-code"); - Mockito.when(templateUtil.getSummaryTemplateTypeCode(Mockito.any(), Mockito.any())).thenReturn("template-type-code"); - ResponseWrapper primaryLangResp = new ResponseWrapper<>(); - primaryLangResp.setResponse(Map.of("filtext","Authentication is successful")); - Mockito.when(proxyMasterdataService - .getAllTemplateBylangCodeAndTemplateTypeCode(Mockito.anyString(), Mockito.anyString())).thenReturn(primaryLangResp); - Mockito.when(environment.getProperty(Mockito.anyString())).thenReturn("property"); - } - - @Test - public void getEventStatusTest() throws ResidentServiceCheckedException { - ResponseWrapper resultResponseWrapper =residentService.getEventStatus(eventId, langCode, 0); - assert resultResponseWrapper.getResponse().getEventId().equals(eventId); - } - - @Test - public void getEventStatusTestVid() throws ResidentServiceCheckedException { - Mockito.when(validator.validateVid(Mockito.anyString())).thenReturn(true); - ResponseWrapper resultResponseWrapper =residentService.getEventStatus(eventId, langCode, 0); - assert resultResponseWrapper.getResponse().getEventId().equals(eventId); - } - - @Test - public void getEventStatusTestUIN() throws ResidentServiceCheckedException { - Mockito.when(validator.validateUin(Mockito.anyString())).thenReturn(true); - ResponseWrapper resultResponseWrapper =residentService.getEventStatus(eventId, langCode, 0); - assert resultResponseWrapper.getResponse().getEventId().equals(eventId); - } - - @Test - public void getEventStatusTestEventStatusFailure() throws ResidentServiceCheckedException { - residentTransactionEntity.get().setStatusCode(EventStatusFailure.AUTHENTICATION_FAILED.name()); - Mockito.when(residentTransactionRepository.findById(Mockito.anyString())).thenReturn(residentTransactionEntity); - ResponseWrapper resultResponseWrapper =residentService.getEventStatus(eventId, langCode, 0); - assert resultResponseWrapper.getResponse().getEventId().equals(eventId); - } - - @Test - public void getEventStatusTestEventStatusPending() throws ResidentServiceCheckedException{ - residentTransactionEntity.get().setStatusCode("in-progress"); - Mockito.when(residentTransactionRepository.findById(Mockito.anyString())).thenReturn(residentTransactionEntity); - ResponseWrapper resultResponseWrapper =residentService.getEventStatus(eventId, langCode, 0); - assert resultResponseWrapper.getResponse().getEventId().equals(eventId); - } - - @Test(expected = ResidentServiceCheckedException.class) - public void getEventStatusTestException() throws ResidentServiceCheckedException { - Mockito.when(residentTransactionRepository.findById(Mockito.anyString())).thenReturn(Optional.empty()); - residentService.getEventStatus(eventId, langCode, 0); - } - - @Test(expected = ResidentServiceCheckedException.class) - public void getEventStatusNestedIfTest() throws ResidentServiceCheckedException, ApisResourceAccessException { - Mockito.when(identityServiceImpl.getResidentIdaToken()).thenReturn("abcd"); - residentService.getEventStatus(eventId, langCode, 0); - } - - @Test(expected = ResidentServiceCheckedException.class) - public void getEventStatusThrowsExceptionTest() throws ResidentServiceCheckedException, ApisResourceAccessException { - Mockito.when(identityServiceImpl.getResidentIdaToken()).thenThrow(new ApisResourceAccessException()); - residentService.getEventStatus(eventId, langCode, 0); - } - - @Test - public void getEventStatusServiceTypeNotMappedTest() throws ResidentServiceCheckedException { - Mockito.when(RequestType.SEND_OTP.getAckTemplateVariables(templateUtil, eventId, "eng", 0)). - thenReturn(Tuples.of(templateVariables, "acknowledgement-order-a-physical-card")); - residentTransactionEntity.get().setRequestTypeCode(RequestType.SEND_OTP.name()); - ResponseWrapper resultResponseWrapper =residentService.getEventStatus(eventId, langCode, 0); - assert resultResponseWrapper.getResponse().getEventId().equals(eventId); - } -} diff --git a/resident/resident-service/src/test/java/io/mosip/resident/test/service/ResidentServiceGetServiceHistoryTest.java b/resident/resident-service/src/test/java/io/mosip/resident/test/service/ResidentServiceGetServiceHistoryTest.java deleted file mode 100644 index 0da965b3bfd..00000000000 --- a/resident/resident-service/src/test/java/io/mosip/resident/test/service/ResidentServiceGetServiceHistoryTest.java +++ /dev/null @@ -1,407 +0,0 @@ -package io.mosip.resident.test.service; - -import io.mosip.kernel.core.http.ResponseWrapper; -import io.mosip.resident.constant.EventStatus; -import io.mosip.resident.constant.EventStatusSuccess; -import io.mosip.resident.constant.RequestType; -import io.mosip.resident.constant.ServiceType; -import io.mosip.resident.dto.AidStatusRequestDTO; -import io.mosip.resident.dto.AutnTxnDto; -import io.mosip.resident.dto.PageDto; -import io.mosip.resident.dto.ServiceHistoryResponseDto; -import io.mosip.resident.entity.ResidentSessionEntity; -import io.mosip.resident.entity.ResidentTransactionEntity; -import io.mosip.resident.exception.ApisResourceAccessException; -import io.mosip.resident.exception.OtpValidationFailedException; -import io.mosip.resident.exception.ResidentServiceCheckedException; -import io.mosip.resident.exception.ResidentServiceException; -import io.mosip.resident.repository.ResidentSessionRepository; -import io.mosip.resident.repository.ResidentTransactionRepository; -import io.mosip.resident.service.IdAuthService; -import io.mosip.resident.service.ProxyIdRepoService; -import io.mosip.resident.service.ProxyMasterdataService; -import io.mosip.resident.service.impl.IdentityServiceImpl; -import io.mosip.resident.service.impl.PartnerServiceImpl; -import io.mosip.resident.service.impl.ResidentServiceImpl; -import io.mosip.resident.util.AuditUtil; -import io.mosip.resident.util.TemplateUtil; -import io.mosip.resident.util.Utilities; -import io.mosip.resident.util.Utility; -import io.mosip.resident.validator.RequestValidator; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.springframework.boot.test.mock.mockito.MockBean; -import org.springframework.core.env.Environment; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.PageImpl; -import org.springframework.test.context.junit4.SpringRunner; - -import javax.persistence.EntityManager; -import javax.persistence.Query; -import java.io.IOException; -import java.math.BigInteger; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import static org.junit.Assert.assertEquals; - -/** - * This class is used to test the get service history service - * @author Kamesh Shekhar Prasad - */ - -@RunWith(SpringRunner.class) -public class ResidentServiceGetServiceHistoryTest { - - @MockBean - private ProxyIdRepoService proxyIdRepoService; - - @Mock - private AuditUtil audit; - - @InjectMocks - private ResidentServiceImpl residentServiceImpl; - - @Mock - private IdentityServiceImpl identityServiceImpl; - - @Mock - private ResidentTransactionRepository residentTransactionRepository; - - @Mock - private RequestValidator validator; - - @Mock - private Utilities utilities; - - @Mock - private PartnerServiceImpl partnerServiceImpl; - - @Mock - private IdAuthService idAuthServiceImpl; - - @Mock - private Environment environment; - - @Mock - private ResidentSessionRepository residentSessionRepository; - - @Mock - private Utility utility; - - @Mock - private TemplateUtil templateUtil; - - @Mock - private ProxyMasterdataService proxyMasterdataService; - - @Mock - private EntityManager entityManager; - - List details = null; - - private int pageStart; - private int pageSize; - private LocalDate fromDate; - private LocalDate toDate; - private String serviceType; - private String sortType; - List serviceHistoryResponseDto; - private ArrayList partnerIds; - List residentTransactionEntityList; - ResidentTransactionEntity residentTransactionEntity; - private String statusFilter; - private String searchText; - - private ResponseWrapper> responseWrapper; - - private ResidentSessionEntity residentSessionEntity; - - private Query query; - - @Before - public void setup() throws ResidentServiceCheckedException, ApisResourceAccessException, IOException { - statusFilter = EventStatus.SUCCESS.toString(); - searchText = "1"; - details = new ArrayList<>(); - pageSize = 10; - pageStart = 2; - serviceType = "AUTHENTICATION_REQUEST"; - sortType = "ASC"; - serviceHistoryResponseDto = new ArrayList<>(); - partnerIds = new ArrayList<>(); - residentTransactionEntityList = new ArrayList<>(); - residentTransactionEntity = new ResidentTransactionEntity(); - residentTransactionEntity.setEventId("eventId"); - responseWrapper = new ResponseWrapper<>(); - residentTransactionEntity.setRequestTrnId("12345"); - residentTransactionEntity.setStatusCode(ServiceType.AUTHENTICATION_REQUEST.name()); - residentTransactionEntity.setStatusComment("Success"); - residentTransactionEntity.setCrDtimes(LocalDateTime.now()); - residentTransactionEntity.setStatusCode(EventStatusSuccess.AUTHENTICATION_SUCCESSFUL.toString()); - - residentTransactionEntityList.add(residentTransactionEntity); - - partnerIds.add("m-partner-default-auth"); - partnerIds.add("MOVP"); - - query = Mockito.mock(Query.class); - Mockito.when(entityManager.createNativeQuery(Mockito.anyString(), (Class) Mockito.any())).thenReturn(query); - Mockito.when(entityManager.createNativeQuery(Mockito.anyString())).thenReturn(query); - Mockito.when(query.getSingleResult()).thenReturn(BigInteger.valueOf(1)); - - Mockito.when(residentTransactionRepository.findByTokenAndTransactionType(Mockito.anyString(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.anyString())).thenReturn(residentTransactionEntityList); - - Mockito.when(residentTransactionRepository.findByTokenWithoutDate(Mockito.anyString(), Mockito.any(), Mockito.any(),Mockito.any(), Mockito.anyString())).thenReturn(residentTransactionEntityList); - Mockito.when(identityServiceImpl.getResidentIndvidualIdFromSession()).thenReturn("8251649601"); - Mockito.when(identityServiceImpl.getIDAToken(Mockito.anyString(), Mockito.anyString())).thenReturn("346697314566835424394775924659202696"); - Mockito.when(partnerServiceImpl.getPartnerDetails(Mockito.anyString())).thenReturn(partnerIds); - Mockito.doNothing().when(audit).setAuditRequestDto(Mockito.any()); - - Mockito.when(identityServiceImpl.getAvailableclaimValue(Mockito.anyString())).thenReturn("Kamesh"); - Mockito.when(environment.getProperty(Mockito.anyString())).thenReturn("property"); - residentSessionEntity = new ResidentSessionEntity(); - residentSessionEntity.setHost("localhost"); - Mockito.when(residentSessionRepository.findFirst2ByIdaTokenOrderByLoginDtimesDesc( - Mockito.anyString())).thenReturn(List.of(residentSessionEntity)); - Page residentTransactionEntityPage = - new PageImpl<>(residentTransactionEntityList); - Mockito.when(residentTransactionRepository.findByTokenIdAndStatusCodeInAndOlvPartnerIdIsNullOrOlvPartnerId(Mockito.anyString(), Mockito.anyList(), Mockito.anyString(), Mockito.any())) - .thenReturn(residentTransactionEntityPage); - Mockito.when(residentTransactionRepository.findByTokenIdAndCrDtimesBetweenAndRequestTypeCodeInAndStatusCodeInAndOlvPartnerIdIsNullOrOlvPartnerId( - Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.anyString(), Mockito.any())).thenReturn(residentTransactionEntityPage); - Mockito.when(residentTransactionRepository.findByTokenIdAndCrDtimesBetweenAndStatusCodeInAndOlvPartnerIdIsNullOrOlvPartnerId - (Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.anyString(), Mockito.any())).thenReturn(residentTransactionEntityPage); - Mockito.when(residentTransactionRepository.findByTokenIdAndCrDtimesBetweenAndRequestTypeCodeInAndOlvPartnerIdIsNullOrOlvPartnerId - (Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.anyString(), Mockito.any())) - .thenReturn(residentTransactionEntityPage); - Mockito.when(residentTransactionRepository.findByTokenIdAndOlvPartnerIdIsNullOrOlvPartnerId( - Mockito.anyString(), Mockito.anyString(), Mockito.any())) - .thenReturn(residentTransactionEntityPage); - Mockito.when(residentTransactionRepository.findByTokenIdAndCrDtimesBetweenAndRequestTypeCodeInAndStatusCodeInAndEventIdLikeAndOlvPartnerIdIsNullOrOlvPartnerId( - Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.anyString(), Mockito.any() - )).thenReturn(residentTransactionEntityPage); - Mockito.when(residentTransactionRepository.findByTokenIdAndCrDtimesBetweenAndOlvPartnerIdIsNullOrOlvPartnerId( - Mockito.any(), Mockito.any(), Mockito.any(), Mockito.anyString(), Mockito.any() - )).thenReturn(residentTransactionEntityPage); - Mockito.when(residentTransactionRepository.findByEventIdLikeAndOlvPartnerIdIsNullOrOlvPartnerId(Mockito.any(), Mockito.anyString(), Mockito.any())).thenReturn(residentTransactionEntityPage); - Mockito.when(residentTransactionRepository.findByTokenIdAndRequestTypeCodeInAndOlvPartnerIdIsNullOrOlvPartnerId(Mockito.any(), Mockito.any() - , Mockito.anyString(), Mockito.any())).thenReturn(residentTransactionEntityPage); - Mockito.when(residentTransactionRepository.findByTokenIdAndCrDtimesBetweenAndEventIdLikeAndOlvPartnerIdIsNullOrOlvPartnerId( - Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.anyString(), Mockito.any())).thenReturn(residentTransactionEntityPage); - Mockito.when(residentTransactionRepository.findByTokenIdAndStatusCodeInAndEventIdLikeAndOlvPartnerIdIsNullOrOlvPartnerId( - Mockito.any(), Mockito.any(), Mockito.any(), Mockito.anyString(), Mockito.any())).thenReturn(residentTransactionEntityPage); - Mockito.when(residentTransactionRepository.findByTokenIdAndRequestTypeCodeInAndEventIdLikeAndOlvPartnerIdIsNullOrOlvPartnerId( - Mockito.any(), Mockito.any(), Mockito.any(), Mockito.anyString(), Mockito.any())).thenReturn(residentTransactionEntityPage); - Mockito.when(residentTransactionRepository.findByTokenIdAndRequestTypeCodeInAndStatusCodeInAndEventIdLikeAndOlvPartnerIdIsNullOrOlvPartnerId - (Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.anyString(), Mockito.any())).thenReturn(residentTransactionEntityPage); - Mockito.when(residentTransactionRepository.findByTokenIdAndCrDtimesBetweenAndStatusCodeInAndEventIdLikeAndOlvPartnerIdIsNullOrOlvPartnerId( - Mockito.any(), Mockito.any() , Mockito.any() , Mockito.any(), Mockito.any(), Mockito.anyString(), Mockito.any())) - .thenReturn(residentTransactionEntityPage); - Mockito.when(residentTransactionRepository.findByTokenIdAndCrDtimesBetweenAndRequestTypeCodeInAndEventIdLikeAndOlvPartnerIdIsNullOrOlvPartnerId - (Mockito.any(), Mockito.any() , Mockito.any() , Mockito.any(), Mockito.any(), Mockito.anyString(), Mockito.any())) - .thenReturn(residentTransactionEntityPage); - Mockito.when(residentTransactionRepository.findByTokenIdAndRequestTypeCodeInAndStatusCodeInAndOlvPartnerIdIsNullOrOlvPartnerId( - Mockito.any(), Mockito.any(), Mockito.any(), Mockito.anyString(), Mockito.any() - )).thenReturn(residentTransactionEntityPage); - Mockito.when(identityServiceImpl.getResidentIdaToken()).thenReturn("1234"); - - Mockito.when(templateUtil.getPurposeTemplateTypeCode(Mockito.any(), Mockito.any())).thenReturn("template-type-code"); - Mockito.when(templateUtil.getSummaryTemplateTypeCode(Mockito.any(), Mockito.any())).thenReturn("template-type-code"); - ResponseWrapper primaryLangResp = new ResponseWrapper<>(); - primaryLangResp.setResponse(Map.of("filtext","Authentication is successful")); - Mockito.when(proxyMasterdataService - .getAllTemplateBylangCodeAndTemplateTypeCode(Mockito.anyString(), Mockito.anyString())).thenReturn(primaryLangResp); - Mockito.when(environment.getProperty(Mockito.anyString())).thenReturn("property"); - } - - @Test - public void testGetServiceHistorySuccess() throws ResidentServiceCheckedException, ApisResourceAccessException { - pageStart = 2; - pageSize = 3; - fromDate = LocalDate.now(); - toDate = LocalDate.now(); - assertEquals(3, residentServiceImpl.getServiceHistory(pageStart, pageSize, null, null, - null, null, null, null, "eng", 0).getResponse().getPageSize()); - assertEquals(3, residentServiceImpl.getServiceHistory(pageStart, pageSize, LocalDate.now(), LocalDate.now(), serviceType, "DESC", statusFilter, searchText, "eng", 0).getResponse().getPageSize()); - } - - @Test - public void testGetServiceHistoryDateNullCheck() throws ResidentServiceCheckedException, ApisResourceAccessException { - pageStart = 2; - pageSize = 3; - - assertEquals(3, residentServiceImpl.getServiceHistory(pageStart, pageSize, null, null, serviceType, sortType, statusFilter, searchText, "eng", 0).getResponse().getPageSize()); - assertEquals(3, residentServiceImpl.getServiceHistory(pageStart, pageSize, null, null, serviceType, "DESC", statusFilter, searchText, "eng", 0).getResponse().getPageSize()); - assertEquals(3, residentServiceImpl.getServiceHistory(pageStart, pageSize, null, null, serviceType, "DESC", statusFilter, searchText, "eng", 0).getResponse().getPageSize()); - - } - - @Test - public void testGetServiceHistoryNullCheck() throws ResidentServiceCheckedException, ApisResourceAccessException { - assertEquals(10, residentServiceImpl.getServiceHistory(pageStart, pageSize, fromDate, toDate, serviceType, sortType, statusFilter, searchText, "eng", 0).getResponse().getPageSize()); - } - - @Test - public void testGetServiceHistoryAllStatusFilter() throws ResidentServiceCheckedException, ApisResourceAccessException { - fromDate = LocalDate.now(); - toDate = LocalDate.now(); - assertEquals(10, residentServiceImpl.getServiceHistory(pageStart, pageSize, fromDate, toDate, serviceType, - sortType, statusFilter, null, "eng", 0).getResponse().getPageSize()); - } - - @Test(expected = ResidentServiceCheckedException.class) - public void testGetServiceHistoryCheckedException() throws ResidentServiceCheckedException, ApisResourceAccessException { - Integer pageStart = 1; - Integer pageSize = 1; - Mockito.when(residentServiceImpl.getServiceHistory( -1, pageSize, fromDate, toDate, serviceType, sortType, statusFilter, searchText, "eng", 0)).thenThrow(ResidentServiceCheckedException.class); - Mockito.when(residentServiceImpl.getServiceHistory( pageStart, -1, fromDate, toDate, serviceType, sortType, statusFilter, searchText, "eng", 0)).thenThrow(ResidentServiceCheckedException.class); - Mockito.when(residentServiceImpl.getServiceHistory( pageStart, 1, fromDate, toDate, serviceType, sortType, statusFilter, searchText, "eng", 0)).thenThrow(ResidentServiceCheckedException.class); - assertEquals(0, residentServiceImpl.getServiceHistory( -1, pageSize, fromDate, toDate, serviceType, sortType, statusFilter, searchText, "eng", 0).getResponse().getPageSize()); - assertEquals(0, residentServiceImpl.getServiceHistory( pageStart, -1, fromDate, toDate, serviceType, sortType, statusFilter, searchText, "eng", 0).getResponse().getPageSize()); - } - - @Test(expected = ResidentServiceCheckedException.class) - public void testGetServiceHistoryNegativeResidentServiceCheckedException() throws ResidentServiceCheckedException, ApisResourceAccessException { - Integer pageStart = 1; - Mockito.when(residentServiceImpl.getServiceHistory( pageStart, -1, fromDate, toDate, serviceType, sortType, statusFilter, searchText, "eng", 0)).thenThrow(ResidentServiceCheckedException.class); - assertEquals(0, residentServiceImpl.getServiceHistory( pageStart, -1, fromDate, toDate, serviceType, sortType, statusFilter, searchText, "eng", 0).getResponse().getPageSize()); - } - - @Test - public void testPageSizeCheck() throws ResidentServiceCheckedException, ApisResourceAccessException { - pageSize = 10; - pageStart = 1; - assertEquals(10, residentServiceImpl.getServiceHistory(null, null, fromDate, toDate, serviceType, sortType, statusFilter, searchText, "eng", 0).getResponse().getPageSize()); - assertEquals(10, residentServiceImpl.getServiceHistory(null, pageSize, fromDate, toDate, serviceType, sortType, statusFilter, searchText, "eng", 0).getResponse().getPageSize()); - assertEquals(10, residentServiceImpl.getServiceHistory(pageStart, null, fromDate, toDate, serviceType, sortType, statusFilter, searchText, "eng", 0).getResponse().getPageSize()); - } - - @Test - public void testSortTypeNullCheck() throws ResidentServiceCheckedException, ApisResourceAccessException { - pageStart = 1; - pageSize = 10; - assertEquals(10, residentServiceImpl.getServiceHistory(pageStart, pageSize, fromDate, toDate, serviceType, - null, statusFilter, searchText, "eng", 0).getResponse().getPageSize()); - } - - @Test - public void testServiceHistoryWithDifferentParameters() throws ResidentServiceCheckedException, ApisResourceAccessException { - pageStart = 1; - pageSize = 10; - fromDate = LocalDate.MAX; - toDate = LocalDate.MIN; - serviceType = ServiceType.AUTHENTICATION_REQUEST.toString(); - sortType = "ASC"; - statusFilter = "SUCCESS"; - searchText = "a"; - assertEquals(10, residentServiceImpl.getServiceHistory(pageStart, pageSize, fromDate, toDate, serviceType, sortType, - statusFilter, searchText, "eng", 0).getResponse().getPageSize()); - assertEquals(10, residentServiceImpl.getServiceHistory(pageStart, pageSize, fromDate, toDate, "ALL", sortType, - statusFilter, searchText, "eng", 0).getResponse().getPageSize()); - assertEquals(10, residentServiceImpl.getServiceHistory(pageStart, pageSize, fromDate, toDate, "ALL", sortType, - statusFilter, null, "eng", 0).getResponse().getPageSize()); - assertEquals(10, residentServiceImpl.getServiceHistory(pageStart, pageSize, fromDate, toDate, serviceType, sortType, - null, "a", "eng", 0).getResponse().getPageSize()); - assertEquals(10, residentServiceImpl.getServiceHistory(pageStart, pageSize, fromDate, toDate, "ALL", sortType, - null, "a", "eng", 0).getResponse().getPageSize()); - assertEquals(10, residentServiceImpl.getServiceHistory(pageStart, pageSize, fromDate, toDate, null, sortType, - statusFilter, "a", "eng", 0).getResponse().getPageSize()); - assertEquals(10, residentServiceImpl.getServiceHistory(pageStart, pageSize, fromDate, toDate, "ALL", sortType, - null, "a", "eng", 0).getResponse().getPageSize()); - } - - @Test - public void testGetServiceHistoryWithStatusFilterServiceType() throws ResidentServiceCheckedException, ApisResourceAccessException { - assertEquals(10, residentServiceImpl.getServiceHistory(pageStart, pageSize, LocalDate.now(), LocalDate.now(), - ServiceType.ALL.toString(), sortType, - "SUCCESS", null, "eng", 0).getResponse().getPageSize()); - assertEquals(10, residentServiceImpl.getServiceHistory(pageStart, pageSize, null, null, - ServiceType.AUTHENTICATION_REQUEST.toString(), sortType, - "In Progress", null, "eng", 0).getResponse().getPageSize()); - assertEquals(10, residentServiceImpl.getServiceHistory(pageStart, pageSize, null, null, - ServiceType.AUTHENTICATION_REQUEST.toString(), sortType, - null, "1", "eng", 0).getResponse().getPageSize()); - assertEquals(10, residentServiceImpl.getServiceHistory(pageStart, pageSize, null, null, - null, sortType, - "SUCCESS", "1", "eng", 0).getResponse().getPageSize()); - assertEquals(10, residentServiceImpl.getServiceHistory(pageStart, pageSize, LocalDate.now(), LocalDate.now(), - ServiceType.AUTHENTICATION_REQUEST.toString(), sortType, - null, null, "eng", 0).getResponse().getPageSize()); - assertEquals(10, residentServiceImpl.getServiceHistory(pageStart, pageSize, LocalDate.now(), LocalDate.now(), - null, sortType, - null, null, "eng", 0).getResponse().getPageSize()); - assertEquals(10, residentServiceImpl.getServiceHistory(pageStart, pageSize, null, null, - ServiceType.AUTHENTICATION_REQUEST.toString(), sortType, - null, null, "eng", 0).getResponse().getPageSize()); - assertEquals(10, residentServiceImpl.getServiceHistory(pageStart, pageSize, null, null, - null, sortType, - "FAILED", null, "eng", 0).getResponse().getPageSize()); - assertEquals(10, residentServiceImpl.getServiceHistory(pageStart, pageSize, null, null, - null, sortType, - null, "123", "eng", 0).getResponse().getPageSize()); - } - - @Test - public void testGetServiceHistoryWithUpdatedDtimes() throws ResidentServiceCheckedException, ApisResourceAccessException { - residentTransactionEntity.setUpdDtimes(LocalDateTime.now()); - residentTransactionEntity.setRequestTypeCode(RequestType.REVOKE_VID.name()); - residentTransactionEntityList.add(residentTransactionEntity); - Page residentTransactionEntityPage = - new PageImpl<>(residentTransactionEntityList); - Mockito.when(residentTransactionRepository.findByEventIdLikeAndOlvPartnerIdIsNullOrOlvPartnerId(Mockito.any(), Mockito.anyString(), Mockito.any())).thenReturn(residentTransactionEntityPage); - assertEquals(10, residentServiceImpl.getServiceHistory(pageStart, pageSize, null, null, - null, sortType, - null, "123", "eng", 0).getResponse().getPageSize()); - - } - @Test - public void testGetAidStatus() throws OtpValidationFailedException, ResidentServiceCheckedException, ApisResourceAccessException { - AidStatusRequestDTO aidStatusRequestDTO = new AidStatusRequestDTO(); - aidStatusRequestDTO.setIndividualId("10087100401001420220929210144"); - aidStatusRequestDTO.setOtp("111111"); - aidStatusRequestDTO.setTransactionId("1234567890"); - Mockito.when(idAuthServiceImpl.validateOtp(Mockito.anyString(), Mockito.anyString(), Mockito.anyString())).thenReturn(true); - Mockito.when(identityServiceImpl.getIndividualIdForAid(Mockito.anyString())).thenReturn("2476302389"); - assertEquals("PROCESSED", residentServiceImpl.getAidStatus(aidStatusRequestDTO).getAidStatus()); - } - - @Test - public void testGetAidStatusOtpValidationFalse() throws OtpValidationFailedException, ResidentServiceCheckedException, ApisResourceAccessException { - AidStatusRequestDTO aidStatusRequestDTO = new AidStatusRequestDTO(); - aidStatusRequestDTO.setIndividualId("10087100401001420220929210144"); - aidStatusRequestDTO.setOtp("111111"); - aidStatusRequestDTO.setTransactionId("1234567890"); - Mockito.when(idAuthServiceImpl.validateOtp(Mockito.anyString(), Mockito.anyString(), Mockito.anyString())).thenReturn(true); - Mockito.when(identityServiceImpl.getIndividualIdForAid(Mockito.anyString())).thenReturn("2476302389"); - assertEquals("PROCESSED", residentServiceImpl.getAidStatus(aidStatusRequestDTO, false).getAidStatus()); - } - - @Test - public void testGetUserinfo() throws ApisResourceAccessException { - assertEquals("Kamesh", - residentServiceImpl.getUserinfo("ida_token", 0).getResponse().getFullName()); - } - - @Test - public void testGetUserinfoMultipleLoginTime() throws ApisResourceAccessException { - Mockito.when(residentSessionRepository.findFirst2ByIdaTokenOrderByLoginDtimesDesc( - Mockito.anyString())).thenReturn(List.of(residentSessionEntity, residentSessionEntity)); - assertEquals("Kamesh", - residentServiceImpl.getUserinfo("ida_token", 0).getResponse().getFullName()); - } - - @Test - public void testGetFileName(){ - Mockito.when(utility.getFileName(Mockito.anyString(), Mockito.anyString(), Mockito.anyInt())).thenReturn("Ack"); - assertEquals("Ack", residentServiceImpl.getFileName("123", 0)); - } - -} diff --git a/resident/resident-service/src/test/java/io/mosip/resident/test/service/ResidentServiceRequestTypeAuthLockTest.java b/resident/resident-service/src/test/java/io/mosip/resident/test/service/ResidentServiceRequestTypeAuthLockTest.java deleted file mode 100644 index 2ce0791c5df..00000000000 --- a/resident/resident-service/src/test/java/io/mosip/resident/test/service/ResidentServiceRequestTypeAuthLockTest.java +++ /dev/null @@ -1,326 +0,0 @@ -package io.mosip.resident.test.service; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.when; - -import java.util.ArrayList; -import java.util.List; - -import org.json.simple.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; -import org.springframework.cloud.context.config.annotation.RefreshScope; -import org.springframework.core.env.Environment; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.util.ReflectionTestUtils; - -import com.fasterxml.jackson.databind.ObjectMapper; - -import io.mosip.kernel.core.idvalidator.spi.RidValidator; -import io.mosip.kernel.core.idvalidator.spi.UinValidator; -import io.mosip.kernel.core.idvalidator.spi.VidValidator; -import io.mosip.resident.dto.AuthLockOrUnLockRequestDtoV2; -import io.mosip.resident.dto.AuthTypeStatusDto; -import io.mosip.resident.dto.AuthTypeStatusDtoV2; -import io.mosip.resident.dto.NotificationResponseDTO; -import io.mosip.resident.dto.PacketGeneratorResDto; -import io.mosip.resident.dto.ResidentDocuments; -import io.mosip.resident.dto.ResidentUpdateRequestDto; -import io.mosip.resident.dto.ResponseDTO; -import io.mosip.resident.entity.ResidentTransactionEntity; -import io.mosip.resident.exception.ApisResourceAccessException; -import io.mosip.resident.exception.ResidentServiceCheckedException; -import io.mosip.resident.exception.ResidentServiceException; -import io.mosip.resident.repository.ResidentTransactionRepository; -import io.mosip.resident.service.DocumentService; -import io.mosip.resident.service.IdAuthService; -import io.mosip.resident.service.NotificationService; -import io.mosip.resident.service.PartnerService; -import io.mosip.resident.service.ResidentService; -import io.mosip.resident.service.impl.IdentityServiceImpl; -import io.mosip.resident.service.impl.PartnerServiceImpl; -import io.mosip.resident.service.impl.ResidentServiceImpl; -import io.mosip.resident.util.AuditUtil; -import io.mosip.resident.util.UINCardDownloadService; -import io.mosip.resident.util.Utility; -import reactor.util.function.Tuple2; - - -@RunWith(MockitoJUnitRunner.class) -@RefreshScope -@ContextConfiguration -public class ResidentServiceRequestTypeAuthLockTest { - - @Mock - private VidValidator vidValidator; - - @Mock - private UinValidator uinValidator; - - @Mock - private RidValidator ridValidator; - - @Mock - private UINCardDownloadService uinCardDownloadService; - - @Mock - private IdAuthService idAuthService; - - @Mock - NotificationService notificationService; - - @Mock - private AuditUtil audit; - - @Mock - PartnerServiceImpl partnerServiceImpl; - - @Mock - PartnerService partnerService; - - @Mock - IdentityServiceImpl identityServiceImpl; - - @Mock - private Utility utility; - - @Mock - ResidentTransactionRepository residentTransactionRepository; - - @Mock - private ObjectMapper objectMapper; - - @Mock - private DocumentService docService; - - @Mock - private Environment environment; - - @InjectMocks - private ResidentService residentService = new ResidentServiceImpl(); - - NotificationResponseDTO notificationResponseDTO; - - AuthTypeStatusDto authTypeStatusDto; - - private String individualId; - - @Before - public void setup() throws ApisResourceAccessException, ResidentServiceCheckedException { - - notificationResponseDTO = new NotificationResponseDTO(); - notificationResponseDTO.setStatus("success"); - notificationResponseDTO.setMessage("Notification success"); - Mockito.doNothing().when(audit).setAuditRequestDto(Mockito.any()); - individualId = identityServiceImpl.getResidentIndvidualIdFromSession(); - - List residentTransactionEntities=new ArrayList<>(); - ResidentTransactionEntity residentTransactionEntity = new ResidentTransactionEntity(); - residentTransactionEntity.setEventId("12345"); - when(utility.createEntity()).thenReturn(residentTransactionEntity); - residentTransactionEntities.add(residentTransactionEntity); - Mockito.when(utility.createEventId()).thenReturn("12345"); - ArrayList partnerIds = new ArrayList<>(); - partnerIds.add("m-partner-default-auth"); - when(partnerService.getPartnerDetails(Mockito.anyString())).thenReturn(partnerIds); - ReflectionTestUtils.invokeMethod(residentService, "createResidentTransactionEntity", "2157245364", "partnerId"); - ReflectionTestUtils.setField(residentService, "authTypes", "otp,bio-FIR,bio-IIR,bio-FACE"); - } - - @Test - public void testReqAuthTypeStatusUpdateSuccess() - throws ApisResourceAccessException, ResidentServiceCheckedException { - AuthLockOrUnLockRequestDtoV2 authLockOrUnLockRequestDtoV2 = new AuthLockOrUnLockRequestDtoV2(); - AuthTypeStatusDtoV2 authTypeStatusDto = new AuthTypeStatusDtoV2(); - authTypeStatusDto.setAuthType("OTP"); - authTypeStatusDto.setLocked(true); - authTypeStatusDto.setUnlockForSeconds(10L); - List authTypeStatusDtoList = new java.util.ArrayList<>(); - authTypeStatusDtoList.add(authTypeStatusDto); - authLockOrUnLockRequestDtoV2.setAuthTypes(authTypeStatusDtoList); - for (AuthTypeStatusDto authTypeStatusDto1 : authLockOrUnLockRequestDtoV2.getAuthTypes()) { - Mockito.when(idAuthService.authTypeStatusUpdateForRequestId(any(), any(), any())).thenReturn("123"); - Mockito.when(notificationService.sendNotification(Mockito.any())).thenReturn(notificationResponseDTO); - Tuple2 authLockResponse = residentService.reqAauthTypeStatusUpdateV2(authLockOrUnLockRequestDtoV2); - assertEquals("The chosen authentication types have been successfully locked/unlocked.", authLockResponse.getT1().getMessage()); - } - } - - @Test(expected = ResidentServiceException.class) - public void testReqAuthTypeLockFailed() - throws ApisResourceAccessException, ResidentServiceCheckedException { - AuthLockOrUnLockRequestDtoV2 authLockOrUnLockRequestDtoV2 = new AuthLockOrUnLockRequestDtoV2(); - AuthTypeStatusDtoV2 authTypeStatusDto = new AuthTypeStatusDtoV2(); - authTypeStatusDto.setAuthType("OTP"); - authTypeStatusDto.setLocked(true); - authTypeStatusDto.setUnlockForSeconds(10L); - List authTypeStatusDtoList = new java.util.ArrayList<>(); - authTypeStatusDtoList.add(authTypeStatusDto); - authLockOrUnLockRequestDtoV2.setAuthTypes(authTypeStatusDtoList); - residentService.reqAauthTypeStatusUpdateV2(authLockOrUnLockRequestDtoV2); - - } - - @Test(expected = ResidentServiceCheckedException.class) - public void testReqAuthTypeLockNotificationFailed() - throws ApisResourceAccessException, ResidentServiceCheckedException { - - AuthLockOrUnLockRequestDtoV2 authLockOrUnLockRequestDtoV2 = new AuthLockOrUnLockRequestDtoV2(); - AuthTypeStatusDtoV2 authTypeStatusDto = new AuthTypeStatusDtoV2(); - authTypeStatusDto.setAuthType("OTP"); - authTypeStatusDto.setLocked(true); - authTypeStatusDto.setUnlockForSeconds(10L); - List authTypeStatusDtoList = new java.util.ArrayList<>(); - authTypeStatusDtoList.add(authTypeStatusDto); - authLockOrUnLockRequestDtoV2.setAuthTypes(authTypeStatusDtoList); - Mockito.when(notificationService.sendNotification(Mockito.any())) - .thenThrow(new ResidentServiceCheckedException()); - residentService.reqAauthTypeStatusUpdateV2(authLockOrUnLockRequestDtoV2); - - } - - @Test(expected = ResidentServiceException.class) - public void testReqAuthTypeLockException() - throws ApisResourceAccessException, ResidentServiceCheckedException { - - AuthLockOrUnLockRequestDtoV2 authLockOrUnLockRequestDtoV2 = new AuthLockOrUnLockRequestDtoV2(); - AuthTypeStatusDtoV2 authTypeStatusDto = new AuthTypeStatusDtoV2(); - authTypeStatusDto.setAuthType("OTP"); - authTypeStatusDto.setLocked(true); - authTypeStatusDto.setUnlockForSeconds(10L); - List authTypeStatusDtoList = new java.util.ArrayList<>(); - authTypeStatusDtoList.add(authTypeStatusDto); - authLockOrUnLockRequestDtoV2.setAuthTypes(authTypeStatusDtoList); - residentService.reqAauthTypeStatusUpdateV2(authLockOrUnLockRequestDtoV2); - } - - @Test(expected = ResidentServiceException.class) - public void testReqAuthTypeLockOTPFailedException() - throws ResidentServiceCheckedException, ApisResourceAccessException { - AuthLockOrUnLockRequestDtoV2 authLockOrUnLockRequestDtoV2 = new AuthLockOrUnLockRequestDtoV2(); - AuthTypeStatusDtoV2 authTypeStatusDto = new AuthTypeStatusDtoV2(); - authTypeStatusDto.setAuthType("OTP"); - authTypeStatusDto.setLocked(false); - authTypeStatusDto.setUnlockForSeconds(10L); - List authTypeStatusDtoList = new java.util.ArrayList<>(); - authTypeStatusDtoList.add(authTypeStatusDto); - authLockOrUnLockRequestDtoV2.setAuthTypes(authTypeStatusDtoList); - residentService.reqAauthTypeStatusUpdateV2(authLockOrUnLockRequestDtoV2); - - } - - @Test - public void testGetAuthTypeBasedOnConfigV2(){ - AuthTypeStatusDtoV2 authTypeStatus = new AuthTypeStatusDtoV2(); - authTypeStatus.setAuthType("demo"); - assertEquals("demo",ResidentServiceImpl.getAuthTypeBasedOnConfigV2(authTypeStatus)); - } - - @Test - public void testGetAuthTypeBasedOnConfigV2WithSubType(){ - AuthTypeStatusDtoV2 authTypeStatus = new AuthTypeStatusDtoV2(); - authTypeStatus.setAuthType("demo"); - authTypeStatus.setAuthSubType("demo"); - assertEquals(null,ResidentServiceImpl.getAuthTypeBasedOnConfigV2(authTypeStatus)); - } - - @Test - public void testGetAuthTypeBasedOnConfigV2WithoutSubType(){ - AuthTypeStatusDtoV2 authTypeStatus = new AuthTypeStatusDtoV2(); - authTypeStatus.setAuthType("bio"); - authTypeStatus.setAuthSubType("FIR"); - assertEquals("bio-FIR",ResidentServiceImpl.getAuthTypeBasedOnConfigV2(authTypeStatus)); - } - - @Test - public void testTrySendNotificationFailure() throws ResidentServiceCheckedException { - Mockito.when(notificationService.sendNotification(any())).thenThrow(new ResidentServiceCheckedException()); - ReflectionTestUtils.invokeMethod(residentService, - "trySendNotification", "123", null, null); - } - - @Test - public void testCreateResidentTransEntity() { - ResidentUpdateRequestDto residentUpdateRequestDto = new ResidentUpdateRequestDto(); - JSONObject jsonObject = new JSONObject(); - jsonObject.put("IDSchemaVersion", null); - jsonObject.put("UIN", null); - residentUpdateRequestDto.setIdentity(jsonObject); - residentUpdateRequestDto.setIndividualId("123434343"); - assertNotNull(ReflectionTestUtils.invokeMethod(residentService, - "createResidentTransEntity", residentUpdateRequestDto)); - } - - @Test - public void testUpdateResidentTransaction() { - PacketGeneratorResDto response = new PacketGeneratorResDto(); - response.setRegistrationId("123"); - ResidentTransactionEntity residentTransactionEntity = new ResidentTransactionEntity(); - ReflectionTestUtils.invokeMethod(residentService, - "updateResidentTransaction", residentTransactionEntity, response); - } - - @Test - public void testGetResidentDocuments() { - ResidentUpdateRequestDto residentUpdateRequestDto = new ResidentUpdateRequestDto(); - JSONObject jsonObject = new JSONObject(); - jsonObject.put("IDSchemaVersion", null); - jsonObject.put("UIN", null); - residentUpdateRequestDto.setIdentity(jsonObject); - residentUpdateRequestDto.setIndividualId("123434343"); - JSONObject mappingDocument = new JSONObject(); - mappingDocument.put("key", "value"); - ReflectionTestUtils.invokeMethod(residentService, - "getResidentDocuments", residentUpdateRequestDto, mappingDocument); - } - - @Test - public void testGetResidentDocumentsNullDocuments() { - ResidentUpdateRequestDto residentUpdateRequestDto = new ResidentUpdateRequestDto(); - JSONObject jsonObject = new JSONObject(); - jsonObject.put("IDSchemaVersion", null); - jsonObject.put("UIN", null); - residentUpdateRequestDto.setIdentity(jsonObject); - residentUpdateRequestDto.setIndividualId("123434343"); - ResidentDocuments residentDocuments = new ResidentDocuments("key", "value"); - residentUpdateRequestDto.setDocuments(List.of(residentDocuments)); - ReflectionTestUtils.invokeMethod(residentService, - "getResidentDocuments", residentUpdateRequestDto, null); - } - - @Test - public void testGetResidentDocumentValidDocuments() { - ResidentUpdateRequestDto residentUpdateRequestDto = new ResidentUpdateRequestDto(); - JSONObject jsonObject = new JSONObject(); - jsonObject.put("IDSchemaVersion", null); - jsonObject.put("UIN", null); - residentUpdateRequestDto.setIdentity(jsonObject); - residentUpdateRequestDto.setIndividualId("123434343"); - residentUpdateRequestDto.setTransactionID("123"); - ReflectionTestUtils.invokeMethod(residentService, - "getResidentDocuments", residentUpdateRequestDto, null); - } - - @Test(expected = Exception.class) - public void testGetResidentDocumentInValidDocuments() throws ResidentServiceCheckedException { - ResidentUpdateRequestDto residentUpdateRequestDto = new ResidentUpdateRequestDto(); - JSONObject jsonObject = new JSONObject(); - jsonObject.put("IDSchemaVersion", null); - jsonObject.put("UIN", null); - residentUpdateRequestDto.setIdentity(jsonObject); - residentUpdateRequestDto.setIndividualId("123434343"); - residentUpdateRequestDto.setTransactionID("123"); - Mockito.when(docService.getDocumentsWithMetadata(Mockito.anyString())).thenThrow(new ResidentServiceCheckedException()); - ReflectionTestUtils.invokeMethod(residentService, - "getResidentDocuments", residentUpdateRequestDto, null); - } - - -} diff --git a/resident/resident-service/src/test/java/io/mosip/resident/test/service/ResidentVerificationServiceTest.java b/resident/resident-service/src/test/java/io/mosip/resident/test/service/ResidentVerificationServiceTest.java deleted file mode 100644 index b1b3d32d1a7..00000000000 --- a/resident/resident-service/src/test/java/io/mosip/resident/test/service/ResidentVerificationServiceTest.java +++ /dev/null @@ -1,79 +0,0 @@ -package io.mosip.resident.test.service; - -import static org.junit.Assert.assertEquals; - -import java.security.NoSuchAlgorithmException; -import java.util.UUID; - -import org.joda.time.DateTime; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; -import org.springframework.cloud.context.config.annotation.RefreshScope; -import org.springframework.core.env.Environment; -import org.springframework.test.context.ContextConfiguration; - -import io.mosip.resident.dto.VerificationResponseDTO; -import io.mosip.resident.dto.VerificationStatusDTO; -import io.mosip.resident.entity.ResidentTransactionEntity; -import io.mosip.resident.exception.ApisResourceAccessException; -import io.mosip.resident.exception.ResidentServiceCheckedException; -import io.mosip.resident.repository.ResidentTransactionRepository; -import io.mosip.resident.service.VerificationService; -import io.mosip.resident.service.impl.IdentityServiceImpl; -import io.mosip.resident.service.impl.VerificationServiceImpl; -import io.mosip.resident.util.AuditUtil; -import io.mosip.resident.util.ResidentServiceRestClient; -import io.mosip.resident.util.Utility; - -@RunWith(MockitoJUnitRunner.class) -@RefreshScope -@ContextConfiguration -public class ResidentVerificationServiceTest { - - @Mock - private ResidentServiceRestClient residentServiceRestClient; - - @Mock - Environment env; - - @Mock - private AuditUtil audit; - - @InjectMocks - private VerificationService verificationService = new VerificationServiceImpl(); - - @Mock - private IdentityServiceImpl identityServiceImpl; - - @Mock - private Utility utility; - - @Mock - private ResidentTransactionRepository residentTransactionRepository; - - @Before - public void setup() throws Exception { - ResidentTransactionEntity residentTransactionEntity = new ResidentTransactionEntity(); - residentTransactionEntity.setEventId(UUID.randomUUID().toString()); - } - - @Test - public void testCheckChannelVerificationStatus() throws ResidentServiceCheckedException, NoSuchAlgorithmException, ApisResourceAccessException { - - boolean verificationStatus = false; - VerificationStatusDTO verificationStatusDTO = new VerificationStatusDTO(); - VerificationResponseDTO verificationResponseDTO = new VerificationResponseDTO(); - verificationStatusDTO.setVerificationStatus(verificationStatus); - verificationResponseDTO.setResponse(verificationStatusDTO); - verificationResponseDTO.setId("mosip.resident.channel.verification.status"); - verificationResponseDTO.setVersion("v1"); - verificationResponseDTO.setResponseTime(DateTime.now().toString()); - - VerificationResponseDTO verificationResponseDTO1 =verificationService.checkChannelVerificationStatus("email", "8251649601"); - assertEquals(verificationResponseDTO.getResponse().isVerificationStatus(), verificationResponseDTO1.getResponse().isVerificationStatus()); - } -} \ No newline at end of file diff --git a/resident/resident-service/src/test/java/io/mosip/resident/test/service/WebSubUpdateAuthTypeServiceTest.java b/resident/resident-service/src/test/java/io/mosip/resident/test/service/WebSubUpdateAuthTypeServiceTest.java deleted file mode 100644 index b26c2267fc4..00000000000 --- a/resident/resident-service/src/test/java/io/mosip/resident/test/service/WebSubUpdateAuthTypeServiceTest.java +++ /dev/null @@ -1,121 +0,0 @@ -package io.mosip.resident.test.service; - -import static org.mockito.Mockito.when; -import static org.powermock.api.mockito.PowerMockito.mock; - -import java.time.LocalDateTime; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; -import org.mockito.junit.MockitoJUnitRunner; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.cloud.context.config.annotation.RefreshScope; -import org.springframework.core.env.Environment; -import org.springframework.http.HttpHeaders; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.setup.MockMvcBuilders; - -import io.mosip.kernel.core.websub.model.Event; -import io.mosip.kernel.core.websub.model.EventModel; -import io.mosip.kernel.core.websub.spi.PublisherClient; -import io.mosip.kernel.core.websub.spi.SubscriptionClient; -import io.mosip.kernel.websub.api.model.SubscriptionChangeRequest; -import io.mosip.kernel.websub.api.model.SubscriptionChangeResponse; -import io.mosip.kernel.websub.api.model.UnsubscriptionRequest; -import io.mosip.resident.dto.NotificationResponseDTO; -import io.mosip.resident.exception.ApisResourceAccessException; -import io.mosip.resident.exception.ResidentServiceCheckedException; -import io.mosip.resident.repository.ResidentTransactionRepository; -import io.mosip.resident.service.NotificationService; -import io.mosip.resident.service.impl.IdentityServiceImpl; -import io.mosip.resident.service.impl.WebSubUpdateAuthTypeServiceImpl; -import io.mosip.resident.util.AuditUtil; -import io.mosip.resident.util.ResidentServiceRestClient; - -@RunWith(MockitoJUnitRunner.class) -@RefreshScope -@ContextConfiguration -public class WebSubUpdateAuthTypeServiceTest { - - @Mock - private ResidentServiceRestClient residentServiceRestClient; - - @Mock - Environment env; - - @Mock - private AuditUtil audit; - - @InjectMocks - private WebSubUpdateAuthTypeServiceImpl webSubUpdateAuthTypeService; - - @Mock - private ResidentTransactionRepository residentTransactionRepository; - - @Autowired - private MockMvc mockMvc; - - @Mock - private PublisherClient publisher; - - @Mock - SubscriptionClient subscribe; - - @Mock - private NotificationService notificationService; - - private NotificationResponseDTO notificationResponseDTO; - - private EventModel eventModel; - private Event event; - - @Before - public void setup() throws ApisResourceAccessException, ResidentServiceCheckedException { - eventModel=new EventModel(); - event=new Event(); - MockitoAnnotations.initMocks(this); - this.mockMvc = MockMvcBuilders.standaloneSetup(webSubUpdateAuthTypeService).build(); - notificationResponseDTO = new NotificationResponseDTO(); - notificationResponseDTO.setStatus("Notification success"); - when(notificationService.sendNotification(Mockito.any())).thenReturn(notificationResponseDTO); - } - - @Test - public void testWebSubUpdateAuthTypeService() throws ResidentServiceCheckedException, ApisResourceAccessException { - event.setTransactionId("1234"); - event.setId("1234"); - - eventModel.setEvent(event); - eventModel.setTopic("AUTH_TYPE_STATUS_UPDATE_ACK"); - eventModel.setPublishedOn(String.valueOf(LocalDateTime.now())); - eventModel.setPublisher("AUTH_TYPE_STATUS_UPDATE_ACK"); - - webSubUpdateAuthTypeService.updateAuthTypeStatus(eventModel); - webSubUpdateAuthTypeService = mock(WebSubUpdateAuthTypeServiceImpl.class); - Mockito.lenient().doNothing().when(webSubUpdateAuthTypeService).updateAuthTypeStatus(Mockito.any()); - } - - @Test - public void testWebSubUpdateAuthPassed() throws ResidentServiceCheckedException, ApisResourceAccessException { - Map data = new HashMap<>(); - List> authTypeList = new ArrayList<>(); - Map authTypeMap = new HashMap<>(); - authTypeMap.put("bio-FIR", "Locked"); - authTypeList.add(authTypeMap); - data.put("authTypes", authTypeList); - data.put("requestId", "0839c2bf-5be5-4359-b860-6f9bda908378"); - event.setData(data); - eventModel.setEvent(event); - webSubUpdateAuthTypeService.updateAuthTypeStatus(eventModel); - } -} \ No newline at end of file diff --git a/resident/resident-service/src/test/java/io/mosip/resident/test/validator/RequestHandlerRequestValidatorTest.java b/resident/resident-service/src/test/java/io/mosip/resident/test/validator/RequestHandlerRequestValidatorTest.java deleted file mode 100644 index 9fe2c5d5fb0..00000000000 --- a/resident/resident-service/src/test/java/io/mosip/resident/test/validator/RequestHandlerRequestValidatorTest.java +++ /dev/null @@ -1,505 +0,0 @@ -package io.mosip.resident.test.validator; - -import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.when; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import org.assertj.core.util.Lists; -import org.json.simple.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.springframework.core.env.Environment; -import org.springframework.test.context.junit4.SpringRunner; - -import com.fasterxml.jackson.databind.ObjectMapper; - -import io.mosip.kernel.core.exception.BaseCheckedException; -import io.mosip.kernel.core.exception.ServiceError; -import io.mosip.kernel.core.http.ResponseWrapper; -import io.mosip.kernel.core.idvalidator.exception.InvalidIDException; -import io.mosip.kernel.core.idvalidator.spi.UinValidator; -import io.mosip.kernel.core.idvalidator.spi.VidValidator; -import io.mosip.resident.constant.CardType; -import io.mosip.resident.dto.LogDescription; -import io.mosip.resident.dto.MachineDto; -import io.mosip.resident.dto.MachineResponseDto; -import io.mosip.resident.dto.RegistrationCenterDto; -import io.mosip.resident.dto.RegistrationCenterResponseDto; -import io.mosip.resident.dto.RegistrationType; -import io.mosip.resident.exception.ApisResourceAccessException; -import io.mosip.resident.exception.IdRepoAppException; -import io.mosip.resident.exception.RequestHandlerValidationException; -import io.mosip.resident.exception.VidCreationException; -import io.mosip.resident.util.ResidentServiceRestClient; -import io.mosip.resident.util.Utilities; -import io.mosip.resident.validator.RequestHandlerRequestValidator; - -@RunWith(SpringRunner.class) -public class RequestHandlerRequestValidatorTest { - - @InjectMocks - private RequestHandlerRequestValidator requestHandlerRequestValidator; - - /** The rest client service. */ - @Mock - private ResidentServiceRestClient restClientService; - - /** The mapper. */ - @Mock - private ObjectMapper mapper = new ObjectMapper(); - - @Mock - private UinValidator uinValidatorImpl; - - /** The vid validator impl. */ - @Mock - private VidValidator vidValidatorImpl; - - /** The utilities. */ - @Mock - private Utilities utilities; - - @Mock - private Environment env; - - private static final String ID = "110011"; - - @Before - public void setup() throws ApisResourceAccessException, IOException { - Mockito.when(env.getProperty("mosip.mandatory-languages")).thenReturn("eng"); - Mockito.when(restClientService.getApi(any(), any(), anyString(), anyString(), any(Class.class))).thenReturn(new ResponseWrapper<>()); - Mockito.when(mapper.writeValueAsString(any())).thenReturn("String"); - } - - @Test(expected = RequestHandlerValidationException.class) - public void testValidateWithRequestHandlerValidationException() throws RequestHandlerValidationException { - requestHandlerRequestValidator.validate(ID); - } - - @Test(expected = RequestHandlerValidationException.class) - public void testValidateNullId() throws RequestHandlerValidationException { - requestHandlerRequestValidator.validate(null); - } - - @Test - public void testIsValidCenter() throws BaseCheckedException, IOException { - RegistrationCenterDto registrationCenterDto = new RegistrationCenterDto(); - RegistrationCenterResponseDto rcpdto = new RegistrationCenterResponseDto(); - rcpdto.setRegistrationCenters(Lists.newArrayList(registrationCenterDto)); - - Mockito.when(mapper.readValue(anyString(), any(Class.class))).thenReturn(rcpdto); - - boolean result = requestHandlerRequestValidator.isValidCenter(ID); - assertTrue(result); - } - - @Test(expected = BaseCheckedException.class) - public void testIsValidCenterNestedElse() throws BaseCheckedException, IOException { - RegistrationCenterDto registrationCenterDto = new RegistrationCenterDto(); - ServiceError error=new ServiceError(); - error.setErrorCode("invalid-101"); - error.setMessage("invalid center"); - List errorList=new ArrayList(); - errorList.add(error); - ResponseWrapper wrapper=new ResponseWrapper<>(); - wrapper.setErrors(errorList); - RegistrationCenterResponseDto rcpdto = new RegistrationCenterResponseDto(); - rcpdto.setRegistrationCenters(Lists.newArrayList(registrationCenterDto)); - when(restClientService.getApi(any(), any(), anyString(), anyString(), any())).thenReturn(wrapper); - Mockito.when(mapper.readValue(anyString(), any(Class.class))).thenReturn(rcpdto); - - requestHandlerRequestValidator.isValidCenter(ID); - } - - @Test(expected = BaseCheckedException.class) - public void testIsValidCenterElse() throws BaseCheckedException, IOException { - requestHandlerRequestValidator.isValidCenter(""); - } - - @Test(expected = BaseCheckedException.class) - public void testIsValidCenterElse2() throws BaseCheckedException, IOException { - requestHandlerRequestValidator.isValidCenter(null); - } - - @Test - public void testIsValidCenterWithApisResourceAccessException() throws BaseCheckedException, IOException { - RegistrationCenterDto registrationCenterDto = new RegistrationCenterDto(); - ServiceError error=new ServiceError(); - error.setErrorCode("invalid-101"); - error.setMessage("invalid center"); - List errorList=new ArrayList(); - errorList.add(error); - ResponseWrapper wrapper=new ResponseWrapper<>(); - wrapper.setErrors(errorList); - RegistrationCenterResponseDto rcpdto = new RegistrationCenterResponseDto(); - rcpdto.setRegistrationCenters(Lists.newArrayList(registrationCenterDto)); - when(restClientService.getApi(any(), any(), anyString(), anyString(), any())).thenThrow(new ApisResourceAccessException("error")); -// when(restClientService.getApi(any(), any(), anyString(), anyString(), any())).thenThrow(new ApisResourceAccessException("error", new HttpClientErrorException(HttpStatus.OK))); -// Mockito.when(mapper.readValue(anyString(), any(Class.class))).thenThrow(ApisResourceAccessException.class); - - requestHandlerRequestValidator.isValidCenter(ID); - } - - @Test - public void testIsValidMachine() throws BaseCheckedException, IOException { - MachineDto registrationCenterDto = new MachineDto(); - MachineResponseDto machinedto = new MachineResponseDto(); - machinedto.setMachines(Lists.newArrayList(registrationCenterDto)); - - Mockito.when(mapper.readValue(anyString(), any(Class.class))).thenReturn(machinedto); - - boolean result = requestHandlerRequestValidator.isValidMachine(ID); - assertTrue(result); - } - - @Test(expected = BaseCheckedException.class) - public void testIsValidMachineNestedElse() throws BaseCheckedException, IOException{ - MachineDto registrationCenterDto = new MachineDto(); - ServiceError error=new ServiceError(); - error.setErrorCode("invalid-101"); - error.setMessage("invalid center"); - List errorList=new ArrayList(); - errorList.add(error); - ResponseWrapper wrapper=new ResponseWrapper<>(); - wrapper.setErrors(errorList); - MachineResponseDto machinedto = new MachineResponseDto(); - machinedto.setMachines(Lists.newArrayList(registrationCenterDto)); - - when(restClientService.getApi(any(), any(), anyString(), anyString(), any())).thenReturn(wrapper); - Mockito.when(mapper.readValue(anyString(), any(Class.class))).thenReturn(machinedto); - - requestHandlerRequestValidator.isValidMachine(ID); - } - - @Test(expected = BaseCheckedException.class) - public void testIsValidMachineElse() throws BaseCheckedException, IOException{ - requestHandlerRequestValidator.isValidMachine(null); - } - - @Test(expected = BaseCheckedException.class) - public void testIsValidMachineElse2() throws BaseCheckedException, IOException{ - requestHandlerRequestValidator.isValidMachine(""); - } - - @Test - public void testIsValidMachineWithApisResourceAccessException() throws BaseCheckedException, IOException{ - MachineDto registrationCenterDto = new MachineDto(); - ServiceError error=new ServiceError(); - error.setErrorCode("invalid-101"); - error.setMessage("invalid center"); - List errorList=new ArrayList(); - errorList.add(error); - ResponseWrapper wrapper=new ResponseWrapper<>(); - wrapper.setErrors(errorList); - MachineResponseDto machinedto = new MachineResponseDto(); - machinedto.setMachines(Lists.newArrayList(registrationCenterDto)); - - when(restClientService.getApi(any(), any(), anyString(), anyString(), any())).thenThrow(new ApisResourceAccessException("error")); -// when(restClientService.getApi(any(), any(), anyString(), anyString(), any())).thenThrow(new ApisResourceAccessException("error", new HttpClientErrorException(HttpStatus.OK))); -// Mockito.when(mapper.readValue(anyString(), any(Class.class))).thenThrow(ApisResourceAccessException.class); - - requestHandlerRequestValidator.isValidMachine(ID); - } - - @Test - public void testIsValidUin() throws BaseCheckedException, IOException { - JSONObject jsonObject = new JSONObject(); - Mockito.when(uinValidatorImpl.validateId(anyString())).thenReturn(true); - Mockito.when(utilities.retrieveIdrepoJson(anyString())).thenReturn(jsonObject); - - boolean result = requestHandlerRequestValidator.isValidUin("1234"); - assertTrue(result); - } - - @Test(expected = BaseCheckedException.class) - public void testIsValidUinElse1() throws BaseCheckedException, IOException { - JSONObject jsonObject = new JSONObject(); - when(uinValidatorImpl.validateId(anyString())).thenReturn(true); - when(utilities.retrieveIdrepoJson(anyString())).thenReturn(null); - - requestHandlerRequestValidator.isValidUin("1234"); - } - - @Test(expected = BaseCheckedException.class) - public void testIsValidUinElse2() throws BaseCheckedException, IOException { - JSONObject jsonObject = new JSONObject(); - when(uinValidatorImpl.validateId(anyString())).thenReturn(false); - when(utilities.retrieveIdrepoJson(anyString())).thenReturn(jsonObject); - - requestHandlerRequestValidator.isValidUin("1234"); - } - - @Test(expected = BaseCheckedException.class) - public void testIsValidUinWithInvalidIDException() throws BaseCheckedException, IOException { - JSONObject jsonObject = new JSONObject(); - Mockito.when(uinValidatorImpl.validateId(anyString())).thenReturn(true); - Mockito.when(utilities.retrieveIdrepoJson(anyString())).thenThrow(new InvalidIDException("errorcode", "message")); - - requestHandlerRequestValidator.isValidUin("1234"); - } - - @Test(expected = BaseCheckedException.class) - public void testIsValidUinWithIdRepoAppException() throws BaseCheckedException, IOException { - JSONObject jsonObject = new JSONObject(); - Mockito.when(uinValidatorImpl.validateId(anyString())).thenReturn(true); - Mockito.when(utilities.retrieveIdrepoJson(anyString())).thenThrow(new IdRepoAppException("errorcode", "message")); - - requestHandlerRequestValidator.isValidUin("1234"); - } - - @Test(expected = BaseCheckedException.class) - public void testIsValidUinWithNumberFormatException() throws BaseCheckedException, IOException { - JSONObject jsonObject = new JSONObject(); - Mockito.when(uinValidatorImpl.validateId(anyString())).thenReturn(true); - Mockito.when(utilities.retrieveIdrepoJson(anyString())).thenThrow(new NumberFormatException("errorcode")); - - requestHandlerRequestValidator.isValidUin("1234"); - } - - @Test(expected = BaseCheckedException.class) - public void testIsValidUinWithApisResourceAccessException() throws BaseCheckedException, IOException { - JSONObject jsonObject = new JSONObject(); - Mockito.when(uinValidatorImpl.validateId(anyString())).thenReturn(true); - Mockito.when(utilities.retrieveIdrepoJson(anyString())).thenThrow(new ApisResourceAccessException("errorcode")); - - requestHandlerRequestValidator.isValidUin("1234"); - } - - @Test(expected = BaseCheckedException.class) - public void testIsValidUinWithIOException() throws BaseCheckedException, IOException { - JSONObject jsonObject = new JSONObject(); - Mockito.when(uinValidatorImpl.validateId(anyString())).thenReturn(true); - Mockito.when(utilities.retrieveIdrepoJson(anyString())).thenThrow(new IOException("errorcode")); - - requestHandlerRequestValidator.isValidUin("1234"); - } - - @Test - public void testIsValidRePrintRegistrationType() throws BaseCheckedException, IOException { - boolean result = requestHandlerRequestValidator.isValidRePrintRegistrationType(RegistrationType.RES_REPRINT.name()); - assertTrue(result); - } - - @Test(expected = BaseCheckedException.class) - public void testIsValidRePrintRegistrationTypeElse() throws BaseCheckedException { - requestHandlerRequestValidator.isValidRePrintRegistrationType("LOST"); - } - - @Test(expected = BaseCheckedException.class) - public void testIsValidRePrintRegistrationTypeElse2() throws BaseCheckedException { - requestHandlerRequestValidator.isValidRePrintRegistrationType(null); - } - - @Test - public void testIsValidRegistrationTypeAndUinNestedNestedIf11() throws BaseCheckedException, IOException{ - when(uinValidatorImpl.validateId(anyString())).thenReturn(true); - when(utilities.retrieveIdrepoJsonStatus(anyString())).thenReturn("ACTIVATED"); - JSONObject idObject=new JSONObject(); - when(utilities.retrieveIdrepoJson(anyString())).thenReturn(idObject); - boolean result=requestHandlerRequestValidator.isValidRegistrationTypeAndUin(RegistrationType.RES_UPDATE.name(), "1234"); - assertTrue(result); - } - - @Test(expected = BaseCheckedException.class) - public void testIsValidRegistrationTypeAndUinNestedNestedIf12() throws BaseCheckedException, IOException{ - when(uinValidatorImpl.validateId(anyString())).thenReturn(true); - when(utilities.retrieveIdrepoJsonStatus(anyString())).thenReturn("ACTIVATED"); - when(utilities.retrieveIdrepoJson(anyString())).thenReturn(null); - requestHandlerRequestValidator.isValidRegistrationTypeAndUin(RegistrationType.RES_UPDATE.name(), "1234"); - } - - @Test(expected = BaseCheckedException.class) - public void testIsValidRegistrationTypeAndUinNestedNestedIf13() throws BaseCheckedException, IOException{ - when(uinValidatorImpl.validateId(anyString())).thenReturn(true); - when(utilities.retrieveIdrepoJsonStatus(anyString())).thenReturn("any status"); - when(utilities.retrieveIdrepoJson(anyString())).thenReturn(new JSONObject()); - requestHandlerRequestValidator.isValidRegistrationTypeAndUin(RegistrationType.RES_UPDATE.name(), "1234"); - } - - @Test - public void testIsValidRegistrationTypeAndUinNestedNestedIf21() throws BaseCheckedException, IOException{ - when(uinValidatorImpl.validateId(anyString())).thenReturn(true); - when(utilities.retrieveIdrepoJsonStatus(anyString())).thenReturn("ACTIVATED"); - boolean result=requestHandlerRequestValidator.isValidRegistrationTypeAndUin(RegistrationType.DEACTIVATED.name(), "1234"); - assertTrue(result); - } - - @Test(expected = BaseCheckedException.class) - public void testIsValidRegistrationTypeAndUinNestedNestedElse21() throws BaseCheckedException, IOException{ - when(uinValidatorImpl.validateId(anyString())).thenReturn(true); - when(utilities.retrieveIdrepoJsonStatus(anyString())).thenReturn("ACTIVATED"); - requestHandlerRequestValidator.isValidRegistrationTypeAndUin(RegistrationType.ACTIVATED.name(), "1234"); - } - - @Test(expected = BaseCheckedException.class) - public void testIsValidRegistrationTypeAndUinNestedElse() throws BaseCheckedException, IOException{ - when(uinValidatorImpl.validateId(anyString())).thenReturn(false); - - requestHandlerRequestValidator.isValidRegistrationTypeAndUin(RegistrationType.ACTIVATED.name(), "1234"); - } - - @Test(expected = BaseCheckedException.class) - public void testIsValidRegistrationTypeAndUinElse1() throws BaseCheckedException, IOException{ - requestHandlerRequestValidator.isValidRegistrationTypeAndUin(null, "1234"); - } - - @Test(expected = BaseCheckedException.class) - public void testIsValidRegistrationTypeAndUinElse2() throws BaseCheckedException, IOException{ - requestHandlerRequestValidator.isValidRegistrationTypeAndUin("any registration", "1234"); - } - - @Test(expected = BaseCheckedException.class) - public void testIsValidRegistrationTypeAndUinWithInvalidIDException() throws BaseCheckedException, IOException{ - when(uinValidatorImpl.validateId(anyString())).thenReturn(true); - when(utilities.retrieveIdrepoJsonStatus(anyString())).thenThrow(new InvalidIDException("errorcode", "message")); - requestHandlerRequestValidator.isValidRegistrationTypeAndUin(RegistrationType.RES_UPDATE.name(), "1234"); - } - - @Test(expected = BaseCheckedException.class) - public void testIsValidRegistrationTypeAndUinWithNumberFormatException() throws BaseCheckedException, IOException{ - when(uinValidatorImpl.validateId(anyString())).thenReturn(true); - when(utilities.retrieveIdrepoJsonStatus(anyString())).thenThrow(new NumberFormatException("message")); - requestHandlerRequestValidator.isValidRegistrationTypeAndUin(RegistrationType.RES_UPDATE.name(), "1234"); - } - - @Test - public void testIsValidVid() throws BaseCheckedException, IOException{ - String str="vid"; - when(vidValidatorImpl.validateId(anyString())).thenReturn(true); - when(utilities.getUinByVid(anyString())).thenReturn(str); - boolean result=requestHandlerRequestValidator.isValidVid(ID); - assertTrue(result); - } - - @Test(expected = BaseCheckedException.class) - public void testIsValidVidElse() throws BaseCheckedException, IOException{ - String str="vid"; - when(vidValidatorImpl.validateId(anyString())).thenReturn(false); - when(utilities.getUinByVid(anyString())).thenReturn(str); - requestHandlerRequestValidator.isValidVid(ID); - } - - @Test(expected = BaseCheckedException.class) - public void testIsValidVidElse2() throws BaseCheckedException, IOException{ - when(vidValidatorImpl.validateId(anyString())).thenReturn(true); - when(utilities.getUinByVid(anyString())).thenReturn(null); - requestHandlerRequestValidator.isValidVid(ID); - } - - @Test(expected = BaseCheckedException.class) - public void testIsValidVidWithInvalidIDException() throws BaseCheckedException, IOException{ - when(vidValidatorImpl.validateId(anyString())).thenReturn(true); - when(utilities.getUinByVid(anyString())).thenThrow(new InvalidIDException("errorcode", "message")); - requestHandlerRequestValidator.isValidVid(ID); - } - - @Test(expected = BaseCheckedException.class) - public void testIsValidVidWithIdRepoAppException() throws BaseCheckedException, IOException{ - when(vidValidatorImpl.validateId(anyString())).thenReturn(true); - when(utilities.getUinByVid(anyString())).thenThrow(new IdRepoAppException("errorcode", "message")); - requestHandlerRequestValidator.isValidVid(ID); - } - - @Test(expected = BaseCheckedException.class) - public void testIsValidVidWithNumberFormatException() throws BaseCheckedException, IOException{ - when(vidValidatorImpl.validateId(anyString())).thenReturn(true); - when(utilities.getUinByVid(anyString())).thenThrow(new NumberFormatException("message")); - requestHandlerRequestValidator.isValidVid(ID); - } - - @Test(expected = BaseCheckedException.class) - public void testIsValidVidWithApisResourceAccessException() throws BaseCheckedException, IOException{ - when(vidValidatorImpl.validateId(anyString())).thenReturn(true); - when(utilities.getUinByVid(anyString())).thenThrow(new ApisResourceAccessException("message")); - requestHandlerRequestValidator.isValidVid(ID); - } - - @Test(expected = BaseCheckedException.class) - public void testIsValidVidWithVidCreationException() throws BaseCheckedException, IOException{ - when(vidValidatorImpl.validateId(anyString())).thenReturn(true); - when(utilities.getUinByVid(anyString())).thenThrow(new VidCreationException("message")); - requestHandlerRequestValidator.isValidVid(ID); - } - - @Test - public void testIsValidIdType() throws Exception{ - boolean result=requestHandlerRequestValidator.isValidIdType("UIN"); - assertTrue(result); - } - - @Test - public void testIsValidIdType2() throws BaseCheckedException { - boolean result = requestHandlerRequestValidator.isValidIdType("VID"); - assertTrue(result); - } - - @Test(expected = BaseCheckedException.class) - public void testIsValidIdTypeElse() throws BaseCheckedException { - requestHandlerRequestValidator.isValidIdType(null); - } - - @Test(expected = BaseCheckedException.class) - public void testIsValidIdTypeElse2() throws BaseCheckedException { - requestHandlerRequestValidator.isValidIdType(""); - } - - @Test - public void testIsValidCardType() throws BaseCheckedException, IOException { - boolean result = requestHandlerRequestValidator.isValidCardType(CardType.MASKED_UIN.name()); - assertTrue(result); - } - - @Test - public void testIsValidCardType2() throws BaseCheckedException, IOException { - boolean result = requestHandlerRequestValidator.isValidCardType(CardType.UIN.name()); - assertTrue(result); - } - - @Test(expected = BaseCheckedException.class) - public void testIsValidCardTypeElse() throws BaseCheckedException { - requestHandlerRequestValidator.isValidCardType("voter-id"); - } - - @Test(expected = BaseCheckedException.class) - public void testIsValidCardTypeElse2() throws BaseCheckedException { - requestHandlerRequestValidator.isValidCardType(""); - } - - @Test(expected = BaseCheckedException.class) - public void testIsValidCardTypeElse3() throws BaseCheckedException { - requestHandlerRequestValidator.isValidCardType(null); - } - - @Test - public void testIsValidContact() throws BaseCheckedException, IOException { - String EMAIL = "Email"; - boolean result = requestHandlerRequestValidator.isValidContactType(EMAIL, new LogDescription()); - assertTrue(result); - } - - @Test - public void testIsValidContact2() throws BaseCheckedException, IOException { - String PHONE = "Phone"; - boolean result = requestHandlerRequestValidator.isValidContactType(PHONE, new LogDescription()); - assertTrue(result); - } - - @Test(expected = BaseCheckedException.class) - public void testIsValidContactElse() throws BaseCheckedException { - requestHandlerRequestValidator.isValidContactType("whatsapp", new LogDescription()); - } - - @Test(expected = BaseCheckedException.class) - public void testIsValidContactElse2() throws BaseCheckedException { - requestHandlerRequestValidator.isValidContactType(null, new LogDescription()); - } -} diff --git a/resident/resident-service/src/test/java/io/mosip/resident/test/util/AuditUtilTest.java b/resident/resident-service/src/test/java/io/mosip/resident/util/AuditUtilTest.java similarity index 79% rename from resident/resident-service/src/test/java/io/mosip/resident/test/util/AuditUtilTest.java rename to resident/resident-service/src/test/java/io/mosip/resident/util/AuditUtilTest.java index fa9bbf4e498..737a8ae03cf 100644 --- a/resident/resident-service/src/test/java/io/mosip/resident/test/util/AuditUtilTest.java +++ b/resident/resident-service/src/test/java/io/mosip/resident/util/AuditUtilTest.java @@ -1,4 +1,4 @@ -package io.mosip.resident.test.util; +package io.mosip.resident.util; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; @@ -36,11 +36,12 @@ import io.mosip.kernel.core.http.RequestWrapper; import io.mosip.kernel.core.http.ResponseWrapper; import io.mosip.kernel.core.util.DateUtils; +import io.mosip.resident.constant.ResidentConstants; import io.mosip.resident.dto.AuditRequestDTO; +import io.mosip.resident.exception.ApisResourceAccessException; import io.mosip.resident.service.impl.IdentityServiceImpl; -import io.mosip.resident.util.AuditResponseDto; -import io.mosip.resident.util.AuditUtil; -import io.mosip.resident.util.EventEnum; +import reactor.util.function.Tuple2; +import reactor.util.function.Tuples; /** * @author Abubacker Siddik @@ -108,10 +109,17 @@ public void setAuditRequestDtoTest() throws Exception { ResponseEntity response = ResponseEntity.ok(responseString); AuditRequestDTO auditRequestDto = new AuditRequestDTO(); + auditRequestDto.setId("9054257143"); + auditRequestDto.setIdType("UIN"); RequestWrapper auditRequestWrapper = new RequestWrapper<>(); auditRequestWrapper.setRequest(auditRequestDto); when(restTemplate.exchange(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(Class.class), Mockito.any(Object.class))).thenReturn(response); when(objectMapper.readValue(Mockito.anyString(), Mockito.any(TypeReference.class))).thenReturn(responseWrapper); + String individualId = "9054257143"; + String refIdType = "UIN"; + Mockito.when(identityService.getResidentIndvidualIdFromSession()).thenReturn(individualId); + Mockito.when(identityService.getIndividualIdType(individualId)).thenReturn(refIdType); + auditUtil.setAuditRequestDto(eventEnum); verify(restTemplate, times(1)).exchange(stringCaptor.capture(), Mockito.any(), httpEntityCaptor.capture(), Mockito.any(Class.class), Mockito.any(Object.class)); @@ -126,22 +134,40 @@ public void setAuditRequestDtoTest() throws Exception { assertEquals(eventEnum.getType(), httpEntity.getBody().getRequest().getEventType()); assertEquals(eventEnum.getName(), httpEntity.getBody().getRequest().getEventName()); assertEquals(eventEnum.getEventId(), httpEntity.getBody().getRequest().getEventId()); - assertEquals(eventEnum.getId(), httpEntity.getBody().getRequest().getId()); - assertEquals(eventEnum.getIdType(), httpEntity.getBody().getRequest().getIdType()); assertEquals(eventEnum.getModuleId(), httpEntity.getBody().getRequest().getModuleId()); assertEquals(eventEnum.getModuleName(), httpEntity.getBody().getRequest().getModuleName()); + assertEquals("07DDDD711B7311BAE05A09F36479BAF78EA4FF1B91603A9704A2D59206766308", + httpEntity.getBody().getRequest().getId()); + assertEquals("UIN", httpEntity.getBody().getRequest().getIdType()); assertEquals(host.getHostName(), httpEntity.getBody().getRequest().getHostName()); assertEquals(host.getHostAddress(), httpEntity.getBody().getRequest().getHostIp()); assertEquals("user1", httpEntity.getBody().getRequest().getSessionUserId()); assertEquals("user1", httpEntity.getBody().getRequest().getSessionUserName()); - assertEquals("RESIDENT", httpEntity.getBody().getRequest().getCreatedBy()); + assertEquals("user1", httpEntity.getBody().getRequest().getCreatedBy()); assertEquals(localDateTime, httpEntity.getBody().getRequest().getActionTimeStamp()); assertEquals(auditUrlInput, auditUrl); } + + @Test + public void testGetRefIdandTypeNoID() { + Tuple2 response = auditUtil.getRefIdandType(); + assertEquals(Tuples.of(ResidentConstants.NO_ID, ResidentConstants.NO_ID_TYPE), response); + } + + @Test + public void testGetRefIdandType() throws ApisResourceAccessException { + String individualId = "9054257143"; + String refIdType = "UIN"; + Mockito.when(identityService.getResidentIndvidualIdFromSession()).thenReturn(individualId); + Mockito.when(identityService.getIndividualIdType(individualId)).thenReturn(refIdType); + Tuple2 refIdandType = auditUtil.getRefIdandType(); + assertEquals(Tuples.of("07DDDD711B7311BAE05A09F36479BAF78EA4FF1B91603A9704A2D59206766308", "UIN"), + refIdandType); + } } diff --git a/resident/resident-service/src/test/java/io/mosip/resident/test/util/EncryptorUtilTest.java b/resident/resident-service/src/test/java/io/mosip/resident/util/EncryptorUtilTest.java similarity index 97% rename from resident/resident-service/src/test/java/io/mosip/resident/test/util/EncryptorUtilTest.java rename to resident/resident-service/src/test/java/io/mosip/resident/util/EncryptorUtilTest.java index 19881e24701..89eb2798c35 100644 --- a/resident/resident-service/src/test/java/io/mosip/resident/test/util/EncryptorUtilTest.java +++ b/resident/resident-service/src/test/java/io/mosip/resident/util/EncryptorUtilTest.java @@ -1,4 +1,4 @@ -package io.mosip.resident.test.util; +package io.mosip.resident.util; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; @@ -32,8 +32,6 @@ import io.mosip.kernel.core.http.RequestWrapper; import io.mosip.kernel.core.util.DateUtils; import io.mosip.resident.dto.CryptomanagerRequestDto; -import io.mosip.resident.util.EncryptorUtil; -import io.mosip.resident.util.ResidentServiceRestClient; /** * @author Abubacker Siddik diff --git a/resident/resident-service/src/test/java/io/mosip/resident/test/util/IdSchemaUtilTest.java b/resident/resident-service/src/test/java/io/mosip/resident/util/IdSchemaUtilTest.java similarity index 99% rename from resident/resident-service/src/test/java/io/mosip/resident/test/util/IdSchemaUtilTest.java rename to resident/resident-service/src/test/java/io/mosip/resident/util/IdSchemaUtilTest.java index fb361634b55..cbda48b546a 100644 --- a/resident/resident-service/src/test/java/io/mosip/resident/test/util/IdSchemaUtilTest.java +++ b/resident/resident-service/src/test/java/io/mosip/resident/util/IdSchemaUtilTest.java @@ -1,4 +1,4 @@ -package io.mosip.resident.test.util; +package io.mosip.resident.util; import static io.mosip.resident.util.IdSchemaUtil.RESPONSE; import static io.mosip.resident.util.IdSchemaUtil.SCHEMA_JSON; @@ -31,8 +31,6 @@ import io.mosip.kernel.core.util.DateUtils; import io.mosip.resident.constant.ApiName; import io.mosip.resident.exception.ApisResourceAccessException; -import io.mosip.resident.util.IdSchemaUtil; -import io.mosip.resident.util.ResidentServiceRestClient; /** * @author Abubacker Siddik diff --git a/resident/resident-service/src/test/java/io/mosip/resident/test/util/JsonUtilTest.java b/resident/resident-service/src/test/java/io/mosip/resident/util/JsonUtilTest.java similarity index 98% rename from resident/resident-service/src/test/java/io/mosip/resident/test/util/JsonUtilTest.java rename to resident/resident-service/src/test/java/io/mosip/resident/util/JsonUtilTest.java index 1544fa0dafc..04ec7b7f5c6 100644 --- a/resident/resident-service/src/test/java/io/mosip/resident/test/util/JsonUtilTest.java +++ b/resident/resident-service/src/test/java/io/mosip/resident/util/JsonUtilTest.java @@ -1,4 +1,4 @@ -package io.mosip.resident.test.util; +package io.mosip.resident.util; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; diff --git a/resident/resident-service/src/test/java/io/mosip/resident/test/util/ResidentServiceRestClientTest.java b/resident/resident-service/src/test/java/io/mosip/resident/util/ResidentServiceRestClientTest.java similarity index 99% rename from resident/resident-service/src/test/java/io/mosip/resident/test/util/ResidentServiceRestClientTest.java rename to resident/resident-service/src/test/java/io/mosip/resident/util/ResidentServiceRestClientTest.java index a6622b1fb80..4c86f6017ec 100644 --- a/resident/resident-service/src/test/java/io/mosip/resident/test/util/ResidentServiceRestClientTest.java +++ b/resident/resident-service/src/test/java/io/mosip/resident/util/ResidentServiceRestClientTest.java @@ -1,4 +1,4 @@ -package io.mosip.resident.test.util; +package io.mosip.resident.util; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; @@ -38,7 +38,6 @@ import io.mosip.resident.constant.ApiName; import io.mosip.resident.dto.AutnTxnResponseDto; import io.mosip.resident.exception.ApisResourceAccessException; -import io.mosip.resident.util.ResidentServiceRestClient; @RunWith(MockitoJUnitRunner.class) public class ResidentServiceRestClientTest { diff --git a/resident/resident-service/src/test/java/io/mosip/resident/test/util/ServerUtilTest.java b/resident/resident-service/src/test/java/io/mosip/resident/util/ServerUtilTest.java similarity index 91% rename from resident/resident-service/src/test/java/io/mosip/resident/test/util/ServerUtilTest.java rename to resident/resident-service/src/test/java/io/mosip/resident/util/ServerUtilTest.java index ef3d9206274..b6ed0cfa697 100644 --- a/resident/resident-service/src/test/java/io/mosip/resident/test/util/ServerUtilTest.java +++ b/resident/resident-service/src/test/java/io/mosip/resident/util/ServerUtilTest.java @@ -1,4 +1,4 @@ -package io.mosip.resident.test.util; +package io.mosip.resident.util; import static org.junit.Assert.assertTrue; @@ -10,8 +10,6 @@ import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.modules.junit4.PowerMockRunner; -import io.mosip.resident.util.ServerUtil; - @RunWith(PowerMockRunner.class) @PowerMockIgnore({"com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "javax.management.*"}) public class ServerUtilTest { diff --git a/resident/resident-service/src/test/java/io/mosip/resident/util/TemplateUtilTest.java b/resident/resident-service/src/test/java/io/mosip/resident/util/TemplateUtilTest.java new file mode 100644 index 00000000000..ef0a45616e9 --- /dev/null +++ b/resident/resident-service/src/test/java/io/mosip/resident/util/TemplateUtilTest.java @@ -0,0 +1,533 @@ +package io.mosip.resident.util; + +import static junit.framework.TestCase.assertEquals; + +import java.time.LocalDateTime; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.Map; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.springframework.core.env.Environment; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.util.ReflectionTestUtils; + +import io.mosip.kernel.core.http.ResponseWrapper; +import io.mosip.resident.constant.EventStatus; +import io.mosip.resident.constant.EventStatusFailure; +import io.mosip.resident.constant.EventStatusInProgress; +import io.mosip.resident.constant.EventStatusSuccess; +import io.mosip.resident.constant.RequestType; +import io.mosip.resident.constant.ResidentConstants; +import io.mosip.resident.constant.TemplateType; +import io.mosip.resident.constant.TemplateVariablesConstants; +import io.mosip.resident.dto.NotificationTemplateVariableDTO; +import io.mosip.resident.entity.ResidentTransactionEntity; +import io.mosip.resident.exception.ApisResourceAccessException; +import io.mosip.resident.exception.ResidentServiceCheckedException; +import io.mosip.resident.exception.ResidentServiceException; +import io.mosip.resident.handler.service.ResidentConfigService; +import io.mosip.resident.repository.ResidentTransactionRepository; +import io.mosip.resident.service.ProxyMasterdataService; +import io.mosip.resident.service.impl.IdentityServiceImpl; +import io.mosip.resident.service.impl.IdentityServiceTest; +import io.mosip.resident.service.impl.ProxyPartnerManagementServiceImpl; +import io.mosip.resident.service.impl.ResidentServiceImpl; +import io.mosip.resident.validator.RequestValidator; + +/** + * This class is used to test the TemplateUtil class + * @author Kamesh Shekhar Prasad + */ + +@RunWith(SpringRunner.class) +public class TemplateUtilTest { + + @InjectMocks + private TemplateUtil templateUtil = new TemplateUtil(); + + @Mock + private ResidentTransactionRepository residentTransactionRepository; + + @Mock + private IdentityServiceImpl identityServiceImpl; + + @Mock + private RequestValidator validator; + + @Mock + private Utility utility; + + @Mock + private ProxyPartnerManagementServiceImpl proxyPartnerManagementServiceImpl; + + @Mock + private Environment environment; + + @Mock + private ResidentServiceImpl residentService; + + @Mock + private ResidentConfigService residentConfigService; + + @Mock + private ProxyMasterdataService proxyMasterdataService; + + private String eventId; + private ResidentTransactionEntity residentTransactionEntity; + + private NotificationTemplateVariableDTO dto; + + private static final String OTP = "otp"; + + private static final String PROPERTY = "YYYY-MM-DD HH:MM:SS"; + + private static final String LOCALE_EN_US = "en-US"; + + private Map templateResponse; + private ResponseWrapper responseWrapper; + private Map templateVariables; + private Map values; + + @Before + public void setUp() throws ApisResourceAccessException, ResidentServiceCheckedException { + eventId = "12345"; + residentTransactionEntity = new ResidentTransactionEntity(); + residentTransactionEntity.setEventId(eventId); + residentTransactionEntity.setRequestTypeCode(RequestType.AUTHENTICATION_REQUEST.name()); + residentTransactionEntity.setPurpose("Test"); + residentTransactionEntity.setStatusCode(EventStatusSuccess.AUTHENTICATION_SUCCESSFULL.name()); + residentTransactionEntity.setRequestSummary("Test"); + residentTransactionEntity.setAuthTypeCode("otp"); + residentTransactionEntity.setAttributeList("YYYY-MM-DD HH:MM:SS"); + residentTransactionEntity.setCrDtimes(LocalDateTime.now()); + Mockito.when(residentTransactionRepository.findById(eventId)).thenReturn(java.util.Optional.ofNullable(residentTransactionEntity)); + Mockito.when(identityServiceImpl.getResidentIndvidualIdFromSession()).thenReturn(eventId); + Mockito.when(validator.validateUin(Mockito.anyString())).thenReturn(true); + ReflectionTestUtils.setField(templateUtil, "templateDatePattern", "dd-MM-yyyy"); + ReflectionTestUtils.setField(templateUtil, "templateTimePattern", "HH:mm:ss"); + Mockito.when(environment.getProperty(Mockito.anyString())).thenReturn(PROPERTY); + dto = new NotificationTemplateVariableDTO(eventId, RequestType.AUTHENTICATION_REQUEST, TemplateType.SUCCESS, "eng", "111111"); + templateResponse = new LinkedHashMap<>(); + templateVariables = new LinkedHashMap<>(); + values = new LinkedHashMap<>(); + values.put("test", String.class); + templateVariables.put("eventId", eventId); + responseWrapper = new ResponseWrapper<>(); + templateResponse.put(ResidentConstants.FILE_TEXT, "otp"); + responseWrapper.setResponse(templateResponse); + Mockito.when(proxyMasterdataService.getAllTemplateBylangCodeAndTemplateTypeCode(Mockito.anyString(), Mockito.anyString())).thenReturn( + responseWrapper); + Mockito.when(residentService.getEventStatusCode(Mockito.anyString())).thenReturn(EventStatus.SUCCESS.getStatus()); + } + + @Test + public void getAckTemplateVariablesForAuthenticationRequest() { + Map ackTemplateVariables = templateUtil.getAckTemplateVariablesForAuthenticationRequest(eventId, "eng", 0, LOCALE_EN_US).getT1(); + assertEquals(EventStatus.SUCCESS.getStatus(),ackTemplateVariables.get(TemplateVariablesConstants.EVENT_STATUS)); + } + + @Test + public void getAckTemplateVariablesForCredentialShare() { + Map ackTemplateVariables = templateUtil.getAckTemplateVariablesForCredentialShare( eventId, "eng", 0, LOCALE_EN_US).getT1(); + assertEquals(OTP,ackTemplateVariables.get(TemplateVariablesConstants.AUTHENTICATION_MODE)); + } + + @Test + public void getAckTemplateVariablesForDownloadPersonalizedCard() { + Map ackTemplateVariables = templateUtil.getAckTemplateVariablesForDownloadPersonalizedCard( eventId, "eng", 0, LOCALE_EN_US).getT1(); + assertEquals(OTP,ackTemplateVariables.get(TemplateVariablesConstants.AUTHENTICATION_MODE)); + } + + @Test + public void getAckTemplateVariablesForOrderPhysicalCard() { + Map ackTemplateVariables = templateUtil.getAckTemplateVariablesForOrderPhysicalCard( eventId, "eng", 0, LOCALE_EN_US).getT1(); + assertEquals(OTP,ackTemplateVariables.get(TemplateVariablesConstants.AUTHENTICATION_MODE)); + } + + @Test + public void getAckTemplateVariablesForOrderPhysicalCardPaymentFailed() { + residentTransactionEntity.setStatusCode(EventStatusFailure.PAYMENT_FAILED.name()); + Mockito.when(residentTransactionRepository.findById(eventId)).thenReturn(java.util.Optional.ofNullable(residentTransactionEntity)); + Map ackTemplateVariables = templateUtil.getAckTemplateVariablesForOrderPhysicalCard( eventId, "eng", 0, LOCALE_EN_US).getT1(); + assertEquals(OTP,ackTemplateVariables.get(TemplateVariablesConstants.AUTHENTICATION_MODE)); + } + + @Test + public void getAckTemplateVariablesForGetMyId() { + Map ackTemplateVariables = templateUtil.getAckTemplateVariablesForGetMyId( eventId, "eng", 0, LOCALE_EN_US).getT1(); + assertEquals(eventId,ackTemplateVariables.get(TemplateVariablesConstants.EVENT_ID)); + } + + @Test + public void getAckTemplateVariablesForBookAnAppointment() { + Map ackTemplateVariables = templateUtil.getAckTemplateVariablesForBookAnAppointment( eventId, "eng", 0, LOCALE_EN_US).getT1(); + assertEquals(Collections.emptyMap(),ackTemplateVariables); + } + + @Test + public void getAckTemplateVariablesForUpdateMyUin() { + Map ackTemplateVariables = templateUtil.getAckTemplateVariablesForUpdateMyUin( eventId, "eng", 0, LOCALE_EN_US).getT1(); + assertEquals(OTP,ackTemplateVariables.get(TemplateVariablesConstants.AUTHENTICATION_MODE)); + } + + @Test + public void getAckTemplateVariablesForGenerateVid() { + Map ackTemplateVariables = templateUtil.getAckTemplateVariablesForGenerateVid( eventId, "eng", 0, LOCALE_EN_US).getT1(); + assertEquals(OTP,ackTemplateVariables.get(TemplateVariablesConstants.AUTHENTICATION_MODE)); + } + + @Test + public void getAckTemplateVariablesForRevokeVid() { + Map ackTemplateVariables = templateUtil.getAckTemplateVariablesForRevokeVid( eventId, "eng", 0, LOCALE_EN_US).getT1(); + assertEquals(OTP,ackTemplateVariables.get(TemplateVariablesConstants.AUTHENTICATION_MODE)); + } + + @Test + public void getAckTemplateVariablesForVerifyPhoneOrEmail() { + Map ackTemplateVariables = templateUtil.getAckTemplateVariablesForVerifyPhoneEmail( eventId, 0, LOCALE_EN_US); + assertEquals(eventId,ackTemplateVariables.get(TemplateVariablesConstants.EVENT_ID)); + } + + @Test + public void getAckTemplateVariablesForAuthLock() { + Map ackTemplateVariables = templateUtil.getAckTemplateVariablesForAuthTypeLockUnlock( eventId, "eng", 0, LOCALE_EN_US).getT1(); + assertEquals(OTP,ackTemplateVariables.get(TemplateVariablesConstants.AUTHENTICATION_MODE)); + } + + @Test(expected = ResidentServiceException.class) + public void getCommonTemplateVariablesTestBadEventId() { + Mockito.when(residentTransactionRepository.findById(eventId)).thenReturn(java.util.Optional.empty()); + templateUtil.getCommonTemplateVariables(eventId, "", 0, LOCALE_EN_US); + } + + @Test + public void getCommonTemplateVariablesTestFailedEventStatus() { + residentTransactionEntity.setStatusCode(EventStatusFailure.AUTHENTICATION_FAILED.name()); + Mockito.when(residentService.getEventStatusCode(Mockito.anyString())).thenReturn(EventStatus.FAILED.getStatus()); + assertEquals(EventStatus.FAILED.getStatus(),templateUtil.getCommonTemplateVariables(eventId, "eng", 0, LOCALE_EN_US).getT1().get( + TemplateVariablesConstants.EVENT_STATUS + )); + } + + @Test + public void getCommonTemplateVariablesTestInProgressEventStatus() { + residentTransactionEntity.setStatusCode(EventStatusInProgress.OTP_REQUESTED.name()); + Mockito.when(residentService.getEventStatusCode(Mockito.anyString())).thenReturn(EventStatus.IN_PROGRESS.getStatus()); + assertEquals(EventStatus.IN_PROGRESS.getStatus(),templateUtil.getCommonTemplateVariables(eventId, "eng", 0, LOCALE_EN_US).getT1().get( + TemplateVariablesConstants.EVENT_STATUS + )); + } + + @Test + public void getAckTemplateVariablesForVidCardDownloadTest() { + assertEquals(2,templateUtil.getAckTemplateVariablesForVidCardDownload(eventId, "eng", 0, LOCALE_EN_US).size()); + } + + @Test + public void getAckTemplateVariablesForSendOtpTest() { + assertEquals(eventId,templateUtil.getAckTemplateVariablesForSendOtp(eventId, "eng", 0, LOCALE_EN_US).getT1().get(TemplateVariablesConstants.EVENT_ID)); + } + + @Test + public void getAckTemplateVariablesForValidateOtpTest() { + assertEquals(eventId,templateUtil.getAckTemplateVariablesForValidateOtp(eventId, "eng", 0, LOCALE_EN_US).getT1().get(TemplateVariablesConstants.EVENT_ID)); + } + + @Test + public void getNotificationCommonTemplateVariablesTest() { + assertEquals(eventId,templateUtil.getNotificationCommonTemplateVariables(dto).get(TemplateVariablesConstants.EVENT_ID)); + } + + @Test + public void getNotificationCommonTemplateVariablesTestFailed() { + dto = new NotificationTemplateVariableDTO(eventId, RequestType.AUTHENTICATION_REQUEST, TemplateType.FAILURE, "eng", "111111"); + assertEquals(eventId,templateUtil.getNotificationCommonTemplateVariables(dto).get(TemplateVariablesConstants.EVENT_ID)); + } + + @Test + public void getNotificationSendOtpVariablesTest() { + assertEquals(eventId,templateUtil.getNotificationSendOtpVariables(dto).get(TemplateVariablesConstants.EVENT_ID)); + } + + public void getNotificationCommonTemplateVariablesTestFailedApiResourceException() throws ApisResourceAccessException { + Mockito.when(identityServiceImpl.getResidentIndvidualIdFromSession()).thenThrow(new ApisResourceAccessException()); + dto = new NotificationTemplateVariableDTO(eventId, RequestType.AUTHENTICATION_REQUEST, TemplateType.FAILURE, "eng", "111111"); + assertEquals(eventId,templateUtil.getNotificationCommonTemplateVariables(dto).get(TemplateVariablesConstants.EVENT_ID)); + } + + @Test + public void getNotificationTemplateVariablesForGenerateOrRevokeVidTest() { + assertEquals(eventId,templateUtil.getNotificationTemplateVariablesForGenerateOrRevokeVid(dto).get(TemplateVariablesConstants.EVENT_ID)); + } + + @Test + public void getNotificationTemplateVariablesForAuthTypeLockUnlockTest() { + assertEquals(eventId,templateUtil.getNotificationTemplateVariablesForAuthTypeLockUnlock(dto).get(TemplateVariablesConstants.EVENT_ID)); + } + + @Test + public void getNotificationTemplateVariablesForUpdateMyUinTest() { + assertEquals(eventId,templateUtil.getNotificationTemplateVariablesForUpdateMyUin(dto).get(TemplateVariablesConstants.EVENT_ID)); + } + + @Test + public void getNotificationTemplateVariablesForVerifyPhoneEmailTest() { + assertEquals(eventId,templateUtil.getNotificationTemplateVariablesForVerifyPhoneEmail(dto).get(TemplateVariablesConstants.EVENT_ID)); + } + + @Test + public void getNotificationTemplateVariablesForGetMyIdTest() { + assertEquals(eventId,templateUtil.getNotificationTemplateVariablesForGetMyId(dto).get(TemplateVariablesConstants.EVENT_ID)); + } + + @Test + public void getNotificationTemplateVariablesForDownloadPersonalizedCardTest() { + assertEquals(eventId,templateUtil.getNotificationTemplateVariablesForDownloadPersonalizedCard(dto).get(TemplateVariablesConstants.EVENT_ID)); + } + + @Test + public void getNotificationTemplateVariablesForOrderPhysicalCardTest() { + assertEquals(eventId,templateUtil.getNotificationTemplateVariablesForOrderPhysicalCard(dto).get(TemplateVariablesConstants.EVENT_ID)); + } + + @Test + public void getNotificationTemplateVariablesForShareCredentialWithPartnerTest() { + assertEquals(eventId,templateUtil.getNotificationTemplateVariablesForShareCredentialWithPartner(dto).get(TemplateVariablesConstants.EVENT_ID)); + } + + @Test + public void getNotificationTemplateVariablesForVidCardDownloadTest() { + assertEquals(eventId,templateUtil.getNotificationTemplateVariablesForVidCardDownload(dto).get(TemplateVariablesConstants.EVENT_ID)); + } + + @Test + public void getEmailSubjectTemplateTypeCodeTest() { + assertEquals(PROPERTY, + templateUtil.getEmailSubjectTemplateTypeCode(RequestType.AUTHENTICATION_REQUEST, TemplateType.SUCCESS)); + } + + @Test + public void getEmailContentTemplateTypeCodeTest() { + assertEquals(PROPERTY, + templateUtil.getEmailContentTemplateTypeCode(RequestType.AUTHENTICATION_REQUEST, TemplateType.SUCCESS)); + } + + @Test + public void getSmsTemplateTypeCodeTest() { + assertEquals(PROPERTY, + templateUtil.getSmsTemplateTypeCode(RequestType.AUTHENTICATION_REQUEST, TemplateType.SUCCESS)); + } + + @Test + public void getBellIconTemplateTypeCodeTest() { + assertEquals(PROPERTY, + templateUtil.getBellIconTemplateTypeCode(RequestType.AUTHENTICATION_REQUEST, TemplateType.SUCCESS)); + } + + @Test + public void getPurposeTemplateTypeCodeTest() { + assertEquals(PROPERTY, + templateUtil.getPurposeTemplateTypeCode(RequestType.AUTHENTICATION_REQUEST, TemplateType.SUCCESS)); + } + + @Test + public void getSummaryTemplateTypeCodeTest() { + assertEquals(PROPERTY, + templateUtil.getSummaryTemplateTypeCode(RequestType.AUTHENTICATION_REQUEST, TemplateType.SUCCESS)); + } + + @Test + public void testGetDescriptionTemplateVariablesForDownloadPersonalizedCard(){ + assertEquals("VID", templateUtil. + getDescriptionTemplateVariablesForDownloadPersonalizedCard(residentTransactionEntity, "VID", "eng")); + } + + @Test + public void testGetDescriptionTemplateVariablesForDownloadPersonalizedCardNullFileText(){ + templateUtil. + getDescriptionTemplateVariablesForDownloadPersonalizedCard(residentTransactionEntity, null, "eng"); + } + + @Test + public void testGetDescriptionTemplateVariablesForDownloadPersonalizedCardSuccess(){ + templateUtil. + getDescriptionTemplateVariablesForDownloadPersonalizedCard(residentTransactionEntity, ResidentConstants.ATTRIBUTES.toString(), "eng"); + } + + @Test + public void testGetDescriptionTemplateVariablesForDownloadPersonalizedCardFailure(){ + residentTransactionEntity.setAttributeList(null); + residentTransactionEntity.setPurpose(null); + Mockito.when(residentTransactionRepository.findById(eventId)).thenReturn(java.util.Optional.ofNullable(residentTransactionEntity)); + templateUtil. + getDescriptionTemplateVariablesForDownloadPersonalizedCard(residentTransactionEntity, ResidentConstants.ATTRIBUTES.toString(), "eng"); + } + + @Test(expected = ResidentServiceException.class) + public void testGetTemplateValueFromTemplateTypeCodeAndLangCode() throws ResidentServiceCheckedException { + Mockito.when(proxyMasterdataService.getAllTemplateBylangCodeAndTemplateTypeCode(Mockito.anyString(), Mockito.anyString())) + .thenThrow(new ResidentServiceCheckedException()); + assertEquals(PROPERTY, + templateUtil.getTemplateValueFromTemplateTypeCodeAndLangCode("eng", "ack")); + + } + + @Test + public void getCommonTemplateVariablesTestForRequestTypeNotPresentInServiceType() throws ResidentServiceCheckedException { + templateResponse.put(ResidentConstants.FILE_TEXT, "Unknown"); + responseWrapper.setResponse(templateResponse); + Mockito.when(proxyMasterdataService.getAllTemplateBylangCodeAndTemplateTypeCode(Mockito.anyString(), Mockito.anyString())).thenReturn( + responseWrapper); + residentTransactionEntity.setStatusCode(EventStatusInProgress.OTP_REQUESTED.name()); + residentTransactionEntity.setRequestTypeCode("requestType"); + Mockito.when(residentService.getEventStatusCode(Mockito.anyString())).thenReturn(EventStatus.IN_PROGRESS.getStatus()); + assertEquals(EventStatus.IN_PROGRESS.getStatus(),templateUtil.getCommonTemplateVariables(eventId, "eng", 0, LOCALE_EN_US).getT1().get( + TemplateVariablesConstants.EVENT_STATUS + )); + } + + @Test + public void getCommonTemplateVariablesTestApiResourceException() throws ResidentServiceCheckedException, ApisResourceAccessException { + templateResponse.put(ResidentConstants.FILE_TEXT, "Unknown"); + responseWrapper.setResponse(templateResponse); + Mockito.when(proxyMasterdataService.getAllTemplateBylangCodeAndTemplateTypeCode(Mockito.anyString(), Mockito.anyString())).thenReturn( + responseWrapper); + residentTransactionEntity.setStatusCode(EventStatusInProgress.OTP_REQUESTED.name()); + residentTransactionEntity.setRequestTypeCode("requestType"); + Mockito.when(residentService.getEventStatusCode(Mockito.anyString())).thenReturn(EventStatus.IN_PROGRESS.getStatus()); + Mockito.when(identityServiceImpl.getResidentIndvidualIdFromSession()).thenThrow(new ApisResourceAccessException()); + assertEquals(EventStatus.IN_PROGRESS.getStatus(),templateUtil.getCommonTemplateVariables(eventId, "eng", 0, LOCALE_EN_US).getT1().get( + TemplateVariablesConstants.EVENT_STATUS + )); + } + + @Test + public void getDescriptionTemplateVariablesForAuthenticationRequestTest() { + residentTransactionEntity.setStatusComment("SUCCESS"); + assertEquals("SUCCESS", + templateUtil.getDescriptionTemplateVariablesForAuthenticationRequest + (residentTransactionEntity, null, null)); + } + + @Test + public void getDescriptionTemplateVariablesForShareCredentialTest(){ + templateUtil.getDescriptionTemplateVariablesForShareCredential(residentTransactionEntity, null, null); + } + + @Test + public void getDescriptionTemplateVariablesForOrderPhysicalCardTest(){ + assertEquals("OTP", templateUtil.getDescriptionTemplateVariablesForOrderPhysicalCard( + residentTransactionEntity, "OTP", "eng")); + } + + @Test + public void getDescriptionTemplateVariablesForGetMyIdTest(){ + assertEquals("OTP", templateUtil.getDescriptionTemplateVariablesForGetMyId( + residentTransactionEntity, "OTP", "eng")); + } + + @Test + public void getDescriptionTemplateVariablesForUpdateMyUinTest(){ + templateUtil.getDescriptionTemplateVariablesForUpdateMyUin(residentTransactionEntity, "OTP", "eng"); + } + + @Test + public void getDescriptionTemplateVariablesForManageMyVidTest(){ + assertEquals("OTP", templateUtil.getDescriptionTemplateVariablesForManageMyVid( + residentTransactionEntity, "OTP", "eng")); + } + + @Test + public void getDescriptionTemplateVariablesForManageMyVidGenerateVidTest(){ + residentTransactionEntity.setRequestTypeCode(RequestType.GENERATE_VID.name()); + assertEquals("OTP", templateUtil.getDescriptionTemplateVariablesForManageMyVid( + residentTransactionEntity, "OTP", "eng")); + } + + @Test + public void getDescriptionTemplateVariablesForManageMyVidRevokeVidTest(){ + residentTransactionEntity.setRequestTypeCode(RequestType.REVOKE_VID.name()); + assertEquals("OTP", templateUtil.getDescriptionTemplateVariablesForManageMyVid( + residentTransactionEntity, "OTP", "eng")); + } + + @Test + public void getDescriptionTemplateVariablesForVidCardDownloadTest(){ + assertEquals("OTP", templateUtil.getDescriptionTemplateVariablesForVidCardDownload(residentTransactionEntity, "OTP", + "eng")); + } + + @Test + public void getDescriptionTemplateVariablesForValidateOtpTest(){ + assertEquals("OTP", templateUtil.getDescriptionTemplateVariablesForValidateOtp(residentTransactionEntity, "OTP", + "eng")); + } + + @Test + public void getDescriptionTemplateVariablesForValidateOtpNullChannelTest(){ + residentTransactionEntity.setPurpose(null); + assertEquals("OTP", templateUtil.getDescriptionTemplateVariablesForValidateOtp(residentTransactionEntity, "OTP", + "eng")); + } + + @Test + public void getDescriptionTemplateVariablesForValidateOtpEmptyChannelTest(){ + residentTransactionEntity.setPurpose(""); + assertEquals("OTP", templateUtil.getDescriptionTemplateVariablesForValidateOtp(residentTransactionEntity, "OTP", + "eng")); + } + + @Test + public void getDescriptionTemplateVariablesForSecureMyIdTest(){ + residentTransactionEntity.setPurpose("fullName,dateOfBirth,UIN,perpetualVID,phone,email"); + assertEquals("OTP, OTP, OTP, OTP, OTP, OTP", templateUtil.getDescriptionTemplateVariablesForSecureMyId( + residentTransactionEntity, + "OTP", "eng")); + } + + @Test + public void getDescriptionTemplateVariablesForSecureMyIdUnlockedTest(){ + residentTransactionEntity.setPurpose("UNLOCKED,dateOfBirth,UIN,perpetualVID,phone,email"); + assertEquals("OTP, OTP, OTP, OTP, OTP, OTP", templateUtil.getDescriptionTemplateVariablesForSecureMyId( + residentTransactionEntity, + "OTP", "eng")); + } + + @Test + public void getDefaultTemplateVariablesTest(){ + templateUtil.getDefaultTemplateVariables(eventId, "eng", 0, LOCALE_EN_US); + } + + @Test + public void getFeatureNameTest(){ + templateUtil.getFeatureName(eventId, LOCALE_EN_US); + } + + @Test + public void getPurposeFromResidentTransactionEntityLangCodeTest() throws ResidentServiceCheckedException { + Mockito.when(residentService.getDescriptionForLangCode(Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.any())) + .thenThrow(new ResidentServiceCheckedException()); + assertEquals("",templateUtil.getPurposeFromResidentTransactionEntityLangCode(residentTransactionEntity, "eng")); + } + + @Test + public void getSummaryFromResidentTransactionEntityLangCodeTest() throws ResidentServiceCheckedException { + Mockito.when(residentService.getSummaryForLangCode(Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.any())) + .thenThrow(new ResidentServiceCheckedException()); + assertEquals("AUTHENTICATION_REQUEST",templateUtil.getSummaryFromResidentTransactionEntityLangCode( + residentTransactionEntity, "eng", "SUCCESS", + RequestType.AUTHENTICATION_REQUEST)); + } + + @Test + public void getNotificationCommonTemplateVariablesSecureSessionTest() { + IdentityServiceTest.getAuthUserDetailsFromAuthentication(); + assertEquals(eventId,templateUtil.getNotificationCommonTemplateVariables(dto).get(TemplateVariablesConstants.EVENT_ID)); + } +} diff --git a/resident/resident-service/src/test/java/io/mosip/resident/test/util/TokenGeneratorTest.java b/resident/resident-service/src/test/java/io/mosip/resident/util/TokenGeneratorTest.java similarity index 99% rename from resident/resident-service/src/test/java/io/mosip/resident/test/util/TokenGeneratorTest.java rename to resident/resident-service/src/test/java/io/mosip/resident/util/TokenGeneratorTest.java index 0c241ec1b13..7699f8b03d2 100644 --- a/resident/resident-service/src/test/java/io/mosip/resident/test/util/TokenGeneratorTest.java +++ b/resident/resident-service/src/test/java/io/mosip/resident/util/TokenGeneratorTest.java @@ -1,4 +1,4 @@ -package io.mosip.resident.test.util; +package io.mosip.resident.util; import static org.mockito.ArgumentMatchers.any; import static org.powermock.api.mockito.PowerMockito.mockStatic; diff --git a/resident/resident-service/src/test/java/io/mosip/resident/test/util/UINCardDownloadTest.java b/resident/resident-service/src/test/java/io/mosip/resident/util/UINCardDownloadTest.java similarity index 98% rename from resident/resident-service/src/test/java/io/mosip/resident/test/util/UINCardDownloadTest.java rename to resident/resident-service/src/test/java/io/mosip/resident/util/UINCardDownloadTest.java index 0d231b02dcb..8a028d532e1 100644 --- a/resident/resident-service/src/test/java/io/mosip/resident/test/util/UINCardDownloadTest.java +++ b/resident/resident-service/src/test/java/io/mosip/resident/util/UINCardDownloadTest.java @@ -1,4 +1,4 @@ -package io.mosip.resident.test.util; +package io.mosip.resident.util; import static org.junit.Assert.assertEquals; diff --git a/resident/resident-service/src/test/java/io/mosip/resident/test/util/UtilitiesTest.java b/resident/resident-service/src/test/java/io/mosip/resident/util/UtilitiesTest.java similarity index 94% rename from resident/resident-service/src/test/java/io/mosip/resident/test/util/UtilitiesTest.java rename to resident/resident-service/src/test/java/io/mosip/resident/util/UtilitiesTest.java index d10a576a1bd..87b71b96ec9 100644 --- a/resident/resident-service/src/test/java/io/mosip/resident/test/util/UtilitiesTest.java +++ b/resident/resident-service/src/test/java/io/mosip/resident/util/UtilitiesTest.java @@ -1,4 +1,4 @@ -package io.mosip.resident.test.util; +package io.mosip.resident.util; import static io.mosip.resident.constant.ResidentConstants.TRANSACTION_TYPE_CODE; import static org.junit.Assert.assertEquals; @@ -18,6 +18,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Optional; import org.apache.commons.io.IOUtils; import org.json.simple.JSONObject; @@ -50,10 +51,8 @@ import io.mosip.resident.exception.ApisResourceAccessException; import io.mosip.resident.exception.IdRepoAppException; import io.mosip.resident.exception.IndividualIdNotFoundException; +import io.mosip.resident.exception.ResidentServiceCheckedException; import io.mosip.resident.exception.VidCreationException; -import io.mosip.resident.util.JsonUtil; -import io.mosip.resident.util.ResidentServiceRestClient; -import io.mosip.resident.util.Utilities; @RunWith(PowerMockRunner.class) @PowerMockIgnore({"com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "javax.management.*"}) @@ -304,7 +303,7 @@ public void testGetRidByIndividualIdFailed() throws ApisResourceAccessException } @Test - public void testGetRidStatus() throws ApisResourceAccessException, IOException { + public void testGetRidStatus() throws ApisResourceAccessException, IOException, ResidentServiceCheckedException { ResponseWrapper response = new ResponseWrapper<>(); ArrayList arrayList = new ArrayList<>(); arrayList.add("123"); @@ -315,21 +314,19 @@ public void testGetRidStatus() throws ApisResourceAccessException, IOException { @Test public void testGetTransactionTypeCode() throws ApisResourceAccessException, IOException { - ArrayList transactionTypeCode = new ArrayList<>(); + when(env.getProperty(any())).thenReturn("PACKET_UPLOAD,PACKET_RECEIVER"); HashMap packetStatus = new HashMap<>(); packetStatus.put(TRANSACTION_TYPE_CODE, "PACKET_RECEIVER"); - transactionTypeCode.add(packetStatus); - assertEquals("Request received", - ReflectionTestUtils.invokeMethod(utilities, "getTransactionTypeCode", transactionTypeCode)); + assertEquals(Optional.of("REQUEST_RECEIVED"), + ReflectionTestUtils.invokeMethod(utilities, "getTransactionTypeCode", packetStatus)); } @Test public void testGetTransactionTypeCodeFailed() throws ApisResourceAccessException, IOException { - ArrayList transactionTypeCode = new ArrayList<>(); + when(env.getProperty(any())).thenReturn("status,packet"); HashMap packetStatus = new HashMap<>(); packetStatus.put(TRANSACTION_TYPE_CODE, "test"); - transactionTypeCode.add(packetStatus); - ReflectionTestUtils.invokeMethod(utilities, "getTransactionTypeCode", transactionTypeCode); + ReflectionTestUtils.invokeMethod(utilities, "getTransactionTypeCode", packetStatus); } @Test diff --git a/resident/resident-service/src/test/java/io/mosip/resident/test/util/UtilityTest.java b/resident/resident-service/src/test/java/io/mosip/resident/util/UtilityTest.java similarity index 82% rename from resident/resident-service/src/test/java/io/mosip/resident/test/util/UtilityTest.java rename to resident/resident-service/src/test/java/io/mosip/resident/util/UtilityTest.java index 00d0d1ae14c..8faf2a637e8 100644 --- a/resident/resident-service/src/test/java/io/mosip/resident/test/util/UtilityTest.java +++ b/resident/resident-service/src/test/java/io/mosip/resident/util/UtilityTest.java @@ -1,4 +1,4 @@ -package io.mosip.resident.test.util; +package io.mosip.resident.util; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; @@ -15,13 +15,19 @@ import java.io.IOException; import java.io.InputStream; import java.security.NoSuchAlgorithmException; +import java.time.LocalDateTime; +import java.time.format.FormatStyle; import java.util.ArrayList; +import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; +import io.mosip.resident.constant.ApiName; +import io.mosip.resident.constant.ResidentErrorCode; +import io.mosip.resident.constant.TemplateVariablesConstants; import org.apache.commons.io.IOUtils; import org.json.simple.JSONObject; import org.junit.Before; @@ -42,10 +48,13 @@ import org.springframework.web.client.HttpServerErrorException; import org.springframework.web.client.RestTemplate; +import com.fasterxml.jackson.databind.ObjectMapper; + import io.mosip.kernel.core.exception.ServiceError; import io.mosip.kernel.core.http.ResponseWrapper; import io.mosip.kernel.core.pdfgenerator.spi.PDFGenerator; import io.mosip.kernel.core.util.HMACUtils2; +import io.mosip.resident.constant.RequestType; import io.mosip.resident.constant.ResidentConstants; import io.mosip.resident.dto.IdRepoResponseDto; import io.mosip.resident.dto.IdentityDTO; @@ -56,14 +65,13 @@ import io.mosip.resident.exception.ResidentServiceException; import io.mosip.resident.repository.ResidentTransactionRepository; import io.mosip.resident.service.impl.IdentityServiceImpl; -import io.mosip.resident.util.JsonUtil; -import io.mosip.resident.util.ResidentServiceRestClient; -import io.mosip.resident.util.Utility; @RunWith(PowerMockRunner.class) @PowerMockIgnore({"com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "javax.management.*"}) @PrepareForTest({ JsonUtil.class }) public class UtilityTest { + private static final String LOCALE = "en-US"; + @Mock private ResidentServiceRestClient residentServiceRestClient; @@ -71,6 +79,8 @@ public class UtilityTest { private Utility utility; private JSONObject identity; + + private JSONObject amrAcrJson; @Mock private Environment env; @@ -90,6 +100,13 @@ public class UtilityTest { @Mock @Qualifier("selfTokenRestTemplate") private RestTemplate residentRestTemplate; + + @Mock + private ObjectMapper objectMapper; + + private ObjectMapper mapper = new ObjectMapper(); + + private String replaceSplChars = "{\" \": \"_\", \",\" : \"\", \":\" : \".\"}"; @Before public void setUp() throws IOException, ApisResourceAccessException { @@ -98,10 +115,19 @@ public void setUp() throws IOException, ApisResourceAccessException { InputStream is = new FileInputStream(idJson); String idJsonString = IOUtils.toString(is, "UTF-8"); identity = JsonUtil.readValue(idJsonString, JSONObject.class); + + File amrAcrJsonFile = new File(classLoader.getResource("amr-acr-mapping.json").getFile()); + InputStream insputStream = new FileInputStream(amrAcrJsonFile); + String amrAcrJsonString = IOUtils.toString(insputStream, "UTF-8"); + amrAcrJson = JsonUtil.readValue(amrAcrJsonString, JSONObject.class); + ReflectionTestUtils.setField(utility, "configServerFileStorageURL", "url"); ReflectionTestUtils.setField(utility, "residentIdentityJson", "json"); - when(env.getProperty("resident.ui.datetime.pattern")).thenReturn("yyyy-MM-dd"); - when(env.getProperty("resident.filename.datetime.pattern")).thenReturn("yyyy-MM-dd"); + ReflectionTestUtils.setField(utility, "amrAcrJsonFile", "amr-acr-mapping.json"); + ReflectionTestUtils.setField(utility, "formattingStyle", FormatStyle.MEDIUM.name()); + ReflectionTestUtils.setField(utility, "specialCharsReplacementMap", mapper.readValue(replaceSplChars, Map.class)); + when(env.getProperty("resident.ui.datetime.pattern.default")).thenReturn("yyyy-MM-dd"); + when(env.getProperty("resident.filename.datetime.pattern.default")).thenReturn("yyyy-MM-dd hh:mm:ss a"); request = Mockito.mock(HttpServletRequest.class); } @@ -358,14 +384,14 @@ public void testGetMailingAttributesIOException() throws IOException, ResidentSe @Test public void testGetFileNameAsPerFeatureNameShareCredWithPartner(){ - assertEquals("SHARE_CRED_WITH_PARTNER", utility.getFileName("123", "SHARE_CRED_WITH_PARTNER", 0)); - assertEquals("GENERATE_VID", utility.getFileName("123", "GENERATE_VID", 0)); - assertEquals("REVOKE_VID", utility.getFileName("123", "REVOKE_VID", 0)); - assertEquals("ORDER_PHYSICAL_CARD", utility.getFileName("123", "ORDER_PHYSICAL_CARD", 0)); - assertEquals("DOWNLOAD_PERSONALIZED_CARD", utility.getFileName("123", "DOWNLOAD_PERSONALIZED_CARD", 0)); - assertEquals("UPDATE_MY_UIN", utility.getFileName("123", "UPDATE_MY_UIN", 0)); - assertEquals("AUTH_TYPE_LOCK_UNLOCK", utility.getFileName("123", "AUTH_TYPE_LOCK_UNLOCK", 0)); - assertEquals("Generic", utility.getFileName("123", "Generic", 0)); + assertEquals("SHARE_CRED_WITH_PARTNER", utility.getFileName("123", "SHARE_CRED_WITH_PARTNER", 0, LOCALE)); + assertEquals("GENERATE_VID", utility.getFileName("123", "GENERATE_VID", 0, LOCALE)); + assertEquals("REVOKE_VID", utility.getFileName("123", "REVOKE_VID", 0, LOCALE)); + assertEquals("ORDER_PHYSICAL_CARD", utility.getFileName("123", "ORDER_PHYSICAL_CARD", 0, LOCALE)); + assertEquals("DOWNLOAD_PERSONALIZED_CARD", utility.getFileName("123", "DOWNLOAD_PERSONALIZED_CARD", 0, LOCALE)); + assertEquals("UPDATE_MY_UIN", utility.getFileName("123", "UPDATE_MY_UIN", 0, LOCALE)); + assertEquals("AUTH_TYPE_LOCK_UNLOCK", utility.getFileName("123", "AUTH_TYPE_LOCK_UNLOCK", 0, LOCALE)); + assertEquals("Generic", utility.getFileName("123", "Generic", 0, LOCALE)); } @Test @@ -374,7 +400,7 @@ public void testGetFileNameAsPerFeatureNameGenerateVid(){ .thenReturn("Ack_Manage_my_VID_{eventId}_{timestamp}.pdf"); Mockito.when(env.getProperty("resident.datetime.pattern")) .thenReturn("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); - assertNotNull(utility.getFileName("123", "Ack_Manage_my_VID_{eventId}_{timestamp}.pdf", 0)); + assertNotNull(utility.getFileName("123", "Ack_Manage_my_VID_{eventId}_{timestamp}.pdf", 0, LOCALE)); } @Test @@ -383,7 +409,7 @@ public void testGetFileNameNullEventId(){ .thenReturn("Ack_Manage_my_VID_{eventId}_{timestamp}.pdf"); Mockito.when(env.getProperty("resident.datetime.pattern")) .thenReturn("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); - assertNotNull(utility.getFileName(null, "Ack_Manage_my_VID_{eventId}_{timestamp}.pdf", 0)); + assertNotNull(utility.getFileName(null, "Ack_Manage_my_VID_{eventId}_{timestamp}.pdf", 0, LOCALE)); } @Test @@ -471,21 +497,21 @@ public void testCreateEventId(){ @Test public void testCreateEntity(){ - assertEquals("resident-services",utility.createEntity().getCrBy()); + assertEquals("Unknown",utility.createEntity(RequestType.SHARE_CRED_WITH_PARTNER).getCrBy()); } @Test public void testGetFileNameAsPerFeatureName(){ Mockito.when(env.getProperty(Mockito.anyString())) .thenReturn("AckFileName"); - assertEquals("AckFileName", utility.getFileNameAsPerFeatureName("123", "SHARE_CRED_WITH_PARTNER", 0)); - assertEquals("AckFileName", utility.getFileNameAsPerFeatureName("123", "GENERATE_VID", 0)); - assertEquals("AckFileName", utility.getFileNameAsPerFeatureName("123", "REVOKE_VID", 0)); - assertEquals("AckFileName", utility.getFileNameAsPerFeatureName("123", "ORDER_PHYSICAL_CARD", 0)); - assertEquals("AckFileName", utility.getFileNameAsPerFeatureName("123", "DOWNLOAD_PERSONALIZED_CARD", 0)); - assertEquals("AckFileName", utility.getFileNameAsPerFeatureName("123", "UPDATE_MY_UIN", 0)); - assertEquals("AckFileName", utility.getFileNameAsPerFeatureName("123", "AUTH_TYPE_LOCK_UNLOCK", 0)); - assertEquals("AckFileName", utility.getFileNameAsPerFeatureName("123", "Generic", 0)); + assertEquals("AckFileName", utility.getFileNameAsPerFeatureName("123", "SHARE_CRED_WITH_PARTNER", 0, LOCALE)); + assertEquals("AckFileName", utility.getFileNameAsPerFeatureName("123", "GENERATE_VID", 0, LOCALE)); + assertEquals("AckFileName", utility.getFileNameAsPerFeatureName("123", "REVOKE_VID", 0, LOCALE)); + assertEquals("AckFileName", utility.getFileNameAsPerFeatureName("123", "ORDER_PHYSICAL_CARD", 0, LOCALE)); + assertEquals("AckFileName", utility.getFileNameAsPerFeatureName("123", "DOWNLOAD_PERSONALIZED_CARD", 0, LOCALE)); + assertEquals("AckFileName", utility.getFileNameAsPerFeatureName("123", "UPDATE_MY_UIN", 0, LOCALE)); + assertEquals("AckFileName", utility.getFileNameAsPerFeatureName("123", "AUTH_TYPE_LOCK_UNLOCK", 0, LOCALE)); + assertEquals("AckFileName", utility.getFileNameAsPerFeatureName("123", "Generic", 0, LOCALE)); } @Test @@ -510,4 +536,56 @@ public void testGetClientIpNull() { String ipAddress = utility.getClientIp(request); assertEquals("1.5.5", ipAddress); } + + @Test + public void test_formatWithOffsetForFileName_en_US() { + LocalDateTime localDateTime = LocalDateTime.of(1993, 8, 14, 16, 54); + String formatWithOffsetForFileName = utility.formatWithOffsetForFileName(0, "en-US", localDateTime); + assertEquals("Aug_14_1993_4.54.00_PM", formatWithOffsetForFileName); + } + + @Test + public void test_formatWithOffsetForFileName_en_IN() { + LocalDateTime localDateTime = LocalDateTime.of(1993, 8, 14, 16, 54); + String formatWithOffsetForFileName = utility.formatWithOffsetForFileName(-330, "en-IN", localDateTime); + assertEquals("14-Aug-1993_10.24.00_PM", formatWithOffsetForFileName); + } + + @Test + public void test_formatWithOffsetForFileName_null_locale() { + LocalDateTime localDateTime = LocalDateTime.of(1993, 8, 14, 16, 54); + String formatWithOffsetForFileName = utility.formatWithOffsetForFileName(0, null, localDateTime); + assertEquals("1993-08-14_04.54.00_PM", formatWithOffsetForFileName); + } + + + + @Test + public void test_formatWithOffsetForUI_en_US() { + LocalDateTime localDateTime = LocalDateTime.of(1993, 8, 14, 16, 54); + String formatWithOffsetForFileName = utility.formatWithOffsetForUI(0, "en-US", localDateTime); + assertEquals("Aug 14, 1993, 4:54:00 PM", formatWithOffsetForFileName); + } + + @Test + public void test_formatWithOffsetForUI_en_IN() { + LocalDateTime localDateTime = LocalDateTime.of(1993, 8, 14, 16, 54); + String formatWithOffsetForFileName = utility.formatWithOffsetForUI(-330, "en-IN", localDateTime); + assertEquals("14-Aug-1993, 10:24:00 PM", formatWithOffsetForFileName); + } + + @Test + public void test_formatWithOffsetForUI_null_locale() { + LocalDateTime localDateTime = LocalDateTime.of(1993, 8, 14, 16, 54); + String formatWithOffsetForFileName = utility.formatWithOffsetForUI(0, null, localDateTime); + assertEquals("1993-08-14", formatWithOffsetForFileName); + } + + @Test(expected = RuntimeException.class) + public void testGetSessionUserName() throws ApisResourceAccessException { + Mockito.when(env.getProperty(Mockito.anyString())).thenReturn("name"); + Mockito.when(identityService.getAvailableclaimValue(Mockito.anyString())).thenThrow(new ApisResourceAccessException()); + utility.getSessionUserName(); + } + } diff --git a/resident/resident-service/src/test/java/io/mosip/resident/validator/RequestHandlerRequestValidatorTest.java b/resident/resident-service/src/test/java/io/mosip/resident/validator/RequestHandlerRequestValidatorTest.java new file mode 100644 index 00000000000..64383100983 --- /dev/null +++ b/resident/resident-service/src/test/java/io/mosip/resident/validator/RequestHandlerRequestValidatorTest.java @@ -0,0 +1,512 @@ +package io.mosip.resident.validator; + +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.when; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import org.assertj.core.util.Lists; +import org.json.simple.JSONObject; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.springframework.core.env.Environment; +import org.springframework.test.context.junit4.SpringRunner; + +import com.fasterxml.jackson.databind.ObjectMapper; + +import io.mosip.kernel.core.exception.BaseCheckedException; +import io.mosip.kernel.core.exception.ServiceError; +import io.mosip.kernel.core.http.ResponseWrapper; +import io.mosip.kernel.core.idvalidator.exception.InvalidIDException; +import io.mosip.kernel.core.idvalidator.spi.UinValidator; +import io.mosip.kernel.core.idvalidator.spi.VidValidator; +import io.mosip.resident.constant.CardType; +import io.mosip.resident.dto.LogDescription; +import io.mosip.resident.dto.MachineDto; +import io.mosip.resident.dto.MachineResponseDto; +import io.mosip.resident.dto.RegistrationCenterDto; +import io.mosip.resident.dto.RegistrationCenterResponseDto; +import io.mosip.resident.dto.RegistrationType; +import io.mosip.resident.exception.ApisResourceAccessException; +import io.mosip.resident.exception.IdRepoAppException; +import io.mosip.resident.exception.RequestHandlerValidationException; +import io.mosip.resident.exception.VidCreationException; +import io.mosip.resident.util.ResidentServiceRestClient; +import io.mosip.resident.util.Utilities; + +@RunWith(SpringRunner.class) +public class RequestHandlerRequestValidatorTest { + + @InjectMocks + private RequestHandlerRequestValidator requestHandlerRequestValidator; + + /** The rest client service. */ + @Mock + private ResidentServiceRestClient restClientService; + + /** The mapper. */ + @Mock + private ObjectMapper mapper = new ObjectMapper(); + + @Mock + private UinValidator uinValidatorImpl; + + /** The vid validator impl. */ + @Mock + private VidValidator vidValidatorImpl; + + /** The utilities. */ + @Mock + private Utilities utilities; + + @Mock + private Environment env; + + private static final String ID = "110011"; + + @Before + public void setup() throws ApisResourceAccessException, IOException { + Mockito.when(env.getProperty("mosip.mandatory-languages")).thenReturn("eng"); + Mockito.when(restClientService.getApi(any(), any(), anyString(), anyString(), any(Class.class))) + .thenReturn(new ResponseWrapper<>()); + Mockito.when(mapper.writeValueAsString(any())).thenReturn("String"); + } + + @Test(expected = RequestHandlerValidationException.class) + public void testValidateWithRequestHandlerValidationException() throws RequestHandlerValidationException { + requestHandlerRequestValidator.validate(ID); + } + + @Test(expected = RequestHandlerValidationException.class) + public void testValidateNullId() throws RequestHandlerValidationException { + requestHandlerRequestValidator.validate(null); + } + + @Test + public void testIsValidCenter() throws BaseCheckedException, IOException { + RegistrationCenterDto registrationCenterDto = new RegistrationCenterDto(); + RegistrationCenterResponseDto rcpdto = new RegistrationCenterResponseDto(); + rcpdto.setRegistrationCenters(Lists.newArrayList(registrationCenterDto)); + + Mockito.when(mapper.readValue(anyString(), any(Class.class))).thenReturn(rcpdto); + + boolean result = requestHandlerRequestValidator.isValidCenter(ID); + assertTrue(result); + } + + @Test(expected = BaseCheckedException.class) + public void testIsValidCenterNestedElse() throws BaseCheckedException, IOException { + RegistrationCenterDto registrationCenterDto = new RegistrationCenterDto(); + ServiceError error = new ServiceError(); + error.setErrorCode("invalid-101"); + error.setMessage("invalid center"); + List errorList = new ArrayList(); + errorList.add(error); + ResponseWrapper wrapper = new ResponseWrapper<>(); + wrapper.setErrors(errorList); + RegistrationCenterResponseDto rcpdto = new RegistrationCenterResponseDto(); + rcpdto.setRegistrationCenters(Lists.newArrayList(registrationCenterDto)); + when(restClientService.getApi(any(), any(), anyString(), anyString(), any())).thenReturn(wrapper); + Mockito.when(mapper.readValue(anyString(), any(Class.class))).thenReturn(rcpdto); + + requestHandlerRequestValidator.isValidCenter(ID); + } + + @Test(expected = BaseCheckedException.class) + public void testIsValidCenterElse() throws BaseCheckedException, IOException { + requestHandlerRequestValidator.isValidCenter(""); + } + + @Test(expected = BaseCheckedException.class) + public void testIsValidCenterElse2() throws BaseCheckedException, IOException { + requestHandlerRequestValidator.isValidCenter(null); + } + + @Test + public void testIsValidCenterWithApisResourceAccessException() throws BaseCheckedException, IOException { + RegistrationCenterDto registrationCenterDto = new RegistrationCenterDto(); + ServiceError error = new ServiceError(); + error.setErrorCode("invalid-101"); + error.setMessage("invalid center"); + List errorList = new ArrayList(); + errorList.add(error); + ResponseWrapper wrapper = new ResponseWrapper<>(); + wrapper.setErrors(errorList); + RegistrationCenterResponseDto rcpdto = new RegistrationCenterResponseDto(); + rcpdto.setRegistrationCenters(Lists.newArrayList(registrationCenterDto)); + when(restClientService.getApi(any(), any(), anyString(), anyString(), any())) + .thenThrow(new ApisResourceAccessException("error")); +// when(restClientService.getApi(any(), any(), anyString(), anyString(), any())).thenThrow(new ApisResourceAccessException("error", new HttpClientErrorException(HttpStatus.OK))); +// Mockito.when(mapper.readValue(anyString(), any(Class.class))).thenThrow(ApisResourceAccessException.class); + + requestHandlerRequestValidator.isValidCenter(ID); + } + + @Test + public void testIsValidMachine() throws BaseCheckedException, IOException { + MachineDto registrationCenterDto = new MachineDto(); + MachineResponseDto machinedto = new MachineResponseDto(); + machinedto.setMachines(Lists.newArrayList(registrationCenterDto)); + + Mockito.when(mapper.readValue(anyString(), any(Class.class))).thenReturn(machinedto); + + boolean result = requestHandlerRequestValidator.isValidMachine(ID); + assertTrue(result); + } + + @Test(expected = BaseCheckedException.class) + public void testIsValidMachineNestedElse() throws BaseCheckedException, IOException { + MachineDto registrationCenterDto = new MachineDto(); + ServiceError error = new ServiceError(); + error.setErrorCode("invalid-101"); + error.setMessage("invalid center"); + List errorList = new ArrayList(); + errorList.add(error); + ResponseWrapper wrapper = new ResponseWrapper<>(); + wrapper.setErrors(errorList); + MachineResponseDto machinedto = new MachineResponseDto(); + machinedto.setMachines(Lists.newArrayList(registrationCenterDto)); + + when(restClientService.getApi(any(), any(), anyString(), anyString(), any())).thenReturn(wrapper); + Mockito.when(mapper.readValue(anyString(), any(Class.class))).thenReturn(machinedto); + + requestHandlerRequestValidator.isValidMachine(ID); + } + + @Test(expected = BaseCheckedException.class) + public void testIsValidMachineElse() throws BaseCheckedException, IOException { + requestHandlerRequestValidator.isValidMachine(null); + } + + @Test(expected = BaseCheckedException.class) + public void testIsValidMachineElse2() throws BaseCheckedException, IOException { + requestHandlerRequestValidator.isValidMachine(""); + } + + @Test + public void testIsValidMachineWithApisResourceAccessException() throws BaseCheckedException, IOException { + MachineDto registrationCenterDto = new MachineDto(); + ServiceError error = new ServiceError(); + error.setErrorCode("invalid-101"); + error.setMessage("invalid center"); + List errorList = new ArrayList(); + errorList.add(error); + ResponseWrapper wrapper = new ResponseWrapper<>(); + wrapper.setErrors(errorList); + MachineResponseDto machinedto = new MachineResponseDto(); + machinedto.setMachines(Lists.newArrayList(registrationCenterDto)); + + when(restClientService.getApi(any(), any(), anyString(), anyString(), any())) + .thenThrow(new ApisResourceAccessException("error")); +// when(restClientService.getApi(any(), any(), anyString(), anyString(), any())).thenThrow(new ApisResourceAccessException("error", new HttpClientErrorException(HttpStatus.OK))); +// Mockito.when(mapper.readValue(anyString(), any(Class.class))).thenThrow(ApisResourceAccessException.class); + + requestHandlerRequestValidator.isValidMachine(ID); + } + + @Test + public void testIsValidUin() throws BaseCheckedException, IOException { + JSONObject jsonObject = new JSONObject(); + Mockito.when(uinValidatorImpl.validateId(anyString())).thenReturn(true); + Mockito.when(utilities.retrieveIdrepoJson(anyString())).thenReturn(jsonObject); + + boolean result = requestHandlerRequestValidator.isValidUin("1234"); + assertTrue(result); + } + + @Test(expected = BaseCheckedException.class) + public void testIsValidUinElse1() throws BaseCheckedException, IOException { + JSONObject jsonObject = new JSONObject(); + when(uinValidatorImpl.validateId(anyString())).thenReturn(true); + when(utilities.retrieveIdrepoJson(anyString())).thenReturn(null); + + requestHandlerRequestValidator.isValidUin("1234"); + } + + @Test(expected = BaseCheckedException.class) + public void testIsValidUinElse2() throws BaseCheckedException, IOException { + JSONObject jsonObject = new JSONObject(); + when(uinValidatorImpl.validateId(anyString())).thenReturn(false); + when(utilities.retrieveIdrepoJson(anyString())).thenReturn(jsonObject); + + requestHandlerRequestValidator.isValidUin("1234"); + } + + @Test(expected = BaseCheckedException.class) + public void testIsValidUinWithInvalidIDException() throws BaseCheckedException, IOException { + JSONObject jsonObject = new JSONObject(); + Mockito.when(uinValidatorImpl.validateId(anyString())).thenReturn(true); + Mockito.when(utilities.retrieveIdrepoJson(anyString())) + .thenThrow(new InvalidIDException("errorcode", "message")); + + requestHandlerRequestValidator.isValidUin("1234"); + } + + @Test(expected = BaseCheckedException.class) + public void testIsValidUinWithIdRepoAppException() throws BaseCheckedException, IOException { + JSONObject jsonObject = new JSONObject(); + Mockito.when(uinValidatorImpl.validateId(anyString())).thenReturn(true); + Mockito.when(utilities.retrieveIdrepoJson(anyString())) + .thenThrow(new IdRepoAppException("errorcode", "message")); + + requestHandlerRequestValidator.isValidUin("1234"); + } + + @Test(expected = BaseCheckedException.class) + public void testIsValidUinWithNumberFormatException() throws BaseCheckedException, IOException { + JSONObject jsonObject = new JSONObject(); + Mockito.when(uinValidatorImpl.validateId(anyString())).thenReturn(true); + Mockito.when(utilities.retrieveIdrepoJson(anyString())).thenThrow(new NumberFormatException("errorcode")); + + requestHandlerRequestValidator.isValidUin("1234"); + } + + @Test(expected = BaseCheckedException.class) + public void testIsValidUinWithApisResourceAccessException() throws BaseCheckedException, IOException { + JSONObject jsonObject = new JSONObject(); + Mockito.when(uinValidatorImpl.validateId(anyString())).thenReturn(true); + Mockito.when(utilities.retrieveIdrepoJson(anyString())).thenThrow(new ApisResourceAccessException("errorcode")); + + requestHandlerRequestValidator.isValidUin("1234"); + } + + @Test(expected = BaseCheckedException.class) + public void testIsValidUinWithIOException() throws BaseCheckedException, IOException { + JSONObject jsonObject = new JSONObject(); + Mockito.when(uinValidatorImpl.validateId(anyString())).thenReturn(true); + Mockito.when(utilities.retrieveIdrepoJson(anyString())).thenThrow(new IOException("errorcode")); + + requestHandlerRequestValidator.isValidUin("1234"); + } + + @Test + public void testIsValidRePrintRegistrationType() throws BaseCheckedException, IOException { + boolean result = requestHandlerRequestValidator + .isValidRePrintRegistrationType(RegistrationType.RES_REPRINT.name()); + assertTrue(result); + } + + @Test(expected = BaseCheckedException.class) + public void testIsValidRePrintRegistrationTypeElse() throws BaseCheckedException { + requestHandlerRequestValidator.isValidRePrintRegistrationType("LOST"); + } + + @Test(expected = BaseCheckedException.class) + public void testIsValidRePrintRegistrationTypeElse2() throws BaseCheckedException { + requestHandlerRequestValidator.isValidRePrintRegistrationType(null); + } + + @Test + public void testIsValidRegistrationTypeAndUinNestedNestedIf11() throws BaseCheckedException, IOException { + when(uinValidatorImpl.validateId(anyString())).thenReturn(true); + when(utilities.retrieveIdrepoJsonStatus(anyString())).thenReturn("ACTIVATED"); + JSONObject idObject = new JSONObject(); + when(utilities.retrieveIdrepoJson(anyString())).thenReturn(idObject); + boolean result = requestHandlerRequestValidator + .isValidRegistrationTypeAndUin(RegistrationType.RES_UPDATE.name(), "1234"); + assertTrue(result); + } + + @Test(expected = BaseCheckedException.class) + public void testIsValidRegistrationTypeAndUinNestedNestedIf12() throws BaseCheckedException, IOException { + when(uinValidatorImpl.validateId(anyString())).thenReturn(true); + when(utilities.retrieveIdrepoJsonStatus(anyString())).thenReturn("ACTIVATED"); + when(utilities.retrieveIdrepoJson(anyString())).thenReturn(null); + requestHandlerRequestValidator.isValidRegistrationTypeAndUin(RegistrationType.RES_UPDATE.name(), "1234"); + } + + @Test(expected = BaseCheckedException.class) + public void testIsValidRegistrationTypeAndUinNestedNestedIf13() throws BaseCheckedException, IOException { + when(uinValidatorImpl.validateId(anyString())).thenReturn(true); + when(utilities.retrieveIdrepoJsonStatus(anyString())).thenReturn("any status"); + when(utilities.retrieveIdrepoJson(anyString())).thenReturn(new JSONObject()); + requestHandlerRequestValidator.isValidRegistrationTypeAndUin(RegistrationType.RES_UPDATE.name(), "1234"); + } + + @Test + public void testIsValidRegistrationTypeAndUinNestedNestedIf21() throws BaseCheckedException, IOException { + when(uinValidatorImpl.validateId(anyString())).thenReturn(true); + when(utilities.retrieveIdrepoJsonStatus(anyString())).thenReturn("ACTIVATED"); + boolean result = requestHandlerRequestValidator + .isValidRegistrationTypeAndUin(RegistrationType.DEACTIVATED.name(), "1234"); + assertTrue(result); + } + + @Test(expected = BaseCheckedException.class) + public void testIsValidRegistrationTypeAndUinNestedNestedElse21() throws BaseCheckedException, IOException { + when(uinValidatorImpl.validateId(anyString())).thenReturn(true); + when(utilities.retrieveIdrepoJsonStatus(anyString())).thenReturn("ACTIVATED"); + requestHandlerRequestValidator.isValidRegistrationTypeAndUin(RegistrationType.ACTIVATED.name(), "1234"); + } + + @Test(expected = BaseCheckedException.class) + public void testIsValidRegistrationTypeAndUinNestedElse() throws BaseCheckedException, IOException { + when(uinValidatorImpl.validateId(anyString())).thenReturn(false); + + requestHandlerRequestValidator.isValidRegistrationTypeAndUin(RegistrationType.ACTIVATED.name(), "1234"); + } + + @Test(expected = BaseCheckedException.class) + public void testIsValidRegistrationTypeAndUinElse1() throws BaseCheckedException, IOException { + requestHandlerRequestValidator.isValidRegistrationTypeAndUin(null, "1234"); + } + + @Test(expected = BaseCheckedException.class) + public void testIsValidRegistrationTypeAndUinElse2() throws BaseCheckedException, IOException { + requestHandlerRequestValidator.isValidRegistrationTypeAndUin("any registration", "1234"); + } + + @Test(expected = BaseCheckedException.class) + public void testIsValidRegistrationTypeAndUinWithInvalidIDException() throws BaseCheckedException, IOException { + when(uinValidatorImpl.validateId(anyString())).thenReturn(true); + when(utilities.retrieveIdrepoJsonStatus(anyString())).thenThrow(new InvalidIDException("errorcode", "message")); + requestHandlerRequestValidator.isValidRegistrationTypeAndUin(RegistrationType.RES_UPDATE.name(), "1234"); + } + + @Test(expected = BaseCheckedException.class) + public void testIsValidRegistrationTypeAndUinWithNumberFormatException() throws BaseCheckedException, IOException { + when(uinValidatorImpl.validateId(anyString())).thenReturn(true); + when(utilities.retrieveIdrepoJsonStatus(anyString())).thenThrow(new NumberFormatException("message")); + requestHandlerRequestValidator.isValidRegistrationTypeAndUin(RegistrationType.RES_UPDATE.name(), "1234"); + } + + @Test + public void testIsValidVid() throws BaseCheckedException, IOException { + String str = "vid"; + when(vidValidatorImpl.validateId(anyString())).thenReturn(true); + when(utilities.getUinByVid(anyString())).thenReturn(str); + boolean result = requestHandlerRequestValidator.isValidVid(ID); + assertTrue(result); + } + + @Test(expected = BaseCheckedException.class) + public void testIsValidVidElse() throws BaseCheckedException, IOException { + String str = "vid"; + when(vidValidatorImpl.validateId(anyString())).thenReturn(false); + when(utilities.getUinByVid(anyString())).thenReturn(str); + requestHandlerRequestValidator.isValidVid(ID); + } + + @Test(expected = BaseCheckedException.class) + public void testIsValidVidElse2() throws BaseCheckedException, IOException { + when(vidValidatorImpl.validateId(anyString())).thenReturn(true); + when(utilities.getUinByVid(anyString())).thenReturn(null); + requestHandlerRequestValidator.isValidVid(ID); + } + + @Test(expected = BaseCheckedException.class) + public void testIsValidVidWithInvalidIDException() throws BaseCheckedException, IOException { + when(vidValidatorImpl.validateId(anyString())).thenReturn(true); + when(utilities.getUinByVid(anyString())).thenThrow(new InvalidIDException("errorcode", "message")); + requestHandlerRequestValidator.isValidVid(ID); + } + + @Test(expected = BaseCheckedException.class) + public void testIsValidVidWithIdRepoAppException() throws BaseCheckedException, IOException { + when(vidValidatorImpl.validateId(anyString())).thenReturn(true); + when(utilities.getUinByVid(anyString())).thenThrow(new IdRepoAppException("errorcode", "message")); + requestHandlerRequestValidator.isValidVid(ID); + } + + @Test(expected = BaseCheckedException.class) + public void testIsValidVidWithNumberFormatException() throws BaseCheckedException, IOException { + when(vidValidatorImpl.validateId(anyString())).thenReturn(true); + when(utilities.getUinByVid(anyString())).thenThrow(new NumberFormatException("message")); + requestHandlerRequestValidator.isValidVid(ID); + } + + @Test(expected = BaseCheckedException.class) + public void testIsValidVidWithApisResourceAccessException() throws BaseCheckedException, IOException { + when(vidValidatorImpl.validateId(anyString())).thenReturn(true); + when(utilities.getUinByVid(anyString())).thenThrow(new ApisResourceAccessException("message")); + requestHandlerRequestValidator.isValidVid(ID); + } + + @Test(expected = BaseCheckedException.class) + public void testIsValidVidWithVidCreationException() throws BaseCheckedException, IOException { + when(vidValidatorImpl.validateId(anyString())).thenReturn(true); + when(utilities.getUinByVid(anyString())).thenThrow(new VidCreationException("message")); + requestHandlerRequestValidator.isValidVid(ID); + } + + @Test + public void testIsValidIdType() throws Exception { + boolean result = requestHandlerRequestValidator.isValidIdType("UIN"); + assertTrue(result); + } + + @Test + public void testIsValidIdType2() throws BaseCheckedException { + boolean result = requestHandlerRequestValidator.isValidIdType("VID"); + assertTrue(result); + } + + @Test(expected = BaseCheckedException.class) + public void testIsValidIdTypeElse() throws BaseCheckedException { + requestHandlerRequestValidator.isValidIdType(null); + } + + @Test(expected = BaseCheckedException.class) + public void testIsValidIdTypeElse2() throws BaseCheckedException { + requestHandlerRequestValidator.isValidIdType(""); + } + + @Test + public void testIsValidCardType() throws BaseCheckedException, IOException { + boolean result = requestHandlerRequestValidator.isValidCardType(CardType.MASKED_UIN.name()); + assertTrue(result); + } + + @Test + public void testIsValidCardType2() throws BaseCheckedException, IOException { + boolean result = requestHandlerRequestValidator.isValidCardType(CardType.UIN.name()); + assertTrue(result); + } + + @Test(expected = BaseCheckedException.class) + public void testIsValidCardTypeElse() throws BaseCheckedException { + requestHandlerRequestValidator.isValidCardType("voter-id"); + } + + @Test(expected = BaseCheckedException.class) + public void testIsValidCardTypeElse2() throws BaseCheckedException { + requestHandlerRequestValidator.isValidCardType(""); + } + + @Test(expected = BaseCheckedException.class) + public void testIsValidCardTypeElse3() throws BaseCheckedException { + requestHandlerRequestValidator.isValidCardType(null); + } + + @Test + public void testIsValidContact() throws BaseCheckedException, IOException { + String EMAIL = "Email"; + boolean result = requestHandlerRequestValidator.isValidContactType(EMAIL, new LogDescription()); + assertTrue(result); + } + + @Test + public void testIsValidContact2() throws BaseCheckedException, IOException { + String PHONE = "Phone"; + boolean result = requestHandlerRequestValidator.isValidContactType(PHONE, new LogDescription()); + assertTrue(result); + } + + @Test(expected = BaseCheckedException.class) + public void testIsValidContactElse() throws BaseCheckedException { + requestHandlerRequestValidator.isValidContactType("whatsapp", new LogDescription()); + } + + @Test(expected = BaseCheckedException.class) + public void testIsValidContactElse2() throws BaseCheckedException { + requestHandlerRequestValidator.isValidContactType(null, new LogDescription()); + } +} diff --git a/resident/resident-service/src/test/java/io/mosip/resident/test/validator/RequestValidatorTest.java b/resident/resident-service/src/test/java/io/mosip/resident/validator/RequestValidatorTest.java similarity index 75% rename from resident/resident-service/src/test/java/io/mosip/resident/test/validator/RequestValidatorTest.java rename to resident/resident-service/src/test/java/io/mosip/resident/validator/RequestValidatorTest.java index b4046fad600..c042c27ae9f 100644 --- a/resident/resident-service/src/test/java/io/mosip/resident/test/validator/RequestValidatorTest.java +++ b/resident/resident-service/src/test/java/io/mosip/resident/validator/RequestValidatorTest.java @@ -1,34 +1,14 @@ -package io.mosip.resident.test.validator; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Optional; - -import org.joda.time.DateTime; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.springframework.core.env.Environment; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.util.ReflectionTestUtils; +package io.mosip.resident.validator; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.mosip.kernel.core.http.ResponseWrapper; import io.mosip.kernel.core.idvalidator.exception.InvalidIDException; import io.mosip.kernel.core.idvalidator.spi.RidValidator; import io.mosip.kernel.core.idvalidator.spi.UinValidator; import io.mosip.kernel.core.idvalidator.spi.VidValidator; import io.mosip.kernel.core.util.DateUtils; +import io.mosip.preregistration.application.dto.TransliterationRequestDTO; +import io.mosip.preregistration.core.common.dto.MainRequestDTO; import io.mosip.resident.constant.AuthTypeStatus; import io.mosip.resident.constant.CardType; import io.mosip.resident.constant.IdType; @@ -47,11 +27,13 @@ import io.mosip.resident.dto.DownloadPersonalizedCardDto; import io.mosip.resident.dto.EuinRequestDTO; import io.mosip.resident.dto.GrievanceRequestDTO; +import io.mosip.resident.dto.IdentityDTO; import io.mosip.resident.dto.IndividualIdOtpRequestDTO; import io.mosip.resident.dto.OtpRequestDTOV2; import io.mosip.resident.dto.OtpRequestDTOV3; import io.mosip.resident.dto.RequestDTO; import io.mosip.resident.dto.RequestWrapper; +import io.mosip.resident.dto.ResidentCredentialRequestDto; import io.mosip.resident.dto.ResidentReprintRequestDto; import io.mosip.resident.dto.ResidentUpdateRequestDto; import io.mosip.resident.dto.ResidentVidRequestDto; @@ -59,6 +41,7 @@ import io.mosip.resident.dto.SharableAttributesDTO; import io.mosip.resident.dto.VidRequestDto; import io.mosip.resident.dto.VidRequestDtoV2; +import io.mosip.resident.dto.VidRevokeRequestDTO; import io.mosip.resident.dto.VidRevokeRequestDTOV2; import io.mosip.resident.entity.ResidentTransactionEntity; import io.mosip.resident.exception.ApisResourceAccessException; @@ -67,11 +50,43 @@ import io.mosip.resident.exception.ResidentServiceCheckedException; import io.mosip.resident.exception.ResidentServiceException; import io.mosip.resident.repository.ResidentTransactionRepository; +import io.mosip.resident.service.ProxyMasterdataService; import io.mosip.resident.service.ResidentService; import io.mosip.resident.service.impl.IdentityServiceImpl; +import io.mosip.resident.service.impl.ResidentConfigServiceImpl; import io.mosip.resident.service.impl.ResidentServiceImpl; import io.mosip.resident.util.AuditUtil; -import io.mosip.resident.validator.RequestValidator; +import io.mosip.resident.util.Utilities; +import org.joda.time.DateTime; +import org.json.simple.JSONObject; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.springframework.core.env.Environment; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.util.ReflectionTestUtils; + +import java.io.IOException; +import java.time.Instant; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; @RunWith(SpringRunner.class) public class RequestValidatorTest { @@ -91,22 +106,37 @@ public class RequestValidatorTest { @Mock private AuditUtil audit; + @Mock + private Utilities utilities; + @Mock private Environment environment; + @Mock + private ResidentConfigServiceImpl residentConfigService; + @Mock private ResidentTransactionRepository residentTransactionRepository; + @Mock + private ProxyMasterdataService proxyMasterdataService; + @Mock private IdentityServiceImpl identityService; + @Mock + private ObjectMapper objectMapper; + String pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"; @InjectMocks private ResidentService residentService = new ResidentServiceImpl(); + private Object schema; + @Before public void setup() { + schema = "{\\\"$schema\\\":\\\"http:\\/\\/json-schema.org\\/draft-07\\/schema#\\\",\\\"description\\\":\\\"MOSIP Sample identity\\\",\\\"additionalProperties\\\":false,\\\"title\\\":\\\"MOSIP identity\\\",\\\"type\\\":\\\"object\\\",\\\"definitions\\\":{\\\"simpleType\\\":{\\\"uniqueItems\\\":true,\\\"additionalItems\\\":false,\\\"type\\\":\\\"array\\\",\\\"items\\\":{\\\"additionalProperties\\\":false,\\\"type\\\":\\\"object\\\",\\\"required\\\":[\\\"language\\\",\\\"value\\\"],\\\"properties\\\":{\\\"language\\\":{\\\"type\\\":\\\"string\\\"},\\\"value\\\":{\\\"type\\\":\\\"string\\\"}}}},\\\"documentType\\\":{\\\"additionalProperties\\\":false,\\\"type\\\":\\\"object\\\",\\\"properties\\\":{\\\"format\\\":{\\\"type\\\":\\\"string\\\"},\\\"type\\\":{\\\"type\\\":\\\"string\\\"},\\\"value\\\":{\\\"type\\\":\\\"string\\\"},\\\"refNumber\\\":{\\\"type\\\":[\\\"string\\\",\\\"null\\\"]}}},\\\"biometricsType\\\":{\\\"additionalProperties\\\":false,\\\"type\\\":\\\"object\\\",\\\"properties\\\":{\\\"format\\\":{\\\"type\\\":\\\"string\\\"},\\\"version\\\":{\\\"type\\\":\\\"number\\\",\\\"minimum\\\":0},\\\"value\\\":{\\\"type\\\":\\\"string\\\"}}}},\\\"properties\\\":{\\\"identity\\\":{\\\"additionalProperties\\\":false,\\\"type\\\":\\\"object\\\",\\\"required\\\":[\\\"IDSchemaVersion\\\",\\\"fullName\\\",\\\"dateOfBirth\\\",\\\"gender\\\",\\\"addressLine1\\\",\\\"addressLine2\\\",\\\"addressLine3\\\",\\\"region\\\",\\\"province\\\",\\\"city\\\",\\\"zone\\\",\\\"postalCode\\\",\\\"phone\\\",\\\"email\\\",\\\"proofOfIdentity\\\",\\\"individualBiometrics\\\"],\\\"properties\\\":{\\\"proofOfAddress\\\":{\\\"bioAttributes\\\":[],\\\"fieldCategory\\\":\\\"pvt\\\",\\\"format\\\":\\\"none\\\",\\\"fieldType\\\":\\\"default\\\",\\\"$ref\\\":\\\"#\\/definitions\\/documentType\\\"},\\\"gender\\\":{\\\"bioAttributes\\\":[],\\\"fieldCategory\\\":\\\"pvt\\\",\\\"format\\\":\\\"\\\",\\\"fieldType\\\":\\\"default\\\",\\\"$ref\\\":\\\"#\\/definitions\\/simpleType\\\"},\\\"city\\\":{\\\"bioAttributes\\\":[],\\\"validators\\\":[{\\\"validator\\\":\\\"^(?=.{0,50}$).*\\\",\\\"arguments\\\":[],\\\"type\\\":\\\"regex\\\"}],\\\"fieldCategory\\\":\\\"pvt\\\",\\\"format\\\":\\\"none\\\",\\\"fieldType\\\":\\\"default\\\",\\\"$ref\\\":\\\"#\\/definitions\\/simpleType\\\"},\\\"postalCode\\\":{\\\"bioAttributes\\\":[],\\\"validators\\\":[{\\\"validator\\\":\\\"^[(?i)A-Z0-9]{5}$|^NA$\\\",\\\"arguments\\\":[],\\\"type\\\":\\\"regex\\\"}],\\\"fieldCategory\\\":\\\"pvt\\\",\\\"format\\\":\\\"none\\\",\\\"type\\\":\\\"string\\\",\\\"fieldType\\\":\\\"default\\\"},\\\"proofOfException-1\\\":{\\\"bioAttributes\\\":[],\\\"fieldCategory\\\":\\\"evidence\\\",\\\"format\\\":\\\"none\\\",\\\"fieldType\\\":\\\"default\\\",\\\"$ref\\\":\\\"#\\/definitions\\/documentType\\\"},\\\"referenceIdentityNumber\\\":{\\\"bioAttributes\\\":[],\\\"validators\\\":[{\\\"validator\\\":\\\"^([0-9]{10,30})$\\\",\\\"arguments\\\":[],\\\"type\\\":\\\"regex\\\"}],\\\"fieldCategory\\\":\\\"pvt\\\",\\\"format\\\":\\\"kyc\\\",\\\"type\\\":\\\"string\\\",\\\"fieldType\\\":\\\"default\\\"},\\\"individualBiometrics\\\":{\\\"bioAttributes\\\":[\\\"leftEye\\\",\\\"rightEye\\\",\\\"rightIndex\\\",\\\"rightLittle\\\",\\\"rightRing\\\",\\\"rightMiddle\\\",\\\"leftIndex\\\",\\\"leftLittle\\\",\\\"leftRing\\\",\\\"leftMiddle\\\",\\\"leftThumb\\\",\\\"rightThumb\\\",\\\"face\\\"],\\\"fieldCategory\\\":\\\"pvt\\\",\\\"format\\\":\\\"none\\\",\\\"fieldType\\\":\\\"default\\\",\\\"$ref\\\":\\\"#\\/definitions\\/biometricsType\\\"},\\\"province\\\":{\\\"bioAttributes\\\":[],\\\"validators\\\":[{\\\"validator\\\":\\\"^(?=.{0,50}$).*\\\",\\\"arguments\\\":[],\\\"type\\\":\\\"regex\\\"}],\\\"fieldCategory\\\":\\\"pvt\\\",\\\"format\\\":\\\"none\\\",\\\"fieldType\\\":\\\"default\\\",\\\"$ref\\\":\\\"#\\/definitions\\/simpleType\\\"},\\\"zone\\\":{\\\"bioAttributes\\\":[],\\\"fieldCategory\\\":\\\"pvt\\\",\\\"format\\\":\\\"none\\\",\\\"fieldType\\\":\\\"default\\\",\\\"$ref\\\":\\\"#\\/definitions\\/simpleType\\\"},\\\"proofOfDateOfBirth\\\":{\\\"bioAttributes\\\":[],\\\"fieldCategory\\\":\\\"pvt\\\",\\\"format\\\":\\\"none\\\",\\\"fieldType\\\":\\\"default\\\",\\\"$ref\\\":\\\"#\\/definitions\\/documentType\\\"},\\\"addressLine1\\\":{\\\"bioAttributes\\\":[],\\\"validators\\\":[{\\\"validator\\\":\\\"^(?=.{0,50}$).*\\\",\\\"arguments\\\":[],\\\"type\\\":\\\"regex\\\"}],\\\"fieldCategory\\\":\\\"pvt\\\",\\\"format\\\":\\\"none\\\",\\\"fieldType\\\":\\\"default\\\",\\\"$ref\\\":\\\"#\\/definitions\\/simpleType\\\"},\\\"addressLine2\\\":{\\\"bioAttributes\\\":[],\\\"validators\\\":[{\\\"validator\\\":\\\"^(?=.{3,50}$).*\\\",\\\"arguments\\\":[],\\\"type\\\":\\\"regex\\\"}],\\\"fieldCategory\\\":\\\"pvt\\\",\\\"format\\\":\\\"none\\\",\\\"fieldType\\\":\\\"default\\\",\\\"$ref\\\":\\\"#\\/definitions\\/simpleType\\\"},\\\"residenceStatus\\\":{\\\"bioAttributes\\\":[],\\\"fieldCategory\\\":\\\"kyc\\\",\\\"format\\\":\\\"none\\\",\\\"fieldType\\\":\\\"default\\\",\\\"$ref\\\":\\\"#\\/definitions\\/simpleType\\\"},\\\"addressLine3\\\":{\\\"bioAttributes\\\":[],\\\"validators\\\":[{\\\"validator\\\":\\\"^(?=.{3,50}$).*\\\",\\\"arguments\\\":[],\\\"type\\\":\\\"regex\\\"}],\\\"fieldCategory\\\":\\\"pvt\\\",\\\"format\\\":\\\"none\\\",\\\"fieldType\\\":\\\"default\\\",\\\"$ref\\\":\\\"#\\/definitions\\/simpleType\\\"},\\\"email\\\":{\\\"bioAttributes\\\":[],\\\"validators\\\":[{\\\"validator\\\":\\\"^[A-Za-z0-9_\\\\\\\\-]+(\\\\\\\\.[A-Za-z0-9_]+)*@[A-Za-z0-9_-]+(\\\\\\\\.[A-Za-z0-9_]+)*(\\\\\\\\.[a-zA-Z]{2,})$\\\",\\\"arguments\\\":[],\\\"type\\\":\\\"regex\\\"}],\\\"fieldCategory\\\":\\\"pvt\\\",\\\"format\\\":\\\"none\\\",\\\"type\\\":\\\"string\\\",\\\"fieldType\\\":\\\"default\\\"},\\\"introducerRID\\\":{\\\"bioAttributes\\\":[],\\\"fieldCategory\\\":\\\"evidence\\\",\\\"format\\\":\\\"none\\\",\\\"type\\\":\\\"string\\\",\\\"fieldType\\\":\\\"default\\\"},\\\"introducerBiometrics\\\":{\\\"bioAttributes\\\":[\\\"leftEye\\\",\\\"rightEye\\\",\\\"rightIndex\\\",\\\"rightLittle\\\",\\\"rightRing\\\",\\\"rightMiddle\\\",\\\"leftIndex\\\",\\\"leftLittle\\\",\\\"leftRing\\\",\\\"leftMiddle\\\",\\\"leftThumb\\\",\\\"rightThumb\\\",\\\"face\\\"],\\\"fieldCategory\\\":\\\"pvt\\\",\\\"format\\\":\\\"none\\\",\\\"fieldType\\\":\\\"default\\\",\\\"$ref\\\":\\\"#\\/definitions\\/biometricsType\\\"},\\\"fullName\\\":{\\\"bioAttributes\\\":[],\\\"validators\\\":[{\\\"validator\\\":\\\"^(?=.{3,50}$).*\\\",\\\"arguments\\\":[],\\\"type\\\":\\\"regex\\\"}],\\\"fieldCategory\\\":\\\"pvt\\\",\\\"format\\\":\\\"none\\\",\\\"fieldType\\\":\\\"default\\\",\\\"$ref\\\":\\\"#\\/definitions\\/simpleType\\\"},\\\"dateOfBirth\\\":{\\\"bioAttributes\\\":[],\\\"validators\\\":[{\\\"validator\\\":\\\"^(1869|18[7-9][0-9]|19[0-9][0-9]|20[0-9][0-9])\\/([0][1-9]|1[0-2])\\/([0][1-9]|[1-2][0-9]|3[01])$\\\",\\\"arguments\\\":[],\\\"type\\\":\\\"regex\\\"}],\\\"fieldCategory\\\":\\\"pvt\\\",\\\"format\\\":\\\"none\\\",\\\"type\\\":\\\"string\\\",\\\"fieldType\\\":\\\"default\\\"},\\\"individualAuthBiometrics\\\":{\\\"bioAttributes\\\":[\\\"leftEye\\\",\\\"rightEye\\\",\\\"rightIndex\\\",\\\"rightLittle\\\",\\\"rightRing\\\",\\\"rightMiddle\\\",\\\"leftIndex\\\",\\\"leftLittle\\\",\\\"leftRing\\\",\\\"leftMiddle\\\",\\\"leftThumb\\\",\\\"rightThumb\\\",\\\"face\\\"],\\\"fieldCategory\\\":\\\"pvt\\\",\\\"format\\\":\\\"none\\\",\\\"fieldType\\\":\\\"default\\\",\\\"$ref\\\":\\\"#\\/definitions\\/biometricsType\\\"},\\\"introducerUIN\\\":{\\\"bioAttributes\\\":[],\\\"fieldCategory\\\":\\\"evidence\\\",\\\"format\\\":\\\"none\\\",\\\"type\\\":\\\"string\\\",\\\"fieldType\\\":\\\"default\\\"},\\\"proofOfIdentity\\\":{\\\"bioAttributes\\\":[],\\\"fieldCategory\\\":\\\"pvt\\\",\\\"format\\\":\\\"none\\\",\\\"fieldType\\\":\\\"default\\\",\\\"$ref\\\":\\\"#\\/definitions\\/documentType\\\"},\\\"IDSchemaVersion\\\":{\\\"bioAttributes\\\":[],\\\"fieldCategory\\\":\\\"none\\\",\\\"format\\\":\\\"none\\\",\\\"type\\\":\\\"number\\\",\\\"fieldType\\\":\\\"default\\\",\\\"minimum\\\":0},\\\"proofOfException\\\":{\\\"bioAttributes\\\":[],\\\"fieldCategory\\\":\\\"evidence\\\",\\\"format\\\":\\\"none\\\",\\\"fieldType\\\":\\\"default\\\",\\\"$ref\\\":\\\"#\\/definitions\\/documentType\\\"},\\\"phone\\\":{\\\"bioAttributes\\\":[],\\\"validators\\\":[{\\\"validator\\\":\\\"^[+]*([0-9]{1})([0-9]{9})$\\\",\\\"arguments\\\":[],\\\"type\\\":\\\"regex\\\"}],\\\"fieldCategory\\\":\\\"pvt\\\",\\\"format\\\":\\\"none\\\",\\\"type\\\":\\\"string\\\",\\\"fieldType\\\":\\\"default\\\"},\\\"introducerName\\\":{\\\"bioAttributes\\\":[],\\\"fieldCategory\\\":\\\"evidence\\\",\\\"format\\\":\\\"none\\\",\\\"fieldType\\\":\\\"default\\\",\\\"$ref\\\":\\\"#\\/definitions\\/simpleType\\\"},\\\"proofOfRelationship\\\":{\\\"bioAttributes\\\":[],\\\"fieldCategory\\\":\\\"pvt\\\",\\\"format\\\":\\\"none\\\",\\\"fieldType\\\":\\\"default\\\",\\\"$ref\\\":\\\"#\\/definitions\\/documentType\\\"},\\\"UIN\\\":{\\\"bioAttributes\\\":[],\\\"fieldCategory\\\":\\\"none\\\",\\\"format\\\":\\\"none\\\",\\\"type\\\":\\\"string\\\",\\\"fieldType\\\":\\\"default\\\"},\\\"region\\\":{\\\"bioAttributes\\\":[],\\\"validators\\\":[{\\\"validator\\\":\\\"^(?=.{0,50}$).*\\\",\\\"arguments\\\":[],\\\"type\\\":\\\"regex\\\"}],\\\"fieldCategory\\\":\\\"pvt\\\",\\\"format\\\":\\\"none\\\",\\\"fieldType\\\":\\\"default\\\",\\\"$ref\\\":\\\"#\\/definitions\\/simpleType\\\"}}}}}"; Map map = new HashMap(); map.put(RequestIdType.RE_PRINT_ID, "mosip.resident.print"); map.put(RequestIdType.AUTH_LOCK_ID, "mosip.resident.authlock"); @@ -909,22 +939,6 @@ public void testValidUpdateRequestIndividualIdNull() throws Exception{ requestValidator.validateUpdateRequest(requestWrapper, false); } - @Test - public void testValidUpdateRequestIsPatchTrue() throws Exception{ - ResidentUpdateRequestDto requestDTO = new ResidentUpdateRequestDto(); - requestDTO.setIndividualIdType("VID"); - requestDTO.setIndividualId("1234567"); - requestDTO.setOtp("1234567"); - requestDTO.setTransactionID("1234567"); - requestDTO.setIdentityJson(""); - RequestWrapper requestWrapper = new RequestWrapper<>(); - requestWrapper.setRequesttime(DateUtils.getUTCCurrentDateTimeString(pattern)); - requestWrapper.setId("mosip.resident.updateuin"); - requestWrapper.setVersion("1.0"); - requestWrapper.setRequest(requestDTO); - requestValidator.validateUpdateRequest(requestWrapper, true); - } - @Test public void testValidateUpdateRequest() throws Exception{ ResidentUpdateRequestDto requestDTO = new ResidentUpdateRequestDto(); @@ -1467,7 +1481,7 @@ public void testValidateChannelVerificationStatusNullChannel() throws Exception{ requestValidator.validateChannelVerificationStatus(channel, individualId); } - @Test(expected = InvalidInputException.class) + @Test(expected = ResidentServiceException.class) public void testValidateChannelVerificationStatusNullIndividualId() throws Exception{ String channel ="PHONE"; requestValidator.validateChannelVerificationStatus(channel, null); @@ -1622,6 +1636,24 @@ public void testValidateRevokeVidRequestWrapper() throws Exception{ requestValidator.validateRevokeVidRequestWrapper(requestWrapper, "v1"); } + @Test(expected = InvalidInputException.class) + public void testValidateId() throws Exception{ + ReflectionTestUtils.setField(requestValidator, "transliterateId", "mosip.resident.transliteration.transliterate"); + MainRequestDTO requestDTO = new MainRequestDTO<>(); + TransliterationRequestDTO transliterationRequestDTO = new TransliterationRequestDTO(); + requestDTO.setId(null); + requestValidator.validateId(requestDTO); + } + + @Test(expected = InvalidInputException.class) + public void testValidateTransliterationId() throws Exception{ + ReflectionTestUtils.setField(requestValidator, "transliterateId", "mosip.resident.transliteration.transliterate"); + MainRequestDTO requestDTO = new MainRequestDTO<>(); + TransliterationRequestDTO transliterationRequestDTO = new TransliterationRequestDTO(); + requestDTO.setId("mosip"); + requestValidator.validateId(requestDTO); + } + @Test(expected = InvalidInputException.class) public void testValidateRequestNewApi() throws Exception{ RequestWrapper request = new RequestWrapper<>(); @@ -1830,6 +1862,12 @@ public void testValidateProxySendOtpRequestInvalidUserId() throws Exception{ @Test public void testValidateProxySendOtpRequestCorrectPhoneUserId() throws Exception{ + IdentityDTO identityDTO = new IdentityDTO(); + identityDTO.setFullName("kamesh"); + identityDTO.setEmail("kam@g.com"); + identityDTO.setPhone("8809393939"); + when(identityService.getResidentIndvidualIdFromSession()).thenReturn("1234567788"); + when(identityService.getIdentity(Mockito.anyString())).thenReturn(identityDTO); ReflectionTestUtils.setField(requestValidator, "emailRegex", "^[a-zA-Z0-9_\\-\\.]+@[a-zA-Z0-9_\\-]+\\.[a-zA-Z]{2,4}$"); ReflectionTestUtils.setField(requestValidator, "phoneRegex", "^([6-9]{1})([0-9]{9})$"); io.mosip.resident.dto.MainRequestDTO userIdOtpRequest = @@ -1877,15 +1915,16 @@ public void testValidateUpdateDataRequestInvalidPhoneUserId() throws Exception{ public void testValidateUpdateDataRequestCorrectPhoneUserId() throws Exception{ ReflectionTestUtils.setField(requestValidator, "emailRegex", "^[a-zA-Z0-9_\\-\\.]+@[a-zA-Z0-9_\\-]+\\.[a-zA-Z]{2,4}$"); ReflectionTestUtils.setField(requestValidator, "phoneRegex", "^([6-9]{1})([0-9]{9})$"); + Mockito.when(environment.getProperty(Mockito.anyString())).thenReturn("60"); io.mosip.resident.dto.MainRequestDTO userIdOtpRequest = new io.mosip.resident.dto.MainRequestDTO<>(); OtpRequestDTOV3 otpRequestDTOV3 = new OtpRequestDTOV3(); otpRequestDTOV3.setOtp("111111"); otpRequestDTOV3.setTransactionId("1232323232"); - userIdOtpRequest.setId("property"); + userIdOtpRequest.setId("60"); userIdOtpRequest.setVersion("1.0"); otpRequestDTOV3.setUserId("8878787878"); - userIdOtpRequest.setRequesttime(new Date(2012, 2, 2, 2, 2,2)); + userIdOtpRequest.setRequesttime(Date.from(Instant.now())); userIdOtpRequest.setRequest(otpRequestDTOV3); requestValidator.validateUpdateDataRequest(userIdOtpRequest); } @@ -1894,15 +1933,16 @@ public void testValidateUpdateDataRequestCorrectPhoneUserId() throws Exception{ public void testValidateUpdateDataRequestCorrectEmailId() throws Exception{ ReflectionTestUtils.setField(requestValidator, "emailRegex", "^[a-zA-Z0-9_\\-\\.]+@[a-zA-Z0-9_\\-]+\\.[a-zA-Z]{2,4}$"); ReflectionTestUtils.setField(requestValidator, "phoneRegex", "^([6-9]{1})([0-9]{9})$"); + Mockito.when(environment.getProperty(Mockito.anyString())).thenReturn("60"); io.mosip.resident.dto.MainRequestDTO userIdOtpRequest = new io.mosip.resident.dto.MainRequestDTO<>(); OtpRequestDTOV3 otpRequestDTOV3 = new OtpRequestDTOV3(); otpRequestDTOV3.setOtp("111111"); otpRequestDTOV3.setTransactionId("1232323232"); - userIdOtpRequest.setId("property"); + userIdOtpRequest.setId("60"); userIdOtpRequest.setVersion("1.0"); otpRequestDTOV3.setUserId("test@g.com"); - userIdOtpRequest.setRequesttime(new Date(2012, 2, 2, 2, 2,2)); + userIdOtpRequest.setRequesttime(Date.from(Instant.now())); userIdOtpRequest.setRequest(otpRequestDTOV3); requestValidator.validateUpdateDataRequest(userIdOtpRequest); } @@ -2049,6 +2089,19 @@ public void testNullUserIdAndTransactionId(){ requestValidator.validateUserIdAndTransactionId(null, "3232323232"); } + @Test + public void testValidateTransliterationIdSuccess() throws Exception{ + ReflectionTestUtils.setField(requestValidator, "transliterateId", "mosip.resident.transliteration.transliterate"); + MainRequestDTO requestDTO = new MainRequestDTO<>(); + TransliterationRequestDTO transliterationRequestDTO = new TransliterationRequestDTO(); + transliterationRequestDTO.setFromFieldLang("eng"); + transliterationRequestDTO.setToFieldLang("fra"); + transliterationRequestDTO.setFromFieldValue("demo"); + requestDTO.setRequest(transliterationRequestDTO); + requestDTO.setId("mosip.resident.transliteration.transliterate"); + requestValidator.validateId(requestDTO); + } + @Test(expected = InvalidInputException.class) public void testValidateOnlyLanguageCode(){ requestValidator.validateOnlyLanguageCode(null); @@ -2550,4 +2603,546 @@ public void testValidateReqOtp() { requestValidator.validateReqOtp(individualIdOtpRequestDTO); } + @Test(expected = InvalidInputException.class) + public void testValidateRequestTimeFailure(){ + Mockito.when(environment.getProperty(Mockito.anyString())).thenReturn("60"); + requestValidator.validateRequestTime(Date.from(Instant.now().minusSeconds(100))); + } + + @Test + public void testValidateRequestTime(){ + Mockito.when(environment.getProperty(Mockito.anyString())).thenReturn("60"); + requestValidator.validateRequestTime(Date.from(Instant.now().minusSeconds(10))); + } + + @Test + public void testValidateNameWithValidName() throws ResidentServiceCheckedException { + String name = "Kamesh Shekhar Prasad"; + RequestValidator requestValidator1 = Mockito.spy(new RequestValidator()); + requestValidator1.validateName(name); + verify(requestValidator1).validateName(name); + } + + @Test(expected = ResidentServiceCheckedException.class) + public void testValidateNameWithBlankName() throws ResidentServiceCheckedException { + requestValidator.validateName(""); + } + + @Test + public void testValidateGrievanceRequestDtoSuccessWithAlternateEmailID() throws ResidentServiceCheckedException, ApisResourceAccessException { + Mockito.when(environment.getProperty(ResidentConstants.MESSAGE_CODE_MAXIMUM_LENGTH)).thenReturn(String.valueOf(1024)); + Mockito.when(environment.getProperty(ResidentConstants.GRIEVANCE_REQUEST_ID)).thenReturn("id"); + Mockito.when(environment.getProperty(ResidentConstants.GRIEVANCE_REQUEST_VERSION)).thenReturn("version"); + ReflectionTestUtils.setField(requestValidator, "emailRegex", "^[a-zA-Z0-9_\\-\\.]+@[a-zA-Z0-9_\\-]+\\.[a-zA-Z]{2,4}$"); + ReflectionTestUtils.setField(requestValidator, "phoneRegex", "^([6-9]{1})([0-9]{9})$"); + io.mosip.resident.dto.MainRequestDTO grievanceRequestDTOMainRequestDTO = + new io.mosip.resident.dto.MainRequestDTO<>(); + GrievanceRequestDTO grievanceRequestDTO = new GrievanceRequestDTO(); + grievanceRequestDTO.setMessage("message"); + grievanceRequestDTO.setEventId("1212121212121211"); + grievanceRequestDTO.setAlternateEmailId("Ka@g.com"); + grievanceRequestDTO.setAlternatePhoneNo("8898787878"); + grievanceRequestDTOMainRequestDTO.setRequest(grievanceRequestDTO); + grievanceRequestDTOMainRequestDTO.setId("id"); + grievanceRequestDTOMainRequestDTO.setVersion("version"); + grievanceRequestDTOMainRequestDTO.setRequesttime(DateTime.now().toDate()); + requestValidator.validateGrievanceRequestDto(grievanceRequestDTOMainRequestDTO); + } + + @Test + public void testValidateReqCredentialRequestSuccess(){ + RequestWrapper requestWrapper = new RequestWrapper<>(); + ResidentCredentialRequestDto residentCredentialRequestDto = new ResidentCredentialRequestDto(); + residentCredentialRequestDto.setIndividualId("1232323232"); + residentCredentialRequestDto.setCredentialType("Vercred"); + residentCredentialRequestDto.setIssuer("resident"); + residentCredentialRequestDto.setOtp("111111"); + residentCredentialRequestDto.setTransactionID("1232323232"); + requestWrapper.setRequest(residentCredentialRequestDto); + requestValidator.validateReqCredentialRequest(requestWrapper); + } + + @Test(expected = ResidentServiceException.class) + public void testValidateReqCredentialRequestFailure(){ + RequestWrapper requestWrapper = new RequestWrapper<>(); + ResidentCredentialRequestDto residentCredentialRequestDto = new ResidentCredentialRequestDto(); + residentCredentialRequestDto.setIndividualId(""); + requestWrapper.setRequest(residentCredentialRequestDto); + requestValidator.validateReqCredentialRequest(requestWrapper); + } + + @Test(expected = InvalidInputException.class) + public void testValidateDownloadPersonalizedCardInvalidAttributeList() throws Exception{ + io.mosip.resident.dto.MainRequestDTO mainRequestDTO = new io.mosip.resident.dto.MainRequestDTO<>(); + mainRequestDTO.setId("property"); + mainRequestDTO.setVersion("1.0"); + mainRequestDTO.setRequesttime(new Date(2012, 2, 2, 2, 2,2)); + DownloadPersonalizedCardDto downloadPersonalizedCardDto = new DownloadPersonalizedCardDto(); + downloadPersonalizedCardDto.setHtml("html"); + downloadPersonalizedCardDto.setAttributes(List.of()); + mainRequestDTO.setRequest(downloadPersonalizedCardDto); + requestValidator.validateDownloadPersonalizedCard(mainRequestDTO); + } + + @Test(expected = ResidentServiceException.class) + public void testValidateProxySendOtpRequestInCorrectPhoneUserId() throws Exception{ + IdentityDTO identityDTO = new IdentityDTO(); + identityDTO.setFullName("kamesh"); + identityDTO.setEmail("kam@g.com"); + identityDTO.setPhone("8878787878"); + when(identityService.getResidentIndvidualIdFromSession()).thenReturn("1234567788"); + when(identityService.getIdentity(Mockito.anyString())).thenReturn(identityDTO); + ReflectionTestUtils.setField(requestValidator, "emailRegex", "^[a-zA-Z0-9_\\-\\.]+@[a-zA-Z0-9_\\-]+\\.[a-zA-Z]{2,4}$"); + ReflectionTestUtils.setField(requestValidator, "phoneRegex", "^([6-9]{1})([0-9]{9})$"); + io.mosip.resident.dto.MainRequestDTO userIdOtpRequest = + new io.mosip.resident.dto.MainRequestDTO<>(); + OtpRequestDTOV2 otpRequestDTOV2 = new OtpRequestDTOV2(); + otpRequestDTOV2.setTransactionId("1232323232"); + userIdOtpRequest.setId("property"); + userIdOtpRequest.setVersion("1.0"); + otpRequestDTOV2.setUserId("8878787878"); + userIdOtpRequest.setRequesttime(new Date(2012, 2, 2, 2, 2,2)); + userIdOtpRequest.setRequest(otpRequestDTOV2); + requestValidator.validateProxySendOtpRequest(userIdOtpRequest); + } + + @Test(expected = ResidentServiceException.class) + public void testValidateProxySendOtpRequestInCorrectEmailUserId() throws Exception{ + IdentityDTO identityDTO = new IdentityDTO(); + identityDTO.setFullName("kamesh"); + identityDTO.setEmail("kam@g.com"); + identityDTO.setPhone("887878"); + when(identityService.getResidentIndvidualIdFromSession()).thenReturn("1234567788"); + when(identityService.getIdentity(Mockito.anyString())).thenReturn(identityDTO); + ReflectionTestUtils.setField(requestValidator, "emailRegex", "^[a-zA-Z0-9_\\-\\.]+@[a-zA-Z0-9_\\-]+\\.[a-zA-Z]{2,4}$"); + ReflectionTestUtils.setField(requestValidator, "phoneRegex", "^([6-9]{1})([0-9]{9})$"); + io.mosip.resident.dto.MainRequestDTO userIdOtpRequest = + new io.mosip.resident.dto.MainRequestDTO<>(); + OtpRequestDTOV2 otpRequestDTOV2 = new OtpRequestDTOV2(); + otpRequestDTOV2.setTransactionId("1232323232"); + userIdOtpRequest.setId("property"); + userIdOtpRequest.setVersion("1.0"); + otpRequestDTOV2.setUserId("kam@g.com"); + userIdOtpRequest.setRequesttime(new Date(2012, 2, 2, 2, 2,2)); + userIdOtpRequest.setRequest(otpRequestDTOV2); + requestValidator.validateProxySendOtpRequest(userIdOtpRequest); + } + + @Test(expected = ResidentServiceException.class) + public void testValidateProxySendOtpRequestFailed() throws Exception{ + IdentityDTO identityDTO = new IdentityDTO(); + identityDTO.setFullName("kamesh"); + identityDTO.setEmail("kam@g.com"); + identityDTO.setPhone("887878"); + when(identityService.getResidentIndvidualIdFromSession()).thenReturn("1234567788"); + when(identityService.getIdentity(Mockito.anyString())).thenThrow(new ResidentServiceCheckedException()); + ReflectionTestUtils.setField(requestValidator, "emailRegex", "^[a-zA-Z0-9_\\-\\.]+@[a-zA-Z0-9_\\-]+\\.[a-zA-Z]{2,4}$"); + ReflectionTestUtils.setField(requestValidator, "phoneRegex", "^([6-9]{1})([0-9]{9})$"); + io.mosip.resident.dto.MainRequestDTO userIdOtpRequest = + new io.mosip.resident.dto.MainRequestDTO<>(); + OtpRequestDTOV2 otpRequestDTOV2 = new OtpRequestDTOV2(); + otpRequestDTOV2.setTransactionId("1232323232"); + userIdOtpRequest.setId("property"); + userIdOtpRequest.setVersion("1.0"); + otpRequestDTOV2.setUserId("kam@g.com"); + userIdOtpRequest.setRequesttime(new Date(2012, 2, 2, 2, 2,2)); + userIdOtpRequest.setRequest(otpRequestDTOV2); + requestValidator.validateProxySendOtpRequest(userIdOtpRequest); + } + + @Test(expected = InvalidInputException.class) + public void testValidateTransliterationIdLangFailed() throws Exception{ + ReflectionTestUtils.setField(requestValidator, "transliterateId", "mosip.resident.transliteration.transliterate"); + MainRequestDTO requestDTO = new MainRequestDTO<>(); + TransliterationRequestDTO transliterationRequestDTO = new TransliterationRequestDTO(); + transliterationRequestDTO.setFromFieldLang("eng"); + transliterationRequestDTO.setToFieldLang("eng"); + transliterationRequestDTO.setFromFieldValue("demo"); + requestDTO.setRequest(transliterationRequestDTO); + requestDTO.setId("mosip.resident.transliteration.transliterate"); + requestValidator.validateId(requestDTO); + } + + @Test + public void testValidateOtpCharLimit(){ + requestValidator.validateOtpCharLimit("111111"); + } + + @Test(expected = ResidentServiceException.class) + public void testValidateOtpCharLimitFailed(){ + requestValidator.validateOtpCharLimit("11111111"); + } + + @Test(expected = InvalidInputException.class) + public void testValidateSchemaType(){ + requestValidator.validateSchemaType("ui"); + } + + @Test + public void testValidateSchemaTypeSuccess(){ + requestValidator.validateSchemaType("update-demographics"); + } + + @Test + public void testValidateSearchText(){ + requestValidator.validateSearchText(null); + } + + @Test + public void testValidateSearchTextNotNull(){ + requestValidator.validateSearchText("11"); + } + + @Test(expected = ResidentServiceException.class) + public void testValidateSearchTextNotNullFailure(){ + requestValidator.validateSearchText("154654545454124545451"); + } + + @Test(expected = ResidentServiceException.class) + public void testValidateChannelVerificationStatusInvalidAllowedChar() throws Exception{ + String channel ="PHONE"; + requestValidator.validateChannelVerificationStatus(channel, "$"); + } + + @Test(expected = ResidentServiceException.class) + public void testValidateChannelVerificationStatusInvalidVidLength() throws Exception{ + String channel ="PHONE"; + requestValidator.validateChannelVerificationStatus(channel, "454645787845124578"); + } + + @Test(expected = InvalidInputException.class) + public void testValidateAidStatusRequestDtoFailure() throws Exception{ + AidStatusRequestDTO aidStatusRequestDTO = new AidStatusRequestDTO(); + aidStatusRequestDTO.setIndividualId(null); + aidStatusRequestDTO.setTransactionId("1234567890"); + RequestWrapper requestWrapper = new RequestWrapper<>(); + requestWrapper.setRequesttime(DateUtils.getUTCCurrentDateTimeString(pattern)); + requestWrapper.setId("mosip.resident.checkstatus"); + requestWrapper.setVersion("1.0"); + requestWrapper.setRequest(aidStatusRequestDTO); + requestValidator.validateAidStatusRequestDto(requestWrapper); + } + + @Test(expected = InvalidInputException.class) + public void testValidateUpdateRequestV2Failed() throws Exception{ + Mockito.when(identityService.getResidentIndvidualIdFromSession()).thenReturn("1212121212"); + JSONObject jsonObject = new JSONObject(); + jsonObject.put("IDSchemaVersion", "0.2"); + ResponseWrapper idSchemaResponse = new ResponseWrapper(); + JSONObject object = new JSONObject(); + object.put("schemaJson", schema); + idSchemaResponse.setResponse(object); + Map map = new HashMap<>(); + when(objectMapper.convertValue(object, Map.class)).thenReturn(object); + + when(proxyMasterdataService.getLatestIdSchema(0.2, null, null)).thenReturn(idSchemaResponse); + Mockito.when(utilities.retrieveIdrepoJson(Mockito.anyString())).thenReturn(jsonObject); + + ResidentUpdateRequestDto requestDTO = new ResidentUpdateRequestDto(); + requestDTO.setIndividualIdType("UIN"); + requestDTO.setIndividualId("1234567"); + requestDTO.setOtp("1234567"); + requestDTO.setTransactionID("1234567"); + requestDTO.setIdentityJson("abcdef"); + RequestWrapper requestWrapper = new RequestWrapper<>(); + requestWrapper.setRequesttime(DateUtils.getUTCCurrentDateTimeString(pattern)); + requestWrapper.setId("mosip.resident.updateuin"); + requestWrapper.setVersion("1.0"); + requestWrapper.setRequest(requestDTO); + requestValidator.validateUpdateRequest(requestWrapper, true); + } + + @Test + public void testValidateUpdateRequestV2Passed() throws Exception{ + Mockito.when(identityService.getResidentIndvidualIdFromSession()).thenReturn("1212121212"); + JSONObject jsonObject = new JSONObject(); + jsonObject.put("IDSchemaVersion", "0.2"); + ResponseWrapper idSchemaResponse = new ResponseWrapper(); + JSONObject object = new JSONObject(); + object.put("schemaJson", schema); + idSchemaResponse.setResponse(object); + Map map = new HashMap<>(); + when(objectMapper.convertValue(object, Map.class)).thenReturn(object); + + when(proxyMasterdataService.getLatestIdSchema(0.2, null, null)).thenReturn(idSchemaResponse); + Mockito.when(utilities.retrieveIdrepoJson(Mockito.anyString())).thenReturn(jsonObject); + + ResidentUpdateRequestDto requestDTO = new ResidentUpdateRequestDto(); + requestDTO.setIndividualIdType("UIN"); + requestDTO.setIndividualId("1234567"); + requestDTO.setOtp("1234567"); + requestDTO.setTransactionID("1234567"); + requestDTO.setIdentityJson("abcdef"); + JSONObject jsonObject1 = new JSONObject(); + jsonObject1.put("identity","abc"); + requestDTO.setIdentity(jsonObject1); + RequestWrapper requestWrapper = new RequestWrapper<>(); + requestWrapper.setRequesttime(DateUtils.getUTCCurrentDateTimeString(pattern)); + requestWrapper.setId("mosip.resident.updateuin"); + requestWrapper.setVersion("1.0"); + requestWrapper.setRequest(requestDTO); + requestValidator.validateUpdateRequest(requestWrapper, true); + } + + @Test + public void testValidateUpdateRequestV2PassedWithLanguageCode() throws Exception{ + Mockito.when(identityService.getResidentIndvidualIdFromSession()).thenReturn("1212121212"); + JSONObject jsonObject = new JSONObject(); + jsonObject.put("IDSchemaVersion", "0.2"); + ResponseWrapper idSchemaResponse = new ResponseWrapper(); + JSONObject object = new JSONObject(); + object.put("schemaJson", schema); + idSchemaResponse.setResponse(object); + Map map = new HashMap<>(); + when(objectMapper.convertValue(object, Map.class)).thenReturn(object); + + when(proxyMasterdataService.getLatestIdSchema(0.2, null, null)).thenReturn(idSchemaResponse); + Mockito.when(utilities.retrieveIdrepoJson(Mockito.anyString())).thenReturn(jsonObject); + + ResidentUpdateRequestDto requestDTO = new ResidentUpdateRequestDto(); + requestDTO.setIndividualIdType("UIN"); + requestDTO.setIndividualId("1234567"); + requestDTO.setOtp("1234567"); + requestDTO.setTransactionID("1234567"); + requestDTO.setIdentityJson("abcdef"); + JSONObject jsonObject1 = new JSONObject(); + jsonObject1.put("identity","abc"); + ArrayList> languageMap = new ArrayList<>(); + Map language = new HashMap<>(); + language.put("language", "eng"); + language.put("value", "eng"); + languageMap.add(language); + jsonObject1.put("value", languageMap); + requestDTO.setIdentity(jsonObject1); + RequestWrapper requestWrapper = new RequestWrapper<>(); + requestWrapper.setRequesttime(DateUtils.getUTCCurrentDateTimeString(pattern)); + requestWrapper.setId("mosip.resident.updateuin"); + requestWrapper.setVersion("1.0"); + requestWrapper.setRequest(requestDTO); + requestValidator.validateUpdateRequest(requestWrapper, true); + } + + @Test(expected = InvalidInputException.class) + public void testValidateUpdateRequestV2InvalidTransactionId() throws Exception{ + Mockito.when(identityService.getResidentIndvidualIdFromSession()).thenReturn("1212121212"); + JSONObject jsonObject = new JSONObject(); + jsonObject.put("IDSchemaVersion", "0.2"); + ResponseWrapper idSchemaResponse = new ResponseWrapper(); + JSONObject object = new JSONObject(); + object.put("schemaJson", schema); + idSchemaResponse.setResponse(object); + Map map = new HashMap<>(); + when(objectMapper.convertValue(object, Map.class)).thenReturn(object); + + when(proxyMasterdataService.getLatestIdSchema(0.2, null, null)).thenReturn(idSchemaResponse); + Mockito.when(utilities.retrieveIdrepoJson(Mockito.anyString())).thenReturn(jsonObject); + + ResidentUpdateRequestDto requestDTO = new ResidentUpdateRequestDto(); + requestDTO.setIndividualIdType("UIN"); + requestDTO.setIndividualId("1234567"); + requestDTO.setOtp("1234567"); + requestDTO.setTransactionID(""); + requestDTO.setIdentityJson("abcdef"); + JSONObject jsonObject1 = new JSONObject(); + jsonObject1.put("identity","abc"); + ArrayList> languageMap = new ArrayList<>(); + Map language = new HashMap<>(); + language.put("language", "eng"); + language.put("value", "eng"); + languageMap.add(language); + jsonObject1.put("value", languageMap); + requestDTO.setIdentity(jsonObject1); + RequestWrapper requestWrapper = new RequestWrapper<>(); + requestWrapper.setRequesttime(DateUtils.getUTCCurrentDateTimeString(pattern)); + requestWrapper.setId("mosip.resident.updateuin"); + requestWrapper.setVersion("1.0"); + requestWrapper.setRequest(requestDTO); + requestValidator.validateUpdateRequest(requestWrapper, true); + } + + @Test + public void testValidateUpdateRequestV2FailedWithLanguageCode() throws Exception{ + ReflectionTestUtils.setField(requestValidator, "attributeNamesWithoutDocumentsRequired", "email"); + Mockito.when(identityService.getResidentIndvidualIdFromSession()).thenReturn("1212121212"); + Map identityMappingMap = new HashMap<>(); + Map identityValue = new HashMap<>(); + identityValue.put("value", "email"); + identityMappingMap.put("email", identityValue); + Mockito.when(residentConfigService.getIdentityMappingMap()).thenReturn(identityMappingMap); + JSONObject jsonObject = new JSONObject(); + jsonObject.put("IDSchemaVersion", "0.2"); + ResponseWrapper idSchemaResponse = new ResponseWrapper(); + JSONObject object = new JSONObject(); + object.put("schemaJson", schema); + idSchemaResponse.setResponse(object); + Map map = new HashMap<>(); + when(objectMapper.convertValue(object, Map.class)).thenReturn(object); + + when(proxyMasterdataService.getLatestIdSchema(0.2, null, null)).thenReturn(idSchemaResponse); + Mockito.when(utilities.retrieveIdrepoJson(Mockito.anyString())).thenReturn(jsonObject); + + ResidentUpdateRequestDto requestDTO = new ResidentUpdateRequestDto(); + requestDTO.setIndividualIdType("UIN"); + requestDTO.setIndividualId("1234567"); + requestDTO.setOtp("1234567"); + requestDTO.setTransactionID("1234567"); + requestDTO.setIdentityJson("abcdef"); + JSONObject jsonObject1 = new JSONObject(); + jsonObject1.put("identity","abc"); + ArrayList> languageMap = new ArrayList<>(); + Map language = new HashMap<>(); + language.put("language", "eng"); + language.put("value", "eng"); + languageMap.add(language); + jsonObject1.put("value", languageMap); + requestDTO.setIdentity(jsonObject1); + RequestWrapper requestWrapper = new RequestWrapper<>(); + requestWrapper.setRequesttime(DateUtils.getUTCCurrentDateTimeString(pattern)); + requestWrapper.setId("mosip.resident.updateuin"); + requestWrapper.setVersion("1.0"); + requestWrapper.setRequest(requestDTO); + requestValidator.validateUpdateRequest(requestWrapper, true); + } + + @Test(expected = RuntimeException.class) + public void testValidateUpdateRequestV2FailedWithRunTimeException() throws Exception{ + ReflectionTestUtils.setField(requestValidator, "attributeNamesWithoutDocumentsRequired", "email"); + Mockito.when(identityService.getResidentIndvidualIdFromSession()).thenReturn("1212121212"); + Map identityMappingMap = new HashMap<>(); + Map identityValue = new HashMap<>(); + identityValue.put("value", "email"); + identityMappingMap.put("email", identityValue); + Mockito.when(residentConfigService.getIdentityMappingMap()).thenThrow(new IOException()); + JSONObject jsonObject = new JSONObject(); + jsonObject.put("IDSchemaVersion", "0.2"); + ResponseWrapper idSchemaResponse = new ResponseWrapper(); + JSONObject object = new JSONObject(); + object.put("schemaJson", schema); + idSchemaResponse.setResponse(object); + Map map = new HashMap<>(); + when(objectMapper.convertValue(object, Map.class)).thenReturn(object); + + when(proxyMasterdataService.getLatestIdSchema(0.2, null, null)).thenReturn(idSchemaResponse); + Mockito.when(utilities.retrieveIdrepoJson(Mockito.anyString())).thenReturn(jsonObject); + + ResidentUpdateRequestDto requestDTO = new ResidentUpdateRequestDto(); + requestDTO.setIndividualIdType("UIN"); + requestDTO.setIndividualId("1234567"); + requestDTO.setOtp("1234567"); + requestDTO.setTransactionID("1234567"); + requestDTO.setIdentityJson("abcdef"); + JSONObject jsonObject1 = new JSONObject(); + jsonObject1.put("identity","abc"); + ArrayList> languageMap = new ArrayList<>(); + Map language = new HashMap<>(); + language.put("language", "eng"); + language.put("value", "eng"); + languageMap.add(language); + jsonObject1.put("value", languageMap); + requestDTO.setIdentity(jsonObject1); + RequestWrapper requestWrapper = new RequestWrapper<>(); + requestWrapper.setRequesttime(DateUtils.getUTCCurrentDateTimeString(pattern)); + requestWrapper.setId("mosip.resident.updateuin"); + requestWrapper.setVersion("1.0"); + requestWrapper.setRequest(requestDTO); + requestValidator.validateUpdateRequest(requestWrapper, true); + } + + @Test + public void testEmailsCharValidator(){ + requestValidator.emailCharsValidator("ka@g.com"); + } + + @Test(expected = ResidentServiceException.class) + public void testEmailsCharValidatorFailed(){ + requestValidator.emailCharsValidator("45454545454545454545454545454545454545454545454545454545454545454545454545454545454545454545454545454545454545454545454545454545454545454545"); + } + + @Test(expected = ResidentServiceException.class) + public void testPhoneCharsValidator(){ + UUID uuid = UUID.randomUUID(); + requestValidator.phoneCharsValidator("45454545454545454545454545454545454545454545454545454545454545454545454545454545454545454545454545454545454545454545454545454545454545454545"); + } + + @Test + public void testValidateRid(){ + Mockito.when(ridValidator.validateId(Mockito.anyString())).thenReturn(true); + assertTrue(requestValidator.validateRid("11345678")); + } + + @Test + public void testValidateRidFailed(){ + Mockito.when(ridValidator.validateId(Mockito.anyString())).thenThrow(new InvalidIDException(ResidentErrorCode.INVALID_RID.getErrorCode(), + ResidentErrorCode.INVALID_RID.getErrorMessage())); + assertFalse(requestValidator.validateRid("11345678")); + } + + @Test(expected = InvalidInputException.class) + public void testValidateVidRevokeV2RequestEmptyRequestIdEmptyVidStatusFailure() throws Exception{ + ReflectionTestUtils.setField(requestValidator, "revokeVidIdNew", "1.0"); + ReflectionTestUtils.setField(requestValidator, "revokeVidVersion", "1.0"); + RequestWrapper requestDto = new RequestWrapper<>(); + requestDto.setId("1.0"); + requestDto.setVersion("1.0"); + VidRevokeRequestDTO vidRevokeRequestDTO = new VidRevokeRequestDTO(); + vidRevokeRequestDTO.setVidStatus("REVOKED"); + vidRevokeRequestDTO.setTransactionID("1212121212"); + requestDto.setRequest(vidRevokeRequestDTO); + requestDto.setRequesttime(LocalDateTime.now().toString()); + requestValidator.validateVidRevokeV2Request(requestDto, false, "3956038419"); + } + + @Test(expected = InvalidInputException.class) + public void testValidateVidRevokeV2RequestEmptyRequestIdEmptyOtpFailure() throws Exception{ + ReflectionTestUtils.setField(requestValidator, "revokeVidIdNew", "1.0"); + ReflectionTestUtils.setField(requestValidator, "revokeVidVersion", "1.0"); + RequestWrapper requestDto = new RequestWrapper<>(); + requestDto.setId("1.0"); + requestDto.setVersion("1.0"); + VidRevokeRequestDTO vidRevokeRequestDTO = new VidRevokeRequestDTO(); + vidRevokeRequestDTO.setVidStatus("REVOKED"); + vidRevokeRequestDTO.setTransactionID("1212121212"); + vidRevokeRequestDTO.setIndividualId("123"); + requestDto.setRequest(vidRevokeRequestDTO); + requestDto.setRequesttime(LocalDateTime.now().toString()); + requestValidator.validateVidRevokeV2Request(requestDto, true, "3956038419"); + } + + @Test(expected = InvalidInputException.class) + public void testValidateAuthLockOrUnlockRequestV2Failed() throws Exception{ + ReflectionTestUtils.setField(requestValidator, "authLockStatusUpdateV2Id", "mosip.resident.auth.lock.unlock"); + AuthLockOrUnLockRequestDtoV2 authLockOrUnLockRequestDtoV2 = new AuthLockOrUnLockRequestDtoV2(); + List authTypes = new ArrayList<>(); + AuthTypeStatusDtoV2 authTypeStatusDto = new AuthTypeStatusDtoV2(); + authTypeStatusDto.setAuthType("bio-IR"); + authTypeStatusDto.setLocked(true); + authTypeStatusDto.setUnlockForSeconds(10L); + authTypes.add(authTypeStatusDto); + authLockOrUnLockRequestDtoV2.setAuthTypes(authTypes); + RequestWrapper requestWrapper = new RequestWrapper<>(); + requestWrapper.setRequesttime(DateUtils.getUTCCurrentDateTimeString(pattern)); + requestWrapper.setId("mosip.resident.auth.lock.unlock"); + requestWrapper.setVersion("1.0"); + requestWrapper.setRequest(authLockOrUnLockRequestDtoV2); + requestValidator.validateAuthLockOrUnlockRequestV2(requestWrapper); + } + + @Test(expected = InvalidInputException.class) + public void testValidateAuthLockOrUnlockRequestV2FailedUnlockSeconds() throws Exception{ + ReflectionTestUtils.setField(requestValidator, "authLockStatusUpdateV2Id", "mosip.resident.auth.lock.unlock"); + AuthLockOrUnLockRequestDtoV2 authLockOrUnLockRequestDtoV2 = new AuthLockOrUnLockRequestDtoV2(); + List authTypes = new ArrayList<>(); + AuthTypeStatusDtoV2 authTypeStatusDto = new AuthTypeStatusDtoV2(); + authTypeStatusDto.setAuthType("bio-FIR"); + authTypeStatusDto.setLocked(true); + authTypeStatusDto.setUnlockForSeconds(-10L); + authTypes.add(authTypeStatusDto); + authLockOrUnLockRequestDtoV2.setAuthTypes(authTypes); + RequestWrapper requestWrapper = new RequestWrapper<>(); + requestWrapper.setRequesttime(DateUtils.getUTCCurrentDateTimeString(pattern)); + requestWrapper.setId("mosip.resident.auth.lock.unlock"); + requestWrapper.setVersion("1.0"); + requestWrapper.setRequest(authLockOrUnLockRequestDtoV2); + requestValidator.validateAuthLockOrUnlockRequestV2(requestWrapper); + } } diff --git a/resident/resident-service/src/test/resources/amr-acr-mapping.json b/resident/resident-service/src/test/resources/amr-acr-mapping.json new file mode 100644 index 00000000000..e6802646629 --- /dev/null +++ b/resident/resident-service/src/test/resources/amr-acr-mapping.json @@ -0,0 +1,14 @@ +{ + "amr" : { + "PIN" : [{ "type": "PIN" }], + "OTP" : [{ "type": "OTP" }], + "Wallet" : [{ "type": "WLA" }], + "L1-bio-device" : [{ "type": "BIO", "count": 1 }] + }, + "acr_amr" : { + "mosip:idp:acr:static-code" : ["PIN"], + "mosip:idp:acr:generated-code" : ["OTP"], + "mosip:idp:acr:linked-wallet" : [ "Wallet" ], + "mosip:idp:acr:biometrics" : [ "L1-bio-device" ] + } +} diff --git a/resident/resident-service/src/test/resources/application.properties b/resident/resident-service/src/test/resources/application.properties index bcd9131f85f..284186bc3d6 100644 --- a/resident/resident-service/src/test/resources/application.properties +++ b/resident/resident-service/src/test/resources/application.properties @@ -76,6 +76,7 @@ PARTNER_REFERENCE_Id=mpartner-default-print DECRYPT_API_URL=https://qa.mosip.net/v1/keymanager/decrypt APPLICATION_Id=RESIDENT mosip.kernel.pdf_owner_password=123456 +resident.attribute.names.without.documents.required=preferredLanguage,email,phone #-----------------------------RID Properties--------------------------------------- # length of the rid mosip.kernel.rid.length=29 @@ -346,7 +347,7 @@ resident.dateofbirth.pattern=yyyy/MM/dd resident.revokevid.version=v1 # Identity Data format MVEL file name -resident-data-format-mvel-file-name=identity-data-formatter.mvel +resident-data-format-mvel-file-name=credentialdata.mvel resident-data-format-mvel-file-source=classpath:${resident-data-format-mvel-file-name} #Mask functions @@ -402,7 +403,7 @@ resident.document.delete.version=1.0 resident.service.event.id=mosip.resident.event.status resident.service.event.version=1.0 mosip.resident.transliteration.transliterate.id=mosip.resident.transliteration.transliterate -resident.data.mask.function=convertToMaskDataFormat +resident.data.mask.function=convertToMaskData mosip.notification.timezone=GMT+05:30 @@ -445,7 +446,6 @@ resident.service-history.download.max.count=100 resident.additional.identity.attribute.to.fetch=UIN,email,phone,dateOfBirth,fullName auth.token.header=Authorization -resident.async.request.types=VID_CARD_DOWNLOAD,ORDER_PHYSICAL_CARD resident.batchjob.process.status.list=NEW,ISSUED,RECEIVED,PRINTING,FAILED mosip.resident.keymanager.application-name=RESIDENT mosip.resident.keymanager.reference-id=resident_document @@ -457,3 +457,23 @@ resident.otp.validation.transaction-id.regex=^[0-9]{10}$ resident.validation.event-id.regex=^[0-9]{16}$ mosip.registration.processor.rid.delimiter=-PDF +resident.registration-centers.download.max.count=10 + +# amr-acr JSON file name +amr-acr.json.filename=amr-acr-mapping.json + +mosip.resident.authentication.mode.property=authenticationMode + +# WebSub Topic and callback propertis for auth type status event +mosip.api.internal.url=https://dev.mosip.net +resident.websub.credential-status-update.secret=dummypassword +resident.websub.credential-status.secret=${resident.websub.credential-status-update.secret} +resident.websub.credential-status.topic=AUTH_TYPE_STATUS_UPDATE_ACK +resident.websub.callback.credential-status.relative.url=${server.servlet.context-path}/callback/credentialStatusUpdate +resident.websub.callback.credential-status.url=${mosip.api.internal.url}${resident.websub.callback.credential-status.relative.url} + +idrepo-dummy-online-verification-partner-id=MOVP + +mosip.resident.download.card.naming.convention=Get_my_UIN +# Asyc Request Types +resident.async.request.types=VID_CARD_DOWNLOAD,ORDER_PHYSICAL_CARD,SHARE_CRED_WITH_PARTNER,UPDATE_MY_UIN diff --git a/resident/resident-service/src/test/resources/credentialdata.mvel b/resident/resident-service/src/test/resources/credentialdata.mvel new file mode 100644 index 00000000000..aece9354d56 --- /dev/null +++ b/resident/resident-service/src/test/resources/credentialdata.mvel @@ -0,0 +1,10 @@ + +def maskPhone(inputPhoneNum) { + +return inputPhoneNum.replaceAll(".(?=.{4})", "*"); +}; + +def maskEmail(inputEmailAddr) { + +return inputEmailAddr.replaceAll("(^[^@]{3}|(?!^)\\G)[^@]", "$1*"); +};