diff --git a/README.md b/README.md index d423976b56c..49a17c93cb2 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,5 @@ -[![Maven Package upon a push](https://github.com/mosip/registration/actions/workflows/push_trigger.yml/badge.svg?branch=release-1.2.0)](https://github.com/mosip/registration/actions/workflows/push_trigger.yml) -[![Quality Gate Status](https://sonarcloud.io/api/project_badges/measure?branch=release-1.2.0&project=mosip_registration&metric=alert_status)](https://sonarcloud.io/dashboard?branch=release-1.2.0&id=mosip_registration) +[![Maven Package upon a push](https://github.com/mosip/registration/actions/workflows/push_trigger.yml/badge.svg?branch=release-1.2.0.1)](https://github.com/mosip/registration/actions/workflows/push_trigger.yml) +[![Quality Gate Status](https://sonarcloud.io/api/project_badges/measure?branch=release-1.2.0.1&project=mosip_registration&metric=alert_status)](https://sonarcloud.io/dashboard?branch=release-1.2.0.1&id=mosip_registration) # Registration Processor diff --git a/db_release_scripts/mosip_regprc/ddl/regprc-additional_info_request.sql b/db_release_scripts/mosip_regprc/ddl/regprc-additional_info_request.sql deleted file mode 100644 index 4e468a7216c..00000000000 --- a/db_release_scripts/mosip_regprc/ddl/regprc-additional_info_request.sql +++ /dev/null @@ -1,27 +0,0 @@ --- ------------------------------------------------------------------------------------------------- --- Database Name: mosip_regprc --- Table Name : regprc.additional_info_request --- Purpose : Additional Info Request : --- --- Create By : Ram Bhatt --- Created Date : Jul-2021 --- --- Modified Date Modified By Comments / Remarks --- ------------------------------------------------------------------------------------------ - --- ------------------------------------------------------------------------------------------ - --- object: regprc.additional_info_request | type: TABLE -- --- DROP TABLE IF EXISTS regprc.additional_info_request CASCADE; -CREATE TABLE regprc.additional_info_request( - additional_info_process character varying(64), - reg_id character varying(39), - workflow_instance_id character varying(36), - timestamp timestamp, - additional_info_iteration integer, - additional_info_req_id character varying(256), - CONSTRAINT pk_addl_info_req PRIMARY KEY (workflow_instance_id , additional_info_req_id) - -); --- ddl-end -- - diff --git a/db_release_scripts/mosip_regprc/ddl/regprc-anonymous_profile.sql b/db_release_scripts/mosip_regprc/ddl/regprc-anonymous_profile.sql deleted file mode 100644 index 820eff5fe5a..00000000000 --- a/db_release_scripts/mosip_regprc/ddl/regprc-anonymous_profile.sql +++ /dev/null @@ -1,29 +0,0 @@ --- ------------------------------------------------------------------------------------------------- --- Database Name: mosip_regprc --- Table Name : regprc.anonymous_profile --- Purpose : Storing anonymous profile info --- --- Create By : Monobikash Das --- Created Date : Sep-2021 --- --- Modified Date Modified By Comments / Remarks --- ------------------------------------------------------------------------------------------ - --- ------------------------------------------------------------------------------------------ - --- object: regprc.anonymous_profile | type: TABLE -- --- DROP TABLE IF EXISTS regprc.anonymous_profile CASCADE; -CREATE TABLE regprc.anonymous_profile( - id character varying(39) NOT NULL, - process_stage character varying(36) NOT NULL, - profile character varying NOT NULL, - cr_by character varying(256) NOT NULL, - cr_dtimes timestamp NOT NULL, - upd_by character varying(256), - upd_dtimes timestamp, - is_deleted boolean DEFAULT FALSE, - del_dtimes timestamp, - CONSTRAINT pk_anonymous_id PRIMARY KEY (id) -); --- ddl-end -- - diff --git a/db_release_scripts/mosip_regprc/ddl/regprc-crypto_salt.sql b/db_release_scripts/mosip_regprc/ddl/regprc-crypto_salt.sql deleted file mode 100644 index 0aceabc96cc..00000000000 --- a/db_release_scripts/mosip_regprc/ddl/regprc-crypto_salt.sql +++ /dev/null @@ -1,25 +0,0 @@ --- ------------------------------------------------------------------------------------------------- --- Database Name: mosip_regprc --- Table Name : regprc.crypto_salt --- Purpose : - --- Create By : Ram Bhatt --- Created Date : Jun-2021 --- --- Modified Date Modified By Comments / Remarks --- ------------------------------------------------------------------------------------------ - --- ------------------------------------------------------------------------------------------ - --- object: regprc.crypto_salt | type: TABLE -- --- DROP TABLE IF EXISTS regprc.crypto_salt CASCADE; -CREATE TABLE regprc.crypto_salt( - id integer NOT NULL, - salt character varying(36) NOT NULL, - cr_by character varying(256) NOT NULL, - cr_dtimes timestamp NOT NULL, - upd_by character varying(256) , - upd_dtimes timestamp , - CONSTRAINT pk_rides PRIMARY KEY (id)); --- ddl-end -- - diff --git a/db_release_scripts/mosip_regprc/ddl/regprc-reg_verification.sql b/db_release_scripts/mosip_regprc/ddl/regprc-reg_verification.sql deleted file mode 100644 index 7d0193fdb12..00000000000 --- a/db_release_scripts/mosip_regprc/ddl/regprc-reg_verification.sql +++ /dev/null @@ -1,33 +0,0 @@ --- ------------------------------------------------------------------------------------------------- --- Database Name: mosip_regprc --- Table Name : regprc.reg_manual_verification --- Purpose : Verification: Records marked for verification will be present in this table. --- Create By : Monobikash --- Created Date : Nov-2021 --- --- ------------------------------------------------------------------------------------------ --- --- ------------------------------------------------------------------------------------------ - --- object: regprc.reg_verification | type: TABLE -- --- DROP TABLE IF EXISTS regprc.reg_verification CASCADE; -CREATE TABLE regprc.reg_verification( - workflow_instance_id character varying(36) NOT NULL, - reg_id character varying(39) NOT NULL, - verification_req_id character varying(39) NOT NULL, - matched_type character varying(36), - verification_usr_id character varying(256), - response_text character varying(512), - status_code character varying(36), - reason_code character varying(36), - status_comment character varying(256), - is_active boolean NOT NULL, - cr_by character varying(256) NOT NULL, - cr_dtimes timestamp NOT NULL, - upd_by character varying(256), - upd_dtimes timestamp, - is_deleted boolean, - del_dtimes timestamp, - CONSTRAINT pk_reg_ver_id PRIMARY KEY (workflow_instance_id) -); --- ddl-end -- \ No newline at end of file diff --git a/db_release_scripts/mosip_regprc/dml/regprc-transaction_type.csv b/db_release_scripts/mosip_regprc/dml/regprc-transaction_type.csv deleted file mode 100644 index 9637e52692d..00000000000 --- a/db_release_scripts/mosip_regprc/dml/regprc-transaction_type.csv +++ /dev/null @@ -1,34 +0,0 @@ -code,descr,lang_code,is_active,cr_by,cr_dtimes -CREATE,transaction_done,eng,TRUE,MOSIP_SYSTEM,now() -DELETE,delete transaction,eng,TRUE,MOSIP_SYSTEM,now() -FAILED,transaction failed,eng,TRUE,MOSIP_SYSTEM,now() -UPDATE,transaction_done,eng,TRUE,MOSIP_SYSTEM,now() -DEMO,transaction_done,eng,TRUE,MOSIP_SYSTEM,now() -BIO,transaction_done,eng,TRUE,MOSIP_SYSTEM,now() -PACKET_RECEIVER,transaction done,eng,TRUE,MOSIP_SYSTEM,now() -UPLOAD_PACKET,transaction done,eng,TRUE,MOSIP_SYSTEM,now() -VALIDATE_PACKET,transaction done,eng,TRUE,MOSIP_SYSTEM,now() -VIRUS_SCAN,transaction done,eng,TRUE,MOSIP_SYSTEM,now() -OSI_VALIDATE,transaction done,eng,TRUE,MOSIP_SYSTEM,now() -EXTERNAL_INTEGRATION,transaction done,eng,TRUE,MOSIP_SYSTEM,now() -DEMOGRAPHIC_VERIFICATION,transaction done,eng,TRUE,MOSIP_SYSTEM,now() -VERIFICATION,transaction done,eng,TRUE,MOSIP_SYSTEM,now() -BIOGRAPHIC_VERIFICATION,transaction done,eng,TRUE,MOSIP_SYSTEM,now() -UIN_GENERATOR,transaction done,eng,TRUE,MOSIP_SYSTEM,now() -NOTIFICATION,transaction done,eng,TRUE,MOSIP_SYSTEM,now() -PRINT_SERVICE,transaction done,eng,TRUE,MOSIP_SYSTEM,now() -PRINT_POSTAL_SERVICE,transaction done,eng,TRUE,MOSIP_SYSTEM,now() -QUALITY_CLASSIFIER,transaction done,eng,TRUE,MOSIP_SYSTEM,now() -BIOMETRIC_AUTHENTICATION,transaction done,eng,TRUE,MOSIP_SYSTEM,now() -PACKET_REPROCESS,transcation done,eng,TRUE,MOSIP_SYSTEM,now() -SECUREZONE_NOTIFICATION,transaction notification,eng,TRUE,MOSIP_SYSTEM,now() -PACKET_CLASSIFICATION,transcation done,eng,TRUE,MOSIP_SYSTEM,now() -WORKFLOW_RESUME,transcation done,eng,TRUE,MOSIP_SYSTEM,now() -CMD_VALIDATION,transaction done,eng,TRUE,MOSIP_SYSTEM,now() -SUPERVISOR_VALIDATION,transaction done,eng,TRUE,MOSIP_SYSTEM,now() -OPERATOR_VALIDATION,transaction done,eng,TRUE,MOSIP_SYSTEM,now() -INTRODUCER_VALIDATION,transaction done,eng,TRUE,MOSIP_SYSTEM,now() -INTERNAL_WORKFLOW_ACTION,transaction done,eng,TRUE,MOSIP_SYSTEM,now() -BIOMETRIC_EXTRACTION,transaction done,eng,TRUE,MOSIP_SYSTEM,now() -FINALIZATION,transaction done,eng,TRUE,MOSIP_SYSTEM,now() -MANUAL_ADJUDICATION,transaction done,eng,TRUE,MOSIP_SYSTEM,now() diff --git a/db_release_scripts/mosip_regprc/mosip_regprc_release_db_deploy.sh b/db_release_scripts/mosip_regprc/mosip_regprc_release_db_deploy.sh deleted file mode 100644 index 208e74e589a..00000000000 --- a/db_release_scripts/mosip_regprc/mosip_regprc_release_db_deploy.sh +++ /dev/null @@ -1,92 +0,0 @@ -### -- --------------------------------------------------------------------------------------------------------- -### -- Script Name : Regprc Release DB deploy -### -- Deploy Module : MOSIP Regprc -### -- Purpose : To deploy Regprc Database alter scripts for the release. -### -- Create By : Sadanandegowda -### -- Created Date : 25-Oct-2019 -### -- -### -- Modified Date Modified By Comments / Remarks -### -- ----------------------------------------------------------------------------------------------------------- - -### -- ----------------------------------------------------------------------------------------------------------- - -#########Properties file ############# -set -e -properties_file="$1" -release_version="$2" - echo `date "+%m/%d/%Y %H:%M:%S"` ": Properties File Name - $properties_file" - echo `date "+%m/%d/%Y %H:%M:%S"` ": DB Deploymnet Version - $release_version" -#properties_file="./app.properties" -if [ -f "$properties_file" ] -then - echo `date "+%m/%d/%Y %H:%M:%S"` ": Property file \"$properties_file\" found." - while IFS='=' read -r key value - do - key=$(echo $key | tr '.' '_') - eval ${key}=\${value} - done < "$properties_file" -else - echo `date "+%m/%d/%Y %H:%M:%S"` ": Property file not found, Pass property file name as argument." -fi -echo `date "+%m/%d/%Y %H:%M:%S"` ": ------------------ Database server and service status check for ${MOSIP_DB_NAME}------------------------" - -today=`date '+%d%m%Y_%H%M%S'`; -LOG="${LOG_PATH}${MOSIP_DB_NAME}-release-${release_version}-${today}.log" -touch $LOG - -SERVICE=$(PGPASSWORD=$SU_USER_PWD psql --username=$SU_USER --host=$DB_SERVERIP --port=$DB_PORT --dbname=$DEFAULT_DB_NAME -t -c "select count(1) from pg_roles where rolname IN('sysadmin')";exit; > /dev/null) - -if [ "$SERVICE" -eq 0 ] || [ "$SERVICE" -eq 1 ] -then -echo `date "+%m/%d/%Y %H:%M:%S"` ": Postgres database server and service is up and running" | tee -a $LOG 2>&1 -else -echo `date "+%m/%d/%Y %H:%M:%S"` ": Postgres database server or service is not running" | tee -a $LOG 2>&1 -fi - -echo `date "+%m/%d/%Y %H:%M:%S"` ": ----------------------------------------------------------------------------------------" - -echo `date "+%m/%d/%Y %H:%M:%S"` ": Started sourcing the $MOSIP_DB_NAME Database Alter scripts" | tee -a $LOG 2>&1 - -echo `date "+%m/%d/%Y %H:%M:%S"` ": Database Alter scripts are sourcing from :$BASEPATH/$MOSIP_DB_NAME/" | tee -a $LOG 2>&1 - -#========================================DB Alter Scripts deployment process begins on IDMAP DB SERVER================================== - -echo `date "+%m/%d/%Y %H:%M:%S"` ": Alter scripts deployment on $MOSIP_DB_NAME database is started....Deployment Version...$release_version" | tee -a $LOG 2>&1 - -ALTER_SCRIPT_FILENAME_VERSION="sql/${release_version}_${ALTER_SCRIPT_FILENAME}" - -echo `date "+%m/%d/%Y %H:%M:%S"` ": Alter scripts file which is considered for release deployment - $ALTER_SCRIPT_FILENAME_VERSION" | tee -a $LOG 2>&1 - -cd /$BASEPATH/$MOSIP_DB_NAME/ - -pwd | tee -a $LOG 2>&1 - -CONN=$(PGPASSWORD=$SYSADMIN_PWD psql --username=$SYSADMIN_USER --host=$DB_SERVERIP --port=$DB_PORT --dbname=$DEFAULT_DB_NAME -t -c "SELECT count(pg_terminate_backend(pg_stat_activity.pid)) FROM pg_stat_activity WHERE datname = '$MOSIP_DB_NAME' AND pid <> pg_backend_pid()";exit; >> $LOG 2>&1) - -if [ ${CONN} == 0 ] -then - echo `date "+%m/%d/%Y %H:%M:%S"` ": No active database connections exist on ${MOSIP_DB_NAME}" | tee -a $LOG 2>&1 -else - echo `date "+%m/%d/%Y %H:%M:%S"` ": Active connections exist on the database server and active connection will be terminated for DB deployment." | tee -a $LOG 2>&1 -fi - -if [ ${ALTER_SCRIPT_FLAG} == 1 ] -then - echo `date "+%m/%d/%Y %H:%M:%S"` ": Deploying Alter scripts for ${MOSIP_DB_NAME} database" | tee -a $LOG 2>&1 - PGPASSWORD=$SYSADMIN_PWD psql --username=$SYSADMIN_USER --host=$DB_SERVERIP --port=$DB_PORT --dbname=$DEFAULT_DB_NAME -a -b -f $ALTER_SCRIPT_FILENAME_VERSION >> $LOG 2>&1 -else - echo `date "+%m/%d/%Y %H:%M:%S"` ": There are no alter scripts available for this deployment at ${MOSIP_DB_NAME}" | tee -a $LOG 2>&1 -fi - -if [ $(grep -c ERROR $LOG) -ne 0 ] -then - echo `date "+%m/%d/%Y %H:%M:%S"` ": Database Alter scripts deployment version $release_version is completed with ERRORS, Please check the logs for more information" | tee -a $LOG 2>&1 - echo `date "+%m/%d/%Y %H:%M:%S"` ": END of Alter scripts MOSIP database deployment" | tee -a $LOG 2>&1 -else - echo `date "+%m/%d/%Y %H:%M:%S"` ": Database Alter scripts deployment version $release_version completed successfully, Please check the logs for more information" | tee -a $LOG 2>&1 - echo `date "+%m/%d/%Y %H:%M:%S"` ": END of MOSIP \"${MOSIP_DB_NAME}\" database alter scripts deployment" | tee -a $LOG 2>&1 -fi - -echo "******************************************"`date "+%m/%d/%Y %H:%M:%S"` "*****************************************************" >> $LOG 2>&1 - - diff --git a/db_release_scripts/mosip_regprc/mosip_regprc_release_deploy.properties b/db_release_scripts/mosip_regprc/mosip_regprc_release_deploy.properties deleted file mode 100644 index ef632c3b0de..00000000000 --- a/db_release_scripts/mosip_regprc/mosip_regprc_release_deploy.properties +++ /dev/null @@ -1,14 +0,0 @@ -DB_SERVERIP= -DB_PORT=9001 -SU_USER=postgres -SU_USER_PWD= -DEFAULT_DB_NAME=postgres -MOSIP_DB_NAME=mosip_regprc -SYSADMIN_USER=sysadmin -SYSADMIN_PWD= -BASEPATH=/home/madmin/database_release -LOG_PATH=/home/madmin/logs/ -ALTER_SCRIPT_FLAG=1 -ALTER_SCRIPT_FILENAME=regprc-scripts_release.sql -REVOKE_SCRIPT_FLAG=1 -REVOKE_SCRIPT_FILENAME=regprc-scripts_revoke.sql diff --git a/db_release_scripts/mosip_regprc/mosip_regprc_revoke_db_deploy.sh b/db_release_scripts/mosip_regprc/mosip_regprc_revoke_db_deploy.sh deleted file mode 100644 index 406088db04e..00000000000 --- a/db_release_scripts/mosip_regprc/mosip_regprc_revoke_db_deploy.sh +++ /dev/null @@ -1,92 +0,0 @@ -### -- --------------------------------------------------------------------------------------------------------- -### -- Script Name : Regprc Revoke DB deploy -### -- Deploy Module : MOSIP Regprc -### -- Purpose : To revoke Regprc Database alter scripts for the release. -### -- Create By : Sadanandegowda -### -- Created Date : 25-Oct-2019 -### -- -### -- Modified Date Modified By Comments / Remarks -### -- ----------------------------------------------------------------------------------------------------------- - -### -- ----------------------------------------------------------------------------------------------------------- - -#########Properties file ############# -set -e -properties_file="$1" -revoke_version="$2" - echo `date "+%m/%d/%Y %H:%M:%S"` ": $properties_file" - echo `date "+%m/%d/%Y %H:%M:%S"` ": DB Revoke Version - $revoke_version" -#properties_file="./app.properties" -if [ -f "$properties_file" ] -then - echo `date "+%m/%d/%Y %H:%M:%S"` ": Property file \"$properties_file\" found." - while IFS='=' read -r key value - do - key=$(echo $key | tr '.' '_') - eval ${key}=\${value} - done < "$properties_file" -else - echo `date "+%m/%d/%Y %H:%M:%S"` ": Property file not found, Pass property file name as argument." -fi -echo `date "+%m/%d/%Y %H:%M:%S"` ": ------------------ Database server and service status check for ${MOSIP_DB_NAME}------------------------" - -today=`date '+%d%m%Y_%H%M%S'`; -LOG="${LOG_PATH}${MOSIP_DB_NAME}-revoke-${today}.log" -touch $LOG - -SERVICE=$(PGPASSWORD=$SU_USER_PWD psql --username=$SU_USER --host=$DB_SERVERIP --port=$DB_PORT --dbname=$DEFAULT_DB_NAME -t -c "select count(1) from pg_roles where rolname IN('sysadmin')";exit; > /dev/null) - -if [ "$SERVICE" -eq 0 ] || [ "$SERVICE" -eq 1 ] -then -echo `date "+%m/%d/%Y %H:%M:%S"` ": Postgres database server and service is up and running" | tee -a $LOG 2>&1 -else -echo `date "+%m/%d/%Y %H:%M:%S"` ": Postgres database server or service is not running" | tee -a $LOG 2>&1 -fi - -echo `date "+%m/%d/%Y %H:%M:%S"` ": ----------------------------------------------------------------------------------------" - -echo `date "+%m/%d/%Y %H:%M:%S"` ": Started sourcing the $MOSIP_DB_NAME Database Deployment Revoke scripts" | tee -a $LOG 2>&1 - -echo `date "+%m/%d/%Y %H:%M:%S"` ": Database revoke scripts are sourcing from :$BASEPATH/$MOSIP_DB_NAME/alter-scripts" | tee -a $LOG 2>&1 - -#========================================DB Alter Scripts deployment process begins on IDMAP DB SERVER================================== - -echo `date "+%m/%d/%Y %H:%M:%S"` ": Revoke scripts for DB deployment on $MOSIP_DB_NAME database is started....Revoke Version...$revoke_version" | tee -a $LOG 2>&1 - -REVOKE_SCRIPT_FILENAME_VERSION="sql/${revoke_version}_${REVOKE_SCRIPT_FILENAME}" - -echo `date "+%m/%d/%Y %H:%M:%S"` ": Alter scripts file which is considered for deployment revoke - $REVOKE_SCRIPT_FILENAME_VERSION" | tee -a $LOG 2>&1 - -cd /$BASEPATH/$MOSIP_DB_NAME/ - -pwd | tee -a $LOG 2>&1 - -CONN=$(PGPASSWORD=$SYSADMIN_PWD psql --username=$SYSADMIN_USER --host=$DB_SERVERIP --port=$DB_PORT --dbname=$DEFAULT_DB_NAME -t -c "SELECT count(pg_terminate_backend(pg_stat_activity.pid)) FROM pg_stat_activity WHERE datname = '$MOSIP_DB_NAME' AND pid <> pg_backend_pid()";exit; >> $LOG 2>&1) - -if [ ${CONN} == 0 ] -then - echo `date "+%m/%d/%Y %H:%M:%S"` ": No active database connections exist on ${MOSIP_DB_NAME}" | tee -a $LOG 2>&1 -else - echo `date "+%m/%d/%Y %H:%M:%S"` ": Active connections exist on the database server and active connection will be terminated for DB deployment." | tee -a $LOG 2>&1 -fi - -if [ ${REVOKE_SCRIPT_FLAG} == 1 ] -then - echo `date "+%m/%d/%Y %H:%M:%S"` ": Executing revoke scripts for ${MOSIP_DB_NAME} database" | tee -a $LOG 2>&1 - PGPASSWORD=$SYSADMIN_PWD psql --username=$SYSADMIN_USER --host=$DB_SERVERIP --port=$DB_PORT --dbname=$DEFAULT_DB_NAME -a -b -f $REVOKE_SCRIPT_FILENAME_VERSION >> $LOG 2>&1 -else - echo `date "+%m/%d/%Y %H:%M:%S"` ": There are no revoke scripts available for this deployment at ${MOSIP_DB_NAME}" | tee -a $LOG 2>&1 -fi - -if [ $(grep -c ERROR $LOG) -ne 0 ] -then - echo `date "+%m/%d/%Y %H:%M:%S"` ": Database deployment revoke version $revoke_version is completed with ERRORS, Please check the logs for more information" | tee -a $LOG 2>&1 - echo `date "+%m/%d/%Y %H:%M:%S"` ": END of Alter scripts MOSIP database deployment" | tee -a $LOG 2>&1 -else - echo `date "+%m/%d/%Y %H:%M:%S"` ": Database deployment revoke version $revoke_version completed successfully, Please check the logs for more information" | tee -a $LOG 2>&1 - echo `date "+%m/%d/%Y %H:%M:%S"` ": END of MOSIP \"${MOSIP_DB_NAME}\" database deployment revoke" | tee -a $LOG 2>&1 -fi - -echo "******************************************"`date "+%m/%d/%Y %H:%M:%S"` "*****************************************************" >> $LOG 2>&1 - - diff --git a/db_release_scripts/mosip_regprc/sql/1.1.4_regprc-scripts_release.sql b/db_release_scripts/mosip_regprc/sql/1.1.4_regprc-scripts_release.sql deleted file mode 100644 index 6279fefa2aa..00000000000 --- a/db_release_scripts/mosip_regprc/sql/1.1.4_regprc-scripts_release.sql +++ /dev/null @@ -1,21 +0,0 @@ --- ------------------------------------------------------------------------------------------------- --- Database Name: mosip_regprc --- Release Version : 1.1.4 --- Purpose : Database Alter scripts for the release for Registration Processor DB. --- Create By : Sadanandegowda DM --- Created Date : Dec-2020 --- --- Modified Date Modified By Comments / Remarks --- ------------------------------------------------------------------------------------------------- - -\c mosip_regprc sysadmin - -ALTER TABLE regprc.reg_manual_verification DROP COLUMN IF EXISTS matched_score; - -ALTER TABLE regprc.reg_manual_verification ADD COLUMN IF NOT EXISTS ref_regtrn_id character varying(36); - -ALTER TABLE regprc.reg_manual_verification ADD COLUMN IF NOT EXISTS request_id character varying(36); - -ALTER TABLE regprc.reg_manual_verification ADD COLUMN IF NOT EXISTS res_text bytea; - ----------------------------------------------------------------------------------------------------- \ No newline at end of file diff --git a/db_release_scripts/mosip_regprc/sql/1.1.4_regprc-scripts_revoke.sql b/db_release_scripts/mosip_regprc/sql/1.1.4_regprc-scripts_revoke.sql deleted file mode 100644 index de1d86384f9..00000000000 --- a/db_release_scripts/mosip_regprc/sql/1.1.4_regprc-scripts_revoke.sql +++ /dev/null @@ -1,19 +0,0 @@ --- ------------------------------------------------------------------------------------------------- --- Database Name: mosip_regprc --- Release Version : 1.1.4 --- Purpose : Revoking Database Alter deployement done for release in Registration ProcessorDB. --- Create By : Sadanandegowda DM --- Created Date : Dec-2020 --- --- Modified Date Modified By Comments / Remarks --- ------------------------------------------------------------------------------------------------- - -\c mosip_regprc sysadmin - -ALTER TABLE regprc.reg_manual_verification DROP COLUMN IF EXISTS ref_regtrn_id; - -ALTER TABLE regprc.reg_manual_verification DROP COLUMN IF EXISTS request_id; - -ALTER TABLE regprc.reg_manual_verification DROP COLUMN IF EXISTS res_text; - ----------------------------------------------------------------------------------------------------- \ No newline at end of file diff --git a/db_release_scripts/mosip_regprc/sql/1.1.5_regprc-scripts_release.sql b/db_release_scripts/mosip_regprc/sql/1.1.5_regprc-scripts_release.sql deleted file mode 100644 index 89fa3f3283e..00000000000 --- a/db_release_scripts/mosip_regprc/sql/1.1.5_regprc-scripts_release.sql +++ /dev/null @@ -1,23 +0,0 @@ --- ------------------------------------------------------------------------------------------------- --- Database Name: mosip_regprc --- Release Version : 1.1.5 --- Purpose : Database Alter scripts for the release for Registration Processor DB. --- Created By : Ram Bhatt --- Created Date : Jan-2021 --- --- Modified Date Modified By Comments / Remarks --- ------------------------------------------------------------------------------------------------- --- Mar-2021 Ram Bhatt Reverting is_deleted not null changes for 1.1.5 --- Apr-2021 Ram Bhatt Packet Classification dml Changes ----------------------------------------------------------------------------------------------------- - -\c mosip_regprc sysadmin - -TRUNCATE TABLE regprc.transaction_type cascade ; - -\COPY regprc.transaction_type (code,descr,lang_code,is_active,cr_by,cr_dtimes) FROM '../dml/regprc-transaction_type.csv' delimiter ',' HEADER csv; - -ALTER TABLE regprc.reg_manual_verification ADD COLUMN res_text bytea; - - ----------------------------------------------------------------------------------------------------- diff --git a/db_release_scripts/mosip_regprc/sql/1.1.5_regprc-scripts_revoke.sql b/db_release_scripts/mosip_regprc/sql/1.1.5_regprc-scripts_revoke.sql deleted file mode 100644 index 87b757f1f3c..00000000000 --- a/db_release_scripts/mosip_regprc/sql/1.1.5_regprc-scripts_revoke.sql +++ /dev/null @@ -1,16 +0,0 @@ --- ------------------------------------------------------------------------------------------------- --- Database Name: mosip_regprc --- Release Version : 1.1.5 --- Purpose : Revoking Database Alter deployement done for release in Registration ProcessorDB. --- Create By : Ram Bhatt --- Created Date : Jan-2021 --- --- Modified Date Modified By Comments / Remarks --- ------------------------------------------------------------------------------------------------- - -\c mosip_regprc sysadmin - - -ALTER TABLE regprc.reg_manual_verification DROP COLUMN res_text; - ----------------------------------------------------------------------------------------------------- diff --git a/db_release_scripts/mosip_regprc/sql/1.2_regprc-scripts_revoke.sql b/db_release_scripts/mosip_regprc/sql/1.2_regprc-scripts_revoke.sql deleted file mode 100644 index dc1f093e3bd..00000000000 --- a/db_release_scripts/mosip_regprc/sql/1.2_regprc-scripts_revoke.sql +++ /dev/null @@ -1,20 +0,0 @@ --- ------------------------------------------------------------------------------------------------- --- Database Name: mosip_regprc --- Release Version : 1.2 --- Purpose : Revoking Database Alter deployement done for release in Registration ProcessorDB. --- Create By : Ram Bhatt --- Created Date : Mar-2021 --- --- Modified Date Modified By Comments / Remarks --- ------------------------------------------------------------------------------------------------- --- Apr-2021 Ram Bhatt Added resume_remove_tags column to registration table ------------------------------------------------------------------------------------------------------ - -\c mosip_regprc sysadmin - -ALTER TABLE regprc.registration DROP COLUMN IF EXISTS resume_timestamp; -ALTER TABLE regprc.registration DROP COLUMN IF EXISTS default_resume_action; - --------------------------------------------------------------------------------------------- -ALTER TABLE regprc.registration DROP COLUMN IF EXISTS resume_remove_tags; ----------------------------------------------------------------------------------------------------- diff --git a/db_scripts/mosip_regprc/ddl/regprc-reg_bio_ref.sql b/db_scripts/mosip_regprc/ddl/regprc-reg_bio_ref.sql index 1003ede660e..cbc4ef41cac 100644 --- a/db_scripts/mosip_regprc/ddl/regprc-reg_bio_ref.sql +++ b/db_scripts/mosip_regprc/ddl/regprc-reg_bio_ref.sql @@ -13,7 +13,6 @@ CREATE TABLE regprc.reg_bio_ref( is_deleted boolean DEFAULT FALSE, del_dtimes timestamp, workflow_instance_id character varying(36) NOT NULL, - source character varying, process character varying, iteration integer DEFAULT 1, CONSTRAINT pk_regbref_id PRIMARY KEY (bio_ref_id,workflow_instance_id) diff --git a/db_scripts/mosip_regprc/deploy.sh b/db_scripts/mosip_regprc/deploy.sh index 38299d594af..ecef78c3a83 100644 --- a/db_scripts/mosip_regprc/deploy.sh +++ b/db_scripts/mosip_regprc/deploy.sh @@ -22,27 +22,26 @@ echo "Terminated connections" ## Drop db and role echo "Dropping DB" -PGPASSWORD=$SU_USER_PWD psql -v ON_ERROR_STOP=1 --username=$SU_USER --host=$DB_SERVERIP --port=$DB_PORT --dbname=$DEFAULT_DB_NAME -f drop_db.sql - +PGPASSWORD=$SU_USER_PWD psql -v ON_ERROR_STOP=1 --username=$SU_USER --host=$DB_SERVERIP --port=$DB_PORT --dbname=$DEFAULT_DB_NAME -f drop_db.sql echo "Dropping user" -PGPASSWORD=$SU_USER_PWD psql -v ON_ERROR_STOP=1 --username=$SU_USER --host=$DB_SERVERIP --port=$DB_PORT --dbname=$DEFAULT_DB_NAME -f drop_role.sql +PGPASSWORD=$SU_USER_PWD psql -v ON_ERROR_STOP=1 --username=$SU_USER --host=$DB_SERVERIP --port=$DB_PORT --dbname=$DEFAULT_DB_NAME -f drop_role.sql ## Create users echo `date "+%m/%d/%Y %H:%M:%S"` ": Creating database users" -PGPASSWORD=$SU_USER_PWD psql -v ON_ERROR_STOP=1 --username=$SU_USER --host=$DB_SERVERIP --port=$DB_PORT --dbname=$DEFAULT_DB_NAME -f role_dbuser.sql -v dbuserpwd=\'$DBUSER_PWD\' +PGPASSWORD=$SU_USER_PWD psql -v ON_ERROR_STOP=1 --username=$SU_USER --host=$DB_SERVERIP --port=$DB_PORT --dbname=$DEFAULT_DB_NAME -f role_dbuser.sql -v dbuserpwd=\'$DBUSER_PWD\' ## Create DB echo "Creating DB" -PGPASSWORD=$SU_USER_PWD psql -v ON_ERROR_STOP=1 --username=$SU_USER --host=$DB_SERVERIP --port=$DB_PORT --dbname=$DEFAULT_DB_NAME -f db.sql -PGPASSWORD=$SU_USER_PWD psql -v ON_ERROR_STOP=1 --username=$SU_USER --host=$DB_SERVERIP --port=$DB_PORT --dbname=$DEFAULT_DB_NAME -f ddl.sql +PGPASSWORD=$SU_USER_PWD psql -v ON_ERROR_STOP=1 --username=$SU_USER --host=$DB_SERVERIP --port=$DB_PORT --dbname=$DEFAULT_DB_NAME -f db.sql +PGPASSWORD=$SU_USER_PWD psql -v ON_ERROR_STOP=1 --username=$SU_USER --host=$DB_SERVERIP --port=$DB_PORT --dbname=$DEFAULT_DB_NAME -f ddl.sql ## Grants -PGPASSWORD=$SU_USER_PWD psql -v ON_ERROR_STOP=1 --username=$SU_USER --host=$DB_SERVERIP --port=$DB_PORT --dbname=$DEFAULT_DB_NAME -f grants.sql +PGPASSWORD=$SU_USER_PWD psql -v ON_ERROR_STOP=1 --username=$SU_USER --host=$DB_SERVERIP --port=$DB_PORT --dbname=$DEFAULT_DB_NAME -f grants.sql ## Populate tables if [ ${DML_FLAG} == 1 ] then echo `date "+%m/%d/%Y %H:%M:%S"` ": Deploying DML for ${MOSIP_DB_NAME} database" - PGPASSWORD=$SU_USER_PWD psql -v ON_ERROR_STOP=1 --username=$SU_USER --host=$DB_SERVERIP --port=$DB_PORT --dbname=$DEFAULT_DB_NAME -a -b -f dml.sql + PGPASSWORD=$SU_USER_PWD psql -v ON_ERROR_STOP=1 --username=$SU_USER --host=$DB_SERVERIP --port=$DB_PORT --dbname=$DEFAULT_DB_NAME -a -b -f dml.sql fi diff --git a/db_scripts/mosip_regprc/dml.sql b/db_scripts/mosip_regprc/dml.sql index 76782056184..a5db8cdbe70 100644 --- a/db_scripts/mosip_regprc/dml.sql +++ b/db_scripts/mosip_regprc/dml.sql @@ -1,21 +1,3 @@ \c mosip_regprc - +TRUNCATE TABLE regprc.transaction_type cascade ; \COPY regprc.transaction_type (code,descr,lang_code,is_active,cr_by,cr_dtimes) FROM './dml/regprc-transaction_type.csv' delimiter ',' HEADER csv; - - - - - - - - - - - - - - - - - - diff --git a/db_scripts/mosip_regprc/dml/regprc-transaction_type.csv b/db_scripts/mosip_regprc/dml/regprc-transaction_type.csv index 9637e52692d..1d55586a892 100644 --- a/db_scripts/mosip_regprc/dml/regprc-transaction_type.csv +++ b/db_scripts/mosip_regprc/dml/regprc-transaction_type.csv @@ -32,3 +32,4 @@ INTERNAL_WORKFLOW_ACTION,transaction done,eng,TRUE,MOSIP_SYSTEM,now() BIOMETRIC_EXTRACTION,transaction done,eng,TRUE,MOSIP_SYSTEM,now() FINALIZATION,transaction done,eng,TRUE,MOSIP_SYSTEM,now() MANUAL_ADJUDICATION,transaction done,eng,TRUE,MOSIP_SYSTEM,now() +MANUAL_VERIFICATION,transaction done,eng,TRUE,MOSIP_SYSTEM,now() diff --git a/db_release_scripts/README.MD b/db_upgrade_scripts/README.MD similarity index 100% rename from db_release_scripts/README.MD rename to db_upgrade_scripts/README.MD diff --git a/db_upgrade_scripts/mosip_regprc/sql/1.1.5.5_to_1.2.0.1-B1_rollback.sql b/db_upgrade_scripts/mosip_regprc/sql/1.1.5.5_to_1.2.0.1-B1_rollback.sql new file mode 100644 index 00000000000..f0efae48dcd --- /dev/null +++ b/db_upgrade_scripts/mosip_regprc/sql/1.1.5.5_to_1.2.0.1-B1_rollback.sql @@ -0,0 +1,119 @@ +\c mosip_regprc + +REASSIGN OWNED BY postgres TO sysadmin; + +GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA regprc TO sysadmin; + +ALTER TABLE regprc.individual_demographic_dedup DROP CONSTRAINT IF EXISTS fk_idemogd_reg CASCADE; +ALTER TABLE regprc.reg_manual_verification DROP CONSTRAINT IF EXISTS fk_rmnlver_reg CASCADE; +ALTER TABLE regprc.reg_bio_ref DROP CONSTRAINT IF EXISTS fk_regref_reg CASCADE; +ALTER TABLE regprc.reg_lost_uin_det DROP CONSTRAINT IF EXISTS fk_rlostd_reg CASCADE; +ALTER TABLE regprc.registration_transaction DROP CONSTRAINT IF EXISTS fk_regtrn_reg CASCADE; + +DROP TABLE IF EXISTS regprc.additional_info_request CASCADE; +DROP TABLE IF EXISTS regprc.anonymous_profile CASCADE; +DROP TABLE IF EXISTS regprc.crypto_salt CASCADE; +DROP TABLE IF EXISTS regprc.reg_verification CASCADE; + +ALTER TABLE regprc.registration_list RENAME COLUMN workflow_instance_id TO id; +ALTER TABLE regprc.registration_list RENAME COLUMN process TO reg_type; +ALTER TABLE regprc.registration_list DROP COLUMN IF EXISTS additional_info_req_id; +ALTER TABLE regprc.registration_list DROP COLUMN IF EXISTS packet_id; +ALTER TABLE regprc.registration_list DROP COLUMN IF EXISTS source; +ALTER TABLE regprc.registration_list DROP COLUMN IF EXISTS ref_id; + +ALTER TABLE regprc.individual_demographic_dedup DROP COLUMN IF EXISTS workflow_instance_id; +ALTER TABLE regprc.individual_demographic_dedup DROP COLUMN IF EXISTS process; +ALTER TABLE regprc.individual_demographic_dedup DROP COLUMN IF EXISTS iteration; + +ALTER TABLE regprc.reg_manual_verification DROP COLUMN IF EXISTS workflow_instance_id; + +ALTER TABLE regprc.reg_lost_uin_det DROP COLUMN IF EXISTS workflow_instance_id; + +ALTER TABLE regprc.reg_bio_ref DROP COLUMN IF EXISTS workflow_instance_id; +ALTER TABLE regprc.reg_bio_ref DROP COLUMN IF EXISTS process; +ALTER TABLE regprc.reg_bio_ref DROP COLUMN IF EXISTS iteration; + +ALTER TABLE regprc.registration RENAME COLUMN reg_id TO id; +ALTER TABLE regprc.registration RENAME COLUMN process TO reg_type; +ALTER TABLE regprc.registration DROP COLUMN IF EXISTS workflow_instance_id; +ALTER TABLE regprc.registration DROP COLUMN IF EXISTS source; +ALTER TABLE regprc.registration DROP COLUMN IF EXISTS iteration; + +DROP INDEX IF EXISTS idx_rbioref_crdtimes; +DROP INDEX IF EXISTS idx_bio_ref_id; +DROP INDEX IF EXISTS idx_idemogd_namedobgender; +DROP INDEX IF EXISTS idx_rbioref_crdtimes; +DROP INDEX IF EXISTS idx_rmanvrn_reqid; +DROP INDEX IF EXISTS idx_rgstrn_ltstrbcode_ltststscode; +DROP INDEX IF EXISTS idx_reg_latest_trn_dtimes; +DROP INDEX IF EXISTS idx_rgstrnlst_pcktid; +DROP INDEX IF EXISTS idx_rgstrnlst_aireqid; +DROP INDEX IF EXISTS idx_reg_verification_reqId; +DROP INDEX IF EXISTS idx_reg_trn_reg_id; +DROP INDEX IF EXISTS idx_reg_trn_status_code; +DROP INDEX IF EXISTS idx_reg_trn_trntypecode; +DROP INDEX IF EXISTS idx_reg_trn_upd_dtimes; +DROP INDEX IF EXISTS idx_user_detail_cntr_id; +DROP INDEX IF EXISTS idx_abis_req_regtrn_id; + +ALTER TABLE regprc.individual_demographic_dedup DROP CONSTRAINT IF EXISTS pk_idemogd_id; +ALTER TABLE regprc.individual_demographic_dedup ALTER COLUMN reg_id SET NOT NULL; +ALTER TABLE regprc.individual_demographic_dedup ADD CONSTRAINT pk_idemogd_id PRIMARY KEY (reg_id,lang_code); + +ALTER TABLE regprc.reg_bio_ref DROP CONSTRAINT IF EXISTS pk_regbref_id; +ALTER TABLE regprc.reg_bio_ref ALTER COLUMN reg_id SET NOT NULL; +ALTER TABLE regprc.reg_bio_ref ADD CONSTRAINT pk_regbref_id PRIMARY KEY (reg_id); + +ALTER TABLE regprc.reg_lost_uin_det DROP CONSTRAINT IF EXISTS pk_rlostd; +ALTER TABLE regprc.reg_lost_uin_det ALTER COLUMN reg_id SET NOT NULL; +ALTER TABLE regprc.reg_lost_uin_det ADD CONSTRAINT pk_rlostd PRIMARY KEY (reg_id); + +ALTER TABLE regprc.reg_manual_verification DROP CONSTRAINT IF EXISTS pk_rmnlver_id; +ALTER TABLE regprc.reg_manual_verification ALTER COLUMN reg_id SET NOT NULL; +ALTER TABLE regprc.reg_manual_verification ADD CONSTRAINT pk_rmnlver_id PRIMARY KEY (reg_id,matched_ref_id,matched_ref_type); + +ALTER TABLE regprc.registration DROP CONSTRAINT IF EXISTS pk_reg_id CASCADE; +ALTER TABLE regprc.registration ALTER COLUMN id SET NOT NULL; +ALTER TABLE regprc.registration ADD CONSTRAINT pk_reg_id PRIMARY KEY (id); + +ALTER TABLE regprc.individual_demographic_dedup ADD CONSTRAINT fk_idemogd_reg FOREIGN KEY (reg_id) +REFERENCES regprc.registration (id) MATCH SIMPLE +ON DELETE NO ACTION ON UPDATE NO ACTION; + +ALTER TABLE regprc.reg_manual_verification ADD CONSTRAINT fk_rmnlver_reg FOREIGN KEY (reg_id) +REFERENCES regprc.registration (id) MATCH SIMPLE +ON DELETE NO ACTION ON UPDATE NO ACTION; + +ALTER TABLE regprc.reg_bio_ref ADD CONSTRAINT fk_regbrf_reg FOREIGN KEY (reg_id) +REFERENCES regprc.registration (id) MATCH SIMPLE +ON DELETE NO ACTION ON UPDATE NO ACTION; + +ALTER TABLE regprc.reg_lost_uin_det ADD CONSTRAINT fk_rlostd_reg FOREIGN KEY (reg_id) +REFERENCES regprc.registration (id) MATCH SIMPLE +ON DELETE NO ACTION ON UPDATE NO ACTION; + +ALTER TABLE regprc.registration DROP COLUMN IF EXISTS resume_timestamp; +ALTER TABLE regprc.registration DROP COLUMN IF EXISTS default_resume_action; +ALTER TABLE regprc.registration DROP COLUMN IF EXISTS pause_rule_ids; +ALTER TABLE regprc.registration DROP COLUMN IF EXISTS last_success_stage_name; +-------------------------------------------------------drop columns to registration_list---------------------------------------------- + +ALTER TABLE regprc.registration_list DROP COLUMN IF EXISTS name; +ALTER TABLE regprc.registration_list DROP COLUMN IF EXISTS phone; +ALTER TABLE regprc.registration_list DROP COLUMN IF EXISTS email; +ALTER TABLE regprc.registration_list DROP COLUMN IF EXISTS center_id; +ALTER TABLE regprc.registration_list DROP COLUMN IF EXISTS registration_date; +ALTER TABLE regprc.registration_list DROP COLUMN IF EXISTS location_code; + +---------------------delete scripts keep always last if it throws error need to handle it manually-------------------------------------- +DELETE from regprc.transaction_type where code='VERIFICATION'; +DELETE from regprc.transaction_type where code='QUALITY_CLASSIFIER'; +DELETE from regprc.transaction_type where code='WORKFLOW_RESUME'; +DELETE from regprc.transaction_type where code='CMD_VALIDATION'; +DELETE from regprc.transaction_type where code='SUPERVISOR_VALIDATION'; +DELETE from regprc.transaction_type where code='OPERATOR_VALIDATION'; +DELETE from regprc.transaction_type where code='INTRODUCER_VALIDATION'; +DELETE from regprc.transaction_type where code='BIOMETRIC_EXTRACTION'; +DELETE from regprc.transaction_type where code='FINALIZATION'; +DELETE from regprc.transaction_type where code='MANUAL_ADJUDICATION'; \ No newline at end of file diff --git a/db_release_scripts/mosip_regprc/sql/1.2_regprc-scripts_release.sql b/db_upgrade_scripts/mosip_regprc/sql/1.1.5.5_to_1.2.0.1-B1_upgrade.sql similarity index 85% rename from db_release_scripts/mosip_regprc/sql/1.2_regprc-scripts_release.sql rename to db_upgrade_scripts/mosip_regprc/sql/1.1.5.5_to_1.2.0.1-B1_upgrade.sql index 872697386c5..0698a379f3e 100644 --- a/db_release_scripts/mosip_regprc/sql/1.2_regprc-scripts_release.sql +++ b/db_upgrade_scripts/mosip_regprc/sql/1.1.5.5_to_1.2.0.1-B1_upgrade.sql @@ -1,26 +1,14 @@ --- ------------------------------------------------------------------------------------------------- --- Database Name: mosip_regprc --- Release Version : 1.2 --- Purpose : Database Alter scripts for the release for Registration Processor DB. --- Create By : Ram Bhatt --- Created Date : Mar-2021 --- --- Modified Date Modified By Comments / Remarks --- ------------------------------------------------------------------------------------------------- --- Apr-2021 Ram Bhatt Added resume_remove_tags column to registration table --- Apr-2021 Ram Bhatt Added rows to transaction_type.csv --- May-2021 Ram Bhatt Creation of last_success_stage_name in registration table --- Jun-2021 Ram Bhatt Added rows to transaction_type.csv --- Jun-2021 Ram Bhatt Added columns to registration list table --- Jun-2021 Ram Bhatt Create crypto salt table. --- July-2021 Ram Bhatt Added rows to transaction_type.csv --- Jul-2021 Ram Bhatt Multiple table changes on regprc db --- Aug-2021 Ram Bhatt Remove resume_remove_tags column from registration table --- Aug-2021 Ram Bhatt Added pause_rule_ids column to registration table --- Sep-2021 Ram Bhatt Anonymous profile table creation --- Apr-2022 JyotiPrakashNayak Removed column 'reg_type' and added 'process' ----------------------------------------------------------------------------------------------------- -\c mosip_regprc sysadmin +\c mosip_regprc + +REASSIGN OWNED BY sysadmin TO postgres; + +REVOKE ALL PRIVILEGES ON ALL TABLES IN SCHEMA regprc FROM regprcuser; + +REVOKE ALL PRIVILEGES ON ALL TABLES IN SCHEMA regprc FROM sysadmin; + +GRANT SELECT, INSERT, TRUNCATE, REFERENCES, UPDATE, DELETE ON ALL TABLES IN SCHEMA regprc TO regprcuser; + +GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA regprc TO postgres; ----------------------------------------------Multiple table level changes on regprc db------------------------------------------------------- @@ -30,17 +18,67 @@ ALTER TABLE regprc.reg_bio_ref DROP CONSTRAINT IF EXISTS fk_regref_reg CASCADE; ALTER TABLE regprc.reg_lost_uin_det DROP CONSTRAINT IF EXISTS fk_rlostd_reg CASCADE; ALTER TABLE regprc.registration_transaction DROP CONSTRAINT IF EXISTS fk_regtrn_reg CASCADE; -\ir ../ddl/regprc-additional_info_request.sql - -\ir ../ddl/regprc-anonymous_profile.sql - -\ir ../ddl/regprc-reg_verification.sql +CREATE TABLE regprc.additional_info_request( + additional_info_process character varying(64), + reg_id character varying(39), + workflow_instance_id character varying(36), + timestamp timestamp, + additional_info_iteration integer, + additional_info_req_id character varying(256), + CONSTRAINT pk_addl_info_req PRIMARY KEY (workflow_instance_id , additional_info_req_id) + +); + +GRANT SELECT, INSERT, TRUNCATE, REFERENCES, UPDATE, DELETE + ON regprc.additional_info_request + TO regprcuser; + +CREATE TABLE regprc.anonymous_profile( + id character varying(39) NOT NULL, + process_stage character varying(36) NOT NULL, + profile character varying NOT NULL, + cr_by character varying(256) NOT NULL, + cr_dtimes timestamp NOT NULL, + upd_by character varying(256), + upd_dtimes timestamp, + is_deleted boolean DEFAULT FALSE, + del_dtimes timestamp, + CONSTRAINT pk_anonymous_id PRIMARY KEY (id) +); +GRANT SELECT, INSERT, TRUNCATE, REFERENCES, UPDATE, DELETE + ON regprc.anonymous_profile + TO regprcuser; + +CREATE TABLE regprc.reg_verification( + workflow_instance_id character varying(36) NOT NULL, + reg_id character varying(39) NOT NULL, + verification_req_id character varying(39) NOT NULL, + matched_type character varying(36), + verification_usr_id character varying(256), + response_text character varying(512), + status_code character varying(36), + reason_code character varying(36), + status_comment character varying(256), + is_active boolean NOT NULL, + cr_by character varying(256) NOT NULL, + cr_dtimes timestamp NOT NULL, + upd_by character varying(256), + upd_dtimes timestamp, + is_deleted boolean, + del_dtimes timestamp, + CONSTRAINT pk_reg_ver_id PRIMARY KEY (workflow_instance_id) +); + +GRANT SELECT, INSERT, TRUNCATE, REFERENCES, UPDATE, DELETE + ON regprc.reg_verification + TO regprcuser; ALTER TABLE regprc.registration_list RENAME COLUMN id TO workflow_instance_id; ALTER TABLE regprc.registration_list RENAME COLUMN reg_type TO process; ALTER TABLE regprc.registration_list ADD COLUMN additional_info_req_id character varying(256); ALTER TABLE regprc.registration_list ADD COLUMN packet_id character varying; ALTER TABLE regprc.registration_list ADD COLUMN source character varying; +ALTER TABLE regprc.registration_list ADD COLUMN ref_id character varying(512); ALTER TABLE regprc.registration RENAME COLUMN id TO reg_id; ALTER TABLE regprc.registration RENAME COLUMN reg_type TO process; @@ -107,11 +145,6 @@ ALTER TABLE regprc.registration DROP CONSTRAINT pk_reg_id CASCADE; ALTER TABLE regprc.registration ALTER COLUMN workflow_instance_id SET NOT NULL; ALTER TABLE regprc.registration ADD CONSTRAINT pk_reg_id PRIMARY KEY (workflow_instance_id); -ALTER TABLE regprc.registration_list DROP CONSTRAINT pk_reglist_id; -ALTER TABLE regprc.registration_list ALTER COLUMN workflow_instance_id SET NOT NULL; -ALTER TABLE regprc.registration_list ADD CONSTRAINT pk_reglist_id PRIMARY KEY (workflow_instance_id); - - ALTER TABLE regprc.individual_demographic_dedup ADD CONSTRAINT fk_idemogd_reg FOREIGN KEY (workflow_instance_id) REFERENCES regprc.registration (workflow_instance_id) MATCH SIMPLE ON DELETE NO ACTION ON UPDATE NO ACTION; @@ -138,29 +171,28 @@ ALTER TABLE regprc.registration ADD COLUMN default_resume_action character varyi ALTER TABLE regprc.registration ADD COLUMN pause_rule_ids character varying(256); ---------------------------------------------------------------------------------------------------- -ALTER TABLE regprc.registration_transaction DROP CONSTRAINT IF EXISTS fk_regtrn_trntyp ; -ALTER TABLE regprc.reg_manual_verification DROP CONSTRAINT IF EXISTS fk_rmnlver_trntyp ; -ALTER TABLE regprc.reg_demo_dedupe_list DROP CONSTRAINT IF EXISTS fk_regded_regtrn ; - -TRUNCATE TABLE regprc.transaction_type cascade ; - -\COPY regprc.transaction_type (code,descr,lang_code,is_active,cr_by,cr_dtimes) FROM './dml/regprc-transaction_type.csv' delimiter ',' HEADER csv; - -UPDATE regprc.registration_transaction SET trn_type_code='QUALITY_CLASSIFIER' WHERE trn_type_code='QUALITY_CHECK'; -UPDATE regprc.reg_manual_verification SET trntyp_code='QUALITY_CLASSIFIER' WHERE trntyp_code='QUALITY_CHECK'; - -ALTER TABLE regprc.registration_transaction ADD CONSTRAINT fk_regtrn_trntyp FOREIGN KEY (trn_type_code,lang_code) -REFERENCES regprc.transaction_type (code,lang_code) MATCH SIMPLE -ON DELETE NO ACTION ON UPDATE NO ACTION; - -ALTER TABLE regprc.reg_manual_verification ADD CONSTRAINT fk_rmnlver_trntyp FOREIGN KEY (trntyp_code,lang_code) -REFERENCES regprc.transaction_type (code,lang_code) MATCH SIMPLE -ON DELETE NO ACTION ON UPDATE NO ACTION; - -ALTER TABLE regprc.reg_demo_dedupe_list ADD CONSTRAINT fk_regded_regtrn FOREIGN KEY (regtrn_id) -REFERENCES regprc.registration_transaction (id) MATCH FULL -ON DELETE NO ACTION ON UPDATE NO ACTION; - +INSERT INTO regprc.transaction_type (code,descr,lang_code,is_active,cr_by,cr_dtimes,upd_by,upd_dtimes,is_deleted,del_dtimes) VALUES + ('VERIFICATION','transaction_done','eng',true,'MOSIP_SYSTEM',now(),NULL,NULL,false,NULL); +INSERT INTO regprc.transaction_type (code,descr,lang_code,is_active,cr_by,cr_dtimes,upd_by,upd_dtimes,is_deleted,del_dtimes) VALUES + ('QUALITY_CLASSIFIER','transaction_done','eng',true,'MOSIP_SYSTEM',now(),NULL,NULL,false,NULL); +INSERT INTO regprc.transaction_type (code,descr,lang_code,is_active,cr_by,cr_dtimes,upd_by,upd_dtimes,is_deleted,del_dtimes) VALUES + ('WORKFLOW_RESUME','transaction_done','eng',true,'MOSIP_SYSTEM',now(),NULL,NULL,false,NULL); +INSERT INTO regprc.transaction_type (code,descr,lang_code,is_active,cr_by,cr_dtimes,upd_by,upd_dtimes,is_deleted,del_dtimes) VALUES + ('CMD_VALIDATION','transaction_done','eng',true,'MOSIP_SYSTEM',now(),NULL,NULL,false,NULL); +INSERT INTO regprc.transaction_type (code,descr,lang_code,is_active,cr_by,cr_dtimes,upd_by,upd_dtimes,is_deleted,del_dtimes) VALUES + ('SUPERVISOR_VALIDATION','transaction_done','eng',true,'MOSIP_SYSTEM',now(),NULL,NULL,false,NULL); +INSERT INTO regprc.transaction_type (code,descr,lang_code,is_active,cr_by,cr_dtimes,upd_by,upd_dtimes,is_deleted,del_dtimes) VALUES + ('OPERATOR_VALIDATION','transaction_done','eng',true,'MOSIP_SYSTEM',now(),NULL,NULL,false,NULL); +INSERT INTO regprc.transaction_type (code,descr,lang_code,is_active,cr_by,cr_dtimes,upd_by,upd_dtimes,is_deleted,del_dtimes) VALUES + ('INTRODUCER_VALIDATION','transaction_done','eng',true,'MOSIP_SYSTEM',now(),NULL,NULL,false,NULL); +INSERT INTO regprc.transaction_type (code,descr,lang_code,is_active,cr_by,cr_dtimes,upd_by,upd_dtimes,is_deleted,del_dtimes) VALUES + ('INTERNAL_WORKFLOW_ACTION','transaction_done','eng',true,'MOSIP_SYSTEM',now(),NULL,NULL,false,NULL); +INSERT INTO regprc.transaction_type (code,descr,lang_code,is_active,cr_by,cr_dtimes,upd_by,upd_dtimes,is_deleted,del_dtimes) VALUES + ('BIOMETRIC_EXTRACTION','transaction_done','eng',true,'MOSIP_SYSTEM',now(),NULL,NULL,false,NULL); +INSERT INTO regprc.transaction_type (code,descr,lang_code,is_active,cr_by,cr_dtimes,upd_by,upd_dtimes,is_deleted,del_dtimes) VALUES + ('FINALIZATION','transaction_done','eng',true,'MOSIP_SYSTEM',now(),NULL,NULL,false,NULL); +INSERT INTO regprc.transaction_type (code,descr,lang_code,is_active,cr_by,cr_dtimes,upd_by,upd_dtimes,is_deleted,del_dtimes) VALUES + ('MANUAL_ADJUDICATION','transaction_done','eng',true,'MOSIP_SYSTEM',now(),NULL,NULL,false,NULL); ------------------------------------------------------------------------------------------------------ @@ -177,7 +209,18 @@ ALTER TABLE regprc.registration_list ADD COLUMN location_code character varying; ------------------------------------------------------------------------------------------------------------------------------------------- -------------------------------------------------Creation of crypto salt table-------------------------------------------------------------- -\ir ../ddl/regprc-crypto_salt.sql +CREATE TABLE regprc.crypto_salt( + id integer NOT NULL, + salt character varying(36) NOT NULL, + cr_by character varying(256) NOT NULL, + cr_dtimes timestamp NOT NULL, + upd_by character varying(256) , + upd_dtimes timestamp , + CONSTRAINT pk_rides PRIMARY KEY (id)); + +GRANT SELECT, INSERT, TRUNCATE, REFERENCES, UPDATE, DELETE + ON regprc.crypto_salt + TO regprcuser; -------------------------------------------------------------------------------------------------------------------------------------------- @@ -318,3 +361,10 @@ UPDATE regprc.registration SET last_success_stage_name = 'PacketUploaderStage' w UPDATE regprc.registration SET last_success_stage_name = 'UinGeneratorStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='PrintingStage' and process = 'DEACTIVATED'; ------------------------------------------------------------------------------------------------------------------------------------- +DROP INDEX IF EXISTS regprc.idx_reg_verification_reqid; + +DROP INDEX IF EXISTS regprc.idx_idemogd_namedob; + +ALTER TABLE regprc.reg_bio_ref ALTER COLUMN process TYPE character varying COLLATE pg_catalog."default"; + +CREATE INDEX IF NOT EXISTS idx_reglist_reg_id ON regprc.registration_list USING btree (reg_id COLLATE pg_catalog."default" ASC NULLS LAST) TABLESPACE pg_default; \ No newline at end of file diff --git a/db_upgrade_scripts/mosip_regprc/sql/1.2.0.1-B1_to_1.2.0.1-B2_rollback.sql b/db_upgrade_scripts/mosip_regprc/sql/1.2.0.1-B1_to_1.2.0.1-B2_rollback.sql new file mode 100644 index 00000000000..381e2be11c1 --- /dev/null +++ b/db_upgrade_scripts/mosip_regprc/sql/1.2.0.1-B1_to_1.2.0.1-B2_rollback.sql @@ -0,0 +1 @@ +\echo 'Upgrade Queries not required for transition from $CURRENT_VERSION to $UPGRADE_VERSION' \ No newline at end of file diff --git a/db_upgrade_scripts/mosip_regprc/sql/1.2.0.1-B1_to_1.2.0.1-B2_upgrade.sql b/db_upgrade_scripts/mosip_regprc/sql/1.2.0.1-B1_to_1.2.0.1-B2_upgrade.sql new file mode 100644 index 00000000000..5548b94e9cb --- /dev/null +++ b/db_upgrade_scripts/mosip_regprc/sql/1.2.0.1-B1_to_1.2.0.1-B2_upgrade.sql @@ -0,0 +1 @@ +\echo 'Upgrade Queries not required for transition from $CURRENT_VERSION to $UPGRADE_VERSION' diff --git a/db_upgrade_scripts/mosip_regprc/sql/1.2.0.1-B2_to_1.2.0.1-B3_rollback.sql b/db_upgrade_scripts/mosip_regprc/sql/1.2.0.1-B2_to_1.2.0.1-B3_rollback.sql new file mode 100644 index 00000000000..5548b94e9cb --- /dev/null +++ b/db_upgrade_scripts/mosip_regprc/sql/1.2.0.1-B2_to_1.2.0.1-B3_rollback.sql @@ -0,0 +1 @@ +\echo 'Upgrade Queries not required for transition from $CURRENT_VERSION to $UPGRADE_VERSION' diff --git a/db_upgrade_scripts/mosip_regprc/sql/1.2.0.1-B2_to_1.2.0.1-B3_upgrade.sql b/db_upgrade_scripts/mosip_regprc/sql/1.2.0.1-B2_to_1.2.0.1-B3_upgrade.sql new file mode 100644 index 00000000000..5548b94e9cb --- /dev/null +++ b/db_upgrade_scripts/mosip_regprc/sql/1.2.0.1-B2_to_1.2.0.1-B3_upgrade.sql @@ -0,0 +1 @@ +\echo 'Upgrade Queries not required for transition from $CURRENT_VERSION to $UPGRADE_VERSION' diff --git a/db_upgrade_scripts/mosip_regprc/sql/1.2.0.1-B3_to_1.2.0.1_rollback.sql b/db_upgrade_scripts/mosip_regprc/sql/1.2.0.1-B3_to_1.2.0.1_rollback.sql new file mode 100644 index 00000000000..5548b94e9cb --- /dev/null +++ b/db_upgrade_scripts/mosip_regprc/sql/1.2.0.1-B3_to_1.2.0.1_rollback.sql @@ -0,0 +1 @@ +\echo 'Upgrade Queries not required for transition from $CURRENT_VERSION to $UPGRADE_VERSION' diff --git a/db_upgrade_scripts/mosip_regprc/sql/1.2.0.1-B3_to_1.2.0.1_upgrade.sql b/db_upgrade_scripts/mosip_regprc/sql/1.2.0.1-B3_to_1.2.0.1_upgrade.sql new file mode 100644 index 00000000000..5548b94e9cb --- /dev/null +++ b/db_upgrade_scripts/mosip_regprc/sql/1.2.0.1-B3_to_1.2.0.1_upgrade.sql @@ -0,0 +1 @@ +\echo 'Upgrade Queries not required for transition from $CURRENT_VERSION to $UPGRADE_VERSION' diff --git a/db_upgrade_scripts/mosip_regprc/upgrade.properties b/db_upgrade_scripts/mosip_regprc/upgrade.properties new file mode 100644 index 00000000000..88b7143ad4a --- /dev/null +++ b/db_upgrade_scripts/mosip_regprc/upgrade.properties @@ -0,0 +1,12 @@ +ACTION=upgrade +MOSIP_DB_NAME=mosip_regprc +DB_SERVERIP= +DB_PORT= +SU_USER=postgres +SU_USER_PWD= +SYS_ADMIN_USER= +SYS_ADMIN_PWD= +DEFAULT_DB_NAME=postgres +DBUSER_PWD= +CURRENT_VERSION= +UPGRADE_VERSION= \ No newline at end of file diff --git a/db_upgrade_scripts/mosip_regprc/upgrade.sh b/db_upgrade_scripts/mosip_regprc/upgrade.sh new file mode 100644 index 00000000000..a6fb0b1e457 --- /dev/null +++ b/db_upgrade_scripts/mosip_regprc/upgrade.sh @@ -0,0 +1,51 @@ +#!/bin/bash + +set -e +properties_file="$1" +echo `date "+%m/%d/%Y %H:%M:%S"` ": $properties_file" +if [ -f "$properties_file" ] +then + echo `date "+%m/%d/%Y %H:%M:%S"` ": Property file \"$properties_file\" found." + while IFS='=' read -r key value + do + key=$(echo $key | tr '.' '_') + eval ${key}=\${value} + done < "$properties_file" +else + echo `date "+%m/%d/%Y %H:%M:%S"` ": Property file not found, Pass property file name as argument." +fi + +echo "Current version: "$CURRENT_VERSION +echo "UPGRADE version: "$UPGRADE_VERSION +echo "Action: "$ACTION + +# Terminate existing connections +echo "Terminating active connections" +CONN=$(PGPASSWORD=$SU_USER_PWD psql -v ON_ERROR_STOP=1 --username=$SU_USER --host=$DB_SERVERIP --port=$DB_PORT --dbname=$DEFAULT_DB_NAME -t -c "SELECT count(pg_terminate_backend(pg_stat_activity.pid)) FROM pg_stat_activity WHERE datname = '$MOSIP_DB_NAME' AND pid <> pg_backend_pid()";exit;) +echo "Terminated connections" + +# Execute upgrade or rollback +if [ $ACTION == "upgrade" ]; then + echo "Upgrading database from $CURRENT_VERSION to $UPGRADE_VERSION" + UPGRADE_SCRIPT_FILE="sql/${CURRENT_VERSION}_to_${UPGRADE_VERSION}_upgrade.sql" + if [ -f "$UPGRADE_SCRIPT_FILE" ]; then + echo "Executing upgrade script $UPGRADE_SCRIPT_FILE" + PGPASSWORD=$SU_USER_PWD psql -v ON_ERROR_STOP=1 --username=$SU_USER --host=$DB_SERVERIP --port=$DB_PORT --dbname=$DEFAULT_DB_NAME -a -b -f $UPGRADE_SCRIPT_FILE + else + echo "Upgrade script not found, exiting." + exit 1 + fi +elif [ $ACTION == "rollback" ]; then + echo "Rolling back database for $CURRENT_VERSION to $UPGRADE_VERSION" + REVOKE_SCRIPT_FILE="sql/${CURRENT_VERSION}_to_${UPGRADE_VERSION}_rollback.sql" + if [ -f "$REVOKE_SCRIPT_FILE" ]; then + echo "Executing rollback script $REVOKE_SCRIPT_FILE" + PGPASSWORD=$SU_USER_PWD psql -v ON_ERROR_STOP=1 --username=$SU_USER --host=$DB_SERVERIP --port=$DB_PORT --dbname=$DEFAULT_DB_NAME -a -b -f $REVOKE_SCRIPT_FILE + else + echo "rollback script not found, exiting." + exit 1 + fi +else + echo "Unknown action: $ACTION, must be 'upgrade' or 'rollback'." + exit 1 +fi \ No newline at end of file diff --git a/registration-processor/core-processor/registration-processor-abis-handler-stage/src/main/java/io/mosip/registration/processor/abis/handler/stage/AbisHandlerStage.java b/registration-processor/core-processor/registration-processor-abis-handler-stage/src/main/java/io/mosip/registration/processor/abis/handler/stage/AbisHandlerStage.java index 8148ede2aea..23ab72ea0ef 100644 --- a/registration-processor/core-processor/registration-processor-abis-handler-stage/src/main/java/io/mosip/registration/processor/abis/handler/stage/AbisHandlerStage.java +++ b/registration-processor/core-processor/registration-processor-abis-handler-stage/src/main/java/io/mosip/registration/processor/abis/handler/stage/AbisHandlerStage.java @@ -1,800 +1,811 @@ -package io.mosip.registration.processor.abis.handler.stage; - -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 java.util.Optional; -import java.util.Set; -import java.util.UUID; -import java.util.stream.Collectors; - -import org.apache.commons.lang3.exception.ExceptionUtils; -import org.json.JSONArray; -import org.json.JSONException; -import org.json.simple.JSONObject; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.cloud.context.config.annotation.RefreshScope; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.core.env.Environment; -import org.springframework.core.io.ByteArrayResource; -import org.springframework.http.MediaType; -import org.springframework.stereotype.Service; -import org.springframework.util.CollectionUtils; -import org.springframework.util.LinkedMultiValueMap; -import org.springframework.util.MultiValueMap; - -import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.JsonMappingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.google.common.collect.Lists; - -import io.mosip.kernel.biometrics.constant.BiometricType; -import io.mosip.kernel.biometrics.entities.BIR; -import io.mosip.kernel.biometrics.entities.BiometricRecord; -import io.mosip.kernel.biometrics.spi.CbeffUtil; -import io.mosip.kernel.core.logger.spi.Logger; -import io.mosip.kernel.core.util.DateUtils; -import io.mosip.kernel.core.util.JsonUtils; -import io.mosip.kernel.core.util.StringUtils; -import io.mosip.kernel.core.util.exception.JsonProcessingException; -import io.mosip.registration.processor.abis.handler.constant.AbisHandlerStageConstant; -import io.mosip.registration.processor.abis.handler.dto.DataShareResponseDto; -import io.mosip.registration.processor.abis.handler.exception.AbisHandlerException; -import io.mosip.registration.processor.abis.handler.exception.DataShareException; -import io.mosip.registration.processor.abis.queue.dto.AbisQueueDetails; -import io.mosip.registration.processor.core.abstractverticle.MessageBusAddress; -import io.mosip.registration.processor.core.abstractverticle.MessageDTO; -import io.mosip.registration.processor.core.abstractverticle.MosipEventBus; -import io.mosip.registration.processor.core.abstractverticle.MosipRouter; -import io.mosip.registration.processor.core.abstractverticle.MosipVerticleAPIManager; -import io.mosip.registration.processor.core.code.AbisStatusCode; -import io.mosip.registration.processor.core.code.ApiName; -import io.mosip.registration.processor.core.code.EventId; -import io.mosip.registration.processor.core.code.EventName; -import io.mosip.registration.processor.core.code.EventType; -import io.mosip.registration.processor.core.code.ModuleName; -import io.mosip.registration.processor.core.code.RegistrationTransactionStatusCode; -import io.mosip.registration.processor.core.constant.JsonConstant; -import io.mosip.registration.processor.core.constant.LoggerFileConstant; -import io.mosip.registration.processor.core.constant.MappingJsonConstants; -import io.mosip.registration.processor.core.constant.PolicyConstant; -import io.mosip.registration.processor.core.constant.ProviderStageName; -import io.mosip.registration.processor.core.exception.ApisResourceAccessException; -import io.mosip.registration.processor.core.exception.PacketManagerException; -import io.mosip.registration.processor.core.exception.util.PlatformErrorMessages; -import io.mosip.registration.processor.core.exception.util.PlatformSuccessMessages; -import io.mosip.registration.processor.core.http.ResponseWrapper; -import io.mosip.registration.processor.core.logger.LogDescription; -import io.mosip.registration.processor.core.logger.RegProcessorLogger; -import io.mosip.registration.processor.core.packet.dto.FieldValue; -import io.mosip.registration.processor.core.packet.dto.Identity; -import io.mosip.registration.processor.core.packet.dto.abis.AbisIdentifyRequestDto; -import io.mosip.registration.processor.core.packet.dto.abis.AbisIdentifyRequestGalleryDto; -import io.mosip.registration.processor.core.packet.dto.abis.AbisInsertRequestDto; -import io.mosip.registration.processor.core.packet.dto.abis.AbisRequestDto; -import io.mosip.registration.processor.core.packet.dto.abis.Flag; -import io.mosip.registration.processor.core.packet.dto.abis.ReferenceIdDto; -import io.mosip.registration.processor.core.packet.dto.abis.RegBioRefDto; -import io.mosip.registration.processor.core.packet.dto.abis.RegDemoDedupeListDto; -import io.mosip.registration.processor.core.packet.dto.datashare.Filter; -import io.mosip.registration.processor.core.packet.dto.datashare.ShareableAttributes; -import io.mosip.registration.processor.core.packet.dto.datashare.Source; -import io.mosip.registration.processor.core.spi.packetmanager.PacketInfoManager; -import io.mosip.registration.processor.core.spi.restclient.RegistrationProcessorRestClientService; -import io.mosip.registration.processor.core.status.util.StatusUtil; -import io.mosip.registration.processor.core.status.util.TrimExceptionMessage; -import io.mosip.registration.processor.core.util.JsonUtil; -import io.mosip.registration.processor.packet.storage.dto.ApplicantInfoDto; -import io.mosip.registration.processor.packet.storage.utils.PacketManagerService; -import io.mosip.registration.processor.packet.storage.utils.PriorityBasedPacketManagerService; -import io.mosip.registration.processor.packet.storage.utils.Utilities; -import io.mosip.registration.processor.rest.client.audit.builder.AuditLogRequestBuilder; -import io.mosip.registration.processor.status.dto.InternalRegistrationStatusDto; -import io.mosip.registration.processor.status.dto.RegistrationStatusDto; -import io.mosip.registration.processor.status.service.RegistrationStatusService; - -/** - * The Class AbisHandlerStage. - * - * @author M1048358 Alok - */ -@RefreshScope -@Service -@Configuration -@ComponentScan(basePackages = { "${mosip.auth.adapter.impl.basepackage}", - "io.mosip.registration.processor.abis.handler.config", - "io.mosip.registration.processor.status.config", "io.mosip.registration.processor.rest.client.config", - "io.mosip.registration.processor.packet.storage.config", "io.mosip.registration.processor.core.config", - "io.mosip.registration.processor.core.kernel.beans", "io.mosip.kernel.packetmanager.config" }) -public class AbisHandlerStage extends MosipVerticleAPIManager { - - private static final String STAGE_PROPERTY_PREFIX = "mosip.regproc.abis.handler."; - private Map> typeAndSubTypeMap = new HashMap<>(); - LinkedHashMap datasharePolicies = null; - - /** The cluster manager url. */ - @Value("${vertx.cluster.configuration}") - private String clusterManagerUrl; - - /** The max results. */ - @Value("${registration.processor.abis.maxResults}") - private String maxResults; - - /** The target FPIR. */ - @Value("${registration.processor.abis.targetFPIR}") - private String targetFPIR; - - /** worker pool size. */ - @Value("${worker.pool.size}") - private Integer workerPoolSize; - - /** - * After this time intervel, message should be considered as expired (In - * seconds). - */ - @Value("${mosip.regproc.abis.handler.message.expiry-time-limit}") - private Long messageExpiryTimeLimit; - - @Value("${registration.processor.policy.id}") - private String policyId; - - @Value("${registration.processor.subscriber.id}") - private String subscriberId; - - @Value("${mosip.regproc.data.share.protocol}") - private String httpProtocol; - - @Value("${mosip.regproc.data.share.internal.domain.name}") - private String internalDomainName; - - @Value("#{${mosip.regproc.abis.handler.biometric-modalities-segments-mapping-for-age-group}}") - private Map>> biometricModalitySegmentsMapforAgeGroup; - - @Value("#{${mosip.regproc.abis.handler.biometric-segments-exceptions-mapping}}") - private Map exceptionSegmentsMap; - - @Autowired - private RegistrationProcessorRestClientService registrationProcessorRestClientService; - - /** The reg proc logger. */ - private static Logger regProcLogger = RegProcessorLogger.getLogger(AbisHandlerStage.class); - - /** The core audit request builder. */ - @Autowired - private AuditLogRequestBuilder auditLogRequestBuilder; - - /** The registration status service. */ - @Autowired - private RegistrationStatusService registrationStatusService; - - /** The packet info manager. */ - @Autowired - private PacketInfoManager packetInfoManager; - - @Autowired - private PacketManagerService packetManagerService; - - @Autowired - private Utilities utility; - - @Autowired - private ObjectMapper mapper; - - /** The mosip event bus. */ - MosipEventBus mosipEventBus = null; - - /** Mosip router for APIs */ - @Autowired - MosipRouter router; - - @Autowired - private CbeffUtil cbeffutil; - - @Autowired - private Environment env; - - @Autowired - private PriorityBasedPacketManagerService priorityBasedPacketManagerService; - - private static final String DATASHARECREATEURL = "DATASHARECREATEURL"; - - private static final String DATETIME_PATTERN = "mosip.registration.processor.datetime.pattern"; - - @Value("#{T(java.util.Arrays).asList('${mosip.regproc.common.before-cbeff-others-attibute.reg-client-versions:}')}") - private List regClientVersionsBeforeCbeffOthersAttritube; - - /** - * Deploy verticle. - */ - public void deployVerticle() { - mosipEventBus = this.getEventBus(this, clusterManagerUrl, workerPoolSize); - this.consumeAndSend(mosipEventBus, MessageBusAddress.ABIS_HANDLER_BUS_IN, - MessageBusAddress.ABIS_HANDLER_BUS_OUT, messageExpiryTimeLimit); - } - - @Override - public void start() { - router.setRoute(this.postUrl(getVertx(), MessageBusAddress.ABIS_HANDLER_BUS_IN, - MessageBusAddress.ABIS_HANDLER_BUS_OUT)); - this.createServer(router.getRouter(), getPort()); - } - - @Override - protected String getPropertyPrefix() { - return STAGE_PROPERTY_PREFIX; - } - - /* - * (non-Javadoc) - * - * @see - * io.mosip.registration.processor.core.spi.eventbus.EventBusManager#process( - * java.lang.Object) - */ - @Override - public MessageDTO process(MessageDTO object) { - TrimExceptionMessage trimExceptionMessage = new TrimExceptionMessage(); - LogDescription description = new LogDescription(); - object.setMessageBusAddress(MessageBusAddress.ABIS_HANDLER_BUS_IN); - object.setIsValid(Boolean.TRUE); - Boolean isTransactionSuccessful = false; - String regId = object.getRid(); - object.setInternalError(Boolean.FALSE); - InternalRegistrationStatusDto registrationStatusDto = null; - String transactionTypeCode = null; - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - regId, "AbisHandlerStage::process()::entry"); - try { - registrationStatusDto = registrationStatusService.getRegistrationStatus(regId, object.getReg_type(), - object.getIteration(), object.getWorkflowInstanceId()); - transactionTypeCode = registrationStatusDto.getLatestTransactionTypeCode(); - String transactionId = registrationStatusDto.getLatestRegistrationTransactionId(); - - Boolean isIdentifyRequestPresent = packetInfoManager.getIdentifyByTransactionId(transactionId, - AbisHandlerStageConstant.IDENTIFY); - - if (!isIdentifyRequestPresent) { - List abisQueueDetails = utility.getAbisQueueDetails(); - if (abisQueueDetails.isEmpty()) { - description.setStatusComment(AbisHandlerStageConstant.DETAILS_NOT_FOUND); - description.setMessage(PlatformErrorMessages.RPR_DETAILS_NOT_FOUND.getMessage()); - description.setCode(PlatformErrorMessages.RPR_DETAILS_NOT_FOUND.getCode()); - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), - LoggerFileConstant.REGISTRATIONID.toString(), "", - AbisHandlerStageConstant.DETAILS_NOT_FOUND); - throw new AbisHandlerException(PlatformErrorMessages.RPR_ABIS_INTERNAL_ERROR.getCode()); - } - createRequest(regId, abisQueueDetails, transactionId, registrationStatusDto.getRegistrationType(),registrationStatusDto.getIteration(), - registrationStatusDto.getWorkflowInstanceId(), description, transactionTypeCode); - object.setMessageBusAddress(MessageBusAddress.ABIS_MIDDLEWARE_BUS_IN); - } else { - if (transactionTypeCode.equalsIgnoreCase(AbisHandlerStageConstant.DEMOGRAPHIC_VERIFICATION)) { - object.setMessageBusAddress(MessageBusAddress.DEMO_DEDUPE_BUS_IN); - } else if (transactionTypeCode.equalsIgnoreCase(AbisHandlerStageConstant.BIOGRAPHIC_VERIFICATION)) { - object.setMessageBusAddress(MessageBusAddress.BIO_DEDUPE_BUS_IN); - } - } - description.setStatusComment(AbisHandlerStageConstant.ABIS_HANDLER_SUCCESS); - description.setMessage(PlatformSuccessMessages.RPR_ABIS_HANDLER_STAGE_SUCCESS.getMessage()); - description.setCode(PlatformSuccessMessages.RPR_ABIS_HANDLER_STAGE_SUCCESS.getCode()); - isTransactionSuccessful = true; - regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - regId, description.getMessage()); - } catch (Exception e) { - - if (e instanceof DataShareException) { - object.setIsValid(false); - } - description.setStatusComment(AbisHandlerStageConstant.ERROR_IN_ABIS_HANDLER); - description.setMessage(PlatformErrorMessages.RPR_MESSAGE_SENDER_STAGE_FAILED.getMessage()); - description.setCode(PlatformErrorMessages.RPR_MESSAGE_SENDER_STAGE_FAILED.getCode()); - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - regId, ExceptionUtils.getStackTrace(e)); - object.setInternalError(Boolean.TRUE); - registrationStatusDto - .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.REPROCESS.toString()); - registrationStatusDto.setSubStatusCode(StatusUtil.SYSTEM_EXCEPTION_OCCURED.getCode()); - if (transactionTypeCode.equalsIgnoreCase(AbisHandlerStageConstant.DEMOGRAPHIC_VERIFICATION)) { - registrationStatusDto.setRegistrationStageName(AbisHandlerStageConstant.DEMO_DEDUPE_STAGE); - } else if (transactionTypeCode.equalsIgnoreCase(AbisHandlerStageConstant.BIOGRAPHIC_VERIFICATION)) { - registrationStatusDto.setRegistrationStageName(AbisHandlerStageConstant.BIO_DEDUPE_STAGE); - } - registrationStatusDto.setStatusComment(trimExceptionMessage - .trimExceptionMessage(StatusUtil.UNKNOWN_EXCEPTION_OCCURED.getMessage() + e.getMessage())); - String moduleId = description.getCode(); - String moduleName = ModuleName.ABIS_HANDLER.toString(); - registrationStatusService.updateRegistrationStatus(registrationStatusDto, moduleId, moduleName); - } finally { - if (object.getInternalError()) { - updateErrorFlags(registrationStatusDto, object); - } - String eventId = isTransactionSuccessful ? EventId.RPR_402.toString() : EventId.RPR_405.toString(); - String eventName = isTransactionSuccessful ? EventName.UPDATE.toString() : EventName.EXCEPTION.toString(); - String eventType = isTransactionSuccessful ? EventType.BUSINESS.toString() : EventType.SYSTEM.toString(); - - /** Module-Id can be Both Success/Error code */ - String moduleId = isTransactionSuccessful ? PlatformSuccessMessages.RPR_ABIS_HANDLER_STAGE_SUCCESS.getCode() - : description.getCode(); - String moduleName = ModuleName.ABIS_HANDLER.toString(); - - auditLogRequestBuilder.createAuditRequestBuilder(description.getMessage(), eventId, eventName, eventType, - moduleId, moduleName, regId); - - } - - return object; - } - - private void createRequest(String regId, List abisQueueDetails, String transactionId, - String process, int iteration, String workflowInstanceId, LogDescription description, String transactionTypeCode) throws Exception { - String bioRefId = getUUID(); - insertInBioRef(regId, bioRefId,process,iteration, workflowInstanceId); - createInsertRequest(abisQueueDetails, transactionId, bioRefId, regId, process, description); - createIdentifyRequest(abisQueueDetails, transactionId, bioRefId, transactionTypeCode, description); - - } - - /** - * Creates the identify request. - * - * @param abisQueueDetails the abis application dto list - * @param transactionId the transaction id - * @param bioRefId the bio ref id - * @param transactionTypeCode the transaction type code - * @param description - */ - private void createIdentifyRequest(List abisQueueDetails, String transactionId, String bioRefId, - String transactionTypeCode, LogDescription description) { - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", - "AbisHandlerStage::createIdentifyRequest()::entry"); - String batchId = getUUID(); - for (AbisQueueDetails abisQueue : abisQueueDetails) { - AbisRequestDto abisRequestDto = new AbisRequestDto(); - String id = getUUID(); - abisRequestDto.setId(id); - abisRequestDto.setAbisAppCode(abisQueue.getName()); - abisRequestDto.setBioRefId(bioRefId); - abisRequestDto.setRequestType(AbisHandlerStageConstant.IDENTIFY); - abisRequestDto.setReqBatchId(batchId); - abisRequestDto.setRefRegtrnId(transactionId); - - byte[] abisIdentifyRequestBytes = getIdentifyRequestBytes(transactionId, bioRefId, transactionTypeCode, id, - description); - abisRequestDto.setReqText(abisIdentifyRequestBytes); - - abisRequestDto.setStatusCode(RegistrationTransactionStatusCode.IN_PROGRESS.toString()); - abisRequestDto.setStatusComment(null); - abisRequestDto.setLangCode(AbisHandlerStageConstant.ENG); - abisRequestDto.setCrBy(AbisHandlerStageConstant.USER); - abisRequestDto.setUpdBy(null); - abisRequestDto.setIsDeleted(Boolean.FALSE); - - String moduleId = PlatformSuccessMessages.RPR_ABIS_HANDLER_STAGE_SUCCESS.getCode(); - String moduleName = ModuleName.ABIS_HANDLER.toString(); - packetInfoManager.saveAbisRequest(abisRequestDto, moduleId, moduleName); - } - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", - "AbisHandlerStage::createIdentifyRequest()::exit"); - } - - /** - * Gets the identify request bytes. - * - * @param transactionId the transaction id - * @param bioRefId the bio ref id - * @param transactionTypeCode the transaction type code - * @param id the id - * @param description - * @return the identify request bytes - */ - private byte[] getIdentifyRequestBytes(String transactionId, String bioRefId, String transactionTypeCode, String id, - LogDescription description) { - AbisIdentifyRequestDto abisIdentifyRequestDto = new AbisIdentifyRequestDto(); - Flag flag = new Flag(); - abisIdentifyRequestDto.setId(AbisHandlerStageConstant.MOSIP_ABIS_IDENTIFY); - abisIdentifyRequestDto.setVersion(AbisHandlerStageConstant.VERSION); - abisIdentifyRequestDto.setRequestId(id); - abisIdentifyRequestDto.setReferenceId(bioRefId); - abisIdentifyRequestDto.setReferenceUrl(""); - abisIdentifyRequestDto.setRequesttime(DateUtils.getUTCCurrentDateTimeString(env.getProperty(DATETIME_PATTERN))); - flag.setMaxResults(maxResults); - flag.setTargetFPIR(targetFPIR); - abisIdentifyRequestDto.setFlags(flag); - - // Added Gallery data for demo dedupe - if (transactionTypeCode.equalsIgnoreCase(AbisHandlerStageConstant.DEMOGRAPHIC_VERIFICATION)) { - List regDemoDedupeListDtoList = packetInfoManager - .getDemoListByTransactionId(transactionId); - if (regDemoDedupeListDtoList.isEmpty()) { - description.setStatusComment(AbisHandlerStageConstant.NO_RECORD_FOUND); - description.setMessage(PlatformErrorMessages.RPR_NO_RECORD_FOUND.getMessage()); - description.setCode(PlatformErrorMessages.RPR_NO_RECORD_FOUND.getCode()); - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), - LoggerFileConstant.REGISTRATIONID.toString(), "", - "Potential Match Records are Not Found for Demo Dedupe Potential Match"); - throw new AbisHandlerException(description.getMessage()); - } - List referenceIdDtos = new ArrayList<>(); - - for (RegDemoDedupeListDto dedupeListDto : regDemoDedupeListDtoList) { - ReferenceIdDto dto = new ReferenceIdDto(); - List regBioRefDto = packetInfoManager.getBioRefIdByRegId(dedupeListDto.getMatchedRegId()); - if (!CollectionUtils.isEmpty(regBioRefDto)) { - dto.setReferenceId(regBioRefDto.get(0).getBioRefId()); - } - - referenceIdDtos.add(dto); - } - AbisIdentifyRequestGalleryDto galleryDto = new AbisIdentifyRequestGalleryDto(); - galleryDto.setReferenceIds(referenceIdDtos); - abisIdentifyRequestDto.setGallery(galleryDto); - } - - try { - String jsonString = JsonUtils.javaObjectToJsonString(abisIdentifyRequestDto); - return jsonString.getBytes(); - } catch (JsonProcessingException e) { - description.setStatusComment(AbisHandlerStageConstant.ERROR_IN_ABIS_HANDLER_IDENTIFY_REQUEST); - description.setMessage(PlatformErrorMessages.RPR_ERROR_IN_ABIS_HANDLER_IDENTIFY_REQUEST.getMessage()); - description.setCode(PlatformErrorMessages.RPR_ERROR_IN_ABIS_HANDLER_IDENTIFY_REQUEST.getCode()); - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - "", AbisHandlerStageConstant.ERROR_IN_ABIS_HANDLER_IDENTIFY_REQUEST); - throw new AbisHandlerException(PlatformErrorMessages.RPR_ABIS_INTERNAL_ERROR.getCode(), e); - } - } - - /** - * Insert in bio ref. - * - * @param regId the reg id - * @param bioRefId the bio ref id - */ - private void insertInBioRef(String regId, String bioRefId, String process, int iteration, String workflowInstanceId) { - RegBioRefDto regBioRefDto = new RegBioRefDto(); - regBioRefDto.setBioRefId(bioRefId); - regBioRefDto.setCrBy(AbisHandlerStageConstant.USER); - regBioRefDto.setIsActive(Boolean.TRUE); - regBioRefDto.setIsDeleted(Boolean.FALSE); - regBioRefDto.setRegId(regId); - regBioRefDto.setUpdBy(null); - regBioRefDto.setProcess(process); - regBioRefDto.setIteration(iteration); - regBioRefDto.setWorkflowInstanceId(workflowInstanceId); - String moduleId = PlatformSuccessMessages.RPR_ABIS_HANDLER_STAGE_SUCCESS.getCode(); - String moduleName = ModuleName.ABIS_HANDLER.toString(); - packetInfoManager.saveBioRef(regBioRefDto, moduleId, moduleName); - } - - /** - * Creates the insert request. - * - * @param abisQueueDetails the abis application dto list - * @param transactionId the transaction id - * @param bioRefId the bio ref id - * @param regId the reg id - * @param description - */ - private void createInsertRequest(List abisQueueDetails, String transactionId, String bioRefId, - String regId, String process, LogDescription description) throws Exception { - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - regId, "AbisHandlerStage::createInsertRequest()::entry"); - String batchId = getUUID(); - List abisProcessedInsertAppCodeList = packetInfoManager.getAbisProcessedRequestsAppCodeByBioRefId( - bioRefId, AbisStatusCode.INSERT.toString(), AbisStatusCode.PROCESSED.toString()); - List abisAppCodeList = new ArrayList<>(); - for (AbisQueueDetails abisQueue : abisQueueDetails) { - abisAppCodeList.add(abisQueue.getName()); - } - - for (String appCode : abisAppCodeList) { - - AbisRequestDto abisRequestDto = new AbisRequestDto(); - String id = getUUID(); - abisRequestDto.setId(id); - abisRequestDto.setAbisAppCode(appCode); - abisRequestDto.setBioRefId(bioRefId); - abisRequestDto.setRequestType(AbisHandlerStageConstant.INSERT); - abisRequestDto.setReqBatchId(batchId); - abisRequestDto.setRefRegtrnId(transactionId); - - - abisRequestDto.setStatusCode(AbisStatusCode.IN_PROGRESS.toString()); - abisRequestDto.setStatusComment(null); - abisRequestDto.setLangCode(AbisHandlerStageConstant.ENG); - abisRequestDto.setCrBy(AbisHandlerStageConstant.USER); - abisRequestDto.setUpdBy(null); - abisRequestDto.setIsDeleted(Boolean.FALSE); - String moduleId = PlatformSuccessMessages.RPR_ABIS_HANDLER_STAGE_SUCCESS.getCode(); - String moduleName = ModuleName.ABIS_HANDLER.toString(); - byte[] abisInsertRequestBytes =null; - if (abisProcessedInsertAppCodeList != null && abisProcessedInsertAppCodeList.contains(appCode)) { - - abisInsertRequestBytes = getInsertRequestBytes(regId, id, process, bioRefId, description, - AbisStatusCode.ALREADY_PROCESSED.toString()); - abisRequestDto.setStatusCode(AbisStatusCode.ALREADY_PROCESSED.toString()); - - } else { - abisInsertRequestBytes = getInsertRequestBytes(regId, id, process, bioRefId, description, - AbisStatusCode.IN_PROGRESS.toString()); - abisRequestDto.setStatusCode(AbisStatusCode.IN_PROGRESS.toString()); - - } - abisRequestDto.setReqText(abisInsertRequestBytes); - packetInfoManager.saveAbisRequest(abisRequestDto, moduleId, moduleName); - } - - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", - "AbisHandlerStage::createInsertRequest()::exit"); - } - - /** - * Gets the insert request bytes. - * - * @param regId the reg id - * @param id the id - * @param bioRefId the bio ref id - * @param description - * @param status - * @return the insert request bytes - */ - private byte[] getInsertRequestBytes(String regId, String id, String process, String bioRefId, - LogDescription description, String status) throws Exception { - AbisInsertRequestDto abisInsertRequestDto = new AbisInsertRequestDto(); - abisInsertRequestDto.setId(AbisHandlerStageConstant.MOSIP_ABIS_INSERT); - abisInsertRequestDto.setReferenceId(bioRefId); - abisInsertRequestDto.setReferenceURL(status.equalsIgnoreCase(AbisStatusCode.IN_PROGRESS.toString())?getDataShareUrl(regId, process):null); - abisInsertRequestDto.setRequestId(id); - abisInsertRequestDto.setRequesttime(DateUtils.getUTCCurrentDateTimeString(env.getProperty(DATETIME_PATTERN))); - abisInsertRequestDto.setVersion(AbisHandlerStageConstant.VERSION); - try { - String jsonString = JsonUtils.javaObjectToJsonString(abisInsertRequestDto); - return jsonString.getBytes(); - } catch (JsonProcessingException e) { - description.setStatusComment(AbisHandlerStageConstant.ERROR_IN_ABIS_HANDLER_IDENTIFY_REQUEST); - description.setMessage(PlatformErrorMessages.RPR_ERROR_IN_ABIS_HANDLER_IDENTIFY_REQUEST.getMessage()); - description.setCode(PlatformErrorMessages.RPR_ERROR_IN_ABIS_HANDLER_IDENTIFY_REQUEST.getCode()); - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - "", AbisHandlerStageConstant.ERROR_IN_ABIS_HANDLER_IDENTIFY_REQUEST); - throw new AbisHandlerException(PlatformErrorMessages.RPR_ABIS_INTERNAL_ERROR.getCode(), e); - } - } - - /** - * Gets the uuid. - * - * @return the uuid - */ - private String getUUID() { - return UUID.randomUUID().toString(); - } - - private String getDataShareUrl(String id, String process) throws Exception { - Map> typeAndSubtypMap = createTypeSubtypeMapping(); - List modalities = new ArrayList<>(); - for (Map.Entry> entry : typeAndSubtypMap.entrySet()) { - if (entry.getValue() == null) { - modalities.add(entry.getKey()); - } else { - modalities.addAll(entry.getValue()); - } - } - JSONObject regProcessorIdentityJson = utility - .getRegistrationProcessorMappingJson(MappingJsonConstants.IDENTITY); - String individualBiometricsLabel = JsonUtil.getJSONValue( - JsonUtil.getJSONObject(regProcessorIdentityJson, MappingJsonConstants.INDIVIDUAL_BIOMETRICS), - MappingJsonConstants.VALUE); - BiometricRecord biometricRecord = priorityBasedPacketManagerService.getBiometrics(id, individualBiometricsLabel, - modalities, process, ProviderStageName.BIO_DEDUPE); - - Map tags = packetManagerService.getAllTags(id); - String ageGroup = tags.get("AGE_GROUP"); - Map> biometricModalitySegmentsMap; - if(biometricModalitySegmentsMapforAgeGroup.containsKey(ageGroup)){ - biometricModalitySegmentsMap = biometricModalitySegmentsMapforAgeGroup.get(ageGroup); - } - else { - biometricModalitySegmentsMap = biometricModalitySegmentsMapforAgeGroup.get("DEFAULT"); - } - validateBiometricRecord(biometricRecord, modalities, biometricModalitySegmentsMap, - priorityBasedPacketManagerService.getMetaInfo(id, process, ProviderStageName.BIO_DEDUPE)); - - byte[] content = cbeffutil.createXML(filterExceptionBiometrics(biometricRecord,id,process).getSegments()); - - MultiValueMap map = new LinkedMultiValueMap<>(); - map.add("name", individualBiometricsLabel); - map.add("filename", individualBiometricsLabel); - - ByteArrayResource contentsAsResource = new ByteArrayResource(content) { - @Override - public String getFilename() { - return individualBiometricsLabel; - } - }; - map.add("file", contentsAsResource); - - List pathSegments = new ArrayList<>(); - pathSegments.add(policyId); - pathSegments.add(subscriberId); - String protocol = StringUtils.isNotEmpty(httpProtocol) ? PolicyConstant.HTTP_PROTOCOL : PolicyConstant.HTTPS_PROTOCOL; - String url = null; - - if (!CollectionUtils.isEmpty(datasharePolicies) && datasharePolicies.get(PolicyConstant.SHAREDOMAIN_WRITE) != null) - url = datasharePolicies.get(PolicyConstant.SHAREDOMAIN_WRITE) + env.getProperty(ApiName.DATASHARECREATEURL.name()); - else - url = protocol + internalDomainName + env.getProperty(ApiName.DATASHARECREATEURL.name()); - url = url.replaceAll("[\\[\\]]", ""); - DataShareResponseDto response = (DataShareResponseDto) registrationProcessorRestClientService.postApi(url, - MediaType.MULTIPART_FORM_DATA, pathSegments, null, null, map, DataShareResponseDto.class); - if (response == null || (response.getErrors() != null && response.getErrors().size() > 0)) - throw new DataShareException( - response == null ? "Datashare response is null" : response.getErrors().get(0).getMessage()); - - return response.getDataShare().getUrl(); - } - - @SuppressWarnings("deprecation") - private void validateBiometricRecord(BiometricRecord biometricRecord, List modalities, - Map> biometricModalitySegmentsMap, Map metaInfoMap) - throws DataShareException, JsonParseException, JsonMappingException, IOException { - if (modalities == null || modalities.isEmpty()) { - throw new DataShareException("Data Share Policy Modalities were Empty"); - } - if (biometricRecord == null || biometricRecord.getSegments() == null - || biometricRecord.getSegments().isEmpty()) { - throw new DataShareException("No Biometrics Found with Data Share Policy"); - } - Map> metaInfoExceptionBiometrics = metaInfoMap != null - && metaInfoMap.containsKey("exceptionBiometrics") - ? mapper.readValue(metaInfoMap.get("exceptionBiometrics"), - new TypeReference>>() { - }) - : null; - Set exceptionList = null; - if (metaInfoExceptionBiometrics != null && metaInfoExceptionBiometrics.containsKey("applicant")) { - exceptionList = metaInfoExceptionBiometrics.get("applicant").keySet(); - } - boolean isBioFound = false; - for (String biometricSegment : biometricModalitySegmentsMap.keySet()) { - if (!modalities.contains(biometricSegment)) { - throw new DataShareException("Biometrics Segments Not Configured for modality : " + biometricSegment); - } - for (String segment : biometricModalitySegmentsMap.get(biometricSegment)) { - Optional optionalBIR = Optional.empty(); - if (segment.equalsIgnoreCase("Face")) { - optionalBIR = biometricRecord.getSegments().stream() - .filter(bir -> bir.getBdbInfo().getType() != null - && bir.getBdbInfo().getType().get(0).equals(BiometricType.FACE)) - .findFirst(); - } else { - String[] segmentArray = segment.split(" "); - optionalBIR = biometricRecord.getSegments().stream() - .filter(bir -> bir.getBdbInfo().getSubtype()!=null && bir.getBdbInfo().getSubtype().size() == segmentArray.length - ? (bir.getBdbInfo().getSubtype().get(0).equalsIgnoreCase(segmentArray[0]) - && (segmentArray.length == 2 - ? bir.getBdbInfo().getSubtype().get(1) - .equalsIgnoreCase(segmentArray[1]) - : true)) - : false) - .findFirst(); - } - if (optionalBIR.isPresent()) { - BIR bir = optionalBIR.get(); - Map othersMap = new HashMap(); - if (bir.getOthers() != null) { - othersMap = bir.getOthers().entrySet().stream() - .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue())); - } - - if (bir.getBdb() != null) { - isBioFound = true; - } else if ((othersMap == null || !othersMap.containsKey("EXCEPTION")) ? true - : !(Boolean.parseBoolean(othersMap.get("EXCEPTION")))) { - throw new DataShareException("Biometric BDB Not Found : " + segment); - } - } else if (exceptionList == null || !exceptionList.contains(exceptionSegmentsMap.get(segment))) { - throw new DataShareException("Biometrics/Exceptions Not Found : " + segment); - } - } - } - if (!isBioFound) { - throw new DataShareException("No Biometric Matched with Data Share Policy"); - } - } - - private BiometricRecord filterExceptionBiometrics(BiometricRecord biometricRecord, String id, String process) - throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException, - JSONException - { - - String version = getRegClientVersionFromMetaInfo(id, process, priorityBasedPacketManagerService.getMetaInfo(id, process, ProviderStageName.BIO_DEDUPE)); - if (regClientVersionsBeforeCbeffOthersAttritube.contains(version)) { - return biometricRecord; - } - List segments = biometricRecord.getSegments().stream().filter(bio -> { - Map othersMap = bio.getOthers().entrySet().stream() - .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue())); - return (othersMap == null || !othersMap.containsKey("EXCEPTION")) ? true - : !(Boolean.parseBoolean(othersMap.get("EXCEPTION"))); - }).collect(Collectors.toList()); - BiometricRecord biorecord = new BiometricRecord(); - biorecord.setSegments(segments); - return biorecord; - } - - private String getRegClientVersionFromMetaInfo(String id, String process, Map metaInfoMap) - throws ApisResourceAccessException, PacketManagerException, IOException, JSONException { - String metadata = metaInfoMap.get(JsonConstant.METADATA); - String version = null; - if (StringUtils.isNotEmpty(metadata)) { - JSONArray jsonArray = new JSONArray(metadata); - - for (int i = 0; i < jsonArray.length(); i++) { - if (!jsonArray.isNull(i)) { - org.json.JSONObject jsonObject = (org.json.JSONObject) jsonArray.get(i); - FieldValue fieldValue = mapper.readValue(jsonObject.toString(), FieldValue.class); - if (fieldValue.getLabel().equalsIgnoreCase(JsonConstant.REGCLIENTVERSION)) { - version = fieldValue.getValue(); - break; - } - } - } - } - return version; - } - - public Map> createTypeSubtypeMapping() throws ApisResourceAccessException, DataShareException, - IOException { - - // Call only once and use cache - if (!CollectionUtils.isEmpty(typeAndSubTypeMap) && !CollectionUtils.isEmpty(datasharePolicies)) - return typeAndSubTypeMap; - - ResponseWrapper policyResponse = (ResponseWrapper) registrationProcessorRestClientService.getApi( - ApiName.PMS, Lists.newArrayList(policyId, PolicyConstant.PARTNER_ID, subscriberId), "", "", - ResponseWrapper.class); - if (policyResponse == null || (policyResponse.getErrors() != null && policyResponse.getErrors().size() > 0)) { - throw new DataShareException(policyResponse == null ? "Policy Response response is null" - : policyResponse.getErrors().get(0).getMessage()); - - } else { - LinkedHashMap responseMap = (LinkedHashMap) policyResponse.getResponse(); - LinkedHashMap policies = (LinkedHashMap) responseMap - .get(PolicyConstant.POLICIES); - List attributes = (List) policies.get(PolicyConstant.SHAREABLE_ATTRIBUTES); - datasharePolicies = (LinkedHashMap) policies.get(PolicyConstant.DATASHARE_POLICIES); - ShareableAttributes shareableAttributes = mapper.readValue(mapper.writeValueAsString(attributes.get(0)), - ShareableAttributes.class); - for (Source source : shareableAttributes.getSource()) { - List filterList = source.getFilter(); - if (filterList != null && !filterList.isEmpty()) { - - filterList.forEach(filter -> { - if (filter.getSubType() != null && !filter.getSubType().isEmpty()) { - typeAndSubTypeMap.put(filter.getType(), filter.getSubType()); - } else { - typeAndSubTypeMap.put(filter.getType(), null); - } - }); - } - } - } - return typeAndSubTypeMap; - - } - - private void updateErrorFlags(InternalRegistrationStatusDto registrationStatusDto, MessageDTO object) { - object.setInternalError(true); - if (registrationStatusDto.getLatestTransactionStatusCode() - .equalsIgnoreCase(RegistrationTransactionStatusCode.REPROCESS.toString())) { - object.setIsValid(true); - } else { - object.setIsValid(false); - } - } +package io.mosip.registration.processor.abis.handler.stage; + +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 java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.stream.Collectors; + +import org.apache.commons.lang3.exception.ExceptionUtils; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.simple.JSONObject; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.cloud.context.config.annotation.RefreshScope; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.env.Environment; +import org.springframework.core.io.ByteArrayResource; +import org.springframework.http.MediaType; +import org.springframework.stereotype.Service; +import org.springframework.util.CollectionUtils; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; + +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.common.collect.Lists; + +import io.mosip.kernel.biometrics.constant.BiometricType; +import io.mosip.kernel.biometrics.entities.BIR; +import io.mosip.kernel.biometrics.entities.BiometricRecord; +import io.mosip.kernel.biometrics.spi.CbeffUtil; +import io.mosip.kernel.core.logger.spi.Logger; +import io.mosip.kernel.core.util.DateUtils; +import io.mosip.kernel.core.util.JsonUtils; +import io.mosip.kernel.core.util.StringUtils; +import io.mosip.kernel.core.util.exception.JsonProcessingException; +import io.mosip.registration.processor.abis.handler.constant.AbisHandlerStageConstant; +import io.mosip.registration.processor.abis.handler.dto.DataShareResponseDto; +import io.mosip.registration.processor.abis.handler.exception.AbisHandlerException; +import io.mosip.registration.processor.abis.handler.exception.DataShareException; +import io.mosip.registration.processor.abis.queue.dto.AbisQueueDetails; +import io.mosip.registration.processor.core.abstractverticle.MessageBusAddress; +import io.mosip.registration.processor.core.abstractverticle.MessageDTO; +import io.mosip.registration.processor.core.abstractverticle.MosipEventBus; +import io.mosip.registration.processor.core.abstractverticle.MosipRouter; +import io.mosip.registration.processor.core.abstractverticle.MosipVerticleAPIManager; +import io.mosip.registration.processor.core.code.AbisStatusCode; +import io.mosip.registration.processor.core.code.ApiName; +import io.mosip.registration.processor.core.code.EventId; +import io.mosip.registration.processor.core.code.EventName; +import io.mosip.registration.processor.core.code.EventType; +import io.mosip.registration.processor.core.code.ModuleName; +import io.mosip.registration.processor.core.code.RegistrationTransactionStatusCode; +import io.mosip.registration.processor.core.constant.JsonConstant; +import io.mosip.registration.processor.core.constant.LoggerFileConstant; +import io.mosip.registration.processor.core.constant.MappingJsonConstants; +import io.mosip.registration.processor.core.constant.PolicyConstant; +import io.mosip.registration.processor.core.constant.ProviderStageName; +import io.mosip.registration.processor.core.exception.ApisResourceAccessException; +import io.mosip.registration.processor.core.exception.PacketManagerException; +import io.mosip.registration.processor.core.exception.util.PlatformErrorMessages; +import io.mosip.registration.processor.core.exception.util.PlatformSuccessMessages; +import io.mosip.registration.processor.core.http.ResponseWrapper; +import io.mosip.registration.processor.core.logger.LogDescription; +import io.mosip.registration.processor.core.logger.RegProcessorLogger; +import io.mosip.registration.processor.core.packet.dto.FieldValue; +import io.mosip.registration.processor.core.packet.dto.Identity; +import io.mosip.registration.processor.core.packet.dto.abis.AbisIdentifyRequestDto; +import io.mosip.registration.processor.core.packet.dto.abis.AbisIdentifyRequestGalleryDto; +import io.mosip.registration.processor.core.packet.dto.abis.AbisInsertRequestDto; +import io.mosip.registration.processor.core.packet.dto.abis.AbisRequestDto; +import io.mosip.registration.processor.core.packet.dto.abis.Flag; +import io.mosip.registration.processor.core.packet.dto.abis.ReferenceIdDto; +import io.mosip.registration.processor.core.packet.dto.abis.RegBioRefDto; +import io.mosip.registration.processor.core.packet.dto.abis.RegDemoDedupeListDto; +import io.mosip.registration.processor.core.packet.dto.datashare.Filter; +import io.mosip.registration.processor.core.packet.dto.datashare.ShareableAttributes; +import io.mosip.registration.processor.core.packet.dto.datashare.Source; +import io.mosip.registration.processor.core.spi.packetmanager.PacketInfoManager; +import io.mosip.registration.processor.core.spi.restclient.RegistrationProcessorRestClientService; +import io.mosip.registration.processor.core.status.util.StatusUtil; +import io.mosip.registration.processor.core.status.util.TrimExceptionMessage; +import io.mosip.registration.processor.core.util.JsonUtil; +import io.mosip.registration.processor.packet.storage.dto.ApplicantInfoDto; +import io.mosip.registration.processor.packet.storage.utils.PacketManagerService; +import io.mosip.registration.processor.packet.storage.utils.PriorityBasedPacketManagerService; +import io.mosip.registration.processor.packet.storage.utils.Utilities; +import io.mosip.registration.processor.rest.client.audit.builder.AuditLogRequestBuilder; +import io.mosip.registration.processor.status.dto.InternalRegistrationStatusDto; +import io.mosip.registration.processor.status.dto.RegistrationStatusDto; +import io.mosip.registration.processor.status.service.RegistrationStatusService; + +/** + * The Class AbisHandlerStage. + * + * @author M1048358 Alok + */ +@RefreshScope +@Service +@Configuration +@ComponentScan(basePackages = { "${mosip.auth.adapter.impl.basepackage}", + "io.mosip.registration.processor.abis.handler.config", + "io.mosip.registration.processor.status.config", "io.mosip.registration.processor.rest.client.config", + "io.mosip.registration.processor.packet.storage.config", "io.mosip.registration.processor.core.config", + "io.mosip.registration.processor.core.kernel.beans", "io.mosip.kernel.packetmanager.config" }) +public class AbisHandlerStage extends MosipVerticleAPIManager { + + private static final String STAGE_PROPERTY_PREFIX = "mosip.regproc.abis.handler."; + private Map> typeAndSubTypeMap = new HashMap<>(); + LinkedHashMap datasharePolicies = null; + + /** The cluster manager url. */ + @Value("${vertx.cluster.configuration}") + private String clusterManagerUrl; + + /** The max results. */ + @Value("${registration.processor.abis.maxResults}") + private String maxResults; + + /** The target FPIR. */ + @Value("${registration.processor.abis.targetFPIR}") + private String targetFPIR; + + /** worker pool size. */ + @Value("${worker.pool.size}") + private Integer workerPoolSize; + + /** + * After this time intervel, message should be considered as expired (In + * seconds). + */ + @Value("${mosip.regproc.abis.handler.message.expiry-time-limit}") + private Long messageExpiryTimeLimit; + + @Value("${registration.processor.policy.id}") + private String policyId; + + @Value("${registration.processor.subscriber.id}") + private String subscriberId; + + @Value("${mosip.regproc.data.share.protocol}") + private String httpProtocol; + + @Value("${mosip.regproc.data.share.internal.domain.name}") + private String internalDomainName; + + @Value("#{${mosip.regproc.abis.handler.biometric-modalities-segments-mapping-for-age-group}}") + private Map>> biometricModalitySegmentsMapforAgeGroup; + + @Value("#{${mosip.regproc.abis.handler.biometric-segments-exceptions-mapping}}") + private Map exceptionSegmentsMap; + + @Autowired + private RegistrationProcessorRestClientService registrationProcessorRestClientService; + + /** The reg proc logger. */ + private static Logger regProcLogger = RegProcessorLogger.getLogger(AbisHandlerStage.class); + + /** The core audit request builder. */ + @Autowired + private AuditLogRequestBuilder auditLogRequestBuilder; + + /** The registration status service. */ + @Autowired + private RegistrationStatusService registrationStatusService; + + /** The packet info manager. */ + @Autowired + private PacketInfoManager packetInfoManager; + + @Autowired + private PacketManagerService packetManagerService; + + @Autowired + private Utilities utility; + + @Autowired + private ObjectMapper mapper; + + /** The mosip event bus. */ + MosipEventBus mosipEventBus = null; + + /** Mosip router for APIs */ + @Autowired + MosipRouter router; + + @Autowired + private CbeffUtil cbeffutil; + + @Autowired + private Environment env; + + @Autowired + private PriorityBasedPacketManagerService priorityBasedPacketManagerService; + + private static final String DATASHARECREATEURL = "DATASHARECREATEURL"; + + private static final String DATETIME_PATTERN = "mosip.registration.processor.datetime.pattern"; + + @Value("#{T(java.util.Arrays).asList('${mosip.regproc.common.before-cbeff-others-attibute.reg-client-versions:}')}") + private List regClientVersionsBeforeCbeffOthersAttritube; + + /** + * Deploy verticle. + */ + public void deployVerticle() { + mosipEventBus = this.getEventBus(this, clusterManagerUrl, workerPoolSize); + this.consumeAndSend(mosipEventBus, MessageBusAddress.ABIS_HANDLER_BUS_IN, + MessageBusAddress.ABIS_HANDLER_BUS_OUT, messageExpiryTimeLimit); + } + + @Override + public void start() { + router.setRoute(this.postUrl(getVertx(), MessageBusAddress.ABIS_HANDLER_BUS_IN, + MessageBusAddress.ABIS_HANDLER_BUS_OUT)); + this.createServer(router.getRouter(), getPort()); + } + + @Override + protected String getPropertyPrefix() { + return STAGE_PROPERTY_PREFIX; + } + + /* + * (non-Javadoc) + * + * @see + * io.mosip.registration.processor.core.spi.eventbus.EventBusManager#process( + * java.lang.Object) + */ + @Override + public MessageDTO process(MessageDTO object) { + TrimExceptionMessage trimExceptionMessage = new TrimExceptionMessage(); + LogDescription description = new LogDescription(); + object.setMessageBusAddress(MessageBusAddress.ABIS_HANDLER_BUS_IN); + object.setIsValid(Boolean.TRUE); + Boolean isTransactionSuccessful = false; + String regId = object.getRid(); + object.setInternalError(Boolean.FALSE); + InternalRegistrationStatusDto registrationStatusDto = null; + String transactionTypeCode = null; + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + regId, "AbisHandlerStage::process()::entry"); + try { + registrationStatusDto = registrationStatusService.getRegistrationStatus(regId, object.getReg_type(), + object.getIteration(), object.getWorkflowInstanceId()); + transactionTypeCode = registrationStatusDto.getLatestTransactionTypeCode(); + String transactionId = registrationStatusDto.getLatestRegistrationTransactionId(); + + Boolean isIdentifyRequestPresent = packetInfoManager.getIdentifyByTransactionId(transactionId, + AbisHandlerStageConstant.IDENTIFY); + + if (!isIdentifyRequestPresent) { + List abisQueueDetails = utility.getAbisQueueDetails(); + if (abisQueueDetails.isEmpty()) { + description.setStatusComment(AbisHandlerStageConstant.DETAILS_NOT_FOUND); + description.setMessage(PlatformErrorMessages.RPR_DETAILS_NOT_FOUND.getMessage()); + description.setCode(PlatformErrorMessages.RPR_DETAILS_NOT_FOUND.getCode()); + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString(), "", + AbisHandlerStageConstant.DETAILS_NOT_FOUND); + throw new AbisHandlerException(PlatformErrorMessages.RPR_ABIS_INTERNAL_ERROR.getCode()); + } + createRequest(regId, abisQueueDetails, transactionId, registrationStatusDto.getRegistrationType(),registrationStatusDto.getIteration(), + registrationStatusDto.getWorkflowInstanceId(), description, transactionTypeCode); + object.setMessageBusAddress(MessageBusAddress.ABIS_MIDDLEWARE_BUS_IN); + } else { + if (transactionTypeCode.equalsIgnoreCase(AbisHandlerStageConstant.DEMOGRAPHIC_VERIFICATION)) { + object.setMessageBusAddress(MessageBusAddress.DEMO_DEDUPE_BUS_IN); + } else if (transactionTypeCode.equalsIgnoreCase(AbisHandlerStageConstant.BIOGRAPHIC_VERIFICATION)) { + object.setMessageBusAddress(MessageBusAddress.BIO_DEDUPE_BUS_IN); + } + } + description.setStatusComment(AbisHandlerStageConstant.ABIS_HANDLER_SUCCESS); + description.setMessage(PlatformSuccessMessages.RPR_ABIS_HANDLER_STAGE_SUCCESS.getMessage()); + description.setCode(PlatformSuccessMessages.RPR_ABIS_HANDLER_STAGE_SUCCESS.getCode()); + isTransactionSuccessful = true; + regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + regId, description.getMessage()); + } catch (Exception e) { + + if (e instanceof DataShareException) { + object.setIsValid(false); + } + description.setStatusComment(AbisHandlerStageConstant.ERROR_IN_ABIS_HANDLER); + description.setMessage(PlatformErrorMessages.RPR_MESSAGE_SENDER_STAGE_FAILED.getMessage()); + description.setCode(PlatformErrorMessages.RPR_MESSAGE_SENDER_STAGE_FAILED.getCode()); + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + regId, ExceptionUtils.getStackTrace(e)); + object.setInternalError(Boolean.TRUE); + registrationStatusDto + .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.REPROCESS.toString()); + registrationStatusDto.setSubStatusCode(StatusUtil.SYSTEM_EXCEPTION_OCCURED.getCode()); + if (transactionTypeCode.equalsIgnoreCase(AbisHandlerStageConstant.DEMOGRAPHIC_VERIFICATION)) { + registrationStatusDto.setRegistrationStageName(AbisHandlerStageConstant.DEMO_DEDUPE_STAGE); + } else if (transactionTypeCode.equalsIgnoreCase(AbisHandlerStageConstant.BIOGRAPHIC_VERIFICATION)) { + registrationStatusDto.setRegistrationStageName(AbisHandlerStageConstant.BIO_DEDUPE_STAGE); + } + registrationStatusDto.setStatusComment(trimExceptionMessage + .trimExceptionMessage(StatusUtil.UNKNOWN_EXCEPTION_OCCURED.getMessage() + e.getMessage())); + String moduleId = description.getCode(); + String moduleName = ModuleName.ABIS_HANDLER.toString(); + registrationStatusService.updateRegistrationStatus(registrationStatusDto, moduleId, moduleName); + } finally { + if (object.getInternalError()) { + updateErrorFlags(registrationStatusDto, object); + } + String eventId = isTransactionSuccessful ? EventId.RPR_402.toString() : EventId.RPR_405.toString(); + String eventName = isTransactionSuccessful ? EventName.UPDATE.toString() : EventName.EXCEPTION.toString(); + String eventType = isTransactionSuccessful ? EventType.BUSINESS.toString() : EventType.SYSTEM.toString(); + + /** Module-Id can be Both Success/Error code */ + String moduleId = isTransactionSuccessful ? PlatformSuccessMessages.RPR_ABIS_HANDLER_STAGE_SUCCESS.getCode() + : description.getCode(); + String moduleName = ModuleName.ABIS_HANDLER.toString(); + + auditLogRequestBuilder.createAuditRequestBuilder(description.getMessage(), eventId, eventName, eventType, + moduleId, moduleName, regId); + + } + + return object; + } + + private void createRequest(String regId, List abisQueueDetails, String transactionId, + String process, int iteration, String workflowInstanceId, LogDescription description, String transactionTypeCode) throws Exception { + String bioRefId = getUUID(); + insertInBioRef(regId, bioRefId,process,iteration, workflowInstanceId); + createInsertRequest(abisQueueDetails, transactionId, bioRefId, regId, process, description); + createIdentifyRequest(abisQueueDetails, transactionId, bioRefId, transactionTypeCode, description); + + } + + /** + * Creates the identify request. + * + * @param abisQueueDetails the abis application dto list + * @param transactionId the transaction id + * @param bioRefId the bio ref id + * @param transactionTypeCode the transaction type code + * @param description + */ + private void createIdentifyRequest(List abisQueueDetails, String transactionId, String bioRefId, + String transactionTypeCode, LogDescription description) { + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", + "AbisHandlerStage::createIdentifyRequest()::entry"); + String batchId = getUUID(); + for (AbisQueueDetails abisQueue : abisQueueDetails) { + AbisRequestDto abisRequestDto = new AbisRequestDto(); + String id = getUUID(); + abisRequestDto.setId(id); + abisRequestDto.setAbisAppCode(abisQueue.getName()); + abisRequestDto.setBioRefId(bioRefId); + abisRequestDto.setRequestType(AbisHandlerStageConstant.IDENTIFY); + abisRequestDto.setReqBatchId(batchId); + abisRequestDto.setRefRegtrnId(transactionId); + + byte[] abisIdentifyRequestBytes = getIdentifyRequestBytes(transactionId, bioRefId, transactionTypeCode, id, + description); + abisRequestDto.setReqText(abisIdentifyRequestBytes); + + abisRequestDto.setStatusCode(RegistrationTransactionStatusCode.IN_PROGRESS.toString()); + abisRequestDto.setStatusComment(null); + abisRequestDto.setLangCode(AbisHandlerStageConstant.ENG); + abisRequestDto.setCrBy(AbisHandlerStageConstant.USER); + abisRequestDto.setUpdBy(null); + abisRequestDto.setIsDeleted(Boolean.FALSE); + + String moduleId = PlatformSuccessMessages.RPR_ABIS_HANDLER_STAGE_SUCCESS.getCode(); + String moduleName = ModuleName.ABIS_HANDLER.toString(); + packetInfoManager.saveAbisRequest(abisRequestDto, moduleId, moduleName); + } + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", + "AbisHandlerStage::createIdentifyRequest()::exit"); + } + + /** + * Gets the identify request bytes. + * + * @param transactionId the transaction id + * @param bioRefId the bio ref id + * @param transactionTypeCode the transaction type code + * @param id the id + * @param description + * @return the identify request bytes + */ + private byte[] getIdentifyRequestBytes(String transactionId, String bioRefId, String transactionTypeCode, String id, + LogDescription description) { + AbisIdentifyRequestDto abisIdentifyRequestDto = new AbisIdentifyRequestDto(); + Flag flag = new Flag(); + abisIdentifyRequestDto.setId(AbisHandlerStageConstant.MOSIP_ABIS_IDENTIFY); + abisIdentifyRequestDto.setVersion(AbisHandlerStageConstant.VERSION); + abisIdentifyRequestDto.setRequestId(id); + abisIdentifyRequestDto.setReferenceId(bioRefId); + abisIdentifyRequestDto.setReferenceUrl(""); + abisIdentifyRequestDto.setRequesttime(DateUtils.getUTCCurrentDateTimeString(env.getProperty(DATETIME_PATTERN))); + flag.setMaxResults(maxResults); + flag.setTargetFPIR(targetFPIR); + abisIdentifyRequestDto.setFlags(flag); + + // Added Gallery data for demo dedupe + if (transactionTypeCode.equalsIgnoreCase(AbisHandlerStageConstant.DEMOGRAPHIC_VERIFICATION)) { + List regDemoDedupeListDtoList = packetInfoManager + .getDemoListByTransactionId(transactionId); + if (regDemoDedupeListDtoList.isEmpty()) { + description.setStatusComment(AbisHandlerStageConstant.NO_RECORD_FOUND); + description.setMessage(PlatformErrorMessages.RPR_NO_RECORD_FOUND.getMessage()); + description.setCode(PlatformErrorMessages.RPR_NO_RECORD_FOUND.getCode()); + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString(), "", + "Potential Match Records are Not Found for Demo Dedupe Potential Match"); + throw new AbisHandlerException(description.getMessage()); + } + List referenceIdDtos = new ArrayList<>(); + + for (RegDemoDedupeListDto dedupeListDto : regDemoDedupeListDtoList) { + ReferenceIdDto dto = new ReferenceIdDto(); + List regBioRefDto = packetInfoManager.getBioRefIdByRegId(dedupeListDto.getMatchedRegId()); + if (!CollectionUtils.isEmpty(regBioRefDto)) { + dto.setReferenceId(regBioRefDto.get(0).getBioRefId()); + } + + referenceIdDtos.add(dto); + } + AbisIdentifyRequestGalleryDto galleryDto = new AbisIdentifyRequestGalleryDto(); + galleryDto.setReferenceIds(referenceIdDtos); + abisIdentifyRequestDto.setGallery(galleryDto); + } + + try { + String jsonString = JsonUtils.javaObjectToJsonString(abisIdentifyRequestDto); + return jsonString.getBytes(); + } catch (JsonProcessingException e) { + description.setStatusComment(AbisHandlerStageConstant.ERROR_IN_ABIS_HANDLER_IDENTIFY_REQUEST); + description.setMessage(PlatformErrorMessages.RPR_ERROR_IN_ABIS_HANDLER_IDENTIFY_REQUEST.getMessage()); + description.setCode(PlatformErrorMessages.RPR_ERROR_IN_ABIS_HANDLER_IDENTIFY_REQUEST.getCode()); + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + "", AbisHandlerStageConstant.ERROR_IN_ABIS_HANDLER_IDENTIFY_REQUEST); + throw new AbisHandlerException(PlatformErrorMessages.RPR_ABIS_INTERNAL_ERROR.getCode(), e); + } + } + + /** + * Insert in bio ref. + * + * @param regId the reg id + * @param bioRefId the bio ref id + */ + private void insertInBioRef(String regId, String bioRefId, String process, int iteration, String workflowInstanceId) { + RegBioRefDto regBioRefDto = new RegBioRefDto(); + regBioRefDto.setBioRefId(bioRefId); + regBioRefDto.setCrBy(AbisHandlerStageConstant.USER); + regBioRefDto.setIsActive(Boolean.TRUE); + regBioRefDto.setIsDeleted(Boolean.FALSE); + regBioRefDto.setRegId(regId); + regBioRefDto.setUpdBy(null); + regBioRefDto.setProcess(process); + regBioRefDto.setIteration(iteration); + regBioRefDto.setWorkflowInstanceId(workflowInstanceId); + String moduleId = PlatformSuccessMessages.RPR_ABIS_HANDLER_STAGE_SUCCESS.getCode(); + String moduleName = ModuleName.ABIS_HANDLER.toString(); + packetInfoManager.saveBioRef(regBioRefDto, moduleId, moduleName); + } + + /** + * Creates the insert request. + * + * @param abisQueueDetails the abis application dto list + * @param transactionId the transaction id + * @param bioRefId the bio ref id + * @param regId the reg id + * @param description + */ + private void createInsertRequest(List abisQueueDetails, String transactionId, String bioRefId, + String regId, String process, LogDescription description) throws Exception { + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + regId, "AbisHandlerStage::createInsertRequest()::entry"); + String batchId = getUUID(); + List abisProcessedInsertAppCodeList = packetInfoManager.getAbisProcessedRequestsAppCodeByBioRefId( + bioRefId, AbisStatusCode.INSERT.toString(), AbisStatusCode.PROCESSED.toString()); + List abisAppCodeList = new ArrayList<>(); + for (AbisQueueDetails abisQueue : abisQueueDetails) { + abisAppCodeList.add(abisQueue.getName()); + } + + for (String appCode : abisAppCodeList) { + + AbisRequestDto abisRequestDto = new AbisRequestDto(); + String id = getUUID(); + abisRequestDto.setId(id); + abisRequestDto.setAbisAppCode(appCode); + abisRequestDto.setBioRefId(bioRefId); + abisRequestDto.setRequestType(AbisHandlerStageConstant.INSERT); + abisRequestDto.setReqBatchId(batchId); + abisRequestDto.setRefRegtrnId(transactionId); + + + abisRequestDto.setStatusCode(AbisStatusCode.IN_PROGRESS.toString()); + abisRequestDto.setStatusComment(null); + abisRequestDto.setLangCode(AbisHandlerStageConstant.ENG); + abisRequestDto.setCrBy(AbisHandlerStageConstant.USER); + abisRequestDto.setUpdBy(null); + abisRequestDto.setIsDeleted(Boolean.FALSE); + String moduleId = PlatformSuccessMessages.RPR_ABIS_HANDLER_STAGE_SUCCESS.getCode(); + String moduleName = ModuleName.ABIS_HANDLER.toString(); + byte[] abisInsertRequestBytes =null; + if (abisProcessedInsertAppCodeList != null && abisProcessedInsertAppCodeList.contains(appCode)) { + + abisInsertRequestBytes = getInsertRequestBytes(regId, id, process, bioRefId, description, + AbisStatusCode.ALREADY_PROCESSED.toString()); + abisRequestDto.setStatusCode(AbisStatusCode.ALREADY_PROCESSED.toString()); + + } else { + abisInsertRequestBytes = getInsertRequestBytes(regId, id, process, bioRefId, description, + AbisStatusCode.IN_PROGRESS.toString()); + abisRequestDto.setStatusCode(AbisStatusCode.IN_PROGRESS.toString()); + + } + abisRequestDto.setReqText(abisInsertRequestBytes); + packetInfoManager.saveAbisRequest(abisRequestDto, moduleId, moduleName); + } + + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", + "AbisHandlerStage::createInsertRequest()::exit"); + } + + /** + * Gets the insert request bytes. + * + * @param regId the reg id + * @param id the id + * @param bioRefId the bio ref id + * @param description + * @param status + * @return the insert request bytes + */ + private byte[] getInsertRequestBytes(String regId, String id, String process, String bioRefId, + LogDescription description, String status) throws Exception { + AbisInsertRequestDto abisInsertRequestDto = new AbisInsertRequestDto(); + abisInsertRequestDto.setId(AbisHandlerStageConstant.MOSIP_ABIS_INSERT); + abisInsertRequestDto.setReferenceId(bioRefId); + abisInsertRequestDto.setReferenceURL(status.equalsIgnoreCase(AbisStatusCode.IN_PROGRESS.toString())?getDataShareUrl(regId, process):null); + abisInsertRequestDto.setRequestId(id); + abisInsertRequestDto.setRequesttime(DateUtils.getUTCCurrentDateTimeString(env.getProperty(DATETIME_PATTERN))); + abisInsertRequestDto.setVersion(AbisHandlerStageConstant.VERSION); + try { + String jsonString = JsonUtils.javaObjectToJsonString(abisInsertRequestDto); + return jsonString.getBytes(); + } catch (JsonProcessingException e) { + description.setStatusComment(AbisHandlerStageConstant.ERROR_IN_ABIS_HANDLER_IDENTIFY_REQUEST); + description.setMessage(PlatformErrorMessages.RPR_ERROR_IN_ABIS_HANDLER_IDENTIFY_REQUEST.getMessage()); + description.setCode(PlatformErrorMessages.RPR_ERROR_IN_ABIS_HANDLER_IDENTIFY_REQUEST.getCode()); + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + "", AbisHandlerStageConstant.ERROR_IN_ABIS_HANDLER_IDENTIFY_REQUEST); + throw new AbisHandlerException(PlatformErrorMessages.RPR_ABIS_INTERNAL_ERROR.getCode(), e); + } + } + + /** + * Gets the uuid. + * + * @return the uuid + */ + private String getUUID() { + return UUID.randomUUID().toString(); + } + + private String getDataShareUrl(String id, String process) throws Exception { + Map> policyTypeAndSubTypeMap = createTypeSubtypeMapping(); + List modalities = new ArrayList<>(); + List policyTypeAndSubTypeList = new ArrayList<>(); + modalities.addAll(policyTypeAndSubTypeMap.keySet()); + for (Map.Entry> entry : policyTypeAndSubTypeMap.entrySet()) { + if (entry.getValue() == null) { + policyTypeAndSubTypeList.add(entry.getKey()); + } else { + policyTypeAndSubTypeList.addAll(entry.getValue()); + } + } + JSONObject regProcessorIdentityJson = utility + .getRegistrationProcessorMappingJson(MappingJsonConstants.IDENTITY); + String individualBiometricsLabel = JsonUtil.getJSONValue( + JsonUtil.getJSONObject(regProcessorIdentityJson, MappingJsonConstants.INDIVIDUAL_BIOMETRICS), + MappingJsonConstants.VALUE); + BiometricRecord biometricRecord = priorityBasedPacketManagerService.getBiometrics(id, individualBiometricsLabel, + policyTypeAndSubTypeList, process, ProviderStageName.BIO_DEDUPE); + + Map tags = packetManagerService.getAllTags(id); + String ageGroup = tags.get("AGE_GROUP"); + Map> ageGroupModalitySegmentMap; + if(biometricModalitySegmentsMapforAgeGroup.containsKey(ageGroup)){ + ageGroupModalitySegmentMap = biometricModalitySegmentsMapforAgeGroup.get(ageGroup); + } + else { + ageGroupModalitySegmentMap = biometricModalitySegmentsMapforAgeGroup.get("DEFAULT"); + } + validateBiometricRecord(biometricRecord, modalities, ageGroupModalitySegmentMap, + priorityBasedPacketManagerService.getMetaInfo(id, process, ProviderStageName.BIO_DEDUPE), + policyTypeAndSubTypeMap); + + byte[] content = cbeffutil.createXML(filterExceptionBiometrics(biometricRecord,id,process).getSegments()); + + MultiValueMap map = new LinkedMultiValueMap<>(); + map.add("name", individualBiometricsLabel); + map.add("filename", individualBiometricsLabel); + + ByteArrayResource contentsAsResource = new ByteArrayResource(content) { + @Override + public String getFilename() { + return individualBiometricsLabel; + } + }; + map.add("file", contentsAsResource); + + List pathSegments = new ArrayList<>(); + pathSegments.add(policyId); + pathSegments.add(subscriberId); + String protocol = StringUtils.isNotEmpty(httpProtocol) ? PolicyConstant.HTTP_PROTOCOL : PolicyConstant.HTTPS_PROTOCOL; + String url = null; + + if (!CollectionUtils.isEmpty(datasharePolicies) && datasharePolicies.get(PolicyConstant.SHAREDOMAIN_WRITE) != null) + url = datasharePolicies.get(PolicyConstant.SHAREDOMAIN_WRITE) + env.getProperty(ApiName.DATASHARECREATEURL.name()); + else + url = protocol + internalDomainName + env.getProperty(ApiName.DATASHARECREATEURL.name()); + url = url.replaceAll("[\\[\\]]", ""); + DataShareResponseDto response = (DataShareResponseDto) registrationProcessorRestClientService.postApi(url, + MediaType.MULTIPART_FORM_DATA, pathSegments, null, null, map, DataShareResponseDto.class); + if (response == null || (response.getErrors() != null && response.getErrors().size() > 0)) + throw new DataShareException( + response == null ? "Datashare response is null" : response.getErrors().get(0).getMessage()); + + return response.getDataShare().getUrl(); + } + + @SuppressWarnings("deprecation") + private void validateBiometricRecord(BiometricRecord biometricRecord, List modalities, + Map> ageGroupModalitySegmentMap, Map metaInfoMap, + Map> policyTypeAndSubTypeMap) + throws DataShareException, JsonParseException, JsonMappingException, IOException { + if (modalities == null || modalities.isEmpty()) { + throw new DataShareException("Data Share Policy Modalities were Empty"); + } + if (biometricRecord == null || biometricRecord.getSegments() == null + || biometricRecord.getSegments().isEmpty()) { + throw new DataShareException("No Biometrics Found with Data Share Policy"); + } + Map> metaInfoExceptionBiometrics = metaInfoMap != null + && metaInfoMap.containsKey("exceptionBiometrics") + ? mapper.readValue(metaInfoMap.get("exceptionBiometrics"), + new TypeReference>>() { + }) + : null; + Set exceptionList = null; + if (metaInfoExceptionBiometrics != null && metaInfoExceptionBiometrics.containsKey("applicant")) { + exceptionList = metaInfoExceptionBiometrics.get("applicant").keySet(); + } + boolean isBioFound = false; + for (String biometricModality : ageGroupModalitySegmentMap.keySet()) { + if (!modalities.contains(biometricModality)) { + throw new DataShareException( + "Modalities not Configured as per policy for modality : " + biometricModality); + } + List policySegmentList = policyTypeAndSubTypeMap.get(biometricModality); + for (String segment : ageGroupModalitySegmentMap.get(biometricModality)) { + if (policySegmentList != null + && !policySegmentList.contains(segment)) { + throw new DataShareException( + "Biometrics Segments Not Configured as per policy for modality : " + biometricModality); + } + Optional optionalBIR = Optional.empty(); + if (segment.equalsIgnoreCase("Face")) { + optionalBIR = biometricRecord.getSegments().stream() + .filter(bir -> bir.getBdbInfo().getType() != null + && bir.getBdbInfo().getType().get(0).equals(BiometricType.FACE)) + .findFirst(); + } else { + String[] segmentArray = segment.split(" "); + optionalBIR = biometricRecord.getSegments().stream() + .filter(bir -> bir.getBdbInfo().getSubtype()!=null && bir.getBdbInfo().getSubtype().size() == segmentArray.length + ? (bir.getBdbInfo().getSubtype().get(0).equalsIgnoreCase(segmentArray[0]) + && (segmentArray.length == 2 + ? bir.getBdbInfo().getSubtype().get(1) + .equalsIgnoreCase(segmentArray[1]) + : true)) + : false) + .findFirst(); + } + if (optionalBIR.isPresent()) { + BIR bir = optionalBIR.get(); + Map othersMap = new HashMap(); + if (bir.getOthers() != null) { + othersMap = bir.getOthers().entrySet().stream() + .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue())); + } + + if (bir.getBdb() != null) { + isBioFound = true; + } else if ((othersMap == null || !othersMap.containsKey("EXCEPTION")) ? true + : !(Boolean.parseBoolean(othersMap.get("EXCEPTION")))) { + throw new DataShareException("Biometric BDB Not Found : " + segment); + } + } else if (exceptionList == null || !exceptionList.contains(exceptionSegmentsMap.get(segment))) { + throw new DataShareException("Biometrics/Exceptions Not Found : " + segment); + } + } + } + if (!isBioFound) { + throw new DataShareException("No Biometric Matched with Data Share Policy"); + } + } + + private BiometricRecord filterExceptionBiometrics(BiometricRecord biometricRecord, String id, String process) + throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException, + JSONException + { + + String version = getRegClientVersionFromMetaInfo(id, process, priorityBasedPacketManagerService.getMetaInfo(id, process, ProviderStageName.BIO_DEDUPE)); + if (regClientVersionsBeforeCbeffOthersAttritube.contains(version)) { + return biometricRecord; + } + List segments = biometricRecord.getSegments().stream().filter(bio -> { + Map othersMap = bio.getOthers().entrySet().stream() + .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue())); + return (othersMap == null || !othersMap.containsKey("EXCEPTION")) ? true + : !(Boolean.parseBoolean(othersMap.get("EXCEPTION"))); + }).collect(Collectors.toList()); + BiometricRecord biorecord = new BiometricRecord(); + biorecord.setSegments(segments); + return biorecord; + } + + private String getRegClientVersionFromMetaInfo(String id, String process, Map metaInfoMap) + throws ApisResourceAccessException, PacketManagerException, IOException, JSONException { + String metadata = metaInfoMap.get(JsonConstant.METADATA); + String version = null; + if (StringUtils.isNotEmpty(metadata)) { + JSONArray jsonArray = new JSONArray(metadata); + + for (int i = 0; i < jsonArray.length(); i++) { + if (!jsonArray.isNull(i)) { + org.json.JSONObject jsonObject = (org.json.JSONObject) jsonArray.get(i); + FieldValue fieldValue = mapper.readValue(jsonObject.toString(), FieldValue.class); + if (fieldValue.getLabel().equalsIgnoreCase(JsonConstant.REGCLIENTVERSION)) { + version = fieldValue.getValue(); + break; + } + } + } + } + return version; + } + + public Map> createTypeSubtypeMapping() throws ApisResourceAccessException, DataShareException, + IOException { + + // Call only once and use cache + if (!CollectionUtils.isEmpty(typeAndSubTypeMap) && !CollectionUtils.isEmpty(datasharePolicies)) + return typeAndSubTypeMap; + + ResponseWrapper policyResponse = (ResponseWrapper) registrationProcessorRestClientService.getApi( + ApiName.PMS, Lists.newArrayList(policyId, PolicyConstant.PARTNER_ID, subscriberId), "", "", + ResponseWrapper.class); + if (policyResponse == null || (policyResponse.getErrors() != null && policyResponse.getErrors().size() > 0)) { + throw new DataShareException(policyResponse == null ? "Policy Response response is null" + : policyResponse.getErrors().get(0).getMessage()); + + } else { + LinkedHashMap responseMap = (LinkedHashMap) policyResponse.getResponse(); + LinkedHashMap policies = (LinkedHashMap) responseMap + .get(PolicyConstant.POLICIES); + List attributes = (List) policies.get(PolicyConstant.SHAREABLE_ATTRIBUTES); + datasharePolicies = (LinkedHashMap) policies.get(PolicyConstant.DATASHARE_POLICIES); + ShareableAttributes shareableAttributes = mapper.readValue(mapper.writeValueAsString(attributes.get(0)), + ShareableAttributes.class); + for (Source source : shareableAttributes.getSource()) { + List filterList = source.getFilter(); + if (filterList != null && !filterList.isEmpty()) { + + filterList.forEach(filter -> { + if (filter.getSubType() != null && !filter.getSubType().isEmpty()) { + typeAndSubTypeMap.put(filter.getType(), filter.getSubType()); + } else { + typeAndSubTypeMap.put(filter.getType(), null); + } + }); + } + } + } + return typeAndSubTypeMap; + + } + + private void updateErrorFlags(InternalRegistrationStatusDto registrationStatusDto, MessageDTO object) { + object.setInternalError(true); + if (registrationStatusDto.getLatestTransactionStatusCode() + .equalsIgnoreCase(RegistrationTransactionStatusCode.REPROCESS.toString())) { + object.setIsValid(true); + } else { + object.setIsValid(false); + } + } } \ No newline at end of file diff --git a/registration-processor/core-processor/registration-processor-abis-middleware-stage/src/main/java/io/mosip/registartion/processor/abis/middleware/stage/AbisMiddleWareStage.java b/registration-processor/core-processor/registration-processor-abis-middleware-stage/src/main/java/io/mosip/registartion/processor/abis/middleware/stage/AbisMiddleWareStage.java index 9e99e6f6d36..828ab154953 100644 --- a/registration-processor/core-processor/registration-processor-abis-middleware-stage/src/main/java/io/mosip/registartion/processor/abis/middleware/stage/AbisMiddleWareStage.java +++ b/registration-processor/core-processor/registration-processor-abis-middleware-stage/src/main/java/io/mosip/registartion/processor/abis/middleware/stage/AbisMiddleWareStage.java @@ -1,819 +1,819 @@ -package io.mosip.registartion.processor.abis.middleware.stage; - -import java.io.IOException; -import java.time.LocalDateTime; -import java.time.ZoneId; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.stream.Collectors; - -import javax.jms.Message; -import javax.jms.TextMessage; - -import org.apache.activemq.command.ActiveMQBytesMessage; -import org.assertj.core.util.Arrays; -import org.json.simple.JSONObject; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.cloud.context.config.annotation.RefreshScope; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.stereotype.Service; - -import io.mosip.kernel.core.exception.ExceptionUtils; -import io.mosip.kernel.core.logger.spi.Logger; -import io.mosip.registration.processor.abis.queue.dto.AbisQueueDetails; -import io.mosip.registration.processor.core.abstractverticle.MessageBusAddress; -import io.mosip.registration.processor.core.abstractverticle.MessageDTO; -import io.mosip.registration.processor.core.abstractverticle.MosipEventBus; -import io.mosip.registration.processor.core.abstractverticle.MosipRouter; -import io.mosip.registration.processor.core.abstractverticle.MosipVerticleAPIManager; -import io.mosip.registration.processor.core.code.AbisStatusCode; -import io.mosip.registration.processor.core.code.EventId; -import io.mosip.registration.processor.core.code.EventName; -import io.mosip.registration.processor.core.code.EventType; -import io.mosip.registration.processor.core.code.ModuleName; -import io.mosip.registration.processor.core.code.RegistrationTransactionStatusCode; -import io.mosip.registration.processor.core.constant.LoggerFileConstant; -import io.mosip.registration.processor.core.exception.RegistrationProcessorCheckedException; -import io.mosip.registration.processor.core.exception.RegistrationProcessorUnCheckedException; -import io.mosip.registration.processor.core.exception.util.PlatformErrorMessages; -import io.mosip.registration.processor.core.exception.util.PlatformSuccessMessages; -import io.mosip.registration.processor.core.logger.LogDescription; -import io.mosip.registration.processor.core.logger.RegProcessorLogger; -import io.mosip.registration.processor.core.packet.dto.Identity; -import io.mosip.registration.processor.core.packet.dto.abis.AbisCommonResponseDto; -import io.mosip.registration.processor.core.packet.dto.abis.AbisIdentifyResponseDto; -import io.mosip.registration.processor.core.packet.dto.abis.AbisInsertResponseDto; -import io.mosip.registration.processor.core.packet.dto.abis.AbisRequestDto; -import io.mosip.registration.processor.core.packet.dto.abis.AbisResponseDto; -import io.mosip.registration.processor.core.packet.dto.abis.CandidatesDto; -import io.mosip.registration.processor.core.packet.dto.abis.RegBioRefDto; -import io.mosip.registration.processor.core.queue.factory.MosipQueue; -import io.mosip.registration.processor.core.queue.factory.QueueListener; -import io.mosip.registration.processor.core.spi.packetmanager.PacketInfoManager; -import io.mosip.registration.processor.core.spi.queue.MosipQueueManager; -import io.mosip.registration.processor.core.status.util.StatusUtil; -import io.mosip.registration.processor.core.status.util.TrimExceptionMessage; -import io.mosip.registration.processor.core.util.JsonUtil; -import io.mosip.registration.processor.packet.storage.dao.PacketInfoDao; -import io.mosip.registration.processor.packet.storage.dto.ApplicantInfoDto; -import io.mosip.registration.processor.packet.storage.entity.AbisRequestEntity; -import io.mosip.registration.processor.packet.storage.entity.AbisRequestPKEntity; -import io.mosip.registration.processor.packet.storage.entity.AbisResponseDetEntity; -import io.mosip.registration.processor.packet.storage.entity.AbisResponseDetPKEntity; -import io.mosip.registration.processor.packet.storage.entity.AbisResponseEntity; -import io.mosip.registration.processor.packet.storage.entity.AbisResponsePKEntity; -import io.mosip.registration.processor.packet.storage.repository.BasePacketRepository; -import io.mosip.registration.processor.packet.storage.utils.Utilities; -import io.mosip.registration.processor.rest.client.audit.builder.AuditLogRequestBuilder; -import io.mosip.registration.processor.status.code.RegistrationType; -import io.mosip.registration.processor.status.dao.RegistrationStatusDao; -import io.mosip.registration.processor.status.dto.InternalRegistrationStatusDto; -import io.mosip.registration.processor.status.dto.RegistrationStatusDto; -import io.mosip.registration.processor.status.entity.RegistrationStatusEntity; -import io.mosip.registration.processor.status.entity.TransactionEntity; -import io.mosip.registration.processor.status.repositary.TransactionRepository; -import io.mosip.registration.processor.status.service.RegistrationStatusService; -import io.mosip.registration.processor.status.utilities.RegistrationUtility; - -/** - * - * @author Girish Yarru - * @since v1.0 - * - */ -@RefreshScope -@Service -@Configuration -@ComponentScan(basePackages = { "${mosip.auth.adapter.impl.basepackage}", - "io.mosip.registration.processor.abis.handler.config", - "io.mosip.registration.processor.status.config", - "io.mosip.registration.processor.rest.client.config", - "io.mosip.registration.processor.packet.storage.config", - "io.mosip.registration.processor.core.config", - "io.mosip.registration.processor.core.kernel.beans", - "io.mosip.registration.processor.stages.config", - "io.mosip.registartion.processor.abis.middleware.validators"}) -public class AbisMiddleWareStage extends MosipVerticleAPIManager { - private static Logger regProcLogger = RegProcessorLogger.getLogger(AbisMiddleWareStage.class); - private static final String STAGE_PROPERTY_PREFIX = "mosip.regproc.abis.middleware."; - - /** The mosip queue manager. */ - @Autowired - private MosipQueueManager mosipQueueManager; - - @Autowired - private PacketInfoManager packetInfoManager; - - @Autowired - private BasePacketRepository abisRequestRepositary; - - @Autowired - private BasePacketRepository abisResponseRepositary; - - @Autowired - private BasePacketRepository abisResponseDetailRepositary; - - @Autowired - private Utilities utility; - - @Autowired - private RegistrationStatusDao registrationStatusDao; - - @Autowired - private RegistrationStatusService registrationStatusService; - - /** The core audit request builder. */ - @Autowired - private AuditLogRequestBuilder auditLogRequestBuilder; - - @Autowired - private PacketInfoDao packetInfoDao; - - @Value("${vertx.cluster.configuration}") - private String clusterManagerUrl; - - /** worker pool size. */ - @Value("${worker.pool.size}") - private Integer workerPoolSize; - - /** After this time intervel, message should be considered as expired (In seconds). */ - @Value("${mosip.regproc.abis.middleware.message.expiry-time-limit}") - private Long messageExpiryTimeLimit; - - /** Message Format. */ - @Value("${activemq.message.format}") - private String messageFormat; - - /** The mosip event bus. */ - MosipEventBus mosipEventBus = null; - - /** Mosip router for APIs */ - @Autowired - MosipRouter router; - - /** The url. */ - private static final String SYSTEM = "SYSTEM"; - private List abisQueueDetails; - private static final String REQUESTID = "requestId"; - private static final String DEMOGRAPHIC_VERIFICATION = "DEMOGRAPHIC_VERIFICATION"; - private static final String BIOGRAPHIC_VERIFICATION = "BIOGRAPHIC_VERIFICATION"; - private static final String ABIS_QUEUE_NOT_FOUND = "ABIS_QUEUE_NOT_FOUND"; - private static final String TEXT_MESSAGE = "text"; - - /** - * Get all the abis queue details,register listener to outbound queue's - */ - public void deployVerticle() { - try { - mosipEventBus = this.getEventBus(this, clusterManagerUrl, workerPoolSize); - this.consume(mosipEventBus, MessageBusAddress.ABIS_MIDDLEWARE_BUS_IN, messageExpiryTimeLimit); - abisQueueDetails = utility.getAbisQueueDetails(); - for (AbisQueueDetails abisQueue : abisQueueDetails) { - String abisInBoundaddress = abisQueue.getInboundQueueName(); - int inboundMessageTTL = abisQueue.getInboundMessageTTL(); - MosipQueue queue = abisQueue.getMosipQueue(); - QueueListener listener = new QueueListener() { - @Override - public void setListener(Message message) { - try { - consumerListener(message, abisInBoundaddress, queue, mosipEventBus, - inboundMessageTTL); - } catch (Exception e) { - - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), - LoggerFileConstant.REGISTRATIONID.toString(), "", ExceptionUtils.getStackTrace(e)); - - } - } - }; - mosipQueueManager.consume(queue, abisQueue.getOutboundQueueName(), listener); - } - - } catch (Exception e) { - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - "", ExceptionUtils.getStackTrace(e)); - throw new RegistrationProcessorUnCheckedException(PlatformErrorMessages.UNKNOWN_EXCEPTION_OCCURED.getCode(), - PlatformErrorMessages.UNKNOWN_EXCEPTION_OCCURED.getMessage(), e); - - } - } - - @Override - public void start() { - router.setRoute(this.postUrl(getVertx(), MessageBusAddress.ABIS_MIDDLEWARE_BUS_IN, - MessageBusAddress.ABIS_MIDDLEWARE_BUS_OUT)); - this.createServer(router.getRouter(), getPort()); - - } - - @Override - protected String getPropertyPrefix() { - return STAGE_PROPERTY_PREFIX; - } - - - @Override - public MessageDTO process(MessageDTO object) { - TrimExceptionMessage trimExceptionMessage = new TrimExceptionMessage(); - object.setMessageBusAddress(MessageBusAddress.ABIS_MIDDLEWARE_BUS_IN); - object.setIsValid(false); - object.setInternalError(false); - boolean isTransactionSuccessful = false; - LogDescription description = new LogDescription(); - String registrationId = object.getRid(); - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - registrationId, "AbisMiddlewareStage::process()::entry"); - InternalRegistrationStatusDto internalRegDto = registrationStatusService.getRegistrationStatus( - registrationId, object.getReg_type(), object.getIteration(), object.getWorkflowInstanceId()); - try { - List abisRefList = packetInfoManager.getReferenceIdByWorkflowInstanceId(object.getWorkflowInstanceId()); - validateNullCheck(abisRefList, "ABIS_REFERENCE_ID_NOT_FOUND"); - - String refRegtrnId = getLatestTransactionId(registrationId, - object.getReg_type(), object.getIteration(), object.getWorkflowInstanceId()); - validateNullCheck(refRegtrnId, "LATEST_TRANSACTION_ID_NOT_FOUND"); - String abisRefId = abisRefList.get(0); - List abisInsertIdentifyList = packetInfoManager.getInsertOrIdentifyRequest(abisRefId, - refRegtrnId); - validateNullCheck(abisInsertIdentifyList, "IDENTIFY_REQUESTS_NOT_FOUND"); - // get all insert requests(already processed,in progress) - List abisInsertRequestList = abisInsertIdentifyList.stream() - .filter(dto -> dto.getRequestType().equals(AbisStatusCode.INSERT.toString())) - .collect(Collectors.toList()); - List abisInprogressInsertRequestList = abisInsertRequestList.stream() - .filter(dto -> dto.getStatusCode().equals(AbisStatusCode.IN_PROGRESS.toString())) - .collect(Collectors.toList()); - List abisAlreadyprocessedInsertRequestList = abisInsertRequestList.stream() - .filter(dto -> dto.getStatusCode().equals(AbisStatusCode.ALREADY_PROCESSED.toString())) - .collect(Collectors.toList()); - List abisIdentifyRequestList = abisInsertIdentifyList.stream() - .filter(dto -> dto.getRequestType().equals(AbisStatusCode.IDENTIFY.toString())) - .collect(Collectors.toList()); - - processInsertIdentify(abisInsertRequestList, abisIdentifyRequestList, abisInprogressInsertRequestList, - internalRegDto, abisAlreadyprocessedInsertRequestList); - - object.setIsValid(true); - object.setInternalError(false); - isTransactionSuccessful = true; - description.setMessage(PlatformSuccessMessages.RPR_ABIS_MIDDLEWARE_STAGE_SUCCESS.getMessage()); - description.setCode(PlatformSuccessMessages.RPR_ABIS_MIDDLEWARE_STAGE_SUCCESS.getCode()); - - regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - registrationId, "AbisMiddlewareStage::process()::Abis insertRequests sucessfully sent to Queue"); - } catch (RegistrationProcessorCheckedException e) { - object.setInternalError(true); - description.setMessage(PlatformErrorMessages.UNKNOWN_EXCEPTION_OCCURED.getMessage()); - description.setCode(PlatformErrorMessages.UNKNOWN_EXCEPTION_OCCURED.getCode()); - internalRegDto.setLatestTransactionStatusCode(RegistrationTransactionStatusCode.REPROCESS.toString()); - internalRegDto.setStatusComment(trimExceptionMessage - .trimExceptionMessage(StatusUtil.SYSTEM_EXCEPTION_OCCURED.getMessage() + e.getMessage())); - internalRegDto.setSubStatusCode(StatusUtil.SYSTEM_EXCEPTION_OCCURED.getCode()); - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - registrationId, ExceptionUtils.getStackTrace(e)); - } catch (Exception e) { - object.setInternalError(true); - description.setMessage(PlatformErrorMessages.UNKNOWN_EXCEPTION_OCCURED.getMessage()); - description.setCode(PlatformErrorMessages.UNKNOWN_EXCEPTION_OCCURED.getCode()); - internalRegDto.setLatestTransactionStatusCode(RegistrationTransactionStatusCode.REPROCESS.toString()); - internalRegDto.setStatusComment(trimExceptionMessage - .trimExceptionMessage(StatusUtil.UNKNOWN_EXCEPTION_OCCURED.getMessage() + e.getMessage())); - internalRegDto.setSubStatusCode(StatusUtil.SYSTEM_EXCEPTION_OCCURED.getCode()); - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - registrationId, ExceptionUtils.getStackTrace(e)); - } finally { - if (!isTransactionSuccessful) { - String transactionTypeCode = ""; - if (transactionTypeCode.equalsIgnoreCase(DEMOGRAPHIC_VERIFICATION)) { - internalRegDto.setRegistrationStageName("DemoDedupeStage"); - } else if (transactionTypeCode.equalsIgnoreCase(BIOGRAPHIC_VERIFICATION)) { - internalRegDto.setRegistrationStageName("BioDedupeStage"); - } - updateErrorFlags(internalRegDto, object); - String moduleId = description.getCode(); - String moduleName = ModuleName.ABIS_MIDDLEWARE.toString(); - registrationStatusService.updateRegistrationStatus(internalRegDto, moduleId, moduleName); - } - - String eventId = isTransactionSuccessful ? EventId.RPR_402.toString() : EventId.RPR_405.toString(); - String eventName = isTransactionSuccessful ? EventName.UPDATE.toString() : EventName.EXCEPTION.toString(); - String eventType = isTransactionSuccessful ? EventType.BUSINESS.toString() : EventType.SYSTEM.toString(); - - /** Module-Id can be Both Success/Error code */ - String moduleId = isTransactionSuccessful - ? PlatformSuccessMessages.RPR_ABIS_MIDDLEWARE_STAGE_SUCCESS.getCode() - : description.getCode(); - String moduleName = ModuleName.ABIS_MIDDLEWARE.toString(); - - auditLogRequestBuilder.createAuditRequestBuilder(description.getMessage(), eventId, eventName, eventType, - moduleId, moduleName, registrationId); - } - return object; - } - - private void processInsertIdentify(List abisInsertRequestList, - List abisIdentifyRequestList, List abisInprogressInsertRequestList, - InternalRegistrationStatusDto internalRegDto, List abisAlreadyprocessedInsertRequestList) - throws RegistrationProcessorCheckedException { - // If all insert request are null then send all identify requests. - if (abisInsertRequestList.isEmpty()) { - for (AbisRequestDto abisIdentifyRequest : abisIdentifyRequestList) { - List abisQueue = abisQueueDetails.stream() - .filter(dto -> dto.getName().equals(abisIdentifyRequest.getAbisAppCode())) - .collect(Collectors.toList()); - validateNullCheck(abisQueue, ABIS_QUEUE_NOT_FOUND); - byte[] reqBytearray = abisIdentifyRequest.getReqText(); - - boolean isAddedToQueue = sendToQueue(abisQueue.get(0).getMosipQueue(), new String(reqBytearray), - abisQueue.get(0).getInboundQueueName(), abisQueue.get(0).getInboundMessageTTL()); - - updateAbisRequest(isAddedToQueue, abisIdentifyRequest, internalRegDto); - } - - } - // send in progress insert requests to queue - for (AbisRequestDto abisInprogressRequest : abisInprogressInsertRequestList) { - List abisQueue = abisQueueDetails.stream() - .filter(dto -> dto.getName().equals(abisInprogressRequest.getAbisAppCode())) - .collect(Collectors.toList()); - validateNullCheck(abisQueue, ABIS_QUEUE_NOT_FOUND); - - byte[] reqBytearray = abisInprogressRequest.getReqText(); - - boolean isAddedToQueue = sendToQueue(abisQueue.get(0).getMosipQueue(), new String(reqBytearray), - abisQueue.get(0).getInboundQueueName(), abisQueue.get(0).getInboundMessageTTL()); - - updateAbisRequest(isAddedToQueue, abisInprogressRequest, internalRegDto); - } - // send all identify requests for already processed insert requests - for (AbisRequestDto abisAlreadyProcessedInsertRequest : abisAlreadyprocessedInsertRequestList) { - List abisQueue = abisQueueDetails.stream() - .filter(dto -> dto.getName().equals(abisAlreadyProcessedInsertRequest.getAbisAppCode())) - .collect(Collectors.toList()); - validateNullCheck(abisQueue, ABIS_QUEUE_NOT_FOUND); - List identifyRequest = abisIdentifyRequestList.stream() - .filter(dto -> dto.getAbisAppCode().equals(abisAlreadyProcessedInsertRequest.getAbisAppCode())) - .collect(Collectors.toList()); - byte[] reqBytearray = identifyRequest.get(0).getReqText(); - boolean isAddedToQueue = sendToQueue(abisQueue.get(0).getMosipQueue(), new String(reqBytearray), - abisQueue.get(0).getInboundQueueName(), abisQueue.get(0).getInboundMessageTTL()); - updateAbisRequest(isAddedToQueue, identifyRequest.get(0), internalRegDto); - - } - } - - public void consumerListener(Message message, String abisInBoundAddress, MosipQueue queue, - MosipEventBus eventBus, int inboundMessageTTL) - throws RegistrationProcessorCheckedException { - TrimExceptionMessage trimExceptionMessage = new TrimExceptionMessage(); - InternalRegistrationStatusDto internalRegStatusDto = null; - String registrationId = null; - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", - "AbisMiddlewareStage::consumerListener()::entry"); - String moduleId = ""; - String moduleName = ModuleName.ABIS_MIDDLEWARE.toString(); - boolean isTransactionSuccessful = true; - String response = null; - LogDescription description = new LogDescription(); - try { - if (messageFormat.equalsIgnoreCase(TEXT_MESSAGE)) { - TextMessage textMessage = (TextMessage) message; - response =textMessage.getText(); - } else - response = new String(((ActiveMQBytesMessage) message).getContent().data); - JSONObject inserOrIdentifyResponse = JsonUtil.objectMapperReadValue(response, JSONObject.class); - String requestId = JsonUtil.getJSONValue(inserOrIdentifyResponse, REQUESTID); - String batchId = packetInfoManager.getBatchIdByRequestId(requestId); - validateNullCheck(batchId, "ABIS_BATCH_ID_NOT_FOUND"); - List bioRefId = packetInfoManager.getReferenceIdByBatchId(batchId); - validateNullCheck(bioRefId, "ABIS_REFERENCE_ID_NOT_FOUND"); - - List regBioRefist = packetInfoManager.getRegBioRefDataByBioRefIds(bioRefId); - RegBioRefDto regBioRefDto = regBioRefist.get(0); - registrationId = regBioRefDto.getRegId(); - internalRegStatusDto = registrationStatusService.getRegistrationStatus(registrationId, - regBioRefDto.getProcess(), regBioRefDto.getIteration(), regBioRefDto.getWorkflowInstanceId()); - regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", - "AbisMiddlewareStage::consumerListener()::response from abis for requestId ::" + requestId); - - AbisRequestDto abisCommonRequestDto = packetInfoManager.getAbisRequestByRequestId(requestId); - // check for insert response,if success send corresponding identify request to - // queue - if (abisCommonRequestDto.getRequestType().equals(AbisStatusCode.INSERT.toString())) { - if (AbisStatusCode.SENT.toString().equals(abisCommonRequestDto.getStatusCode())) { - - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", - "AbisMiddlewareStage::consumerListener()::Insert Response received from abis ::" - + inserOrIdentifyResponse); - AbisInsertResponseDto abisInsertResponseDto = JsonUtil.objectMapperReadValue(response, - AbisInsertResponseDto.class); - - if (abisInsertResponseDto.getFailureReason() != null && abisInsertResponseDto.getFailureReason().equalsIgnoreCase("10")) - regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), - "Received failure response from abis.", - "Reference id already present for requestId : " + requestId +". Regproc will pass this insert response."); - - updateAbisResponseEntity(abisInsertResponseDto, response); - updteAbisRequestProcessed(abisInsertResponseDto, abisCommonRequestDto); - if (isInsertSuccess(abisInsertResponseDto)) { - List transactionIdList = packetInfoManager.getAbisTransactionIdByRequestId(requestId); - validateNullCheck(transactionIdList, "LATEST_TRANSACTION_ID_NOT_FOUND"); - List abisIdentifyRequestList = packetInfoManager.getIdentifyReqListByTransactionId( - transactionIdList.get(0), AbisStatusCode.IDENTIFY.toString()); - List abisIdentifyRequest = abisIdentifyRequestList.stream() - .filter(dto1 -> dto1.getAbisAppCode().equals(abisCommonRequestDto.getAbisAppCode())) - .collect(Collectors.toList()); - validateNullCheck(abisIdentifyRequest, "IDENTIFY_REQUESTS_NOT_FOUND"); - AbisRequestDto abisIdentifyRequestDto = abisIdentifyRequest.get(0); - boolean isAddedToQueue = sendToQueue(queue, new String(abisIdentifyRequestDto.getReqText()), - abisInBoundAddress, inboundMessageTTL); - updateAbisRequest(isAddedToQueue, abisIdentifyRequestDto, internalRegStatusDto); - } else { - internalRegStatusDto - .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.REPROCESS.toString()); - internalRegStatusDto.setStatusComment( - StatusUtil.INSERT_RESPONSE_FAILED.getMessage() + abisCommonRequestDto.getId() +"- failure reason - "+abisInsertResponseDto.getFailureReason() + "-" - + io.mosip.registartion.processor.abis.middleware.constants.FailureReason - .getValueFromKey(abisInsertResponseDto.getFailureReason())); - internalRegStatusDto.setSubStatusCode(StatusUtil.SYSTEM_EXCEPTION_OCCURED.getCode()); - moduleId = PlatformErrorMessages.SYSTEM_EXCEPTION_OCCURED.getCode(); - registrationStatusService.updateRegistrationStatus(internalRegStatusDto, moduleId, moduleName); - } - - } else { - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), - "", - "AbisMiddlewareStage::consumerListener()::Duplicate Insert Response received from abis for same request id ::" - + requestId + " response " + inserOrIdentifyResponse); - isTransactionSuccessful = false; - description.setMessage(PlatformErrorMessages.DUPLICATE_INSERT_RESPONSE.getMessage() + requestId); - description.setCode(PlatformErrorMessages.DUPLICATE_INSERT_RESPONSE.getCode()); - - } - } - // check if identify response,then if all identify requests are processed send - // to abis handler - if (abisCommonRequestDto.getRequestType().equals(AbisStatusCode.IDENTIFY.toString())) { - if (AbisStatusCode.SENT.toString().equals(abisCommonRequestDto.getStatusCode())) { - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", - "AbisMiddlewareStage::consumerListener()::Identify Response received from abis ::" - + inserOrIdentifyResponse); - - AbisIdentifyResponseDto abisIdentifyResponseDto = JsonUtil.readValueWithUnknownProperties(response, - AbisIdentifyResponseDto.class); - if (!abisIdentifyResponseDto.getReturnValue().equalsIgnoreCase("1")){ - internalRegStatusDto - .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.REPROCESS.toString()); - internalRegStatusDto.setStatusComment( - StatusUtil.IDENTIFY_RESPONSE_FAILED.getMessage() + abisCommonRequestDto.getId()+"- failure reason -"+abisIdentifyResponseDto.getFailureReason() + "-" - + io.mosip.registartion.processor.abis.middleware.constants.FailureReason - .getValueFromKey(abisIdentifyResponseDto.getFailureReason())); - internalRegStatusDto.setSubStatusCode(StatusUtil.SYSTEM_EXCEPTION_OCCURED.getCode()); - moduleId = PlatformErrorMessages.SYSTEM_EXCEPTION_OCCURED.getCode(); - registrationStatusService.updateRegistrationStatus(internalRegStatusDto, moduleId, moduleName); - } - AbisResponseDto abisResponseDto = updateAbisResponseEntity(abisIdentifyResponseDto, response); - if (abisIdentifyResponseDto.getCandidateList() != null) { - CandidatesDto[] candidatesDtos = abisIdentifyResponseDto.getCandidateList().getCandidates(); - if (!Arrays.isNullOrEmpty(candidatesDtos)) { - saveCandiateDtos(candidatesDtos, abisResponseDto, bioRefId.get(0)); - } - } - updteAbisRequestProcessed(abisIdentifyResponseDto, abisCommonRequestDto); - - if (checkAllIdentifyRequestsProcessed(batchId)) { - - regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), - "", - "AbisMiddlewareStage::consumerListener()::All identify are requests processed sending to Abis handler"); - - sendToAbisHandler(eventBus, bioRefId, registrationId, internalRegStatusDto.getRegistrationType(), - internalRegStatusDto.getIteration(), internalRegStatusDto.getWorkflowInstanceId()); - - } - } else { - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), - "", - "AbisMiddlewareStage::consumerListener()::Duplicate Identify Response received from abis for same request id ::" - + requestId + " response " + inserOrIdentifyResponse); - isTransactionSuccessful = false; - description.setMessage(PlatformErrorMessages.DUPLICATE_IDENTITY_RESPONSE.getMessage() + requestId); - description.setCode(PlatformErrorMessages.DUPLICATE_IDENTITY_RESPONSE.getCode()); - - } - } - - } catch (IOException e) { - if (internalRegStatusDto != null) { - internalRegStatusDto - .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.REPROCESS.toString()); - internalRegStatusDto.setStatusComment(trimExceptionMessage - .trimExceptionMessage(StatusUtil.IO_EXCEPTION.getMessage() + e.getMessage())); - internalRegStatusDto.setSubStatusCode(StatusUtil.SYSTEM_EXCEPTION_OCCURED.getCode()); - moduleId = PlatformErrorMessages.SYSTEM_EXCEPTION_OCCURED.getCode(); - registrationStatusService.updateRegistrationStatus(internalRegStatusDto, moduleId, moduleName); - } - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - registrationId, ExceptionUtils.getStackTrace(e)); - throw new RegistrationProcessorCheckedException(PlatformErrorMessages.RPR_SYS_IO_EXCEPTION.getCode(), - PlatformErrorMessages.RPR_SYS_IO_EXCEPTION.getMessage(), e); - } catch (Exception e) { - if (internalRegStatusDto != null) { - internalRegStatusDto - .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.REPROCESS.toString()); - internalRegStatusDto.setStatusComment(trimExceptionMessage - .trimExceptionMessage(StatusUtil.UNKNOWN_EXCEPTION_OCCURED.getMessage() + e.getMessage())); - internalRegStatusDto.setSubStatusCode(StatusUtil.SYSTEM_EXCEPTION_OCCURED.getCode()); - moduleId = PlatformErrorMessages.SYSTEM_EXCEPTION_OCCURED.getCode(); - registrationStatusService.updateRegistrationStatus(internalRegStatusDto, moduleId, moduleName); - } - - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - registrationId, ExceptionUtils.getStackTrace(e)); - } finally { - if (!isTransactionSuccessful) { - String eventId = EventId.RPR_405.toString(); - String eventName = EventName.EXCEPTION.toString(); - String eventType = EventType.SYSTEM.toString(); - moduleId = description.getCode(); - moduleName = ModuleName.ABIS_MIDDLEWARE.toString(); - auditLogRequestBuilder.createAuditRequestBuilder(description.getMessage(), eventId, eventName, - eventType, moduleId, moduleName, registrationId); - } - - } - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", - "AbisMiddlewareStage::consumerListener()::Exit()"); - } - - private void validateNullCheck(Object obj, String errorMessage) { - if (obj == null) { - throw new RegistrationProcessorUnCheckedException(PlatformErrorMessages.valueOf(errorMessage).getCode(), - PlatformErrorMessages.valueOf(errorMessage).getMessage()); - } - if (obj instanceof Collection) { - List genericList = new ArrayList<>((Collection) obj); - if (genericList.isEmpty()) { - throw new RegistrationProcessorUnCheckedException(PlatformErrorMessages.valueOf(errorMessage).getCode(), - PlatformErrorMessages.valueOf(errorMessage).getMessage()); - } - } - - } - - private boolean sendToQueue(MosipQueue queue, String abisReqTextString, String abisQueueAddress, - int messageTTL) throws RegistrationProcessorCheckedException { - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", - "AbisMiddlewareStage::sendToQueue()::Entry"); - boolean isAddedToQueue; - try { - if (messageFormat.equalsIgnoreCase(TEXT_MESSAGE)) - isAddedToQueue = mosipQueueManager.send(queue, abisReqTextString, - abisQueueAddress, messageTTL); - else - isAddedToQueue = mosipQueueManager.send(queue, abisReqTextString.getBytes(), - abisQueueAddress, messageTTL); - - regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", - "AbisMiddlewareStage:: sent to abis queue ::" + abisReqTextString); - - } catch (Exception e) { - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - "", ExceptionUtils.getStackTrace(e)); - throw new RegistrationProcessorCheckedException(PlatformErrorMessages.RPR_SYS_IO_EXCEPTION.getCode(), - PlatformErrorMessages.RPR_SYS_IO_EXCEPTION.getMessage(), e); - } - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", - "AbisMiddlewareStage::sendToQueue()::Exit"); - return isAddedToQueue; - } - - private void updateAbisRequest(boolean isAddedToQueue, AbisRequestDto abisRequestDto, - InternalRegistrationStatusDto internalRegDto) { - AbisRequestEntity abisReqEntity = convertAbisRequestDtoToAbisRequestEntity(abisRequestDto); - - if (isAddedToQueue) { - - abisReqEntity.setStatusCode(AbisStatusCode.SENT.toString()); - abisReqEntity.setStatusComment( - StatusUtil.INSERT_IDENTIFY_REQUEST_SUCCESS.getMessage() + abisRequestDto.getAbisAppCode()); - } else { - abisReqEntity.setStatusCode(AbisStatusCode.FAILED.toString()); - abisReqEntity.setStatusComment( - StatusUtil.INSERT_IDENTIFY_REQUEST_FAILED.getMessage() + abisRequestDto.getAbisAppCode()); - internalRegDto.setLatestTransactionStatusCode(RegistrationTransactionStatusCode.REPROCESS.toString()); - internalRegDto.setStatusComment( - StatusUtil.INSERT_IDENTIFY_REQUEST_FAILED.getMessage() + abisRequestDto.getAbisAppCode()); - internalRegDto.setSubStatusCode(StatusUtil.SYSTEM_EXCEPTION_OCCURED.getCode()); - } - abisRequestRepositary.save(abisReqEntity); - - } - - private void updteAbisRequestProcessed(AbisCommonResponseDto abisCommonResponseDto, - AbisRequestDto abisCommonRequestDto) { - AbisRequestEntity abisReqEntity = new AbisRequestEntity(); - AbisRequestPKEntity abisReqPKEntity = new AbisRequestPKEntity(); - abisReqPKEntity.setId(abisCommonResponseDto.getRequestId()); - abisReqEntity.setId(abisReqPKEntity); - abisReqEntity.setStatusCode(isInsertSuccess(abisCommonResponseDto) ? AbisStatusCode.PROCESSED.toString() - : AbisStatusCode.FAILED.toString()); - if (isInsertSuccess(abisCommonResponseDto)) { - abisReqEntity.setStatusComment(StatusUtil.INSERT_IDENTIFY_RESPONSE_SUCCESS.getMessage()); - } else { - abisReqEntity.setStatusComment(io.mosip.registartion.processor.abis.middleware.constants.FailureReason - .getValueFromKey(abisCommonResponseDto.getFailureReason())); - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), - "Abis response failed for "+packetInfoDao.getRegIdByBioRefId(abisCommonRequestDto.getBioRefId())+" due to " + abisCommonResponseDto.getFailureReason() + "-" - + io.mosip.registartion.processor.abis.middleware.constants.FailureReason - .getValueFromKey(abisCommonResponseDto.getFailureReason()), - "AbisMiddleWareStage::updteAbisRequestProcessed()"); - - } - abisReqEntity.setAbisAppCode(abisCommonRequestDto.getAbisAppCode()); - abisReqEntity.setRequestType(abisCommonRequestDto.getRequestType()); - abisReqEntity.setRequestDtimes(abisCommonRequestDto.getRequestDtimes()); - abisReqEntity.setReqBatchId(abisCommonRequestDto.getReqBatchId()); - abisReqEntity.setLangCode(abisCommonRequestDto.getLangCode()); - abisReqEntity.setCrBy(SYSTEM); - abisReqEntity.setCrDtimes(abisCommonRequestDto.getCrDtimes()); - abisReqEntity.setBioRefId(abisCommonRequestDto.getBioRefId()); - abisReqEntity.setRefRegtrnId(abisCommonRequestDto.getRefRegtrnId()); - abisReqEntity.setReqText(abisCommonRequestDto.getReqText()); - abisRequestRepositary.save(abisReqEntity); - } - - private AbisRequestEntity convertAbisRequestDtoToAbisRequestEntity(AbisRequestDto abisRequestDto) { - AbisRequestEntity abisReqEntity = new AbisRequestEntity(); - AbisRequestPKEntity abisReqPKEntity = new AbisRequestPKEntity(); - abisReqPKEntity.setId(abisRequestDto.getId()); - abisReqEntity.setId(abisReqPKEntity); - abisReqEntity.setAbisAppCode(abisRequestDto.getAbisAppCode()); - abisReqEntity.setBioRefId(abisRequestDto.getBioRefId()); - abisReqEntity.setCrBy(abisRequestDto.getCrBy()); - if (abisRequestDto.getCrDtimes() == null) { - abisReqEntity.setCrDtimes(LocalDateTime.now(ZoneId.of("UTC"))); - } else { - abisReqEntity.setCrDtimes(abisRequestDto.getCrDtimes()); - } - abisReqEntity.setIsDeleted(false); - abisReqEntity.setLangCode(abisRequestDto.getLangCode()); - abisReqEntity.setRefRegtrnId(abisRequestDto.getRefRegtrnId()); - abisReqEntity.setReqBatchId(abisRequestDto.getReqBatchId()); - abisReqEntity.setReqText(abisRequestDto.getReqText()); - abisReqEntity.setRequestDtimes(abisRequestDto.getRequestDtimes()); - abisReqEntity.setRequestType(abisRequestDto.getRequestType()); - abisReqEntity.setStatusCode(abisRequestDto.getStatusCode()); - abisReqEntity.setStatusComment(abisRequestDto.getStatusComment()); - abisReqEntity.setUpdBy(abisRequestDto.getUpdBy()); - abisReqEntity.setUpdDtimes(LocalDateTime.now(ZoneId.of("UTC"))); - return abisReqEntity; - - } - - private AbisResponseEntity convertAbisResponseDtoToAbisResponseEntity(AbisResponseDto abisResponseDto) { - AbisResponseEntity abisResponseEntity = new AbisResponseEntity(); - AbisResponsePKEntity abisResponsePKEntity = new AbisResponsePKEntity(); - abisResponsePKEntity.setId(abisResponseDto.getId()); - abisResponseEntity.setId(abisResponsePKEntity); - abisResponseEntity.setAbisRequest(abisResponseDto.getAbisRequest()); - abisResponseEntity.setRespText(abisResponseDto.getRespText()); - abisResponseEntity.setStatusCode(abisResponseDto.getStatusCode()); - abisResponseEntity.setStatusComment(abisResponseDto.getStatusComment()); - abisResponseEntity.setLangCode(abisResponseDto.getLangCode()); - abisResponseEntity.setCrBy(abisResponseDto.getCrBy()); - if (abisResponseDto.getCrDtimes() == null) { - abisResponseEntity.setCrDtimes(LocalDateTime.now(ZoneId.of("UTC"))); - } else { - abisResponseEntity.setCrDtimes(abisResponseDto.getCrDtimes()); - } - abisResponseEntity.setUpdBy(abisResponseDto.getUpdBy()); - abisResponseEntity.setUpdDtimes(abisResponseDto.getUpdDtimes()); - abisResponseEntity.setIsDeleted(abisResponseDto.getIsDeleted()); - abisResponseEntity.setRespDtimes(LocalDateTime.now(ZoneId.of("UTC"))); - - return abisResponseEntity; - - } - - private AbisResponseDto updateAbisResponseEntity(AbisCommonResponseDto abisCommonResponseDto, String response) { - AbisResponseDto abisResponseDto = new AbisResponseDto(); - - abisResponseDto.setId(RegistrationUtility.generateId()); - abisResponseDto.setRespText(response.getBytes()); - - if (isInsertSuccess(abisCommonResponseDto)) { - abisResponseDto.setStatusCode(AbisStatusCode.SUCCESS.toString()); - } else { - abisResponseDto.setStatusCode(AbisStatusCode.FAILED.toString()); - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), - "Abis response failed for request Id " + abisCommonResponseDto.getRequestId() + " due to " - + abisCommonResponseDto.getFailureReason() + "-" - + io.mosip.registartion.processor.abis.middleware.constants.FailureReason - .getValueFromKey(abisCommonResponseDto.getFailureReason()), - "AbisMiddleWareStage::updateAbisResponseEntity()"); - } - - abisResponseDto.setStatusComment(io.mosip.registartion.processor.abis.middleware.constants.FailureReason.getValueFromKey(abisCommonResponseDto.getFailureReason())); - abisResponseDto.setLangCode("eng"); - abisResponseDto.setCrBy(SYSTEM); - abisResponseDto.setUpdBy(SYSTEM); - abisResponseDto.setUpdDtimes(LocalDateTime.now(ZoneId.of("UTC"))); - abisResponseDto.setIsDeleted(false); - abisResponseDto.setAbisRequest(abisCommonResponseDto.getRequestId()); - abisResponseRepositary.save(convertAbisResponseDtoToAbisResponseEntity(abisResponseDto)); - - return abisResponseDto; - } - - private void updateAbisResponseDetail(CandidatesDto candidatesDto, AbisResponseDto abisResponseDto, - String bioRefId) { - - if (!candidatesDto.getReferenceId().equalsIgnoreCase(bioRefId)) { - - String candidateRegId = packetInfoDao.getRegIdByBioRefId(candidatesDto.getReferenceId().toLowerCase()); - if (candidateRegId == null || candidateRegId.isEmpty()) - return; - AbisResponseDetEntity abisResponseDetEntity = new AbisResponseDetEntity(); - AbisResponseDetPKEntity abisResponseDetPKEntity = new AbisResponseDetPKEntity(); - abisResponseDetPKEntity.setAbisRespId(abisResponseDto.getId()); - abisResponseDetPKEntity.setMatchedBioRefId(candidatesDto.getReferenceId().toLowerCase()); - abisResponseDetEntity.setId(abisResponseDetPKEntity); - abisResponseDetEntity.setCrBy(SYSTEM); - abisResponseDetEntity.setUpdBy(SYSTEM); - abisResponseDetEntity.setIsDeleted(false); - abisResponseDetEntity.setCrDtimes(LocalDateTime.now(ZoneId.of("UTC"))); - abisResponseDetEntity.setUpdDtimes(LocalDateTime.now(ZoneId.of("UTC"))); - abisResponseDetailRepositary.save(abisResponseDetEntity); - - } - - } - - private String getLatestTransactionId(String registrationId, String process, int iteration, String workflowInstanceId) { - RegistrationStatusEntity entity = registrationStatusDao.find(registrationId, process, iteration, workflowInstanceId); - return entity != null ? entity.getLatestRegistrationTransactionId() : null; - - } - - private boolean checkAllIdentifyRequestsProcessed(String batchId) { - List batchStatus = packetInfoManager.getBatchStatusbyBatchId(batchId); - if (batchStatus != null) { - boolean flag = batchStatus.stream().allMatch(status -> status.equals(AbisStatusCode.PROCESSED.toString())); - if (flag) - return true; - } - return false; - } - - private void sendToAbisHandler(MosipEventBus eventBus, List bioRefId, - String regId, String regType, int iteration, String workflowInstanceId) { - if (bioRefId != null) { - MessageDTO messageDto = new MessageDTO(); - messageDto.setRid(regId); - messageDto.setReg_type(regType); - messageDto.setIsValid(Boolean.TRUE); - messageDto.setInternalError(Boolean.FALSE); - messageDto.setIteration(iteration); - messageDto.setWorkflowInstanceId(workflowInstanceId); - regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", - "AbisMiddlewareStage::consumerListener()::sending to Abis handler"); - this.send(eventBus, MessageBusAddress.ABIS_MIDDLEWARE_BUS_OUT, messageDto); - regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", - "AbisMiddlewareStage::consumerListener()::sent to Abis handler"); - } - - } - - private void saveCandiateDtos(CandidatesDto[] candidatesDtos, AbisResponseDto abisResponseDto, String bioRefId) { - for (CandidatesDto candidatesDto : candidatesDtos) { - updateAbisResponseDetail(candidatesDto, abisResponseDto, bioRefId); - } - } - - private void updateErrorFlags(InternalRegistrationStatusDto registrationStatusDto, MessageDTO object) { - object.setInternalError(true); - if (registrationStatusDto.getLatestTransactionStatusCode() - .equalsIgnoreCase(RegistrationTransactionStatusCode.REPROCESS.toString())) { - object.setIsValid(true); - } else { - object.setIsValid(false); - } - } - - /** - * If return value is 1 or failure reason is 10(which means ABIS has already processed the - * reference id) then return true - * @param abisInsertResponseDto - * @return boolean - */ - private boolean isInsertSuccess(AbisCommonResponseDto abisInsertResponseDto) { - return abisInsertResponseDto.getReturnValue().equalsIgnoreCase("1") - || (abisInsertResponseDto.getFailureReason() != null - && abisInsertResponseDto.getFailureReason().equalsIgnoreCase("10")); - } - +package io.mosip.registartion.processor.abis.middleware.stage; + +import java.io.IOException; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.stream.Collectors; + +import javax.jms.Message; +import javax.jms.TextMessage; + +import org.apache.activemq.command.ActiveMQBytesMessage; +import org.assertj.core.util.Arrays; +import org.json.simple.JSONObject; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.cloud.context.config.annotation.RefreshScope; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.stereotype.Service; + +import io.mosip.kernel.core.exception.ExceptionUtils; +import io.mosip.kernel.core.logger.spi.Logger; +import io.mosip.registration.processor.abis.queue.dto.AbisQueueDetails; +import io.mosip.registration.processor.core.abstractverticle.MessageBusAddress; +import io.mosip.registration.processor.core.abstractverticle.MessageDTO; +import io.mosip.registration.processor.core.abstractverticle.MosipEventBus; +import io.mosip.registration.processor.core.abstractverticle.MosipRouter; +import io.mosip.registration.processor.core.abstractverticle.MosipVerticleAPIManager; +import io.mosip.registration.processor.core.code.AbisStatusCode; +import io.mosip.registration.processor.core.code.EventId; +import io.mosip.registration.processor.core.code.EventName; +import io.mosip.registration.processor.core.code.EventType; +import io.mosip.registration.processor.core.code.ModuleName; +import io.mosip.registration.processor.core.code.RegistrationTransactionStatusCode; +import io.mosip.registration.processor.core.constant.LoggerFileConstant; +import io.mosip.registration.processor.core.exception.RegistrationProcessorCheckedException; +import io.mosip.registration.processor.core.exception.RegistrationProcessorUnCheckedException; +import io.mosip.registration.processor.core.exception.util.PlatformErrorMessages; +import io.mosip.registration.processor.core.exception.util.PlatformSuccessMessages; +import io.mosip.registration.processor.core.logger.LogDescription; +import io.mosip.registration.processor.core.logger.RegProcessorLogger; +import io.mosip.registration.processor.core.packet.dto.Identity; +import io.mosip.registration.processor.core.packet.dto.abis.AbisCommonResponseDto; +import io.mosip.registration.processor.core.packet.dto.abis.AbisIdentifyResponseDto; +import io.mosip.registration.processor.core.packet.dto.abis.AbisInsertResponseDto; +import io.mosip.registration.processor.core.packet.dto.abis.AbisRequestDto; +import io.mosip.registration.processor.core.packet.dto.abis.AbisResponseDto; +import io.mosip.registration.processor.core.packet.dto.abis.CandidatesDto; +import io.mosip.registration.processor.core.packet.dto.abis.RegBioRefDto; +import io.mosip.registration.processor.core.queue.factory.MosipQueue; +import io.mosip.registration.processor.core.queue.factory.QueueListener; +import io.mosip.registration.processor.core.spi.packetmanager.PacketInfoManager; +import io.mosip.registration.processor.core.spi.queue.MosipQueueManager; +import io.mosip.registration.processor.core.status.util.StatusUtil; +import io.mosip.registration.processor.core.status.util.TrimExceptionMessage; +import io.mosip.registration.processor.core.util.JsonUtil; +import io.mosip.registration.processor.packet.storage.dao.PacketInfoDao; +import io.mosip.registration.processor.packet.storage.dto.ApplicantInfoDto; +import io.mosip.registration.processor.packet.storage.entity.AbisRequestEntity; +import io.mosip.registration.processor.packet.storage.entity.AbisRequestPKEntity; +import io.mosip.registration.processor.packet.storage.entity.AbisResponseDetEntity; +import io.mosip.registration.processor.packet.storage.entity.AbisResponseDetPKEntity; +import io.mosip.registration.processor.packet.storage.entity.AbisResponseEntity; +import io.mosip.registration.processor.packet.storage.entity.AbisResponsePKEntity; +import io.mosip.registration.processor.packet.storage.repository.BasePacketRepository; +import io.mosip.registration.processor.packet.storage.utils.Utilities; +import io.mosip.registration.processor.rest.client.audit.builder.AuditLogRequestBuilder; +import io.mosip.registration.processor.status.code.RegistrationType; +import io.mosip.registration.processor.status.dao.RegistrationStatusDao; +import io.mosip.registration.processor.status.dto.InternalRegistrationStatusDto; +import io.mosip.registration.processor.status.dto.RegistrationStatusDto; +import io.mosip.registration.processor.status.entity.RegistrationStatusEntity; +import io.mosip.registration.processor.status.entity.TransactionEntity; +import io.mosip.registration.processor.status.repositary.TransactionRepository; +import io.mosip.registration.processor.status.service.RegistrationStatusService; +import io.mosip.registration.processor.status.utilities.RegistrationUtility; + +/** + * + * @author Girish Yarru + * @since v1.0 + * + */ +@RefreshScope +@Service +@Configuration +@ComponentScan(basePackages = { "${mosip.auth.adapter.impl.basepackage}", + "io.mosip.registration.processor.abis.handler.config", + "io.mosip.registration.processor.status.config", + "io.mosip.registration.processor.rest.client.config", + "io.mosip.registration.processor.packet.storage.config", + "io.mosip.registration.processor.core.config", + "io.mosip.registration.processor.core.kernel.beans", + "io.mosip.registration.processor.stages.config", + "io.mosip.registartion.processor.abis.middleware.validators"}) +public class AbisMiddleWareStage extends MosipVerticleAPIManager { + private static Logger regProcLogger = RegProcessorLogger.getLogger(AbisMiddleWareStage.class); + private static final String STAGE_PROPERTY_PREFIX = "mosip.regproc.abis.middleware."; + + /** The mosip queue manager. */ + @Autowired + private MosipQueueManager mosipQueueManager; + + @Autowired + private PacketInfoManager packetInfoManager; + + @Autowired + private BasePacketRepository abisRequestRepositary; + + @Autowired + private BasePacketRepository abisResponseRepositary; + + @Autowired + private BasePacketRepository abisResponseDetailRepositary; + + @Autowired + private Utilities utility; + + @Autowired + private RegistrationStatusDao registrationStatusDao; + + @Autowired + private RegistrationStatusService registrationStatusService; + + /** The core audit request builder. */ + @Autowired + private AuditLogRequestBuilder auditLogRequestBuilder; + + @Autowired + private PacketInfoDao packetInfoDao; + + @Value("${vertx.cluster.configuration}") + private String clusterManagerUrl; + + /** worker pool size. */ + @Value("${worker.pool.size}") + private Integer workerPoolSize; + + /** After this time intervel, message should be considered as expired (In seconds). */ + @Value("${mosip.regproc.abis.middleware.message.expiry-time-limit}") + private Long messageExpiryTimeLimit; + + /** Message Format. */ + @Value("${activemq.message.format}") + private String messageFormat; + + /** The mosip event bus. */ + MosipEventBus mosipEventBus = null; + + /** Mosip router for APIs */ + @Autowired + MosipRouter router; + + /** The url. */ + private static final String SYSTEM = "SYSTEM"; + private List abisQueueDetails; + private static final String REQUESTID = "requestId"; + private static final String DEMOGRAPHIC_VERIFICATION = "DEMOGRAPHIC_VERIFICATION"; + private static final String BIOGRAPHIC_VERIFICATION = "BIOGRAPHIC_VERIFICATION"; + private static final String ABIS_QUEUE_NOT_FOUND = "ABIS_QUEUE_NOT_FOUND"; + private static final String TEXT_MESSAGE = "text"; + + /** + * Get all the abis queue details,register listener to outbound queue's + */ + public void deployVerticle() { + try { + mosipEventBus = this.getEventBus(this, clusterManagerUrl, workerPoolSize); + this.consume(mosipEventBus, MessageBusAddress.ABIS_MIDDLEWARE_BUS_IN, messageExpiryTimeLimit); + abisQueueDetails = utility.getAbisQueueDetails(); + for (AbisQueueDetails abisQueue : abisQueueDetails) { + String abisInBoundaddress = abisQueue.getInboundQueueName(); + int inboundMessageTTL = abisQueue.getInboundMessageTTL(); + MosipQueue queue = abisQueue.getMosipQueue(); + QueueListener listener = new QueueListener() { + @Override + public void setListener(Message message) { + try { + consumerListener(message, abisInBoundaddress, queue, mosipEventBus, + inboundMessageTTL); + } catch (Exception e) { + + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString(), "", ExceptionUtils.getStackTrace(e)); + + } + } + }; + mosipQueueManager.consume(queue, abisQueue.getOutboundQueueName(), listener); + } + + } catch (Exception e) { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + "", ExceptionUtils.getStackTrace(e)); + throw new RegistrationProcessorUnCheckedException(PlatformErrorMessages.UNKNOWN_EXCEPTION_OCCURED.getCode(), + PlatformErrorMessages.UNKNOWN_EXCEPTION_OCCURED.getMessage(), e); + + } + } + + @Override + public void start() { + router.setRoute(this.postUrl(getVertx(), MessageBusAddress.ABIS_MIDDLEWARE_BUS_IN, + MessageBusAddress.ABIS_MIDDLEWARE_BUS_OUT)); + this.createServer(router.getRouter(), getPort()); + + } + + @Override + protected String getPropertyPrefix() { + return STAGE_PROPERTY_PREFIX; + } + + + @Override + public MessageDTO process(MessageDTO object) { + TrimExceptionMessage trimExceptionMessage = new TrimExceptionMessage(); + object.setMessageBusAddress(MessageBusAddress.ABIS_MIDDLEWARE_BUS_IN); + object.setIsValid(false); + object.setInternalError(false); + boolean isTransactionSuccessful = false; + LogDescription description = new LogDescription(); + String registrationId = object.getRid(); + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + registrationId, "AbisMiddlewareStage::process()::entry"); + InternalRegistrationStatusDto internalRegDto = registrationStatusService.getRegistrationStatus( + registrationId, object.getReg_type(), object.getIteration(), object.getWorkflowInstanceId()); + try { + List abisRefList = packetInfoManager.getReferenceIdByWorkflowInstanceId(object.getWorkflowInstanceId()); + validateNullCheck(abisRefList, "ABIS_REFERENCE_ID_NOT_FOUND"); + + String refRegtrnId = getLatestTransactionId(registrationId, + object.getReg_type(), object.getIteration(), object.getWorkflowInstanceId()); + validateNullCheck(refRegtrnId, "LATEST_TRANSACTION_ID_NOT_FOUND"); + String abisRefId = abisRefList.get(0); + List abisInsertIdentifyList = packetInfoManager.getInsertOrIdentifyRequest(abisRefId, + refRegtrnId); + validateNullCheck(abisInsertIdentifyList, "IDENTIFY_REQUESTS_NOT_FOUND"); + // get all insert requests(already processed,in progress) + List abisInsertRequestList = abisInsertIdentifyList.stream() + .filter(dto -> dto.getRequestType().equals(AbisStatusCode.INSERT.toString())) + .collect(Collectors.toList()); + List abisInprogressInsertRequestList = abisInsertRequestList.stream() + .filter(dto -> dto.getStatusCode().equals(AbisStatusCode.IN_PROGRESS.toString())) + .collect(Collectors.toList()); + List abisAlreadyprocessedInsertRequestList = abisInsertRequestList.stream() + .filter(dto -> dto.getStatusCode().equals(AbisStatusCode.ALREADY_PROCESSED.toString())) + .collect(Collectors.toList()); + List abisIdentifyRequestList = abisInsertIdentifyList.stream() + .filter(dto -> dto.getRequestType().equals(AbisStatusCode.IDENTIFY.toString())) + .collect(Collectors.toList()); + + processInsertIdentify(abisInsertRequestList, abisIdentifyRequestList, abisInprogressInsertRequestList, + internalRegDto, abisAlreadyprocessedInsertRequestList); + + object.setIsValid(true); + object.setInternalError(false); + isTransactionSuccessful = true; + description.setMessage(PlatformSuccessMessages.RPR_ABIS_MIDDLEWARE_STAGE_SUCCESS.getMessage()); + description.setCode(PlatformSuccessMessages.RPR_ABIS_MIDDLEWARE_STAGE_SUCCESS.getCode()); + + regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + registrationId, "AbisMiddlewareStage::process()::Abis insertRequests sucessfully sent to Queue"); + } catch (RegistrationProcessorCheckedException e) { + object.setInternalError(true); + description.setMessage(PlatformErrorMessages.UNKNOWN_EXCEPTION_OCCURED.getMessage()); + description.setCode(PlatformErrorMessages.UNKNOWN_EXCEPTION_OCCURED.getCode()); + internalRegDto.setLatestTransactionStatusCode(RegistrationTransactionStatusCode.REPROCESS.toString()); + internalRegDto.setStatusComment(trimExceptionMessage + .trimExceptionMessage(StatusUtil.SYSTEM_EXCEPTION_OCCURED.getMessage() + e.getMessage())); + internalRegDto.setSubStatusCode(StatusUtil.SYSTEM_EXCEPTION_OCCURED.getCode()); + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + registrationId, ExceptionUtils.getStackTrace(e)); + } catch (Exception e) { + object.setInternalError(true); + description.setMessage(PlatformErrorMessages.UNKNOWN_EXCEPTION_OCCURED.getMessage()); + description.setCode(PlatformErrorMessages.UNKNOWN_EXCEPTION_OCCURED.getCode()); + internalRegDto.setLatestTransactionStatusCode(RegistrationTransactionStatusCode.REPROCESS.toString()); + internalRegDto.setStatusComment(trimExceptionMessage + .trimExceptionMessage(StatusUtil.UNKNOWN_EXCEPTION_OCCURED.getMessage() + e.getMessage())); + internalRegDto.setSubStatusCode(StatusUtil.SYSTEM_EXCEPTION_OCCURED.getCode()); + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + registrationId, ExceptionUtils.getStackTrace(e)); + } finally { + if (!isTransactionSuccessful) { + String transactionTypeCode = ""; + if (transactionTypeCode.equalsIgnoreCase(DEMOGRAPHIC_VERIFICATION)) { + internalRegDto.setRegistrationStageName("DemoDedupeStage"); + } else if (transactionTypeCode.equalsIgnoreCase(BIOGRAPHIC_VERIFICATION)) { + internalRegDto.setRegistrationStageName("BioDedupeStage"); + } + updateErrorFlags(internalRegDto, object); + String moduleId = description.getCode(); + String moduleName = ModuleName.ABIS_MIDDLEWARE.toString(); + registrationStatusService.updateRegistrationStatus(internalRegDto, moduleId, moduleName); + } + + String eventId = isTransactionSuccessful ? EventId.RPR_402.toString() : EventId.RPR_405.toString(); + String eventName = isTransactionSuccessful ? EventName.UPDATE.toString() : EventName.EXCEPTION.toString(); + String eventType = isTransactionSuccessful ? EventType.BUSINESS.toString() : EventType.SYSTEM.toString(); + + /** Module-Id can be Both Success/Error code */ + String moduleId = isTransactionSuccessful + ? PlatformSuccessMessages.RPR_ABIS_MIDDLEWARE_STAGE_SUCCESS.getCode() + : description.getCode(); + String moduleName = ModuleName.ABIS_MIDDLEWARE.toString(); + + auditLogRequestBuilder.createAuditRequestBuilder(description.getMessage(), eventId, eventName, eventType, + moduleId, moduleName, registrationId); + } + return object; + } + + private void processInsertIdentify(List abisInsertRequestList, + List abisIdentifyRequestList, List abisInprogressInsertRequestList, + InternalRegistrationStatusDto internalRegDto, List abisAlreadyprocessedInsertRequestList) + throws RegistrationProcessorCheckedException { + // If all insert request are null then send all identify requests. + if (abisInsertRequestList.isEmpty()) { + for (AbisRequestDto abisIdentifyRequest : abisIdentifyRequestList) { + List abisQueue = abisQueueDetails.stream() + .filter(dto -> dto.getName().equals(abisIdentifyRequest.getAbisAppCode())) + .collect(Collectors.toList()); + validateNullCheck(abisQueue, ABIS_QUEUE_NOT_FOUND); + byte[] reqBytearray = abisIdentifyRequest.getReqText(); + + boolean isAddedToQueue = sendToQueue(abisQueue.get(0).getMosipQueue(), new String(reqBytearray), + abisQueue.get(0).getInboundQueueName(), abisQueue.get(0).getInboundMessageTTL()); + + updateAbisRequest(isAddedToQueue, abisIdentifyRequest, internalRegDto); + } + + } + // send in progress insert requests to queue + for (AbisRequestDto abisInprogressRequest : abisInprogressInsertRequestList) { + List abisQueue = abisQueueDetails.stream() + .filter(dto -> dto.getName().equals(abisInprogressRequest.getAbisAppCode())) + .collect(Collectors.toList()); + validateNullCheck(abisQueue, ABIS_QUEUE_NOT_FOUND); + + byte[] reqBytearray = abisInprogressRequest.getReqText(); + + boolean isAddedToQueue = sendToQueue(abisQueue.get(0).getMosipQueue(), new String(reqBytearray), + abisQueue.get(0).getInboundQueueName(), abisQueue.get(0).getInboundMessageTTL()); + + updateAbisRequest(isAddedToQueue, abisInprogressRequest, internalRegDto); + } + // send all identify requests for already processed insert requests + for (AbisRequestDto abisAlreadyProcessedInsertRequest : abisAlreadyprocessedInsertRequestList) { + List abisQueue = abisQueueDetails.stream() + .filter(dto -> dto.getName().equals(abisAlreadyProcessedInsertRequest.getAbisAppCode())) + .collect(Collectors.toList()); + validateNullCheck(abisQueue, ABIS_QUEUE_NOT_FOUND); + List identifyRequest = abisIdentifyRequestList.stream() + .filter(dto -> dto.getAbisAppCode().equals(abisAlreadyProcessedInsertRequest.getAbisAppCode())) + .collect(Collectors.toList()); + byte[] reqBytearray = identifyRequest.get(0).getReqText(); + boolean isAddedToQueue = sendToQueue(abisQueue.get(0).getMosipQueue(), new String(reqBytearray), + abisQueue.get(0).getInboundQueueName(), abisQueue.get(0).getInboundMessageTTL()); + updateAbisRequest(isAddedToQueue, identifyRequest.get(0), internalRegDto); + + } + } + + public void consumerListener(Message message, String abisInBoundAddress, MosipQueue queue, + MosipEventBus eventBus, int inboundMessageTTL) + throws RegistrationProcessorCheckedException { + TrimExceptionMessage trimExceptionMessage = new TrimExceptionMessage(); + InternalRegistrationStatusDto internalRegStatusDto = null; + String registrationId = null; + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", + "AbisMiddlewareStage::consumerListener()::entry"); + String moduleId = ""; + String moduleName = ModuleName.ABIS_MIDDLEWARE.toString(); + boolean isTransactionSuccessful = true; + String response = null; + LogDescription description = new LogDescription(); + try { + if (messageFormat.equalsIgnoreCase(TEXT_MESSAGE)) { + TextMessage textMessage = (TextMessage) message; + response =textMessage.getText(); + } else + response = new String(((ActiveMQBytesMessage) message).getContent().data); + JSONObject inserOrIdentifyResponse = JsonUtil.objectMapperReadValue(response, JSONObject.class); + String requestId = JsonUtil.getJSONValue(inserOrIdentifyResponse, REQUESTID); + String batchId = packetInfoManager.getBatchIdByRequestId(requestId); + validateNullCheck(batchId, "ABIS_BATCH_ID_NOT_FOUND"); + List bioRefId = packetInfoManager.getReferenceIdByBatchId(batchId); + validateNullCheck(bioRefId, "ABIS_REFERENCE_ID_NOT_FOUND"); + + List regBioRefist = packetInfoManager.getRegBioRefDataByBioRefIds(bioRefId); + RegBioRefDto regBioRefDto = regBioRefist.get(0); + registrationId = regBioRefDto.getRegId(); + internalRegStatusDto = registrationStatusService.getRegistrationStatus(registrationId, + regBioRefDto.getProcess(), regBioRefDto.getIteration(), regBioRefDto.getWorkflowInstanceId()); + regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", + "AbisMiddlewareStage::consumerListener()::response from abis for requestId ::" + requestId); + + AbisRequestDto abisCommonRequestDto = packetInfoManager.getAbisRequestByRequestId(requestId); + // check for insert response,if success send corresponding identify request to + // queue + if (abisCommonRequestDto.getRequestType().equals(AbisStatusCode.INSERT.toString())) { + if (AbisStatusCode.SENT.toString().equals(abisCommonRequestDto.getStatusCode())) { + + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", + "AbisMiddlewareStage::consumerListener()::Insert Response received from abis ::" + + inserOrIdentifyResponse); + AbisInsertResponseDto abisInsertResponseDto = JsonUtil.objectMapperReadValue(response, + AbisInsertResponseDto.class); + + if (abisInsertResponseDto.getFailureReason() != null && abisInsertResponseDto.getFailureReason().equalsIgnoreCase("10")) + regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), + "Received failure response from abis.", + "Reference id already present for requestId : " + requestId +". Regproc will pass this insert response."); + + updateAbisResponseEntity(abisInsertResponseDto, response); + updteAbisRequestProcessed(abisInsertResponseDto, abisCommonRequestDto); + if (isInsertSuccess(abisInsertResponseDto)) { + List transactionIdList = packetInfoManager.getAbisTransactionIdByRequestId(requestId); + validateNullCheck(transactionIdList, "LATEST_TRANSACTION_ID_NOT_FOUND"); + List abisIdentifyRequestList = packetInfoManager.getIdentifyReqListByTransactionId( + transactionIdList.get(0), AbisStatusCode.IDENTIFY.toString()); + List abisIdentifyRequest = abisIdentifyRequestList.stream() + .filter(dto1 -> dto1.getAbisAppCode().equals(abisCommonRequestDto.getAbisAppCode())) + .collect(Collectors.toList()); + validateNullCheck(abisIdentifyRequest, "IDENTIFY_REQUESTS_NOT_FOUND"); + AbisRequestDto abisIdentifyRequestDto = abisIdentifyRequest.get(0); + boolean isAddedToQueue = sendToQueue(queue, new String(abisIdentifyRequestDto.getReqText()), + abisInBoundAddress, inboundMessageTTL); + updateAbisRequest(isAddedToQueue, abisIdentifyRequestDto, internalRegStatusDto); + } else { + internalRegStatusDto + .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.REPROCESS.toString()); + internalRegStatusDto.setStatusComment( + StatusUtil.INSERT_RESPONSE_FAILED.getMessage() + abisCommonRequestDto.getId() +"- failure reason - "+abisInsertResponseDto.getFailureReason() + "-" + + io.mosip.registartion.processor.abis.middleware.constants.FailureReason + .getValueFromKey(abisInsertResponseDto.getFailureReason())); + internalRegStatusDto.setSubStatusCode(StatusUtil.SYSTEM_EXCEPTION_OCCURED.getCode()); + moduleId = PlatformErrorMessages.SYSTEM_EXCEPTION_OCCURED.getCode(); + registrationStatusService.updateRegistrationStatus(internalRegStatusDto, moduleId, moduleName); + } + + } else { + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), + "", + "AbisMiddlewareStage::consumerListener()::Duplicate Insert Response received from abis for same request id ::" + + requestId + " response " + inserOrIdentifyResponse); + isTransactionSuccessful = false; + description.setMessage(PlatformErrorMessages.DUPLICATE_INSERT_RESPONSE.getMessage() + requestId); + description.setCode(PlatformErrorMessages.DUPLICATE_INSERT_RESPONSE.getCode()); + + } + } + // check if identify response,then if all identify requests are processed send + // to abis handler + if (abisCommonRequestDto.getRequestType().equals(AbisStatusCode.IDENTIFY.toString())) { + if (AbisStatusCode.SENT.toString().equals(abisCommonRequestDto.getStatusCode())) { + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", + "AbisMiddlewareStage::consumerListener()::Identify Response received from abis ::" + + inserOrIdentifyResponse); + + AbisIdentifyResponseDto abisIdentifyResponseDto = JsonUtil.readValueWithUnknownProperties(response, + AbisIdentifyResponseDto.class); + if (!abisIdentifyResponseDto.getReturnValue().equalsIgnoreCase("1")){ + internalRegStatusDto + .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.REPROCESS.toString()); + internalRegStatusDto.setStatusComment( + StatusUtil.IDENTIFY_RESPONSE_FAILED.getMessage() + abisCommonRequestDto.getId()+"- failure reason -"+abisIdentifyResponseDto.getFailureReason() + "-" + + io.mosip.registartion.processor.abis.middleware.constants.FailureReason + .getValueFromKey(abisIdentifyResponseDto.getFailureReason())); + internalRegStatusDto.setSubStatusCode(StatusUtil.SYSTEM_EXCEPTION_OCCURED.getCode()); + moduleId = PlatformErrorMessages.SYSTEM_EXCEPTION_OCCURED.getCode(); + registrationStatusService.updateRegistrationStatus(internalRegStatusDto, moduleId, moduleName); + } + AbisResponseDto abisResponseDto = updateAbisResponseEntity(abisIdentifyResponseDto, response); + if (abisIdentifyResponseDto.getCandidateList() != null) { + CandidatesDto[] candidatesDtos = abisIdentifyResponseDto.getCandidateList().getCandidates(); + if (!Arrays.isNullOrEmpty(candidatesDtos)) { + saveCandiateDtos(candidatesDtos, abisResponseDto, bioRefId.get(0)); + } + } + updteAbisRequestProcessed(abisIdentifyResponseDto, abisCommonRequestDto); + + if (checkAllIdentifyRequestsProcessed(batchId)) { + + regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), + "", + "AbisMiddlewareStage::consumerListener()::All identify are requests processed sending to Abis handler"); + + sendToAbisHandler(eventBus, bioRefId, registrationId, internalRegStatusDto.getRegistrationType(), + internalRegStatusDto.getIteration(), internalRegStatusDto.getWorkflowInstanceId()); + + } + } else { + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), + "", + "AbisMiddlewareStage::consumerListener()::Duplicate Identify Response received from abis for same request id ::" + + requestId + " response " + inserOrIdentifyResponse); + isTransactionSuccessful = false; + description.setMessage(PlatformErrorMessages.DUPLICATE_IDENTITY_RESPONSE.getMessage() + requestId); + description.setCode(PlatformErrorMessages.DUPLICATE_IDENTITY_RESPONSE.getCode()); + + } + } + + } catch (IOException e) { + if (internalRegStatusDto != null) { + internalRegStatusDto + .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.REPROCESS.toString()); + internalRegStatusDto.setStatusComment(trimExceptionMessage + .trimExceptionMessage(StatusUtil.IO_EXCEPTION.getMessage() + e.getMessage())); + internalRegStatusDto.setSubStatusCode(StatusUtil.SYSTEM_EXCEPTION_OCCURED.getCode()); + moduleId = PlatformErrorMessages.SYSTEM_EXCEPTION_OCCURED.getCode(); + registrationStatusService.updateRegistrationStatus(internalRegStatusDto, moduleId, moduleName); + } + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + registrationId, ExceptionUtils.getStackTrace(e)); + throw new RegistrationProcessorCheckedException(PlatformErrorMessages.RPR_SYS_IO_EXCEPTION.getCode(), + PlatformErrorMessages.RPR_SYS_IO_EXCEPTION.getMessage(), e); + } catch (Exception e) { + if (internalRegStatusDto != null) { + internalRegStatusDto + .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.REPROCESS.toString()); + internalRegStatusDto.setStatusComment(trimExceptionMessage + .trimExceptionMessage(StatusUtil.UNKNOWN_EXCEPTION_OCCURED.getMessage() + e.getMessage())); + internalRegStatusDto.setSubStatusCode(StatusUtil.SYSTEM_EXCEPTION_OCCURED.getCode()); + moduleId = PlatformErrorMessages.SYSTEM_EXCEPTION_OCCURED.getCode(); + registrationStatusService.updateRegistrationStatus(internalRegStatusDto, moduleId, moduleName); + } + + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + registrationId, ExceptionUtils.getStackTrace(e)); + } finally { + if (!isTransactionSuccessful) { + String eventId = EventId.RPR_405.toString(); + String eventName = EventName.EXCEPTION.toString(); + String eventType = EventType.SYSTEM.toString(); + moduleId = description.getCode(); + moduleName = ModuleName.ABIS_MIDDLEWARE.toString(); + auditLogRequestBuilder.createAuditRequestBuilder(description.getMessage(), eventId, eventName, + eventType, moduleId, moduleName, registrationId); + } + + } + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", + "AbisMiddlewareStage::consumerListener()::Exit()"); + } + + private void validateNullCheck(Object obj, String errorMessage) { + if (obj == null) { + throw new RegistrationProcessorUnCheckedException(PlatformErrorMessages.valueOf(errorMessage).getCode(), + PlatformErrorMessages.valueOf(errorMessage).getMessage()); + } + if (obj instanceof Collection) { + List genericList = new ArrayList<>((Collection) obj); + if (genericList.isEmpty()) { + throw new RegistrationProcessorUnCheckedException(PlatformErrorMessages.valueOf(errorMessage).getCode(), + PlatformErrorMessages.valueOf(errorMessage).getMessage()); + } + } + + } + + private boolean sendToQueue(MosipQueue queue, String abisReqTextString, String abisQueueAddress, + int messageTTL) throws RegistrationProcessorCheckedException { + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", + "AbisMiddlewareStage::sendToQueue()::Entry"); + boolean isAddedToQueue; + try { + if (messageFormat.equalsIgnoreCase(TEXT_MESSAGE)) + isAddedToQueue = mosipQueueManager.send(queue, abisReqTextString, + abisQueueAddress, messageTTL); + else + isAddedToQueue = mosipQueueManager.send(queue, abisReqTextString.getBytes(), + abisQueueAddress, messageTTL); + + regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", + "AbisMiddlewareStage:: sent to abis queue ::" + abisReqTextString); + + } catch (Exception e) { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + "", ExceptionUtils.getStackTrace(e)); + throw new RegistrationProcessorCheckedException(PlatformErrorMessages.RPR_SYS_IO_EXCEPTION.getCode(), + PlatformErrorMessages.RPR_SYS_IO_EXCEPTION.getMessage(), e); + } + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", + "AbisMiddlewareStage::sendToQueue()::Exit"); + return isAddedToQueue; + } + + private void updateAbisRequest(boolean isAddedToQueue, AbisRequestDto abisRequestDto, + InternalRegistrationStatusDto internalRegDto) { + AbisRequestEntity abisReqEntity = convertAbisRequestDtoToAbisRequestEntity(abisRequestDto); + + if (isAddedToQueue) { + + abisReqEntity.setStatusCode(AbisStatusCode.SENT.toString()); + abisReqEntity.setStatusComment( + StatusUtil.INSERT_IDENTIFY_REQUEST_SUCCESS.getMessage() + abisRequestDto.getAbisAppCode()); + } else { + abisReqEntity.setStatusCode(AbisStatusCode.FAILED.toString()); + abisReqEntity.setStatusComment( + StatusUtil.INSERT_IDENTIFY_REQUEST_FAILED.getMessage() + abisRequestDto.getAbisAppCode()); + internalRegDto.setLatestTransactionStatusCode(RegistrationTransactionStatusCode.REPROCESS.toString()); + internalRegDto.setStatusComment( + StatusUtil.INSERT_IDENTIFY_REQUEST_FAILED.getMessage() + abisRequestDto.getAbisAppCode()); + internalRegDto.setSubStatusCode(StatusUtil.SYSTEM_EXCEPTION_OCCURED.getCode()); + } + abisRequestRepositary.save(abisReqEntity); + + } + + private void updteAbisRequestProcessed(AbisCommonResponseDto abisCommonResponseDto, + AbisRequestDto abisCommonRequestDto) { + AbisRequestEntity abisReqEntity = new AbisRequestEntity(); + AbisRequestPKEntity abisReqPKEntity = new AbisRequestPKEntity(); + abisReqPKEntity.setId(abisCommonResponseDto.getRequestId()); + abisReqEntity.setId(abisReqPKEntity); + abisReqEntity.setStatusCode(isInsertSuccess(abisCommonResponseDto) ? AbisStatusCode.PROCESSED.toString() + : AbisStatusCode.FAILED.toString()); + if (isInsertSuccess(abisCommonResponseDto)) { + abisReqEntity.setStatusComment(StatusUtil.INSERT_IDENTIFY_RESPONSE_SUCCESS.getMessage()); + } else { + abisReqEntity.setStatusComment(io.mosip.registartion.processor.abis.middleware.constants.FailureReason + .getValueFromKey(abisCommonResponseDto.getFailureReason())); + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), + "Abis response failed for "+packetInfoDao.getRegIdByBioRefId(abisCommonRequestDto.getBioRefId())+" due to " + abisCommonResponseDto.getFailureReason() + "-" + + io.mosip.registartion.processor.abis.middleware.constants.FailureReason + .getValueFromKey(abisCommonResponseDto.getFailureReason()), + "AbisMiddleWareStage::updteAbisRequestProcessed()"); + + } + abisReqEntity.setAbisAppCode(abisCommonRequestDto.getAbisAppCode()); + abisReqEntity.setRequestType(abisCommonRequestDto.getRequestType()); + abisReqEntity.setRequestDtimes(abisCommonRequestDto.getRequestDtimes()); + abisReqEntity.setReqBatchId(abisCommonRequestDto.getReqBatchId()); + abisReqEntity.setLangCode(abisCommonRequestDto.getLangCode()); + abisReqEntity.setCrBy(SYSTEM); + abisReqEntity.setCrDtimes(abisCommonRequestDto.getCrDtimes()); + abisReqEntity.setBioRefId(abisCommonRequestDto.getBioRefId()); + abisReqEntity.setRefRegtrnId(abisCommonRequestDto.getRefRegtrnId()); + abisReqEntity.setReqText(abisCommonRequestDto.getReqText()); + abisRequestRepositary.save(abisReqEntity); + } + + private AbisRequestEntity convertAbisRequestDtoToAbisRequestEntity(AbisRequestDto abisRequestDto) { + AbisRequestEntity abisReqEntity = new AbisRequestEntity(); + AbisRequestPKEntity abisReqPKEntity = new AbisRequestPKEntity(); + abisReqPKEntity.setId(abisRequestDto.getId()); + abisReqEntity.setId(abisReqPKEntity); + abisReqEntity.setAbisAppCode(abisRequestDto.getAbisAppCode()); + abisReqEntity.setBioRefId(abisRequestDto.getBioRefId()); + abisReqEntity.setCrBy(abisRequestDto.getCrBy()); + if (abisRequestDto.getCrDtimes() == null) { + abisReqEntity.setCrDtimes(LocalDateTime.now(ZoneId.of("UTC"))); + } else { + abisReqEntity.setCrDtimes(abisRequestDto.getCrDtimes()); + } + abisReqEntity.setIsDeleted(false); + abisReqEntity.setLangCode(abisRequestDto.getLangCode()); + abisReqEntity.setRefRegtrnId(abisRequestDto.getRefRegtrnId()); + abisReqEntity.setReqBatchId(abisRequestDto.getReqBatchId()); + abisReqEntity.setReqText(abisRequestDto.getReqText()); + abisReqEntity.setRequestDtimes(abisRequestDto.getRequestDtimes()); + abisReqEntity.setRequestType(abisRequestDto.getRequestType()); + abisReqEntity.setStatusCode(abisRequestDto.getStatusCode()); + abisReqEntity.setStatusComment(abisRequestDto.getStatusComment()); + abisReqEntity.setUpdBy(abisRequestDto.getUpdBy()); + abisReqEntity.setUpdDtimes(LocalDateTime.now(ZoneId.of("UTC"))); + return abisReqEntity; + + } + + private AbisResponseEntity convertAbisResponseDtoToAbisResponseEntity(AbisResponseDto abisResponseDto) { + AbisResponseEntity abisResponseEntity = new AbisResponseEntity(); + AbisResponsePKEntity abisResponsePKEntity = new AbisResponsePKEntity(); + abisResponsePKEntity.setId(abisResponseDto.getId()); + abisResponseEntity.setId(abisResponsePKEntity); + abisResponseEntity.setAbisRequest(abisResponseDto.getAbisRequest()); + abisResponseEntity.setRespText(abisResponseDto.getRespText()); + abisResponseEntity.setStatusCode(abisResponseDto.getStatusCode()); + abisResponseEntity.setStatusComment(abisResponseDto.getStatusComment()); + abisResponseEntity.setLangCode(abisResponseDto.getLangCode()); + abisResponseEntity.setCrBy(abisResponseDto.getCrBy()); + if (abisResponseDto.getCrDtimes() == null) { + abisResponseEntity.setCrDtimes(LocalDateTime.now(ZoneId.of("UTC"))); + } else { + abisResponseEntity.setCrDtimes(abisResponseDto.getCrDtimes()); + } + abisResponseEntity.setUpdBy(abisResponseDto.getUpdBy()); + abisResponseEntity.setUpdDtimes(abisResponseDto.getUpdDtimes()); + abisResponseEntity.setIsDeleted(abisResponseDto.getIsDeleted()); + abisResponseEntity.setRespDtimes(LocalDateTime.now(ZoneId.of("UTC"))); + + return abisResponseEntity; + + } + + private AbisResponseDto updateAbisResponseEntity(AbisCommonResponseDto abisCommonResponseDto, String response) { + AbisResponseDto abisResponseDto = new AbisResponseDto(); + + abisResponseDto.setId(RegistrationUtility.generateId()); + abisResponseDto.setRespText(response.getBytes()); + + if (isInsertSuccess(abisCommonResponseDto)) { + abisResponseDto.setStatusCode(AbisStatusCode.SUCCESS.toString()); + } else { + abisResponseDto.setStatusCode(AbisStatusCode.FAILED.toString()); + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), + "Abis response failed for request Id " + abisCommonResponseDto.getRequestId() + " due to " + + abisCommonResponseDto.getFailureReason() + "-" + + io.mosip.registartion.processor.abis.middleware.constants.FailureReason + .getValueFromKey(abisCommonResponseDto.getFailureReason()), + "AbisMiddleWareStage::updateAbisResponseEntity()"); + } + + abisResponseDto.setStatusComment(io.mosip.registartion.processor.abis.middleware.constants.FailureReason.getValueFromKey(abisCommonResponseDto.getFailureReason())); + abisResponseDto.setLangCode("eng"); + abisResponseDto.setCrBy(SYSTEM); + abisResponseDto.setUpdBy(SYSTEM); + abisResponseDto.setUpdDtimes(LocalDateTime.now(ZoneId.of("UTC"))); + abisResponseDto.setIsDeleted(false); + abisResponseDto.setAbisRequest(abisCommonResponseDto.getRequestId()); + abisResponseRepositary.save(convertAbisResponseDtoToAbisResponseEntity(abisResponseDto)); + + return abisResponseDto; + } + + private void updateAbisResponseDetail(CandidatesDto candidatesDto, AbisResponseDto abisResponseDto, + String bioRefId) { + + if (!candidatesDto.getReferenceId().equalsIgnoreCase(bioRefId)) { + + String candidateRegId = packetInfoDao.getRegIdByBioRefId(candidatesDto.getReferenceId().toLowerCase()); + if (candidateRegId == null || candidateRegId.isEmpty()) + return; + AbisResponseDetEntity abisResponseDetEntity = new AbisResponseDetEntity(); + AbisResponseDetPKEntity abisResponseDetPKEntity = new AbisResponseDetPKEntity(); + abisResponseDetPKEntity.setAbisRespId(abisResponseDto.getId()); + abisResponseDetPKEntity.setMatchedBioRefId(candidatesDto.getReferenceId().toLowerCase()); + abisResponseDetEntity.setId(abisResponseDetPKEntity); + abisResponseDetEntity.setCrBy(SYSTEM); + abisResponseDetEntity.setUpdBy(SYSTEM); + abisResponseDetEntity.setIsDeleted(false); + abisResponseDetEntity.setCrDtimes(LocalDateTime.now(ZoneId.of("UTC"))); + abisResponseDetEntity.setUpdDtimes(LocalDateTime.now(ZoneId.of("UTC"))); + abisResponseDetailRepositary.save(abisResponseDetEntity); + + } + + } + + private String getLatestTransactionId(String registrationId, String process, int iteration, String workflowInstanceId) { + RegistrationStatusEntity entity = registrationStatusDao.find(registrationId, process, iteration, workflowInstanceId); + return entity != null ? entity.getLatestRegistrationTransactionId() : null; + + } + + private boolean checkAllIdentifyRequestsProcessed(String batchId) { + List batchStatus = packetInfoManager.getBatchStatusbyBatchId(batchId); + if (batchStatus != null) { + boolean flag = batchStatus.stream().allMatch(status -> status.equals(AbisStatusCode.PROCESSED.toString())); + if (flag) + return true; + } + return false; + } + + private void sendToAbisHandler(MosipEventBus eventBus, List bioRefId, + String regId, String regType, int iteration, String workflowInstanceId) { + if (bioRefId != null) { + MessageDTO messageDto = new MessageDTO(); + messageDto.setRid(regId); + messageDto.setReg_type(regType); + messageDto.setIsValid(Boolean.TRUE); + messageDto.setInternalError(Boolean.FALSE); + messageDto.setIteration(iteration); + messageDto.setWorkflowInstanceId(workflowInstanceId); + regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", + "AbisMiddlewareStage::consumerListener()::sending to Abis handler"); + this.send(eventBus, MessageBusAddress.ABIS_MIDDLEWARE_BUS_OUT, messageDto); + regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", + "AbisMiddlewareStage::consumerListener()::sent to Abis handler"); + } + + } + + private void saveCandiateDtos(CandidatesDto[] candidatesDtos, AbisResponseDto abisResponseDto, String bioRefId) { + for (CandidatesDto candidatesDto : candidatesDtos) { + updateAbisResponseDetail(candidatesDto, abisResponseDto, bioRefId); + } + } + + private void updateErrorFlags(InternalRegistrationStatusDto registrationStatusDto, MessageDTO object) { + object.setInternalError(true); + if (registrationStatusDto.getLatestTransactionStatusCode() + .equalsIgnoreCase(RegistrationTransactionStatusCode.REPROCESS.toString())) { + object.setIsValid(true); + } else { + object.setIsValid(false); + } + } + + /** + * If return value is 1 or failure reason is 10(which means ABIS has already processed the + * reference id) then return true + * @param abisInsertResponseDto + * @return boolean + */ + private boolean isInsertSuccess(AbisCommonResponseDto abisInsertResponseDto) { + return abisInsertResponseDto.getReturnValue().equalsIgnoreCase("1") + || (abisInsertResponseDto.getFailureReason() != null + && abisInsertResponseDto.getFailureReason().equalsIgnoreCase("10")); + } + } \ No newline at end of file diff --git a/registration-processor/core-processor/registration-processor-bio-dedupe-stage/src/main/java/io/mosip/registration/processor/biodedupe/service/CbeffValidateAndVerificatonService.java b/registration-processor/core-processor/registration-processor-bio-dedupe-stage/src/main/java/io/mosip/registration/processor/biodedupe/service/CbeffValidateAndVerificatonService.java index bdad19b7636..6f2b006810d 100644 --- a/registration-processor/core-processor/registration-processor-bio-dedupe-stage/src/main/java/io/mosip/registration/processor/biodedupe/service/CbeffValidateAndVerificatonService.java +++ b/registration-processor/core-processor/registration-processor-bio-dedupe-stage/src/main/java/io/mosip/registration/processor/biodedupe/service/CbeffValidateAndVerificatonService.java @@ -1,87 +1,93 @@ -package io.mosip.registration.processor.biodedupe.service; - -import java.io.IOException; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.stream.Collectors; - -import org.json.simple.JSONObject; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.stereotype.Service; -import org.springframework.util.CollectionUtils; - -import io.mosip.kernel.biometrics.entities.BiometricRecord; -import io.mosip.kernel.core.logger.spi.Logger; -import io.mosip.kernel.core.util.exception.JsonProcessingException; -import io.mosip.registration.processor.biodedupe.stage.exception.CbeffNotFoundException; -import io.mosip.registration.processor.core.constant.LoggerFileConstant; -import io.mosip.registration.processor.core.constant.MappingJsonConstants; -import io.mosip.registration.processor.core.constant.ProviderStageName; -import io.mosip.registration.processor.core.exception.ApisResourceAccessException; -import io.mosip.registration.processor.core.exception.PacketManagerException; -import io.mosip.registration.processor.core.logger.RegProcessorLogger; -import io.mosip.registration.processor.core.util.JsonUtil; -import io.mosip.registration.processor.packet.storage.utils.PriorityBasedPacketManagerService; -import io.mosip.registration.processor.packet.storage.utils.Utilities; - -@Service -public class CbeffValidateAndVerificatonService { - private static Logger regProcLogger = RegProcessorLogger.getLogger(CbeffValidateAndVerificatonService.class); - - @Value("${registration.processor.policy.id}") - private String policyId; - - @Value("${registration.processor.subscriber.id}") - private String subscriberId; - - @Value("#{'${mosip.regproc.cbeff-validation.mandatory.modalities:Right,Left,Left RingFinger,Left LittleFinger," - + "Right RingFinger,Left Thumb,Left IndexFinger,Right IndexFinger,Right LittleFinger,Right MiddleFinger," - + "Left MiddleFinger,Right Thumb,Face}'.split(',')}") - private List mandatoryModalities ; - - /** The utilities. */ - @Autowired - Utilities utilities; - - @Autowired - private PriorityBasedPacketManagerService priorityBasedPacketManagerService; - - - public void validateBiometrics(String id, String process) - throws ApisResourceAccessException, IOException, PacketManagerException, JsonProcessingException { - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - id, "CbeffValidateAndVerificatonService::validateBiometrics()::entry"); - JSONObject regProcessorIdentityJson = utilities.getRegistrationProcessorMappingJson(MappingJsonConstants.IDENTITY); - String individualBiometricsLabel = JsonUtil.getJSONValue(JsonUtil.getJSONObject( - regProcessorIdentityJson, MappingJsonConstants.INDIVIDUAL_BIOMETRICS), MappingJsonConstants.VALUE); - - BiometricRecord biometricRecord = priorityBasedPacketManagerService.getBiometrics(id, individualBiometricsLabel, - mandatoryModalities, process, ProviderStageName.BIO_DEDUPE); - - Set availableModalities = biometricRecord != null && !CollectionUtils.isEmpty(biometricRecord.getSegments()) ? - biometricRecord.getSegments().stream().map(b -> { - if(!CollectionUtils.isEmpty(b.getBdbInfo().getType())) { - for(Map.Entry entry : b.getOthers().entrySet()) { - if(entry.getKey().equals("EXCEPTION") &&!entry.getValue().equals("true")) { - return b.getBdbInfo().getSubtype()!=null && !b.getBdbInfo().getSubtype().isEmpty()? - String.join(" ", b.getBdbInfo().getSubtype()) - :b.getBdbInfo().getType().get(0).value(); - } - } - } - return null; - }).collect(Collectors.toSet()) : null; - - boolean isBiometricsNotPresent = availableModalities != null ? mandatoryModalities.stream().noneMatch( - modalities -> availableModalities.contains(modalities)) : true; - - if (isBiometricsNotPresent) - throw new CbeffNotFoundException("Biometrics not found for : " + id); - - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - id, "CbeffValidateAndVerificatonService::validateBiometrics()::exit" ); - } - -} +package io.mosip.registration.processor.biodedupe.service; + +import java.io.IOException; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + +import org.json.simple.JSONObject; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; +import org.springframework.util.CollectionUtils; + +import io.mosip.kernel.biometrics.entities.BiometricRecord; +import io.mosip.kernel.core.logger.spi.Logger; +import io.mosip.kernel.core.util.exception.JsonProcessingException; +import io.mosip.registration.processor.biodedupe.stage.exception.CbeffNotFoundException; +import io.mosip.registration.processor.core.constant.LoggerFileConstant; +import io.mosip.registration.processor.core.constant.MappingJsonConstants; +import io.mosip.registration.processor.core.constant.ProviderStageName; +import io.mosip.registration.processor.core.exception.ApisResourceAccessException; +import io.mosip.registration.processor.core.exception.PacketManagerException; +import io.mosip.registration.processor.core.logger.RegProcessorLogger; +import io.mosip.registration.processor.core.util.JsonUtil; +import io.mosip.registration.processor.packet.storage.utils.PriorityBasedPacketManagerService; +import io.mosip.registration.processor.packet.storage.utils.Utilities; + +@Service +public class CbeffValidateAndVerificatonService { + private static Logger regProcLogger = RegProcessorLogger.getLogger(CbeffValidateAndVerificatonService.class); + + @Value("${registration.processor.policy.id}") + private String policyId; + + @Value("${registration.processor.subscriber.id}") + private String subscriberId; + + @Value("#{'${mosip.regproc.cbeff-validation.mandatory.modalities:Right,Left,Left RingFinger,Left LittleFinger," + + "Right RingFinger,Left Thumb,Left IndexFinger,Right IndexFinger,Right LittleFinger,Right MiddleFinger," + + "Left MiddleFinger,Right Thumb,Face}'.split(',')}") + private List mandatoryModalities ; + + /** The utilities. */ + @Autowired + Utilities utilities; + + @Autowired + private PriorityBasedPacketManagerService priorityBasedPacketManagerService; + + + public void validateBiometrics(String id, String process) + throws ApisResourceAccessException, IOException, PacketManagerException, JsonProcessingException { + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + id, "CbeffValidateAndVerificatonService::validateBiometrics()::entry"); + JSONObject regProcessorIdentityJson = utilities.getRegistrationProcessorMappingJson(MappingJsonConstants.IDENTITY); + String individualBiometricsLabel = JsonUtil.getJSONValue(JsonUtil.getJSONObject( + regProcessorIdentityJson, MappingJsonConstants.INDIVIDUAL_BIOMETRICS), MappingJsonConstants.VALUE); + + BiometricRecord biometricRecord = priorityBasedPacketManagerService.getBiometrics(id, individualBiometricsLabel, + mandatoryModalities, process, ProviderStageName.BIO_DEDUPE); + + Set availableModalities = biometricRecord != null && !CollectionUtils.isEmpty(biometricRecord.getSegments()) ? + biometricRecord.getSegments().stream().map(b -> { + if(!CollectionUtils.isEmpty(b.getBdbInfo().getType())) { + if (b.getOthers() != null) { + for(Map.Entry entry : b.getOthers().entrySet()) { + if(entry.getKey().equals("EXCEPTION") &&!entry.getValue().equals("true")) { + return b.getBdbInfo().getSubtype()!=null && !b.getBdbInfo().getSubtype().isEmpty()? + String.join(" ", b.getBdbInfo().getSubtype()) + :b.getBdbInfo().getType().get(0).value(); + } + } + } else { + return b.getBdbInfo().getSubtype()!=null && !b.getBdbInfo().getSubtype().isEmpty()? + String.join(" ", b.getBdbInfo().getSubtype()) + :b.getBdbInfo().getType().get(0).value(); + } + } + return null; + }).collect(Collectors.toSet()) : null; + + boolean isBiometricsNotPresent = availableModalities != null ? mandatoryModalities.stream().noneMatch( + modalities -> availableModalities.contains(modalities)) : true; + + if (isBiometricsNotPresent) + throw new CbeffNotFoundException("Biometrics not found for : " + id); + + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + id, "CbeffValidateAndVerificatonService::validateBiometrics()::exit" ); + } + +} diff --git a/registration-processor/core-processor/registration-processor-biometric-authentication-stage/src/test/java/io/mosip/registration/processor/biometric/authentication/stage/BiometricAuthenticationStageTest.java b/registration-processor/core-processor/registration-processor-biometric-authentication-stage/src/test/java/io/mosip/registration/processor/biometric/authentication/stage/BiometricAuthenticationStageTest.java index 6b1ae621272..97d50d9bfba 100644 --- a/registration-processor/core-processor/registration-processor-biometric-authentication-stage/src/test/java/io/mosip/registration/processor/biometric/authentication/stage/BiometricAuthenticationStageTest.java +++ b/registration-processor/core-processor/registration-processor-biometric-authentication-stage/src/test/java/io/mosip/registration/processor/biometric/authentication/stage/BiometricAuthenticationStageTest.java @@ -529,7 +529,7 @@ public void deployVerticle() { biometricAuthenticationStage.deployVerticle(); } - + @Test public void testAuthSystemException() throws ApisResourceAccessException, IOException, InvalidKeySpecException, NoSuchAlgorithmException, BioTypeException, JsonProcessingException, PacketManagerException, CertificateException ,ValidationFailedException,Exception { @@ -596,7 +596,7 @@ public void testAuthFailed() throws ApisResourceAccessException, IOException, In assertTrue(messageDto.getIsValid()); assertFalse(messageDto.getInternalError()); } - + @Test public void testJsonProcessingException() throws ApisResourceAccessException, IOException, PacketManagerException, io.mosip.kernel.core.exception.IOException, JsonProcessingException { diff --git a/registration-processor/core-processor/registration-processor-biometric-extraction-stage/src/main/java/io/mosip/registration/processor/stages/biometric/extraction/stage/BiometricExtractionStage.java b/registration-processor/core-processor/registration-processor-biometric-extraction-stage/src/main/java/io/mosip/registration/processor/stages/biometric/extraction/stage/BiometricExtractionStage.java index 893abfcee5a..2f7651b3ab4 100644 --- a/registration-processor/core-processor/registration-processor-biometric-extraction-stage/src/main/java/io/mosip/registration/processor/stages/biometric/extraction/stage/BiometricExtractionStage.java +++ b/registration-processor/core-processor/registration-processor-biometric-extraction-stage/src/main/java/io/mosip/registration/processor/stages/biometric/extraction/stage/BiometricExtractionStage.java @@ -135,7 +135,6 @@ protected String getPropertyPrefix() { * Deploy verticle. */ public void deployVerticle() { - mosipEventBus = this.getEventBus(this, clusterManagerUrl, workerPoolSize); this.consumeAndSend(mosipEventBus, MessageBusAddress.BIOMETRIC_EXTRACTION_BUS_IN, MessageBusAddress.BIOMETRIC_EXTRACTION_BUS_OUT, messageExpiryTimeLimit); @@ -172,8 +171,6 @@ public MessageDTO process(MessageDTO object) { registrationStatusDto .setLatestTransactionTypeCode(RegistrationTransactionTypeCode.BIOMETRIC_EXTRACTION.toString()); registrationStatusDto.setRegistrationStageName(getStageName()); - - if(!idrepoDraftService.idrepoHasDraft(registrationStatusDto.getRegistrationId())) { registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.toString()); registrationStatusDto.setLatestTransactionStatusCode(registrationStatusMapperUtil @@ -196,9 +193,9 @@ public MessageDTO process(MessageDTO object) { else { ExtractorsDto extractorsDto=getExtractors(registrationStatusDto.getRegistrationId()); if(extractorsDto.getExtractors()!=null && !extractorsDto.getExtractors().isEmpty()) { - for(ExtractorDto dto:extractorsDto.getExtractors()) { - addBiometricExtractiontoIdRepository(dto,registrationStatusDto.getRegistrationId()); - } + for(ExtractorDto dto:extractorsDto.getExtractors()) { + addBiometricExtractiontoIdRepository(dto,registrationStatusDto.getRegistrationId()); + } } else { throw new RegistrationProcessorCheckedException(PlatformErrorMessages.RPR_PMS_BIOMETRIC_EXTRACTION_NULL_RESPONSE.getCode(), @@ -361,13 +358,13 @@ private IdResponseDTO addBiometricExtractiontoIdRepository(ExtractorDto dto, } List segments=List.of(registrationId); IdResponseDTO response= (IdResponseDTO) registrationProcessorRestClientService.putApi(ApiName.IDREPOEXTRACTBIOMETRICS, segments, extractionFormat, dto.getAttributeName(), null, IdResponseDTO.class, null); - if (response.getErrors() != null && !response.getErrors().isEmpty()) { ErrorDTO error = response.getErrors().get(0); regProcLogger.error("Error occured while updating draft for id : " + registrationId, error.toString()); if (response.getErrors().get(0).getErrorCode().equalsIgnoreCase(ID_REPO_KEY_MANAGER_ERROR)) { throw new IdrepoDraftReprocessableException(error.getErrorCode(), error.getMessage()); } else { + idrepoDraftService.idrepoDiscardDraft(registrationId); throw new IdrepoDraftException(error.getErrorCode(), error.getMessage()); } } diff --git a/registration-processor/core-processor/registration-processor-biometric-extraction-stage/src/test/java/io/mosip/registration/processor/stages/biometric/extraction/stages/test/BiometricExtractionStageTest.java b/registration-processor/core-processor/registration-processor-biometric-extraction-stage/src/test/java/io/mosip/registration/processor/stages/biometric/extraction/stages/test/BiometricExtractionStageTest.java index a443b07f2f5..f7b9b5b629e 100644 --- a/registration-processor/core-processor/registration-processor-biometric-extraction-stage/src/test/java/io/mosip/registration/processor/stages/biometric/extraction/stages/test/BiometricExtractionStageTest.java +++ b/registration-processor/core-processor/registration-processor-biometric-extraction-stage/src/test/java/io/mosip/registration/processor/stages/biometric/extraction/stages/test/BiometricExtractionStageTest.java @@ -4,13 +4,15 @@ 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 static org.mockito.Mockito.*; import java.util.ArrayList; import java.util.List; import org.apache.commons.io.IOUtils; +import org.apache.hadoop.yarn.webapp.hamlet.HamletSpec; import org.assertj.core.util.Lists; +import org.json.JSONObject; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -141,8 +143,6 @@ public void senderHealthCheck(Handler eventHandler, String addre // TODO Auto-generated method stub } - - }; } @@ -170,8 +170,6 @@ public void setUp() throws Exception { dto.setReg_type("UPDATE"); MockitoAnnotations.initMocks(this); - - ResponseWrapper responseWrapper = new ResponseWrapper<>(); Mockito.doReturn(responseWrapper).when(auditLogRequestBuilder).createAuditRequestBuilder( "test case description", EventId.RPR_405.toString(), EventName.UPDATE.toString(), @@ -356,4 +354,31 @@ public void testIdrepoDraftReprocessableException() throws Exception { assertTrue(result.getInternalError()); assertTrue(result.getIsValid()); } + @Test + public void testBiometricExtractionDraftExceptionAndDiscardDreaft() throws Exception { + MessageDTO messageDTO = new MessageDTO(); + messageDTO.setRid("27847657360002520181210094052"); + messageDTO.setReg_type(RegistrationType.NEW.name()); + messageDTO.setWorkflowInstanceId("123er"); + messageDTO.setIteration(1); + when(idrepoDraftService.idrepoHasDraft(anyString())).thenReturn(true); + IdResponseDTO idResponseDTO=new IdResponseDTO(); + List errorList=new ArrayList<>(); + io.mosip.registration.processor.core.common.rest.dto.ErrorDTO dto=new io.mosip.registration.processor.core.common.rest.dto.ErrorDTO(); + dto.setErrorCode("aa"); + dto.setMessage("bb"); + errorList.add(dto); + idResponseDTO.setId("mosip.id.read"); + idResponseDTO.setResponse(null); + idResponseDTO.setErrors(errorList); + idResponseDTO.setVersion("1.0"); + List segment=new ArrayList<>(); + segment.add(messageDTO.getRid()); + when(registrationProcessorRestClientService.putApi(Mockito.eq(ApiName.IDREPOEXTRACTBIOMETRICS), any(), anyString(), anyString(), Mockito.isNull(), Mockito.eq(IdResponseDTO.class), isNull())).thenReturn(idResponseDTO); + MessageDTO result = biometricExtractionStage.process(messageDTO); + verify(idrepoDraftService,atLeastOnce()).idrepoDiscardDraft(anyString()); + + assertTrue(result.getInternalError()); + assertFalse(result.getIsValid()); + } } diff --git a/registration-processor/core-processor/registration-processor-finalization-stage/src/main/java/io/mosip/registration/processor/stages/finalization/stage/FinalizationStage.java b/registration-processor/core-processor/registration-processor-finalization-stage/src/main/java/io/mosip/registration/processor/stages/finalization/stage/FinalizationStage.java index c4236fde362..e01b00bf9bc 100644 --- a/registration-processor/core-processor/registration-processor-finalization-stage/src/main/java/io/mosip/registration/processor/stages/finalization/stage/FinalizationStage.java +++ b/registration-processor/core-processor/registration-processor-finalization-stage/src/main/java/io/mosip/registration/processor/stages/finalization/stage/FinalizationStage.java @@ -1,5 +1,6 @@ package io.mosip.registration.processor.stages.finalization.stage; +import io.mosip.registration.processor.core.common.rest.dto.ErrorDTO; import org.apache.commons.lang3.exception.ExceptionUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; diff --git a/registration-processor/core-processor/registration-processor-manual-adjudication-stage/src/main/java/io/mosip/registration/processor/adjudication/config/ManualAdjudicationConfigBean.java b/registration-processor/core-processor/registration-processor-manual-adjudication-stage/src/main/java/io/mosip/registration/processor/adjudication/config/ManualAdjudicationConfigBean.java index eded8175730..a1080f8eba2 100644 --- a/registration-processor/core-processor/registration-processor-manual-adjudication-stage/src/main/java/io/mosip/registration/processor/adjudication/config/ManualAdjudicationConfigBean.java +++ b/registration-processor/core-processor/registration-processor-manual-adjudication-stage/src/main/java/io/mosip/registration/processor/adjudication/config/ManualAdjudicationConfigBean.java @@ -1,34 +1,34 @@ -package io.mosip.registration.processor.adjudication.config; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -import io.mosip.registration.processor.adjudication.exception.handler.ManualVerificationExceptionHandler; -import io.mosip.registration.processor.adjudication.service.ManualAdjudicationService; -import io.mosip.registration.processor.adjudication.service.impl.ManualAdjudicationServiceImpl; -import io.mosip.registration.processor.adjudication.util.ManualVerificationRequestValidator; -import io.mosip.registration.processor.adjudication.util.ManualVerificationUpdateUtility; - -@Configuration -public class ManualAdjudicationConfigBean { - - @Bean - ManualAdjudicationService getManualVerificationService() { - return new ManualAdjudicationServiceImpl(); - } - - @Bean - ManualVerificationRequestValidator getManualVerificationRequestValidator() { - return new ManualVerificationRequestValidator(); - } - - @Bean - ManualVerificationExceptionHandler getManualVerificationExceptionHandler() { - return new ManualVerificationExceptionHandler(); - } - - @Bean - ManualVerificationUpdateUtility getManualVerificationUpdateUtility() { - return new ManualVerificationUpdateUtility(); - } +package io.mosip.registration.processor.adjudication.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import io.mosip.registration.processor.adjudication.exception.handler.ManualVerificationExceptionHandler; +import io.mosip.registration.processor.adjudication.service.ManualAdjudicationService; +import io.mosip.registration.processor.adjudication.service.impl.ManualAdjudicationServiceImpl; +import io.mosip.registration.processor.adjudication.util.ManualVerificationRequestValidator; +import io.mosip.registration.processor.adjudication.util.ManualVerificationUpdateUtility; + +@Configuration +public class ManualAdjudicationConfigBean { + + @Bean + ManualAdjudicationService getManualVerificationService() { + return new ManualAdjudicationServiceImpl(); + } + + @Bean + ManualVerificationRequestValidator getManualVerificationRequestValidator() { + return new ManualVerificationRequestValidator(); + } + + @Bean + ManualVerificationExceptionHandler getManualVerificationExceptionHandler() { + return new ManualVerificationExceptionHandler(); + } + + @Bean + ManualVerificationUpdateUtility getManualVerificationUpdateUtility() { + return new ManualVerificationUpdateUtility(); + } } \ No newline at end of file diff --git a/registration-processor/core-processor/registration-processor-manual-adjudication-stage/src/main/java/io/mosip/registration/processor/adjudication/service/impl/ManualAdjudicationServiceImpl.java b/registration-processor/core-processor/registration-processor-manual-adjudication-stage/src/main/java/io/mosip/registration/processor/adjudication/service/impl/ManualAdjudicationServiceImpl.java index 59c182b9df9..f84631a0d01 100644 --- a/registration-processor/core-processor/registration-processor-manual-adjudication-stage/src/main/java/io/mosip/registration/processor/adjudication/service/impl/ManualAdjudicationServiceImpl.java +++ b/registration-processor/core-processor/registration-processor-manual-adjudication-stage/src/main/java/io/mosip/registration/processor/adjudication/service/impl/ManualAdjudicationServiceImpl.java @@ -202,10 +202,11 @@ public class ManualAdjudicationServiceImpl implements ManualAdjudicationService @Autowired RegistrationExceptionMapperUtil registrationExceptionMapperUtil; - - @Autowired + + @Autowired private ManualVerificationUpdateUtility manualVerificationUpdateUtility; + /** The Constant PROTOCOL. */ public static final String PROTOCOL = "https"; @@ -555,34 +556,34 @@ private DataShareRequestDto setDocuments(Map policyMap,DataShareR HashMap docmap = (HashMap) docJson.get(doc.toString()); String docName = docmap != null && docmap.get(MappingJsonConstants.VALUE)!= null ? docmap.get(MappingJsonConstants.VALUE).toString() : null; for(Entry entry: policyMap.entrySet()) { - if (docmap != null && entry.getValue().contains(docName)) { - if(documents==null || documents.isEmpty()) { - Document document = packetManagerService.getDocument(id, docName, process, ProviderStageName.MANUAL_ADJUDICATION); - if (document != null) { - if (requestDto.getDocuments() != null) - requestDto.getDocuments().put(docmap.get(MappingJsonConstants.VALUE).toString(), CryptoUtil.encodeToURLSafeBase64(document.getDocument())); - else { - Map docMap = new HashMap<>(); - docMap.put(docmap.get(MappingJsonConstants.VALUE).toString(), CryptoUtil.encodeToURLSafeBase64(document.getDocument())); - requestDto.setDocuments(docMap); - } - } - } - else { - for(Documents docs:documents) { - if(docs.getCategory().equalsIgnoreCase(docName)) { - if (requestDto.getDocuments() != null) { - requestDto.getDocuments().put(docmap.get(MappingJsonConstants.VALUE).toString(), docs.getValue()); - }else { + if (entry.getValue().contains(docName) && docmap!=null) { + if(documents==null || documents.isEmpty()) { + Document document = packetManagerService.getDocument(id, docName, process, ProviderStageName.MANUAL_ADJUDICATION); + if (document != null) { + if (requestDto.getDocuments() != null) + requestDto.getDocuments().put(docmap.get(MappingJsonConstants.VALUE).toString(), CryptoUtil.encodeToURLSafeBase64(document.getDocument())); + else { Map docMap = new HashMap<>(); - docMap.put(docmap.get(MappingJsonConstants.VALUE).toString(), docs.getValue()); + docMap.put(docmap.get(MappingJsonConstants.VALUE).toString(), CryptoUtil.encodeToURLSafeBase64(document.getDocument())); requestDto.setDocuments(docMap); } } } + else { + for(Documents docs:documents) { + if(docs.getCategory().equalsIgnoreCase(docName)) { + if (requestDto.getDocuments() != null) { + requestDto.getDocuments().put(docmap.get(MappingJsonConstants.VALUE).toString(), docs.getValue()); + }else { + Map docMap = new HashMap<>(); + docMap.put(docmap.get(MappingJsonConstants.VALUE).toString(), docs.getValue()); + requestDto.setDocuments(docMap); + } + } + } + } } } - } } } return requestDto; diff --git a/registration-processor/core-processor/registration-processor-manual-adjudication-stage/src/main/java/io/mosip/registration/processor/adjudication/util/ManualVerificationUpdateUtility.java b/registration-processor/core-processor/registration-processor-manual-adjudication-stage/src/main/java/io/mosip/registration/processor/adjudication/util/ManualVerificationUpdateUtility.java index 817ddc68560..4f49fc40e24 100644 --- a/registration-processor/core-processor/registration-processor-manual-adjudication-stage/src/main/java/io/mosip/registration/processor/adjudication/util/ManualVerificationUpdateUtility.java +++ b/registration-processor/core-processor/registration-processor-manual-adjudication-stage/src/main/java/io/mosip/registration/processor/adjudication/util/ManualVerificationUpdateUtility.java @@ -1,48 +1,48 @@ -package io.mosip.registration.processor.adjudication.util; - - - import java.sql.Timestamp; -import java.util.List; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; -import org.springframework.transaction.annotation.Propagation; -import org.springframework.transaction.annotation.Transactional; - -import io.mosip.kernel.core.logger.spi.Logger; -import io.mosip.kernel.core.util.DateUtils; -import io.mosip.registration.processor.adjudication.dto.ManualVerificationStatus; -import io.mosip.registration.processor.core.constant.LoggerFileConstant; -import io.mosip.registration.processor.core.logger.RegProcessorLogger; -import io.mosip.registration.processor.packet.storage.entity.ManualVerificationEntity; -import io.mosip.registration.processor.packet.storage.repository.BasePacketRepository; - - @Component - @Transactional(propagation=Propagation.REQUIRES_NEW) - public class ManualVerificationUpdateUtility { - /** The logger. */ - private static Logger regProcLogger = RegProcessorLogger.getLogger(ManualVerificationUpdateUtility.class); - - /** The base packet repository. */ - @Autowired - private BasePacketRepository basePacketRepository; - - /** - * Update manual verification entity once request is pushed to queue for a given - * RID - */ - public void updateManualVerificationEntityRID(List mves, String requestId) { - mves.stream().forEach(mve -> { - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - mve.getRegId(), "ManualVerificationUpdateUtility::updateManualVerificationEntityRID()::entry"); - mve.setStatusCode(ManualVerificationStatus.INQUEUE.name()); - mve.setStatusComment("Sent to manual adjudication queue"); - mve.setUpdDtimes(Timestamp.valueOf(DateUtils.getUTCCurrentDateTime())); - mve.setRequestId(requestId); - basePacketRepository.update(mve); - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - mve.getRegId(), "ManualVerificationUpdateUtility::updateManualVerificationEntityRID()::exit"); - }); - } - } - +package io.mosip.registration.processor.adjudication.util; + + + import java.sql.Timestamp; +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; + +import io.mosip.kernel.core.logger.spi.Logger; +import io.mosip.kernel.core.util.DateUtils; +import io.mosip.registration.processor.adjudication.dto.ManualVerificationStatus; +import io.mosip.registration.processor.core.constant.LoggerFileConstant; +import io.mosip.registration.processor.core.logger.RegProcessorLogger; +import io.mosip.registration.processor.packet.storage.entity.ManualVerificationEntity; +import io.mosip.registration.processor.packet.storage.repository.BasePacketRepository; + + @Component + @Transactional(propagation=Propagation.REQUIRES_NEW) + public class ManualVerificationUpdateUtility { + /** The logger. */ + private static Logger regProcLogger = RegProcessorLogger.getLogger(ManualVerificationUpdateUtility.class); + + /** The base packet repository. */ + @Autowired + private BasePacketRepository basePacketRepository; + + /** + * Update manual verification entity once request is pushed to queue for a given + * RID + */ + public void updateManualVerificationEntityRID(List mves, String requestId) { + mves.stream().forEach(mve -> { + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + mve.getRegId(), "ManualVerificationUpdateUtility::updateManualVerificationEntityRID()::entry"); + mve.setStatusCode(ManualVerificationStatus.INQUEUE.name()); + mve.setStatusComment("Sent to manual adjudication queue"); + mve.setUpdDtimes(Timestamp.valueOf(DateUtils.getUTCCurrentDateTime())); + mve.setRequestId(requestId); + basePacketRepository.update(mve); + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + mve.getRegId(), "ManualVerificationUpdateUtility::updateManualVerificationEntityRID()::exit"); + }); + } + } + diff --git a/registration-processor/core-processor/registration-processor-manual-adjudication-stage/src/test/java/io/mosip/registration/processor/verification/service/ManualAdjudicationServiceTest.java b/registration-processor/core-processor/registration-processor-manual-adjudication-stage/src/test/java/io/mosip/registration/processor/verification/service/ManualAdjudicationServiceTest.java index 86b67758834..ca9ae1243d5 100644 --- a/registration-processor/core-processor/registration-processor-manual-adjudication-stage/src/test/java/io/mosip/registration/processor/verification/service/ManualAdjudicationServiceTest.java +++ b/registration-processor/core-processor/registration-processor-manual-adjudication-stage/src/test/java/io/mosip/registration/processor/verification/service/ManualAdjudicationServiceTest.java @@ -108,6 +108,9 @@ public class ManualAdjudicationServiceTest { @Mock UserDto dto; + @Mock + private ManualVerificationUpdateUtility manualVerificationUpdateUtility; + @Mock ManualAdjudicationStage manualAdjudicationStage; @@ -119,9 +122,7 @@ public class ManualAdjudicationServiceTest { @Mock AuditLogRequestBuilder auditLogRequestBuilder; - - @Mock - private ManualVerificationUpdateUtility manualVerificationUpdateUtility; + @Mock RegistrationStatusService registrationStatusService; @@ -270,9 +271,13 @@ public void createConnection(String username, String password, String brokerUrl, CandidateList candidateList=new CandidateList(); candidateList.setCount(0); manualAdjudicationResponseDTO.setCandidateList(candidateList); - + Mockito.doNothing().when(manualVerificationUpdateUtility).updateManualVerificationEntityRID(any(), any()); - + + Mockito.doNothing().when(manualVerificationUpdateUtility).updateManualVerificationEntityRID(any(), any()); + + Mockito.doNothing().when(manualVerificationUpdateUtility).updateManualVerificationEntityRID(any(), any()); + } @Test diff --git a/registration-processor/core-processor/registration-processor-manual-verification-stage/src/main/java/io/mosip/registration/processor/manual/verification/config/ManualVerificationConfigBean.java b/registration-processor/core-processor/registration-processor-manual-verification-stage/src/main/java/io/mosip/registration/processor/manual/verification/config/ManualVerificationConfigBean.java new file mode 100644 index 00000000000..4e7c5f868af --- /dev/null +++ b/registration-processor/core-processor/registration-processor-manual-verification-stage/src/main/java/io/mosip/registration/processor/manual/verification/config/ManualVerificationConfigBean.java @@ -0,0 +1,44 @@ +package io.mosip.registration.processor.manual.adjudication.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import io.mosip.registration.processor.manual.verification.exception.handler.ManualVerificationExceptionHandler; +import io.mosip.registration.processor.manual.verification.response.builder.ManualVerificationResponseBuilder; +import io.mosip.registration.processor.manual.verification.service.ManualVerificationService; +import io.mosip.registration.processor.manual.verification.service.impl.ManualVerificationServiceImpl; +import io.mosip.registration.processor.manual.verification.stage.ManualVerificationStage; +import io.mosip.registration.processor.adjudication.util.ManualVerificationRequestValidator; +import io.mosip.registration.processor.adjudication.util.ManualVerificationUpdateUtility; + +@Configuration +public class ManualVerificationConfigBean { + + + @Bean ManualVerificationService getManualVerificationService() { + return new ManualVerificationServiceImpl(); + } + @Bean + ManualVerificationUpdateUtility getManualVerificationUpdateUtility() { + return new ManualVerificationUpdateUtility(); + } + @Bean + public ManualVerificationStage getManualVerificationStage() { + return new ManualVerificationStage(); + } + + @Bean + ManualVerificationRequestValidator getManualVerificationRequestValidator() { + return new ManualVerificationRequestValidator(); + } + + @Bean + ManualVerificationExceptionHandler getManualVerificationExceptionHandler() { + return new ManualVerificationExceptionHandler(); + } + + @Bean + ManualVerificationResponseBuilder getManualVerificationResponseBuilder() { + return new ManualVerificationResponseBuilder(); + } + +} \ No newline at end of file diff --git a/registration-processor/core-processor/registration-processor-uin-generator-stage/src/main/java/io/mosip/registration/processor/stages/uingenerator/stage/UinGeneratorStage.java b/registration-processor/core-processor/registration-processor-uin-generator-stage/src/main/java/io/mosip/registration/processor/stages/uingenerator/stage/UinGeneratorStage.java index 63c05ac64ac..fd94304312a 100644 --- a/registration-processor/core-processor/registration-processor-uin-generator-stage/src/main/java/io/mosip/registration/processor/stages/uingenerator/stage/UinGeneratorStage.java +++ b/registration-processor/core-processor/registration-processor-uin-generator-stage/src/main/java/io/mosip/registration/processor/stages/uingenerator/stage/UinGeneratorStage.java @@ -1011,12 +1011,13 @@ protected String getPropertyPrefix() { * @throws IOException Signals that an I/O exception has * occurred. * @throws IdrepoDraftReprocessableException + * @throws JSONException */ @SuppressWarnings("unchecked") private IdResponseDTO lostAndUpdateUin(String lostPacketRegId, String matchedRegId, String process, MessageDTO object, LogDescription description) throws ApisResourceAccessException, IOException, io.mosip.kernel.core.util.exception.JsonProcessingException, PacketManagerException, IdrepoDraftException, - IdrepoDraftReprocessableException { + IdrepoDraftReprocessableException, JSONException { IdResponseDTO idResponse = null; String uin = idRepoService.getUinByRid(matchedRegId, utility.getGetRegProcessorDemographicIdentity()); @@ -1035,15 +1036,23 @@ private IdResponseDTO lostAndUpdateUin(String lostPacketRegId, String matchedReg String schemaVersion = packetManagerService.getFieldByMappingJsonKey(lostPacketRegId, MappingJsonConstants.IDSCHEMA_VERSION, process, ProviderStageName.UIN_GENERATOR); identityObject.put(idschemaversion, convertIdschemaToDouble ? Double.valueOf(schemaVersion) : schemaVersion); regProcLogger.info("Fields to be updated "+updateInfo); - if (null != updateInfo && !updateInfo.isEmpty()) { - String[] upd = updateInfo.split(","); - for (String infoField : upd) { - String fldValue = packetManagerService.getField(lostPacketRegId, infoField, process, - ProviderStageName.UIN_GENERATOR); - if (null != fldValue) - identityObject.put(infoField, fldValue); + Map fieldMap = new HashMap(); + if (StringUtils.isNotEmpty(updateInfo)) { + String[] updateFields = updateInfo.split(","); + for (String fieldName : updateFields) { + String actualFieldName = JsonUtil.getJSONValue( + JsonUtil.getJSONObject(regProcessorIdentityJson, fieldName), + MappingJsonConstants.VALUE); + if (StringUtils.isNotEmpty(actualFieldName)) { + String fldValue = packetManagerService.getField(lostPacketRegId, actualFieldName, process, + ProviderStageName.UIN_GENERATOR); + if (null != fldValue) + fieldMap.put(actualFieldName, fldValue); + } + } } + loadDemographicIdentity(fieldMap, identityObject); requestDto.setRegistrationId(lostPacketRegId); requestDto.setIdentity(identityObject); diff --git a/registration-processor/core-processor/registration-processor-uin-generator-stage/src/test/java/io/mosip/registration/processor/stages/uigenerator/UinGeneratorStageTest.java b/registration-processor/core-processor/registration-processor-uin-generator-stage/src/test/java/io/mosip/registration/processor/stages/uigenerator/UinGeneratorStageTest.java index a94473058a9..2a2ed521a14 100644 --- a/registration-processor/core-processor/registration-processor-uin-generator-stage/src/test/java/io/mosip/registration/processor/stages/uigenerator/UinGeneratorStageTest.java +++ b/registration-processor/core-processor/registration-processor-uin-generator-stage/src/test/java/io/mosip/registration/processor/stages/uigenerator/UinGeneratorStageTest.java @@ -1,11 +1,14 @@ package io.mosip.registration.processor.stages.uigenerator; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyDouble; import static org.mockito.ArgumentMatchers.anyList; import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.*; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; import java.io.ByteArrayInputStream; import java.io.File; @@ -14,8 +17,6 @@ import java.io.InputStream; import java.lang.reflect.Field; import java.nio.charset.StandardCharsets; -import java.time.LocalDateTime; -import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; @@ -23,10 +24,6 @@ import java.util.List; import java.util.Map; -import com.fasterxml.jackson.databind.JsonNode; -import io.mosip.kernel.core.util.DateUtils; -import io.mosip.registration.processor.packet.manager.dto.IdRequestDto; -import io.mosip.registration.processor.stages.uingenerator.dto.VidResponseDto; import org.apache.commons.io.IOUtils; import org.assertj.core.util.Lists; import org.json.JSONException; @@ -35,7 +32,12 @@ import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; -import org.mockito.*; +import org.mockito.ArgumentCaptor; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.mockito.Spy; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; @@ -46,6 +48,7 @@ import org.springframework.web.client.HttpClientErrorException; import org.springframework.web.client.HttpServerErrorException; +import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import io.mosip.kernel.biometrics.constant.BiometricType; @@ -83,6 +86,7 @@ import io.mosip.registration.processor.core.spi.restclient.RegistrationProcessorRestClientService; import io.mosip.registration.processor.core.util.JsonUtil; import io.mosip.registration.processor.core.util.RegistrationExceptionMapperUtil; +import io.mosip.registration.processor.packet.manager.dto.IdRequestDto; import io.mosip.registration.processor.packet.manager.dto.IdResponseDTO; import io.mosip.registration.processor.packet.manager.dto.ResponseDTO; import io.mosip.registration.processor.packet.manager.exception.IdrepoDraftException; @@ -1544,11 +1548,13 @@ public void testLinkSuccessForLostUin() throws Exception { @Test public void testLinkSuccessForLostUinAndUpdateContactInfo() throws Exception { + ReflectionTestUtils.setField(uinGeneratorStage, "updateInfo", "phone,email,addressLine1"); Map fieldMap = new HashMap<>(); fieldMap.put("UIN", "123456"); fieldMap.put("name", "mono"); fieldMap.put("email", "mono@mono.com"); - + fieldMap.put("addressLine1", + "[{\"language\":\"eng\",\"value\":\"abc\"},{\"language\":\"ara\",\"value\":\"abc\"}]"); List defaultFields = new ArrayList<>(); defaultFields.add("name"); defaultFields.add("dob"); @@ -1580,7 +1586,9 @@ public void testLinkSuccessForLostUinAndUpdateContactInfo() throws Exception { idResponseDTO.setResponse(responseDTO); idResponseDTO.setResponsetime("2019-01-17T06:29:01.940Z"); idResponseDTO.setVersion("1.0"); - when(packetManagerService.getField(any(), any(), any(),any())).thenReturn("989879234"); + when(packetManagerService.getField(any(), any(), any(), any())).thenReturn("989879234") + .thenReturn("mono@mono.com") + .thenReturn("[{\"language\":\"eng\",\"value\":\"abc\"},{\"language\":\"ara\",\"value\":\"abc\"}]"); when(idrepoDraftService.idrepoUpdateDraft(anyString(), any(), any())).thenReturn(idResponseDTO); when(registrationProcessorRestClientService.postApi(any(), any(), any(), any(), any(Class.class))) diff --git a/registration-processor/core-processor/registration-processor-verification-stage/src/main/java/io/mosip/registration/processor/verification/service/impl/VerificationServiceImpl.java b/registration-processor/core-processor/registration-processor-verification-stage/src/main/java/io/mosip/registration/processor/verification/service/impl/VerificationServiceImpl.java index 4f8ee06a1f0..d0c65e7fbc3 100644 --- a/registration-processor/core-processor/registration-processor-verification-stage/src/main/java/io/mosip/registration/processor/verification/service/impl/VerificationServiceImpl.java +++ b/registration-processor/core-processor/registration-processor-verification-stage/src/main/java/io/mosip/registration/processor/verification/service/impl/VerificationServiceImpl.java @@ -3,9 +3,6 @@ import static io.mosip.registration.processor.verification.constants.VerificationConstants.DATETIME_PATTERN; import java.io.IOException; -import java.sql.Timestamp; -import java.time.LocalDateTime; -import java.time.ZoneId; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; @@ -34,7 +31,6 @@ import io.mosip.kernel.biometrics.entities.BiometricRecord; import io.mosip.kernel.biometrics.spi.CbeffUtil; -import io.mosip.kernel.core.dataaccess.exception.DataAccessLayerException; import io.mosip.kernel.core.logger.spi.Logger; import io.mosip.kernel.core.util.CryptoUtil; import io.mosip.kernel.core.util.DateUtils; @@ -73,8 +69,6 @@ import io.mosip.registration.processor.packet.storage.dto.ApplicantInfoDto; import io.mosip.registration.processor.packet.storage.dto.Document; import io.mosip.registration.processor.packet.storage.entity.VerificationEntity; -import io.mosip.registration.processor.packet.storage.entity.VerificationPKEntity; -import io.mosip.registration.processor.packet.storage.exception.UnableToInsertData; import io.mosip.registration.processor.packet.storage.repository.BasePacketRepository; import io.mosip.registration.processor.packet.storage.utils.PriorityBasedPacketManagerService; import io.mosip.registration.processor.packet.storage.utils.Utilities; @@ -192,7 +186,7 @@ public class VerificationServiceImpl implements VerificationService { @Autowired RegistrationExceptionMapperUtil registrationExceptionMapperUtil; - + @Autowired SaveVerificationRecordUtility saveVerificationRecordUtility; @@ -338,7 +332,7 @@ public boolean updatePacketStatus(VerificationResponseDTO manualVerificationDTO, description.setCode(StatusUtil.VERIFICATION_RESEND.getCode()); messageDTO.setInternalError(true); messageDTO.setIsValid(isTransactionSuccessful); - + } else { // call success flow and process the response received from manual verification // system @@ -408,7 +402,7 @@ private void updateStatus(MessageDTO messageDTO, InternalRegistrationStatusDto r String moduleId = isTransactionSuccessful ? platformSuccessMessages.getCode() : description.getCode(); String moduleName = ModuleName.VERIFICATION.toString(); registrationStatusService.updateRegistrationStatus(registrationStatusDto, moduleId, moduleName); - + String eventId = isTransactionSuccessful ? EventId.RPR_402.toString() : EventId.RPR_405.toString(); String eventName = eventId.equalsIgnoreCase(EventId.RPR_402.toString()) ? EventName.UPDATE.toString() : EventName.EXCEPTION.toString(); diff --git a/registration-processor/core-processor/registration-processor-verification-stage/src/test/java/io/mosip/registration/processor/verification/service/VerificationServiceTest.java b/registration-processor/core-processor/registration-processor-verification-stage/src/test/java/io/mosip/registration/processor/verification/service/VerificationServiceTest.java index 7228dcdb5d7..4c0f6fa4985 100644 --- a/registration-processor/core-processor/registration-processor-verification-stage/src/test/java/io/mosip/registration/processor/verification/service/VerificationServiceTest.java +++ b/registration-processor/core-processor/registration-processor-verification-stage/src/test/java/io/mosip/registration/processor/verification/service/VerificationServiceTest.java @@ -135,11 +135,10 @@ public class VerificationServiceTest { @Mock private RegistrationProcessorRestClientService registrationProcessorRestClientService; - + @Mock SaveVerificationRecordUtility saveVerificationRecordUtility; - private InternalRegistrationStatusDto registrationStatusDto; private VerificationPKEntity PKId; private ManualVerificationDTO manualVerificationDTO; @@ -523,6 +522,6 @@ public void testUpdateStatusRejected() throws JsonProcessingException, com.faste assertTrue(result); } - + } diff --git a/registration-processor/init/registration-processor-dmz-packet-server/Dockerfile b/registration-processor/init/registration-processor-dmz-packet-server/Dockerfile index dc11c026753..a0ded0a963d 100644 --- a/registration-processor/init/registration-processor-dmz-packet-server/Dockerfile +++ b/registration-processor/init/registration-processor-dmz-packet-server/Dockerfile @@ -1,6 +1,11 @@ FROM nginx VOLUME /home/mosip + COPY nginx.conf /etc/nginx/nginx.conf + COPY healthcheck.txt /home/mosip/landing/healthcheck.txt + EXPOSE 8082 + +CMD ["nginx", "-g", "daemon off;"] diff --git a/registration-processor/init/registration-processor-packet-receiver-stage/src/main/java/io/mosip/registration/processor/packet/receiver/exception/handler/PacketReceiverExceptionHandler.java b/registration-processor/init/registration-processor-packet-receiver-stage/src/main/java/io/mosip/registration/processor/packet/receiver/exception/handler/PacketReceiverExceptionHandler.java index a71ae864574..8c95156e0c6 100644 --- a/registration-processor/init/registration-processor-packet-receiver-stage/src/main/java/io/mosip/registration/processor/packet/receiver/exception/handler/PacketReceiverExceptionHandler.java +++ b/registration-processor/init/registration-processor-packet-receiver-stage/src/main/java/io/mosip/registration/processor/packet/receiver/exception/handler/PacketReceiverExceptionHandler.java @@ -8,6 +8,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.security.core.AuthenticationException; import org.springframework.stereotype.Component; import org.springframework.web.multipart.support.MissingServletRequestPartException; @@ -176,6 +177,12 @@ private PacketReceiverResponseDTO handleInvalidTokenException(InvalidTokenExcept return buildPacketReceiverExceptionResponse((Exception)e); } + private PacketReceiverResponseDTO handleInvalidTokenException(AuthenticationException e) { + InvalidTokenException ex = new InvalidTokenException(e.getMessage()); + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(),LoggerFileConstant.APPLICATIONID.toString(), ex.getErrorCode(), e.getStackTrace()[0].toString()); + return buildPacketReceiverExceptionResponse((Exception)ex); + } + /** * Handles access denied exception * @@ -347,6 +354,8 @@ public PacketReceiverResponseDTO handler(Throwable exe) { return handleAccessDeniedException((AccessDeniedException)exe); if(exe instanceof InvalidTokenException) return handleInvalidTokenException((InvalidTokenException)exe); + if (exe instanceof AuthenticationException) + return handleInvalidTokenException((AuthenticationException)exe); if(exe instanceof ValidationException) return handleValidationException((ValidationException) exe); if (exe instanceof UnexpectedException) diff --git a/registration-processor/init/registration-processor-packet-receiver-stage/src/main/java/io/mosip/registration/processor/packet/receiver/service/impl/PacketReceiverServiceImpl.java b/registration-processor/init/registration-processor-packet-receiver-stage/src/main/java/io/mosip/registration/processor/packet/receiver/service/impl/PacketReceiverServiceImpl.java index 9668819abf3..6ef30cac0fb 100644 --- a/registration-processor/init/registration-processor-packet-receiver-stage/src/main/java/io/mosip/registration/processor/packet/receiver/service/impl/PacketReceiverServiceImpl.java +++ b/registration-processor/init/registration-processor-packet-receiver-stage/src/main/java/io/mosip/registration/processor/packet/receiver/service/impl/PacketReceiverServiceImpl.java @@ -9,6 +9,10 @@ import java.util.ArrayList; import java.util.List; +import io.mosip.kernel.core.util.DateUtils; +import io.mosip.registration.processor.core.exception.AdditionalInfoIdNotFoundException; +import io.mosip.registration.processor.core.exception.ObjectStoreNotAccessibleException; +import io.mosip.registration.processor.core.packet.dto.AdditionalInfoRequestDto; import org.apache.commons.io.IOUtils; import org.h2.store.fs.FileUtils; import org.h2.util.StringUtils; @@ -108,7 +112,7 @@ public class PacketReceiverServiceImpl implements PacketReceiverService fileUploadEntry=getFileFromCtx(routingContext).entrySet().iterator().next(); - deleteFile(fileUploadEntry.getValue()); + File file = fileUploadEntry.getValue(); + regProcLogger.error("Exception occurred for packet id : " + file.getName(), routingContext.failure()); + deleteFile(file); deleteFile(FileUtils.getFile(fileUploadEntry.getKey().uploadedFileName())); } catch (IOException e) { regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), @@ -149,7 +151,6 @@ public void failure(RoutingContext routingContext) { } this.setResponseWithDigitalSignature(routingContext, globalExceptionHandler.handler(routingContext.failure()), APPLICATION_JSON); - } diff --git a/registration-processor/init/registration-processor-registration-status-service/src/test/java/io/mosip/registration/processor/status/api/config/RegistrationStatusConfigTest.java b/registration-processor/init/registration-processor-registration-status-service/src/test/java/io/mosip/registration/processor/status/api/config/RegistrationStatusConfigTest.java index 32284e9a3b1..952a880fe86 100644 --- a/registration-processor/init/registration-processor-registration-status-service/src/test/java/io/mosip/registration/processor/status/api/config/RegistrationStatusConfigTest.java +++ b/registration-processor/init/registration-processor-registration-status-service/src/test/java/io/mosip/registration/processor/status/api/config/RegistrationStatusConfigTest.java @@ -1,23 +1,54 @@ -package io.mosip.registration.processor.status.api.config; - -import io.mosip.registration.processor.status.dto.AuthorizedRolesDto; -import org.springframework.boot.test.mock.mockito.MockBean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.ComponentScan.Filter; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.FilterType; - -import io.mosip.registration.processor.core.config.CoreConfigBean; -import io.mosip.registration.processor.rest.client.config.RestConfigBean; -import io.mosip.registration.processor.status.config.RegistrationStatusBeanConfig; -import io.mosip.registration.processor.status.config.RegistrationStatusServiceBeanConfig; - -@Configuration -@ComponentScan(basePackages = { - "io.mosip.registration.processor.status.*" }, excludeFilters = @Filter(type = FilterType.ASSIGNABLE_TYPE, value = { - RegistrationStatusServiceBeanConfig.class, RegistrationStatusBeanConfig.class, RestConfigBean.class, - CoreConfigBean.class, AuthorizedRolesDto.class})) -public class RegistrationStatusConfigTest { - -} - +package io.mosip.registration.processor.status.api.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.ComponentScan.Filter; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.FilterType; + +import io.mosip.kernel.core.authmanager.authadapter.spi.VertxAuthenticationProvider; +import io.mosip.registration.processor.core.config.CoreConfigBean; +import io.mosip.registration.processor.rest.client.config.RestConfigBean; +import io.mosip.registration.processor.status.config.RegistrationStatusBeanConfig; +import io.mosip.registration.processor.status.config.RegistrationStatusServiceBeanConfig; +import io.mosip.registration.processor.status.dto.AuthorizedRolesDto; +import io.vertx.core.Vertx; +import io.vertx.core.http.HttpMethod; +import io.vertx.core.http.HttpServer; +import io.vertx.ext.web.Router; +import io.vertx.ext.web.RoutingContext; + +@Configuration +@ComponentScan(basePackages = { + "io.mosip.registration.processor.status.*" }, excludeFilters = @Filter(type = FilterType.ASSIGNABLE_TYPE, value = { + RegistrationStatusServiceBeanConfig.class, RegistrationStatusBeanConfig.class, RestConfigBean.class, + CoreConfigBean.class, AuthorizedRolesDto.class})) +public class RegistrationStatusConfigTest { + + @Bean + public VertxAuthenticationProvider vertxAuthenticationProvider() { + return new VertxAuthenticationProvider() { + @Override + public void addCorsFilter(HttpServer httpServer, Vertx vertx) { + + } + + @Override + public void addAuthFilter(Router router, String s, HttpMethod httpMethod, String s1) { + + } + + @Override + public void addAuthFilter(RoutingContext routingContext, String s) { + + } + + @Override + public String getContextUser(RoutingContext routingContext) { + return null; + } + }; + } + +} + diff --git a/registration-processor/mosip-stage-executor/src/main/java/io/mosip/registration/processor/stages/executor/MosipStageExecutorApplication.java b/registration-processor/mosip-stage-executor/src/main/java/io/mosip/registration/processor/stages/executor/MosipStageExecutorApplication.java index acba33d1cf6..37e168d3cbe 100644 --- a/registration-processor/mosip-stage-executor/src/main/java/io/mosip/registration/processor/stages/executor/MosipStageExecutorApplication.java +++ b/registration-processor/mosip-stage-executor/src/main/java/io/mosip/registration/processor/stages/executor/MosipStageExecutorApplication.java @@ -13,6 +13,7 @@ import io.mosip.kernel.core.exception.ExceptionUtils; import io.mosip.registration.processor.core.abstractverticle.MosipVerticleAPIManager; + import io.mosip.registration.processor.stages.executor.config.StagesConfig; import io.mosip.registration.processor.stages.executor.util.StageClassesUtil; diff --git a/registration-processor/mosip-stage-executor/src/main/java/io/mosip/registration/processor/stages/executor/util/StageClassesUtil.java b/registration-processor/mosip-stage-executor/src/main/java/io/mosip/registration/processor/stages/executor/util/StageClassesUtil.java index 484756ffda1..74916e3a516 100644 --- a/registration-processor/mosip-stage-executor/src/main/java/io/mosip/registration/processor/stages/executor/util/StageClassesUtil.java +++ b/registration-processor/mosip-stage-executor/src/main/java/io/mosip/registration/processor/stages/executor/util/StageClassesUtil.java @@ -21,6 +21,8 @@ import io.mosip.kernel.core.exception.ExceptionUtils; import io.mosip.registration.processor.core.abstractverticle.MosipVerticleAPIManager; +import io.mosip.registration.processor.core.logger.RegProcessorLogger; +import io.mosip.kernel.core.logger.spi.Logger; import io.mosip.registration.processor.stages.executor.config.StagesConfig; /** diff --git a/registration-processor/pom.xml b/registration-processor/pom.xml index 95341868fc1..28a19731638 100644 --- a/registration-processor/pom.xml +++ b/registration-processor/pom.xml @@ -29,6 +29,7 @@ registration-processor Parent project of MOSIP Registration processor + https://github.com/mosip/registration none @@ -278,27 +279,36 @@ none - - - ossrh - CentralRepository - https://oss.sonatype.org/content/repositories/snapshots - default - - true - - - - central - MavenCentral - default - https://repo1.maven.org/maven2 - - false - - - - + + + ossrh + CentralRepository + https://oss.sonatype.org/content/repositories/snapshots + default + + true + + + + central + MavenCentral + default + https://repo1.maven.org/maven2 + + false + + + + + + ossrh + https://oss.sonatype.org/content/repositories/snapshots + + + ossrh + https://oss.sonatype.org/service/local/staging/deploy/maven2/ + + @@ -327,10 +337,10 @@ provided - org.powermock - powermock-core - 2.0.7 - test + org.powermock + powermock-core + 2.0.7 + test javax.xml.bind @@ -376,97 +386,142 @@ post-processor mosip-stage-executor stage-groups - workflow-engine - registration-processor-landing-zone - + workflow-engine + registration-processor-landing-zone + - - - org.apache.maven.plugins - maven-surefire-plugin - ${maven.surefire.plugin.version} - - ${skipTests} - false - - ${argLine} --add-opens java.xml/jdk.xml.internal=ALL-UNNAMED --illegal-access=permit - - - - - org.jacoco - jacoco-maven-plugin - ${maven.jacoco.version} - - - - prepare-agent - - - - report - prepare-package - - report - - - - - - org.apache.maven.plugins - maven-compiler-plugin - ${maven.compiler.version} - - ${maven.compiler.source} - ${maven.compiler.target} - - - - org.apache.maven.plugins - maven-jar-plugin - ${maven.jar.plugin.version} - - - - true - true - - - ${project.name} - ${project.version} - ${user.name} - ${os.name} - ${maven.build.timestamp} - ${env.BUILD_NUMBER} - ${env.BUILD_ID} - ${env.BUILD_URL} - - - - - - org.apache.maven.plugins - maven-war-plugin - ${maven.war.plugin.version} - - - - true - true - - - ${project.name} - ${project.version} - ${user.name} - ${os.name} - ${maven.build.timestamp} - ${env.BUILD_NUMBER} - ${env.BUILD_ID} - ${env.BUILD_URL} - - - - + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven.surefire.plugin.version} + + ${skipTests} + false + + ${argLine} --add-opens java.xml/jdk.xml.internal=ALL-UNNAMED --illegal-access=permit + + + + + org.jacoco + jacoco-maven-plugin + ${maven.jacoco.version} + + + + prepare-agent + + + + report + prepare-package + + report + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven.compiler.version} + + ${maven.compiler.source} + ${maven.compiler.target} + + + + org.apache.maven.plugins + maven-jar-plugin + ${maven.jar.plugin.version} + + + + true + true + + + ${project.name} + ${project.version} + ${user.name} + ${os.name} + ${maven.build.timestamp} + ${env.BUILD_NUMBER} + ${env.BUILD_ID} + ${env.BUILD_URL} + + + + + + pl.project13.maven + git-commit-id-plugin + 3.0.1 + + + get-the-git-infos + + revision + + validate + + + + true + ${project.build.outputDirectory}/git.properties + + ^git.build.(time|version)$ + ^git.commit.id.(abbrev|full)$ + + full + ${project.basedir}/.git + + + + + org.apache.maven.plugins + maven-gpg-plugin + 1.5 + + + sign-artifacts + verify + + sign + + + + --pinentry-mode + loopback + + + + + + + org.apache.maven.plugins + maven-war-plugin + ${maven.war.plugin.version} + + + + true + true + + + ${project.name} + ${project.version} + ${user.name} + ${os.name} + ${maven.build.timestamp} + ${env.BUILD_NUMBER} + ${env.BUILD_ID} + ${env.BUILD_URL} + + + + org.apache.maven.plugins maven-javadoc-plugin @@ -476,51 +531,47 @@ none - - pl.project13.maven - git-commit-id-plugin - 3.0.1 - - - get-the-git-infos - - revision - - validate - - - - true - ${project.build.outputDirectory}/git.properties - - ^git.build.(time|version)$ - ^git.commit.id.(abbrev|full)$ - - full - ${project.basedir}/.git - - - - - org.apache.maven.plugins - maven-gpg-plugin - 1.5 - - - sign-artifacts - verify - - sign - - - - --pinentry-mode - loopback - - - - - + + org.sonatype.plugins + nexus-staging-maven-plugin + 1.6.7 + true + + ossrh + https://oss.sonatype.org/ + false + + + + + org.apache.maven.plugins + maven-source-plugin + 2.2.1 + + + attach-sources + + jar-no-fork + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + 3.2.0 + + + attach-javadocs + + jar + + + + + none + + @@ -555,4 +606,4 @@ - \ No newline at end of file + diff --git a/registration-processor/post-processor/registration-processor-credential-requestor-stage/src/main/java/io/mosip/registration/processor/credentialrequestor/stage/CredentialRequestorStage.java b/registration-processor/post-processor/registration-processor-credential-requestor-stage/src/main/java/io/mosip/registration/processor/credentialrequestor/stage/CredentialRequestorStage.java index 50810572c81..b790193c459 100644 --- a/registration-processor/post-processor/registration-processor-credential-requestor-stage/src/main/java/io/mosip/registration/processor/credentialrequestor/stage/CredentialRequestorStage.java +++ b/registration-processor/post-processor/registration-processor-credential-requestor-stage/src/main/java/io/mosip/registration/processor/credentialrequestor/stage/CredentialRequestorStage.java @@ -34,18 +34,11 @@ import io.mosip.kernel.core.exception.ServiceError; import io.mosip.kernel.core.logger.spi.Logger; import io.mosip.kernel.core.util.DateUtils; -import io.mosip.registration.processor.core.abstractverticle.MessageBusAddress; -import io.mosip.registration.processor.core.abstractverticle.MessageDTO; -import io.mosip.registration.processor.core.abstractverticle.MosipEventBus; -import io.mosip.registration.processor.core.abstractverticle.MosipRouter; -import io.mosip.registration.processor.core.abstractverticle.MosipVerticleAPIManager; -import io.mosip.registration.processor.core.code.ApiName; +import io.mosip.registration.processor.core.abstractverticle.*; import io.mosip.registration.processor.core.code.EventId; import io.mosip.registration.processor.core.code.EventName; import io.mosip.registration.processor.core.code.EventType; -import io.mosip.registration.processor.core.code.ModuleName; -import io.mosip.registration.processor.core.code.RegistrationTransactionStatusCode; -import io.mosip.registration.processor.core.code.RegistrationTransactionTypeCode; +import io.mosip.registration.processor.core.code.*; import io.mosip.registration.processor.core.common.rest.dto.ErrorDTO; import io.mosip.registration.processor.core.constant.IdType; import io.mosip.registration.processor.core.constant.JsonConstant; diff --git a/registration-processor/post-processor/registration-processor-credential-requestor-stage/src/test/java/io/mosip/registrationprocessor/credentialrequestor/test/CredentialRequestorStageTest.java b/registration-processor/post-processor/registration-processor-credential-requestor-stage/src/test/java/io/mosip/registrationprocessor/credentialrequestor/test/CredentialRequestorStageTest.java index 6c2f1189ff5..1704e102626 100644 --- a/registration-processor/post-processor/registration-processor-credential-requestor-stage/src/test/java/io/mosip/registrationprocessor/credentialrequestor/test/CredentialRequestorStageTest.java +++ b/registration-processor/post-processor/registration-processor-credential-requestor-stage/src/test/java/io/mosip/registrationprocessor/credentialrequestor/test/CredentialRequestorStageTest.java @@ -1,473 +1,473 @@ -package io.mosip.registrationprocessor.credentialrequestor.test; - -import static org.junit.Assert.assertFalse; -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.lang.reflect.Field; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import io.mosip.registration.processor.credentialrequestor.dto.CredentialPartner; -import io.mosip.registration.processor.credentialrequestor.dto.CredentialPartnersList; -import io.mosip.registration.processor.credentialrequestor.util.CredentialPartnerUtil; -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.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; -import org.springframework.context.annotation.PropertySource; -import org.springframework.core.env.Environment; -import org.springframework.http.MediaType; -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.exception.ServiceError; -import io.mosip.registration.processor.core.abstractverticle.EventDTO; -import io.mosip.registration.processor.core.abstractverticle.HealthCheckDTO; -import io.mosip.registration.processor.core.abstractverticle.MessageBusAddress; -import io.mosip.registration.processor.core.abstractverticle.MessageDTO; -import io.mosip.registration.processor.core.abstractverticle.MosipEventBus; -import io.mosip.registration.processor.core.abstractverticle.MosipRouter; -import io.mosip.registration.processor.core.code.ApiName; -import io.mosip.registration.processor.core.common.rest.dto.ErrorDTO; -import io.mosip.registration.processor.core.constant.EventId; -import io.mosip.registration.processor.core.constant.EventName; -import io.mosip.registration.processor.core.constant.EventType; -import io.mosip.registration.processor.core.constant.RegistrationType; -import io.mosip.registration.processor.core.constant.VidType; -import io.mosip.registration.processor.core.exception.ApisResourceAccessException; -import io.mosip.registration.processor.core.http.ResponseWrapper; -import io.mosip.registration.processor.core.idrepo.dto.CredentialResponseDto; -import io.mosip.registration.processor.core.idrepo.dto.VidInfoDTO; -import io.mosip.registration.processor.core.idrepo.dto.VidsInfosDTO; -import io.mosip.registration.processor.core.packet.dto.Identity; -import io.mosip.registration.processor.core.spi.eventbus.EventHandler; -import io.mosip.registration.processor.core.spi.restclient.RegistrationProcessorRestClientService; -import io.mosip.registration.processor.core.util.PropertiesUtil; -import io.mosip.registration.processor.packet.storage.utils.Utilities; -import io.mosip.registration.processor.credentialrequestor.stage.CredentialRequestorStage; -import io.mosip.registration.processor.rest.client.audit.builder.AuditLogRequestBuilder; -import io.mosip.registration.processor.rest.client.audit.dto.AuditResponseDto; -import io.mosip.registration.processor.status.dto.InternalRegistrationStatusDto; -import io.mosip.registration.processor.status.dto.RegistrationStatusDto; -import io.mosip.registration.processor.status.service.RegistrationStatusService; -import io.vertx.core.AsyncResult; -import io.vertx.core.Handler; -import io.vertx.core.Vertx; -import io.vertx.ext.web.Router; -import io.vertx.ext.web.RoutingContext; - -@SuppressWarnings("deprecation") -@RunWith(PowerMockRunner.class) -@PrepareForTest({}) -@PowerMockIgnore({ "com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*","javax.management.*", "javax.net.*" }) -@PropertySource("classpath:bootstrap.properties") -public class CredentialRequestorStageTest { - - @Mock - private AuditLogRequestBuilder auditLogRequestBuilder; - - @Mock - MosipRouter router; - - @Mock - protected PropertiesUtil propertiesUtil; - - @Mock - private CredentialPartnerUtil credentialPartnerUtil; - - @Mock - private ObjectMapper objectMapper; - - private InternalRegistrationStatusDto registrationStatusDto = new InternalRegistrationStatusDto(); - - @Mock - private RegistrationStatusService registrationStatusService; - /** The rest template. */ - @Mock - private RegistrationProcessorRestClientService restClientService; - - - - /** The identity. */ - Identity identity = new Identity(); - - @Mock - private Environment env; - - private String response; - - @Mock - private Utilities utitilites; - - @InjectMocks - private CredentialRequestorStage stage = new CredentialRequestorStage() { - @Override - public MosipEventBus getEventBus(Object verticleName, String url, int instanceNumber) { - vertx = Vertx.vertx(); - - return new MosipEventBus() { - - @Override - public Vertx getEventbus() { - return vertx; - } - - @Override - public void consume(MessageBusAddress fromAddress, - EventHandler>> eventHandler) { - - } - - @Override - public void consumeAndSend(MessageBusAddress fromAddress, MessageBusAddress toAddress, - EventHandler>> eventHandler) { - - } - - @Override - public void send(MessageBusAddress toAddress, MessageDTO message) { - - } - - @Override - public void consumerHealthCheck(Handler eventHandler, String address) { - // TODO Auto-generated method stub - - } - - @Override - public void senderHealthCheck(Handler eventHandler, String address) { - // TODO Auto-generated method stub - - } - - - }; - } - - @Override - public void consume(MosipEventBus mosipEventBus, MessageBusAddress fromAddress, - long messageExpiryTimeLimit) { - } - - - @Override - public void send(MosipEventBus mosipEventBus, MessageBusAddress toAddress, MessageDTO message) { - } - - @Override - public void createServer(Router router, int port) { - - } - - @Override - public Router postUrl(Vertx vertx, MessageBusAddress consumeAddress, MessageBusAddress sendAddress) { - return null; - } - - @Override - public void setResponseWithDigitalSignature(RoutingContext ctx, Object object, String contentType) { - - } - }; - - @Before - public void setup() throws Exception { - when(env.getProperty("mosip.registration.processor.datetime.pattern")) - .thenReturn("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); - when(env.getProperty("mosip.regproc.credentialrequestor.server.port")).thenReturn("8099"); - when(env.getProperty("mosip.registration.processor.issuer")) - .thenReturn("mpartner-default-digitalcard:PDFCard:RPR_UIN_CARD_TEMPLATE;mpartner-default-print:euin:RPR_UIN_CARD_TEMPLATE"); - ReflectionTestUtils.setField(stage, "workerPoolSize", 10); - ReflectionTestUtils.setField(stage, "messageExpiryTimeLimit", Long.valueOf(0)); - ReflectionTestUtils.setField(stage, "clusterManagerUrl", "/dummyPath"); - ReflectionTestUtils.setField(stage, "busOutHaltAddresses", Arrays.asList()); - ReflectionTestUtils.setField(stage, "defaultPartners", Arrays.asList("digitalcardPartner", "opencrvsPartner")); - - System.setProperty("server.port", "8099"); - - //ReflectionTestUtils.setField(stage, "port", "8080"); - ReflectionTestUtils.setField(stage, "encrypt", false); - registrationStatusDto.setRegistrationId("45451454520011220230523070548"); - registrationStatusDto.setRegistrationType("NEW"); - registrationStatusDto.setWorkflowInstanceId("33e1fb7f-8202-41dc-82a1-49e821364eb2"); - Mockito.when(registrationStatusService.getRegistrationStatus(any(String.class), any(), any(), any())).thenReturn(registrationStatusDto); - Mockito.when(propertiesUtil.getIntegerProperty(any(), any())).thenReturn(8080); - - - - //Mockito.doNothing().when(registrationStatusDto).setStatusCode(any()); - //Mockito.doNothing().when(registrationStatusDto).setStatusComment(any()); - Mockito.doNothing().when(registrationStatusService).updateRegistrationStatus(any(), any(), any()); - //Mockito.doNothing().when(registrationStatusDto).setLatestTransactionTypeCode(any()); - //Mockito.doNothing().when(registrationStatusDto).setRegistrationStageName(any()); - //Mockito.doNothing().when(registrationStatusDto).setLatestTransactionStatusCode(any()); - Mockito.when(router.post(any())).thenReturn(null); - Mockito.when(router.get(any())).thenReturn(null); - - - Field auditLog = AuditLogRequestBuilder.class.getDeclaredField("registrationProcessorRestService"); - auditLog.setAccessible(true); - @SuppressWarnings("unchecked") - RegistrationProcessorRestClientService mockObj = Mockito - .mock(RegistrationProcessorRestClientService.class); - auditLog.set(auditLogRequestBuilder, mockObj); - AuditResponseDto auditResponseDto = new AuditResponseDto(); - ResponseWrapper responseWrapper = new ResponseWrapper<>(); - responseWrapper.setResponse(auditResponseDto); - Mockito.doReturn(responseWrapper).when(auditLogRequestBuilder).createAuditRequestBuilder( - "test case description", EventId.RPR_401.toString(), EventName.ADD.toString(), - EventType.BUSINESS.toString(), "1234testcase", ApiName.AUDIT); - Mockito.when(objectMapper.writeValueAsString(any())).thenReturn(response); - VidsInfosDTO vidsInfosDTO = new VidsInfosDTO(); - List vidList = new ArrayList<>(); - VidInfoDTO vidInfoDTO = new VidInfoDTO(); - vidInfoDTO.setVid("4796042638691271"); - vidInfoDTO.setVidType(VidType.PERPETUAL.name()); - vidList.add(vidInfoDTO); - vidsInfosDTO.setResponse(vidList); - Mockito.when(restClientService.getApi(any(), any(), anyString(), any(), any())).thenReturn(vidsInfosDTO); - Map map1 = new HashMap<>(); - map1.put("UIN", "4238135072"); - JSONObject jsonObject = new JSONObject(map1); - Mockito.when(utitilites.idrepoRetrieveIdentityByRid(any())).thenReturn(jsonObject); - - CredentialPartner partner1 = new CredentialPartner(); - partner1.setId("digitalcardPartner"); - partner1.setPartnerId("mpartner-default-digitalcard"); - partner1.setCredentialType("PDFCard"); - partner1.setTemplate("RPR_UIN_CARD_TEMPLATE"); - partner1.setAppIdBasedCredentialIdSuffix(".pdf"); - - CredentialPartner partner2 = new CredentialPartner(); - partner2.setId("opencrvsPartner"); - partner2.setPartnerId("opencrvs-partner"); - partner2.setCredentialType("opencrvs"); - partner2.setTemplate("RPR_UIN_CARD_TEMPLATE"); - - CredentialPartnersList partnersList = new CredentialPartnersList(); - partnersList.setPartners(Lists.newArrayList(partner1, partner2)); - when(credentialPartnerUtil.getAllCredentialPartners()).thenReturn(partnersList); - - - - } - - @Test - public void testAll() throws Exception { - testDeployVerticle(); - testStart(); - testPrintStageSuccess(); - } - - public void testStart() { - stage.start(); - } - - public void testDeployVerticle() throws Exception { - - - stage.deployVerticle(); - } - - - - - @Test - public void testPrintStageSuccess() - throws ApisResourceAccessException, JsonParseException, JsonMappingException, IOException { - MessageDTO dto = new MessageDTO(); - dto.setRid("1234567890987654321"); - - dto.setReg_type(RegistrationType.NEW.name()); - - ResponseWrapper responseWrapper = new ResponseWrapper<>(); - CredentialResponseDto credentialResponseDto = new CredentialResponseDto(); - credentialResponseDto.setRequestId("879664323421"); - Mockito.when(objectMapper.readValue(response, CredentialResponseDto.class)) - .thenReturn(credentialResponseDto); - responseWrapper.setResponse(credentialResponseDto); - Mockito.when(restClientService.postApi(any(), any(), any(), any(), any(), any(MediaType.class))) - .thenReturn(responseWrapper); - Mockito.when(restClientService.postApi((ApiName) any(), any(MediaType.class),any(),any(), any(), any(), any())) - .thenReturn(responseWrapper); - MessageDTO result = stage.process(dto); - assertTrue(result.getIsValid()); - assertFalse(result.getInternalError()); - } - - - @Test - public void testPrintStageFailure() throws ApisResourceAccessException { - - MessageDTO dto = new MessageDTO(); - dto.setRid("1234567890987654321"); - - dto.setReg_type(RegistrationType.NEW.name()); - - ResponseWrapper responseWrapper = new ResponseWrapper<>(); - ErrorDTO error = new ErrorDTO(); - error.setErrorCode("IDR-CRG-004"); - error.setMessage("unknown exception"); - List errors = new ArrayList<>(); - errors.add(error); - responseWrapper.setErrors(errors); - - Mockito.when(restClientService.postApi(any(ApiName.class), any(), any(), any(), any(), any(MediaType.class))) - .thenReturn(responseWrapper); - - MessageDTO result = stage.process(dto); - assertTrue(result.getInternalError()); - } - - - @Test - public void testException() - throws JsonParseException, JsonMappingException, IOException, ApisResourceAccessException { - MessageDTO dto = new MessageDTO(); - dto.setRid("1234567890987654321"); - - dto.setReg_type(RegistrationType.NEW.name()); - - ResponseWrapper responseWrapper = new ResponseWrapper<>(); - CredentialResponseDto credentialResponseDto = new CredentialResponseDto(); - credentialResponseDto.setRequestId("879664323421"); - Mockito.when(objectMapper.readValue(response, CredentialResponseDto.class)).thenReturn(credentialResponseDto); - responseWrapper.setResponse(credentialResponseDto); - Mockito.when(restClientService.postApi(any(), any(), any(), any(), any(), any(MediaType.class))) - .thenReturn(null); - MessageDTO result = stage.process(dto); - assertTrue(result.getInternalError()); - assertTrue(result.getIsValid()); - } - - @Test - public void testApisResourceAccessException() - throws JsonParseException, JsonMappingException, IOException, ApisResourceAccessException { - MessageDTO dto = new MessageDTO(); - dto.setRid("1234567890987654321"); - - dto.setReg_type(RegistrationType.NEW.name()); - - ResponseWrapper responseWrapper = new ResponseWrapper<>(); - CredentialResponseDto credentialResponseDto = new CredentialResponseDto(); - credentialResponseDto.setRequestId("879664323421"); - Mockito.when(objectMapper.readValue(response, CredentialResponseDto.class)).thenReturn(credentialResponseDto); - responseWrapper.setResponse(credentialResponseDto); - Mockito.when(restClientService.postApi(any(), any(), any(), any(), any(), any(MediaType.class))) - .thenThrow(new ApisResourceAccessException()); - MessageDTO result = stage.process(dto); - assertTrue(result.getInternalError()); - assertTrue(result.getIsValid()); - } - - @Test - public void testUINNotavailable() - throws JsonParseException, JsonMappingException, IOException, ApisResourceAccessException { - MessageDTO dto = new MessageDTO(); - dto.setRid("1234567890987654321"); - - dto.setReg_type(RegistrationType.NEW.name()); - - ResponseWrapper responseWrapper = new ResponseWrapper<>(); - CredentialResponseDto credentialResponseDto = new CredentialResponseDto(); - credentialResponseDto.setRequestId("879664323421"); - Mockito.when(objectMapper.readValue(response, CredentialResponseDto.class)).thenReturn(credentialResponseDto); - responseWrapper.setResponse(credentialResponseDto); - Mockito.when(restClientService.postApi(any(), any(), any(), any(), any(), any(MediaType.class))) - .thenThrow(new ApisResourceAccessException()); - Map map1 = new HashMap<>(); - - JSONObject jsonObject = new JSONObject(map1); - Mockito.when(utitilites.idrepoRetrieveIdentityByRid(any())).thenReturn(jsonObject); - MessageDTO result = stage.process(dto); - - assertFalse(result.getIsValid()); - assertFalse(result.getInternalError()); - } - - @Test - public void testVidNotAvailableException() - throws JsonParseException, JsonMappingException, IOException, ApisResourceAccessException { - MessageDTO dto = new MessageDTO(); - dto.setRid("1234567890987654321"); - - dto.setReg_type(RegistrationType.NEW.name()); - - ResponseWrapper responseWrapper = new ResponseWrapper<>(); - CredentialResponseDto credentialResponseDto = new CredentialResponseDto(); - credentialResponseDto.setRequestId("879664323421"); - Mockito.when(objectMapper.readValue(response, CredentialResponseDto.class)).thenReturn(credentialResponseDto); - responseWrapper.setResponse(credentialResponseDto); - Mockito.when(restClientService.postApi(any(), any(), any(), any(), any(), any(MediaType.class))) - .thenThrow(new ApisResourceAccessException()); - VidsInfosDTO vidsInfosDTO = new VidsInfosDTO(); - List vidList = new ArrayList<>(); - VidInfoDTO vidInfoDTO = new VidInfoDTO(); - vidInfoDTO.setVid("4796042638691271"); - vidInfoDTO.setVidType(VidType.TEMPORARY.name()); - vidList.add(vidInfoDTO); - vidsInfosDTO.setResponse(vidList); - Mockito.when(restClientService.getApi(any(), any(), anyString(), any(), any())).thenReturn(vidsInfosDTO); - MessageDTO result = stage.process(dto); - - assertTrue(result.getInternalError()); - assertTrue(result.getIsValid()); - } - - @Test - public void testVidNotAvailableGETAPIResponseNullException() - throws ApisResourceAccessException, JsonParseException, JsonMappingException, IOException { - MessageDTO dto = new MessageDTO(); - dto.setRid("1234567890987654321"); - - dto.setReg_type(RegistrationType.NEW.name()); - - VidsInfosDTO vidsInfosDTO = new VidsInfosDTO(); - vidsInfosDTO.setResponse(null); - Mockito.when(restClientService.getApi(any(), any(), anyString(), any(), any())).thenReturn(vidsInfosDTO); - - MessageDTO result = stage.process(dto); - assertTrue(result.getIsValid()); - assertTrue(result.getInternalError()); - } - - @Test - public void testVidNotAvailableGETAPIException() - throws ApisResourceAccessException, JsonParseException, JsonMappingException, IOException { - MessageDTO dto = new MessageDTO(); - dto.setRid("1234567890987654321"); - - dto.setReg_type(RegistrationType.NEW.name()); - - VidsInfosDTO vidsInfosDTO = new VidsInfosDTO(); - vidsInfosDTO.setResponse(null); - ServiceError error = new ServiceError(); - error.setErrorCode("ERR-001"); - error.setMessage("exception occured"); - vidsInfosDTO.setErrors(Arrays.asList(error)); - Mockito.when(restClientService.getApi(any(), any(), anyString(), any(), any())).thenReturn(vidsInfosDTO); - - MessageDTO result = stage.process(dto); - assertTrue(result.getIsValid()); - assertTrue(result.getInternalError()); - } - +package io.mosip.registrationprocessor.credentialrequestor.test; + +import static org.junit.Assert.assertFalse; +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.lang.reflect.Field; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +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.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.springframework.context.annotation.PropertySource; +import org.springframework.core.env.Environment; +import org.springframework.http.MediaType; +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.exception.ServiceError; +import io.mosip.registration.processor.core.abstractverticle.EventDTO; +import io.mosip.registration.processor.core.abstractverticle.HealthCheckDTO; +import io.mosip.registration.processor.core.abstractverticle.MessageBusAddress; +import io.mosip.registration.processor.core.abstractverticle.MessageDTO; +import io.mosip.registration.processor.core.abstractverticle.MosipEventBus; +import io.mosip.registration.processor.core.abstractverticle.MosipRouter; +import io.mosip.registration.processor.core.code.ApiName; +import io.mosip.registration.processor.core.common.rest.dto.ErrorDTO; +import io.mosip.registration.processor.core.constant.EventId; +import io.mosip.registration.processor.core.constant.EventName; +import io.mosip.registration.processor.core.constant.EventType; +import io.mosip.registration.processor.core.constant.RegistrationType; +import io.mosip.registration.processor.core.constant.VidType; +import io.mosip.registration.processor.core.exception.ApisResourceAccessException; +import io.mosip.registration.processor.core.http.ResponseWrapper; +import io.mosip.registration.processor.core.idrepo.dto.CredentialResponseDto; +import io.mosip.registration.processor.core.idrepo.dto.VidInfoDTO; +import io.mosip.registration.processor.core.idrepo.dto.VidsInfosDTO; +import io.mosip.registration.processor.core.packet.dto.Identity; +import io.mosip.registration.processor.core.spi.eventbus.EventHandler; +import io.mosip.registration.processor.core.spi.restclient.RegistrationProcessorRestClientService; +import io.mosip.registration.processor.core.util.PropertiesUtil; +import io.mosip.registration.processor.credentialrequestor.dto.CredentialPartner; +import io.mosip.registration.processor.credentialrequestor.dto.CredentialPartnersList; +import io.mosip.registration.processor.credentialrequestor.stage.CredentialRequestorStage; +import io.mosip.registration.processor.credentialrequestor.util.CredentialPartnerUtil; +import io.mosip.registration.processor.packet.storage.utils.Utilities; +import io.mosip.registration.processor.rest.client.audit.builder.AuditLogRequestBuilder; +import io.mosip.registration.processor.rest.client.audit.dto.AuditResponseDto; +import io.mosip.registration.processor.status.dto.InternalRegistrationStatusDto; +import io.mosip.registration.processor.status.dto.RegistrationStatusDto; +import io.mosip.registration.processor.status.service.RegistrationStatusService; +import io.vertx.core.AsyncResult; +import io.vertx.core.Handler; +import io.vertx.core.Vertx; +import io.vertx.ext.web.Router; +import io.vertx.ext.web.RoutingContext; + +@SuppressWarnings("deprecation") +@RunWith(PowerMockRunner.class) +@PrepareForTest({}) +@PowerMockIgnore({ "com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*","javax.management.*", "javax.net.*" }) +@PropertySource("classpath:bootstrap.properties") +public class CredentialRequestorStageTest { + + @Mock + private AuditLogRequestBuilder auditLogRequestBuilder; + + @Mock + MosipRouter router; + + @Mock + protected PropertiesUtil propertiesUtil; + + @Mock + private CredentialPartnerUtil credentialPartnerUtil; + + @Mock + private ObjectMapper objectMapper; + + private InternalRegistrationStatusDto registrationStatusDto = new InternalRegistrationStatusDto(); + + @Mock + private RegistrationStatusService registrationStatusService; + /** The rest template. */ + @Mock + private RegistrationProcessorRestClientService restClientService; + + + + /** The identity. */ + Identity identity = new Identity(); + + @Mock + private Environment env; + + private String response; + + @Mock + private Utilities utitilites; + + @InjectMocks + private CredentialRequestorStage stage = new CredentialRequestorStage() { + @Override + public MosipEventBus getEventBus(Object verticleName, String url, int instanceNumber) { + vertx = Vertx.vertx(); + + return new MosipEventBus() { + + @Override + public Vertx getEventbus() { + return vertx; + } + + @Override + public void consume(MessageBusAddress fromAddress, + EventHandler>> eventHandler) { + + } + + @Override + public void consumeAndSend(MessageBusAddress fromAddress, MessageBusAddress toAddress, + EventHandler>> eventHandler) { + + } + + @Override + public void send(MessageBusAddress toAddress, MessageDTO message) { + + } + + @Override + public void consumerHealthCheck(Handler eventHandler, String address) { + // TODO Auto-generated method stub + + } + + @Override + public void senderHealthCheck(Handler eventHandler, String address) { + // TODO Auto-generated method stub + + } + + + }; + } + + @Override + public void consume(MosipEventBus mosipEventBus, MessageBusAddress fromAddress, + long messageExpiryTimeLimit) { + } + + + @Override + public void send(MosipEventBus mosipEventBus, MessageBusAddress toAddress, MessageDTO message) { + } + + @Override + public void createServer(Router router, int port) { + + } + + @Override + public Router postUrl(Vertx vertx, MessageBusAddress consumeAddress, MessageBusAddress sendAddress) { + return null; + } + + @Override + public void setResponseWithDigitalSignature(RoutingContext ctx, Object object, String contentType) { + + } + }; + + @Before + public void setup() throws Exception { + when(env.getProperty("mosip.registration.processor.datetime.pattern")) + .thenReturn("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); + when(env.getProperty("mosip.regproc.credentialrequestor.server.port")).thenReturn("8099"); + when(env.getProperty("mosip.registration.processor.issuer")) + .thenReturn("mpartner-default-digitalcard:PDFCard:RPR_UIN_CARD_TEMPLATE;mpartner-default-print:euin:RPR_UIN_CARD_TEMPLATE"); + ReflectionTestUtils.setField(stage, "workerPoolSize", 10); + ReflectionTestUtils.setField(stage, "messageExpiryTimeLimit", Long.valueOf(0)); + ReflectionTestUtils.setField(stage, "clusterManagerUrl", "/dummyPath"); + ReflectionTestUtils.setField(stage, "busOutHaltAddresses", Arrays.asList()); + ReflectionTestUtils.setField(stage, "defaultPartners", Arrays.asList("digitalcardPartner", "opencrvsPartner")); + + System.setProperty("server.port", "8099"); + + //ReflectionTestUtils.setField(stage, "port", "8080"); + ReflectionTestUtils.setField(stage, "encrypt", false); + registrationStatusDto.setRegistrationId("45451454520011220230523070548"); + registrationStatusDto.setRegistrationType("NEW"); + registrationStatusDto.setWorkflowInstanceId("33e1fb7f-8202-41dc-82a1-49e821364eb2"); + Mockito.when(registrationStatusService.getRegistrationStatus(any(String.class), any(), any(), any())).thenReturn(registrationStatusDto); + Mockito.when(propertiesUtil.getIntegerProperty(any(), any())).thenReturn(8080); + + + + //Mockito.doNothing().when(registrationStatusDto).setStatusCode(any()); + //Mockito.doNothing().when(registrationStatusDto).setStatusComment(any()); + Mockito.doNothing().when(registrationStatusService).updateRegistrationStatus(any(), any(), any()); + //Mockito.doNothing().when(registrationStatusDto).setLatestTransactionTypeCode(any()); + //Mockito.doNothing().when(registrationStatusDto).setRegistrationStageName(any()); + //Mockito.doNothing().when(registrationStatusDto).setLatestTransactionStatusCode(any()); + Mockito.when(router.post(any())).thenReturn(null); + Mockito.when(router.get(any())).thenReturn(null); + + + Field auditLog = AuditLogRequestBuilder.class.getDeclaredField("registrationProcessorRestService"); + auditLog.setAccessible(true); + @SuppressWarnings("unchecked") + RegistrationProcessorRestClientService mockObj = Mockito + .mock(RegistrationProcessorRestClientService.class); + auditLog.set(auditLogRequestBuilder, mockObj); + AuditResponseDto auditResponseDto = new AuditResponseDto(); + ResponseWrapper responseWrapper = new ResponseWrapper<>(); + responseWrapper.setResponse(auditResponseDto); + Mockito.doReturn(responseWrapper).when(auditLogRequestBuilder).createAuditRequestBuilder( + "test case description", EventId.RPR_401.toString(), EventName.ADD.toString(), + EventType.BUSINESS.toString(), "1234testcase", ApiName.AUDIT); + Mockito.when(objectMapper.writeValueAsString(any())).thenReturn(response); + VidsInfosDTO vidsInfosDTO = new VidsInfosDTO(); + List vidList = new ArrayList<>(); + VidInfoDTO vidInfoDTO = new VidInfoDTO(); + vidInfoDTO.setVid("4796042638691271"); + vidInfoDTO.setVidType(VidType.PERPETUAL.name()); + vidList.add(vidInfoDTO); + vidsInfosDTO.setResponse(vidList); + Mockito.when(restClientService.getApi(any(), any(), anyString(), any(), any())).thenReturn(vidsInfosDTO); + Map map1 = new HashMap<>(); + map1.put("UIN", "4238135072"); + JSONObject jsonObject = new JSONObject(map1); + Mockito.when(utitilites.idrepoRetrieveIdentityByRid(any())).thenReturn(jsonObject); + + CredentialPartner partner1 = new CredentialPartner(); + partner1.setId("digitalcardPartner"); + partner1.setPartnerId("mpartner-default-digitalcard"); + partner1.setCredentialType("PDFCard"); + partner1.setTemplate("RPR_UIN_CARD_TEMPLATE"); + partner1.setAppIdBasedCredentialIdSuffix(".pdf"); + + CredentialPartner partner2 = new CredentialPartner(); + partner2.setId("opencrvsPartner"); + partner2.setPartnerId("opencrvs-partner"); + partner2.setCredentialType("opencrvs"); + partner2.setTemplate("RPR_UIN_CARD_TEMPLATE"); + + CredentialPartnersList partnersList = new CredentialPartnersList(); + partnersList.setPartners(Lists.newArrayList(partner1, partner2)); + when(credentialPartnerUtil.getAllCredentialPartners()).thenReturn(partnersList); + + + + } + + @Test + public void testAll() throws Exception { + testDeployVerticle(); + testStart(); + testPrintStageSuccess(); + } + + public void testStart() { + stage.start(); + } + + public void testDeployVerticle() throws Exception { + + + stage.deployVerticle(); + } + + + + + @Test + public void testPrintStageSuccess() + throws ApisResourceAccessException, JsonParseException, JsonMappingException, IOException { + MessageDTO dto = new MessageDTO(); + dto.setRid("1234567890987654321"); + + dto.setReg_type(RegistrationType.NEW.name()); + + ResponseWrapper responseWrapper = new ResponseWrapper<>(); + CredentialResponseDto credentialResponseDto = new CredentialResponseDto(); + credentialResponseDto.setRequestId("879664323421"); + Mockito.when(objectMapper.readValue(response, CredentialResponseDto.class)) + .thenReturn(credentialResponseDto); + responseWrapper.setResponse(credentialResponseDto); + Mockito.when(restClientService.postApi(any(), any(), any(), any(), any(), any(MediaType.class))) + .thenReturn(responseWrapper); + Mockito.when(restClientService.postApi((ApiName) any(), any(MediaType.class),any(),any(), any(), any(), any())) + .thenReturn(responseWrapper); + MessageDTO result = stage.process(dto); + assertTrue(result.getIsValid()); + assertFalse(result.getInternalError()); + } + + + @Test + public void testPrintStageFailure() throws ApisResourceAccessException { + + MessageDTO dto = new MessageDTO(); + dto.setRid("1234567890987654321"); + + dto.setReg_type(RegistrationType.NEW.name()); + + ResponseWrapper responseWrapper = new ResponseWrapper<>(); + ErrorDTO error = new ErrorDTO(); + error.setErrorCode("IDR-CRG-004"); + error.setMessage("unknown exception"); + List errors = new ArrayList<>(); + errors.add(error); + responseWrapper.setErrors(errors); + + Mockito.when(restClientService.postApi(any(ApiName.class), any(), any(), any(), any(), any(MediaType.class))) + .thenReturn(responseWrapper); + + MessageDTO result = stage.process(dto); + assertTrue(result.getInternalError()); + } + + + @Test + public void testException() + throws JsonParseException, JsonMappingException, IOException, ApisResourceAccessException { + MessageDTO dto = new MessageDTO(); + dto.setRid("1234567890987654321"); + + dto.setReg_type(RegistrationType.NEW.name()); + + ResponseWrapper responseWrapper = new ResponseWrapper<>(); + CredentialResponseDto credentialResponseDto = new CredentialResponseDto(); + credentialResponseDto.setRequestId("879664323421"); + Mockito.when(objectMapper.readValue(response, CredentialResponseDto.class)).thenReturn(credentialResponseDto); + responseWrapper.setResponse(credentialResponseDto); + Mockito.when(restClientService.postApi(any(), any(), any(), any(), any(), any(MediaType.class))) + .thenReturn(null); + MessageDTO result = stage.process(dto); + assertTrue(result.getInternalError()); + assertTrue(result.getIsValid()); + } + + @Test + public void testApisResourceAccessException() + throws JsonParseException, JsonMappingException, IOException, ApisResourceAccessException { + MessageDTO dto = new MessageDTO(); + dto.setRid("1234567890987654321"); + + dto.setReg_type(RegistrationType.NEW.name()); + + ResponseWrapper responseWrapper = new ResponseWrapper<>(); + CredentialResponseDto credentialResponseDto = new CredentialResponseDto(); + credentialResponseDto.setRequestId("879664323421"); + Mockito.when(objectMapper.readValue(response, CredentialResponseDto.class)).thenReturn(credentialResponseDto); + responseWrapper.setResponse(credentialResponseDto); + Mockito.when(restClientService.postApi(any(), any(), any(), any(), any(), any(MediaType.class))) + .thenThrow(new ApisResourceAccessException()); + MessageDTO result = stage.process(dto); + assertTrue(result.getInternalError()); + assertTrue(result.getIsValid()); + } + + @Test + public void testUINNotavailable() + throws JsonParseException, JsonMappingException, IOException, ApisResourceAccessException { + MessageDTO dto = new MessageDTO(); + dto.setRid("1234567890987654321"); + + dto.setReg_type(RegistrationType.NEW.name()); + + ResponseWrapper responseWrapper = new ResponseWrapper<>(); + CredentialResponseDto credentialResponseDto = new CredentialResponseDto(); + credentialResponseDto.setRequestId("879664323421"); + Mockito.when(objectMapper.readValue(response, CredentialResponseDto.class)).thenReturn(credentialResponseDto); + responseWrapper.setResponse(credentialResponseDto); + Mockito.when(restClientService.postApi(any(), any(), any(), any(), any(), any(MediaType.class))) + .thenThrow(new ApisResourceAccessException()); + Map map1 = new HashMap<>(); + + JSONObject jsonObject = new JSONObject(map1); + Mockito.when(utitilites.idrepoRetrieveIdentityByRid(any())).thenReturn(jsonObject); + MessageDTO result = stage.process(dto); + + assertFalse(result.getIsValid()); + assertFalse(result.getInternalError()); + } + + @Test + public void testVidNotAvailableException() + throws JsonParseException, JsonMappingException, IOException, ApisResourceAccessException { + MessageDTO dto = new MessageDTO(); + dto.setRid("1234567890987654321"); + + dto.setReg_type(RegistrationType.NEW.name()); + + ResponseWrapper responseWrapper = new ResponseWrapper<>(); + CredentialResponseDto credentialResponseDto = new CredentialResponseDto(); + credentialResponseDto.setRequestId("879664323421"); + Mockito.when(objectMapper.readValue(response, CredentialResponseDto.class)).thenReturn(credentialResponseDto); + responseWrapper.setResponse(credentialResponseDto); + Mockito.when(restClientService.postApi(any(), any(), any(), any(), any(), any(MediaType.class))) + .thenThrow(new ApisResourceAccessException()); + VidsInfosDTO vidsInfosDTO = new VidsInfosDTO(); + List vidList = new ArrayList<>(); + VidInfoDTO vidInfoDTO = new VidInfoDTO(); + vidInfoDTO.setVid("4796042638691271"); + vidInfoDTO.setVidType(VidType.TEMPORARY.name()); + vidList.add(vidInfoDTO); + vidsInfosDTO.setResponse(vidList); + Mockito.when(restClientService.getApi(any(), any(), anyString(), any(), any())).thenReturn(vidsInfosDTO); + MessageDTO result = stage.process(dto); + + assertTrue(result.getInternalError()); + assertTrue(result.getIsValid()); + } + + @Test + public void testVidNotAvailableGETAPIResponseNullException() + throws ApisResourceAccessException, JsonParseException, JsonMappingException, IOException { + MessageDTO dto = new MessageDTO(); + dto.setRid("1234567890987654321"); + + dto.setReg_type(RegistrationType.NEW.name()); + + VidsInfosDTO vidsInfosDTO = new VidsInfosDTO(); + vidsInfosDTO.setResponse(null); + Mockito.when(restClientService.getApi(any(), any(), anyString(), any(), any())).thenReturn(vidsInfosDTO); + + MessageDTO result = stage.process(dto); + assertTrue(result.getIsValid()); + assertTrue(result.getInternalError()); + } + + @Test + public void testVidNotAvailableGETAPIException() + throws ApisResourceAccessException, JsonParseException, JsonMappingException, IOException { + MessageDTO dto = new MessageDTO(); + dto.setRid("1234567890987654321"); + + dto.setReg_type(RegistrationType.NEW.name()); + + VidsInfosDTO vidsInfosDTO = new VidsInfosDTO(); + vidsInfosDTO.setResponse(null); + ServiceError error = new ServiceError(); + error.setErrorCode("ERR-001"); + error.setMessage("exception occured"); + vidsInfosDTO.setErrors(Arrays.asList(error)); + Mockito.when(restClientService.getApi(any(), any(), anyString(), any(), any())).thenReturn(vidsInfosDTO); + + MessageDTO result = stage.process(dto); + assertTrue(result.getIsValid()); + assertTrue(result.getInternalError()); + } + } \ No newline at end of file diff --git a/registration-processor/pre-processor/registration-processor-operator-validator-stage/src/main/java/io/mosip/registration/processor/stages/operatorvalidator/OperatorValidator.java b/registration-processor/pre-processor/registration-processor-operator-validator-stage/src/main/java/io/mosip/registration/processor/stages/operatorvalidator/OperatorValidator.java index 2d432c56874..6bc14a00ba2 100644 --- a/registration-processor/pre-processor/registration-processor-operator-validator-stage/src/main/java/io/mosip/registration/processor/stages/operatorvalidator/OperatorValidator.java +++ b/registration-processor/pre-processor/registration-processor-operator-validator-stage/src/main/java/io/mosip/registration/processor/stages/operatorvalidator/OperatorValidator.java @@ -1,359 +1,355 @@ -package io.mosip.registration.processor.stages.operatorvalidator; - -import java.io.IOException; -import java.security.NoSuchAlgorithmException; -import java.security.cert.CertificateException; -import java.security.spec.InvalidKeySpecException; -import java.util.ArrayList; -import java.util.List; -import java.util.stream.Collectors; - -import javax.xml.parsers.ParserConfigurationException; - -import io.mosip.registration.processor.packet.storage.utils.Utilities; -import org.json.JSONException; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; -import org.xml.sax.SAXException; - -import com.fasterxml.jackson.databind.ObjectMapper; - -import io.mosip.kernel.biometrics.entities.BIR; -import io.mosip.kernel.biometrics.entities.BiometricRecord; -import io.mosip.kernel.core.bioapi.exception.BiometricException; -import io.mosip.kernel.core.exception.BaseCheckedException; -import io.mosip.kernel.core.logger.spi.Logger; -import io.mosip.kernel.core.util.StringUtils; -import io.mosip.registration.processor.core.auth.dto.AuthResponseDTO; -import io.mosip.registration.processor.core.auth.dto.IndividualIdDto; -import io.mosip.registration.processor.core.code.ApiName; -import io.mosip.registration.processor.core.code.RegistrationExceptionTypeCode; -import io.mosip.registration.processor.core.common.rest.dto.ErrorDTO; -import io.mosip.registration.processor.core.constant.MappingJsonConstants; -import io.mosip.registration.processor.core.constant.ProviderStageName; -import io.mosip.registration.processor.core.exception.ApisResourceAccessException; -import io.mosip.registration.processor.core.exception.AuthSystemException; -import io.mosip.registration.processor.core.exception.PacketDecryptionFailureException; -import io.mosip.registration.processor.core.exception.RegistrationProcessorCheckedException; -import io.mosip.registration.processor.core.exception.ValidationFailedException; -import io.mosip.registration.processor.core.exception.util.PlatformErrorMessages; -import io.mosip.registration.processor.core.http.ResponseWrapper; -import io.mosip.registration.processor.core.logger.RegProcessorLogger; -import io.mosip.registration.processor.core.packet.dto.RegOsiDto; -import io.mosip.registration.processor.core.packet.dto.ServerError; -import io.mosip.registration.processor.core.packet.dto.masterdata.UserResponseDto; -import io.mosip.registration.processor.core.packet.dto.regcentermachine.RegistrationCenterUserMachineMappingHistoryResponseDto; -import io.mosip.registration.processor.core.spi.restclient.RegistrationProcessorRestClientService; -import io.mosip.registration.processor.core.status.util.StatusUtil; -import io.mosip.registration.processor.core.util.JsonUtil; -import io.mosip.registration.processor.core.util.RegistrationExceptionMapperUtil; -import io.mosip.registration.processor.packet.storage.utils.BioSdkUtil; -import io.mosip.registration.processor.packet.storage.utils.PriorityBasedPacketManagerService; -import io.mosip.registration.processor.status.code.RegistrationStatusCode; -import io.mosip.registration.processor.status.dto.InternalRegistrationStatusDto; - -@Service -public class OperatorValidator { - - private static Logger regProcLogger = RegProcessorLogger.getLogger(OperatorValidator.class); - - private static final String ISTRUE = "true"; - - private static final String INDIVIDUAL_TYPE_USERID = "USERID"; - - private static final String APPID = "regproc"; - - @Autowired - RegistrationExceptionMapperUtil registrationExceptionMapperUtil; - - @Autowired - RegistrationProcessorRestClientService restClientService; - - @Autowired - private PriorityBasedPacketManagerService packetManagerService; - - @Autowired - private ObjectMapper mapper; - - @Autowired - private Utilities utility; - - @Autowired - private BioSdkUtil bioUtil; - - /** - * Checks if is valid Operator. - * - * @param registrationId the registration id - * @throws SAXException - * @throws ParserConfigurationException - * @throws io.mosip.kernel.core.exception.IOException - * @throws Exception - * @throws PacketDecryptionFailureException - * @throws RegistrationProcessorCheckedException - */ - public void validate(String registrationId, InternalRegistrationStatusDto registrationStatusDto, RegOsiDto regOsi) - throws Exception { - regProcLogger.debug("validate called for registrationId {}", registrationId); - - validateOperator(registrationId, regOsi, registrationStatusDto); - authenticateOperator(regOsi, registrationId, registrationStatusDto); - validateUMCmapping(regOsi.getPacketCreationDate(), regOsi.getRegcntrId(), regOsi.getMachineId(), - regOsi.getOfficerId(), registrationStatusDto); - regProcLogger.debug("validate call ended for registrationId {}", registrationId); - } - - private void validateOperator(String registrationId, RegOsiDto regOsi, - InternalRegistrationStatusDto registrationStatusDto) throws IOException, BaseCheckedException { - String creationDate = regOsi.getPacketCreationDate(); - if (creationDate != null && !(StringUtils.isEmpty(creationDate))) { - if (!isActiveUser(regOsi.getOfficerId(), creationDate, registrationStatusDto)) { - registrationStatusDto.setLatestTransactionStatusCode(registrationExceptionMapperUtil - .getStatusCode(RegistrationExceptionTypeCode.OFFICER_WAS_INACTIVE)); - registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.toString()); - regProcLogger.debug("ActiveUserId call ended for registrationId {} {}", registrationId, - StatusUtil.OFFICER_WAS_INACTIVE.getMessage() + regOsi.getOfficerId()); - throw new BaseCheckedException(StatusUtil.OFFICER_WAS_INACTIVE.getMessage() + regOsi.getOfficerId(), - StatusUtil.OFFICER_WAS_INACTIVE.getCode()); - } - - } else { - registrationStatusDto.setLatestTransactionStatusCode(registrationExceptionMapperUtil - .getStatusCode(RegistrationExceptionTypeCode.PACKET_CREATION_DATE_NOT_PRESENT_IN_PACKET)); - registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.toString()); - regProcLogger.debug("ActiveUserId call ended for registrationId {}. packet creationDate is null", - registrationId); - throw new BaseCheckedException(StatusUtil.OPERATOR_PACKET_CREATION_DATE_NOT_FOUND_IN_PACKET.getMessage(), - StatusUtil.OPERATOR_PACKET_CREATION_DATE_NOT_FOUND_IN_PACKET.getCode()); - } - } - - private boolean isActiveUser(String officerId, String creationDate, - InternalRegistrationStatusDto registrationStatusDto) throws IOException, BaseCheckedException { - boolean wasOfficerActiveDuringPCT = false; - if (officerId != null && !officerId.isEmpty()) { - UserResponseDto officerResponse = getUserDetails(officerId, creationDate, registrationStatusDto); - if (officerResponse.getErrors() == null) { - wasOfficerActiveDuringPCT = officerResponse.getResponse().getUserResponseDto().get(0).getIsActive(); - if (!wasOfficerActiveDuringPCT) { - regProcLogger.debug("isActiveUser call ended for registrationId {} {}", - registrationStatusDto.getRegistrationId(), StatusUtil.OFFICER_WAS_INACTIVE.getMessage()); - } - } else { - List errors = officerResponse.getErrors(); - regProcLogger.debug("isActiveUser call ended with error {}", errors.get(0).getMessage()); - throw new BaseCheckedException( - StatusUtil.OFFICER_AUTHENTICATION_FAILED.getMessage() + errors.get(0).getMessage(), - StatusUtil.OFFICER_AUTHENTICATION_FAILED.getCode()); - } - } - return wasOfficerActiveDuringPCT; - } - - private UserResponseDto getUserDetails(String operatorId, String creationDate, - InternalRegistrationStatusDto registrationStatusDto) throws ApisResourceAccessException, IOException { - UserResponseDto userResponse; - List pathSegments = new ArrayList<>(); - pathSegments.add(operatorId); - pathSegments.add(creationDate); - - userResponse = (UserResponseDto) restClientService.getApi(ApiName.USERDETAILS, pathSegments, "", "", - UserResponseDto.class); - regProcLogger.debug("isUserActive call ended with response data {}", - JsonUtil.objectMapperObjectToJson(userResponse)); - return userResponse; - } - - /** - * To authenticate operator. - * - * @param regOsi the reg osi - * @param registrationId the registration id - * @throws SAXException - * @throws ParserConfigurationException - * @throws BiometricException - * @throws InvalidKeySpecException - * @throws io.mosip.kernel.core.exception.IOException - * @throws PacketDecryptionFailureException - * @throws Exception - * - */ - private void authenticateOperator(RegOsiDto regOsi, String registrationId, - InternalRegistrationStatusDto registrationStatusDto) - throws Exception { - String officerId = regOsi.getOfficerId(); - // officer password and otp check - String officerPassword = regOsi.getOfficerHashedPwd(); - String officerOTPAuthentication = regOsi.getOfficerOTPAuthentication(); - - String officerBiometricFileName = regOsi.getOfficerBiometricFileName(); - - if (StringUtils.isEmpty(officerBiometricFileName) || officerBiometricFileName == null) { - if (!validateOtpAndPwd(officerPassword, officerOTPAuthentication)) { - registrationStatusDto.setLatestTransactionStatusCode(registrationExceptionMapperUtil - .getStatusCode(RegistrationExceptionTypeCode.OPERATOR_PASSWORD_OTP_FAILURE)); - registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.toString()); - regProcLogger.debug("validateOperator call ended for registrationId {} {}", registrationId, - StatusUtil.OPERATOR_PASSWORD_OTP_FAILURE.getMessage() + officerId); - throw new ValidationFailedException(StatusUtil.OPERATOR_PASSWORD_OTP_FAILURE.getMessage() + officerId, - StatusUtil.OPERATOR_PASSWORD_OTP_FAILURE.getCode()); - } - } else { - BiometricRecord biometricRecord = packetManagerService.getBiometricsByMappingJsonKey(registrationId, - MappingJsonConstants.OFFICERBIOMETRICFILENAME, registrationStatusDto.getRegistrationType(), - ProviderStageName.OPERATOR_VALIDATOR); - - if (biometricRecord == null || biometricRecord.getSegments() == null - || biometricRecord.getSegments().isEmpty()) { - regProcLogger.error("validateOperator call ended for registrationId {} {}", registrationId, - "ERROR =======>" + StatusUtil.BIOMETRICS_VALIDATION_FAILURE.getMessage()); - - registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.toString()); - throw new ValidationFailedException( - StatusUtil.BIOMETRICS_VALIDATION_FAILURE.getMessage() + " for officer : " + officerId, - StatusUtil.BIOMETRICS_VALIDATION_FAILURE.getCode()); - } else { - validateUserBiometric(registrationId, officerId, biometricRecord.getSegments(), INDIVIDUAL_TYPE_USERID, - registrationStatusDto); - } - } - } - - /** - * Validate opValidated and otpValidated. - * - * @param pwd the opValidated - * @param otp the otpValidated - * @return true, if successful - */ - private boolean validateOtpAndPwd(String opValidated, String otpValidated) { - return (opValidated != null && opValidated.equals(ISTRUE) || otpValidated != null && otpValidated.equals(ISTRUE)); - } - - - /** - * Validate user. - * - * @param userId the userid - * @param registrationId the registration id - * @param list biometric data as BIR object - * @param individualType user type - * @param registrationStatusDto - * @throws Exception - * @throws SAXException - * @throws ParserConfigurationException - * @throws NoSuchAlgorithmException - * @throws InvalidKeySpecException - * @throws BiometricException - */ - - private void validateUserBiometric(String registrationId, String userId, List list, String individualType, - InternalRegistrationStatusDto registrationStatusDto) - throws Exception { - - if (INDIVIDUAL_TYPE_USERID.equalsIgnoreCase(individualType)) { - userId = getIndividualIdByUserId(userId); - individualType = null; - } - - bioUtil.authenticateBiometrics(userId, individualType, list,registrationStatusDto, - StatusUtil.OFFICER_AUTHENTICATION_FAILED.getMessage(), - StatusUtil.OFFICER_AUTHENTICATION_FAILED.getCode()); - - regProcLogger.debug("validateUserBiometric call ended for registrationId {}", registrationId); - - } - - /** - * get the individualId by userid - * - * @param userid - * @return individualId - * @throws ApisResourceAccessException - * @throws IOException - */ - private String getIndividualIdByUserId(String userid) throws ApisResourceAccessException, IOException { - - regProcLogger.debug("getIndividualIdByUserId called for userid {}", userid); - List pathSegments = new ArrayList<>(); - pathSegments.add(APPID); - pathSegments.add(userid); - String individualId = null; - ResponseWrapper response = null; - response = (ResponseWrapper) restClientService.getApi(ApiName.GETINDIVIDUALIDFROMUSERID, pathSegments, "", - "", ResponseWrapper.class); - regProcLogger.debug( - "getIndividualIdByUserId called for with GETINDIVIDUALIDFROMUSERID GET service call ended successfully"); - if (response.getErrors() != null) { - throw new ApisResourceAccessException( - PlatformErrorMessages.LINK_FOR_USERID_INDIVIDUALID_FAILED_OVM_EXCEPTION.toString()); - } else { - IndividualIdDto readValue = mapper.readValue(mapper.writeValueAsString(response.getResponse()), - IndividualIdDto.class); - individualId = readValue.getIndividualId(); - } - regProcLogger.debug("getIndividualIdByUserId call ended for userid {}", userid); - return individualId; - } - - /** - * Validate UMC cmapping. - * - * @param effectiveTimestamp the effective timestamp - * @param registrationCenterId the registration center id - * @param machineId the machine id - * @param officerId the officer id - * @param registrationStatusDto - * @throws IOException - * @throws BaseCheckedException - */ - private void validateUMCmapping(String effectiveTimestamp, String registrationCenterId, String machineId, - String officerId, InternalRegistrationStatusDto registrationStatusDto) - throws IOException, BaseCheckedException { - - List officerpathsegments = new ArrayList<>(); - officerpathsegments.add(effectiveTimestamp); - officerpathsegments.add(registrationCenterId); - officerpathsegments.add(machineId); - officerpathsegments.add(officerId); - - if (!validateMapping(officerpathsegments, registrationStatusDto)) { - throw new ValidationFailedException(StatusUtil.OFFICER_NOT_ACTIVE.getMessage(), - StatusUtil.OFFICER_NOT_ACTIVE.getCode()); - } - - } - - private boolean validateMapping(List pathsegments, InternalRegistrationStatusDto registrationStatusDto) - throws IOException, BaseCheckedException { - boolean isValidUser = false; - ResponseWrapper responseWrapper; - RegistrationCenterUserMachineMappingHistoryResponseDto userDto = null; - - responseWrapper = (ResponseWrapper) restClientService.getApi(ApiName.CENTERUSERMACHINEHISTORY, - pathsegments, "", "", ResponseWrapper.class); - userDto = mapper.readValue(mapper.writeValueAsString(responseWrapper.getResponse()), - RegistrationCenterUserMachineMappingHistoryResponseDto.class); - regProcLogger.debug("validateMapping call ended for registrationId {} with response data {}", - registrationStatusDto.getRegistrationId(), JsonUtil.objectMapperObjectToJson(userDto)); - - if (responseWrapper.getErrors() != null) { - List error = responseWrapper.getErrors(); - regProcLogger.debug("validateMapping call ended for registrationId {} with error data {}", - registrationStatusDto.getRegistrationId(), error.get(0).getMessage()); - throw new BaseCheckedException(error.get(0).getMessage(), - StatusUtil.CENTER_DEVICE_MAPPING_NOT_FOUND.getCode()); - } else if (userDto != null) { - userDto.setRegistrationCenters(userDto.getRegistrationCenters().stream().filter(u ->u!=null && u.getIsActive()).collect(Collectors.toList())); - isValidUser = userDto.getRegistrationCenters()!=null && !userDto.getRegistrationCenters().isEmpty(); - } else { - regProcLogger.debug( - "validateMapping call ended with no erros and userDTO as null so considering as mapping not valid"); - isValidUser = false; - } - - return isValidUser; - } - - -} +package io.mosip.registration.processor.stages.operatorvalidator; + +import java.io.IOException; +import java.security.NoSuchAlgorithmException; +import java.security.spec.InvalidKeySpecException; +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + +import javax.xml.parsers.ParserConfigurationException; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.xml.sax.SAXException; + +import com.fasterxml.jackson.databind.ObjectMapper; + +import io.mosip.kernel.biometrics.entities.BIR; +import io.mosip.kernel.biometrics.entities.BiometricRecord; +import io.mosip.kernel.core.bioapi.exception.BiometricException; +import io.mosip.kernel.core.exception.BaseCheckedException; +import io.mosip.kernel.core.logger.spi.Logger; +import io.mosip.kernel.core.util.StringUtils; +import io.mosip.registration.processor.core.auth.dto.IndividualIdDto; +import io.mosip.registration.processor.core.code.ApiName; +import io.mosip.registration.processor.core.code.RegistrationExceptionTypeCode; +import io.mosip.registration.processor.core.common.rest.dto.ErrorDTO; +import io.mosip.registration.processor.core.constant.MappingJsonConstants; +import io.mosip.registration.processor.core.constant.ProviderStageName; +import io.mosip.registration.processor.core.exception.ApisResourceAccessException; +import io.mosip.registration.processor.core.exception.PacketDecryptionFailureException; +import io.mosip.registration.processor.core.exception.RegistrationProcessorCheckedException; +import io.mosip.registration.processor.core.exception.ValidationFailedException; +import io.mosip.registration.processor.core.exception.util.PlatformErrorMessages; +import io.mosip.registration.processor.core.http.ResponseWrapper; +import io.mosip.registration.processor.core.logger.RegProcessorLogger; +import io.mosip.registration.processor.core.packet.dto.RegOsiDto; +import io.mosip.registration.processor.core.packet.dto.ServerError; +import io.mosip.registration.processor.core.packet.dto.masterdata.UserResponseDto; +import io.mosip.registration.processor.core.packet.dto.regcentermachine.RegistrationCenterUserMachineMappingHistoryResponseDto; +import io.mosip.registration.processor.core.spi.restclient.RegistrationProcessorRestClientService; +import io.mosip.registration.processor.core.status.util.StatusUtil; +import io.mosip.registration.processor.core.util.JsonUtil; +import io.mosip.registration.processor.core.util.RegistrationExceptionMapperUtil; +import io.mosip.registration.processor.packet.storage.utils.BioSdkUtil; +import io.mosip.registration.processor.packet.storage.utils.PriorityBasedPacketManagerService; +import io.mosip.registration.processor.packet.storage.utils.Utilities; +import io.mosip.registration.processor.status.code.RegistrationStatusCode; +import io.mosip.registration.processor.status.dto.InternalRegistrationStatusDto; + +@Service +public class OperatorValidator { + + private static Logger regProcLogger = RegProcessorLogger.getLogger(OperatorValidator.class); + + private static final String ISTRUE = "true"; + + private static final String INDIVIDUAL_TYPE_USERID = "USERID"; + + private static final String APPID = "regproc"; + + @Autowired + RegistrationExceptionMapperUtil registrationExceptionMapperUtil; + + @Autowired + RegistrationProcessorRestClientService restClientService; + + @Autowired + private PriorityBasedPacketManagerService packetManagerService; + + @Autowired + private ObjectMapper mapper; + + @Autowired + private Utilities utility; + + @Autowired + private BioSdkUtil bioUtil; + + /** + * Checks if is valid Operator. + * + * @param registrationId the registration id + * @throws SAXException + * @throws ParserConfigurationException + * @throws io.mosip.kernel.core.exception.IOException + * @throws Exception + * @throws PacketDecryptionFailureException + * @throws RegistrationProcessorCheckedException + */ + public void validate(String registrationId, InternalRegistrationStatusDto registrationStatusDto, RegOsiDto regOsi) + throws Exception { + regProcLogger.debug("validate called for registrationId {}", registrationId); + + validateOperator(registrationId, regOsi, registrationStatusDto); + authenticateOperator(regOsi, registrationId, registrationStatusDto); + validateUMCmapping(regOsi.getPacketCreationDate(), regOsi.getRegcntrId(), regOsi.getMachineId(), + regOsi.getOfficerId(), registrationStatusDto); + regProcLogger.debug("validate call ended for registrationId {}", registrationId); + } + + private void validateOperator(String registrationId, RegOsiDto regOsi, + InternalRegistrationStatusDto registrationStatusDto) throws IOException, BaseCheckedException { + String creationDate = regOsi.getPacketCreationDate(); + if (creationDate != null && !(StringUtils.isEmpty(creationDate))) { + if (!isActiveUser(regOsi.getOfficerId(), creationDate, registrationStatusDto)) { + registrationStatusDto.setLatestTransactionStatusCode(registrationExceptionMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.OFFICER_WAS_INACTIVE)); + registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.toString()); + regProcLogger.debug("ActiveUserId call ended for registrationId {} {}", registrationId, + StatusUtil.OFFICER_WAS_INACTIVE.getMessage() + regOsi.getOfficerId()); + throw new BaseCheckedException(StatusUtil.OFFICER_WAS_INACTIVE.getMessage() + regOsi.getOfficerId(), + StatusUtil.OFFICER_WAS_INACTIVE.getCode()); + } + + } else { + registrationStatusDto.setLatestTransactionStatusCode(registrationExceptionMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.PACKET_CREATION_DATE_NOT_PRESENT_IN_PACKET)); + registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.toString()); + regProcLogger.debug("ActiveUserId call ended for registrationId {}. packet creationDate is null", + registrationId); + throw new BaseCheckedException(StatusUtil.OPERATOR_PACKET_CREATION_DATE_NOT_FOUND_IN_PACKET.getMessage(), + StatusUtil.OPERATOR_PACKET_CREATION_DATE_NOT_FOUND_IN_PACKET.getCode()); + } + } + + private boolean isActiveUser(String officerId, String creationDate, + InternalRegistrationStatusDto registrationStatusDto) throws IOException, BaseCheckedException { + boolean wasOfficerActiveDuringPCT = false; + if (officerId != null && !officerId.isEmpty()) { + UserResponseDto officerResponse = getUserDetails(officerId, creationDate, registrationStatusDto); + if (officerResponse.getErrors() == null) { + wasOfficerActiveDuringPCT = officerResponse.getResponse().getUserResponseDto().get(0).getIsActive(); + if (!wasOfficerActiveDuringPCT) { + regProcLogger.debug("isActiveUser call ended for registrationId {} {}", + registrationStatusDto.getRegistrationId(), StatusUtil.OFFICER_WAS_INACTIVE.getMessage()); + } + } else { + List errors = officerResponse.getErrors(); + regProcLogger.debug("isActiveUser call ended with error {}", errors.get(0).getMessage()); + throw new BaseCheckedException( + StatusUtil.OFFICER_AUTHENTICATION_FAILED.getMessage() + errors.get(0).getMessage(), + StatusUtil.OFFICER_AUTHENTICATION_FAILED.getCode()); + } + } + return wasOfficerActiveDuringPCT; + } + + private UserResponseDto getUserDetails(String operatorId, String creationDate, + InternalRegistrationStatusDto registrationStatusDto) throws ApisResourceAccessException, IOException { + UserResponseDto userResponse; + List pathSegments = new ArrayList<>(); + pathSegments.add(operatorId); + pathSegments.add(creationDate); + + userResponse = (UserResponseDto) restClientService.getApi(ApiName.USERDETAILS, pathSegments, "", "", + UserResponseDto.class); + regProcLogger.debug("isUserActive call ended with response data {}", + JsonUtil.objectMapperObjectToJson(userResponse)); + return userResponse; + } + + /** + * To authenticate operator. + * + * @param regOsi the reg osi + * @param registrationId the registration id + * @throws SAXException + * @throws ParserConfigurationException + * @throws BiometricException + * @throws InvalidKeySpecException + * @throws io.mosip.kernel.core.exception.IOException + * @throws PacketDecryptionFailureException + * @throws Exception + * + */ + private void authenticateOperator(RegOsiDto regOsi, String registrationId, + InternalRegistrationStatusDto registrationStatusDto) + throws Exception { + String officerId = regOsi.getOfficerId(); + // officer password and otp check + String officerPassword = regOsi.getOfficerHashedPwd(); + String officerOTPAuthentication = regOsi.getOfficerOTPAuthentication(); + + String officerBiometricFileName = regOsi.getOfficerBiometricFileName(); + + if (StringUtils.isEmpty(officerBiometricFileName) || officerBiometricFileName == null) { + if (!validateOtpAndPwd(officerPassword, officerOTPAuthentication)) { + registrationStatusDto.setLatestTransactionStatusCode(registrationExceptionMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.OPERATOR_PASSWORD_OTP_FAILURE)); + registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.toString()); + regProcLogger.debug("validateOperator call ended for registrationId {} {}", registrationId, + StatusUtil.OPERATOR_PASSWORD_OTP_FAILURE.getMessage() + officerId); + throw new ValidationFailedException(StatusUtil.OPERATOR_PASSWORD_OTP_FAILURE.getMessage() + officerId, + StatusUtil.OPERATOR_PASSWORD_OTP_FAILURE.getCode()); + } + } else { + BiometricRecord biometricRecord = packetManagerService.getBiometricsByMappingJsonKey(registrationId, + MappingJsonConstants.OFFICERBIOMETRICFILENAME, registrationStatusDto.getRegistrationType(), + ProviderStageName.OPERATOR_VALIDATOR); + + if (biometricRecord == null || biometricRecord.getSegments() == null + || biometricRecord.getSegments().isEmpty()) { + regProcLogger.error("validateOperator call ended for registrationId {} {}", registrationId, + "ERROR =======>" + StatusUtil.BIOMETRICS_VALIDATION_FAILURE.getMessage()); + + registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.toString()); + throw new ValidationFailedException( + StatusUtil.BIOMETRICS_VALIDATION_FAILURE.getMessage() + " for officer : " + officerId, + StatusUtil.BIOMETRICS_VALIDATION_FAILURE.getCode()); + } else { + validateUserBiometric(registrationId, officerId, biometricRecord.getSegments(), INDIVIDUAL_TYPE_USERID, + registrationStatusDto); + } + } + } + + /** + * Validate opValidated and otpValidated. + * + * @param pwd the opValidated + * @param otp the otpValidated + * @return true, if successful + */ + private boolean validateOtpAndPwd(String opValidated, String otpValidated) { + return (opValidated != null && opValidated.equals(ISTRUE) || otpValidated != null && otpValidated.equals(ISTRUE)); + } + + + /** + * Validate user. + * + * @param userId the userid + * @param registrationId the registration id + * @param list biometric data as BIR object + * @param individualType user type + * @param registrationStatusDto + * @throws Exception + * @throws SAXException + * @throws ParserConfigurationException + * @throws NoSuchAlgorithmException + * @throws InvalidKeySpecException + * @throws BiometricException + */ + + private void validateUserBiometric(String registrationId, String userId, List list, String individualType, + InternalRegistrationStatusDto registrationStatusDto) + throws Exception { + + if (INDIVIDUAL_TYPE_USERID.equalsIgnoreCase(individualType)) { + userId = getIndividualIdByUserId(userId); + individualType = null; + } + + bioUtil.authenticateBiometrics(userId, individualType, list,registrationStatusDto, + StatusUtil.OFFICER_AUTHENTICATION_FAILED.getMessage(), + StatusUtil.OFFICER_AUTHENTICATION_FAILED.getCode()); + + regProcLogger.debug("validateUserBiometric call ended for registrationId {}", registrationId); + + } + + /** + * get the individualId by userid + * + * @param userid + * @return individualId + * @throws ApisResourceAccessException + * @throws IOException + */ + private String getIndividualIdByUserId(String userid) throws ApisResourceAccessException, IOException { + + regProcLogger.debug("getIndividualIdByUserId called for userid {}", userid); + List pathSegments = new ArrayList<>(); + pathSegments.add(APPID); + pathSegments.add(userid); + String individualId = null; + ResponseWrapper response = null; + response = (ResponseWrapper) restClientService.getApi(ApiName.GETINDIVIDUALIDFROMUSERID, pathSegments, "", + "", ResponseWrapper.class); + regProcLogger.debug( + "getIndividualIdByUserId called for with GETINDIVIDUALIDFROMUSERID GET service call ended successfully"); + if (response.getErrors() != null) { + throw new ApisResourceAccessException( + PlatformErrorMessages.LINK_FOR_USERID_INDIVIDUALID_FAILED_OVM_EXCEPTION.toString()); + } else { + IndividualIdDto readValue = mapper.readValue(mapper.writeValueAsString(response.getResponse()), + IndividualIdDto.class); + individualId = readValue.getIndividualId(); + } + regProcLogger.debug("getIndividualIdByUserId call ended for userid {}", userid); + return individualId; + } + + /** + * Validate UMC cmapping. + * + * @param effectiveTimestamp the effective timestamp + * @param registrationCenterId the registration center id + * @param machineId the machine id + * @param officerId the officer id + * @param registrationStatusDto + * @throws IOException + * @throws BaseCheckedException + */ + private void validateUMCmapping(String effectiveTimestamp, String registrationCenterId, String machineId, + String officerId, InternalRegistrationStatusDto registrationStatusDto) + throws IOException, BaseCheckedException { + + List officerpathsegments = new ArrayList<>(); + officerpathsegments.add(effectiveTimestamp); + officerpathsegments.add(registrationCenterId); + officerpathsegments.add(machineId); + officerpathsegments.add(officerId); + + if (!validateMapping(officerpathsegments, registrationStatusDto)) { + throw new ValidationFailedException(StatusUtil.OFFICER_NOT_ACTIVE.getMessage(), + StatusUtil.OFFICER_NOT_ACTIVE.getCode()); + } + + } + + private boolean validateMapping(List pathsegments, InternalRegistrationStatusDto registrationStatusDto) + throws IOException, BaseCheckedException { + boolean isValidUser = false; + ResponseWrapper responseWrapper; + RegistrationCenterUserMachineMappingHistoryResponseDto userDto = null; + + responseWrapper = (ResponseWrapper) restClientService.getApi(ApiName.CENTERUSERMACHINEHISTORY, + pathsegments, "", "", ResponseWrapper.class); + userDto = mapper.readValue(mapper.writeValueAsString(responseWrapper.getResponse()), + RegistrationCenterUserMachineMappingHistoryResponseDto.class); + regProcLogger.debug("validateMapping call ended for registrationId {} with response data {}", + registrationStatusDto.getRegistrationId(), JsonUtil.objectMapperObjectToJson(userDto)); + + if (responseWrapper.getErrors() != null) { + List error = responseWrapper.getErrors(); + regProcLogger.debug("validateMapping call ended for registrationId {} with error data {}", + registrationStatusDto.getRegistrationId(), error.get(0).getMessage()); + throw new BaseCheckedException(error.get(0).getMessage(), + StatusUtil.CENTER_DEVICE_MAPPING_NOT_FOUND.getCode()); + } else if (userDto != null) { + userDto.setRegistrationCenters(userDto.getRegistrationCenters().stream().filter(u ->u!=null && u.getIsActive()).collect(Collectors.toList())); + isValidUser = userDto.getRegistrationCenters()!=null && !userDto.getRegistrationCenters().isEmpty(); + } else { + regProcLogger.debug( + "validateMapping call ended with no erros and userDTO as null so considering as mapping not valid"); + isValidUser = false; + } + + return isValidUser; + } + + +} diff --git a/registration-processor/pre-processor/registration-processor-packet-uploader-stage/src/main/java/io/mosip/registration/processor/packet/uploader/service/impl/PacketUploaderServiceImpl.java b/registration-processor/pre-processor/registration-processor-packet-uploader-stage/src/main/java/io/mosip/registration/processor/packet/uploader/service/impl/PacketUploaderServiceImpl.java index 0b55963cf81..866dac0884c 100644 --- a/registration-processor/pre-processor/registration-processor-packet-uploader-stage/src/main/java/io/mosip/registration/processor/packet/uploader/service/impl/PacketUploaderServiceImpl.java +++ b/registration-processor/pre-processor/registration-processor-packet-uploader-stage/src/main/java/io/mosip/registration/processor/packet/uploader/service/impl/PacketUploaderServiceImpl.java @@ -1,657 +1,657 @@ -package io.mosip.registration.processor.packet.uploader.service.impl; -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -import org.apache.commons.io.IOUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.cloud.context.config.annotation.RefreshScope; -import org.springframework.http.HttpStatus; -import org.springframework.stereotype.Component; -import org.springframework.web.client.HttpClientErrorException; - -import com.fasterxml.jackson.databind.ObjectMapper; - -import io.mosip.commons.khazana.exception.ObjectStoreAdapterException; -import io.mosip.commons.khazana.spi.ObjectStoreAdapter; -import io.mosip.kernel.core.exception.ExceptionUtils; -import io.mosip.kernel.core.logger.spi.Logger; -import io.mosip.kernel.core.util.HMACUtils2; -import io.mosip.kernel.core.virusscanner.exception.VirusScannerException; -import io.mosip.kernel.core.virusscanner.spi.VirusScanner; -import io.mosip.registration.processor.core.abstractverticle.MessageDTO; -import io.mosip.registration.processor.core.code.ApiName; -import io.mosip.registration.processor.core.code.EventId; -import io.mosip.registration.processor.core.code.EventName; -import io.mosip.registration.processor.core.code.EventType; -import io.mosip.registration.processor.core.code.ModuleName; -import io.mosip.registration.processor.core.code.RegistrationExceptionTypeCode; -import io.mosip.registration.processor.core.code.RegistrationTransactionStatusCode; -import io.mosip.registration.processor.core.code.RegistrationTransactionTypeCode; -import io.mosip.registration.processor.core.constant.LandingZoneTypeConstant; -import io.mosip.registration.processor.core.constant.LoggerFileConstant; -import io.mosip.registration.processor.core.exception.ApisResourceAccessException; -import io.mosip.registration.processor.core.exception.ObjectStoreNotAccessibleException; -import io.mosip.registration.processor.core.exception.PacketDecryptionFailureException; -import io.mosip.registration.processor.core.exception.SftpFileOperationException; -import io.mosip.registration.processor.core.exception.util.PlatformErrorMessages; -import io.mosip.registration.processor.core.exception.util.PlatformSuccessMessages; -import io.mosip.registration.processor.core.logger.LogDescription; -import io.mosip.registration.processor.core.logger.RegProcessorLogger; -import io.mosip.registration.processor.core.packet.dto.AdditionalInfoRequestDto; -import io.mosip.registration.processor.core.spi.restclient.RegistrationProcessorRestClientService; -import io.mosip.registration.processor.core.status.util.StatusUtil; -import io.mosip.registration.processor.core.status.util.TrimExceptionMessage; -import io.mosip.registration.processor.core.util.RegistrationExceptionMapperUtil; -import io.mosip.registration.processor.packet.manager.decryptor.Decryptor; -import io.mosip.registration.processor.packet.manager.utils.ZipUtils; -import io.mosip.registration.processor.packet.storage.dto.ConfigEnum; -import io.mosip.registration.processor.packet.storage.utils.Utilities; -import io.mosip.registration.processor.packet.uploader.exception.PacketNotFoundException; -import io.mosip.registration.processor.packet.uploader.service.PacketUploaderService; -import io.mosip.registration.processor.rest.client.audit.builder.AuditLogRequestBuilder; -import io.mosip.registration.processor.status.code.RegistrationStatusCode; -import io.mosip.registration.processor.status.dto.InternalRegistrationStatusDto; -import io.mosip.registration.processor.status.dto.RegistrationStatusDto; -import io.mosip.registration.processor.status.dto.SyncRegistrationDto; -import io.mosip.registration.processor.status.dto.SyncResponseDto; -import io.mosip.registration.processor.status.entity.SyncRegistrationEntity; -import io.mosip.registration.processor.status.exception.TablenotAccessibleException; -import io.mosip.registration.processor.status.service.RegistrationStatusService; -import io.mosip.registration.processor.status.service.AdditionalInfoRequestService; -import io.mosip.registration.processor.status.service.SyncRegistrationService; - -/** - * The Class PacketUploaderServiceImpl. - * - * @author Rishabh Keshari - */ -@RefreshScope -@Component -public class PacketUploaderServiceImpl implements PacketUploaderService { - - /** - * The reg proc logger. - */ - private static Logger regProcLogger = RegProcessorLogger.getLogger(PacketUploaderServiceImpl.class); - - /** - * The fillesystem manager. - */ - private static final String USER = "MOSIP_SYSTEM"; - private static final String ZIP = ".zip"; - private static final String JSON = ".json"; - private static final String FORWARD_SLASH = "/"; - - @Value("${mosip.regproc.landing.zone.account.name}") - private String landingZoneAccount; - - @Value("${mosip.regproc.landing.zone.type:ObjectStore}") - private String landingZoneType; - - @Value("${packet.manager.account.name}") - private String packetManagerAccount; - - @Value("${packet.manager.iteration.addition.enabled:true}") - private boolean isIterationAdditionEnabled; - - /** - * the packet extension(Ex - .zip) - */ - @Value("${registration.processor.packet.ext}") - private String extention; - - @Value("${mosip.commons.packetnames}") - private String packetNames; - - /** - * The max retry count. - */ - @Value("${registration.processor.max.retry}") - private int maxRetryCount; - - @Autowired - private ObjectStoreAdapter objectStoreAdapter; - - /** - * The sync registration service. - */ - @Autowired - private SyncRegistrationService syncRegistrationService; - - /** - * The registration status service. - */ - @Autowired - private RegistrationStatusService registrationStatusService; - - @Autowired - private AdditionalInfoRequestService additionalInfoRequestService; - - /** - * The core audit request builder. - */ - @Autowired - private AuditLogRequestBuilder auditLogRequestBuilder; - - /** - * The virus scanner service. - */ - @Autowired - private VirusScanner virusScannerService; - - @Autowired - private RegistrationProcessorRestClientService restClient; - - /** - * The registration status mapper util. - */ - @Autowired - private RegistrationExceptionMapperUtil registrationStatusMapperUtil; - - @Autowired - private Decryptor decryptor; - - @Autowired - private ObjectMapper mapper; - - @Autowired - private Utilities utility; - - - /** - * The is transaction successful. - */ - boolean isTransactionSuccessful = false; - - /* - * java class to trim exception message - */ - private TrimExceptionMessage trimExpMessage = new TrimExceptionMessage(); - - /* - * (non-Javadoc) - * - * @see io.mosip.id.issuance.packet.handler.service.PacketUploadService# - * validatePacket( java.lang.Object) - */ - - @Override - public MessageDTO validateAndUploadPacket(MessageDTO messageDTO, String stageName) { - - LogDescription description = new LogDescription(); - InternalRegistrationStatusDto dto = new InternalRegistrationStatusDto(); - messageDTO.setInternalError(Boolean.FALSE); - messageDTO.setIsValid(Boolean.FALSE); - isTransactionSuccessful = false; - String registrationId = messageDTO.getRid(); - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - registrationId, "PacketUploaderServiceImpl::validateAndUploadPacket()::entry"); - SyncRegistrationEntity regEntity = null; - - try { - regEntity = syncRegistrationService.findByWorkflowInstanceId(messageDTO.getWorkflowInstanceId()); - dto = registrationStatusService.getRegistrationStatus( - registrationId, messageDTO.getReg_type(), messageDTO.getIteration(), regEntity.getWorkflowInstanceId()); - - dto.setLatestTransactionTypeCode(RegistrationTransactionTypeCode.UPLOAD_PACKET.toString()); - dto.setRegistrationStageName(stageName); - - final byte[] encryptedByteArray = getPakcetFromDMZ(regEntity.getPacketId(),registrationId); - - if (encryptedByteArray != null) { - - if (validateHashCode(new ByteArrayInputStream(encryptedByteArray), regEntity, registrationId, dto, - description)) { - InputStream decryptedPacket = decryptor.decrypt( - registrationId, - utility.getRefId(registrationId, regEntity.getReferenceId()), - new ByteArrayInputStream(encryptedByteArray)); - final byte[] decryptedPacketBytes = IOUtils.toByteArray(decryptedPacket); - if (scanFile(encryptedByteArray, registrationId, - regEntity.getReferenceId(), ZipUtils.unzipAndGetFiles(new ByteArrayInputStream( - decryptedPacketBytes)), dto, description, messageDTO)) { - int retrycount = (dto.getRetryCount() == null) ? 0 : dto.getRetryCount() + 1; - dto.setRetryCount(retrycount); - if (retrycount < getMaxRetryCount()) { - - messageDTO = uploadPacket(regEntity, dto, ZipUtils.unzipAndGetFiles(new ByteArrayInputStream(decryptedPacketBytes)), messageDTO, description); - if (messageDTO.getIsValid()) { - dto.setLatestTransactionStatusCode( - RegistrationTransactionStatusCode.SUCCESS.toString()); - isTransactionSuccessful = true; - description.setMessage(PlatformSuccessMessages.RPR_PUM_PACKET_UPLOADER.getMessage()); - regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), - LoggerFileConstant.REGISTRATIONID.toString(), registrationId, - description.getMessage()); - - } - } else { - - messageDTO.setInternalError(Boolean.TRUE); - description.setMessage(PlatformErrorMessages.RPR_PUM_PACKET_RETRY_CNT_FAILURE.getMessage()); - description.setCode(PlatformErrorMessages.RPR_PUM_PACKET_RETRY_CNT_FAILURE.getCode()); - dto.setLatestTransactionStatusCode(registrationStatusMapperUtil - .getStatusCode(RegistrationExceptionTypeCode.PACKET_UPLOAD_FAILED_ON_MAX_RETRY_CNT)); - dto.setStatusCode(RegistrationStatusCode.FAILED.toString()); - dto.setStatusComment(StatusUtil.PACKET_RETRY_CNT_EXCEEDED.getMessage()); - dto.setSubStatusCode(StatusUtil.PACKET_RETRY_CNT_EXCEEDED.getCode()); - dto.setUpdatedBy(USER); - regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), - LoggerFileConstant.REGISTRATIONID.toString(), registrationId, - description.getMessage()); - } - } - } - } else { - messageDTO.setInternalError(Boolean.TRUE); - - dto.setLatestTransactionStatusCode(registrationStatusMapperUtil - .getStatusCode(RegistrationExceptionTypeCode.PACKET_NOT_FOUND_EXCEPTION)); - dto.setStatusCode(RegistrationExceptionTypeCode.PACKET_NOT_FOUND_EXCEPTION.toString()); - dto.setStatusComment(StatusUtil.PACKET_NOT_FOUND_LANDING_ZONE.getMessage()); - dto.setSubStatusCode(StatusUtil.PACKET_NOT_FOUND_LANDING_ZONE.getCode()); - dto.setUpdatedBy(USER); - description.setMessage(PlatformErrorMessages.RPR_PUM_PACKET_NOT_FOUND_EXCEPTION.getMessage()); - description.setCode(PlatformErrorMessages.RPR_PUM_PACKET_NOT_FOUND_EXCEPTION.getCode()); - - } - - } catch (TablenotAccessibleException e) { - messageDTO.setInternalError(Boolean.TRUE); - dto.setLatestTransactionStatusCode(registrationStatusMapperUtil - .getStatusCode(RegistrationExceptionTypeCode.TABLE_NOT_ACCESSIBLE_EXCEPTION)); - dto.setStatusComment( - trimExpMessage.trimExceptionMessage(StatusUtil.DB_NOT_ACCESSIBLE.getMessage() + e.getMessage())); - dto.setSubStatusCode(StatusUtil.DB_NOT_ACCESSIBLE.getCode()); - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - registrationId, PlatformErrorMessages.RPR_RGS_REGISTRATION_TABLE_NOT_ACCESSIBLE.name() - + ExceptionUtils.getStackTrace(e)); - - description.setMessage(PlatformErrorMessages.RPR_RGS_REGISTRATION_TABLE_NOT_ACCESSIBLE.getMessage()); - description.setCode(PlatformErrorMessages.RPR_RGS_REGISTRATION_TABLE_NOT_ACCESSIBLE.getCode()); - - } catch (PacketNotFoundException ex) { - if (!isPacketAlreadyPresentInObjectStore(messageDTO.getRid(), messageDTO.getReg_type())) { - messageDTO.setInternalError(Boolean.TRUE); - dto.setLatestTransactionStatusCode(registrationStatusMapperUtil - .getStatusCode(RegistrationExceptionTypeCode.PACKET_NOT_FOUND_EXCEPTION)); - dto.setStatusComment(RegistrationExceptionTypeCode.PACKET_NOT_FOUND_EXCEPTION.toString()); - dto.setSubStatusCode(StatusUtil.PACKET_NOT_FOUND_PACKET_STORE.getCode()); - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - registrationId, - PlatformErrorMessages.RPR_PUM_PACKET_NOT_FOUND_EXCEPTION.name() + ExceptionUtils.getStackTrace(ex)); - description.setMessage(PlatformErrorMessages.RPR_PUM_PACKET_NOT_FOUND_EXCEPTION.getMessage()); - description.setCode(PlatformErrorMessages.RPR_PUM_PACKET_NOT_FOUND_EXCEPTION.getCode()); - } else { - regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), - LoggerFileConstant.REGISTRATIONID.toString(), registrationId, - "Packet is not present in LANDING_ZONE but alrady present in object store. Hence this request will be marked as success."); - messageDTO.setInternalError(false); - messageDTO.setIsValid(true); - isTransactionSuccessful = true; - dto.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); - dto.setStatusComment(StatusUtil.PACKET_ALREADY_UPLOADED.getMessage()); - dto.setSubStatusCode(StatusUtil.PACKET_ALREADY_UPLOADED.getCode()); - dto.setLatestTransactionStatusCode(RegistrationTransactionStatusCode.SUCCESS.toString()); - description.setMessage(PlatformSuccessMessages.RPR_PUM_PACKET_UPLOADER_ALREADY_UPLOADED.getMessage()); - description.setCode(PlatformSuccessMessages.RPR_PUM_PACKET_UPLOADER_ALREADY_UPLOADED.getCode()); - } - - } catch (ApisResourceAccessException e) { - messageDTO.setInternalError(Boolean.TRUE); - dto.setLatestTransactionStatusCode( - registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.NGINX_ACCESS_EXCEPTION)); - dto.setStatusComment(trimExpMessage - .trimExceptionMessage(StatusUtil.NGINX_ACCESS_EXCEPTION.getMessage() + e.getMessage())); - dto.setSubStatusCode(StatusUtil.IO_EXCEPTION.getCode()); - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - registrationId, - PlatformErrorMessages.RPR_PUM_NGINX_ACCESS_FAILED.name() + ExceptionUtils.getStackTrace(e)); - - description.setMessage(PlatformErrorMessages.RPR_PUM_NGINX_ACCESS_FAILED.getMessage()); - description.setCode(PlatformErrorMessages.RPR_PUM_NGINX_ACCESS_FAILED.getCode()); - } catch (IOException | NoSuchAlgorithmException e) { - messageDTO.setInternalError(Boolean.TRUE); - dto.setLatestTransactionStatusCode( - registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.IOEXCEPTION)); - dto.setStatusComment( - trimExpMessage.trimExceptionMessage(StatusUtil.IO_EXCEPTION.getMessage() + e.getMessage())); - dto.setSubStatusCode(StatusUtil.IO_EXCEPTION.getCode()); - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - registrationId, - PlatformErrorMessages.RPR_SYS_IO_EXCEPTION.name() + ExceptionUtils.getStackTrace(e)); - description.setMessage(PlatformErrorMessages.RPR_SYS_IO_EXCEPTION.getMessage()); - description.setCode(PlatformErrorMessages.RPR_SYS_IO_EXCEPTION.getCode()); - - } catch (PacketDecryptionFailureException e) { - messageDTO.setInternalError(Boolean.TRUE); - dto.setStatusCode(RegistrationStatusCode.FAILED.toString()); - dto.setStatusComment(StatusUtil.PACKET_DECRYPTION_FAILED.getMessage()); - dto.setSubStatusCode(StatusUtil.PACKET_DECRYPTION_FAILED.getCode()); - dto.setLatestTransactionStatusCode(registrationStatusMapperUtil - .getStatusCode(RegistrationExceptionTypeCode.PACKET_DECRYPTION_FAILURE_EXCEPTION)); - description.setMessage(PlatformErrorMessages.RPR_PUM_PACKET_DECRYPTION_FAILED.getMessage()); - description.setCode(PlatformErrorMessages.RPR_PUM_PACKET_DECRYPTION_FAILED.getCode()); - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - registrationId, ExceptionUtils.getStackTrace(e)); - - } catch (ObjectStoreNotAccessibleException e) { - messageDTO.setInternalError(Boolean.TRUE); - dto.setStatusCode(RegistrationStatusCode.FAILED.toString()); - dto.setStatusComment(StatusUtil.OBJECT_STORE_EXCEPTION.getMessage()); - dto.setSubStatusCode(StatusUtil.OBJECT_STORE_EXCEPTION.getCode()); - dto.setLatestTransactionStatusCode(registrationStatusMapperUtil - .getStatusCode(RegistrationExceptionTypeCode.OBJECT_STORE_EXCEPTION)); - description.setMessage(PlatformErrorMessages.OBJECT_STORE_NOT_ACCESSIBLE.getMessage()); - description.setCode(PlatformErrorMessages.OBJECT_STORE_NOT_ACCESSIBLE.getCode()); - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - registrationId, PlatformErrorMessages.OBJECT_STORE_NOT_ACCESSIBLE.name() - + ExceptionUtils.getStackTrace(e)); - } catch (Exception e) { - messageDTO.setInternalError(Boolean.TRUE); - dto.setLatestTransactionStatusCode( - registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.EXCEPTION)); - dto.setStatusComment(trimExpMessage - .trimExceptionMessage(StatusUtil.UNKNOWN_EXCEPTION_OCCURED.getMessage() + e.getMessage())); - dto.setSubStatusCode(StatusUtil.UNKNOWN_EXCEPTION_OCCURED.getCode()); - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - registrationId, - PlatformErrorMessages.RPR_PKR_UNKNOWN_EXCEPTION.name() + ExceptionUtils.getStackTrace(e)); - description.setMessage(PlatformErrorMessages.RPR_PKR_UNKNOWN_EXCEPTION.getMessage()); - description.setCode(PlatformErrorMessages.RPR_PKR_UNKNOWN_EXCEPTION.getCode()); - - } finally { - if (messageDTO.getInternalError()) { - updateErrorFlags(dto, messageDTO); - } - /** Module-Id can be Both Success/Error code */ - String moduleId = isTransactionSuccessful ? PlatformSuccessMessages.RPR_PUM_PACKET_UPLOADER.getCode() - : description.getCode(); - String moduleName = ModuleName.PACKET_UPLOAD.toString(); - registrationStatusService.updateRegistrationStatus(dto, moduleId, moduleName); - String eventId = ""; - String eventName = ""; - String eventType = ""; - eventId = isTransactionSuccessful ? EventId.RPR_402.toString() : EventId.RPR_405.toString(); - eventName = eventId.equalsIgnoreCase(EventId.RPR_402.toString()) ? EventName.UPDATE.toString() - : EventName.EXCEPTION.toString(); - eventType = eventId.equalsIgnoreCase(EventId.RPR_402.toString()) ? EventType.BUSINESS.toString() - : EventType.SYSTEM.toString(); - - auditLogRequestBuilder.createAuditRequestBuilder(description.getMessage(), eventId, eventName, eventType, - moduleId, moduleName, registrationId); - - } - - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - registrationId, "PacketUploaderServiceImpl::validateAndUploadPacket()::exit"); - return messageDTO; - } - - /** - * Scan file. - * - * @param input the input stream - * @param refId - * @param description - * @return true, if successful - * @throws IOException - * @throws ApisResourceAccessException - */ - private boolean scanFile(final byte[] input, String id, String refId, final Map sourcePackets, InternalRegistrationStatusDto dto, - LogDescription description, MessageDTO messageDTO) throws ApisResourceAccessException, PacketDecryptionFailureException { - boolean isInputFileClean = false; - try { - InputStream packet = new ByteArrayInputStream(input); - // scanning the top level packet - isInputFileClean = virusScannerService.scanFile(packet); - - if (isInputFileClean) { - // scanning the source packets (Like - id, evidence, optional packets). - for (final Map.Entry source : sourcePackets.entrySet()) { - if (source.getKey().endsWith(ZIP)) { - InputStream decryptedData = decryptor - .decrypt(id, utility.getRefId(id, refId), source.getValue()); - isInputFileClean = virusScannerService.scanFile(decryptedData); - } else - isInputFileClean = virusScannerService.scanFile(source.getValue()); - if (!isInputFileClean) - break; - } - } - if (!isInputFileClean) { - description.setMessage(PlatformErrorMessages.RPR_PUM_PACKET_VIRUS_SCAN_FAILED.getMessage()); - description.setCode(PlatformErrorMessages.RPR_PUM_PACKET_VIRUS_SCAN_FAILED.getCode()); - dto.setStatusCode(RegistrationExceptionTypeCode.VIRUS_SCAN_FAILED_EXCEPTION.toString()); - dto.setStatusComment(StatusUtil.VIRUS_SCANNER_FAILED_UPLOADER.getMessage()); - dto.setSubStatusCode(StatusUtil.VIRUS_SCANNER_FAILED_UPLOADER.getCode()); - dto.setLatestTransactionStatusCode(registrationStatusMapperUtil - .getStatusCode(RegistrationExceptionTypeCode.VIRUS_SCAN_FAILED_EXCEPTION)); - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), - LoggerFileConstant.REGISTRATIONID.toString(), id, - PlatformErrorMessages.RPR_PUM_PACKET_VIRUS_SCAN_FAILED.getMessage()); - } - } catch (VirusScannerException e) { - messageDTO.setInternalError(Boolean.TRUE); - description.setMessage(PlatformErrorMessages.RPR_PUM_PACKET_VIRUS_SCANNER_SERVICE_FAILED.getMessage()); - description.setCode(PlatformErrorMessages.RPR_PUM_PACKET_VIRUS_SCANNER_SERVICE_FAILED.getCode()); - dto.setStatusCode(RegistrationExceptionTypeCode.VIRUS_SCANNER_SERVICE_FAILED.toString()); - dto.setStatusComment(trimExpMessage.trimExceptionMessage( - StatusUtil.VIRUS_SCANNER_SERVICE_NOT_ACCESSIBLE.getMessage() + " " + e.getMessage())); - dto.setSubStatusCode(StatusUtil.VIRUS_SCANNER_SERVICE_NOT_ACCESSIBLE.getCode()); - dto.setLatestTransactionStatusCode(registrationStatusMapperUtil - .getStatusCode(RegistrationExceptionTypeCode.VIRUS_SCANNER_SERVICE_FAILED)); - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - id, PlatformErrorMessages.RPR_PUM_PACKET_VIRUS_SCANNER_SERVICE_FAILED.getMessage() - + ExceptionUtils.getStackTrace(e)); - - } - return isInputFileClean; - } - - /** - * Validate hash code. - * - * @param registrationId the registration id - * @param inputStream the input stream - * @param registrationId - * @param description - * @throws IOException Signals that an I/O exception has occurred. - */ - private boolean validateHashCode(InputStream inputStream, SyncRegistrationEntity regEntity, String registrationId, - InternalRegistrationStatusDto dto, LogDescription description) throws IOException, NoSuchAlgorithmException { - boolean isValidHash = false; - byte[] isbytearray = IOUtils.toByteArray(inputStream); - String hashSequence = HMACUtils2.digestAsPlainText(isbytearray); - String packetHashSequence = regEntity.getPacketHashValue(); - if (!(MessageDigest.isEqual(packetHashSequence.getBytes(), hashSequence.getBytes()))) { - description.setMessage(PlatformErrorMessages.RPR_PKR_PACKET_HASH_NOT_EQUALS_SYNCED_HASH.getMessage()); - description.setCode(PlatformErrorMessages.RPR_PKR_PACKET_HASH_NOT_EQUALS_SYNCED_HASH.getCode()); - dto.setLatestTransactionStatusCode( - registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.PACKET_HASH_VALIDATION_FAILED)); - dto.setStatusCode(RegistrationExceptionTypeCode.PACKET_HASH_VALIDATION_FAILED.toString()); - dto.setStatusComment(StatusUtil.PACKET_HASHCODE_VALIDATION_FAILED.getMessage()); - dto.setSubStatusCode(StatusUtil.PACKET_HASHCODE_VALIDATION_FAILED.getCode()); - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - registrationId, PlatformErrorMessages.RPR_PKR_PACKET_HASH_NOT_EQUALS_SYNCED_HASH.getMessage()); - - return isValidHash; - } else { - isValidHash = true; - return isValidHash; - } - } - - /** - * Uploadpacket. - * - * @param dto the dto - * @param sourcePackets source packets - * @param object the object - * @param description - * @return the message DTO - * @throws IOException Signals that an I/O exception has occurred. - * @throws SftpFileOperationException - */ - private MessageDTO uploadPacket(SyncRegistrationEntity regEntity, InternalRegistrationStatusDto dto, final Map sourcePackets, - MessageDTO object, LogDescription description) throws ObjectStoreNotAccessibleException { - - object.setIsValid(false); - String registrationId = dto.getRegistrationId(); - // upload packets - try { - for (Map.Entry entry : sourcePackets.entrySet()) { - if (entry.getKey().endsWith(ZIP)) { - String objStoreKey = isIterationAdditionEnabled ? - getFinalKey(regEntity, entry.getKey().replace(ZIP, ""), object) - : - entry.getKey().replace(ZIP, ""); - boolean result = objectStoreAdapter.putObject(packetManagerAccount, registrationId, - null, null, objStoreKey, entry.getValue()); - if (!result) - throw new ObjectStoreNotAccessibleException("Failed to store packet : " + entry.getKey()); - } - } - - // upload metadata - for (Map.Entry entry : sourcePackets.entrySet()) { - if (entry.getKey().endsWith(JSON)) { - byte[] bytearray = IOUtils.toByteArray(entry.getValue()); - String jsonString = new String(bytearray); - LinkedHashMap currentIdMap = (LinkedHashMap) mapper.readValue(jsonString, LinkedHashMap.class); - String objStoreKey = isIterationAdditionEnabled ? - getFinalKey(regEntity, entry.getKey().replace(JSON, ""), object) - : - entry.getKey().replace(JSON, ""); - objectStoreAdapter.addObjectMetaData(packetManagerAccount, registrationId, - null, null, objStoreKey, currentIdMap); - } - } - } catch (Exception e) { - object.setIsValid(false); - object.setInternalError(true); - throw new ObjectStoreNotAccessibleException(e.getMessage(), e); - } - - - dto.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); - dto.setStatusComment(StatusUtil.PACKET_UPLOADED.getMessage()); - dto.setSubStatusCode(StatusUtil.PACKET_UPLOADED.getCode()); - dto.setUpdatedBy(USER); - object.setInternalError(false); - object.setIsValid(true); - object.setRid(registrationId); - - isTransactionSuccessful = true; - description.setMessage(PlatformErrorMessages.RPR_PUM_PACKET_DELETION_INFO.getMessage()); - description.setCode(PlatformErrorMessages.RPR_PUM_PACKET_DELETION_INFO.getCode()); - - regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), - LoggerFileConstant.REGISTRATIONID.toString(), registrationId, - PlatformErrorMessages.RPR_PUM_PACKET_DELETION_INFO.getMessage()); - - return object; - } - - /** - * Get max retry count. - * - * @return maxRetryCount - */ - public int getMaxRetryCount() { - return maxRetryCount; - } - - private byte[] getPakcetFromDMZ(String packetId, String registrationId) throws ApisResourceAccessException, ObjectStoreNotAccessibleException, IOException { - List pathSegment = new ArrayList<>(); - pathSegment.add(packetId + extention); - byte[] packet = null; - - try { - if(landingZoneType.equalsIgnoreCase(LandingZoneTypeConstant.DMZ_SERVER)) { - packet = (byte[]) restClient.getApi(ApiName.NGINXDMZURL, pathSegment, "", null, byte[].class); - } - else if(landingZoneType.equalsIgnoreCase(LandingZoneTypeConstant.OBJECT_STORE)) { - packet=IOUtils.toByteArray(objectStoreAdapter.getObject(landingZoneAccount, registrationId, null, null, packetId)); - if(packet==null) { - throw new ObjectStoreNotAccessibleException("Failed to get packet : " +packetId); - } - } - } catch (ApisResourceAccessException e) { - if (e.getCause() instanceof HttpClientErrorException) { - HttpClientErrorException ex = (HttpClientErrorException) e.getCause(); - if (ex.getStatusCode().equals(HttpStatus.NOT_FOUND)) - throw new PacketNotFoundException(PlatformErrorMessages.RPR_PUM_PACKET_NOT_FOUND_EXCEPTION.getMessage(), ex); - } else - throw e; - } catch(ObjectStoreAdapterException e) { - throw e; - } - return packet; - } - - /** - * Modify process name to add iteration before uploading to object store. - * @param regEntity - * @param packetKey - * @return - */ - private String getFinalKey(SyncRegistrationEntity regEntity, String packetKey, MessageDTO messageDTO) { - String[] tempKeys = packetKey.split(FORWARD_SLASH); - // if known format of source/process/objectName only then modify the process - if (tempKeys != null && tempKeys.length == 3) { - String source = tempKeys[0]; - String process = tempKeys[1]; - String objectName = tempKeys[2]; - AdditionalInfoRequestDto additionalInfoRequestDto = additionalInfoRequestService - .getAdditionalInfoRequestByRegIdAndProcessAndIteration(messageDTO.getRid(), - messageDTO.getReg_type(), messageDTO.getIteration()); - - if (additionalInfoRequestDto != null && - additionalInfoRequestDto.getAdditionalInfoReqId().equals(regEntity.getAdditionalInfoReqId())) { - return source + FORWARD_SLASH + process + "-" + messageDTO.getIteration() + FORWARD_SLASH + objectName; - } else - return packetKey; - - } else { - regProcLogger.warn("PacketUploaderServiceImpl::getFinalKey() The packet key is not in source/process/objectName format " - + packetKey + " id : " + messageDTO.getRid()); - return packetKey; - } - } - - private void updateErrorFlags(InternalRegistrationStatusDto registrationStatusDto, MessageDTO object) { - object.setInternalError(true); - if (registrationStatusDto.getLatestTransactionStatusCode() - .equalsIgnoreCase(RegistrationTransactionStatusCode.REPROCESS.toString())) { - object.setIsValid(true); - } else { - object.setIsValid(false); - } - } - - - public boolean isPacketAlreadyPresentInObjectStore(String id, String process) { - - for (String name : packetNames.split(",")) { - boolean isPresent = objectStoreAdapter.exists(packetManagerAccount, id, utility.getDefaultSource(process, ConfigEnum.READER), process, id+ "_" + name); - if (!isPresent) { - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - id, name + " : packet not present in object store."); - return false; - } - } - return true; - } - - - +package io.mosip.registration.processor.packet.uploader.service.impl; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import org.apache.commons.io.IOUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.cloud.context.config.annotation.RefreshScope; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Component; +import org.springframework.web.client.HttpClientErrorException; + +import com.fasterxml.jackson.databind.ObjectMapper; + +import io.mosip.commons.khazana.exception.ObjectStoreAdapterException; +import io.mosip.commons.khazana.spi.ObjectStoreAdapter; +import io.mosip.kernel.core.exception.ExceptionUtils; +import io.mosip.kernel.core.logger.spi.Logger; +import io.mosip.kernel.core.util.HMACUtils2; +import io.mosip.kernel.core.virusscanner.exception.VirusScannerException; +import io.mosip.kernel.core.virusscanner.spi.VirusScanner; +import io.mosip.registration.processor.core.abstractverticle.MessageDTO; +import io.mosip.registration.processor.core.code.ApiName; +import io.mosip.registration.processor.core.code.EventId; +import io.mosip.registration.processor.core.code.EventName; +import io.mosip.registration.processor.core.code.EventType; +import io.mosip.registration.processor.core.code.ModuleName; +import io.mosip.registration.processor.core.code.RegistrationExceptionTypeCode; +import io.mosip.registration.processor.core.code.RegistrationTransactionStatusCode; +import io.mosip.registration.processor.core.code.RegistrationTransactionTypeCode; +import io.mosip.registration.processor.core.constant.LandingZoneTypeConstant; +import io.mosip.registration.processor.core.constant.LoggerFileConstant; +import io.mosip.registration.processor.core.exception.ApisResourceAccessException; +import io.mosip.registration.processor.core.exception.ObjectStoreNotAccessibleException; +import io.mosip.registration.processor.core.exception.PacketDecryptionFailureException; +import io.mosip.registration.processor.core.exception.SftpFileOperationException; +import io.mosip.registration.processor.core.exception.util.PlatformErrorMessages; +import io.mosip.registration.processor.core.exception.util.PlatformSuccessMessages; +import io.mosip.registration.processor.core.logger.LogDescription; +import io.mosip.registration.processor.core.logger.RegProcessorLogger; +import io.mosip.registration.processor.core.packet.dto.AdditionalInfoRequestDto; +import io.mosip.registration.processor.core.spi.restclient.RegistrationProcessorRestClientService; +import io.mosip.registration.processor.core.status.util.StatusUtil; +import io.mosip.registration.processor.core.status.util.TrimExceptionMessage; +import io.mosip.registration.processor.core.util.RegistrationExceptionMapperUtil; +import io.mosip.registration.processor.packet.manager.decryptor.Decryptor; +import io.mosip.registration.processor.packet.manager.utils.ZipUtils; +import io.mosip.registration.processor.packet.storage.dto.ConfigEnum; +import io.mosip.registration.processor.packet.storage.utils.Utilities; +import io.mosip.registration.processor.packet.uploader.exception.PacketNotFoundException; +import io.mosip.registration.processor.packet.uploader.service.PacketUploaderService; +import io.mosip.registration.processor.rest.client.audit.builder.AuditLogRequestBuilder; +import io.mosip.registration.processor.status.code.RegistrationStatusCode; +import io.mosip.registration.processor.status.dto.InternalRegistrationStatusDto; +import io.mosip.registration.processor.status.dto.RegistrationStatusDto; +import io.mosip.registration.processor.status.dto.SyncRegistrationDto; +import io.mosip.registration.processor.status.dto.SyncResponseDto; +import io.mosip.registration.processor.status.entity.SyncRegistrationEntity; +import io.mosip.registration.processor.status.exception.TablenotAccessibleException; +import io.mosip.registration.processor.status.service.AdditionalInfoRequestService; +import io.mosip.registration.processor.status.service.RegistrationStatusService; +import io.mosip.registration.processor.status.service.SyncRegistrationService; + +/** + * The Class PacketUploaderServiceImpl. + * + * @author Rishabh Keshari + */ +@RefreshScope +@Component +public class PacketUploaderServiceImpl implements PacketUploaderService { + + /** + * The reg proc logger. + */ + private static Logger regProcLogger = RegProcessorLogger.getLogger(PacketUploaderServiceImpl.class); + + /** + * The fillesystem manager. + */ + private static final String USER = "MOSIP_SYSTEM"; + private static final String ZIP = ".zip"; + private static final String JSON = ".json"; + private static final String FORWARD_SLASH = "/"; + + @Value("${mosip.regproc.landing.zone.account.name}") + private String landingZoneAccount; + + @Value("${mosip.regproc.landing.zone.type:ObjectStore}") + private String landingZoneType; + + @Value("${packet.manager.account.name}") + private String packetManagerAccount; + + @Value("${packet.manager.iteration.addition.enabled:true}") + private boolean isIterationAdditionEnabled; + + /** + * the packet extension(Ex - .zip) + */ + @Value("${registration.processor.packet.ext}") + private String extention; + + @Value("${mosip.commons.packetnames}") + private String packetNames; + + /** + * The max retry count. + */ + @Value("${registration.processor.max.retry}") + private int maxRetryCount; + + @Autowired + private ObjectStoreAdapter objectStoreAdapter; + + /** + * The sync registration service. + */ + @Autowired + private SyncRegistrationService syncRegistrationService; + + /** + * The registration status service. + */ + @Autowired + private RegistrationStatusService registrationStatusService; + + @Autowired + private AdditionalInfoRequestService additionalInfoRequestService; + + /** + * The core audit request builder. + */ + @Autowired + private AuditLogRequestBuilder auditLogRequestBuilder; + + /** + * The virus scanner service. + */ + @Autowired + private VirusScanner virusScannerService; + + @Autowired + private RegistrationProcessorRestClientService restClient; + + /** + * The registration status mapper util. + */ + @Autowired + private RegistrationExceptionMapperUtil registrationStatusMapperUtil; + + @Autowired + private Decryptor decryptor; + + @Autowired + private ObjectMapper mapper; + + @Autowired + private Utilities utility; + + + /** + * The is transaction successful. + */ + boolean isTransactionSuccessful = false; + + /* + * java class to trim exception message + */ + private TrimExceptionMessage trimExpMessage = new TrimExceptionMessage(); + + /* + * (non-Javadoc) + * + * @see io.mosip.id.issuance.packet.handler.service.PacketUploadService# + * validatePacket( java.lang.Object) + */ + + @Override + public MessageDTO validateAndUploadPacket(MessageDTO messageDTO, String stageName) { + + LogDescription description = new LogDescription(); + InternalRegistrationStatusDto dto = new InternalRegistrationStatusDto(); + messageDTO.setInternalError(Boolean.FALSE); + messageDTO.setIsValid(Boolean.FALSE); + isTransactionSuccessful = false; + String registrationId = messageDTO.getRid(); + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + registrationId, "PacketUploaderServiceImpl::validateAndUploadPacket()::entry"); + SyncRegistrationEntity regEntity = null; + + try { + regEntity = syncRegistrationService.findByWorkflowInstanceId(messageDTO.getWorkflowInstanceId()); + dto = registrationStatusService.getRegistrationStatus( + registrationId, messageDTO.getReg_type(), messageDTO.getIteration(), regEntity.getWorkflowInstanceId()); + + dto.setLatestTransactionTypeCode(RegistrationTransactionTypeCode.UPLOAD_PACKET.toString()); + dto.setRegistrationStageName(stageName); + + final byte[] encryptedByteArray = getPakcetFromDMZ(regEntity.getPacketId(),registrationId); + + if (encryptedByteArray != null) { + + if (validateHashCode(new ByteArrayInputStream(encryptedByteArray), regEntity, registrationId, dto, + description)) { + InputStream decryptedPacket = decryptor.decrypt( + registrationId, + utility.getRefId(registrationId, regEntity.getReferenceId()), + new ByteArrayInputStream(encryptedByteArray)); + final byte[] decryptedPacketBytes = IOUtils.toByteArray(decryptedPacket); + if (scanFile(encryptedByteArray, registrationId, + regEntity.getReferenceId(), ZipUtils.unzipAndGetFiles(new ByteArrayInputStream( + decryptedPacketBytes)), dto, description, messageDTO)) { + int retrycount = (dto.getRetryCount() == null) ? 0 : dto.getRetryCount() + 1; + dto.setRetryCount(retrycount); + if (retrycount < getMaxRetryCount()) { + + messageDTO = uploadPacket(regEntity, dto, ZipUtils.unzipAndGetFiles(new ByteArrayInputStream(decryptedPacketBytes)), messageDTO, description); + if (messageDTO.getIsValid()) { + dto.setLatestTransactionStatusCode( + RegistrationTransactionStatusCode.SUCCESS.toString()); + isTransactionSuccessful = true; + description.setMessage(PlatformSuccessMessages.RPR_PUM_PACKET_UPLOADER.getMessage()); + regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString(), registrationId, + description.getMessage()); + + } + } else { + + messageDTO.setInternalError(Boolean.TRUE); + description.setMessage(PlatformErrorMessages.RPR_PUM_PACKET_RETRY_CNT_FAILURE.getMessage()); + description.setCode(PlatformErrorMessages.RPR_PUM_PACKET_RETRY_CNT_FAILURE.getCode()); + dto.setLatestTransactionStatusCode(registrationStatusMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.PACKET_UPLOAD_FAILED_ON_MAX_RETRY_CNT)); + dto.setStatusCode(RegistrationStatusCode.FAILED.toString()); + dto.setStatusComment(StatusUtil.PACKET_RETRY_CNT_EXCEEDED.getMessage()); + dto.setSubStatusCode(StatusUtil.PACKET_RETRY_CNT_EXCEEDED.getCode()); + dto.setUpdatedBy(USER); + regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString(), registrationId, + description.getMessage()); + } + } + } + } else { + messageDTO.setInternalError(Boolean.TRUE); + + dto.setLatestTransactionStatusCode(registrationStatusMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.PACKET_NOT_FOUND_EXCEPTION)); + dto.setStatusCode(RegistrationStatusCode.FAILED.toString()); + dto.setStatusComment(StatusUtil.PACKET_NOT_FOUND_LANDING_ZONE.getMessage()); + dto.setSubStatusCode(StatusUtil.PACKET_NOT_FOUND_LANDING_ZONE.getCode()); + dto.setUpdatedBy(USER); + description.setMessage(PlatformErrorMessages.RPR_PUM_PACKET_NOT_FOUND_EXCEPTION.getMessage()); + description.setCode(PlatformErrorMessages.RPR_PUM_PACKET_NOT_FOUND_EXCEPTION.getCode()); + + } + + } catch (TablenotAccessibleException e) { + messageDTO.setInternalError(Boolean.TRUE); + dto.setLatestTransactionStatusCode(registrationStatusMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.TABLE_NOT_ACCESSIBLE_EXCEPTION)); + dto.setStatusComment( + trimExpMessage.trimExceptionMessage(StatusUtil.DB_NOT_ACCESSIBLE.getMessage() + e.getMessage())); + dto.setSubStatusCode(StatusUtil.DB_NOT_ACCESSIBLE.getCode()); + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + registrationId, PlatformErrorMessages.RPR_RGS_REGISTRATION_TABLE_NOT_ACCESSIBLE.name() + + ExceptionUtils.getStackTrace(e)); + + description.setMessage(PlatformErrorMessages.RPR_RGS_REGISTRATION_TABLE_NOT_ACCESSIBLE.getMessage()); + description.setCode(PlatformErrorMessages.RPR_RGS_REGISTRATION_TABLE_NOT_ACCESSIBLE.getCode()); + + } catch (PacketNotFoundException ex) { + if (!isPacketAlreadyPresentInObjectStore(messageDTO.getRid(), messageDTO.getReg_type())) { + messageDTO.setInternalError(Boolean.TRUE); + dto.setLatestTransactionStatusCode(registrationStatusMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.PACKET_NOT_FOUND_EXCEPTION)); + dto.setStatusComment(RegistrationExceptionTypeCode.PACKET_NOT_FOUND_EXCEPTION.toString()); + dto.setSubStatusCode(StatusUtil.PACKET_NOT_FOUND_PACKET_STORE.getCode()); + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + registrationId, + PlatformErrorMessages.RPR_PUM_PACKET_NOT_FOUND_EXCEPTION.name() + ExceptionUtils.getStackTrace(ex)); + description.setMessage(PlatformErrorMessages.RPR_PUM_PACKET_NOT_FOUND_EXCEPTION.getMessage()); + description.setCode(PlatformErrorMessages.RPR_PUM_PACKET_NOT_FOUND_EXCEPTION.getCode()); + } else { + regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString(), registrationId, + "Packet is not present in LANDING_ZONE but alrady present in object store. Hence this request will be marked as success."); + messageDTO.setInternalError(false); + messageDTO.setIsValid(true); + isTransactionSuccessful = true; + dto.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); + dto.setStatusComment(StatusUtil.PACKET_ALREADY_UPLOADED.getMessage()); + dto.setSubStatusCode(StatusUtil.PACKET_ALREADY_UPLOADED.getCode()); + dto.setLatestTransactionStatusCode(RegistrationTransactionStatusCode.SUCCESS.toString()); + description.setMessage(PlatformSuccessMessages.RPR_PUM_PACKET_UPLOADER_ALREADY_UPLOADED.getMessage()); + description.setCode(PlatformSuccessMessages.RPR_PUM_PACKET_UPLOADER_ALREADY_UPLOADED.getCode()); + } + + } catch (ApisResourceAccessException e) { + messageDTO.setInternalError(Boolean.TRUE); + dto.setLatestTransactionStatusCode( + registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.NGINX_ACCESS_EXCEPTION)); + dto.setStatusComment(trimExpMessage + .trimExceptionMessage(StatusUtil.NGINX_ACCESS_EXCEPTION.getMessage() + e.getMessage())); + dto.setSubStatusCode(StatusUtil.IO_EXCEPTION.getCode()); + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + registrationId, + PlatformErrorMessages.RPR_PUM_NGINX_ACCESS_FAILED.name() + ExceptionUtils.getStackTrace(e)); + + description.setMessage(PlatformErrorMessages.RPR_PUM_NGINX_ACCESS_FAILED.getMessage()); + description.setCode(PlatformErrorMessages.RPR_PUM_NGINX_ACCESS_FAILED.getCode()); + } catch (IOException | NoSuchAlgorithmException e) { + messageDTO.setInternalError(Boolean.TRUE); + dto.setLatestTransactionStatusCode( + registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.IOEXCEPTION)); + dto.setStatusComment( + trimExpMessage.trimExceptionMessage(StatusUtil.IO_EXCEPTION.getMessage() + e.getMessage())); + dto.setSubStatusCode(StatusUtil.IO_EXCEPTION.getCode()); + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + registrationId, + PlatformErrorMessages.RPR_SYS_IO_EXCEPTION.name() + ExceptionUtils.getStackTrace(e)); + description.setMessage(PlatformErrorMessages.RPR_SYS_IO_EXCEPTION.getMessage()); + description.setCode(PlatformErrorMessages.RPR_SYS_IO_EXCEPTION.getCode()); + + } catch (PacketDecryptionFailureException e) { + messageDTO.setInternalError(Boolean.TRUE); + dto.setStatusCode(RegistrationStatusCode.FAILED.toString()); + dto.setStatusComment(StatusUtil.PACKET_DECRYPTION_FAILED.getMessage()); + dto.setSubStatusCode(StatusUtil.PACKET_DECRYPTION_FAILED.getCode()); + dto.setLatestTransactionStatusCode(registrationStatusMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.PACKET_DECRYPTION_FAILURE_EXCEPTION)); + description.setMessage(PlatformErrorMessages.RPR_PUM_PACKET_DECRYPTION_FAILED.getMessage()); + description.setCode(PlatformErrorMessages.RPR_PUM_PACKET_DECRYPTION_FAILED.getCode()); + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + registrationId, ExceptionUtils.getStackTrace(e)); + + } catch (ObjectStoreNotAccessibleException e) { + messageDTO.setInternalError(Boolean.TRUE); + dto.setStatusCode(RegistrationStatusCode.FAILED.toString()); + dto.setStatusComment(StatusUtil.OBJECT_STORE_EXCEPTION.getMessage()); + dto.setSubStatusCode(StatusUtil.OBJECT_STORE_EXCEPTION.getCode()); + dto.setLatestTransactionStatusCode(registrationStatusMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.OBJECT_STORE_EXCEPTION)); + description.setMessage(PlatformErrorMessages.OBJECT_STORE_NOT_ACCESSIBLE.getMessage()); + description.setCode(PlatformErrorMessages.OBJECT_STORE_NOT_ACCESSIBLE.getCode()); + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + registrationId, PlatformErrorMessages.OBJECT_STORE_NOT_ACCESSIBLE.name() + + ExceptionUtils.getStackTrace(e)); + } catch (Exception e) { + messageDTO.setInternalError(Boolean.TRUE); + dto.setLatestTransactionStatusCode( + registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.EXCEPTION)); + dto.setStatusComment(trimExpMessage + .trimExceptionMessage(StatusUtil.UNKNOWN_EXCEPTION_OCCURED.getMessage() + e.getMessage())); + dto.setSubStatusCode(StatusUtil.UNKNOWN_EXCEPTION_OCCURED.getCode()); + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + registrationId, + PlatformErrorMessages.RPR_PKR_UNKNOWN_EXCEPTION.name() + ExceptionUtils.getStackTrace(e)); + description.setMessage(PlatformErrorMessages.RPR_PKR_UNKNOWN_EXCEPTION.getMessage()); + description.setCode(PlatformErrorMessages.RPR_PKR_UNKNOWN_EXCEPTION.getCode()); + + } finally { + if (messageDTO.getInternalError()) { + updateErrorFlags(dto, messageDTO); + } + /** Module-Id can be Both Success/Error code */ + String moduleId = isTransactionSuccessful ? PlatformSuccessMessages.RPR_PUM_PACKET_UPLOADER.getCode() + : description.getCode(); + String moduleName = ModuleName.PACKET_UPLOAD.toString(); + registrationStatusService.updateRegistrationStatus(dto, moduleId, moduleName); + String eventId = ""; + String eventName = ""; + String eventType = ""; + eventId = isTransactionSuccessful ? EventId.RPR_402.toString() : EventId.RPR_405.toString(); + eventName = eventId.equalsIgnoreCase(EventId.RPR_402.toString()) ? EventName.UPDATE.toString() + : EventName.EXCEPTION.toString(); + eventType = eventId.equalsIgnoreCase(EventId.RPR_402.toString()) ? EventType.BUSINESS.toString() + : EventType.SYSTEM.toString(); + + auditLogRequestBuilder.createAuditRequestBuilder(description.getMessage(), eventId, eventName, eventType, + moduleId, moduleName, registrationId); + + } + + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + registrationId, "PacketUploaderServiceImpl::validateAndUploadPacket()::exit"); + return messageDTO; + } + + /** + * Scan file. + * + * @param input the input stream + * @param refId + * @param description + * @return true, if successful + * @throws IOException + * @throws ApisResourceAccessException + */ + private boolean scanFile(final byte[] input, String id, String refId, final Map sourcePackets, InternalRegistrationStatusDto dto, + LogDescription description, MessageDTO messageDTO) throws ApisResourceAccessException, PacketDecryptionFailureException { + boolean isInputFileClean = false; + try { + InputStream packet = new ByteArrayInputStream(input); + // scanning the top level packet + isInputFileClean = virusScannerService.scanFile(packet); + + if (isInputFileClean) { + // scanning the source packets (Like - id, evidence, optional packets). + for (final Map.Entry source : sourcePackets.entrySet()) { + if (source.getKey().endsWith(ZIP)) { + InputStream decryptedData = decryptor + .decrypt(id, utility.getRefId(id, refId), source.getValue()); + isInputFileClean = virusScannerService.scanFile(decryptedData); + } else + isInputFileClean = virusScannerService.scanFile(source.getValue()); + if (!isInputFileClean) + break; + } + } + if (!isInputFileClean) { + description.setMessage(PlatformErrorMessages.RPR_PUM_PACKET_VIRUS_SCAN_FAILED.getMessage()); + description.setCode(PlatformErrorMessages.RPR_PUM_PACKET_VIRUS_SCAN_FAILED.getCode()); + dto.setStatusCode(RegistrationStatusCode.FAILED.toString()); + dto.setStatusComment(StatusUtil.VIRUS_SCANNER_FAILED_UPLOADER.getMessage()); + dto.setSubStatusCode(StatusUtil.VIRUS_SCANNER_FAILED_UPLOADER.getCode()); + dto.setLatestTransactionStatusCode(registrationStatusMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.VIRUS_SCAN_FAILED_EXCEPTION)); + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString(), id, + PlatformErrorMessages.RPR_PUM_PACKET_VIRUS_SCAN_FAILED.getMessage()); + } + } catch (VirusScannerException e) { + messageDTO.setInternalError(Boolean.TRUE); + description.setMessage(PlatformErrorMessages.RPR_PUM_PACKET_VIRUS_SCANNER_SERVICE_FAILED.getMessage()); + description.setCode(PlatformErrorMessages.RPR_PUM_PACKET_VIRUS_SCANNER_SERVICE_FAILED.getCode()); + dto.setStatusCode(RegistrationStatusCode.FAILED.toString()); + dto.setStatusComment(trimExpMessage.trimExceptionMessage( + StatusUtil.VIRUS_SCANNER_SERVICE_NOT_ACCESSIBLE.getMessage() + " " + e.getMessage())); + dto.setSubStatusCode(StatusUtil.VIRUS_SCANNER_SERVICE_NOT_ACCESSIBLE.getCode()); + dto.setLatestTransactionStatusCode(registrationStatusMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.VIRUS_SCANNER_SERVICE_FAILED)); + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + id, PlatformErrorMessages.RPR_PUM_PACKET_VIRUS_SCANNER_SERVICE_FAILED.getMessage() + + ExceptionUtils.getStackTrace(e)); + + } + return isInputFileClean; + } + + /** + * Validate hash code. + * + * @param registrationId the registration id + * @param inputStream the input stream + * @param registrationId + * @param description + * @throws IOException Signals that an I/O exception has occurred. + */ + private boolean validateHashCode(InputStream inputStream, SyncRegistrationEntity regEntity, String registrationId, + InternalRegistrationStatusDto dto, LogDescription description) throws IOException, NoSuchAlgorithmException { + boolean isValidHash = false; + byte[] isbytearray = IOUtils.toByteArray(inputStream); + String hashSequence = HMACUtils2.digestAsPlainText(isbytearray); + String packetHashSequence = regEntity.getPacketHashValue(); + if (!(MessageDigest.isEqual(packetHashSequence.getBytes(), hashSequence.getBytes()))) { + description.setMessage(PlatformErrorMessages.RPR_PKR_PACKET_HASH_NOT_EQUALS_SYNCED_HASH.getMessage()); + description.setCode(PlatformErrorMessages.RPR_PKR_PACKET_HASH_NOT_EQUALS_SYNCED_HASH.getCode()); + dto.setLatestTransactionStatusCode( + registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.PACKET_HASH_VALIDATION_FAILED)); + dto.setStatusCode(RegistrationStatusCode.FAILED.toString()); + dto.setStatusComment(StatusUtil.PACKET_HASHCODE_VALIDATION_FAILED.getMessage()); + dto.setSubStatusCode(StatusUtil.PACKET_HASHCODE_VALIDATION_FAILED.getCode()); + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + registrationId, PlatformErrorMessages.RPR_PKR_PACKET_HASH_NOT_EQUALS_SYNCED_HASH.getMessage()); + + return isValidHash; + } else { + isValidHash = true; + return isValidHash; + } + } + + /** + * Uploadpacket. + * + * @param dto the dto + * @param sourcePackets source packets + * @param object the object + * @param description + * @return the message DTO + * @throws IOException Signals that an I/O exception has occurred. + * @throws SftpFileOperationException + */ + private MessageDTO uploadPacket(SyncRegistrationEntity regEntity, InternalRegistrationStatusDto dto, final Map sourcePackets, + MessageDTO object, LogDescription description) throws ObjectStoreNotAccessibleException { + + object.setIsValid(false); + String registrationId = dto.getRegistrationId(); + // upload packets + try { + for (Map.Entry entry : sourcePackets.entrySet()) { + if (entry.getKey().endsWith(ZIP)) { + String objStoreKey = isIterationAdditionEnabled ? + getFinalKey(regEntity, entry.getKey().replace(ZIP, ""), object) + : + entry.getKey().replace(ZIP, ""); + boolean result = objectStoreAdapter.putObject(packetManagerAccount, registrationId, + null, null, objStoreKey, entry.getValue()); + if (!result) + throw new ObjectStoreNotAccessibleException("Failed to store packet : " + entry.getKey()); + } + } + + // upload metadata + for (Map.Entry entry : sourcePackets.entrySet()) { + if (entry.getKey().endsWith(JSON)) { + byte[] bytearray = IOUtils.toByteArray(entry.getValue()); + String jsonString = new String(bytearray); + LinkedHashMap currentIdMap = (LinkedHashMap) mapper.readValue(jsonString, LinkedHashMap.class); + String objStoreKey = isIterationAdditionEnabled ? + getFinalKey(regEntity, entry.getKey().replace(JSON, ""), object) + : + entry.getKey().replace(JSON, ""); + objectStoreAdapter.addObjectMetaData(packetManagerAccount, registrationId, + null, null, objStoreKey, currentIdMap); + } + } + } catch (Exception e) { + object.setIsValid(false); + object.setInternalError(true); + throw new ObjectStoreNotAccessibleException(e.getMessage(), e); + } + + + dto.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); + dto.setStatusComment(StatusUtil.PACKET_UPLOADED.getMessage()); + dto.setSubStatusCode(StatusUtil.PACKET_UPLOADED.getCode()); + dto.setUpdatedBy(USER); + object.setInternalError(false); + object.setIsValid(true); + object.setRid(registrationId); + + isTransactionSuccessful = true; + description.setMessage(PlatformErrorMessages.RPR_PUM_PACKET_DELETION_INFO.getMessage()); + description.setCode(PlatformErrorMessages.RPR_PUM_PACKET_DELETION_INFO.getCode()); + + regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString(), registrationId, + PlatformErrorMessages.RPR_PUM_PACKET_DELETION_INFO.getMessage()); + + return object; + } + + /** + * Get max retry count. + * + * @return maxRetryCount + */ + public int getMaxRetryCount() { + return maxRetryCount; + } + + private byte[] getPakcetFromDMZ(String packetId, String registrationId) throws ApisResourceAccessException, ObjectStoreNotAccessibleException, IOException { + List pathSegment = new ArrayList<>(); + pathSegment.add(packetId + extention); + byte[] packet = null; + + try { + if(landingZoneType.equalsIgnoreCase(LandingZoneTypeConstant.DMZ_SERVER)) { + packet = (byte[]) restClient.getApi(ApiName.NGINXDMZURL, pathSegment, "", null, byte[].class); + } + else if(landingZoneType.equalsIgnoreCase(LandingZoneTypeConstant.OBJECT_STORE)) { + packet=IOUtils.toByteArray(objectStoreAdapter.getObject(landingZoneAccount, registrationId, null, null, packetId)); + if(packet==null) { + throw new ObjectStoreNotAccessibleException("Failed to get packet : " +packetId); + } + } + } catch (ApisResourceAccessException e) { + if (e.getCause() instanceof HttpClientErrorException) { + HttpClientErrorException ex = (HttpClientErrorException) e.getCause(); + if (ex.getStatusCode().equals(HttpStatus.NOT_FOUND)) + throw new PacketNotFoundException(PlatformErrorMessages.RPR_PUM_PACKET_NOT_FOUND_EXCEPTION.getMessage(), ex); + } else + throw e; + } catch(ObjectStoreAdapterException e) { + throw e; + } + return packet; + } + + /** + * Modify process name to add iteration before uploading to object store. + * @param regEntity + * @param packetKey + * @return + */ + private String getFinalKey(SyncRegistrationEntity regEntity, String packetKey, MessageDTO messageDTO) { + String[] tempKeys = packetKey.split(FORWARD_SLASH); + // if known format of source/process/objectName only then modify the process + if (tempKeys != null && tempKeys.length == 3) { + String source = tempKeys[0]; + String process = tempKeys[1]; + String objectName = tempKeys[2]; + AdditionalInfoRequestDto additionalInfoRequestDto = additionalInfoRequestService + .getAdditionalInfoRequestByRegIdAndProcessAndIteration(messageDTO.getRid(), + messageDTO.getReg_type(), messageDTO.getIteration()); + + if (additionalInfoRequestDto != null && + additionalInfoRequestDto.getAdditionalInfoReqId().equals(regEntity.getAdditionalInfoReqId())) { + return source + FORWARD_SLASH + process + "-" + messageDTO.getIteration() + FORWARD_SLASH + objectName; + } else + return packetKey; + + } else { + regProcLogger.warn("PacketUploaderServiceImpl::getFinalKey() The packet key is not in source/process/objectName format " + + packetKey + " id : " + messageDTO.getRid()); + return packetKey; + } + } + + private void updateErrorFlags(InternalRegistrationStatusDto registrationStatusDto, MessageDTO object) { + object.setInternalError(true); + if (registrationStatusDto.getLatestTransactionStatusCode() + .equalsIgnoreCase(RegistrationTransactionStatusCode.REPROCESS.toString())) { + object.setIsValid(true); + } else { + object.setIsValid(false); + } + } + + + public boolean isPacketAlreadyPresentInObjectStore(String id, String process) { + + for (String name : packetNames.split(",")) { + boolean isPresent = objectStoreAdapter.exists(packetManagerAccount, id, utility.getDefaultSource(process, ConfigEnum.READER), process, id+ "_" + name); + if (!isPresent) { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + id, name + " : packet not present in object store."); + return false; + } + } + return true; + } + + + } \ No newline at end of file diff --git a/registration-processor/pre-processor/registration-processor-packet-validator-stage/src/main/java/io/mosip/registration/processor/stages/packet/validator/PacketValidateProcessor.java b/registration-processor/pre-processor/registration-processor-packet-validator-stage/src/main/java/io/mosip/registration/processor/stages/packet/validator/PacketValidateProcessor.java index a728c2d415d..c39e65fd68d 100644 --- a/registration-processor/pre-processor/registration-processor-packet-validator-stage/src/main/java/io/mosip/registration/processor/stages/packet/validator/PacketValidateProcessor.java +++ b/registration-processor/pre-processor/registration-processor-packet-validator-stage/src/main/java/io/mosip/registration/processor/stages/packet/validator/PacketValidateProcessor.java @@ -1,618 +1,622 @@ -package io.mosip.registration.processor.stages.packet.validator; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.nio.charset.StandardCharsets; -import java.time.LocalDateTime; -import java.time.format.DateTimeFormatter; -import java.time.format.DateTimeParseException; -import java.util.Arrays; -import java.util.Date; -import java.util.Map; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - -import io.mosip.kernel.core.util.DateUtils; -import io.mosip.registration.processor.packet.storage.utils.Utilities; -import org.apache.commons.io.IOUtils; -import org.apache.commons.lang3.exception.ExceptionUtils; -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.dao.DataAccessException; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; -import org.springframework.web.client.HttpClientErrorException; -import org.springframework.web.client.HttpServerErrorException; - -import com.fasterxml.jackson.databind.ObjectMapper; - -import io.mosip.kernel.core.exception.BaseUncheckedException; -import io.mosip.kernel.core.logger.spi.Logger; -import io.mosip.kernel.core.util.JsonUtils; -import io.mosip.kernel.core.util.StringUtils; -import io.mosip.kernel.core.util.exception.JsonProcessingException; -import io.mosip.registration.processor.core.abstractverticle.MessageBusAddress; -import io.mosip.registration.processor.core.abstractverticle.MessageDTO; -import io.mosip.registration.processor.core.code.ApiName; -import io.mosip.registration.processor.core.code.EventId; -import io.mosip.registration.processor.core.code.EventName; -import io.mosip.registration.processor.core.code.EventType; -import io.mosip.registration.processor.core.code.ModuleName; -import io.mosip.registration.processor.core.code.RegistrationExceptionTypeCode; -import io.mosip.registration.processor.core.code.RegistrationTransactionStatusCode; -import io.mosip.registration.processor.core.code.RegistrationTransactionTypeCode; -import io.mosip.registration.processor.core.constant.JsonConstant; -import io.mosip.registration.processor.core.constant.LoggerFileConstant; -import io.mosip.registration.processor.core.constant.ProviderStageName; -import io.mosip.registration.processor.core.exception.ApisResourceAccessException; -import io.mosip.registration.processor.core.exception.PacketManagerException; -import io.mosip.registration.processor.core.exception.RegistrationProcessorCheckedException; -import io.mosip.registration.processor.core.exception.util.PlatformErrorMessages; -import io.mosip.registration.processor.core.exception.util.PlatformSuccessMessages; -import io.mosip.registration.processor.core.logger.LogDescription; -import io.mosip.registration.processor.core.logger.RegProcessorLogger; -import io.mosip.registration.processor.core.packet.dto.FieldValue; -import io.mosip.registration.processor.core.packet.dto.packetvalidator.MainRequestDTO; -import io.mosip.registration.processor.core.packet.dto.packetvalidator.MainResponseDTO; -import io.mosip.registration.processor.core.packet.dto.packetvalidator.PacketValidationDto; -import io.mosip.registration.processor.core.packet.dto.packetvalidator.ReverseDataSyncRequestDTO; -import io.mosip.registration.processor.core.packet.dto.packetvalidator.ReverseDatasyncReponseDTO; -import io.mosip.registration.processor.core.spi.packet.validator.PacketValidator; -import io.mosip.registration.processor.core.spi.restclient.RegistrationProcessorRestClientService; -import io.mosip.registration.processor.core.status.util.StatusUtil; -import io.mosip.registration.processor.core.status.util.TrimExceptionMessage; -import io.mosip.registration.processor.core.util.JsonUtil; -import io.mosip.registration.processor.core.util.RegistrationExceptionMapperUtil; -import io.mosip.registration.processor.packet.manager.decryptor.Decryptor; -import io.mosip.registration.processor.packet.storage.exception.IdentityNotFoundException; -import io.mosip.registration.processor.packet.storage.exception.ParsingException; -import io.mosip.registration.processor.packet.storage.utils.PriorityBasedPacketManagerService; -import io.mosip.registration.processor.rest.client.audit.builder.AuditLogRequestBuilder; -import io.mosip.registration.processor.stages.utils.AuditUtility; -import io.mosip.registration.processor.stages.utils.NotificationUtility; -import io.mosip.registration.processor.status.code.RegistrationStatusCode; -import io.mosip.registration.processor.status.dto.InternalRegistrationStatusDto; -import io.mosip.registration.processor.status.dto.RegistrationAdditionalInfoDTO; -import io.mosip.registration.processor.status.dto.RegistrationStatusDto; -import io.mosip.registration.processor.status.dto.SyncRegistrationDto; -import io.mosip.registration.processor.status.dto.SyncResponseDto; -import io.mosip.registration.processor.status.entity.SyncRegistrationEntity; -import io.mosip.registration.processor.status.exception.TablenotAccessibleException; -import io.mosip.registration.processor.status.service.RegistrationStatusService; -import io.mosip.registration.processor.status.service.SyncRegistrationService; - -@Service -@Transactional -public class PacketValidateProcessor { - - /** - * The Constant FILE_SEPARATOR. - */ - public static final String FILE_SEPARATOR = "\\"; - - /** - * The reg proc logger. - */ - private static Logger regProcLogger = RegProcessorLogger.getLogger(PacketValidateProcessor.class); - - @Autowired - private PacketValidator compositePacketValidator; - - @Autowired - private PriorityBasedPacketManagerService packetManagerService; - - @Autowired - private Utilities utility; - - @Autowired - private ObjectMapper objectMapper; - - /** - * The Constant USER. - */ - private static final String USER = "MOSIP_SYSTEM"; - - /** - * The Constant APPLICANT_TYPE. - */ - public static final String APPLICANT_TYPE = "applicantType"; - - /** - * The Constant APPROVED. - */ - public static final String APPROVED = "APPROVED"; - - /** - * The Constant REJECTED. - */ - public static final String REJECTED = "REJECTED"; - - /** - * The registration status service. - */ - @Autowired - RegistrationStatusService registrationStatusService; - - /** - * The core audit request builder. - */ - @Autowired - AuditLogRequestBuilder auditLogRequestBuilder; - - @Autowired - private RegistrationProcessorRestClientService restClientService; - - @Autowired - private AuditUtility auditUtility; - - /** - * The sync registration service. - */ - @Autowired - private SyncRegistrationService syncRegistrationService; - - private static final String PRE_REG_ID = "mosip.pre-registration.datasync.store"; - private static final String VERSION = "1.0"; - - String registrationId = null; - - @Autowired - RegistrationExceptionMapperUtil registrationStatusMapperUtil; - - @Value("${mosip.notificationtype}") - private String notificationTypes; - - @Autowired - private Decryptor decryptor; - - @Autowired - private NotificationUtility notificationUtility; - - @Value("${mosip.registration.processor.datetime.pattern}") - private String dateformat; - - public MessageDTO process(MessageDTO object, String stageName) { - TrimExceptionMessage trimMessage = new TrimExceptionMessage(); - LogDescription description = new LogDescription(); - PacketValidationDto packetValidationDto = new PacketValidationDto(); - InternalRegistrationStatusDto registrationStatusDto = new InternalRegistrationStatusDto(); - try { - registrationStatusDto - .setLatestTransactionTypeCode(RegistrationTransactionTypeCode.PRINT_SERVICE.toString()); - registrationStatusDto.setRegistrationStageName(stageName); - object.setMessageBusAddress(MessageBusAddress.PACKET_VALIDATOR_BUS_IN); - object.setIsValid(Boolean.FALSE); - object.setInternalError(Boolean.TRUE); - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - "", "PacketValidateProcessor::process()::entry"); - registrationId = object.getRid(); - packetValidationDto.setTransactionSuccessful(false); - registrationStatusDto = registrationStatusService.getRegistrationStatus( - registrationId, object.getReg_type(), object.getIteration(), object.getWorkflowInstanceId()); - setPacketCreatedDateTime(registrationStatusDto); - registrationStatusDto - .setLatestTransactionTypeCode(RegistrationTransactionTypeCode.VALIDATE_PACKET.toString()); - registrationStatusDto.setRegistrationStageName(stageName); - boolean isValidSupervisorStatus = isValidSupervisorStatus(object); - if (isValidSupervisorStatus) { - Boolean isValid = compositePacketValidator.validate(object.getRid(), - registrationStatusDto.getRegistrationType(), packetValidationDto); - if (isValid) { - // save audit details - InternalRegistrationStatusDto finalRegistrationStatusDto = registrationStatusDto; - Runnable r = () -> { - try { - auditUtility.saveAuditDetails(registrationId, - finalRegistrationStatusDto.getRegistrationType()); - } catch (Exception e) { - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), - LoggerFileConstant.REGISTRATIONID.toString(), - description.getCode() + " Inside Runnable ", ""); - - } - }; - ExecutorService es = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()); - es.submit(r); - es.shutdown(); - registrationStatusDto - .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.SUCCESS.toString()); - object.setIsValid(Boolean.TRUE); - registrationStatusDto - .setStatusComment(StatusUtil.PACKET_STRUCTURAL_VALIDATION_SUCCESS.getMessage()); - registrationStatusDto.setSubStatusCode(StatusUtil.PACKET_STRUCTURAL_VALIDATION_SUCCESS.getCode()); - registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); - // ReverseDataSync - reverseDataSync(registrationId, registrationStatusDto.getRegistrationType(), description, - packetValidationDto); - - packetValidationDto.setTransactionSuccessful(true); - description.setMessage( - PlatformSuccessMessages.RPR_PKR_PACKET_VALIDATE.getMessage() + " -- " + registrationId); - description.setCode(PlatformSuccessMessages.RPR_PKR_PACKET_VALIDATE.getCode()); - - regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), - LoggerFileConstant.REGISTRATIONID.toString(), registrationId, - description.getCode() + description.getMessage()); - - } else { - registrationStatusDto.setLatestTransactionStatusCode(registrationStatusMapperUtil - .getStatusCode(RegistrationExceptionTypeCode.PACKET_STRUCTURAL_VALIDATION_FAILED)); - int retryCount = registrationStatusDto.getRetryCount() != null - ? registrationStatusDto.getRetryCount() + 1 - : 1; - description.setMessage(packetValidationDto.getPacketValidatonStatusCode() + " : " - + packetValidationDto.getPacketValidaionFailureMessage()); - packetValidationDto.setTransactionSuccessful(false); - registrationStatusDto.setRetryCount(retryCount); - registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.toString()); - registrationStatusDto.setStatusComment(packetValidationDto.getPacketValidaionFailureMessage()); - registrationStatusDto.setSubStatusCode(packetValidationDto.getPacketValidatonStatusCode()); - - description.setMessage(PlatformErrorMessages.STRUCTURAL_VALIDATION_FAILED.getMessage()); - description.setCode(PlatformErrorMessages.STRUCTURAL_VALIDATION_FAILED.getCode()); - - regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), - LoggerFileConstant.REGISTRATIONID.toString(), - description.getCode() + " -- " + registrationId, description.getMessage()); - - } - } else { - registrationStatusDto.setLatestTransactionStatusCode( - registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.PACKET_REJECTED)); - int retryCount = registrationStatusDto.getRetryCount() != null - ? registrationStatusDto.getRetryCount() + 1 - : 1; - packetValidationDto.setTransactionSuccessful(false); - registrationStatusDto.setRetryCount(retryCount); - registrationStatusDto.setStatusCode(RegistrationStatusCode.REJECTED.toString()); - registrationStatusDto.setStatusComment(StatusUtil.PACKET_REJECTED.getMessage()); - registrationStatusDto.setSubStatusCode(StatusUtil.PACKET_REJECTED.getCode()); - - description.setMessage(PlatformErrorMessages.RPR_PVM_PACKET_REJECTED.getMessage()); - description.setCode(PlatformErrorMessages.RPR_PVM_PACKET_REJECTED.getCode()); - - regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), - LoggerFileConstant.REGISTRATIONID.toString(), description.getCode() + " -- " + registrationId, - description.getMessage()); - } - object.setInternalError(Boolean.FALSE); - registrationStatusDto.setUpdatedBy(USER); - SyncRegistrationEntity regEntity = syncRegistrationService.findByWorkflowInstanceId(object.getWorkflowInstanceId()); - sendNotification(regEntity, registrationStatusDto, packetValidationDto.isTransactionSuccessful(),isValidSupervisorStatus); - } catch (PacketManagerException e) { - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - registrationId, - RegistrationStatusCode.FAILED.toString() + e.getMessage() + ExceptionUtils.getStackTrace(e)); - registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.name()); - registrationStatusDto.setStatusComment(trimMessage - .trimExceptionMessage(StatusUtil.PACKET_MANAGER_EXCEPTION.getMessage() + e.getMessage())); - registrationStatusDto.setSubStatusCode(StatusUtil.PACKET_MANAGER_EXCEPTION.getCode()); - registrationStatusDto.setLatestTransactionStatusCode( - registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.PACKET_MANAGER_EXCEPTION)); - description.setMessage(PlatformErrorMessages.PACKET_MANAGER_EXCEPTION.getMessage()); - description.setCode(PlatformErrorMessages.PACKET_MANAGER_EXCEPTION.getCode()); - registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.name()); - } catch (DataAccessException e) { - registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); - registrationStatusDto.setStatusComment( - trimMessage.trimExceptionMessage(StatusUtil.DB_NOT_ACCESSIBLE.getMessage() + e.getMessage())); - registrationStatusDto.setSubStatusCode(StatusUtil.DB_NOT_ACCESSIBLE.getCode()); - registrationStatusDto.setLatestTransactionStatusCode( - registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.DATA_ACCESS_EXCEPTION)); - packetValidationDto.setTransactionSuccessful(false); - description.setMessage(PlatformErrorMessages.RPR_RGS_REGISTRATION_TABLE_NOT_ACCESSIBLE.getMessage()); - description.setCode(PlatformErrorMessages.RPR_RGS_REGISTRATION_TABLE_NOT_ACCESSIBLE.getCode()); - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - description.getCode() + " -- " + registrationId, - PlatformErrorMessages.RPR_RGS_REGISTRATION_TABLE_NOT_ACCESSIBLE.getMessage() + e.getMessage() - + ExceptionUtils.getStackTrace(e)); - } catch (IdentityNotFoundException | IOException exc) { - registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.toString()); - registrationStatusDto.setStatusComment( - trimMessage.trimExceptionMessage(StatusUtil.IO_EXCEPTION.getMessage() + exc.getMessage())); - registrationStatusDto.setSubStatusCode(StatusUtil.IO_EXCEPTION.getCode()); - registrationStatusDto.setLatestTransactionStatusCode( - registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.IOEXCEPTION)); - packetValidationDto.setTransactionSuccessful(false); - description.setMessage(PlatformErrorMessages.RPR_SYS_IO_EXCEPTION.getMessage()); - description.setCode(PlatformErrorMessages.STRUCTURAL_VALIDATION_FAILED.getCode()); - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - description.getCode() + " -- " + registrationId, - PlatformErrorMessages.STRUCTURAL_VALIDATION_FAILED.getMessage() + exc.getMessage() - + ExceptionUtils.getStackTrace(exc)); - } catch (ParsingException exc) { - registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.toString()); - registrationStatusDto.setStatusComment(trimMessage - .trimExceptionMessage(StatusUtil.JSON_PARSING_EXCEPTION.getMessage() + exc.getMessage())); - registrationStatusDto.setSubStatusCode(StatusUtil.JSON_PARSING_EXCEPTION.getCode()); - registrationStatusDto.setLatestTransactionStatusCode( - registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.PARSE_EXCEPTION)); - packetValidationDto.setTransactionSuccessful(false); - description.setMessage(PlatformErrorMessages.RPR_SYS_JSON_PARSING_EXCEPTION.getMessage()); - description.setCode(PlatformErrorMessages.STRUCTURAL_VALIDATION_FAILED.getCode()); - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - description.getCode() + " -- " + registrationId, - PlatformErrorMessages.STRUCTURAL_VALIDATION_FAILED.getMessage() + exc.getMessage() - + ExceptionUtils.getStackTrace(exc)); - } catch (TablenotAccessibleException e) { - registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); - registrationStatusDto.setStatusComment( - trimMessage.trimExceptionMessage(StatusUtil.DB_NOT_ACCESSIBLE.getMessage() + e.getMessage())); - registrationStatusDto.setSubStatusCode(StatusUtil.DB_NOT_ACCESSIBLE.getCode()); - registrationStatusDto.setLatestTransactionStatusCode(registrationStatusMapperUtil - .getStatusCode(RegistrationExceptionTypeCode.TABLE_NOT_ACCESSIBLE_EXCEPTION)); - description.setMessage(PlatformErrorMessages.RPR_RGS_REGISTRATION_TABLE_NOT_ACCESSIBLE.getMessage()); - description.setCode(PlatformErrorMessages.RPR_RGS_REGISTRATION_TABLE_NOT_ACCESSIBLE.getCode()); - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), - description.getCode() + " -- " + registrationId, - PlatformErrorMessages.RPR_RGS_REGISTRATION_TABLE_NOT_ACCESSIBLE.getMessage(), - ExceptionUtils.getStackTrace(e)); - - } catch (ApisResourceAccessException e) { - if (e.getCause() instanceof HttpClientErrorException) { - HttpClientErrorException httpClientException = (HttpClientErrorException) e.getCause(); - regProcLogger.info(LoggerFileConstant.REGISTRATIONID.toString(), registrationId, - PlatformErrorMessages.REVERSE_DATA_SYNC_FAILED.getMessage(), - httpClientException.getResponseBodyAsString() + ExceptionUtils.getStackTrace(e)); - } else if (e.getCause() instanceof HttpServerErrorException) { - HttpServerErrorException httpServerException = (HttpServerErrorException) e.getCause(); - regProcLogger.info(LoggerFileConstant.REGISTRATIONID.toString(), registrationId, - PlatformErrorMessages.REVERSE_DATA_SYNC_FAILED.getMessage(), - httpServerException.getResponseBodyAsString() + ExceptionUtils.getStackTrace(e)); - } else { - regProcLogger.info(LoggerFileConstant.REGISTRATIONID.toString(), registrationId, - PlatformErrorMessages.REVERSE_DATA_SYNC_FAILED.getMessage(), e.getMessage()); - } - registrationStatusDto.setStatusCode(RegistrationStatusCode.REPROCESS.toString()); - registrationStatusDto.setLatestTransactionStatusCode( - registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.APIS_RESOURCE_ACCESS_EXCEPTION)); - registrationStatusDto.setStatusComment(trimMessage - .trimExceptionMessage(StatusUtil.API_RESOUCE_ACCESS_FAILED.getMessage() + e.getMessage())); - registrationStatusDto.setSubStatusCode(StatusUtil.API_RESOUCE_ACCESS_FAILED.getCode()); - packetValidationDto.setTransactionSuccessful(false); - - description.setMessage(PlatformErrorMessages.REVERSE_DATA_SYNC_FAILED.getMessage()); - description.setCode(PlatformErrorMessages.REVERSE_DATA_SYNC_FAILED.getCode()); - } catch (RegistrationProcessorCheckedException e) { - registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.toString()); - registrationStatusDto.setStatusComment( - trimMessage.trimExceptionMessage(StatusUtil.BASE_CHECKED_EXCEPTION.getMessage() + e.getMessage())); - registrationStatusDto.setSubStatusCode(StatusUtil.BASE_CHECKED_EXCEPTION.getCode()); - registrationStatusDto.setLatestTransactionStatusCode( - registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.BASE_CHECKED_EXCEPTION)); - packetValidationDto.setTransactionSuccessful(false); - description.setMessage(PlatformErrorMessages.RPR_PVM_BASE_CHECKED_EXCEPTION.getMessage()); - description.setCode(PlatformErrorMessages.RPR_PVM_BASE_CHECKED_EXCEPTION.getCode()); - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - description.getCode() + " -- " + registrationId, - PlatformErrorMessages.RPR_PVM_BASE_CHECKED_EXCEPTION.getMessage() + e.getMessage() - + ExceptionUtils.getStackTrace(e)); - } catch (BaseUncheckedException e) { - registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.toString()); - registrationStatusDto.setStatusComment(trimMessage - .trimExceptionMessage(StatusUtil.BASE_UNCHECKED_EXCEPTION.getMessage() + e.getMessage())); - registrationStatusDto.setSubStatusCode(StatusUtil.BASE_UNCHECKED_EXCEPTION.getCode()); - registrationStatusDto.setLatestTransactionStatusCode( - registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.BASE_UNCHECKED_EXCEPTION)); - packetValidationDto.setTransactionSuccessful(false); - description.setMessage(PlatformErrorMessages.RPR_PVM_BASE_UNCHECKED_EXCEPTION.getMessage()); - description.setCode(PlatformErrorMessages.RPR_PVM_BASE_UNCHECKED_EXCEPTION.getCode()); - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - description.getCode() + " -- " + registrationId, - PlatformErrorMessages.RPR_PVM_BASE_UNCHECKED_EXCEPTION.getMessage() + e.getMessage() - + ExceptionUtils.getStackTrace(e)); - } catch (Exception ex) { - registrationStatusDto.setStatusComment(trimMessage - .trimExceptionMessage(StatusUtil.UNKNOWN_EXCEPTION_OCCURED.getMessage() + ex.getMessage())); - registrationStatusDto.setSubStatusCode(StatusUtil.UNKNOWN_EXCEPTION_OCCURED.getCode()); - registrationStatusDto.setLatestTransactionStatusCode( - registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.EXCEPTION)); - packetValidationDto.setTransactionSuccessful(false); - description.setMessage(PlatformErrorMessages.STRUCTURAL_VALIDATION_FAILED.getMessage()); - description.setCode(PlatformErrorMessages.STRUCTURAL_VALIDATION_FAILED.getCode()); - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - description.getCode() + " -- " + registrationId, - PlatformErrorMessages.STRUCTURAL_VALIDATION_FAILED.getMessage() + ex.getMessage() - + ExceptionUtils.getStackTrace(ex)); - } finally { - - if (object.getInternalError()) { - registrationStatusDto.setUpdatedBy(USER); - int retryCount = registrationStatusDto.getRetryCount() != null - ? registrationStatusDto.getRetryCount() + 1 - : 1; - registrationStatusDto.setRetryCount(retryCount); - updateErrorFlags(registrationStatusDto, object); - } - object.setRid(registrationStatusDto.getRegistrationId()); - /** Module-Id can be Both Success/Error code */ - String moduleId = packetValidationDto.isTransactionSuccessful() - ? PlatformSuccessMessages.RPR_PKR_PACKET_VALIDATE.getCode() - : description.getCode(); - String moduleName = ModuleName.PACKET_VALIDATOR.toString(); - registrationStatusService.updateRegistrationStatus(registrationStatusDto, moduleId, moduleName); - if (packetValidationDto.isTransactionSuccessful()) - description.setMessage(PlatformSuccessMessages.RPR_PKR_PACKET_VALIDATE.getMessage()); - String eventId = packetValidationDto.isTransactionSuccessful() ? EventId.RPR_402.toString() - : EventId.RPR_405.toString(); - String eventName = packetValidationDto.isTransactionSuccessful() ? EventName.UPDATE.toString() - : EventName.EXCEPTION.toString(); - String eventType = packetValidationDto.isTransactionSuccessful() ? EventType.BUSINESS.toString() - : EventType.SYSTEM.toString(); - - auditLogRequestBuilder.createAuditRequestBuilder(description.getMessage(), eventId, eventName, eventType, - moduleId, moduleName, registrationId); - } - - return object; - - } - - - private void setPacketCreatedDateTime(InternalRegistrationStatusDto registrationStatusDto) throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { - try { - Map metaInfo = packetManagerService.getMetaInfo( - registrationStatusDto.getRegistrationId(), registrationStatusDto.getRegistrationType(), ProviderStageName.PACKET_VALIDATOR); - DateTimeFormatter formatter = DateTimeFormatter.ofPattern(dateformat); - String packetCreatedDateTime = metaInfo.get(JsonConstant.CREATIONDATE); - if (packetCreatedDateTime != null && !packetCreatedDateTime.isEmpty()) { - LocalDateTime dateTime = DateUtils.parseToLocalDateTime(packetCreatedDateTime); - registrationStatusDto.setPacketCreateDateTime(dateTime); - } else { - regProcLogger.warn(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - " -- " + registrationStatusDto.getRefId(), - PlatformErrorMessages.RPR_PVM_PACKET_CREATED_DATE_TIME_EMPTY_OR_NULL.getMessage()); - } - } catch (DateTimeParseException e) { - regProcLogger.warn(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - " -- " + registrationStatusDto.getRefId(), - PlatformErrorMessages.RPR_PVM_PACKET_CREATED_DATE_TIME_PARSE_EXCEPTION.getMessage() + e.getMessage()); - }catch (IllegalArgumentException ex) - { - regProcLogger.warn(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - " -- " + registrationStatusDto.getRefId(), - PlatformErrorMessages.RPR_PVM_INVALID_ARGUMENT_EXCEPTION.getMessage() + ex.getMessage()); - } - } - - private boolean isValidSupervisorStatus(MessageDTO messageDTO) { - SyncRegistrationEntity regEntity = syncRegistrationService.findByWorkflowInstanceId(messageDTO.getWorkflowInstanceId()); - if (regEntity.getSupervisorStatus().equalsIgnoreCase(APPROVED)) { - return true; - - } else if (regEntity.getSupervisorStatus().equalsIgnoreCase(REJECTED)) { - return false; - } - return false; - } - - @SuppressWarnings("unchecked") - private void reverseDataSync(String id, String process, LogDescription description, - PacketValidationDto packetValidationDto) throws IOException, ApisResourceAccessException, - PacketManagerException, JsonProcessingException, JSONException { - - Map metaInfoMap = packetManagerService.getMetaInfo(id, process, - ProviderStageName.PACKET_VALIDATOR); - String metadata = metaInfoMap.get(JsonConstant.METADATA); - if (StringUtils.isNotEmpty(metadata)) { - JSONArray jsonArray = new JSONArray(metadata); - - String preRegId = null; - for (int i = 0; i < jsonArray.length(); i++) { - if (!jsonArray.isNull(i)) { - JSONObject jsonObject = (JSONObject) jsonArray.get(i); - FieldValue fieldValue = objectMapper.readValue(jsonObject.toString(), FieldValue.class); - if (fieldValue.getLabel().equalsIgnoreCase(JsonConstant.PREREGISTRATIONID)) { - preRegId = fieldValue.getValue(); - break; - } - - } - } - if (preRegId == null || preRegId.trim().isEmpty()) { - regProcLogger.info(LoggerFileConstant.REGISTRATIONID.toString(), registrationId, - "Pre-registration id not present.", - "Reverse datasync is not applicable for the registration id"); - return; - } - if (registrationId != null) { - packetValidationDto.setTransactionSuccessful(false); - MainResponseDTO mainResponseDto = null; - if (preRegId != null && !preRegId.trim().isEmpty()) { - MainRequestDTO mainRequestDto = new MainRequestDTO<>(); - mainRequestDto.setId(PRE_REG_ID); - mainRequestDto.setVersion(VERSION); - mainRequestDto.setRequesttime(new Date()); - ReverseDataSyncRequestDTO reverseDataSyncRequestDto = new ReverseDataSyncRequestDTO(); - reverseDataSyncRequestDto.setPreRegistrationIds(Arrays.asList(preRegId)); - mainRequestDto.setRequest(reverseDataSyncRequestDto); - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), - LoggerFileConstant.REGISTRATIONID.toString(), registrationId, - "PacketValidateProcessor::reverseDataSync()::ReverseDataSync Api call started with request data :" - + JsonUtil.objectMapperObjectToJson(mainRequestDto)); - mainResponseDto = (MainResponseDTO) restClientService.postApi(ApiName.REVERSEDATASYNC, "", "", - mainRequestDto, MainResponseDTO.class); - - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), - LoggerFileConstant.REGISTRATIONID.toString(), registrationId, - "\"PacketValidateProcessor::reverseDataSync()::ReverseDataSync Api call ended with response data : " - + JsonUtil.objectMapperObjectToJson(mainResponseDto)); - packetValidationDto.setTransactionSuccessful(true); - - } - if (mainResponseDto != null && mainResponseDto.getErrors() != null - && mainResponseDto.getErrors().size() > 0) { - regProcLogger.error(LoggerFileConstant.REGISTRATIONID.toString(), registrationId, - PlatformErrorMessages.REVERSE_DATA_SYNC_FAILED.getMessage(), - mainResponseDto.getErrors().toString()); - packetValidationDto.setTransactionSuccessful(false); - description.setMessage(PlatformErrorMessages.REVERSE_DATA_SYNC_FAILED.getMessage()); - - } else if (mainResponseDto == null) { - packetValidationDto.setTransactionSuccessful(false); - description.setMessage(PlatformErrorMessages.REVERSE_DATA_SYNC_FAILED.getMessage() - + " null response from rest client "); - } else { - packetValidationDto.setTransactionSuccessful(true); - regProcLogger.info(LoggerFileConstant.REGISTRATIONID.toString(), registrationId, - PlatformSuccessMessages.REVERSE_DATA_SYNC_SUCCESS.getMessage(), ""); - } - - } - } - - } - - private void updateErrorFlags(InternalRegistrationStatusDto registrationStatusDto, MessageDTO object) { - object.setInternalError(true); - if (registrationStatusDto.getLatestTransactionStatusCode() - .equalsIgnoreCase(RegistrationTransactionStatusCode.REPROCESS.toString())) { - object.setIsValid(true); - } else { - object.setIsValid(false); - } - } - - private void sendNotification(SyncRegistrationEntity regEntity, - InternalRegistrationStatusDto registrationStatusDto, boolean isTransactionSuccessful,boolean isValidSupervisorStatus) { - try { - if (regEntity.getOptionalValues() != null) { - String[] allNotificationTypes = notificationTypes.split("\\|"); - boolean isProcessingSuccess; - InputStream inputStream = new ByteArrayInputStream(regEntity.getOptionalValues()); - InputStream decryptedInputStream = decryptor.decrypt( - registrationId, - utility.getRefId(registrationId, regEntity.getReferenceId()), - inputStream); - String decryptedData = IOUtils.toString(decryptedInputStream, StandardCharsets.UTF_8); - RegistrationAdditionalInfoDTO registrationAdditionalInfoDTO = (RegistrationAdditionalInfoDTO) JsonUtils - .jsonStringToJavaObject(RegistrationAdditionalInfoDTO.class, decryptedData); - if (isTransactionSuccessful) { - isProcessingSuccess = true; - notificationUtility.sendNotification(registrationAdditionalInfoDTO, registrationStatusDto, - regEntity, allNotificationTypes, isProcessingSuccess,isValidSupervisorStatus); - } else { - isProcessingSuccess = false; - notificationUtility.sendNotification(registrationAdditionalInfoDTO, registrationStatusDto, - regEntity, allNotificationTypes, isProcessingSuccess,isValidSupervisorStatus); - } - boolean isDeleted = syncRegistrationService.deleteAdditionalInfo(regEntity); - if (isDeleted) { - regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), - LoggerFileConstant.REGISTRATIONID.toString(), registrationId, - PlatformSuccessMessages.RPR_PKR_ADDITIONAL_INFO_DELETED.getCode() + - PlatformSuccessMessages.RPR_PKR_ADDITIONAL_INFO_DELETED.getMessage()); - } - } - } catch (Exception e) { - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), - LoggerFileConstant.REGISTRATIONID.toString(), - "Send notification failed for rid - " + registrationStatusDto.getRegistrationId(), ExceptionUtils.getStackTrace(e)); - } - } - -} +package io.mosip.registration.processor.stages.packet.validator; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; +import java.util.Arrays; +import java.util.Date; +import java.util.Map; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +import io.mosip.kernel.core.util.DateUtils; +import io.mosip.registration.processor.packet.storage.utils.Utilities; +import org.apache.commons.io.IOUtils; +import org.apache.commons.lang3.exception.ExceptionUtils; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.dao.DataAccessException; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.web.client.HttpServerErrorException; + +import com.fasterxml.jackson.databind.ObjectMapper; + +import io.mosip.kernel.core.exception.BaseUncheckedException; +import io.mosip.kernel.core.logger.spi.Logger; +import io.mosip.kernel.core.util.JsonUtils; +import io.mosip.kernel.core.util.StringUtils; +import io.mosip.kernel.core.util.exception.JsonProcessingException; +import io.mosip.registration.processor.core.abstractverticle.MessageBusAddress; +import io.mosip.registration.processor.core.abstractverticle.MessageDTO; +import io.mosip.registration.processor.core.code.ApiName; +import io.mosip.registration.processor.core.code.EventId; +import io.mosip.registration.processor.core.code.EventName; +import io.mosip.registration.processor.core.code.EventType; +import io.mosip.registration.processor.core.code.ModuleName; +import io.mosip.registration.processor.core.code.RegistrationExceptionTypeCode; +import io.mosip.registration.processor.core.code.RegistrationTransactionStatusCode; +import io.mosip.registration.processor.core.code.RegistrationTransactionTypeCode; +import io.mosip.registration.processor.core.constant.JsonConstant; +import io.mosip.registration.processor.core.constant.LoggerFileConstant; +import io.mosip.registration.processor.core.constant.ProviderStageName; +import io.mosip.registration.processor.core.exception.ApisResourceAccessException; +import io.mosip.registration.processor.core.exception.PacketManagerException; +import io.mosip.registration.processor.core.exception.RegistrationProcessorCheckedException; +import io.mosip.registration.processor.core.exception.util.PlatformErrorMessages; +import io.mosip.registration.processor.core.exception.util.PlatformSuccessMessages; +import io.mosip.registration.processor.core.logger.LogDescription; +import io.mosip.registration.processor.core.logger.RegProcessorLogger; +import io.mosip.registration.processor.core.packet.dto.FieldValue; +import io.mosip.registration.processor.core.packet.dto.packetvalidator.MainRequestDTO; +import io.mosip.registration.processor.core.packet.dto.packetvalidator.MainResponseDTO; +import io.mosip.registration.processor.core.packet.dto.packetvalidator.PacketValidationDto; +import io.mosip.registration.processor.core.packet.dto.packetvalidator.ReverseDataSyncRequestDTO; +import io.mosip.registration.processor.core.packet.dto.packetvalidator.ReverseDatasyncReponseDTO; +import io.mosip.registration.processor.core.spi.packet.validator.PacketValidator; +import io.mosip.registration.processor.core.spi.restclient.RegistrationProcessorRestClientService; +import io.mosip.registration.processor.core.status.util.StatusUtil; +import io.mosip.registration.processor.core.status.util.TrimExceptionMessage; +import io.mosip.registration.processor.core.util.JsonUtil; +import io.mosip.registration.processor.core.util.RegistrationExceptionMapperUtil; +import io.mosip.registration.processor.packet.manager.decryptor.Decryptor; +import io.mosip.registration.processor.packet.storage.exception.IdentityNotFoundException; +import io.mosip.registration.processor.packet.storage.exception.ParsingException; +import io.mosip.registration.processor.packet.storage.utils.PriorityBasedPacketManagerService; +import io.mosip.registration.processor.rest.client.audit.builder.AuditLogRequestBuilder; +import io.mosip.registration.processor.stages.utils.AuditUtility; +import io.mosip.registration.processor.stages.utils.NotificationUtility; +import io.mosip.registration.processor.status.code.RegistrationStatusCode; +import io.mosip.registration.processor.status.dto.InternalRegistrationStatusDto; +import io.mosip.registration.processor.status.dto.RegistrationAdditionalInfoDTO; +import io.mosip.registration.processor.status.dto.RegistrationStatusDto; +import io.mosip.registration.processor.status.dto.SyncRegistrationDto; +import io.mosip.registration.processor.status.dto.SyncResponseDto; +import io.mosip.registration.processor.status.entity.SyncRegistrationEntity; +import io.mosip.registration.processor.status.exception.TablenotAccessibleException; +import io.mosip.registration.processor.status.service.RegistrationStatusService; +import io.mosip.registration.processor.status.service.SyncRegistrationService; + +@Service +@Transactional +public class PacketValidateProcessor { + + /** + * The Constant FILE_SEPARATOR. + */ + public static final String FILE_SEPARATOR = "\\"; + + /** + * The reg proc logger. + */ + private static Logger regProcLogger = RegProcessorLogger.getLogger(PacketValidateProcessor.class); + + @Autowired + private PacketValidator compositePacketValidator; + + @Autowired + private PriorityBasedPacketManagerService packetManagerService; + + @Autowired + private Utilities utility; + + @Autowired + private ObjectMapper objectMapper; + + /** + * The Constant USER. + */ + private static final String USER = "MOSIP_SYSTEM"; + + /** + * The Constant APPLICANT_TYPE. + */ + public static final String APPLICANT_TYPE = "applicantType"; + + /** + * The Constant APPROVED. + */ + public static final String APPROVED = "APPROVED"; + + /** + * The Constant REJECTED. + */ + public static final String REJECTED = "REJECTED"; + + /** + * The registration status service. + */ + @Autowired + RegistrationStatusService registrationStatusService; + + /** + * The core audit request builder. + */ + @Autowired + AuditLogRequestBuilder auditLogRequestBuilder; + + @Autowired + private RegistrationProcessorRestClientService restClientService; + + @Autowired + private AuditUtility auditUtility; + + /** + * The sync registration service. + */ + @Autowired + private SyncRegistrationService syncRegistrationService; + + private static final String PRE_REG_ID = "mosip.pre-registration.datasync.store"; + private static final String VERSION = "1.0"; + + + + @Autowired + RegistrationExceptionMapperUtil registrationStatusMapperUtil; + + @Value("${mosip.notificationtype}") + private String notificationTypes; + + @Autowired + private Decryptor decryptor; + + @Autowired + private NotificationUtility notificationUtility; + + @Value("${mosip.registration.processor.datetime.pattern}") + private String dateformat; + + public MessageDTO process(MessageDTO object, String stageName) { + TrimExceptionMessage trimMessage = new TrimExceptionMessage(); + LogDescription description = new LogDescription(); + PacketValidationDto packetValidationDto = new PacketValidationDto(); + String registrationId = null; + InternalRegistrationStatusDto registrationStatusDto = new InternalRegistrationStatusDto(); + try { + registrationStatusDto + .setLatestTransactionTypeCode(RegistrationTransactionTypeCode.PRINT_SERVICE.toString()); + registrationStatusDto.setRegistrationStageName(stageName); + object.setMessageBusAddress(MessageBusAddress.PACKET_VALIDATOR_BUS_IN); + object.setIsValid(Boolean.FALSE); + object.setInternalError(Boolean.TRUE); + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + "", "PacketValidateProcessor::process()::entry"); + registrationId = object.getRid(); + packetValidationDto.setTransactionSuccessful(false); + registrationStatusDto = registrationStatusService.getRegistrationStatus( + registrationId, object.getReg_type(), object.getIteration(), object.getWorkflowInstanceId()); + setPacketCreatedDateTime(registrationStatusDto); + registrationStatusDto + .setLatestTransactionTypeCode(RegistrationTransactionTypeCode.VALIDATE_PACKET.toString()); + registrationStatusDto.setRegistrationStageName(stageName); + boolean isValidSupervisorStatus = isValidSupervisorStatus(object); + if (isValidSupervisorStatus) { + Boolean isValid = compositePacketValidator.validate(object.getRid(), + registrationStatusDto.getRegistrationType(), packetValidationDto); + + if (isValid) { + // save audit details + InternalRegistrationStatusDto finalRegistrationStatusDto = registrationStatusDto; + String finalRegistrationId = registrationId; + Runnable r = () -> { + try { + auditUtility.saveAuditDetails(finalRegistrationId, + finalRegistrationStatusDto.getRegistrationType()); + } catch (Exception e) { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString(), + description.getCode() + " Inside Runnable ", ""); + + } + }; + ExecutorService es = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()); + es.submit(r); + es.shutdown(); + registrationStatusDto + .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.SUCCESS.toString()); + object.setIsValid(Boolean.TRUE); + registrationStatusDto + .setStatusComment(StatusUtil.PACKET_STRUCTURAL_VALIDATION_SUCCESS.getMessage()); + registrationStatusDto.setSubStatusCode(StatusUtil.PACKET_STRUCTURAL_VALIDATION_SUCCESS.getCode()); + registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); + // ReverseDataSync + reverseDataSync(registrationId, registrationStatusDto.getRegistrationType(), description, + packetValidationDto); + + packetValidationDto.setTransactionSuccessful(true); + description.setMessage( + PlatformSuccessMessages.RPR_PKR_PACKET_VALIDATE.getMessage() + " -- " + registrationId); + description.setCode(PlatformSuccessMessages.RPR_PKR_PACKET_VALIDATE.getCode()); + + regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString(), registrationId, + description.getCode() + description.getMessage()); + + } else { + registrationStatusDto.setLatestTransactionStatusCode(registrationStatusMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.PACKET_STRUCTURAL_VALIDATION_FAILED)); + int retryCount = registrationStatusDto.getRetryCount() != null + ? registrationStatusDto.getRetryCount() + 1 + : 1; + description.setMessage(packetValidationDto.getPacketValidatonStatusCode() + " : " + + packetValidationDto.getPacketValidaionFailureMessage()); + packetValidationDto.setTransactionSuccessful(false); + registrationStatusDto.setRetryCount(retryCount); + registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.toString()); + registrationStatusDto.setStatusComment(packetValidationDto.getPacketValidaionFailureMessage()); + registrationStatusDto.setSubStatusCode(packetValidationDto.getPacketValidatonStatusCode()); + + description.setMessage(PlatformErrorMessages.STRUCTURAL_VALIDATION_FAILED.getMessage()); + description.setCode(PlatformErrorMessages.STRUCTURAL_VALIDATION_FAILED.getCode()); + + regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString(), + description.getCode() + " -- " + registrationId, description.getMessage()); + + } + } else { + registrationStatusDto.setLatestTransactionStatusCode( + registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.PACKET_REJECTED)); + int retryCount = registrationStatusDto.getRetryCount() != null + ? registrationStatusDto.getRetryCount() + 1 + : 1; + packetValidationDto.setTransactionSuccessful(false); + registrationStatusDto.setRetryCount(retryCount); + registrationStatusDto.setStatusCode(RegistrationStatusCode.REJECTED.toString()); + registrationStatusDto.setStatusComment(StatusUtil.PACKET_REJECTED.getMessage()); + registrationStatusDto.setSubStatusCode(StatusUtil.PACKET_REJECTED.getCode()); + + description.setMessage(PlatformErrorMessages.RPR_PVM_PACKET_REJECTED.getMessage()); + description.setCode(PlatformErrorMessages.RPR_PVM_PACKET_REJECTED.getCode()); + + regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString(), description.getCode() + " -- " + registrationId, + description.getMessage()); + } + object.setInternalError(Boolean.FALSE); + registrationStatusDto.setUpdatedBy(USER); + SyncRegistrationEntity regEntity = syncRegistrationService.findByWorkflowInstanceId(object.getWorkflowInstanceId()); + sendNotification(regEntity, registrationStatusDto, packetValidationDto.isTransactionSuccessful(),isValidSupervisorStatus); + } catch (PacketManagerException e) { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + registrationId, + RegistrationStatusCode.FAILED.toString() + e.getMessage() + ExceptionUtils.getStackTrace(e)); + registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.name()); + registrationStatusDto.setStatusComment(trimMessage + .trimExceptionMessage(StatusUtil.PACKET_MANAGER_EXCEPTION.getMessage() + e.getMessage())); + registrationStatusDto.setSubStatusCode(StatusUtil.PACKET_MANAGER_EXCEPTION.getCode()); + registrationStatusDto.setLatestTransactionStatusCode( + registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.PACKET_MANAGER_EXCEPTION)); + description.setMessage(PlatformErrorMessages.PACKET_MANAGER_EXCEPTION.getMessage()); + description.setCode(PlatformErrorMessages.PACKET_MANAGER_EXCEPTION.getCode()); + registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.name()); + } catch (DataAccessException e) { + registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); + registrationStatusDto.setStatusComment( + trimMessage.trimExceptionMessage(StatusUtil.DB_NOT_ACCESSIBLE.getMessage() + e.getMessage())); + registrationStatusDto.setSubStatusCode(StatusUtil.DB_NOT_ACCESSIBLE.getCode()); + registrationStatusDto.setLatestTransactionStatusCode( + registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.DATA_ACCESS_EXCEPTION)); + packetValidationDto.setTransactionSuccessful(false); + description.setMessage(PlatformErrorMessages.RPR_RGS_REGISTRATION_TABLE_NOT_ACCESSIBLE.getMessage()); + description.setCode(PlatformErrorMessages.RPR_RGS_REGISTRATION_TABLE_NOT_ACCESSIBLE.getCode()); + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + description.getCode() + " -- " + registrationId, + PlatformErrorMessages.RPR_RGS_REGISTRATION_TABLE_NOT_ACCESSIBLE.getMessage() + e.getMessage() + + ExceptionUtils.getStackTrace(e)); + } catch (IdentityNotFoundException | IOException exc) { + registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.toString()); + registrationStatusDto.setStatusComment( + trimMessage.trimExceptionMessage(StatusUtil.IO_EXCEPTION.getMessage() + exc.getMessage())); + registrationStatusDto.setSubStatusCode(StatusUtil.IO_EXCEPTION.getCode()); + registrationStatusDto.setLatestTransactionStatusCode( + registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.IOEXCEPTION)); + packetValidationDto.setTransactionSuccessful(false); + description.setMessage(PlatformErrorMessages.RPR_SYS_IO_EXCEPTION.getMessage()); + description.setCode(PlatformErrorMessages.STRUCTURAL_VALIDATION_FAILED.getCode()); + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + description.getCode() + " -- " + registrationId, + PlatformErrorMessages.STRUCTURAL_VALIDATION_FAILED.getMessage() + exc.getMessage() + + ExceptionUtils.getStackTrace(exc)); + } catch (ParsingException exc) { + registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.toString()); + registrationStatusDto.setStatusComment(trimMessage + .trimExceptionMessage(StatusUtil.JSON_PARSING_EXCEPTION.getMessage() + exc.getMessage())); + registrationStatusDto.setSubStatusCode(StatusUtil.JSON_PARSING_EXCEPTION.getCode()); + registrationStatusDto.setLatestTransactionStatusCode( + registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.PARSE_EXCEPTION)); + packetValidationDto.setTransactionSuccessful(false); + description.setMessage(PlatformErrorMessages.RPR_SYS_JSON_PARSING_EXCEPTION.getMessage()); + description.setCode(PlatformErrorMessages.STRUCTURAL_VALIDATION_FAILED.getCode()); + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + description.getCode() + " -- " + registrationId, + PlatformErrorMessages.STRUCTURAL_VALIDATION_FAILED.getMessage() + exc.getMessage() + + ExceptionUtils.getStackTrace(exc)); + } catch (TablenotAccessibleException e) { + registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); + registrationStatusDto.setStatusComment( + trimMessage.trimExceptionMessage(StatusUtil.DB_NOT_ACCESSIBLE.getMessage() + e.getMessage())); + registrationStatusDto.setSubStatusCode(StatusUtil.DB_NOT_ACCESSIBLE.getCode()); + registrationStatusDto.setLatestTransactionStatusCode(registrationStatusMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.TABLE_NOT_ACCESSIBLE_EXCEPTION)); + description.setMessage(PlatformErrorMessages.RPR_RGS_REGISTRATION_TABLE_NOT_ACCESSIBLE.getMessage()); + description.setCode(PlatformErrorMessages.RPR_RGS_REGISTRATION_TABLE_NOT_ACCESSIBLE.getCode()); + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), + description.getCode() + " -- " + registrationId, + PlatformErrorMessages.RPR_RGS_REGISTRATION_TABLE_NOT_ACCESSIBLE.getMessage(), + ExceptionUtils.getStackTrace(e)); + + } catch (ApisResourceAccessException e) { + if (e.getCause() instanceof HttpClientErrorException) { + HttpClientErrorException httpClientException = (HttpClientErrorException) e.getCause(); + regProcLogger.info(LoggerFileConstant.REGISTRATIONID.toString(), registrationId, + PlatformErrorMessages.REVERSE_DATA_SYNC_FAILED.getMessage(), + httpClientException.getResponseBodyAsString() + ExceptionUtils.getStackTrace(e)); + } else if (e.getCause() instanceof HttpServerErrorException) { + HttpServerErrorException httpServerException = (HttpServerErrorException) e.getCause(); + regProcLogger.info(LoggerFileConstant.REGISTRATIONID.toString(), registrationId, + PlatformErrorMessages.REVERSE_DATA_SYNC_FAILED.getMessage(), + httpServerException.getResponseBodyAsString() + ExceptionUtils.getStackTrace(e)); + } else { + regProcLogger.info(LoggerFileConstant.REGISTRATIONID.toString(), registrationId, + PlatformErrorMessages.REVERSE_DATA_SYNC_FAILED.getMessage(), e.getMessage()); + } + registrationStatusDto.setStatusCode(RegistrationStatusCode.REPROCESS.toString()); + registrationStatusDto.setLatestTransactionStatusCode( + registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.APIS_RESOURCE_ACCESS_EXCEPTION)); + registrationStatusDto.setStatusComment(trimMessage + .trimExceptionMessage(StatusUtil.API_RESOUCE_ACCESS_FAILED.getMessage() + e.getMessage())); + registrationStatusDto.setSubStatusCode(StatusUtil.API_RESOUCE_ACCESS_FAILED.getCode()); + packetValidationDto.setTransactionSuccessful(false); + + description.setMessage(PlatformErrorMessages.REVERSE_DATA_SYNC_FAILED.getMessage()); + description.setCode(PlatformErrorMessages.REVERSE_DATA_SYNC_FAILED.getCode()); + } catch (RegistrationProcessorCheckedException e) { + registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.toString()); + registrationStatusDto.setStatusComment( + trimMessage.trimExceptionMessage(StatusUtil.BASE_CHECKED_EXCEPTION.getMessage() + e.getMessage())); + registrationStatusDto.setSubStatusCode(StatusUtil.BASE_CHECKED_EXCEPTION.getCode()); + registrationStatusDto.setLatestTransactionStatusCode( + registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.BASE_CHECKED_EXCEPTION)); + packetValidationDto.setTransactionSuccessful(false); + description.setMessage(PlatformErrorMessages.RPR_PVM_BASE_CHECKED_EXCEPTION.getMessage()); + description.setCode(PlatformErrorMessages.RPR_PVM_BASE_CHECKED_EXCEPTION.getCode()); + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + description.getCode() + " -- " + registrationId, + PlatformErrorMessages.RPR_PVM_BASE_CHECKED_EXCEPTION.getMessage() + e.getMessage() + + ExceptionUtils.getStackTrace(e)); + } catch (BaseUncheckedException e) { + registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.toString()); + registrationStatusDto.setStatusComment(trimMessage + .trimExceptionMessage(StatusUtil.BASE_UNCHECKED_EXCEPTION.getMessage() + e.getMessage())); + registrationStatusDto.setSubStatusCode(StatusUtil.BASE_UNCHECKED_EXCEPTION.getCode()); + registrationStatusDto.setLatestTransactionStatusCode( + registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.BASE_UNCHECKED_EXCEPTION)); + packetValidationDto.setTransactionSuccessful(false); + description.setMessage(PlatformErrorMessages.RPR_PVM_BASE_UNCHECKED_EXCEPTION.getMessage()); + description.setCode(PlatformErrorMessages.RPR_PVM_BASE_UNCHECKED_EXCEPTION.getCode()); + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + description.getCode() + " -- " + registrationId, + PlatformErrorMessages.RPR_PVM_BASE_UNCHECKED_EXCEPTION.getMessage() + e.getMessage() + + ExceptionUtils.getStackTrace(e)); + } catch (Exception ex) { + registrationStatusDto.setStatusComment(trimMessage + .trimExceptionMessage(StatusUtil.UNKNOWN_EXCEPTION_OCCURED.getMessage() + ex.getMessage())); + registrationStatusDto.setSubStatusCode(StatusUtil.UNKNOWN_EXCEPTION_OCCURED.getCode()); + registrationStatusDto.setLatestTransactionStatusCode( + registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.EXCEPTION)); + packetValidationDto.setTransactionSuccessful(false); + description.setMessage(PlatformErrorMessages.STRUCTURAL_VALIDATION_FAILED.getMessage()); + description.setCode(PlatformErrorMessages.STRUCTURAL_VALIDATION_FAILED.getCode()); + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + description.getCode() + " -- " + registrationId, + PlatformErrorMessages.STRUCTURAL_VALIDATION_FAILED.getMessage() + ex.getMessage() + + ExceptionUtils.getStackTrace(ex)); + } finally { + + if (object.getInternalError()) { + registrationStatusDto.setUpdatedBy(USER); + int retryCount = registrationStatusDto.getRetryCount() != null + ? registrationStatusDto.getRetryCount() + 1 + : 1; + registrationStatusDto.setRetryCount(retryCount); + updateErrorFlags(registrationStatusDto, object); + } + object.setRid(registrationStatusDto.getRegistrationId()); + /** Module-Id can be Both Success/Error code */ + String moduleId = packetValidationDto.isTransactionSuccessful() + ? PlatformSuccessMessages.RPR_PKR_PACKET_VALIDATE.getCode() + : description.getCode(); + String moduleName = ModuleName.PACKET_VALIDATOR.toString(); + registrationStatusService.updateRegistrationStatus(registrationStatusDto, moduleId, moduleName); + if (packetValidationDto.isTransactionSuccessful()) + description.setMessage(PlatformSuccessMessages.RPR_PKR_PACKET_VALIDATE.getMessage()); + String eventId = packetValidationDto.isTransactionSuccessful() ? EventId.RPR_402.toString() + : EventId.RPR_405.toString(); + String eventName = packetValidationDto.isTransactionSuccessful() ? EventName.UPDATE.toString() + : EventName.EXCEPTION.toString(); + String eventType = packetValidationDto.isTransactionSuccessful() ? EventType.BUSINESS.toString() + : EventType.SYSTEM.toString(); + + auditLogRequestBuilder.createAuditRequestBuilder(description.getMessage(), eventId, eventName, eventType, + moduleId, moduleName, registrationId); + } + + return object; + + } + + + private void setPacketCreatedDateTime(InternalRegistrationStatusDto registrationStatusDto) throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { + try { + Map metaInfo = packetManagerService.getMetaInfo( + registrationStatusDto.getRegistrationId(), registrationStatusDto.getRegistrationType(), ProviderStageName.PACKET_VALIDATOR); + DateTimeFormatter formatter = DateTimeFormatter.ofPattern(dateformat); + String packetCreatedDateTime = metaInfo.get(JsonConstant.CREATIONDATE); + if (packetCreatedDateTime != null && !packetCreatedDateTime.isEmpty()) { + LocalDateTime dateTime = DateUtils.parseToLocalDateTime(packetCreatedDateTime); + registrationStatusDto.setPacketCreateDateTime(dateTime); + } else { + regProcLogger.warn(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + " -- " + registrationStatusDto.getRefId(), + PlatformErrorMessages.RPR_PVM_PACKET_CREATED_DATE_TIME_EMPTY_OR_NULL.getMessage()); + } + } catch (DateTimeParseException e) { + regProcLogger.warn(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + " -- " + registrationStatusDto.getRefId(), + PlatformErrorMessages.RPR_PVM_PACKET_CREATED_DATE_TIME_PARSE_EXCEPTION.getMessage() + e.getMessage()); + }catch (IllegalArgumentException ex) + { + regProcLogger.warn(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + " -- " + registrationStatusDto.getRefId(), + PlatformErrorMessages.RPR_PVM_INVALID_ARGUMENT_EXCEPTION.getMessage() + ex.getMessage()); + } + } + + private boolean isValidSupervisorStatus(MessageDTO messageDTO) { + SyncRegistrationEntity regEntity = syncRegistrationService.findByWorkflowInstanceId(messageDTO.getWorkflowInstanceId()); + if (regEntity.getSupervisorStatus().equalsIgnoreCase(APPROVED)) { + return true; + + } else if (regEntity.getSupervisorStatus().equalsIgnoreCase(REJECTED)) { + return false; + } + return false; + } + + @SuppressWarnings("unchecked") + private void reverseDataSync(String id, String process, LogDescription description, + PacketValidationDto packetValidationDto) throws IOException, ApisResourceAccessException, + PacketManagerException, JsonProcessingException, JSONException { + + Map metaInfoMap = packetManagerService.getMetaInfo(id, process, + ProviderStageName.PACKET_VALIDATOR); + String metadata = metaInfoMap.get(JsonConstant.METADATA); + if (StringUtils.isNotEmpty(metadata)) { + JSONArray jsonArray = new JSONArray(metadata); + + String preRegId = null; + for (int i = 0; i < jsonArray.length(); i++) { + if (!jsonArray.isNull(i)) { + JSONObject jsonObject = (JSONObject) jsonArray.get(i); + FieldValue fieldValue = objectMapper.readValue(jsonObject.toString(), FieldValue.class); + if (fieldValue.getLabel().equalsIgnoreCase(JsonConstant.PREREGISTRATIONID)) { + preRegId = fieldValue.getValue(); + break; + } + + } + } + if (preRegId == null || preRegId.trim().isEmpty()) { + regProcLogger.info(LoggerFileConstant.REGISTRATIONID.toString(), id, + "Pre-registration id not present.", + "Reverse datasync is not applicable for the registration id"); + return; + } + if (id != null) { + packetValidationDto.setTransactionSuccessful(false); + MainResponseDTO mainResponseDto = null; + if (preRegId != null && !preRegId.trim().isEmpty()) { + MainRequestDTO mainRequestDto = new MainRequestDTO<>(); + mainRequestDto.setId(PRE_REG_ID); + mainRequestDto.setVersion(VERSION); + mainRequestDto.setRequesttime(new Date()); + ReverseDataSyncRequestDTO reverseDataSyncRequestDto = new ReverseDataSyncRequestDTO(); + reverseDataSyncRequestDto.setPreRegistrationIds(Arrays.asList(preRegId)); + mainRequestDto.setRequest(reverseDataSyncRequestDto); + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString(), id, + "PacketValidateProcessor::reverseDataSync()::ReverseDataSync Api call started with request data :" + + JsonUtil.objectMapperObjectToJson(mainRequestDto)); + mainResponseDto = (MainResponseDTO) restClientService.postApi(ApiName.REVERSEDATASYNC, "", "", + mainRequestDto, MainResponseDTO.class); + + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString(), id, + "\"PacketValidateProcessor::reverseDataSync()::ReverseDataSync Api call ended with response data : " + + JsonUtil.objectMapperObjectToJson(mainResponseDto)); + packetValidationDto.setTransactionSuccessful(true); + + } + if (mainResponseDto != null && mainResponseDto.getErrors() != null + && mainResponseDto.getErrors().size() > 0) { + regProcLogger.error(LoggerFileConstant.REGISTRATIONID.toString(), id, + PlatformErrorMessages.REVERSE_DATA_SYNC_FAILED.getMessage(), + mainResponseDto.getErrors().toString()); + packetValidationDto.setTransactionSuccessful(false); + description.setMessage(PlatformErrorMessages.REVERSE_DATA_SYNC_FAILED.getMessage()); + + } else if (mainResponseDto == null) { + packetValidationDto.setTransactionSuccessful(false); + description.setMessage(PlatformErrorMessages.REVERSE_DATA_SYNC_FAILED.getMessage() + + " null response from rest client "); + } else { + packetValidationDto.setTransactionSuccessful(true); + regProcLogger.info(LoggerFileConstant.REGISTRATIONID.toString(), id, + PlatformSuccessMessages.REVERSE_DATA_SYNC_SUCCESS.getMessage(), ""); + } + + } + } + + } + + private void updateErrorFlags(InternalRegistrationStatusDto registrationStatusDto, MessageDTO object) { + object.setInternalError(true); + if (registrationStatusDto.getLatestTransactionStatusCode() + .equalsIgnoreCase(RegistrationTransactionStatusCode.REPROCESS.toString())) { + object.setIsValid(true); + } else { + object.setIsValid(false); + } + } + + private void sendNotification(SyncRegistrationEntity regEntity, + InternalRegistrationStatusDto registrationStatusDto, boolean isTransactionSuccessful,boolean isValidSupervisorStatus) { + try { + String registrationId = registrationStatusDto.getRegistrationId(); + if (regEntity.getOptionalValues() != null) { + String[] allNotificationTypes = notificationTypes.split("\\|"); + boolean isProcessingSuccess; + InputStream inputStream = new ByteArrayInputStream(regEntity.getOptionalValues()); + InputStream decryptedInputStream = decryptor.decrypt( + registrationId, + utility.getRefId(registrationId, regEntity.getReferenceId()), + inputStream); + String decryptedData = IOUtils.toString(decryptedInputStream, StandardCharsets.UTF_8); + RegistrationAdditionalInfoDTO registrationAdditionalInfoDTO = (RegistrationAdditionalInfoDTO) JsonUtils + .jsonStringToJavaObject(RegistrationAdditionalInfoDTO.class, decryptedData); + if (isTransactionSuccessful) { + isProcessingSuccess = true; + notificationUtility.sendNotification(registrationAdditionalInfoDTO, registrationStatusDto, + regEntity, allNotificationTypes, isProcessingSuccess,isValidSupervisorStatus); + } else { + isProcessingSuccess = false; + notificationUtility.sendNotification(registrationAdditionalInfoDTO, registrationStatusDto, + regEntity, allNotificationTypes, isProcessingSuccess,isValidSupervisorStatus); + } + boolean isDeleted = syncRegistrationService.deleteAdditionalInfo(regEntity); + if (isDeleted) { + regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString(), registrationId, + PlatformSuccessMessages.RPR_PKR_ADDITIONAL_INFO_DELETED.getCode() + + PlatformSuccessMessages.RPR_PKR_ADDITIONAL_INFO_DELETED.getMessage()); + } + } + } catch (Exception e) { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString(), + "Send notification failed for rid - " + registrationStatusDto.getRegistrationId(), ExceptionUtils.getStackTrace(e)); + } + } + +} diff --git a/registration-processor/pre-processor/registration-processor-quality-classifier-stage/src/test/java/io/mosip/registration/processor/quality/qualifier/stage/test/QualityClassifierStageTest.java b/registration-processor/pre-processor/registration-processor-quality-classifier-stage/src/test/java/io/mosip/registration/processor/quality/qualifier/stage/test/QualityClassifierStageTest.java index 37972938e79..933885cf448 100644 --- a/registration-processor/pre-processor/registration-processor-quality-classifier-stage/src/test/java/io/mosip/registration/processor/quality/qualifier/stage/test/QualityClassifierStageTest.java +++ b/registration-processor/pre-processor/registration-processor-quality-classifier-stage/src/test/java/io/mosip/registration/processor/quality/qualifier/stage/test/QualityClassifierStageTest.java @@ -107,6 +107,7 @@ public class QualityClassifierStageTest { private String qualityPrefixTag = "Biometric_Quality-"; + private String level_1 = "level-1"; private String level_2 = "level-2"; private String level_3 = "level-3"; @@ -118,7 +119,7 @@ public class QualityClassifierStageTest { private String level_9 = "level-9"; private String level_10 = "level-10"; -// + JSONObject mappingJSONObject; @InjectMocks diff --git a/registration-processor/pre-processor/registration-processor-supervisor-validator-stage/src/main/java/io/mosip/registration/processor/stages/supervisorvalidator/SupervisorValidator.java b/registration-processor/pre-processor/registration-processor-supervisor-validator-stage/src/main/java/io/mosip/registration/processor/stages/supervisorvalidator/SupervisorValidator.java index f45c5e21cf9..2d4e439aed1 100644 --- a/registration-processor/pre-processor/registration-processor-supervisor-validator-stage/src/main/java/io/mosip/registration/processor/stages/supervisorvalidator/SupervisorValidator.java +++ b/registration-processor/pre-processor/registration-processor-supervisor-validator-stage/src/main/java/io/mosip/registration/processor/stages/supervisorvalidator/SupervisorValidator.java @@ -1,355 +1,351 @@ -package io.mosip.registration.processor.stages.supervisorvalidator; - -import java.io.IOException; -import java.security.NoSuchAlgorithmException; -import java.security.cert.CertificateException; -import java.security.spec.InvalidKeySpecException; -import java.util.ArrayList; -import java.util.List; -import java.util.stream.Collectors; - -import javax.xml.parsers.ParserConfigurationException; - -import io.mosip.registration.processor.packet.storage.utils.Utilities; -import org.json.JSONException; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; -import org.xml.sax.SAXException; - -import com.fasterxml.jackson.databind.ObjectMapper; - -import io.mosip.kernel.biometrics.entities.BIR; -import io.mosip.kernel.biometrics.entities.BiometricRecord; -import io.mosip.kernel.core.bioapi.exception.BiometricException; -import io.mosip.kernel.core.exception.BaseCheckedException; -import io.mosip.kernel.core.logger.spi.Logger; -import io.mosip.kernel.core.util.StringUtils; -import io.mosip.registration.processor.core.auth.dto.AuthResponseDTO; -import io.mosip.registration.processor.core.auth.dto.IndividualIdDto; -import io.mosip.registration.processor.core.code.ApiName; -import io.mosip.registration.processor.core.code.RegistrationExceptionTypeCode; -import io.mosip.registration.processor.core.common.rest.dto.ErrorDTO; -import io.mosip.registration.processor.core.constant.MappingJsonConstants; -import io.mosip.registration.processor.core.constant.ProviderStageName; -import io.mosip.registration.processor.core.exception.ApisResourceAccessException; -import io.mosip.registration.processor.core.exception.AuthSystemException; -import io.mosip.registration.processor.core.exception.PacketDecryptionFailureException; -import io.mosip.registration.processor.core.exception.RegistrationProcessorCheckedException; -import io.mosip.registration.processor.core.exception.ValidationFailedException; -import io.mosip.registration.processor.core.exception.util.PlatformErrorMessages; -import io.mosip.registration.processor.core.http.ResponseWrapper; -import io.mosip.registration.processor.core.logger.RegProcessorLogger; -import io.mosip.registration.processor.core.packet.dto.RegOsiDto; -import io.mosip.registration.processor.core.packet.dto.ServerError; -import io.mosip.registration.processor.core.packet.dto.masterdata.UserResponseDto; -import io.mosip.registration.processor.core.packet.dto.regcentermachine.RegistrationCenterUserMachineMappingHistoryResponseDto; -import io.mosip.registration.processor.core.spi.restclient.RegistrationProcessorRestClientService; -import io.mosip.registration.processor.core.status.util.StatusUtil; -import io.mosip.registration.processor.core.util.JsonUtil; -import io.mosip.registration.processor.core.util.RegistrationExceptionMapperUtil; -import io.mosip.registration.processor.packet.storage.utils.BioSdkUtil; -import io.mosip.registration.processor.packet.storage.utils.PriorityBasedPacketManagerService; -import io.mosip.registration.processor.status.code.RegistrationStatusCode; -import io.mosip.registration.processor.status.dto.InternalRegistrationStatusDto; - -@Service -public class SupervisorValidator { - - private static Logger regProcLogger = RegProcessorLogger.getLogger(SupervisorValidator.class); - - private static final String ISTRUE = "true"; - - private static final String INDIVIDUAL_TYPE_USERID = "USERID"; - - private static final String APPID = "regproc"; - - @Autowired - RegistrationExceptionMapperUtil registrationExceptionMapperUtil; - - @Autowired - RegistrationProcessorRestClientService restClientService; - - @Autowired - private PriorityBasedPacketManagerService packetManagerService; - - @Autowired - private ObjectMapper mapper; - - @Autowired - private Utilities utility; - - @Autowired - private BioSdkUtil bioUtil; - - /** - * Checks if is valid Supervisor. - * - * @param registrationId the registration id - * @throws SAXException - * @throws ParserConfigurationException - * @throws io.mosip.kernel.core.exception.IOException - * @throws Exception - * @throws PacketDecryptionFailureException - * @throws RegistrationProcessorCheckedException - */ - public void validate(String registrationId, InternalRegistrationStatusDto registrationStatusDto, RegOsiDto regOsi) - throws Exception { - regProcLogger.debug("validate called for registrationId {}", registrationId); - - validateSupervisor(registrationId, regOsi, registrationStatusDto); - authenticateSupervisor(regOsi, registrationId, registrationStatusDto); - validateUMCmapping(regOsi.getPacketCreationDate(), regOsi.getRegcntrId(), regOsi.getMachineId(), - regOsi.getSupervisorId(), registrationStatusDto); - regProcLogger.debug("validate call ended for registrationId {}", registrationId); - } - - private void validateSupervisor(String registrationId, RegOsiDto regOsi, - InternalRegistrationStatusDto registrationStatusDto) throws IOException, BaseCheckedException { - String creationDate = regOsi.getPacketCreationDate(); - if (creationDate != null && !(StringUtils.isEmpty(creationDate))) { - if (!isActiveUser(creationDate, regOsi.getSupervisorId(), registrationStatusDto)) { - registrationStatusDto.setLatestTransactionStatusCode(registrationExceptionMapperUtil - .getStatusCode(RegistrationExceptionTypeCode.SUPERVISOR_WAS_INACTIVE)); - registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.toString()); - regProcLogger.debug("ActiveUserId call ended for registrationId {} {}", registrationId, - StatusUtil.SUPERVISOR_WAS_INACTIVE.getMessage() + regOsi.getSupervisorId()); - throw new BaseCheckedException( - StatusUtil.SUPERVISOR_WAS_INACTIVE.getMessage() + regOsi.getSupervisorId(), - StatusUtil.SUPERVISOR_WAS_INACTIVE.getCode()); - } - - } else { - registrationStatusDto.setLatestTransactionStatusCode(registrationExceptionMapperUtil - .getStatusCode(RegistrationExceptionTypeCode.PACKET_CREATION_DATE_NOT_PRESENT_IN_PACKET)); - registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.toString()); - regProcLogger.debug("ActiveUserId call ended for registrationId {}. packet creationDate is null", - registrationId); - throw new BaseCheckedException(StatusUtil.SUPERVISOR_PACKET_CREATION_DATE_NOT_FOUND_IN_PACKET.getMessage(), - StatusUtil.SUPERVISOR_PACKET_CREATION_DATE_NOT_FOUND_IN_PACKET.getCode()); - - } - } - - private boolean isActiveUser(String creationDate, String supervisorId, - InternalRegistrationStatusDto registrationStatusDto) throws IOException, BaseCheckedException { - boolean wasSupervisorActiveDuringPCT = false; - - if (supervisorId != null && !supervisorId.isEmpty()) { - UserResponseDto supervisorResponse = getUserDetails(supervisorId, creationDate, registrationStatusDto); - if (supervisorResponse.getErrors() == null) { - wasSupervisorActiveDuringPCT = supervisorResponse.getResponse().getUserResponseDto().get(0) - .getIsActive(); - if (!wasSupervisorActiveDuringPCT) { - regProcLogger.debug("isActiveUser call ended for registrationId {} {}", - registrationStatusDto.getRegistrationId(), StatusUtil.SUPERVISOR_WAS_INACTIVE.getMessage()); - } - } else { - List errors = supervisorResponse.getErrors(); - regProcLogger.debug("isActiveUser call ended with error {}", errors.get(0).getMessage()); - throw new BaseCheckedException( - StatusUtil.SUPERVISOR_AUTHENTICATION_FAILED.getMessage() + errors.get(0).getMessage(), - StatusUtil.SUPERVISOR_AUTHENTICATION_FAILED.getCode()); - } - } - return wasSupervisorActiveDuringPCT; - } - - private UserResponseDto getUserDetails(String operatorId, String creationDate, - InternalRegistrationStatusDto registrationStatusDto) throws ApisResourceAccessException, IOException { - UserResponseDto userResponse; - List pathSegments = new ArrayList<>(); - pathSegments.add(operatorId); - pathSegments.add(creationDate); - - userResponse = (UserResponseDto) restClientService.getApi(ApiName.USERDETAILS, pathSegments, "", "", - UserResponseDto.class); - regProcLogger.debug("isUserActive call ended with response data {}", - JsonUtil.objectMapperObjectToJson(userResponse)); - - return userResponse; - } - - /** - * To authenticate supervisor. - * - * @param regOsi the reg osi - * @param registrationId the registration id - * @param registrationStatusDto - * @throws SAXException - * @throws ParserConfigurationException - * @throws io.mosip.kernel.core.exception.IOException - * @throws PacketDecryptionFailureException - * @throws Exception - */ - private void authenticateSupervisor(RegOsiDto regOsi, String registrationId, - InternalRegistrationStatusDto registrationStatusDto) throws Exception { - String supervisorId = regOsi.getSupervisorId(); - - // officer password and otp check - String supervisiorPassword = regOsi.getSupervisorHashedPwd(); - String supervisorOTP = regOsi.getSupervisorOTPAuthentication(); - - String supervisorBiometricFileName = regOsi.getSupervisorBiometricFileName(); - - if (StringUtils.isEmpty(supervisorBiometricFileName) || supervisorBiometricFileName == null) { - if (!validateOtpAndPwd(supervisiorPassword, supervisorOTP)) { - registrationStatusDto.setLatestTransactionStatusCode(registrationExceptionMapperUtil - .getStatusCode(RegistrationExceptionTypeCode.SUPERVISOR_PASSWORD_OTP_FAILURE)); - registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.toString()); - regProcLogger.debug("validateSupervisor call ended for registrationId {} {}", registrationId, - StatusUtil.SUPERVISOR_PASSWORD_OTP_FAILURE.getMessage() + supervisorId); - throw new ValidationFailedException(StatusUtil.SUPERVISOR_PASSWORD_OTP_FAILURE.getMessage() + supervisorId, - StatusUtil.SUPERVISOR_PASSWORD_OTP_FAILURE.getCode()); - } - } else { - BiometricRecord biometricRecord = packetManagerService.getBiometricsByMappingJsonKey(registrationId, - MappingJsonConstants.SUPERVISORBIOMETRICFILENAME, registrationStatusDto.getRegistrationType(), - ProviderStageName.SUPERVISOR_VALIDATOR); - - if (biometricRecord == null || biometricRecord.getSegments() == null - || biometricRecord.getSegments().isEmpty()) { - regProcLogger.error("validateSupervisor call ended for registrationId {} {}", registrationId, - "ERROR =======>" + StatusUtil.BIOMETRICS_VALIDATION_FAILURE.getMessage()); - registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.toString()); - throw new ValidationFailedException( - StatusUtil.BIOMETRICS_VALIDATION_FAILURE.getMessage() + " for Supervisor : " + supervisorId, - StatusUtil.BIOMETRICS_VALIDATION_FAILURE.getCode()); - } - validateUserBiometric(registrationId, supervisorId, biometricRecord.getSegments(), INDIVIDUAL_TYPE_USERID, - registrationStatusDto); - } - - } - - /** - * Validate opValidated and otpValidated. - * - * @param pwd the opValidated - * @param otp the otpValidated - * @return true, if successful - */ - private boolean validateOtpAndPwd(String opValidated, String otpValidated) { - return (opValidated != null && opValidated.equals(ISTRUE) || otpValidated != null && otpValidated.equals(ISTRUE)); - } - - /** - * Validate user. - * - * @param userId the userid - * @param registrationId the registration id - * @param list biometric data as BIR object - * @param individualType user type - * @param registrationStatusDto - * @throws Exception - * @throws SAXException - * @throws ParserConfigurationException - * @throws NoSuchAlgorithmException - * @throws InvalidKeySpecException - * @throws BiometricException - */ - - private void validateUserBiometric(String registrationId, String userId, List list, String individualType, - InternalRegistrationStatusDto registrationStatusDto) - throws Exception { - - if (INDIVIDUAL_TYPE_USERID.equalsIgnoreCase(individualType)) { - userId = getIndividualIdByUserId(userId); - individualType = null; - } - - bioUtil.authenticateBiometrics(userId, individualType, list, registrationStatusDto, - StatusUtil.SUPERVISOR_AUTHENTICATION_FAILED.getMessage(), - StatusUtil.SUPERVISOR_AUTHENTICATION_FAILED.getCode()); - } - - /** - * get the individualId by userid - * - * @param userid - * @return individualId - * @throws ApisResourceAccessException - * @throws IOException - */ - private String getIndividualIdByUserId(String userid) throws ApisResourceAccessException, IOException { - - regProcLogger.debug("getIndividualIdByUserId called for userid {}", userid); - List pathSegments = new ArrayList<>(); - pathSegments.add(APPID); - pathSegments.add(userid); - String individualId = null; - ResponseWrapper response = null; - response = (ResponseWrapper) restClientService.getApi(ApiName.GETINDIVIDUALIDFROMUSERID, pathSegments, "", - "", ResponseWrapper.class); - regProcLogger.debug( - "getIndividualIdByUserId called for with GETINDIVIDUALIDFROMUSERID GET service call ended successfully"); - if (response.getErrors() != null) { - throw new ApisResourceAccessException( - PlatformErrorMessages.LINK_FOR_USERID_INDIVIDUALID_FAILED_SVM_EXCEPTION.toString()); - } else { - IndividualIdDto readValue = mapper.readValue(mapper.writeValueAsString(response.getResponse()), - IndividualIdDto.class); - individualId = readValue.getIndividualId(); - } - regProcLogger.debug("getIndividualIdByUserId call ended for userid {}", userid); - return individualId; - } - - /** - * Validate UMC cmapping. - * - * @param effectiveTimestamp the effective timestamp - * @param registrationCenterId the registration center id - * @param machineId the machine id - * @param superviserId the superviser id - * @param registrationStatusDto - * @throws IOException - * @throws BaseCheckedException - */ - private void validateUMCmapping(String effectiveTimestamp, String registrationCenterId, String machineId, - String supervisorId, InternalRegistrationStatusDto registrationStatusDto) - throws IOException, BaseCheckedException { - - List supervisorpathsegments = new ArrayList<>(); - supervisorpathsegments.add(effectiveTimestamp); - supervisorpathsegments.add(registrationCenterId); - supervisorpathsegments.add(machineId); - supervisorpathsegments.add(supervisorId); - - if (!validateMapping(supervisorpathsegments, registrationStatusDto)) { - throw new ValidationFailedException(StatusUtil.SUPERVISOR_NOT_ACTIVE.getMessage(), - StatusUtil.SUPERVISOR_NOT_ACTIVE.getCode()); - } - } - - private boolean validateMapping(List pathsegments, InternalRegistrationStatusDto registrationStatusDto) - throws IOException, BaseCheckedException { - boolean isValidUser = false; - ResponseWrapper responseWrapper; - RegistrationCenterUserMachineMappingHistoryResponseDto userDto = null; - - responseWrapper = (ResponseWrapper) restClientService.getApi(ApiName.CENTERUSERMACHINEHISTORY, - pathsegments, "", "", ResponseWrapper.class); - userDto = mapper.readValue(mapper.writeValueAsString(responseWrapper.getResponse()), - RegistrationCenterUserMachineMappingHistoryResponseDto.class); - regProcLogger.debug("validateMapping call ended for registrationId {} with response data {}", - registrationStatusDto.getRegistrationId(), JsonUtil.objectMapperObjectToJson(userDto)); - - if (responseWrapper.getErrors() != null) { - List error = responseWrapper.getErrors(); - regProcLogger.debug("validateMapping call ended for registrationId {} with error data {}", - registrationStatusDto.getRegistrationId(), error.get(0).getMessage()); - throw new BaseCheckedException(error.get(0).getMessage(), - StatusUtil.CENTER_DEVICE_MAPPING_NOT_FOUND.getCode()); - } else if (userDto != null) { - userDto.setRegistrationCenters(userDto.getRegistrationCenters().stream().filter(u ->u!=null && u.getIsActive()).collect(Collectors.toList())); - isValidUser = userDto.getRegistrationCenters()!=null && !userDto.getRegistrationCenters().isEmpty(); - } else { - regProcLogger.debug( - "validateMapping call ended with no erros and userDTO as null so considering as mapping not valid"); - isValidUser = false; - } - - return isValidUser; - } - -} +package io.mosip.registration.processor.stages.supervisorvalidator; + +import java.io.IOException; +import java.security.NoSuchAlgorithmException; +import java.security.spec.InvalidKeySpecException; +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + +import javax.xml.parsers.ParserConfigurationException; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.xml.sax.SAXException; + +import com.fasterxml.jackson.databind.ObjectMapper; + +import io.mosip.kernel.biometrics.entities.BIR; +import io.mosip.kernel.biometrics.entities.BiometricRecord; +import io.mosip.kernel.core.bioapi.exception.BiometricException; +import io.mosip.kernel.core.exception.BaseCheckedException; +import io.mosip.kernel.core.logger.spi.Logger; +import io.mosip.kernel.core.util.StringUtils; +import io.mosip.registration.processor.core.auth.dto.IndividualIdDto; +import io.mosip.registration.processor.core.code.ApiName; +import io.mosip.registration.processor.core.code.RegistrationExceptionTypeCode; +import io.mosip.registration.processor.core.common.rest.dto.ErrorDTO; +import io.mosip.registration.processor.core.constant.MappingJsonConstants; +import io.mosip.registration.processor.core.constant.ProviderStageName; +import io.mosip.registration.processor.core.exception.ApisResourceAccessException; +import io.mosip.registration.processor.core.exception.PacketDecryptionFailureException; +import io.mosip.registration.processor.core.exception.RegistrationProcessorCheckedException; +import io.mosip.registration.processor.core.exception.ValidationFailedException; +import io.mosip.registration.processor.core.exception.util.PlatformErrorMessages; +import io.mosip.registration.processor.core.http.ResponseWrapper; +import io.mosip.registration.processor.core.logger.RegProcessorLogger; +import io.mosip.registration.processor.core.packet.dto.RegOsiDto; +import io.mosip.registration.processor.core.packet.dto.ServerError; +import io.mosip.registration.processor.core.packet.dto.masterdata.UserResponseDto; +import io.mosip.registration.processor.core.packet.dto.regcentermachine.RegistrationCenterUserMachineMappingHistoryResponseDto; +import io.mosip.registration.processor.core.spi.restclient.RegistrationProcessorRestClientService; +import io.mosip.registration.processor.core.status.util.StatusUtil; +import io.mosip.registration.processor.core.util.JsonUtil; +import io.mosip.registration.processor.core.util.RegistrationExceptionMapperUtil; +import io.mosip.registration.processor.packet.storage.utils.BioSdkUtil; +import io.mosip.registration.processor.packet.storage.utils.PriorityBasedPacketManagerService; +import io.mosip.registration.processor.packet.storage.utils.Utilities; +import io.mosip.registration.processor.status.code.RegistrationStatusCode; +import io.mosip.registration.processor.status.dto.InternalRegistrationStatusDto; + +@Service +public class SupervisorValidator { + + private static Logger regProcLogger = RegProcessorLogger.getLogger(SupervisorValidator.class); + + private static final String ISTRUE = "true"; + + private static final String INDIVIDUAL_TYPE_USERID = "USERID"; + + private static final String APPID = "regproc"; + + @Autowired + RegistrationExceptionMapperUtil registrationExceptionMapperUtil; + + @Autowired + RegistrationProcessorRestClientService restClientService; + + @Autowired + private PriorityBasedPacketManagerService packetManagerService; + + @Autowired + private ObjectMapper mapper; + + @Autowired + private Utilities utility; + + @Autowired + private BioSdkUtil bioUtil; + + /** + * Checks if is valid Supervisor. + * + * @param registrationId the registration id + * @throws SAXException + * @throws ParserConfigurationException + * @throws io.mosip.kernel.core.exception.IOException + * @throws Exception + * @throws PacketDecryptionFailureException + * @throws RegistrationProcessorCheckedException + */ + public void validate(String registrationId, InternalRegistrationStatusDto registrationStatusDto, RegOsiDto regOsi) + throws Exception { + regProcLogger.debug("validate called for registrationId {}", registrationId); + + validateSupervisor(registrationId, regOsi, registrationStatusDto); + authenticateSupervisor(regOsi, registrationId, registrationStatusDto); + validateUMCmapping(regOsi.getPacketCreationDate(), regOsi.getRegcntrId(), regOsi.getMachineId(), + regOsi.getSupervisorId(), registrationStatusDto); + regProcLogger.debug("validate call ended for registrationId {}", registrationId); + } + + private void validateSupervisor(String registrationId, RegOsiDto regOsi, + InternalRegistrationStatusDto registrationStatusDto) throws IOException, BaseCheckedException { + String creationDate = regOsi.getPacketCreationDate(); + if (creationDate != null && !(StringUtils.isEmpty(creationDate))) { + if (!isActiveUser(creationDate, regOsi.getSupervisorId(), registrationStatusDto)) { + registrationStatusDto.setLatestTransactionStatusCode(registrationExceptionMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.SUPERVISOR_WAS_INACTIVE)); + registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.toString()); + regProcLogger.debug("ActiveUserId call ended for registrationId {} {}", registrationId, + StatusUtil.SUPERVISOR_WAS_INACTIVE.getMessage() + regOsi.getSupervisorId()); + throw new BaseCheckedException( + StatusUtil.SUPERVISOR_WAS_INACTIVE.getMessage() + regOsi.getSupervisorId(), + StatusUtil.SUPERVISOR_WAS_INACTIVE.getCode()); + } + + } else { + registrationStatusDto.setLatestTransactionStatusCode(registrationExceptionMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.PACKET_CREATION_DATE_NOT_PRESENT_IN_PACKET)); + registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.toString()); + regProcLogger.debug("ActiveUserId call ended for registrationId {}. packet creationDate is null", + registrationId); + throw new BaseCheckedException(StatusUtil.SUPERVISOR_PACKET_CREATION_DATE_NOT_FOUND_IN_PACKET.getMessage(), + StatusUtil.SUPERVISOR_PACKET_CREATION_DATE_NOT_FOUND_IN_PACKET.getCode()); + + } + } + + private boolean isActiveUser(String creationDate, String supervisorId, + InternalRegistrationStatusDto registrationStatusDto) throws IOException, BaseCheckedException { + boolean wasSupervisorActiveDuringPCT = false; + + if (supervisorId != null && !supervisorId.isEmpty()) { + UserResponseDto supervisorResponse = getUserDetails(supervisorId, creationDate, registrationStatusDto); + if (supervisorResponse.getErrors() == null) { + wasSupervisorActiveDuringPCT = supervisorResponse.getResponse().getUserResponseDto().get(0) + .getIsActive(); + if (!wasSupervisorActiveDuringPCT) { + regProcLogger.debug("isActiveUser call ended for registrationId {} {}", + registrationStatusDto.getRegistrationId(), StatusUtil.SUPERVISOR_WAS_INACTIVE.getMessage()); + } + } else { + List errors = supervisorResponse.getErrors(); + regProcLogger.debug("isActiveUser call ended with error {}", errors.get(0).getMessage()); + throw new BaseCheckedException( + StatusUtil.SUPERVISOR_AUTHENTICATION_FAILED.getMessage() + errors.get(0).getMessage(), + StatusUtil.SUPERVISOR_AUTHENTICATION_FAILED.getCode()); + } + } + return wasSupervisorActiveDuringPCT; + } + + private UserResponseDto getUserDetails(String operatorId, String creationDate, + InternalRegistrationStatusDto registrationStatusDto) throws ApisResourceAccessException, IOException { + UserResponseDto userResponse; + List pathSegments = new ArrayList<>(); + pathSegments.add(operatorId); + pathSegments.add(creationDate); + + userResponse = (UserResponseDto) restClientService.getApi(ApiName.USERDETAILS, pathSegments, "", "", + UserResponseDto.class); + regProcLogger.debug("isUserActive call ended with response data {}", + JsonUtil.objectMapperObjectToJson(userResponse)); + + return userResponse; + } + + /** + * To authenticate supervisor. + * + * @param regOsi the reg osi + * @param registrationId the registration id + * @param registrationStatusDto + * @throws SAXException + * @throws ParserConfigurationException + * @throws io.mosip.kernel.core.exception.IOException + * @throws PacketDecryptionFailureException + * @throws Exception + */ + private void authenticateSupervisor(RegOsiDto regOsi, String registrationId, + InternalRegistrationStatusDto registrationStatusDto) throws Exception { + String supervisorId = regOsi.getSupervisorId(); + + // officer password and otp check + String supervisiorPassword = regOsi.getSupervisorHashedPwd(); + String supervisorOTP = regOsi.getSupervisorOTPAuthentication(); + + String supervisorBiometricFileName = regOsi.getSupervisorBiometricFileName(); + + if (StringUtils.isEmpty(supervisorBiometricFileName) || supervisorBiometricFileName == null) { + if (!validateOtpAndPwd(supervisiorPassword, supervisorOTP)) { + registrationStatusDto.setLatestTransactionStatusCode(registrationExceptionMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.SUPERVISOR_PASSWORD_OTP_FAILURE)); + registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.toString()); + regProcLogger.debug("validateSupervisor call ended for registrationId {} {}", registrationId, + StatusUtil.SUPERVISOR_PASSWORD_OTP_FAILURE.getMessage() + supervisorId); + throw new ValidationFailedException(StatusUtil.SUPERVISOR_PASSWORD_OTP_FAILURE.getMessage() + supervisorId, + StatusUtil.SUPERVISOR_PASSWORD_OTP_FAILURE.getCode()); + } + } else { + BiometricRecord biometricRecord = packetManagerService.getBiometricsByMappingJsonKey(registrationId, + MappingJsonConstants.SUPERVISORBIOMETRICFILENAME, registrationStatusDto.getRegistrationType(), + ProviderStageName.SUPERVISOR_VALIDATOR); + + if (biometricRecord == null || biometricRecord.getSegments() == null + || biometricRecord.getSegments().isEmpty()) { + regProcLogger.error("validateSupervisor call ended for registrationId {} {}", registrationId, + "ERROR =======>" + StatusUtil.BIOMETRICS_VALIDATION_FAILURE.getMessage()); + registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.toString()); + throw new ValidationFailedException( + StatusUtil.BIOMETRICS_VALIDATION_FAILURE.getMessage() + " for Supervisor : " + supervisorId, + StatusUtil.BIOMETRICS_VALIDATION_FAILURE.getCode()); + } + validateUserBiometric(registrationId, supervisorId, biometricRecord.getSegments(), INDIVIDUAL_TYPE_USERID, + registrationStatusDto); + } + + } + + /** + * Validate opValidated and otpValidated. + * + * @param pwd the opValidated + * @param otp the otpValidated + * @return true, if successful + */ + private boolean validateOtpAndPwd(String opValidated, String otpValidated) { + return (opValidated != null && opValidated.equals(ISTRUE) || otpValidated != null && otpValidated.equals(ISTRUE)); + } + + /** + * Validate user. + * + * @param userId the userid + * @param registrationId the registration id + * @param list biometric data as BIR object + * @param individualType user type + * @param registrationStatusDto + * @throws Exception + * @throws SAXException + * @throws ParserConfigurationException + * @throws NoSuchAlgorithmException + * @throws InvalidKeySpecException + * @throws BiometricException + */ + + private void validateUserBiometric(String registrationId, String userId, List list, String individualType, + InternalRegistrationStatusDto registrationStatusDto) + throws Exception { + + if (INDIVIDUAL_TYPE_USERID.equalsIgnoreCase(individualType)) { + userId = getIndividualIdByUserId(userId); + individualType = null; + } + + bioUtil.authenticateBiometrics(userId, individualType, list, registrationStatusDto, + StatusUtil.SUPERVISOR_AUTHENTICATION_FAILED.getMessage(), + StatusUtil.SUPERVISOR_AUTHENTICATION_FAILED.getCode()); + } + + /** + * get the individualId by userid + * + * @param userid + * @return individualId + * @throws ApisResourceAccessException + * @throws IOException + */ + private String getIndividualIdByUserId(String userid) throws ApisResourceAccessException, IOException { + + regProcLogger.debug("getIndividualIdByUserId called for userid {}", userid); + List pathSegments = new ArrayList<>(); + pathSegments.add(APPID); + pathSegments.add(userid); + String individualId = null; + ResponseWrapper response = null; + response = (ResponseWrapper) restClientService.getApi(ApiName.GETINDIVIDUALIDFROMUSERID, pathSegments, "", + "", ResponseWrapper.class); + regProcLogger.debug( + "getIndividualIdByUserId called for with GETINDIVIDUALIDFROMUSERID GET service call ended successfully"); + if (response.getErrors() != null) { + throw new ApisResourceAccessException( + PlatformErrorMessages.LINK_FOR_USERID_INDIVIDUALID_FAILED_SVM_EXCEPTION.toString()); + } else { + IndividualIdDto readValue = mapper.readValue(mapper.writeValueAsString(response.getResponse()), + IndividualIdDto.class); + individualId = readValue.getIndividualId(); + } + regProcLogger.debug("getIndividualIdByUserId call ended for userid {}", userid); + return individualId; + } + + /** + * Validate UMC cmapping. + * + * @param effectiveTimestamp the effective timestamp + * @param registrationCenterId the registration center id + * @param machineId the machine id + * @param superviserId the superviser id + * @param registrationStatusDto + * @throws IOException + * @throws BaseCheckedException + */ + private void validateUMCmapping(String effectiveTimestamp, String registrationCenterId, String machineId, + String supervisorId, InternalRegistrationStatusDto registrationStatusDto) + throws IOException, BaseCheckedException { + + List supervisorpathsegments = new ArrayList<>(); + supervisorpathsegments.add(effectiveTimestamp); + supervisorpathsegments.add(registrationCenterId); + supervisorpathsegments.add(machineId); + supervisorpathsegments.add(supervisorId); + + if (!validateMapping(supervisorpathsegments, registrationStatusDto)) { + throw new ValidationFailedException(StatusUtil.SUPERVISOR_NOT_ACTIVE.getMessage(), + StatusUtil.SUPERVISOR_NOT_ACTIVE.getCode()); + } + } + + private boolean validateMapping(List pathsegments, InternalRegistrationStatusDto registrationStatusDto) + throws IOException, BaseCheckedException { + boolean isValidUser = false; + ResponseWrapper responseWrapper; + RegistrationCenterUserMachineMappingHistoryResponseDto userDto = null; + + responseWrapper = (ResponseWrapper) restClientService.getApi(ApiName.CENTERUSERMACHINEHISTORY, + pathsegments, "", "", ResponseWrapper.class); + userDto = mapper.readValue(mapper.writeValueAsString(responseWrapper.getResponse()), + RegistrationCenterUserMachineMappingHistoryResponseDto.class); + regProcLogger.debug("validateMapping call ended for registrationId {} with response data {}", + registrationStatusDto.getRegistrationId(), JsonUtil.objectMapperObjectToJson(userDto)); + + if (responseWrapper.getErrors() != null) { + List error = responseWrapper.getErrors(); + regProcLogger.debug("validateMapping call ended for registrationId {} with error data {}", + registrationStatusDto.getRegistrationId(), error.get(0).getMessage()); + throw new BaseCheckedException(error.get(0).getMessage(), + StatusUtil.CENTER_DEVICE_MAPPING_NOT_FOUND.getCode()); + } else if (userDto != null) { + userDto.setRegistrationCenters(userDto.getRegistrationCenters().stream().filter(u ->u!=null && u.getIsActive()).collect(Collectors.toList())); + isValidUser = userDto.getRegistrationCenters()!=null && !userDto.getRegistrationCenters().isEmpty(); + } else { + regProcLogger.debug( + "validateMapping call ended with no erros and userDTO as null so considering as mapping not valid"); + isValidUser = false; + } + + return isValidUser; + } + +} diff --git a/registration-processor/pre-processor/registration-processor-supervisor-validator-stage/src/main/java/io/mosip/registration/processor/stages/supervisorvalidator/SupervisorValidatorStage.java b/registration-processor/pre-processor/registration-processor-supervisor-validator-stage/src/main/java/io/mosip/registration/processor/stages/supervisorvalidator/SupervisorValidatorStage.java index 6825f69ea6d..c92bcb3d583 100644 --- a/registration-processor/pre-processor/registration-processor-supervisor-validator-stage/src/main/java/io/mosip/registration/processor/stages/supervisorvalidator/SupervisorValidatorStage.java +++ b/registration-processor/pre-processor/registration-processor-supervisor-validator-stage/src/main/java/io/mosip/registration/processor/stages/supervisorvalidator/SupervisorValidatorStage.java @@ -1,80 +1,80 @@ -package io.mosip.registration.processor.stages.supervisorvalidator; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.stereotype.Service; - -import io.mosip.registration.processor.core.abstractverticle.MessageBusAddress; -import io.mosip.registration.processor.core.abstractverticle.MessageDTO; -import io.mosip.registration.processor.core.abstractverticle.MosipEventBus; -import io.mosip.registration.processor.core.abstractverticle.MosipRouter; -import io.mosip.registration.processor.core.abstractverticle.MosipVerticleAPIManager; - -@Service -@Configuration -@ComponentScan(basePackages = { "${mosip.auth.adapter.impl.basepackage}", - "io.mosip.registration.processor.core.config", - "io.mosip.registration.processor.stages.config", "io.mosip.registration.processor.status.config", - "io.mosip.registration.processor.rest.client.config", "io.mosip.registration.processor.packet.storage.config", - "io.mosip.registration.processor.packet.manager.config", "io.mosip.registration.processor.core.kernel.beans","io.mosip.kernel.biosdk.provider.impl" }) -public class SupervisorValidatorStage extends MosipVerticleAPIManager { - - private static final String STAGE_PROPERTY_PREFIX = "mosip.regproc.supervisor-validator."; - - @Autowired - SupervisorValidationProcessor supervisorValidationProcessor; - - /** Mosip router for APIs */ - @Autowired - MosipRouter router; - - /** - * Vertx cluster configuration file URL, which ensures all verticle joins the - * same cluster - */ - @Value("${vertx.cluster.configuration}") - private String clusterManagerUrl; - - /** - * worker pool size is the maximum number of worker threads that will be used by - * the Vert.x instance - */ - @Value("${worker.pool.size}") - private Integer workerPoolSize; - - /** - * After this time intervel, message should be considered as expired (In - * seconds). - */ - @Value("${mosip.regproc.supervisor-validator.message.expiry-time-limit}") - private Long messageExpiryTimeLimit; - - /** The mosip event bus. */ - MosipEventBus mosipEventBus = null; - - public void deployVerticle() { - mosipEventBus = this.getEventBus(this, clusterManagerUrl, workerPoolSize); - this.consumeAndSend(mosipEventBus, MessageBusAddress.SUPERVISOR_VALIDATOR_BUS_IN, - MessageBusAddress.SUPERVISOR_VALIDATOR_BUS_OUT, messageExpiryTimeLimit); - } - - @Override - public void start() { - router.setRoute(this.postUrl(getVertx(), MessageBusAddress.SUPERVISOR_VALIDATOR_BUS_IN, - MessageBusAddress.SUPERVISOR_VALIDATOR_BUS_OUT)); - this.createServer(router.getRouter(), getPort()); - } - - @Override - public MessageDTO process(MessageDTO object) { - return supervisorValidationProcessor.process(object, getStageName()); - } - - @Override - protected String getPropertyPrefix() { - return STAGE_PROPERTY_PREFIX; - } - -} +package io.mosip.registration.processor.stages.supervisorvalidator; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.stereotype.Service; + +import io.mosip.registration.processor.core.abstractverticle.MessageBusAddress; +import io.mosip.registration.processor.core.abstractverticle.MessageDTO; +import io.mosip.registration.processor.core.abstractverticle.MosipEventBus; +import io.mosip.registration.processor.core.abstractverticle.MosipRouter; +import io.mosip.registration.processor.core.abstractverticle.MosipVerticleAPIManager; + +@Service +@Configuration +@ComponentScan(basePackages = { "${mosip.auth.adapter.impl.basepackage}", + "io.mosip.registration.processor.core.config", + "io.mosip.registration.processor.stages.config", "io.mosip.registration.processor.status.config", + "io.mosip.registration.processor.rest.client.config", "io.mosip.registration.processor.packet.storage.config", + "io.mosip.registration.processor.packet.manager.config", "io.mosip.registration.processor.core.kernel.beans","io.mosip.kernel.biosdk.provider.impl" }) +public class SupervisorValidatorStage extends MosipVerticleAPIManager { + + private static final String STAGE_PROPERTY_PREFIX = "mosip.regproc.supervisor-validator."; + + @Autowired + SupervisorValidationProcessor supervisorValidationProcessor; + + /** Mosip router for APIs */ + @Autowired + MosipRouter router; + + /** + * Vertx cluster configuration file URL, which ensures all verticle joins the + * same cluster + */ + @Value("${vertx.cluster.configuration}") + private String clusterManagerUrl; + + /** + * worker pool size is the maximum number of worker threads that will be used by + * the Vert.x instance + */ + @Value("${worker.pool.size}") + private Integer workerPoolSize; + + /** + * After this time intervel, message should be considered as expired (In + * seconds). + */ + @Value("${mosip.regproc.supervisor-validator.message.expiry-time-limit}") + private Long messageExpiryTimeLimit; + + /** The mosip event bus. */ + MosipEventBus mosipEventBus = null; + + public void deployVerticle() { + mosipEventBus = this.getEventBus(this, clusterManagerUrl, workerPoolSize); + this.consumeAndSend(mosipEventBus, MessageBusAddress.SUPERVISOR_VALIDATOR_BUS_IN, + MessageBusAddress.SUPERVISOR_VALIDATOR_BUS_OUT, messageExpiryTimeLimit); + } + + @Override + public void start() { + router.setRoute(this.postUrl(getVertx(), MessageBusAddress.SUPERVISOR_VALIDATOR_BUS_IN, + MessageBusAddress.SUPERVISOR_VALIDATOR_BUS_OUT)); + this.createServer(router.getRouter(), getPort()); + } + + @Override + public MessageDTO process(MessageDTO object) { + return supervisorValidationProcessor.process(object, getStageName()); + } + + @Override + protected String getPropertyPrefix() { + return STAGE_PROPERTY_PREFIX; + } + +} diff --git a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/abstractverticle/MosipEventBus.java b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/abstractverticle/MosipEventBus.java index 28d55f64c89..7ebc2e09c9e 100644 --- a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/abstractverticle/MosipEventBus.java +++ b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/abstractverticle/MosipEventBus.java @@ -52,9 +52,7 @@ public void consumeAndSend(MessageBusAddress fromAddress, MessageBusAddress toAd */ public void send(MessageBusAddress toAddress, MessageDTO message); - public void consumerHealthCheck(Handler eventHandler, - String address); + public void consumerHealthCheck(Handler eventHandler, String address); - public void senderHealthCheck(Handler eventHandler, - String address); + public void senderHealthCheck(Handler eventHandler, String address); } diff --git a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/abstractverticle/MosipRouter.java b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/abstractverticle/MosipRouter.java index d7f011cc097..eecf57d03e6 100644 --- a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/abstractverticle/MosipRouter.java +++ b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/abstractverticle/MosipRouter.java @@ -1,19 +1,15 @@ package io.mosip.registration.processor.core.abstractverticle; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - import brave.Tracer; +import io.mosip.kernel.core.authmanager.authadapter.spi.VertxAuthenticationProvider; import io.mosip.registration.processor.core.token.validation.TokenValidator; import io.mosip.registration.processor.core.tracing.VertxWrapperHandler; -import io.vertx.core.AsyncResult; import io.vertx.core.Handler; -import io.vertx.core.json.JsonObject; -import io.vertx.ext.auth.AuthProvider; -import io.vertx.ext.auth.User; import io.vertx.ext.web.Route; import io.vertx.ext.web.Router; import io.vertx.ext.web.RoutingContext; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; @Component public class MosipRouter { @@ -30,6 +26,9 @@ public class MosipRouter { @Autowired private Tracer tracer; + @Autowired + private VertxAuthenticationProvider authHandler; + /** * This method sets router for API * @@ -110,36 +109,8 @@ public Route get(String url) { * @param routingContext */ private void validateToken(RoutingContext routingContext) { - String token = routingContext.request().getHeader("Cookie"); String url = routingContext.normalisedPath(); - String userId = tokenValidator.validate(token, url); - - User user = new User() { - - @Override - public JsonObject principal() { - JsonObject principal = new JsonObject(); - principal.put("username", userId); - return principal; - } - - @Override - public User isAuthorized(String authority, Handler> resultHandler) { - return null; - } - - @Override - public User clearCache() { - return null; - } - - @Override - public void setAuthProvider(AuthProvider authProvider) { - } - - }; - routingContext.setUser(user); - routingContext.next(); + authHandler.addAuthFilter(routingContext, tokenValidator.getRole(url)); } diff --git a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/abstractverticle/MosipVerticleAPIManager.java b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/abstractverticle/MosipVerticleAPIManager.java index 680a7ca63ae..6baa39f6ec8 100644 --- a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/abstractverticle/MosipVerticleAPIManager.java +++ b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/abstractverticle/MosipVerticleAPIManager.java @@ -63,7 +63,7 @@ public abstract class MosipVerticleAPIManager extends MosipVerticleManager { private static Logger regProcLogger = RegProcessorLogger.getLogger(MosipVerticleAPIManager.class); - @Value("${mosip.regproc.health-check.handler-timeout:5000}") + @Value("${mosip.regproc.health-check.handler-timeout:2000}") private long healthCheckTimeOut; diff --git a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/abstractverticle/StageHealthCheckHandler.java b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/abstractverticle/StageHealthCheckHandler.java index bf0085e9f37..f35ac51bbb3 100644 --- a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/abstractverticle/StageHealthCheckHandler.java +++ b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/abstractverticle/StageHealthCheckHandler.java @@ -38,7 +38,6 @@ import io.mosip.kernel.core.exception.ExceptionUtils; import io.mosip.kernel.core.logger.spi.Logger; -import io.mosip.kernel.core.util.StringUtils; import io.mosip.kernel.core.virusscanner.spi.VirusScanner; import io.mosip.registration.processor.core.constant.HealthConstant; import io.mosip.registration.processor.core.constant.LoggerFileConstant; @@ -320,22 +319,20 @@ public void dispSpaceHealthChecker(Promise promise) { public void senderHealthHandler(Promise promise, Vertx vertx, MosipEventBus eventBus, String address) { try { eventBus.senderHealthCheck((healthCheckDto) -> { - try { + try { if (healthCheckDto.isEventBusConnected()) { - final JsonObject result = resultBuilder.create() - .add(HealthConstant.RESPONSE, HealthConstant.PING).build(); - promise.complete(Status.OK(result)); - } else { - final JsonObject result = resultBuilder.create() + final JsonObject result = resultBuilder.create() + .add(HealthConstant.RESPONSE, HealthConstant.PING).build(); + promise.complete(Status.OK(result)); + } else { + final JsonObject result = resultBuilder.create() .add(HealthConstant.ERROR, healthCheckDto.getFailureReason()).build(); - promise.complete(Status.KO(result)); - } - - } catch (Exception e) { - final JsonObject result = resultBuilder.create().add(HealthConstant.ERROR, e.getMessage()) - .build(); promise.complete(Status.KO(result)); } + } catch (Exception e) { + final JsonObject result = resultBuilder.create().add(HealthConstant.ERROR, e.getMessage()).build(); + promise.complete(Status.KO(result)); + } }, address); } catch (Exception e) { final JsonObject result = resultBuilder.create().add(HealthConstant.ERROR, e.getMessage()).build(); @@ -351,23 +348,22 @@ public void senderHealthHandler(Promise promise, Vertx vertx, MosipEvent public void consumerHealthHandler(Promise promise, Vertx vertx, MosipEventBus eventBus, String address) { try { eventBus.consumerHealthCheck((healthCheckDto) -> { - try { + try { if (healthCheckDto.isEventBusConnected()) { - final JsonObject result = resultBuilder.create() + final JsonObject result = resultBuilder.create() .add(HealthConstant.RESPONSE, healthCheckDto.isEventBusConnected()).build(); - promise.complete(Status.OK(result)); - } else { - final JsonObject result = resultBuilder.create() - .add(HealthConstant.ERROR, healthCheckDto.getFailureReason()).build(); - promise.complete(Status.KO(result)); - } - - } catch (Exception e) { + promise.complete(Status.OK(result)); + } else { final JsonObject result = resultBuilder.create() - .add(HealthConstant.ERROR, e.getMessage()).build(); + .add(HealthConstant.ERROR, healthCheckDto.getFailureReason()).build(); promise.complete(Status.KO(result)); } + + } catch (Exception e) { + final JsonObject result = resultBuilder.create().add(HealthConstant.ERROR, e.getMessage()).build(); + promise.complete(Status.KO(result)); + } }, address); } catch (Exception e) { final JsonObject result = resultBuilder.create().add(HealthConstant.ERROR, e.getMessage()).build(); diff --git a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/code/ApiName.java b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/code/ApiName.java index bfaaa1ae892..61fef27c7dc 100644 --- a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/code/ApiName.java +++ b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/code/ApiName.java @@ -197,6 +197,7 @@ public enum ApiName { IDREPOUPDATEDRAFT, IDREPOPUBLISHDRAFT, IDREPOEXTRACTBIOMETRICS, + IDREPODISCARDDRAFT, CREDENTIALREQUESTV2; } diff --git a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/eventbus/KafkaMosipEventBus.java b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/eventbus/KafkaMosipEventBus.java index 36de3006a39..630636391ed 100644 --- a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/eventbus/KafkaMosipEventBus.java +++ b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/eventbus/KafkaMosipEventBus.java @@ -433,8 +433,7 @@ private void resumePartition(TopicPartition topicPartition, Promise promis } @Override - public void consumerHealthCheck(Handler eventHandler, - String address) { + public void consumerHealthCheck(Handler eventHandler, String address) { HealthCheckDTO healthCheckDTO = new HealthCheckDTO(); String timeStamp = address + DateUtils.formatToISOString(DateUtils.getUTCCurrentDateTime()); logger.debug("Consumer health check started {}", @@ -447,16 +446,15 @@ public void consumerHealthCheck(Handler eventHandler, healthCheckDTO.setEventBusConnected(false); healthCheckDTO.setFailureReason(f.cause().getMessage()); } - logger.debug("Consumer health check ended {} {}", - timeStamp); + logger.debug("Consumer health check ended with isEventBusConnected {} {}", timeStamp, + healthCheckDTO.isEventBusConnected()); eventHandler.handle(healthCheckDTO); }); } @Override - public void senderHealthCheck(Handler eventHandler, - String address) { + public void senderHealthCheck(Handler eventHandler, String address) { // To be implemented correctly when we move to later versions of vertx and // current vertx kafka client does not offer any non intrusive way to check the // health of produce diff --git a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/eventbus/VertxMosipEventBus.java b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/eventbus/VertxMosipEventBus.java index 1ebf8df527a..de166e91d18 100644 --- a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/eventbus/VertxMosipEventBus.java +++ b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/eventbus/VertxMosipEventBus.java @@ -129,13 +129,11 @@ public void consumerHealthCheck(Handler eventHandler, String add HealthCheckDTO healthCheckDTO = new HealthCheckDTO(); healthCheckDTO.setEventBusConnected(isRegistered); eventHandler.handle(healthCheckDTO); - + } @Override - public void senderHealthCheck(Handler eventHandler, - String address) - { + public void senderHealthCheck(Handler eventHandler, String address) { HealthCheckDTO healthCheckDTO = new HealthCheckDTO(); try { vertx.eventBus().send(address, HealthConstant.PING); @@ -147,5 +145,4 @@ public void senderHealthCheck(Handler eventHandler, eventHandler.handle(healthCheckDTO); } } - } diff --git a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/exception/util/PlatformErrorMessages.java b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/exception/util/PlatformErrorMessages.java index 065d7b82399..7f3ab7664fa 100644 --- a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/exception/util/PlatformErrorMessages.java +++ b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/exception/util/PlatformErrorMessages.java @@ -1,1485 +1,1483 @@ -package io.mosip.registration.processor.core.exception.util; - -import io.mosip.registration.processor.core.status.util.StatusConstants; - -// TODO: Auto-generated Javadoc -/** - * The Enum RPRPlatformErrorMessages. - * - * @author M1047487 - */ -public enum PlatformErrorMessages { - - /** The rpr pkr packet not yet sync. */ - // Packet Receiver Exception error code and message - RPR_PKR_PACKET_NOT_YET_SYNC(PlatformConstants.RPR_PACKET_RECEIVER_MODULE + "001", "Packet Not Found in Sync Table"), - - /** The rpr pkr invalid packet size. */ - RPR_PKR_INVALID_PACKET_SIZE(PlatformConstants.RPR_PACKET_RECEIVER_MODULE + "002", "Invalid Packet Size"), - RPR_WORKFLOW_SEARCH_API_FAILED(PlatformConstants.RPR_WORKFLOW_SEARCH_API + "000", - "Process the workflow search failed"), - - /** The rpr pkr packet hash not equals synced hash. */ - RPR_PKR_PACKET_HASH_NOT_EQUALS_SYNCED_HASH(PlatformConstants.RPR_PACKET_RECEIVER_MODULE + "009", - "Packet HashSequence did not match"), - /** The prp pkr packet virus scan failed. */ - PRP_PKR_PACKET_VIRUS_SCAN_FAILED(PlatformConstants.RPR_PACKET_RECEIVER_MODULE + "010", "Virus was Found in Packet"), - /** The prp pkr packet virus scanner service failed. */ - PRP_PKR_PACKET_VIRUS_SCANNER_SERVICE_FAILED(PlatformConstants.RPR_PACKET_RECEIVER_MODULE + "008", - "Virus Scan Service is Not Responding"), - - /** The rpr pkr invalid packet format. */ - RPR_PKR_INVALID_PACKET_FORMAT(PlatformConstants.RPR_PACKET_RECEIVER_MODULE + "003", "Invalid Packet Format"), - - /** The rpr pkr validation exception. */ - RPR_PKR_VALIDATION_EXCEPTION(PlatformConstants.RPR_PACKET_RECEIVER_MODULE + "004", "Packet Validation Failed"), - - /** The rpr pkr duplicate packet recieved. */ - RPR_PKR_DUPLICATE_PACKET_RECIEVED(PlatformConstants.RPR_PACKET_RECEIVER_MODULE + "005", - "Duplicate Request Received"), - - /** The rpr pkr packet not available. */ - RPR_PKR_PACKET_NOT_AVAILABLE(PlatformConstants.RPR_PACKET_RECEIVER_MODULE + "006", - "Packet Not Available in Request"), - - /** The rpr pkr unknown exception. */ - RPR_PKR_UNKNOWN_EXCEPTION(PlatformConstants.RPR_PACKET_RECEIVER_MODULE + "007", "Unknown Exception Found"), - - /** The rpr pkr api resouce access failed. */ - RPR_PKR_API_RESOUCE_ACCESS_FAILED(PlatformConstants.RPR_PACKET_RECEIVER_MODULE + "011", - "Unable to Access API Resource"), - - /** The rpr pkr data access exception. */ - RPR_PKR_DATA_ACCESS_EXCEPTION(PlatformConstants.RPR_PACKET_RECEIVER_MODULE + "012", "Unable to Access Database"), - - /** The rpr pkr invalid packet size synced. */ - RPR_PKR_INVALID_PACKET_SIZE_SYNCED(PlatformConstants.RPR_PACKET_RECEIVER_MODULE + "013", - "Packet Size is Not Matching"), - - /** The rpr pkr invalid packet size synced. */ - UNEQUAL_PACKET_HASH_PR(PlatformConstants.RPR_PACKET_RECEIVER_MODULE + "014", - "The Registration Packet HashSequence is not equal as synced packet HashSequence"), - - /** The rpr pkr invalid packet size synced. */ - RPR_PKR_DECRYPTION_FAILED(PlatformConstants.RPR_PACKET_RECEIVER_MODULE + "015", "Packet Decryption Failed"), - - /** The rpr pkr invalid packet size synced. */ - RPR_PKR_ADDITIONAL_INFOID_NOT_FOUND(PlatformConstants.RPR_PACKET_RECEIVER_MODULE + "016", "Additional info request id not found"), - - /** The rpr rgs registration table not accessible. */ - // Registration Status Exception error code and message - RPR_RGS_REGISTRATION_TABLE_NOT_ACCESSIBLE(PlatformConstants.RPR_REGISTRATION_STATUS_MODULE + "001", - "Unable to Access Registration Table"), - - /** The rpr rgs transaction table not accessible. */ - RPR_RGS_TRANSACTION_TABLE_NOT_ACCESSIBLE(PlatformConstants.RPR_REGISTRATION_STATUS_MODULE + "002", - "Unable to Access Registration Transaction Table"), - - /** The rpr rgs anonymous profile table not accessible. */ - RPR_RGS_ANONYMOUS_PROFILE_TABLE_NOT_ACCESSIBLE(PlatformConstants.RPR_REGISTRATION_STATUS_MODULE + "038", - "Unable to anonymous profile Table"), - - /** The rpr rgs invalid synctype. */ - RPR_RGS_INVALID_SYNCTYPE(PlatformConstants.RPR_REGISTRATION_STATUS_MODULE + "003", "Invalid Sync Type"), - - /** The rpr rgs invalid languagecode. */ - RPR_RGS_INVALID_LANGUAGECODE(PlatformConstants.RPR_REGISTRATION_STATUS_MODULE + "004", - "Invalid Language Code - Language Code must be of Three Characters"), - - /** The rpr rgs invalid regid parentregid. */ - RPR_RGS_INVALID_REGID_PARENTREGID(PlatformConstants.RPR_REGISTRATION_STATUS_MODULE + "005", - "Invalid Request Value - RID and Parent RID are Same"), - - /** The rpr rgs empty registrationid. */ - RPR_RGS_EMPTY_REGISTRATIONID(PlatformConstants.RPR_REGISTRATION_STATUS_MODULE + "006", - "Invalid Request Value - RID cannot be NULL"), - - /** The rpr rgs invalid registrationid timestamp. */ - RPR_RGS_INVALID_REGISTRATIONID_TIMESTAMP(PlatformConstants.RPR_REGISTRATION_STATUS_MODULE + "007", - "Invalid Request Value - Invalid Timestamp in RID"), - - /** The rpr rgs invalid registrationid. */ - RPR_RGS_INVALID_REGISTRATIONID(PlatformConstants.RPR_REGISTRATION_STATUS_MODULE + "008", - "Invalid Request Value - RID must be Numberic"), - - /** The rpr rgs invalid registrationid length. */ - RPR_RGS_INVALID_REGISTRATIONID_LENGTH(PlatformConstants.RPR_REGISTRATION_STATUS_MODULE + "009", - "Invalid Request Value - RID Length is not as per Configuration"), - - /** The rpr rgs invalid prid timestamp. */ - RPR_RGS_INVALID_PRID_TIMESTAMP(PlatformConstants.RPR_REGISTRATION_STATUS_MODULE + "010", - "Invalid Request Value - Invalid Timestamp in Parent RID"), - - /** The rpr rgs invalid prid. */ - RPR_RGS_INVALID_PRID(PlatformConstants.RPR_REGISTRATION_STATUS_MODULE + "011", - "Invalid Request Value - Parent RID must be Numeric"), - - /** The rpr rgs invalid prid length. */ - RPR_RGS_INVALID_PRID_LENGTH(PlatformConstants.RPR_REGISTRATION_STATUS_MODULE + "012", - "Invalid Request Value - Parent RID Length is not as per Configuration"), - - /** The missing input parameter. */ - RPR_RGS_MISSING_INPUT_PARAMETER(PlatformConstants.RPR_REGISTRATION_STATUS_MODULE + "013", - "Missing Request Value - %s"), - - /** The invalid input parameter. */ - RPR_RGS_INVALID_INPUT_PARAMETER(PlatformConstants.RPR_REGISTRATION_STATUS_MODULE + "014", - "Invalid Request Value - %s"), - - /** The data validation failed. */ - RPR_RGS_DATA_VALIDATION_FAILED(PlatformConstants.RPR_REGISTRATION_STATUS_MODULE + "015", - "Invalid Request Value - Input Data is Incorrect"), - - /** The rpr rgs json mapping exception. */ - RPR_RGS_JSON_MAPPING_EXCEPTION(PlatformConstants.RPR_REGISTRATION_STATUS_MODULE + "016", "JSON Mapping Failed"), - - /** The rpr rgs json parsing exception. */ - RPR_RGS_JSON_PARSING_EXCEPTION(PlatformConstants.RPR_REGISTRATION_STATUS_MODULE + "017", "JSON Parsing Failed"), - - /** The rpr rgs unknown exception. */ - RPR_RGS_UNKNOWN_EXCEPTION(PlatformConstants.RPR_REGISTRATION_STATUS_MODULE + "018", "Unknown Exception Found"), - - /** The rpr rgs missing input parameter version. */ - RPR_RGS_MISSING_INPUT_PARAMETER_VERSION(PlatformConstants.RPR_REGISTRATION_STATUS_MODULE + "019", - "Missing Request Value - version"), - - /** The rpr rgs missing input parameter timestamp. */ - RPR_RGS_MISSING_INPUT_PARAMETER_TIMESTAMP(PlatformConstants.RPR_REGISTRATION_STATUS_MODULE + "020", - "Missing Request Parameter - requesttime"), - - /** The rpr rgs missing input parameter id. */ - RPR_RGS_MISSING_INPUT_PARAMETER_ID(PlatformConstants.RPR_REGISTRATION_STATUS_MODULE + "021", - "Missing Request Parameter - id"), - - /** The rpr rgs invalid input parameter version. */ - RPR_RGS_INVALID_INPUT_PARAMETER_VERSION(PlatformConstants.RPR_REGISTRATION_STATUS_MODULE + "022", - "Invalid Request Parameter - version"), - - /** The rpr rgs invalid input parameter timestamp. */ - RPR_RGS_INVALID_INPUT_PARAMETER_TIMESTAMP(PlatformConstants.RPR_REGISTRATION_STATUS_MODULE + "023", - "Invalid Request Parameter - requesttime"), - - /** The rpr rgs invalid input parameter id. */ - RPR_RGS_INVALID_INPUT_PARAMETER_ID(PlatformConstants.RPR_REGISTRATION_STATUS_MODULE + "024", - "Invalid Request Parameter - id"), - - /** The rpr rgs registration status not exist. */ - RPR_RGS_REGISTRATION_STATUS_NOT_EXIST(PlatformConstants.RPR_REGISTRATION_STATUS_MODULE + "025", - "Invalid Request Value - Status Code is NULL"), - - /** The rpr rgs invalid supervisor status. */ - RPR_RGS_INVALID_SUPERVISOR_STATUS(PlatformConstants.RPR_REGISTRATION_STATUS_MODULE + "026", - "Invalid Request Value - Supervisor Status can be APPROVED/REJECTED"), - - /** The rpr rgs invalid hashvalue. */ - RPR_RGS_INVALID_HASHVALUE(PlatformConstants.RPR_REGISTRATION_STATUS_MODULE + "027", - "Invalid Request Value - Hash Sequence is NULL"), - - /** The rpr rgs decryption failed. */ - RPR_RGS_DECRYPTION_FAILED(PlatformConstants.RPR_REGISTRATION_STATUS_MODULE + "028", "Request Decryption Failed"), - - /** The rpr rgs registration sync service failed. */ - RPR_RGS_REGISTRATION_SYNC_SERVICE_FAILED(PlatformConstants.RPR_REGISTRATION_STATUS_MODULE + "029", "SYNC Failed"), - - /** The rpr rgs data access exception. */ - RPR_RGS_DATA_ACCESS_EXCEPTION(PlatformConstants.RPR_REGISTRATION_STATUS_MODULE + "030", - "DataAccessLayerException while syncing Registartion Id's"), - /** The rpr rgs rid not found. */ - RPR_RGS_RID_NOT_FOUND(PlatformConstants.RPR_REGISTRATION_STATUS_MODULE + "031", "RID Not Found"), - - RPR_RGS_INVALID_ADDITIONAL_INFORMATION(PlatformConstants.RPR_REGISTRATION_STATUS_MODULE + "036", "additionalInfoReqId is invalid"), - - RPR_RGS_PACKETID_NOT_FOUND(PlatformConstants.RPR_REGISTRATION_STATUS_MODULE + "037", "PacketId Not Found"), - - RPR_RGS_INVALID_SEARCH(PlatformConstants.RPR_REGISTRATION_STATUS_MODULE + "032", "plz narrow down your search"), - - RPR_RGS_SORTING_VALIDATION_FAILED(PlatformConstants.RPR_REGISTRATION_STATUS_MODULE + "033", - "sorting not supported for more than 1 field - %s"), - - RPR_RGS_DATE_VALIDATION_FAILED(PlatformConstants.RPR_REGISTRATION_STATUS_MODULE + "034", - "searching between date should be less then 30 days - %s"), - - /** The rpr rgs io exception */ - RPR_RGS_IOEXCEPTION(PlatformConstants.RPR_REGISTRATION_STATUS_MODULE + "035" , "IO Exception"), - - LINK_FOR_USERID_INDIVIDUALID_FAILED_STATUS_EXCEPTION(PlatformConstants.RPR_REGISTRATION_STATUS_MODULE + "035", - "Unable to get the IndividualId for UserId"), - - UNABLE_TO_ACCESS_API(PlatformConstants.RPR_REGISTRATION_STATUS_MODULE + "036", - "Unable to access API"), - - /** The rpr pis registration table not accessible. */ - // Packet Info Storage Exception error code and message - RPR_PIS_REGISTRATION_TABLE_NOT_ACCESSIBLE(PlatformConstants.RPR_PACKET_INFO_STORAGE_MODULE + "001", - "Unable to Access Registration Table"), - /** The rpr pis identity not found. */ - RPR_PIS_IDENTITY_NOT_FOUND(PlatformConstants.RPR_PACKET_INFO_STORAGE_MODULE + "002", - "Unable to Find Identity Field in ID JSON"), - /** The rpr pis unable to insert data. */ - RPR_PIS_UNABLE_TO_INSERT_DATA(PlatformConstants.RPR_PACKET_INFO_STORAGE_MODULE + "003", - "Unable to Insert Data in DB"), - /** The rpr pis file not found in Packet Store. */ - RPR_PIS_FILE_NOT_FOUND_IN_PACKET_STORE(PlatformConstants.RPR_PACKET_INFO_STORAGE_MODULE + "004", - "Unable to Find File in Packet Store"), - - /** The rpr pis abis queue connection null. */ - RPR_PIS_ABIS_QUEUE_CONNECTION_NULL(PlatformConstants.RPR_PACKET_INFO_STORAGE_MODULE + "005", - "Unable to Find ABIS Queue Connection"), - - GET_FIELD_ERROR(PlatformConstants.RPR_PACKET_INFO_STORAGE_MODULE + "006", - "Not able to read field from packet manager"), - - GET_DOC_ERROR(PlatformConstants.RPR_PACKET_INFO_STORAGE_MODULE + "007", - "Not able to read document from packet manager"), - - GET_BIOMETRIC_ERROR(PlatformConstants.RPR_PACKET_INFO_STORAGE_MODULE + "008", - "Not able to read biometric from packet manager"), - - GET_AUDIT_ERROR(PlatformConstants.RPR_PACKET_INFO_STORAGE_MODULE + "009", - "Not able to read audit from packet manager"), - - GET_METAINFO_ERROR(PlatformConstants.RPR_PACKET_INFO_STORAGE_MODULE + "010", - "Not able to read meta info from packet manager"), - - VALIDATE_ERROR(PlatformConstants.RPR_PACKET_INFO_STORAGE_MODULE + "011", - "Not able to validate packet using packet manager provider."), - - PACKET_MANAGER_EXCEPTION(PlatformConstants.RPR_PACKET_INFO_STORAGE_MODULE + "012", - "Exception occured in packet manager."), - - /** The rpr fac connection not available. */ - // File adaptor Exception error code and message - RPR_FAC_CONNECTION_NOT_AVAILABLE(PlatformConstants.RPR_FILESYSTEM_ADAPTOR_CEPH_MODULE + "001", - "Unable to Find Connection Parameter for Packet Store"), - - /** The rpr fac invalid connection parameters. */ - RPR_FAC_INVALID_CONNECTION_PARAMETERS(PlatformConstants.RPR_FILESYSTEM_ADAPTOR_CEPH_MODULE + "002", - "Invalid Connection Parameter for Packet Store"), - - /** The rpr fac packet not available. */ - RPR_FAC_PACKET_NOT_AVAILABLE(PlatformConstants.RPR_FILESYSTEM_ADAPTOR_CEPH_MODULE + "003", - "Packet Not Found in Packet Store"), - - /** The rpr pkm file path not accessible. */ - // Packet Manager Exception error code and message - RPR_PKM_FILE_PATH_NOT_ACCESSIBLE(PlatformConstants.RPR_PACKET_MANAGER_MODULE + "002", - "Unable to Access the Folder Path"), - - /** The rpr pkm file not found in destination. */ - RPR_PKM_FILE_NOT_FOUND_IN_DESTINATION(PlatformConstants.RPR_PACKET_MANAGER_MODULE + "003", - "Unable to Find File in Destination Folder"), - - /** The rpr pkm file not found in source. */ - RPR_PKM_FILE_NOT_FOUND_IN_SOURCE(PlatformConstants.RPR_PACKET_MANAGER_MODULE + "004", - "Unable to Find File in Source Folder"), - - /** The rpr pkm file not found in source. */ - RPR_PKM_JSCH_NOT_CONNECTED(PlatformConstants.RPR_PACKET_MANAGER_MODULE + "005", "JSCH Connection Failed"), - - /** The rpr pkm file not found in source. */ - RPR_PKM_SFTP_FILE_OPERATION_FAILED(PlatformConstants.RPR_PACKET_MANAGER_MODULE + "006", "SFTP Operation Failed"), - - /** The rpr pkm file not found in source. */ - RPR_PKM_PWD_PPK_NOT_PRESENT(PlatformConstants.RPR_PACKET_MANAGER_MODULE + "007", - "Both DMZ password and PPK file name are not available in config"), - - // Registration processor camel bridge Exception error code and message - - /** The rpr cmb deployment failure. */ - RPR_CMB_DEPLOYMENT_FAILURE(PlatformConstants.RPR_CAMEL_BRIDGE_MODULE + "001", "Camel Bridge Deployment Failure"), - - /** The rpr cmb unsupported encoding. */ - RPR_CMB_UNSUPPORTED_ENCODING(PlatformConstants.RPR_CAMEL_BRIDGE_MODULE + "002", "Unsupported Failure"), - - /** The rpr cmb configuration server failure exception. */ - RPR_CMB_CONFIGURATION_SERVER_FAILURE_EXCEPTION(PlatformConstants.RPR_CAMEL_BRIDGE_MODULE + "003", - "Configuration Server Failure"), - - /** The rpr cmb malformed cluster manager url exception. */ - RPR_CMB_MALFORMED_URL_EXCEPTION(PlatformConstants.RPR_CAMEL_BRIDGE_MODULE + "004", - "Malformed Cluster Manager URL Exception"), - - /** The rpr cmb unknown host exception. */ - RPR_CMB_UNKNOWN_HOST_EXCEPTION(PlatformConstants.RPR_CAMEL_BRIDGE_MODULE + "005", "Unknown Host Exception"), - - - RPR_CMB_WORKFLOW_COMMAND_NOT_SUPPORTED(PlatformConstants.RPR_CAMEL_BRIDGE_MODULE + "006", - "Workflow command not supported"), - - /** The rpr qcr registration table not accessible. */ - // Quality Checker Exception error code and message - RPR_QCR_REGISTRATION_TABLE_NOT_ACCESSIBLE(PlatformConstants.RPR_QUALITY_CHECKER_MODULE + "001", - "Unable to Access Registration Table"), - - /** The rpr qcr result not found. */ - RPR_QCR_RESULT_NOT_FOUND(PlatformConstants.RPR_QUALITY_CHECKER_MODULE + "002", "Result Not Found"), - - /** The rpr qcr invalid qc user id. */ - RPR_QCR_INVALID_QC_USER_ID(PlatformConstants.RPR_QUALITY_CHECKER_MODULE + "003", "Invalid QC User ID"), - - /** The rpr qcr invalid registration id. */ - RPR_QCR_INVALID_REGISTRATION_ID(PlatformConstants.RPR_QUALITY_CHECKER_MODULE + "004", - "Invalid Registration ID - RID is NULL"), - - /** The rpr qcr file name missing. */ - RPR_QCR_FILENAME_MISSING(PlatformConstants.RPR_QUALITY_CHECKER_MODULE + "006", - "Unable to Find Biometric File Name in ID JSON"), - - /** The rpr qcr bio file missing. */ - RPR_QCR_BIO_FILE_MISSING(PlatformConstants.RPR_QUALITY_CHECKER_MODULE + "007", - "Unable to Find Biometric File in Packet"), - - /** The rpr qcr biometric exception. */ - RPR_QCR_BIOMETRIC_EXCEPTION(PlatformConstants.RPR_QUALITY_CHECKER_MODULE + "007", - "Biometric Exception received form IDA"), - - /** The rpr qcr biometric exception. */ - RPR_QCR_BIOMETRIC_TYPE_EXCEPTION(PlatformConstants.RPR_QUALITY_CHECKER_MODULE + "008", - "Requested biometric type not found"), - - /** The rpr qcr biometric exception. */ - INDIVIDUAL_BIOMETRIC_NOT_FOUND(PlatformConstants.RPR_QUALITY_CHECKER_MODULE + "009", - "Individual Biometric Parameter Not Found in ID JSON so skipping biometric classification"), - - /** The rpr qcr biometric exception. */ - BIOMETRIC_QUALITY_CHECK_FAILED(PlatformConstants.RPR_QUALITY_CHECKER_MODULE + "010", - "Quality Score of Biometrics Captured is Below the Threshold"), - - /** The rpr qcr packet store not accessible. */ - RPR_QCR_PACKET_STORE_NOT_ACCESSIBLE(PlatformConstants.RPR_QUALITY_CHECKER_MODULE + "011", - "The Packet store set by the System is not accessible"), - - /** The packet upload failed. */ - PACKET_UPLOAD_FAILED("", "Packet Upload failed"), - - /** The structural validation failed. */ - // Stages - Packet validator Exception error code and message - STRUCTURAL_VALIDATION_FAILED(PlatformConstants.RPR_PACKET_VALIDATOR_MODULE + "015", "Structural Validation Failed"), - - /** The rpr pvm data not available. */ - RPR_PVM_DATA_NOT_AVAILABLE(PlatformConstants.RPR_PACKET_VALIDATOR_MODULE + "002", - "Data Not Available in Master DB"), - /** The rpr pvm update packet deactivated. */ - RPR_PVM_UPDATE_DEACTIVATED(PlatformConstants.RPR_PACKET_VALIDATOR_MODULE + "014", "UIN is Deactivated"), - - /** The rpr pvm identity not found. */ - RPR_PVM_IDENTITY_NOT_FOUND(PlatformConstants.RPR_PACKET_VALIDATOR_MODULE + "003", - "Attribute Not Available in ID JSON for Master Data Validation"), - - /** The rpr pvm resource not found. */ - RPR_PVM_RESOURCE_NOT_FOUND(PlatformConstants.RPR_PACKET_VALIDATOR_MODULE + "004", - "Resource Not Found for Master Data Validation"), - - /** The rpr pvm identity invalid. */ - RPR_PVM_IDENTITY_INVALID(PlatformConstants.RPR_PACKET_VALIDATOR_MODULE + "005", - "Invalid Attribute Value for Master Data Validation"), - - /** The rpr pvm api resouce access failed. */ - RPR_PVM_API_RESOUCE_ACCESS_FAILED(PlatformConstants.RPR_PACKET_VALIDATOR_MODULE + "006", - "Unable to Access API Resource"), - - /** The rpr pvm base unchecked exception. */ - RPR_PVM_BASE_UNCHECKED_EXCEPTION(PlatformConstants.RPR_PACKET_VALIDATOR_MODULE + "007", - "ID Schema Validation Failed"), - - /** The rpr pvm base checked exception. */ - RPR_PVM_BASE_CHECKED_EXCEPTION(PlatformConstants.RPR_PACKET_VALIDATOR_MODULE + "013", - "ID Schema Validation Failed"), - - /** The rpr pvm mandatory field missing. */ - RPR_PVM_MANDATORY_FIELD_MISSING(PlatformConstants.RPR_PACKET_VALIDATOR_MODULE + "010", - "Mandatory Field Validation Failed"), - - /** The rpr pvm record not matched from sync table. */ - RPR_PVM_RECORD_NOT_MATCHED_FROM_SYNC_TABLE(PlatformConstants.RPR_PACKET_VALIDATOR_MODULE + "011", - "RID or Registration Type Mismatch"), - - /** The rpr pvm invalid uin. */ - RPR_PVM_INVALID_UIN(PlatformConstants.RPR_PACKET_VALIDATOR_MODULE + "012", "Invalid UIN"), - - /** The rpr pvm document type invalid. */ - RPR_PVM_DOCUMENT_TYPE_INVALID(PlatformConstants.RPR_PACKET_VALIDATOR_MODULE + "008", - "Invalid Document Type for Document Validation"), - - /** The rpr pvm idjson not found. */ - RPR_PVM_IDJSON_NOT_FOUND(PlatformConstants.RPR_PACKET_VALIDATOR_MODULE + "009", "ID JSON Not Found"), - - /** The rpr pvm applicantdocument validation failed. */ - RPR_PVM_APPLICANTDOCUMENT_VALIDATION_FAILED(PlatformConstants.RPR_PACKET_VALIDATOR_MODULE + "010", - "Applicant Document Validation Failed"), - - RPR_PVM_PACKET_REJECTED(PlatformConstants.RPR_PACKET_VALIDATOR_MODULE + "011", - "Rejected by Supervisor"), - - RPR_PVM_PACKET_CREATED_DATE_TIME_EMPTY_OR_NULL(PlatformConstants.RPR_PACKET_VALIDATOR_MODULE + "017", - "Packet Created Date time is Null or Empty"), - - RPR_PVM_PACKET_CREATED_DATE_TIME_PARSE_EXCEPTION(PlatformConstants.RPR_PACKET_VALIDATOR_MODULE + "018", - "Packet Created Date time is not in correct format"), - - RPR_PVM_INVALID_ARGUMENT_EXCEPTION(PlatformConstants.RPR_PACKET_VALIDATOR_MODULE + "019", - "Invalid Argument"), - - - /** The packet classification failed. */ - PACKET_CLASSIFICATION_FAILED(PlatformConstants.RPR_PACKET_CLASSIFIER_MODULE + "000", "Packet Classification failed"), - - /** The rpr pcm base unchecked exception. */ - RPR_PCM_BASE_UNCHECKED_EXCEPTION(PlatformConstants.RPR_PACKET_CLASSIFIER_MODULE + "001", - "Packet Classification failed"), - - /** The rpr pcm base checked exception. */ - RPR_PCM_BASE_CHECKED_EXCEPTION(PlatformConstants.RPR_PACKET_CLASSIFIER_MODULE + "002", - "Tag generation failed"), - - /** The rpr pcm idobject required field name fetching failed. */ - RPR_PCM_COLLECT_IDOBJECT_FIELD_FAILED(PlatformConstants.RPR_PACKET_CLASSIFIER_MODULE + "003", - "Getting the required Id object field names from tag generator failed"), - - /** The rpr pcm accessing idobject mapping file failed. */ - RPR_PCM_ACCESSING_IDOBJECT_MAPPING_FILE_FAILED(PlatformConstants.RPR_PACKET_CLASSIFIER_MODULE + "004", - "Accessing Idobject mapping file filed"), - - /** The rpr pcm unknown schema data type found. */ - RPR_PCM_UNKNOWN_SCHEMA_DATA_TYPE(PlatformConstants.RPR_PACKET_CLASSIFIER_MODULE + "005", - "Field's schema data type is not supported"), - - /** The rpr pcm schema data type json parsing failed. */ - RPR_PCM_SCHEMA_DATA_TYPE_JSON_PARSING_FAILED(PlatformConstants.RPR_PACKET_CLASSIFIER_MODULE + "006", - "JSON parsing of field value according to the schema type failed"), - - /** The rpr pcm data object mapping failed. */ - RPR_PCM_DATA_OBJECT_MAPPING_FAILED(PlatformConstants.RPR_PACKET_CLASSIFIER_MODULE + "007", - "JSON parsing to java object failed"), - - /** The rpr pcm meta info json parsing failed. */ - RPR_PCM_META_INFO_JSON_PARSING_FAILED(PlatformConstants.RPR_PACKET_CLASSIFIER_MODULE + "008", - "JSON parsing of meta info failed"), - - /** The rpr pcm mapping field name is not present in identity mapping json. */ - RPR_PCM_FIELD_NAME_NOT_AVAILABLE_IN_MAPPING_JSON(PlatformConstants.RPR_PACKET_CLASSIFIER_MODULE + "009", - "Mapping field name is not present in identity mapping json"), - - /** The rpr pcm value not available in configured language. */ - RPR_PCM_VALUE_NOT_AVAILABLE_IN_CONFIGURED_LANGUAGE(PlatformConstants.RPR_PACKET_CLASSIFIER_MODULE + "010", - "Value not available in configured language for field"), - - /** The rpr pcm fieldDTO or non string field value is null. */ - RPR_PCM_FIELD_DTO_OR_NON_STRING_FIELD_IS_NULL(PlatformConstants.RPR_PACKET_CLASSIFIER_MODULE + "011", - "FieldDTO or non string field value is null"), - - /** The rpr pcm sync registration entity not available null. */ - RPR_PCM_SYNC_REGISTRATION_ENTITY_NOT_AVAILABLE(PlatformConstants.RPR_PACKET_CLASSIFIER_MODULE + "012", - "sync registration entity not available"), - - /** The rpr pcm exception biometrics entry not avaiable in metainfo map. */ - RPR_PCM_EXCEPTION_BIOMETRICS_ENTRY_NOT_AVAILABLE(PlatformConstants.RPR_PACKET_CLASSIFIER_MODULE + "013", - "ExceptionBiometrics entry not available in metainfo map"), - - /** The rpr pcm operations data entry not avaiable in metainfo map. */ - RPR_PCM_OPERATIONS_DATA_ENTRY_NOT_AVAILABLE(PlatformConstants.RPR_PACKET_CLASSIFIER_MODULE + "014", - "Operations data entry not avaiable in metainfo map"), - - /** The rpr pcm meta data entry not avaiable in metainfo map. */ - RPR_PCM_META_DATA_ENTRY_NOT_AVAILABLE(PlatformConstants.RPR_PACKET_CLASSIFIER_MODULE + "015", - "Meta data entry not avaiable in metainfo map"), - - /** The rpr pcm ageGroupRangeMap does not contain group for given age. */ - RPR_PCM_AGE_GROUP_NOT_FOUND(PlatformConstants.RPR_PACKET_CLASSIFIER_MODULE + "016", - "Age Group Range Map configuration does not contain age group for given age"), - - /** The rpr pcm Captured Registered Devices entry not avaiable in metainfo map. */ - RPR_PCM_CAPTURED_REGISTERED_DEVICES_ENTRY_NOT_AVAILABLE(PlatformConstants.RPR_PACKET_CLASSIFIER_MODULE + "017", - "Captured registered devices entry not avaiable in metainfo map"), - - /** The rpr pcm exception biometrics entry not avaiable in metainfo map. */ - RPR_PCM_EXCEPTION_BIOMETRICS_APPLICANT_ENTRY_NOT_AVAILABLE(PlatformConstants.RPR_PACKET_CLASSIFIER_MODULE + "018", - "ExceptionBiometrics applicant entry not available in metainfo map"), - - /** The unsupported encoding. */ - // UIN check - JSON file encoding failed. - UNSUPPORTED_ENCODING(PlatformConstants.RPR_BIO_DEDUPE_SERVICE_MODULE + "005", "Json Object Parsing Failed"), - - OSI_VALIDATION_BIO_TYPE_EXCEPTION(PlatformConstants.RPR_CMD_VALIDATOR_MODULE + "007", "Bio Type Exception"), - - /** The cmd validation failed. */ - // Stages - CMD Exception error code and message - CMD_VALIDATION_FAILED(PlatformConstants.RPR_CMD_VALIDATOR_MODULE + "000", "CMD Validation Failed"), - - /** The cmd base unchecked exception. */ - CMD_BASE_UNCHECKED_EXCEPTION(PlatformConstants.RPR_CMD_VALIDATOR_MODULE + "001", - "CMD Validation Failed"), - - /** The cmd base checked exception. */ - CMD_BASE_CHECKED_EXCEPTION(PlatformConstants.RPR_CMD_VALIDATOR_MODULE + "002", - "CMD Validation Failed"), - - /** The operator base unchecked exception. */ - OPERATOR_BASE_UNCHECKED_EXCEPTION(PlatformConstants.RPR_OVM_VALIDATOR_MODULE + "001", - "operator Validation Failed"), - - /** The operator base checked exception. */ - OPERATOR_BASE_CHECKED_EXCEPTION(PlatformConstants.RPR_OVM_VALIDATOR_MODULE + "002", - "operator Validation Failed"), - - /** The Operator validation failed. */ - OPERATOR_VALIDATION_FAILED(PlatformConstants.RPR_OVM_VALIDATOR_MODULE + "000", "Operator Validation Failed"), - - LINK_FOR_USERID_INDIVIDUALID_FAILED_OVM_EXCEPTION(PlatformConstants.RPR_OVM_VALIDATOR_MODULE + "003", - "Unable to get the IndividualId for UserId"), - - /** The Supervisor base unchecked exception. */ - SUPERVISOR_BASE_UNCHECKED_EXCEPTION(PlatformConstants.RPR_SVM_VALIDATOR_MODULE + "001", - "Supervisor Validation Failed"), - - /** The Supervisor base checked exception. */ - SUPERVISOR_BASE_CHECKED_EXCEPTION(PlatformConstants.RPR_SVM_VALIDATOR_MODULE + "002", - "Supervisor Validation Failed"), - - /** The Supervisor validation failed. */ - SUPERVISOR_VALIDATION_FAILED(PlatformConstants.RPR_SVM_VALIDATOR_MODULE + "000", "Supervisor Validation Failed"), - - LINK_FOR_USERID_INDIVIDUALID_FAILED_SVM_EXCEPTION(PlatformConstants.RPR_SVM_VALIDATOR_MODULE + "003", - "Unable to get the IndividualId for UserId"), - - /** The INTRODUCER base unchecked exception. */ - INTRODUCER_BASE_UNCHECKED_EXCEPTION(PlatformConstants.RPR_IVM_VALIDATOR_MODULE + "001", - "INTRODUCER Validation Failed"), - - /** The INTRODUCER base checked exception. */ - INTRODUCER_BASE_CHECKED_EXCEPTION(PlatformConstants.RPR_IVM_VALIDATOR_MODULE + "002", - "INTRODUCER Validation Failed"), - - /** The INTRODUCER validation failed. */ - INTRODUCER_VALIDATION_FAILED(PlatformConstants.RPR_IVM_VALIDATOR_MODULE + "000", "INTRODUCER Validation Failed"), - - /** The INTRODUCER validation failed. */ - INTRODUCER_ON_HOLD(PlatformConstants.RPR_IVM_VALIDATOR_MODULE + "001", "Packet on hold as introducer packet is not processed yet"), - - /** The packet demo dedupe failed. */ - // Stages - Demo-Dedupe error code and message - PACKET_DEMO_DEDUPE_FAILED(PlatformConstants.RPR_DEMO_DEDUPE_MODULE+"000", "Demo Dedupe Failed"), - - /** The packet demo packet store not accessible. */ - PACKET_DEMO_PACKET_STORE_NOT_ACCESSIBLE(PlatformConstants.RPR_DEMO_DEDUPE_MODULE+"003", "Unable to Access Packet Store"), - - /** The packet bio dedupe cbeff not present. */ - PACKET_BIO_DEDUPE_CBEFF_NOT_PRESENT(PlatformConstants.RPR_BIO_DEDUPE_STAGE_MODULE + "001", - "Unable to Find Applicant CBEFF for Adult"), - - /** The registration id not found. */ - REGISTRATION_ID_NOT_FOUND(PlatformConstants.RPR_BIO_DEDUPE_STAGE_MODULE + "002", - "RegistrationId not found for given bio ref Id"), - - /** The rpr bio lost packet multiple match found. */ - RPR_BIO_LOST_PACKET_MULTIPLE_MATCH_FOUND(PlatformConstants.RPR_BIO_DEDUPE_STAGE_MODULE + "003", - "Multiple Match was Found for the Biometrics Received"), - - RPR_BIO_API_RESOUCE_ACCESS_FAILED(PlatformConstants.RPR_BIO_DEDUPE_STAGE_MODULE + "004", - "Unable to Access API Resource"), - - /** The abis reference id not found. */ - // stages - Abis Middleware - ABIS_REFERENCE_ID_NOT_FOUND(PlatformConstants.RPR_ABIS_MIDDLEWARE + "001", "Unable to Find ABIS Reference ID"), - - /** The latest transaction id not found. */ - LATEST_TRANSACTION_ID_NOT_FOUND(PlatformConstants.RPR_ABIS_MIDDLEWARE + "002", - "Unable to Find Latest Transaction ID"), - - /** The identify requests not found. */ - IDENTIFY_REQUESTS_NOT_FOUND(PlatformConstants.RPR_ABIS_MIDDLEWARE + "003", "Unable to Find Identify Request"), - - /** The abis queue json validation failed. */ - ABIS_QUEUE_JSON_VALIDATION_FAILED(PlatformConstants.RPR_ABIS_MIDDLEWARE + "004", - "Unable to Find ABIS Connection Properties"), - - /** The unknown exception occured. */ - UNKNOWN_EXCEPTION_OCCURED(PlatformConstants.RPR_ABIS_MIDDLEWARE + "005", "Unknown Exception Found"), - - /** ABIS_BATCH_ID_NOT_FOUND. */ - ABIS_BATCH_ID_NOT_FOUND(PlatformConstants.RPR_ABIS_MIDDLEWARE + "006", "Unable to Find ABIS Batch ID"), - - /** The abis queue not found. */ - ABIS_QUEUE_NOT_FOUND(PlatformConstants.RPR_ABIS_MIDDLEWARE + "007", "Unable to Connect with ABIS Queue"), - - /** The system exception occured. */ - SYSTEM_EXCEPTION_OCCURED(PlatformConstants.RPR_ABIS_MIDDLEWARE + "008", "Internal error occured"), - - DUPLICATE_INSERT_RESPONSE(PlatformConstants.RPR_ABIS_MIDDLEWARE + "009", - "Duplicate Insert Response received from abis for same request id : "), - - DUPLICATE_IDENTITY_RESPONSE(PlatformConstants.RPR_ABIS_MIDDLEWARE + "010", - "Duplicate Identify Response received from abis for same request id : "), - - /** The packet bio dedupe failed. */ - // Stages - Bio-Dedupe error code and message - PACKET_BIO_DEDUPE_FAILED(PlatformConstants.RPR_BIO_DEDUPE_SERVICE_MODULE + "001", "Bio Dedupe Failed"), - - /** The reverse data sync failed. */ - PACKET_BDD_PACKET_STORE_NOT_ACCESSIBLE(PlatformConstants.RPR_BIO_DEDUPE_SERVICE_MODULE + "002", - "Unable to Access Packet from Packet Store"), - - /** The rpr bio biometric insertion to abis. */ - RPR_BIO_BIOMETRIC_INSERTION_TO_ABIS(PlatformConstants.RPR_BIO_DEDUPE_SERVICE_MODULE + "003", - "Biometric Insertion Failed in ABIS"), - - /** The rpr abis internal error. */ - RPR_ABIS_INTERNAL_ERROR(PlatformConstants.RPR_BIO_DEDUPE_SERVICE_MODULE + "004", "ABIS Internal Error Occurred"), - - DATASHARE_ERROR(PlatformConstants.RPR_BIO_DEDUPE_SERVICE_MODULE + "005", "Datashare exception occured"), - - /** The reverse data sync failed. */ - // Stages - Packet-Validator error message - REVERSE_DATA_SYNC_FAILED(PlatformConstants.RPR_PACKET_VALIDATOR_MODULE + "016", "Reverse Data Sync Failed"), - - /** The Biometric-Authentication stage failed. */ - // stages - Biometric-Authentication stage error code and message - BIOMETRIC_AUTHENTICATION_FAILED(PlatformConstants.RPR_BIOMETRIC_AUTHENTICATION_MODULE, - "Biometric Authentication Failed"), - - /** The Biometric-Authentication io exception. */ - BIOMETRIC_AUTHENTICATION_IOEXCEPTION(PlatformConstants.RPR_BIOMETRIC_AUTHENTICATION_MODULE + "001", "IO Exception"), - - /** The Biometric-Authentication api resource exception. */ - BIOMETRIC_AUTHENTICATION_API_RESOURCE_EXCEPTION(PlatformConstants.RPR_BIOMETRIC_AUTHENTICATION_MODULE + "002", - "Unable to Access API Resource"), - - BIOMETRIC_AUTHENTICATION_TABLE_NOT_ACCESSIBLE(PlatformConstants.RPR_BIOMETRIC_AUTHENTICATION_MODULE + "004", - "Unable to Access Registration Table"), - - BIOMETRIC_AUTHENTICATION_AUTH_SYSTEM_EXCEPTION(PlatformConstants.RPR_BIOMETRIC_AUTHENTICATION_MODULE + "003", - "Request could not be processed. Please try again"), - - /** The rpr psj Packet Store not accessible. */ - // Packet scanner job Exception error code and message - RPR_PSJ_PACKET_STORE_NOT_ACCESSIBLE(PlatformConstants.RPR_PACKET_SCANNER_JOB_MODULE + "002", - "The Packet store set by the System is not accessible"), - - /** The rpr psj retry folder not accessible. */ - RPR_PSJ_RETRY_FOLDER_NOT_ACCESSIBLE(PlatformConstants.RPR_PACKET_SCANNER_JOB_MODULE + "003", - "The Retry folder set by the System is not accessible"), - - /** The rpr psj virus scan folder not accessible. */ - RPR_PSJ_VIRUS_SCAN_FOLDER_NOT_ACCESSIBLE(PlatformConstants.RPR_PACKET_SCANNER_JOB_MODULE + "004", - "The Virus scanner set by the System is not accessible"), - - /** The rpr psj space unavailable for retry folder. */ - RPR_PSJ_SPACE_UNAVAILABLE_FOR_RETRY_FOLDER(PlatformConstants.RPR_PACKET_SCANNER_JOB_MODULE + "005", - "There is no space available in retry folder to upload the packet"), - - /** The rpr psj virus scan failed. */ - RPR_PSJ_VIRUS_SCAN_FAILED(PlatformConstants.RPR_PACKET_SCANNER_JOB_MODULE + "006", "Virus scan is failed"), - - /** The rpr psj ftp folder not accessible. */ - RPR_PSJ_FTP_FOLDER_NOT_ACCESSIBLE(PlatformConstants.RPR_PACKET_SCANNER_JOB_MODULE + "007", - "The FTP folder set by the System is not accessible"), - - /** The rpr psj api resouce access failed. */ - RPR_PSJ_API_RESOUCE_ACCESS_FAILED(PlatformConstants.RPR_PACKET_SCANNER_JOB_MODULE + "008", - "Not able to access the API resource"), - - /** The rpr pdj packet not available. */ - // packet decryption job Exception error code and message - RPR_PDS_PACKET_NOT_AVAILABLE(PlatformConstants.RPR_PACKET_DECRYPTION_MODULE + "001", "Packet not available"), - - /** The rpr pdj file path not accessible. */ - RPR_PDS_FILE_PATH_NOT_ACCESSIBLE(PlatformConstants.RPR_PACKET_DECRYPTION_MODULE + "002", - "The File path set by the System is not accessible"), - - /** The rpr pdj packet decryption failure. */ - RPR_PDS_PACKET_DECRYPTION_FAILURE(PlatformConstants.RPR_PACKET_DECRYPTION_MODULE + "003", - "The Decryption for the Packet has failed"), - - /** The rpr pdj packet decryption failure. */ - RPR_PDS_IO_EXCEPTION(PlatformConstants.RPR_PACKET_DECRYPTION_MODULE + "004", - "Exception while reading packet inputStream"), - - /** The rpr pds date time exception. */ - RPR_PDS_DATE_TIME_EXCEPTION(PlatformConstants.RPR_PACKET_DECRYPTION_MODULE + "005", - "Error while parsing packet timestamp"), - - /** The rpr rct unknown resource exception. */ - RPR_RCT_UNKNOWN_RESOURCE_EXCEPTION(PlatformConstants.RPR_REST_CLIENT_MODULE + "001", "Unknown resource provided"), - - /** The rpr mvs invalid file request. */ - RPR_MVS_INVALID_FILE_REQUEST(PlatformConstants.RPR_MANUAL_ADJUDICATION_MODULE + "001", "Invalid file requested"), - - /** The rpr mvs file not present. */ - RPR_MVS_FILE_NOT_PRESENT(PlatformConstants.RPR_MANUAL_ADJUDICATION_MODULE + "002", "Requested file is not present"), - - /** The rpr mvs invalid status update. */ - RPR_MVS_INVALID_STATUS_UPDATE(PlatformConstants.RPR_MANUAL_ADJUDICATION_MODULE + "003", "Invalid status update"), - - /** The rpr mvs invalid field. */ - RPR_MVS_INVALID_FIELD(PlatformConstants.RPR_MANUAL_ADJUDICATION_MODULE + "005", " fields can not be empty"), - - /** The rpr mvs no assigned record. */ - RPR_MVS_NO_ASSIGNED_RECORD(PlatformConstants.RPR_MANUAL_ADJUDICATION_MODULE + "004", "No Assigned Record Found"), - - /** The rpr mvs file not found in packet store. */ - RPR_MVS_FILE_NOT_FOUND_IN_PACKET_STORE(PlatformConstants.RPR_MANUAL_ADJUDICATION_MODULE + "018", - "Packet Not Found in Packet Store"), - - /** The rpr mvs missing input parameter version. */ - RPR_MVS_MISSING_INPUT_PARAMETER_VERSION(PlatformConstants.RPR_MANUAL_ADJUDICATION_MODULE + "019", - "Missing Input Parameter - version"), - - /** The rpr mvs missing input parameter timestamp. */ - RPR_MVS_MISSING_INPUT_PARAMETER_TIMESTAMP(PlatformConstants.RPR_MANUAL_ADJUDICATION_MODULE + "006", - "Missing Input Parameter - requesttime"), - - /** The rpr mvs missing input parameter id. */ - RPR_MVS_MISSING_INPUT_PARAMETER_ID(PlatformConstants.RPR_MANUAL_ADJUDICATION_MODULE + "007", - "Missing Input Parameter - id"), - - /** The rpr mvs invalid input parameter version. */ - RPR_MVS_INVALID_INPUT_PARAMETER_VERSION(PlatformConstants.RPR_MANUAL_ADJUDICATION_MODULE + "008", - "Invalid Input Parameter - version"), - - /** The rpr mvs invalid input parameter timestamp. */ - RPR_MVS_INVALID_INPUT_PARAMETER_TIMESTAMP(PlatformConstants.RPR_MANUAL_ADJUDICATION_MODULE + "009", - "Invalid Input Parameter - requesttime"), - - /** The rpr mvs invalid input parameter id. */ - RPR_MVS_INVALID_INPUT_PARAMETER_ID(PlatformConstants.RPR_MANUAL_ADJUDICATION_MODULE + "010", - "Invalid Input Parameter - id"), - - /** The rpr mvs invalid argument exception. */ - RPR_MVS_INVALID_ARGUMENT_EXCEPTION(PlatformConstants.RPR_MANUAL_ADJUDICATION_MODULE + "011", - "Invalid Argument Exception"), - - /** The rpr mvs unknown exception. */ - RPR_MVS_UNKNOWN_EXCEPTION(PlatformConstants.RPR_MANUAL_ADJUDICATION_MODULE + "012", "Unknown Exception"), - - /** The rpr mvs decode exception. */ - RPR_MVS_DECODE_EXCEPTION(PlatformConstants.RPR_MANUAL_ADJUDICATION_MODULE + "013", "Request Decoding Exception"), - /** The rpr mvs no user id present. */ - RPR_MVS_NO_USER_ID_PRESENT(PlatformConstants.RPR_MANUAL_ADJUDICATION_MODULE + "014", - "User Id does not exists master list"), - - /** The rpr mvs no user id should not empty or null. */ - RPR_MVS_NO_USER_ID_SHOULD_NOT_EMPTY_OR_NULL(PlatformConstants.RPR_MANUAL_ADJUDICATION_MODULE + "017", - "User Id should not empty or null "), - - /** The rpr mvs no registration id should not empty or null. */ - RPR_MVS_NO_RID_SHOULD_NOT_EMPTY_OR_NULL(PlatformConstants.RPR_MANUAL_ADJUDICATION_MODULE + "022", - "Registration Id should not empty or null "), - - /** The rpr mvs no matched ref id found for given ref id. */ - RPR_MVS_NO_MATCHEDRID_FOUND_FOR_GIVEN_RID(PlatformConstants.RPR_MANUAL_ADJUDICATION_MODULE + "023", - "No matched reference id found for given RID"), - /** The rpr mvs user status not active. */ - RPR_MVS_USER_STATUS_NOT_ACTIVE(PlatformConstants.RPR_MANUAL_ADJUDICATION_MODULE + "015", - "User is not in ACTIVE status"), - - /** The rpr mvs no match type present. */ - RPR_MVS_NO_MATCH_TYPE_PRESENT(PlatformConstants.RPR_MANUAL_ADJUDICATION_MODULE + "020", "Match Type is Invalid"), - - /** The rpr mvs reg id should not empty or null. */ - RPR_MVS_REG_ID_SHOULD_NOT_EMPTY_OR_NULL(PlatformConstants.RPR_MANUAL_ADJUDICATION_MODULE + "016", - "Reg Id should not be null or empty"), - - /** The rpr manual verification rejected. */ - RPR_MANUAL_VERIFICATION_REJECTED(PlatformConstants.RPR_MANUAL_ADJUDICATION_MODULE + "021", - "Manual verification rejected"), - - /** The rpr manual verification rejected. */ - RPR_MANUAL_VERIFICATION_RESEND(PlatformConstants.RPR_MANUAL_ADJUDICATION_MODULE + "025", - "Manual verification resend to queue."), - - /** The rpr table not accessible. */ - RPR_TABLE_NOT_ACCESSIBLE(PlatformConstants.RPR_MANUAL_ADJUDICATION_MODULE + "022", - "TablenotAccessibleException in Manual verification"), - - /** The rpr table not accessible. */ - RPR_INVALID_MESSSAGE(PlatformConstants.RPR_MANUAL_ADJUDICATION_MODULE + "023", - "Invalid message received from queue"), - - /** The rpr table not accessible. */ - RPR_INVALID_RID_FOUND(PlatformConstants.RPR_MANUAL_ADJUDICATION_MODULE + "024", - "Multiple rids found for a reference id"), - - MANUAL_VERIFICATION_FAILED(PlatformConstants.RPR_MANUAL_ADJUDICATION_MODULE + "025", - "Manual adjudication failed"), - - /** The rpr tem not found. */ - // Registration processor Message sender Exception error code - RPR_TEM_NOT_FOUND(PlatformConstants.RPR_MESSAGE_SENDER_TEMPLATE + "001", "Template was Not Found"), - - /** The rpr tem processing failure. */ - RPR_TEM_PROCESSING_FAILURE(PlatformConstants.RPR_MESSAGE_SENDER_TEMPLATE + "002", - "The Processing of Template Failed "), - /** The rpr tem packet store not accessible. */ - RPR_TEM_PACKET_STORE_NOT_ACCESSIBLE(PlatformConstants.RPR_MESSAGE_SENDER_TEMPLATE + "003", - "The Packet store set by the System is not accessible"), - /** The rpr sms template generation failure. */ - RPR_SMS_TEMPLATE_GENERATION_FAILURE(PlatformConstants.RPR_MESSAGE_SENDER_TEMPLATE + "001", - "Template Generation failed"), - - /** The rpr sms phone number not found. */ - RPR_SMS_PHONE_NUMBER_NOT_FOUND(PlatformConstants.RPR_MESSAGE_SENDER_TEMPLATE + "002", "Phone number was not found"), - - /** The rpr eml emailid not found. */ - RPR_EML_EMAILID_NOT_FOUND(PlatformConstants.RPR_MESSAGE_SENDER_TEMPLATE + "001", "Email Id was not found"), - - /** The rpr tem configuration not found. */ - RPR_TEM_CONFIGURATION_NOT_FOUND(PlatformConstants.RPR_MESSAGE_SENDER_TEMPLATE + "003", - "The Configuration and Language code not found"), - - /** The rpr notification failed for lost. */ - RPR_NOTIFICATION_FAILED_FOR_LOST(PlatformConstants.RPR_MESSAGE_SENDER_TEMPLATE + "004", - "Unable to Send Notification - UIN was not found for the Lost Packet"), - - /** The rpr template configuration not found. */ - RPR_TEMPLATE_CONFIGURATION_NOT_FOUND(PlatformConstants.RPR_MESSAGE_SENDER_TEMPLATE + "005", - "Template configuration and language not found"), - - /** The rpr message sender stage failed. */ - RPR_MESSAGE_SENDER_STAGE_FAILED(PlatformConstants.RPR_MESSAGE_SENDER_TEMPLATE + "006", - "Message Sender Stage failed"), - - /** The rpr email phone template notification missing. */ - RPR_EMAIL_PHONE_TEMPLATE_NOTIFICATION_MISSING(PlatformConstants.RPR_MESSAGE_SENDER_TEMPLATE + "007", - "Email ID or Phone or Template or Notification Type is Missing"), - - /** The rpr message sender email failed. */ - RPR_MESSAGE_SENDER_EMAIL_FAILED(PlatformConstants.RPR_MESSAGE_SENDER_TEMPLATE + "008", "Email Failed"), - - /** The rpr message sender sms failed. */ - RPR_MESSAGE_SENDER_SMS_FAILED(PlatformConstants.RPR_MESSAGE_SENDER_TEMPLATE + "009", "SMS failed"), - - /** The rpr pum packet not found exception. */ - RPR_PUM_PACKET_NOT_FOUND_EXCEPTION(PlatformConstants.RPR_PACKET_UPLOADER_MODULE + "001", - "Packet not found in LANDING_ZONE "), - - /** The rpr pum packet deletion info. */ - RPR_PUM_PACKET_DELETION_INFO(PlatformConstants.RPR_PACKET_UPLOADER_MODULE + "002", - "File is Already exists in File Store And its now Deleted from landing zone"), - - /** The rpr pum packet store not accessible. */ - RPR_PUM_PACKET_STORE_NOT_ACCESSIBLE(PlatformConstants.RPR_PACKET_UPLOADER_MODULE + "003", - "The Packet store set by the System is not accessible"), - - /** The prp pkr packet virus scan failed. */ - RPR_PUM_PACKET_VIRUS_SCAN_FAILED(PlatformConstants.RPR_PACKET_UPLOADER_MODULE + "004", - "The Registration Packet virus scan failed"), - - /** The rpr pum packet virus scanner service failed. */ - RPR_PUM_PACKET_VIRUS_SCANNER_SERVICE_FAILED(PlatformConstants.RPR_PACKET_UPLOADER_MODULE + "005", - "Virus scanner service failed"), - - /** The rpr pkm file not found in source. */ - RPR_PUM_JSCH_NOT_CONNECTED(PlatformConstants.RPR_PACKET_UPLOADER_MODULE + "006", "The JSCH connection failed"), - - /** The rpr pkm file not found in source. */ - RPR_PUM_NGINX_ACCESS_FAILED(PlatformConstants.RPR_PACKET_UPLOADER_MODULE + "007", - "Could not get the packet from nginx Url"), - - /** The rpr pum packet not yet sync. */ - RPR_PUM_PACKET_NOT_YET_SYNC(PlatformConstants.RPR_PACKET_UPLOADER_MODULE + "008", - "Registration packet is not in Sync with Sync table"), - - /** The rpr pum packet decryption failed. */ - RPR_PUM_PACKET_DECRYPTION_FAILED(PlatformConstants.RPR_PACKET_UPLOADER_MODULE + "009", - "Registration packet decryption failed"), - - /** The rpr pum packet deletion failed. */ - RPR_PUM_PACKET_DELETION_FAILED(PlatformConstants.RPR_PACKET_UPLOADER_MODULE + "010", - "packet upload failed during cleanup"), - - /** The rpr pum packet archival failed. */ - RPR_PUM_PACKET_ARCHIVAL_FAILED(PlatformConstants.RPR_PACKET_UPLOADER_MODULE + "010", - "packet upload failed during archival"), - - /** The rpr pum packet not found exception. */ - RPR_PUM_PACKET_UPLOAD_FAILURE(PlatformConstants.RPR_PACKET_UPLOADER_MODULE + "011", - "Failure in uploading the packet to Packet Store"), - - RPR_PUM_PACKET_RETRY_CNT_FAILURE(PlatformConstants.RPR_PACKET_UPLOADER_MODULE + "012", - "packet upload failed due to Retry count has exceeded the max limit specified"), - - /** The rpr bdd abis internal error. */ - RPR_BDD_ABIS_INTERNAL_ERROR(PlatformConstants.RPR_BIO_DEDUPE_SERVICE_MODULE + "001", - "ABIS for the Reference ID and Request ID threw an Internal Error"), - - /** The rpr bdd abis abort. */ - RPR_BDD_ABIS_ABORT(PlatformConstants.RPR_BIO_DEDUPE_SERVICE_MODULE + "002", - "ABIS for the Reference ID and Request ID was Abort"), - - /** The rpr bdd unexcepted error. */ - RPR_BDD_UNEXCEPTED_ERROR(PlatformConstants.RPR_BIO_DEDUPE_SERVICE_MODULE + "003", - "ABIS for the Reference ID and Request ID was Not able to Access Biometric Data"), - - /** The rpr bdd unable to serve request. */ - RPR_BDD_UNABLE_TO_SERVE_REQUEST(PlatformConstants.RPR_BIO_DEDUPE_SERVICE_MODULE + "004", - "ABIS for the Reference ID and Request ID was Unable to Execute the Request"), - - /** The unknown exception. */ - UNKNOWN_EXCEPTION(PlatformConstants.RPR_BIO_DEDUPE_SERVICE_MODULE + "005", - "un expected exception occured in biodedupe service"), - - /** The connection to MOSIP underlying queue not available. */ - RPR_MQI_CONNECTION_UNAVAILABLE(PlatformConstants.RPR_MOSIP_QUEUE_MODULE + "001", - "The connection to underlying queue not available"), - - /** The rpr mqi unable to send to queue. */ - RPR_MQI_UNABLE_TO_SEND_TO_QUEUE(PlatformConstants.RPR_MOSIP_QUEUE_MODULE + "003", - "Unable to send message to to queue"), - - /** The rpr mqi unable to consume from queue. */ - RPR_MQI_UNABLE_TO_CONSUME_FROM_QUEUE(PlatformConstants.RPR_MOSIP_QUEUE_MODULE + "004", - "Unable to consume message from queue"), - - /** The rpr mqi no files found in queue. */ - RPR_MQI_NO_FILES_FOUND_IN_QUEUE(PlatformConstants.RPR_MOSIP_QUEUE_MODULE + "005", - "There is no file available in queue"), - - /** The rpr mqi invalid connection. */ - RPR_MQI_INVALID_CONNECTION(PlatformConstants.RPR_MOSIP_QUEUE_MODULE + "002", - "Connection not obtained from ConnectionFactory"), - - /** The missing input parameter. */ - RPR_BDD_MISSING_INPUT_PARAMETER(PlatformConstants.RPR_BIO_DEDUPE_SERVICE_MODULE + "005", - "Missing Input Parameter - %s"), - - /** The invalid input parameter. */ - RPR_BDD_INVALID_INPUT_PARAMETER(PlatformConstants.RPR_BIO_DEDUPE_SERVICE_MODULE + "006", - "Invalid Input Parameter - %s"), - - /** The data validation failed. */ - RPR_BDD_DATA_VALIDATION_FAILED(PlatformConstants.RPR_BIO_DEDUPE_SERVICE_MODULE + "007", - "Input Data Validation Failed"), - - /** The rpr bdd json mapping exception. */ - RPR_BDD_JSON_MAPPING_EXCEPTION(PlatformConstants.RPR_BIO_DEDUPE_SERVICE_MODULE + "008", - "Json Data Mapping Exception"), - - /** The rpr bdd json parsing exception. */ - RPR_BDD_JSON_PARSING_EXCEPTION(PlatformConstants.RPR_BIO_DEDUPE_SERVICE_MODULE + "009", - "Json Data Parsing Exception"), - - /** The rpr bdd unknown exception. */ - RPR_BDD_UNKNOWN_EXCEPTION(PlatformConstants.RPR_BIO_DEDUPE_SERVICE_MODULE + "010", "Unknown Exception Occurs"), - - /** The rpr mvs file not present. */ - RPR_BDD_FILE_NOT_PRESENT(PlatformConstants.RPR_BIO_DEDUPE_SERVICE_MODULE + "011", "Requested file is not present"), - - /** *** System Exception ****. */ - - RPR_SYS_UNEXCEPTED_EXCEPTION(PlatformConstants.RPR_SYSTEM_EXCEPTION + "001", "Unexpected exception"), - - /** The rpr sys bad gateway. */ - RPR_SYS_BAD_GATEWAY(PlatformConstants.RPR_SYSTEM_EXCEPTION + "002", "Bad Gateway"), - - /** The rpr sys service unavailable. */ - RPR_SYS_SERVICE_UNAVAILABLE(PlatformConstants.RPR_SYSTEM_EXCEPTION + "003", "Service Unavailable"), - - /** The rpr sys server error. */ - RPR_SYS_SERVER_ERROR(PlatformConstants.RPR_SYSTEM_EXCEPTION + "004", "Internal Server Error"), - - /** The rpr sys timeout exception. */ - RPR_SYS_TIMEOUT_EXCEPTION(PlatformConstants.RPR_SYSTEM_EXCEPTION + "005", "Timeout Error"), - - /** The rpr sys identity json mapping exception. */ - RPR_SYS_IDENTITY_JSON_MAPPING_EXCEPTION(PlatformConstants.RPR_SYSTEM_EXCEPTION + "006", - "Error while mapping Identity Json"), - - /** The rpr sys instantiation exception. */ - RPR_SYS_INSTANTIATION_EXCEPTION(PlatformConstants.RPR_SYSTEM_EXCEPTION + "007", - "Error while creating object of JsonValue class"), - - /** The rpr sys no such field exception. */ - RPR_SYS_NO_SUCH_FIELD_EXCEPTION(PlatformConstants.RPR_SYSTEM_EXCEPTION + "008", "Could not find the field"), - - /** The rpr sys json parsing exception. */ - RPR_SYS_JSON_PARSING_EXCEPTION(PlatformConstants.RPR_SYSTEM_EXCEPTION + "009", "Error while parsing Json"), - - /** The rpr sys unable to convert stream to bytes. */ - RPR_SYS_UNABLE_TO_CONVERT_STREAM_TO_BYTES(PlatformConstants.RPR_SYSTEM_EXCEPTION + "010", - "Error while converting inputstream to bytes"), - - /** The rpr sys parsing date exception. */ - RPR_SYS_PARSING_DATE_EXCEPTION(PlatformConstants.RPR_SYSTEM_EXCEPTION + "011", "Error while parsing date "), - - /** The rpr sys io exception. */ - RPR_SYS_IO_EXCEPTION(PlatformConstants.RPR_SYSTEM_EXCEPTION + "012", "IO EXCEPTION "), - - /** The rpr sys data access exception. */ - RPR_SYS_DATA_ACCESS_EXCEPTION(PlatformConstants.RPR_SYSTEM_EXCEPTION + "013", "Data Access Exception"), - - /** The rpr sys api resource exception. */ - RPR_SYS_API_RESOURCE_EXCEPTION(PlatformConstants.RPR_SYSTEM_EXCEPTION + "014", "API Resource Exception"), - - /** The rpr sys illegal access exception. */ - RPR_SYS_ILLEGAL_ACCESS_EXCEPTION(PlatformConstants.RPR_SYSTEM_EXCEPTION + "015", "ILLEGAL ACCESS Exception"), - - /** The rpr sys Invocation target exception. */ - RPR_SYS_INVOCATION_TARGET_EXCEPTION(PlatformConstants.RPR_SYSTEM_EXCEPTION + "016", "Invocation target Exception"), - - /** The rpr sys Invocation target exception. */ - RPR_SYS_INTROSPECTION_EXCEPTION(PlatformConstants.RPR_SYSTEM_EXCEPTION + "017", "Introspection Exception"), - - /** The packet store not accessible. */ - OBJECT_STORE_NOT_ACCESSIBLE(PlatformConstants.RPR_SYSTEM_EXCEPTION + "018", - "Unable to Access Object Store"), - - /** The packet tags copying failed. */ - RPR_SYS_PACKET_TAGS_COPYING_FAILED(PlatformConstants.RPR_SYSTEM_EXCEPTION + "019", - "Packet tags copying to message event failed"), - - /** The message expired. */ - RPR_SYS_MESSAGE_EXPIRED(PlatformConstants.RPR_SYSTEM_EXCEPTION + "020", - "Message expired as per the last hop timestamp"), - - /** The stage processing failed. */ - RPR_SYS_STAGE_PROCESSING_FAILED(PlatformConstants.RPR_SYSTEM_EXCEPTION + "021", - "Stage processing of message failed with an exception"), - - /** The rpr sys connection exception. */ - RPR_SYS_QUEUE_CONNECTION_EXCEPTION(PlatformConstants.RPR_SYSTEM_EXCEPTION + "022", - "Error while connecting to active mq"), - - // Cbeff Util Exceptions - /** The rpr utl biometric tag match. */ - RPR_UTL_BIOMETRIC_TAG_MATCH(PlatformConstants.RPR_UTIL + "001", "Both Files have same biometrics"), - - /** The rpr utl cbeff version mismatch. */ - RPR_UTL_CBEFF_VERSION_MISMATCH(PlatformConstants.RPR_UTIL + "002", "Both Files have different versions"), - - /** The rpr utl digital sign exception. */ - RPR_UTL_DIGITAL_SIGN_EXCEPTION(PlatformConstants.RPR_UTIL + "003", "Failed to generate digital signature"), - - /** The rpr utl language exception. */ - RPR_UTL_LANGUAGE_EXCEPTION(PlatformConstants.RPR_UTIL + "004", "Failed to retrieve language details."), - - /** The rpr prt pdf not generated. */ - // Printing stage exceptions - RPR_PRT_PDF_NOT_GENERATED(PlatformConstants.RPR_PRINTING_MODULE + "001", "Error while generating PDF for UIN Card"), - - /** The rpr prt uin not found in database. */ - RPR_PRT_UIN_NOT_FOUND_IN_DATABASE(PlatformConstants.RPR_PRINTING_MODULE + "002", "UIN not found in database"), - - /** The rpr prt pdf generation failed. */ - RPR_PRT_PDF_GENERATION_FAILED(PlatformConstants.RPR_PRINTING_MODULE + "003", "PDF Generation Failed"), - - /** The rpr prt queue connection null. */ - RPR_PRT_QUEUE_CONNECTION_NULL(PlatformConstants.RPR_PRINTING_MODULE + "004", "Queue connection is null"), - - /** The rpr prt qrcode not generated. */ - RPR_PRT_QRCODE_NOT_GENERATED(PlatformConstants.RPR_PRINTING_MODULE + "005", "Error while generating QR Code"), - - /** The rpr prt applicant photo not set. */ - RPR_PRT_APPLICANT_PHOTO_NOT_SET(PlatformConstants.RPR_PRINTING_MODULE + "006", - "Error while setting applicant photo"), - - /** The rpr prt qrcode not set. */ - RPR_PRT_QRCODE_NOT_SET(PlatformConstants.RPR_PRINTING_MODULE + "007", "Error while setting qrCode for uin card"), - - /** The rpr prt idrepo response null. */ - RPR_PRT_IDREPO_RESPONSE_NULL(PlatformConstants.RPR_PRINTING_MODULE + "008", "ID Repo response is null"), - - /** The rpr prt idrepo documents absent. */ - RPR_PRT_IDREPO_DOCUMENT_ABSENT(PlatformConstants.RPR_PRINTING_MODULE + "009", "ID Repo response has no documents"), - - /** The print and postal acknowledment generation failed. */ - RPR_PRT_PRINT_POST_ACK_FAILED(PlatformConstants.RPR_PRINTING_MODULE + "010", - "Error while getting response from Print and Postal Service Provider"), - - /** The print validation failed. */ - RPR_PRT_DATA_VALIDATION_FAILED(PlatformConstants.RPR_PRINTING_MODULE + "011", "Error while print data validation"), - - /** The rpr prt cardtype validation failed. */ - RPR_PRT_CARDTYPE_VALIDATION_FAILED(PlatformConstants.RPR_PRINTING_MODULE + "012", - "Invalid CardType : Enter UIN or MASKED_UIN"), - - /** The rpr prt idtype validation failed. */ - RPR_PRT_IDTYPE_VALIDATION_FAILED(PlatformConstants.RPR_PRINTING_MODULE + "013", - "Invalid IdType : Enter UIN or VID or RID"), - - /** The rpr prt uin validation failed. */ - RPR_PRT_UIN_VALIDATION_FAILED(PlatformConstants.RPR_PRINTING_MODULE + "014", "UIN is not valid"), - - /** The rpr prt vid validation failed. */ - RPR_PRT_VID_VALIDATION_FAILED(PlatformConstants.RPR_PRINTING_MODULE + "015", "VID is not valid"), - - /** The rpr prt rid validation failed. */ - RPR_PRT_RID_VALIDATION_FAILED(PlatformConstants.RPR_PRINTING_MODULE + "016", "RID is not valid"), - - /** The rpr prt vid not generated. */ - RPR_PRT_VID_NOT_GENERATED(PlatformConstants.RPR_PRINTING_MODULE + "017", "Error while creating VID"), - - /** The rpr prt vid exception. */ - RPR_PRT_VID_EXCEPTION(PlatformConstants.RPR_PRINTING_MODULE + "018", - "Could not generate/regenerate VID as per policy,Please use existing VID"), - - /** The missing input parameter. */ - RPR_PRT_MISSING_INPUT_PARAMETER(PlatformConstants.RPR_PRINTING_MODULE + "019", "Missing Input Parameter - %s"), - - /** The missing input parameter. */ - RPR_PRT_INVALID_INPUT_PARAMETER(PlatformConstants.RPR_PRINTING_MODULE + "019", "Invalid Input Parameter - %s"), - - /** The missing input parameter. */ - RPR_PRT_PDF_NOT_ADDED(PlatformConstants.RPR_PRINTING_MODULE + "020", - "Pdf was not added to queue due to queue failure"), - - /** The missing input parameter. */ - RPR_PRT_RESEND_UIN_CARD(PlatformConstants.RPR_PRINTING_MODULE + "021", "Re-Send uin card for printing"), - - /** The rpr prt qr code generation error. */ - RPR_PRT_QR_CODE_GENERATION_ERROR(PlatformConstants.RPR_PRINTING_MODULE + "022", "Error while QR Code Generation"), - - /** The rpr prt vid creation error. */ - RPR_PRT_VID_CREATION_ERROR(PlatformConstants.RPR_PRINTING_MODULE + "023", "Error while creating VID"), - - - RPR_PRT_PDF_SIGNATURE_EXCEPTION(PlatformConstants.RPR_PRINTING_MODULE + "024", "PDF Signature error"), - - RPR_PRT_PRINT_REQUEST_FAILED(PlatformConstants.RPR_PRINTING_MODULE + "025", "Print request failed"), - - RPR_PRT_API_RESOUCE_ACCESS_FAILED(PlatformConstants.RPR_PRINTING_MODULE + "026", - "Unable to Access API Resource"), - - /** The rpr prt vid exception. */ - RPR_PRT_VID_NOT_AVAILABLE_EXCEPTION(PlatformConstants.RPR_PRINTING_MODULE + "027", - "vid not available"), - - /** The rpr prt print issuer not found in property. */ - RPR_PRT_ISSUER_NOT_FOUND_IN_PROPERTY(PlatformConstants.RPR_PRINTING_MODULE + "028", "Print issuer property is not found"), - - RPR_PRT_PARSING_ADDITIONAL_CRED_CONFIG(PlatformConstants.RPR_PRINTING_MODULE + "029", "issue with metaInfoFields in credential partner profiles."), - - /** The rpr rgs registration connector not accessible. */ - RPR_RGS_REGISTRATION_CONNECTOR_NOT_ACCESSIBLE("", "Registration connector stage is not accessible "), - - /** The rpr pvm packet store not accessible. */ - RPR_PVM_PACKET_STORE_NOT_ACCESSIBLE(PlatformConstants.RPR_PACKET_VALIDATOR_MODULE + "001", - "The Packet store set by the System is not accessible"), - - /** The rpr ugs packet store not accessible. */ - RPR_UGS_PACKET_STORE_NOT_ACCESSIBLE(PlatformConstants.RPR_UIN_GENERATOR_STAGE + "001", - "The Packet store set by the System is not accessible"), - /** The rpr ugs json parser error. */ - RPR_UGS_JSON__PARSER_ERROR(PlatformConstants.RPR_UIN_GENERATOR_STAGE + "002", "Error while parsing Json"), - /** The rpr ugs api resource exception. */ - RPR_UGS_API_RESOURCE_EXCEPTION(PlatformConstants.RPR_UIN_GENERATOR_STAGE + "003", - "Not able to access the API resource"), - /** The rpr ugs io exception. */ - RPR_UGS_IO_EXCEPTION(PlatformConstants.RPR_UIN_GENERATOR_STAGE + "004", "IO exception"), - /** The rpr ugs vid exception. */ - RPR_UGS_VID_EXCEPTION(PlatformConstants.RPR_UIN_GENERATOR_STAGE + "005", "VID status is not active"), - - /** The rpr ugs uin update failure. */ - RPR_UGS_UIN_UPDATE_FAILURE(PlatformConstants.RPR_UIN_GENERATOR_STAGE + "006", "UIN updation failure"), - - /** The uin already activated. */ - UIN_ALREADY_ACTIVATED(PlatformConstants.RPR_UIN_GENERATOR_STAGE + "007", "UIN is already Activated"), - - /** The uin already deactivated. */ - UIN_ALREADY_DEACTIVATED(PlatformConstants.RPR_UIN_GENERATOR_STAGE + "008", "UIN already deactivated"), - - /** The uin activated failed. */ - UIN_ACTIVATED_FAILED(PlatformConstants.RPR_UIN_GENERATOR_STAGE + "009", "UIN Activation Failed"), - - /** The uin reactivation failed. */ - UIN_REACTIVATION_FAILED(PlatformConstants.RPR_UIN_GENERATOR_STAGE + "010", "UIN Reactivation failed"), - - /** The uin deactivation failed. */ - UIN_DEACTIVATION_FAILED(PlatformConstants.RPR_UIN_GENERATOR_STAGE + "011", "UIN Deactivation failed"), - - /** The link rid for lost packet failed. */ - LINK_RID_FOR_LOST_PACKET_FAILED(PlatformConstants.RPR_UIN_GENERATOR_STAGE + "012", - "UIn not found the the matched RID"), - - /** The uin generation failed. */ - UIN_GENERATION_FAILED(PlatformConstants.RPR_UIN_GENERATOR_STAGE + "013", "UIN Generation failed"), - - VID_CREATION_FAILED(PlatformConstants.RPR_UIN_GENERATOR_STAGE + "014", "VID creation failed"), - - - DRAFT_CHECK_FAILED(PlatformConstants.RPR_UIN_GENERATOR_STAGE + "015", "Could not check if draft is present or not"), - - /** The rpr pgs file not present. */ - RPR_PGS_FILE_NOT_PRESENT(PlatformConstants.RPR_PACKET_GENERATOR_MODULE + "001", - "The Packet store set by the System is not accessible"), - - /** The rpr pgs invalid key illegal argument. */ - RPR_PGS_INVALID_KEY_ILLEGAL_ARGUMENT(PlatformConstants.RPR_PACKET_GENERATOR_MODULE + "002", - "The key is invalid or illegal argument"), - - /** The rpr pgs api resource not available. */ - RPR_PGS_API_RESOURCE_NOT_AVAILABLE(PlatformConstants.RPR_PACKET_GENERATOR_MODULE + "003", - "The Api resource is not available"), - - /** The rpr pgs reg base exception. */ - RPR_PGS_REG_BASE_EXCEPTION(PlatformConstants.RPR_PACKET_GENERATOR_MODULE + "004", "reg Based checked exception"), - - /** The rpr pgs json processing exception. */ - RPR_PGS_JSON_PROCESSING_EXCEPTION(PlatformConstants.RPR_PACKET_GENERATOR_MODULE + "005", - "Exception while parsing object to JSON"), - - /** The rpr pgs json validator error code. */ - RPR_PGS_JSON_VALIDATOR_ERROR_CODE(PlatformConstants.RPR_PACKET_GENERATOR_MODULE + "006", - "Exception while validating ID json file"), - - /** The rpr pgs encryptor invlaid data exception. */ - RPR_PGS_ENCRYPTOR_INVLAID_DATA_EXCEPTION(PlatformConstants.RPR_PACKET_GENERATOR_MODULE + "007", - "Exception occured while encryting the data"), - - /** The rpr pgs encryptor invlaid key exception. */ - RPR_PGS_ENCRYPTOR_INVLAID_KEY_EXCEPTION(PlatformConstants.RPR_PACKET_GENERATOR_MODULE + "008", - "Exception occured while encryting the packet Invalid Key"), - - /** The rpr pgs packet meta convertor exception. */ - RPR_PGS_PACKET_META_CONVERTOR_EXCEPTION(PlatformConstants.RPR_PACKET_GENERATOR_MODULE + "009", - "Packet meta info converter error"), - - /** The missing input parameter. */ - RPR_PGS_MISSING_INPUT_PARAMETER(PlatformConstants.RPR_PACKET_GENERATOR_MODULE + "010", - "Missing Input Parameter - %s"), - - /** The invalid input parameter. */ - RPR_PGS_INVALID_INPUT_PARAMETER(PlatformConstants.RPR_PACKET_GENERATOR_MODULE + "011", - "Invalid Input Parameter - %s"), - /** The data validation failed. */ - RPR_PGS_DATA_VALIDATION_FAILED(PlatformConstants.RPR_PACKET_GENERATOR_MODULE + "012", - "Input Data Validation Failed"), - - /** The rpr pgs vid exception. */ - RPR_PGS_VID_EXCEPTION(PlatformConstants.RPR_PACKET_GENERATOR_MODULE + "013", - "Could not generate/regenerate VID as per policy,Please use existing VID"), - - /** The rpr pgs vid creation exception. */ - RPR_PGS_VID_CREATION_EXCEPTION(PlatformConstants.RPR_PACKET_GENERATOR_MODULE + "014", "VID creation Exception"), - - /** The rpr pgs id object exception. */ - RPR_PGS_ID_OBJECT_EXCEPTION(PlatformConstants.RPR_PACKET_GENERATOR_MODULE + "015", "ID Object Validation failed"), - - /** The rpr pgs id type exception. */ - RPR_PGS_ID_TYPE_EXCEPTION(PlatformConstants.RPR_PACKET_GENERATOR_MODULE + "016", - "Invalid Input Value - ID Type: Enter UIN or RID"), - - /** The rpr pgs contact type exception. */ - RPR_PGS_CONTACT_TYPE_EXCEPTION(PlatformConstants.RPR_PACKET_GENERATOR_MODULE + "017", - "Invalid Input Value - Contact Type : Enter Email or Phone"), - /** The rpr pgs name exception. */ - RPR_PGS_NAME_EXCEPTION(PlatformConstants.RPR_PACKET_GENERATOR_MODULE + "018", - "Invalid Input Value - Name cannot be NULL or Empty"), - /** The rpr pgs contactvalue exception. */ - RPR_PGS_CONTACTVALUE_EXCEPTION(PlatformConstants.RPR_PACKET_GENERATOR_MODULE + "019", - "Invalid Input Value - contactValue cannot be NULL or Empty"), - /** The rpr pgs postalcode exception. */ - RPR_PGS_POSTALCODE_EXCEPTION(PlatformConstants.RPR_PACKET_GENERATOR_MODULE + "020", - "Invalid Input Value - postalCode cannot be NULL or Empty"), - - /** The rpr pgs no records exception. */ - RPR_PGS_NO_RECORDS_EXCEPTION(PlatformConstants.RPR_PACKET_GENERATOR_MODULE + "021", "No Records Found"), - - /** The rpr pgs no records exception. */ - RPR_PGS_MULTIPLE_RECORDS_EXCEPTION(PlatformConstants.RPR_PACKET_GENERATOR_MODULE + "022", "Multiple Records Found"), - - /** The rpr ugs api resource exception. */ - RPR_PGS_API_RESOURCE_EXCEPTION(PlatformConstants.RPR_PACKET_GENERATOR_MODULE + "023", - "Not able to access the API resource"), - /** The rpr ugs io exception. */ - RPR_PGS_IO_EXCEPTION(PlatformConstants.RPR_PACKET_GENERATOR_MODULE + "024", "IO exception"), - - /** The rpr pis identity not found. */ - RPR_PGS_IDENTITY_NOT_FOUND(PlatformConstants.RPR_PACKET_GENERATOR_MODULE + "025", - "Unable to Find Identity Field in ID JSON"), - - /** Idrepo draft creation exception. */ - IDREPO_DRAFT_EXCEPTION(PlatformConstants.RPR_PACKET_GENERATOR_MODULE + "026", - "Exception while updating idrepo draft"), - - /** invalid token present in header. */ - RPR_AUT_INVALID_TOKEN(PlatformConstants.RPR_AUTHENTICATION + "01", "Invalid Token Present"), - - /** Access denied for the token present. */ - RPR_AUT_ACCESS_DENIED(PlatformConstants.RPR_AUTHENTICATION + "02", "Access Denied For Role - %s"), - - /** Reprocessor Stage Failed. */ - REPROCESSOR_VERTICLE_FAILED(PlatformConstants.RPR_REPROCESSOR_VERTICLE + "000", "Reprocessor Verticle Failed"), - - RPR_WIA_DATE_TIME_EXCEPTION(PlatformConstants.RPR_WORKFLOW_INTERNAL_ACTION + "000", - "Error while parsing event or resume timestamp"), - - RPR_WORKFLOW_INTERNAL_ACTION_FAILED(PlatformConstants.RPR_WORKFLOW_INTERNAL_ACTION + "001", - "Work flow internal action failed"), - - RPR_WIA_UNKNOWN_WORKFLOW_ACTION(PlatformConstants.RPR_WORKFLOW_INTERNAL_ACTION + "002", "Unknown Exception"), - - RPR_WIA_ADDITIONALINFOPROCESS_NOT_FOUND(PlatformConstants.RPR_WORKFLOW_INTERNAL_ACTION + "003", - "AdditionalInfoProcess not found"), - - RPR_WIA_ADDITIONALINFOPROCESS_CANNOT_REQUEST(PlatformConstants.RPR_WORKFLOW_INTERNAL_ACTION + "004", - "AdditionalInfoProcess cannot be paused for one more additional info so it is failed"), - - RPR_WAA_MISSING_INPUT_PARAMETER(PlatformConstants.RPR_WORKFLOW_ACTION_API + "000", - "Missing Request Value - %s"), - - RPR_WAA_INVALID_INPUT_PARAMETER(PlatformConstants.RPR_WORKFLOW_ACTION_API + "001", - "Invalid Request Value - %s"), - - RPR_WAA_UNKNOWN_EXCEPTION(PlatformConstants.RPR_WORKFLOW_ACTION_API + "002", "Unknown Exception"), - - RPR_WAS_UNKNOWN_WORKFLOW_ACTION(PlatformConstants.RPR_WORKFLOW_ACTION_SERVICE + "000", - "Workflow Action not supported"), - - RPR_WAS_REMOVE_HOTLISTED_TAG_FAILED(PlatformConstants.RPR_WORKFLOW_ACTION_SERVICE + "001", - "Removing hotlisted tag failed"), - - RPR_WAA_WORKFLOW_ID_NOT_FOUND(PlatformConstants.RPR_WORKFLOW_ACTION_API + "003", - "Workflow id %s not found in registration table"), - - RPR_WAS_UNKNOWN_EXCEPTION(PlatformConstants.RPR_WORKFLOW_ACTION_SERVICE + "003", "Unknown Exception"), - - RPR_WAS_REPROCESS_FAILED(PlatformConstants.RPR_WORKFLOW_ACTION_SERVICE + "004", - "When REPROCESS_FAILED then Resume should not occur"), - - RPR_WAA_NOT_PAUSED(PlatformConstants.RPR_WORKFLOW_ACTION_API + "004", - "Workflow id %s is not PAUSED"), - - RPR_WAA_VALIDATION_SUCCESS(PlatformConstants.RPR_WORKFLOW_ACTION_API + "005", "Workflow id validated successfully"), - - RPR_WORKFLOW_ACTION_JOB_FAILED(PlatformConstants.RPR_WORKFLOW_ACTION_JOB, "Workflow action job failed"), - - /** The external stage failed. */ - EXTERNAL_STAGE_FAILED("", "External Stage Failed"), - - /** internal error for unknown reason. */ - INTERNAL_ERROR_UNKNOWN(PlatformConstants.ABIS + "01", "internal error for reason - %s"), - - /** request aborted. */ - ABORTED(PlatformConstants.ABIS + "02", "request aborted"), - - /** Unexpected error - Unable to access biometric data. */ - UNEXPECTED_ERROR(PlatformConstants.ABIS + "03", "Unexpected error - Unable to access biometric data for - %s"), - - /** Unable to serve the request. */ - UNABLE_TO_SERVE_REQUEST(PlatformConstants.ABIS + "04", "Unable to serve the request"), - - /** Invalid request. */ - INVALID_REQUEST(PlatformConstants.ABIS + "05", "Invalid request / Missing mandatory fields - %S"), - - /** Unauthorized Access. */ - UNAUTHORIZED_ACCESS(PlatformConstants.ABIS + "06", "Unauthorized Access"), - - /** Unable to fetch biometric details. */ - UNABLE_TO_FETCH_BIO_INFO(PlatformConstants.ABIS + "07", "Unable to fetch biometric details"), - - /** The missing mandatory fields. */ - MISSING_MANDATORY_FIELDS(PlatformConstants.ABIS + "08", "Mandatory request fields are missing"), - - /** The transactions not available. */ - TRANSACTIONS_NOT_AVAILABLE(PlatformConstants.REGISTRATION_TRANSACTIONS_SERVICE + "001", "RID Not Found"), - - /** The rpr rts unknown exception. */ - RPR_RTS_UNKNOWN_EXCEPTION(PlatformConstants.REGISTRATION_TRANSACTIONS_SERVICE + "002", "Unknown Exception Occured"), - - /** The rpr rts invalid request. */ - RPR_RTS_INVALID_REQUEST(PlatformConstants.REGISTRATION_TRANSACTIONS_SERVICE + "003", "Invalid request"), - - /** The rpr rts data population exception. */ - RPR_RTS_DATA_POPULATION_EXCEPTION(PlatformConstants.REGISTRATION_TRANSACTIONS_SERVICE + "004", - "globalMessages not found for input langCode"), - - /** The rpr rhs reg base exception. */ - RPR_RHS_REG_BASE_EXCEPTION(PlatformConstants.RPR_PACKET_REQUEST_HANDLER_MODULE + "004", - "reg Based checked exception"), - - /** The rpr details not found. */ - RPR_DETAILS_NOT_FOUND(PlatformConstants.RPR_ABIS_HANDLER + "001", "Abis Queue details not found"), - - /** The rpr no record found. */ - RPR_NO_RECORD_FOUND(PlatformConstants.RPR_ABIS_HANDLER + "002", - "Potential Match Records are Not Found for Demo Dedupe Potential Match"), - - /** The rpr error in abis handler identify request. */ - RPR_ERROR_IN_ABIS_HANDLER_IDENTIFY_REQUEST(PlatformConstants.RPR_ABIS_HANDLER + "004", - "Internal Error occured in Abis Handler identify request"), - - /** The rpr demo sending for manual. */ - RPR_DEMO_SENDING_FOR_MANUAL(PlatformConstants.RPR_DEMO_DEDUPE_MODULE + "001", - "ABIS response Details found. Hence sending to manual adjudication"), - - RPR_DEMO_API_RESOUCE_ACCESS_FAILED(PlatformConstants.RPR_DEMO_DEDUPE_MODULE + "002", - "Unable to Access API Resource"), - - RPR_SECUREZONE_FAILURE(PlatformConstants.RPR_SECUREZONE_NOTIFICATION_MODULE + "001", - "Exception occured in securezone notification stage. Check logs for more info"), - - RPR_SECUREZONE_DUPLICATE_PACKET(PlatformConstants.RPR_SECUREZONE_NOTIFICATION_MODULE + "002", - "Duplicate Packet against same additional info request Id."), - - RPR_AUTH_SYSTEM_EXCEPTION(PlatformConstants.RPR_AUTHENTICATION + "03", "Request could not be processed. Please try again"), - - /** The queue json validation failed. */ - QUEUE_JSON_VALIDATION_FAILED(PlatformConstants.RPR_MA_MIDDLEWARE + "004", - "Unable to find Connection Properties"), - - RPR_BIOMETRIC_EXTRACTION_FAILED(PlatformConstants.RPR_BIOMETRIC_EXTRACTION_STAGE + "000", - "biometric extraction failed"), - - RPR_BIOMETRIC_EXTRACTION_DRAFT_REQUEST_UNAVAILABLE(PlatformConstants.RPR_BIOMETRIC_EXTRACTION_STAGE + "001", - "Draft request is unavaialble in id-repo draft repository."), - /** The rpr ugs api resource exception. */ - RPR_BIOMETRIC_EXTRACTION_API_RESOURCE_EXCEPTION(PlatformConstants.RPR_BIOMETRIC_EXTRACTION_STAGE + "002", - "Not able to access the API resource"), - RPR_BIOMETRIC_EXTRACTION_NULL_RESPONSE(PlatformConstants.RPR_BIOMETRIC_EXTRACTION_STAGE + "003", - "null response from idrepo "), - RPR_PMS_BIOMETRIC_EXTRACTION_NULL_RESPONSE(PlatformConstants.RPR_BIOMETRIC_EXTRACTION_STAGE + "003", - "null response from partner service "), - /** The rpr finalization exception. */ - RPR_FINALIZATION_FAILED(PlatformConstants.RPR_FINALIZATION_STAGE + "001", - "finalization failed"), - RPR_FINALIZATION_FAILED_NULL_RESPONSE(PlatformConstants.RPR_FINALIZATION_STAGE + "002", - "null response from idrepo "), - RPR_FINALIZATION_STAGE_DRAFT_REQUEST_UNAVAILABLE(PlatformConstants.RPR_FINALIZATION_STAGE + "003", - "Draft request is unavaialble in id-repo draft repository."), - RPR_FINALIZATION_STAGE_API_RESOURCE_EXCEPTION(PlatformConstants.RPR_FINALIZATION_STAGE + "004", - "Not able to access the API resource"), - - INDIVIDUAL_BIOMETRIC_AUTHENTICATION_FAILED(PlatformConstants.RPR_BIOMETRIC_AUTHENTICATION_MODULE + "004", - "Bio authentication failed") - ; - - - - /** The error message. */ - private final String errorMessage; - - /** The error code. */ - private final String errorCode; - - /** - * Instantiates a new platform error messages. - * - * @param errorCode - * the error code - * @param errorMsg - * the error msg - */ - private PlatformErrorMessages(String errorCode, String errorMsg) { - this.errorCode = errorCode; - this.errorMessage = errorMsg; - } - - /** - * Gets the error message. - * - * @return the error message - */ - public String getMessage() { - return this.errorMessage; - } - - /** - * Gets the error code. - * - * @return the error code - */ - public String getCode() { - return this.errorCode; - } - +package io.mosip.registration.processor.core.exception.util; + +// TODO: Auto-generated Javadoc +/** + * The Enum RPRPlatformErrorMessages. + * + * @author M1047487 + */ +public enum PlatformErrorMessages { + + /** The rpr pkr packet not yet sync. */ + // Packet Receiver Exception error code and message + RPR_PKR_PACKET_NOT_YET_SYNC(PlatformConstants.RPR_PACKET_RECEIVER_MODULE + "001", "Packet Not Found in Sync Table"), + + /** The rpr pkr invalid packet size. */ + RPR_PKR_INVALID_PACKET_SIZE(PlatformConstants.RPR_PACKET_RECEIVER_MODULE + "002", "Invalid Packet Size"), + RPR_WORKFLOW_SEARCH_API_FAILED(PlatformConstants.RPR_WORKFLOW_SEARCH_API + "000", + "Process the workflow search failed"), + + /** The rpr pkr packet hash not equals synced hash. */ + RPR_PKR_PACKET_HASH_NOT_EQUALS_SYNCED_HASH(PlatformConstants.RPR_PACKET_RECEIVER_MODULE + "009", + "Packet HashSequence did not match"), + /** The prp pkr packet virus scan failed. */ + PRP_PKR_PACKET_VIRUS_SCAN_FAILED(PlatformConstants.RPR_PACKET_RECEIVER_MODULE + "010", "Virus was Found in Packet"), + /** The prp pkr packet virus scanner service failed. */ + PRP_PKR_PACKET_VIRUS_SCANNER_SERVICE_FAILED(PlatformConstants.RPR_PACKET_RECEIVER_MODULE + "008", + "Virus Scan Service is Not Responding"), + + /** The rpr pkr invalid packet format. */ + RPR_PKR_INVALID_PACKET_FORMAT(PlatformConstants.RPR_PACKET_RECEIVER_MODULE + "003", "Invalid Packet Format"), + + /** The rpr pkr validation exception. */ + RPR_PKR_VALIDATION_EXCEPTION(PlatformConstants.RPR_PACKET_RECEIVER_MODULE + "004", "Packet Validation Failed"), + + /** The rpr pkr duplicate packet recieved. */ + RPR_PKR_DUPLICATE_PACKET_RECIEVED(PlatformConstants.RPR_PACKET_RECEIVER_MODULE + "005", + "Duplicate Request Received"), + + /** The rpr pkr packet not available. */ + RPR_PKR_PACKET_NOT_AVAILABLE(PlatformConstants.RPR_PACKET_RECEIVER_MODULE + "006", + "Packet Not Available in Request"), + + /** The rpr pkr unknown exception. */ + RPR_PKR_UNKNOWN_EXCEPTION(PlatformConstants.RPR_PACKET_RECEIVER_MODULE + "007", "Unknown Exception Found"), + + /** The rpr pkr api resouce access failed. */ + RPR_PKR_API_RESOUCE_ACCESS_FAILED(PlatformConstants.RPR_PACKET_RECEIVER_MODULE + "011", + "Unable to Access API Resource"), + + /** The rpr pkr data access exception. */ + RPR_PKR_DATA_ACCESS_EXCEPTION(PlatformConstants.RPR_PACKET_RECEIVER_MODULE + "012", "Unable to Access Database"), + + /** The rpr pkr invalid packet size synced. */ + RPR_PKR_INVALID_PACKET_SIZE_SYNCED(PlatformConstants.RPR_PACKET_RECEIVER_MODULE + "013", + "Packet Size is Not Matching"), + + /** The rpr pkr invalid packet size synced. */ + UNEQUAL_PACKET_HASH_PR(PlatformConstants.RPR_PACKET_RECEIVER_MODULE + "014", + "The Registration Packet HashSequence is not equal as synced packet HashSequence"), + + /** The rpr pkr invalid packet size synced. */ + RPR_PKR_DECRYPTION_FAILED(PlatformConstants.RPR_PACKET_RECEIVER_MODULE + "015", "Packet Decryption Failed"), + + /** The rpr pkr invalid packet size synced. */ + RPR_PKR_ADDITIONAL_INFOID_NOT_FOUND(PlatformConstants.RPR_PACKET_RECEIVER_MODULE + "016", "Additional info request id not found"), + + /** The rpr rgs registration table not accessible. */ + // Registration Status Exception error code and message + RPR_RGS_REGISTRATION_TABLE_NOT_ACCESSIBLE(PlatformConstants.RPR_REGISTRATION_STATUS_MODULE + "001", + "Unable to Access Registration Table"), + + /** The rpr rgs transaction table not accessible. */ + RPR_RGS_TRANSACTION_TABLE_NOT_ACCESSIBLE(PlatformConstants.RPR_REGISTRATION_STATUS_MODULE + "002", + "Unable to Access Registration Transaction Table"), + + /** The rpr rgs anonymous profile table not accessible. */ + RPR_RGS_ANONYMOUS_PROFILE_TABLE_NOT_ACCESSIBLE(PlatformConstants.RPR_REGISTRATION_STATUS_MODULE + "038", + "Unable to anonymous profile Table"), + + /** The rpr rgs invalid synctype. */ + RPR_RGS_INVALID_SYNCTYPE(PlatformConstants.RPR_REGISTRATION_STATUS_MODULE + "003", "Invalid Sync Type"), + + /** The rpr rgs invalid languagecode. */ + RPR_RGS_INVALID_LANGUAGECODE(PlatformConstants.RPR_REGISTRATION_STATUS_MODULE + "004", + "Invalid Language Code - Language Code must be of Three Characters"), + + /** The rpr rgs invalid regid parentregid. */ + RPR_RGS_INVALID_REGID_PARENTREGID(PlatformConstants.RPR_REGISTRATION_STATUS_MODULE + "005", + "Invalid Request Value - RID and Parent RID are Same"), + + /** The rpr rgs empty registrationid. */ + RPR_RGS_EMPTY_REGISTRATIONID(PlatformConstants.RPR_REGISTRATION_STATUS_MODULE + "006", + "Invalid Request Value - RID cannot be NULL"), + + /** The rpr rgs invalid registrationid timestamp. */ + RPR_RGS_INVALID_REGISTRATIONID_TIMESTAMP(PlatformConstants.RPR_REGISTRATION_STATUS_MODULE + "007", + "Invalid Request Value - Invalid Timestamp in RID"), + + /** The rpr rgs invalid registrationid. */ + RPR_RGS_INVALID_REGISTRATIONID(PlatformConstants.RPR_REGISTRATION_STATUS_MODULE + "008", + "Invalid Request Value - RID must be Numberic"), + + /** The rpr rgs invalid registrationid length. */ + RPR_RGS_INVALID_REGISTRATIONID_LENGTH(PlatformConstants.RPR_REGISTRATION_STATUS_MODULE + "009", + "Invalid Request Value - RID Length is not as per Configuration"), + + /** The rpr rgs invalid prid timestamp. */ + RPR_RGS_INVALID_PRID_TIMESTAMP(PlatformConstants.RPR_REGISTRATION_STATUS_MODULE + "010", + "Invalid Request Value - Invalid Timestamp in Parent RID"), + + /** The rpr rgs invalid prid. */ + RPR_RGS_INVALID_PRID(PlatformConstants.RPR_REGISTRATION_STATUS_MODULE + "011", + "Invalid Request Value - Parent RID must be Numeric"), + + /** The rpr rgs invalid prid length. */ + RPR_RGS_INVALID_PRID_LENGTH(PlatformConstants.RPR_REGISTRATION_STATUS_MODULE + "012", + "Invalid Request Value - Parent RID Length is not as per Configuration"), + + /** The missing input parameter. */ + RPR_RGS_MISSING_INPUT_PARAMETER(PlatformConstants.RPR_REGISTRATION_STATUS_MODULE + "013", + "Missing Request Value - %s"), + + /** The invalid input parameter. */ + RPR_RGS_INVALID_INPUT_PARAMETER(PlatformConstants.RPR_REGISTRATION_STATUS_MODULE + "014", + "Invalid Request Value - %s"), + + /** The data validation failed. */ + RPR_RGS_DATA_VALIDATION_FAILED(PlatformConstants.RPR_REGISTRATION_STATUS_MODULE + "015", + "Invalid Request Value - Input Data is Incorrect"), + + /** The rpr rgs json mapping exception. */ + RPR_RGS_JSON_MAPPING_EXCEPTION(PlatformConstants.RPR_REGISTRATION_STATUS_MODULE + "016", "JSON Mapping Failed"), + + /** The rpr rgs json parsing exception. */ + RPR_RGS_JSON_PARSING_EXCEPTION(PlatformConstants.RPR_REGISTRATION_STATUS_MODULE + "017", "JSON Parsing Failed"), + + /** The rpr rgs unknown exception. */ + RPR_RGS_UNKNOWN_EXCEPTION(PlatformConstants.RPR_REGISTRATION_STATUS_MODULE + "018", "Unknown Exception Found"), + + /** The rpr rgs missing input parameter version. */ + RPR_RGS_MISSING_INPUT_PARAMETER_VERSION(PlatformConstants.RPR_REGISTRATION_STATUS_MODULE + "019", + "Missing Request Value - version"), + + /** The rpr rgs missing input parameter timestamp. */ + RPR_RGS_MISSING_INPUT_PARAMETER_TIMESTAMP(PlatformConstants.RPR_REGISTRATION_STATUS_MODULE + "020", + "Missing Request Parameter - requesttime"), + + /** The rpr rgs missing input parameter id. */ + RPR_RGS_MISSING_INPUT_PARAMETER_ID(PlatformConstants.RPR_REGISTRATION_STATUS_MODULE + "021", + "Missing Request Parameter - id"), + + /** The rpr rgs invalid input parameter version. */ + RPR_RGS_INVALID_INPUT_PARAMETER_VERSION(PlatformConstants.RPR_REGISTRATION_STATUS_MODULE + "022", + "Invalid Request Parameter - version"), + + /** The rpr rgs invalid input parameter timestamp. */ + RPR_RGS_INVALID_INPUT_PARAMETER_TIMESTAMP(PlatformConstants.RPR_REGISTRATION_STATUS_MODULE + "023", + "Invalid Request Parameter - requesttime"), + + /** The rpr rgs invalid input parameter id. */ + RPR_RGS_INVALID_INPUT_PARAMETER_ID(PlatformConstants.RPR_REGISTRATION_STATUS_MODULE + "024", + "Invalid Request Parameter - id"), + + /** The rpr rgs registration status not exist. */ + RPR_RGS_REGISTRATION_STATUS_NOT_EXIST(PlatformConstants.RPR_REGISTRATION_STATUS_MODULE + "025", + "Invalid Request Value - Status Code is NULL"), + + /** The rpr rgs invalid supervisor status. */ + RPR_RGS_INVALID_SUPERVISOR_STATUS(PlatformConstants.RPR_REGISTRATION_STATUS_MODULE + "026", + "Invalid Request Value - Supervisor Status can be APPROVED/REJECTED"), + + /** The rpr rgs invalid hashvalue. */ + RPR_RGS_INVALID_HASHVALUE(PlatformConstants.RPR_REGISTRATION_STATUS_MODULE + "027", + "Invalid Request Value - Hash Sequence is NULL"), + + /** The rpr rgs decryption failed. */ + RPR_RGS_DECRYPTION_FAILED(PlatformConstants.RPR_REGISTRATION_STATUS_MODULE + "028", "Request Decryption Failed"), + + /** The rpr rgs registration sync service failed. */ + RPR_RGS_REGISTRATION_SYNC_SERVICE_FAILED(PlatformConstants.RPR_REGISTRATION_STATUS_MODULE + "029", "SYNC Failed"), + + /** The rpr rgs data access exception. */ + RPR_RGS_DATA_ACCESS_EXCEPTION(PlatformConstants.RPR_REGISTRATION_STATUS_MODULE + "030", + "DataAccessLayerException while syncing Registartion Id's"), + /** The rpr rgs rid not found. */ + RPR_RGS_RID_NOT_FOUND(PlatformConstants.RPR_REGISTRATION_STATUS_MODULE + "031", "RID Not Found"), + + RPR_RGS_INVALID_ADDITIONAL_INFORMATION(PlatformConstants.RPR_REGISTRATION_STATUS_MODULE + "036", "additionalInfoReqId is invalid"), + + RPR_RGS_PACKETID_NOT_FOUND(PlatformConstants.RPR_REGISTRATION_STATUS_MODULE + "037", "PacketId Not Found"), + + RPR_RGS_INVALID_SEARCH(PlatformConstants.RPR_REGISTRATION_STATUS_MODULE + "032", "plz narrow down your search"), + + RPR_RGS_SORTING_VALIDATION_FAILED(PlatformConstants.RPR_REGISTRATION_STATUS_MODULE + "033", + "sorting not supported for more than 1 field - %s"), + + RPR_RGS_DATE_VALIDATION_FAILED(PlatformConstants.RPR_REGISTRATION_STATUS_MODULE + "034", + "searching between date should be less then 30 days - %s"), + + /** The rpr rgs io exception */ + RPR_RGS_IOEXCEPTION(PlatformConstants.RPR_REGISTRATION_STATUS_MODULE + "035" , "IO Exception"), + + LINK_FOR_USERID_INDIVIDUALID_FAILED_STATUS_EXCEPTION(PlatformConstants.RPR_REGISTRATION_STATUS_MODULE + "035", + "Unable to get the IndividualId for UserId"), + + UNABLE_TO_ACCESS_API(PlatformConstants.RPR_REGISTRATION_STATUS_MODULE + "036", + "Unable to access API"), + + /** The rpr pis registration table not accessible. */ + // Packet Info Storage Exception error code and message + RPR_PIS_REGISTRATION_TABLE_NOT_ACCESSIBLE(PlatformConstants.RPR_PACKET_INFO_STORAGE_MODULE + "001", + "Unable to Access Registration Table"), + /** The rpr pis identity not found. */ + RPR_PIS_IDENTITY_NOT_FOUND(PlatformConstants.RPR_PACKET_INFO_STORAGE_MODULE + "002", + "Unable to Find Identity Field in ID JSON"), + /** The rpr pis unable to insert data. */ + RPR_PIS_UNABLE_TO_INSERT_DATA(PlatformConstants.RPR_PACKET_INFO_STORAGE_MODULE + "003", + "Unable to Insert Data in DB"), + /** The rpr pis file not found in Packet Store. */ + RPR_PIS_FILE_NOT_FOUND_IN_PACKET_STORE(PlatformConstants.RPR_PACKET_INFO_STORAGE_MODULE + "004", + "Unable to Find File in Packet Store"), + + /** The rpr pis abis queue connection null. */ + RPR_PIS_ABIS_QUEUE_CONNECTION_NULL(PlatformConstants.RPR_PACKET_INFO_STORAGE_MODULE + "005", + "Unable to Find ABIS Queue Connection"), + + GET_FIELD_ERROR(PlatformConstants.RPR_PACKET_INFO_STORAGE_MODULE + "006", + "Not able to read field from packet manager"), + + GET_DOC_ERROR(PlatformConstants.RPR_PACKET_INFO_STORAGE_MODULE + "007", + "Not able to read document from packet manager"), + + GET_BIOMETRIC_ERROR(PlatformConstants.RPR_PACKET_INFO_STORAGE_MODULE + "008", + "Not able to read biometric from packet manager"), + + GET_AUDIT_ERROR(PlatformConstants.RPR_PACKET_INFO_STORAGE_MODULE + "009", + "Not able to read audit from packet manager"), + + GET_METAINFO_ERROR(PlatformConstants.RPR_PACKET_INFO_STORAGE_MODULE + "010", + "Not able to read meta info from packet manager"), + + VALIDATE_ERROR(PlatformConstants.RPR_PACKET_INFO_STORAGE_MODULE + "011", + "Not able to validate packet using packet manager provider."), + + PACKET_MANAGER_EXCEPTION(PlatformConstants.RPR_PACKET_INFO_STORAGE_MODULE + "012", + "Exception occured in packet manager."), + + /** The rpr fac connection not available. */ + // File adaptor Exception error code and message + RPR_FAC_CONNECTION_NOT_AVAILABLE(PlatformConstants.RPR_FILESYSTEM_ADAPTOR_CEPH_MODULE + "001", + "Unable to Find Connection Parameter for Packet Store"), + + /** The rpr fac invalid connection parameters. */ + RPR_FAC_INVALID_CONNECTION_PARAMETERS(PlatformConstants.RPR_FILESYSTEM_ADAPTOR_CEPH_MODULE + "002", + "Invalid Connection Parameter for Packet Store"), + + /** The rpr fac packet not available. */ + RPR_FAC_PACKET_NOT_AVAILABLE(PlatformConstants.RPR_FILESYSTEM_ADAPTOR_CEPH_MODULE + "003", + "Packet Not Found in Packet Store"), + + /** The rpr pkm file path not accessible. */ + // Packet Manager Exception error code and message + RPR_PKM_FILE_PATH_NOT_ACCESSIBLE(PlatformConstants.RPR_PACKET_MANAGER_MODULE + "002", + "Unable to Access the Folder Path"), + + /** The rpr pkm file not found in destination. */ + RPR_PKM_FILE_NOT_FOUND_IN_DESTINATION(PlatformConstants.RPR_PACKET_MANAGER_MODULE + "003", + "Unable to Find File in Destination Folder"), + + /** The rpr pkm file not found in source. */ + RPR_PKM_FILE_NOT_FOUND_IN_SOURCE(PlatformConstants.RPR_PACKET_MANAGER_MODULE + "004", + "Unable to Find File in Source Folder"), + + /** The rpr pkm file not found in source. */ + RPR_PKM_JSCH_NOT_CONNECTED(PlatformConstants.RPR_PACKET_MANAGER_MODULE + "005", "JSCH Connection Failed"), + + /** The rpr pkm file not found in source. */ + RPR_PKM_SFTP_FILE_OPERATION_FAILED(PlatformConstants.RPR_PACKET_MANAGER_MODULE + "006", "SFTP Operation Failed"), + + /** The rpr pkm file not found in source. */ + RPR_PKM_PWD_PPK_NOT_PRESENT(PlatformConstants.RPR_PACKET_MANAGER_MODULE + "007", + "Both DMZ password and PPK file name are not available in config"), + + // Registration processor camel bridge Exception error code and message + + /** The rpr cmb deployment failure. */ + RPR_CMB_DEPLOYMENT_FAILURE(PlatformConstants.RPR_CAMEL_BRIDGE_MODULE + "001", "Camel Bridge Deployment Failure"), + + /** The rpr cmb unsupported encoding. */ + RPR_CMB_UNSUPPORTED_ENCODING(PlatformConstants.RPR_CAMEL_BRIDGE_MODULE + "002", "Unsupported Failure"), + + /** The rpr cmb configuration server failure exception. */ + RPR_CMB_CONFIGURATION_SERVER_FAILURE_EXCEPTION(PlatformConstants.RPR_CAMEL_BRIDGE_MODULE + "003", + "Configuration Server Failure"), + + /** The rpr cmb malformed cluster manager url exception. */ + RPR_CMB_MALFORMED_URL_EXCEPTION(PlatformConstants.RPR_CAMEL_BRIDGE_MODULE + "004", + "Malformed Cluster Manager URL Exception"), + + /** The rpr cmb unknown host exception. */ + RPR_CMB_UNKNOWN_HOST_EXCEPTION(PlatformConstants.RPR_CAMEL_BRIDGE_MODULE + "005", "Unknown Host Exception"), + + + RPR_CMB_WORKFLOW_COMMAND_NOT_SUPPORTED(PlatformConstants.RPR_CAMEL_BRIDGE_MODULE + "006", + "Workflow command not supported"), + + /** The rpr qcr registration table not accessible. */ + // Quality Checker Exception error code and message + RPR_QCR_REGISTRATION_TABLE_NOT_ACCESSIBLE(PlatformConstants.RPR_QUALITY_CHECKER_MODULE + "001", + "Unable to Access Registration Table"), + + /** The rpr qcr result not found. */ + RPR_QCR_RESULT_NOT_FOUND(PlatformConstants.RPR_QUALITY_CHECKER_MODULE + "002", "Result Not Found"), + + /** The rpr qcr invalid qc user id. */ + RPR_QCR_INVALID_QC_USER_ID(PlatformConstants.RPR_QUALITY_CHECKER_MODULE + "003", "Invalid QC User ID"), + + /** The rpr qcr invalid registration id. */ + RPR_QCR_INVALID_REGISTRATION_ID(PlatformConstants.RPR_QUALITY_CHECKER_MODULE + "004", + "Invalid Registration ID - RID is NULL"), + + /** The rpr qcr file name missing. */ + RPR_QCR_FILENAME_MISSING(PlatformConstants.RPR_QUALITY_CHECKER_MODULE + "006", + "Unable to Find Biometric File Name in ID JSON"), + + /** The rpr qcr bio file missing. */ + RPR_QCR_BIO_FILE_MISSING(PlatformConstants.RPR_QUALITY_CHECKER_MODULE + "007", + "Unable to Find Biometric File in Packet"), + + /** The rpr qcr biometric exception. */ + RPR_QCR_BIOMETRIC_EXCEPTION(PlatformConstants.RPR_QUALITY_CHECKER_MODULE + "007", + "Biometric Exception received form IDA"), + + /** The rpr qcr biometric exception. */ + RPR_QCR_BIOMETRIC_TYPE_EXCEPTION(PlatformConstants.RPR_QUALITY_CHECKER_MODULE + "008", + "Requested biometric type not found"), + + /** The rpr qcr biometric exception. */ + INDIVIDUAL_BIOMETRIC_NOT_FOUND(PlatformConstants.RPR_QUALITY_CHECKER_MODULE + "009", + "Individual Biometric Parameter Not Found in ID JSON so skipping biometric classification"), + + /** The rpr qcr biometric exception. */ + BIOMETRIC_QUALITY_CHECK_FAILED(PlatformConstants.RPR_QUALITY_CHECKER_MODULE + "010", + "Quality Score of Biometrics Captured is Below the Threshold"), + + /** The rpr qcr packet store not accessible. */ + RPR_QCR_PACKET_STORE_NOT_ACCESSIBLE(PlatformConstants.RPR_QUALITY_CHECKER_MODULE + "011", + "The Packet store set by the System is not accessible"), + + /** The packet upload failed. */ + PACKET_UPLOAD_FAILED("", "Packet Upload failed"), + + /** The structural validation failed. */ + // Stages - Packet validator Exception error code and message + STRUCTURAL_VALIDATION_FAILED(PlatformConstants.RPR_PACKET_VALIDATOR_MODULE + "015", "Structural Validation Failed"), + + /** The rpr pvm data not available. */ + RPR_PVM_DATA_NOT_AVAILABLE(PlatformConstants.RPR_PACKET_VALIDATOR_MODULE + "002", + "Data Not Available in Master DB"), + /** The rpr pvm update packet deactivated. */ + RPR_PVM_UPDATE_DEACTIVATED(PlatformConstants.RPR_PACKET_VALIDATOR_MODULE + "014", "UIN is Deactivated"), + + /** The rpr pvm identity not found. */ + RPR_PVM_IDENTITY_NOT_FOUND(PlatformConstants.RPR_PACKET_VALIDATOR_MODULE + "003", + "Attribute Not Available in ID JSON for Master Data Validation"), + + /** The rpr pvm resource not found. */ + RPR_PVM_RESOURCE_NOT_FOUND(PlatformConstants.RPR_PACKET_VALIDATOR_MODULE + "004", + "Resource Not Found for Master Data Validation"), + + /** The rpr pvm identity invalid. */ + RPR_PVM_IDENTITY_INVALID(PlatformConstants.RPR_PACKET_VALIDATOR_MODULE + "005", + "Invalid Attribute Value for Master Data Validation"), + + /** The rpr pvm api resouce access failed. */ + RPR_PVM_API_RESOUCE_ACCESS_FAILED(PlatformConstants.RPR_PACKET_VALIDATOR_MODULE + "006", + "Unable to Access API Resource"), + + /** The rpr pvm base unchecked exception. */ + RPR_PVM_BASE_UNCHECKED_EXCEPTION(PlatformConstants.RPR_PACKET_VALIDATOR_MODULE + "007", + "ID Schema Validation Failed"), + + /** The rpr pvm base checked exception. */ + RPR_PVM_BASE_CHECKED_EXCEPTION(PlatformConstants.RPR_PACKET_VALIDATOR_MODULE + "013", + "ID Schema Validation Failed"), + + /** The rpr pvm mandatory field missing. */ + RPR_PVM_MANDATORY_FIELD_MISSING(PlatformConstants.RPR_PACKET_VALIDATOR_MODULE + "010", + "Mandatory Field Validation Failed"), + + /** The rpr pvm record not matched from sync table. */ + RPR_PVM_RECORD_NOT_MATCHED_FROM_SYNC_TABLE(PlatformConstants.RPR_PACKET_VALIDATOR_MODULE + "011", + "RID or Registration Type Mismatch"), + + /** The rpr pvm invalid uin. */ + RPR_PVM_INVALID_UIN(PlatformConstants.RPR_PACKET_VALIDATOR_MODULE + "012", "Invalid UIN"), + + /** The rpr pvm document type invalid. */ + RPR_PVM_DOCUMENT_TYPE_INVALID(PlatformConstants.RPR_PACKET_VALIDATOR_MODULE + "008", + "Invalid Document Type for Document Validation"), + + /** The rpr pvm idjson not found. */ + RPR_PVM_IDJSON_NOT_FOUND(PlatformConstants.RPR_PACKET_VALIDATOR_MODULE + "009", "ID JSON Not Found"), + + /** The rpr pvm applicantdocument validation failed. */ + RPR_PVM_APPLICANTDOCUMENT_VALIDATION_FAILED(PlatformConstants.RPR_PACKET_VALIDATOR_MODULE + "010", + "Applicant Document Validation Failed"), + + RPR_PVM_PACKET_REJECTED(PlatformConstants.RPR_PACKET_VALIDATOR_MODULE + "011", + "Rejected by Supervisor"), + + RPR_PVM_PACKET_CREATED_DATE_TIME_EMPTY_OR_NULL(PlatformConstants.RPR_PACKET_VALIDATOR_MODULE + "017", + "Packet Created Date time is Null or Empty"), + + RPR_PVM_PACKET_CREATED_DATE_TIME_PARSE_EXCEPTION(PlatformConstants.RPR_PACKET_VALIDATOR_MODULE + "018", + "Packet Created Date time is not in correct format"), + + RPR_PVM_INVALID_ARGUMENT_EXCEPTION(PlatformConstants.RPR_PACKET_VALIDATOR_MODULE + "019", + "Invalid Argument"), + + + /** The packet classification failed. */ + PACKET_CLASSIFICATION_FAILED(PlatformConstants.RPR_PACKET_CLASSIFIER_MODULE + "000", "Packet Classification failed"), + + /** The rpr pcm base unchecked exception. */ + RPR_PCM_BASE_UNCHECKED_EXCEPTION(PlatformConstants.RPR_PACKET_CLASSIFIER_MODULE + "001", + "Packet Classification failed"), + + /** The rpr pcm base checked exception. */ + RPR_PCM_BASE_CHECKED_EXCEPTION(PlatformConstants.RPR_PACKET_CLASSIFIER_MODULE + "002", + "Tag generation failed"), + + /** The rpr pcm idobject required field name fetching failed. */ + RPR_PCM_COLLECT_IDOBJECT_FIELD_FAILED(PlatformConstants.RPR_PACKET_CLASSIFIER_MODULE + "003", + "Getting the required Id object field names from tag generator failed"), + + /** The rpr pcm accessing idobject mapping file failed. */ + RPR_PCM_ACCESSING_IDOBJECT_MAPPING_FILE_FAILED(PlatformConstants.RPR_PACKET_CLASSIFIER_MODULE + "004", + "Accessing Idobject mapping file filed"), + + /** The rpr pcm unknown schema data type found. */ + RPR_PCM_UNKNOWN_SCHEMA_DATA_TYPE(PlatformConstants.RPR_PACKET_CLASSIFIER_MODULE + "005", + "Field's schema data type is not supported"), + + /** The rpr pcm schema data type json parsing failed. */ + RPR_PCM_SCHEMA_DATA_TYPE_JSON_PARSING_FAILED(PlatformConstants.RPR_PACKET_CLASSIFIER_MODULE + "006", + "JSON parsing of field value according to the schema type failed"), + + /** The rpr pcm data object mapping failed. */ + RPR_PCM_DATA_OBJECT_MAPPING_FAILED(PlatformConstants.RPR_PACKET_CLASSIFIER_MODULE + "007", + "JSON parsing to java object failed"), + + /** The rpr pcm meta info json parsing failed. */ + RPR_PCM_META_INFO_JSON_PARSING_FAILED(PlatformConstants.RPR_PACKET_CLASSIFIER_MODULE + "008", + "JSON parsing of meta info failed"), + + /** The rpr pcm mapping field name is not present in identity mapping json. */ + RPR_PCM_FIELD_NAME_NOT_AVAILABLE_IN_MAPPING_JSON(PlatformConstants.RPR_PACKET_CLASSIFIER_MODULE + "009", + "Mapping field name is not present in identity mapping json"), + + /** The rpr pcm value not available in configured language. */ + RPR_PCM_VALUE_NOT_AVAILABLE_IN_CONFIGURED_LANGUAGE(PlatformConstants.RPR_PACKET_CLASSIFIER_MODULE + "010", + "Value not available in configured language for field"), + + /** The rpr pcm fieldDTO or non string field value is null. */ + RPR_PCM_FIELD_DTO_OR_NON_STRING_FIELD_IS_NULL(PlatformConstants.RPR_PACKET_CLASSIFIER_MODULE + "011", + "FieldDTO or non string field value is null"), + + /** The rpr pcm sync registration entity not available null. */ + RPR_PCM_SYNC_REGISTRATION_ENTITY_NOT_AVAILABLE(PlatformConstants.RPR_PACKET_CLASSIFIER_MODULE + "012", + "sync registration entity not available"), + + /** The rpr pcm exception biometrics entry not avaiable in metainfo map. */ + RPR_PCM_EXCEPTION_BIOMETRICS_ENTRY_NOT_AVAILABLE(PlatformConstants.RPR_PACKET_CLASSIFIER_MODULE + "013", + "ExceptionBiometrics entry not available in metainfo map"), + + /** The rpr pcm operations data entry not avaiable in metainfo map. */ + RPR_PCM_OPERATIONS_DATA_ENTRY_NOT_AVAILABLE(PlatformConstants.RPR_PACKET_CLASSIFIER_MODULE + "014", + "Operations data entry not avaiable in metainfo map"), + + /** The rpr pcm meta data entry not avaiable in metainfo map. */ + RPR_PCM_META_DATA_ENTRY_NOT_AVAILABLE(PlatformConstants.RPR_PACKET_CLASSIFIER_MODULE + "015", + "Meta data entry not avaiable in metainfo map"), + + /** The rpr pcm ageGroupRangeMap does not contain group for given age. */ + RPR_PCM_AGE_GROUP_NOT_FOUND(PlatformConstants.RPR_PACKET_CLASSIFIER_MODULE + "016", + "Age Group Range Map configuration does not contain age group for given age"), + + /** The rpr pcm Captured Registered Devices entry not avaiable in metainfo map. */ + RPR_PCM_CAPTURED_REGISTERED_DEVICES_ENTRY_NOT_AVAILABLE(PlatformConstants.RPR_PACKET_CLASSIFIER_MODULE + "017", + "Captured registered devices entry not avaiable in metainfo map"), + + /** The rpr pcm exception biometrics entry not avaiable in metainfo map. */ + RPR_PCM_EXCEPTION_BIOMETRICS_APPLICANT_ENTRY_NOT_AVAILABLE(PlatformConstants.RPR_PACKET_CLASSIFIER_MODULE + "018", + "ExceptionBiometrics applicant entry not available in metainfo map"), + + /** The unsupported encoding. */ + // UIN check - JSON file encoding failed. + UNSUPPORTED_ENCODING(PlatformConstants.RPR_BIO_DEDUPE_SERVICE_MODULE + "005", "Json Object Parsing Failed"), + + OSI_VALIDATION_BIO_TYPE_EXCEPTION(PlatformConstants.RPR_CMD_VALIDATOR_MODULE + "007", "Bio Type Exception"), + + /** The cmd validation failed. */ + // Stages - CMD Exception error code and message + CMD_VALIDATION_FAILED(PlatformConstants.RPR_CMD_VALIDATOR_MODULE + "000", "CMD Validation Failed"), + + /** The cmd base unchecked exception. */ + CMD_BASE_UNCHECKED_EXCEPTION(PlatformConstants.RPR_CMD_VALIDATOR_MODULE + "001", + "CMD Validation Failed"), + + /** The cmd base checked exception. */ + CMD_BASE_CHECKED_EXCEPTION(PlatformConstants.RPR_CMD_VALIDATOR_MODULE + "002", + "CMD Validation Failed"), + + /** The operator base unchecked exception. */ + OPERATOR_BASE_UNCHECKED_EXCEPTION(PlatformConstants.RPR_OVM_VALIDATOR_MODULE + "001", + "operator Validation Failed"), + + /** The operator base checked exception. */ + OPERATOR_BASE_CHECKED_EXCEPTION(PlatformConstants.RPR_OVM_VALIDATOR_MODULE + "002", + "operator Validation Failed"), + + /** The Operator validation failed. */ + OPERATOR_VALIDATION_FAILED(PlatformConstants.RPR_OVM_VALIDATOR_MODULE + "000", "Operator Validation Failed"), + + LINK_FOR_USERID_INDIVIDUALID_FAILED_OVM_EXCEPTION(PlatformConstants.RPR_OVM_VALIDATOR_MODULE + "003", + "Unable to get the IndividualId for UserId"), + + /** The Supervisor base unchecked exception. */ + SUPERVISOR_BASE_UNCHECKED_EXCEPTION(PlatformConstants.RPR_SVM_VALIDATOR_MODULE + "001", + "Supervisor Validation Failed"), + + /** The Supervisor base checked exception. */ + SUPERVISOR_BASE_CHECKED_EXCEPTION(PlatformConstants.RPR_SVM_VALIDATOR_MODULE + "002", + "Supervisor Validation Failed"), + + /** The Supervisor validation failed. */ + SUPERVISOR_VALIDATION_FAILED(PlatformConstants.RPR_SVM_VALIDATOR_MODULE + "000", "Supervisor Validation Failed"), + + LINK_FOR_USERID_INDIVIDUALID_FAILED_SVM_EXCEPTION(PlatformConstants.RPR_SVM_VALIDATOR_MODULE + "003", + "Unable to get the IndividualId for UserId"), + + /** The INTRODUCER base unchecked exception. */ + INTRODUCER_BASE_UNCHECKED_EXCEPTION(PlatformConstants.RPR_IVM_VALIDATOR_MODULE + "001", + "INTRODUCER Validation Failed"), + + /** The INTRODUCER base checked exception. */ + INTRODUCER_BASE_CHECKED_EXCEPTION(PlatformConstants.RPR_IVM_VALIDATOR_MODULE + "002", + "INTRODUCER Validation Failed"), + + /** The INTRODUCER validation failed. */ + INTRODUCER_VALIDATION_FAILED(PlatformConstants.RPR_IVM_VALIDATOR_MODULE + "000", "INTRODUCER Validation Failed"), + + /** The INTRODUCER validation failed. */ + INTRODUCER_ON_HOLD(PlatformConstants.RPR_IVM_VALIDATOR_MODULE + "001", "Packet on hold as introducer packet is not processed yet"), + + /** The packet demo dedupe failed. */ + // Stages - Demo-Dedupe error code and message + PACKET_DEMO_DEDUPE_FAILED(PlatformConstants.RPR_DEMO_DEDUPE_MODULE+"000", "Demo Dedupe Failed"), + + /** The packet demo packet store not accessible. */ + PACKET_DEMO_PACKET_STORE_NOT_ACCESSIBLE(PlatformConstants.RPR_DEMO_DEDUPE_MODULE+"003", "Unable to Access Packet Store"), + + /** The packet bio dedupe cbeff not present. */ + PACKET_BIO_DEDUPE_CBEFF_NOT_PRESENT(PlatformConstants.RPR_BIO_DEDUPE_STAGE_MODULE + "001", + "Unable to Find Applicant CBEFF for Adult"), + + /** The registration id not found. */ + REGISTRATION_ID_NOT_FOUND(PlatformConstants.RPR_BIO_DEDUPE_STAGE_MODULE + "002", + "RegistrationId not found for given bio ref Id"), + + /** The rpr bio lost packet multiple match found. */ + RPR_BIO_LOST_PACKET_MULTIPLE_MATCH_FOUND(PlatformConstants.RPR_BIO_DEDUPE_STAGE_MODULE + "003", + "Multiple Match was Found for the Biometrics Received"), + + RPR_BIO_API_RESOUCE_ACCESS_FAILED(PlatformConstants.RPR_BIO_DEDUPE_STAGE_MODULE + "004", + "Unable to Access API Resource"), + + /** The abis reference id not found. */ + // stages - Abis Middleware + ABIS_REFERENCE_ID_NOT_FOUND(PlatformConstants.RPR_ABIS_MIDDLEWARE + "001", "Unable to Find ABIS Reference ID"), + + /** The latest transaction id not found. */ + LATEST_TRANSACTION_ID_NOT_FOUND(PlatformConstants.RPR_ABIS_MIDDLEWARE + "002", + "Unable to Find Latest Transaction ID"), + + /** The identify requests not found. */ + IDENTIFY_REQUESTS_NOT_FOUND(PlatformConstants.RPR_ABIS_MIDDLEWARE + "003", "Unable to Find Identify Request"), + + /** The abis queue json validation failed. */ + ABIS_QUEUE_JSON_VALIDATION_FAILED(PlatformConstants.RPR_ABIS_MIDDLEWARE + "004", + "Unable to Find ABIS Connection Properties"), + + /** The unknown exception occured. */ + UNKNOWN_EXCEPTION_OCCURED(PlatformConstants.RPR_ABIS_MIDDLEWARE + "005", "Unknown Exception Found"), + + /** ABIS_BATCH_ID_NOT_FOUND. */ + ABIS_BATCH_ID_NOT_FOUND(PlatformConstants.RPR_ABIS_MIDDLEWARE + "006", "Unable to Find ABIS Batch ID"), + + /** The abis queue not found. */ + ABIS_QUEUE_NOT_FOUND(PlatformConstants.RPR_ABIS_MIDDLEWARE + "007", "Unable to Connect with ABIS Queue"), + + /** The system exception occured. */ + SYSTEM_EXCEPTION_OCCURED(PlatformConstants.RPR_ABIS_MIDDLEWARE + "008", "Internal error occured"), + + DUPLICATE_INSERT_RESPONSE(PlatformConstants.RPR_ABIS_MIDDLEWARE + "009", + "Duplicate Insert Response received from abis for same request id : "), + + DUPLICATE_IDENTITY_RESPONSE(PlatformConstants.RPR_ABIS_MIDDLEWARE + "010", + "Duplicate Identify Response received from abis for same request id : "), + + /** The packet bio dedupe failed. */ + // Stages - Bio-Dedupe error code and message + PACKET_BIO_DEDUPE_FAILED(PlatformConstants.RPR_BIO_DEDUPE_SERVICE_MODULE + "001", "Bio Dedupe Failed"), + + /** The reverse data sync failed. */ + PACKET_BDD_PACKET_STORE_NOT_ACCESSIBLE(PlatformConstants.RPR_BIO_DEDUPE_SERVICE_MODULE + "002", + "Unable to Access Packet from Packet Store"), + + /** The rpr bio biometric insertion to abis. */ + RPR_BIO_BIOMETRIC_INSERTION_TO_ABIS(PlatformConstants.RPR_BIO_DEDUPE_SERVICE_MODULE + "003", + "Biometric Insertion Failed in ABIS"), + + /** The rpr abis internal error. */ + RPR_ABIS_INTERNAL_ERROR(PlatformConstants.RPR_BIO_DEDUPE_SERVICE_MODULE + "004", "ABIS Internal Error Occurred"), + + DATASHARE_ERROR(PlatformConstants.RPR_BIO_DEDUPE_SERVICE_MODULE + "005", "Datashare exception occured"), + + /** The reverse data sync failed. */ + // Stages - Packet-Validator error message + REVERSE_DATA_SYNC_FAILED(PlatformConstants.RPR_PACKET_VALIDATOR_MODULE + "016", "Reverse Data Sync Failed"), + + /** The Biometric-Authentication stage failed. */ + // stages - Biometric-Authentication stage error code and message + BIOMETRIC_AUTHENTICATION_FAILED(PlatformConstants.RPR_BIOMETRIC_AUTHENTICATION_MODULE, + "Biometric Authentication Failed"), + + /** The Biometric-Authentication io exception. */ + BIOMETRIC_AUTHENTICATION_IOEXCEPTION(PlatformConstants.RPR_BIOMETRIC_AUTHENTICATION_MODULE + "001", "IO Exception"), + + /** The Biometric-Authentication api resource exception. */ + BIOMETRIC_AUTHENTICATION_API_RESOURCE_EXCEPTION(PlatformConstants.RPR_BIOMETRIC_AUTHENTICATION_MODULE + "002", + "Unable to Access API Resource"), + + BIOMETRIC_AUTHENTICATION_TABLE_NOT_ACCESSIBLE(PlatformConstants.RPR_BIOMETRIC_AUTHENTICATION_MODULE + "004", + "Unable to Access Registration Table"), + + BIOMETRIC_AUTHENTICATION_AUTH_SYSTEM_EXCEPTION(PlatformConstants.RPR_BIOMETRIC_AUTHENTICATION_MODULE + "003", + "Request could not be processed. Please try again"), + + /** The rpr psj Packet Store not accessible. */ + // Packet scanner job Exception error code and message + RPR_PSJ_PACKET_STORE_NOT_ACCESSIBLE(PlatformConstants.RPR_PACKET_SCANNER_JOB_MODULE + "002", + "The Packet store set by the System is not accessible"), + + /** The rpr psj retry folder not accessible. */ + RPR_PSJ_RETRY_FOLDER_NOT_ACCESSIBLE(PlatformConstants.RPR_PACKET_SCANNER_JOB_MODULE + "003", + "The Retry folder set by the System is not accessible"), + + /** The rpr psj virus scan folder not accessible. */ + RPR_PSJ_VIRUS_SCAN_FOLDER_NOT_ACCESSIBLE(PlatformConstants.RPR_PACKET_SCANNER_JOB_MODULE + "004", + "The Virus scanner set by the System is not accessible"), + + /** The rpr psj space unavailable for retry folder. */ + RPR_PSJ_SPACE_UNAVAILABLE_FOR_RETRY_FOLDER(PlatformConstants.RPR_PACKET_SCANNER_JOB_MODULE + "005", + "There is no space available in retry folder to upload the packet"), + + /** The rpr psj virus scan failed. */ + RPR_PSJ_VIRUS_SCAN_FAILED(PlatformConstants.RPR_PACKET_SCANNER_JOB_MODULE + "006", "Virus scan is failed"), + + /** The rpr psj ftp folder not accessible. */ + RPR_PSJ_FTP_FOLDER_NOT_ACCESSIBLE(PlatformConstants.RPR_PACKET_SCANNER_JOB_MODULE + "007", + "The FTP folder set by the System is not accessible"), + + /** The rpr psj api resouce access failed. */ + RPR_PSJ_API_RESOUCE_ACCESS_FAILED(PlatformConstants.RPR_PACKET_SCANNER_JOB_MODULE + "008", + "Not able to access the API resource"), + + /** The rpr pdj packet not available. */ + // packet decryption job Exception error code and message + RPR_PDS_PACKET_NOT_AVAILABLE(PlatformConstants.RPR_PACKET_DECRYPTION_MODULE + "001", "Packet not available"), + + /** The rpr pdj file path not accessible. */ + RPR_PDS_FILE_PATH_NOT_ACCESSIBLE(PlatformConstants.RPR_PACKET_DECRYPTION_MODULE + "002", + "The File path set by the System is not accessible"), + + /** The rpr pdj packet decryption failure. */ + RPR_PDS_PACKET_DECRYPTION_FAILURE(PlatformConstants.RPR_PACKET_DECRYPTION_MODULE + "003", + "The Decryption for the Packet has failed"), + + /** The rpr pdj packet decryption failure. */ + RPR_PDS_IO_EXCEPTION(PlatformConstants.RPR_PACKET_DECRYPTION_MODULE + "004", + "Exception while reading packet inputStream"), + + /** The rpr pds date time exception. */ + RPR_PDS_DATE_TIME_EXCEPTION(PlatformConstants.RPR_PACKET_DECRYPTION_MODULE + "005", + "Error while parsing packet timestamp"), + + /** The rpr rct unknown resource exception. */ + RPR_RCT_UNKNOWN_RESOURCE_EXCEPTION(PlatformConstants.RPR_REST_CLIENT_MODULE + "001", "Unknown resource provided"), + + /** The rpr mvs invalid file request. */ + RPR_MVS_INVALID_FILE_REQUEST(PlatformConstants.RPR_MANUAL_ADJUDICATION_MODULE + "001", "Invalid file requested"), + + /** The rpr mvs file not present. */ + RPR_MVS_FILE_NOT_PRESENT(PlatformConstants.RPR_MANUAL_ADJUDICATION_MODULE + "002", "Requested file is not present"), + + /** The rpr mvs invalid status update. */ + RPR_MVS_INVALID_STATUS_UPDATE(PlatformConstants.RPR_MANUAL_ADJUDICATION_MODULE + "003", "Invalid status update"), + + /** The rpr mvs invalid field. */ + RPR_MVS_INVALID_FIELD(PlatformConstants.RPR_MANUAL_ADJUDICATION_MODULE + "005", " fields can not be empty"), + + /** The rpr mvs no assigned record. */ + RPR_MVS_NO_ASSIGNED_RECORD(PlatformConstants.RPR_MANUAL_ADJUDICATION_MODULE + "004", "No Assigned Record Found"), + + /** The rpr mvs file not found in packet store. */ + RPR_MVS_FILE_NOT_FOUND_IN_PACKET_STORE(PlatformConstants.RPR_MANUAL_ADJUDICATION_MODULE + "018", + "Packet Not Found in Packet Store"), + + /** The rpr mvs missing input parameter version. */ + RPR_MVS_MISSING_INPUT_PARAMETER_VERSION(PlatformConstants.RPR_MANUAL_ADJUDICATION_MODULE + "019", + "Missing Input Parameter - version"), + + /** The rpr mvs missing input parameter timestamp. */ + RPR_MVS_MISSING_INPUT_PARAMETER_TIMESTAMP(PlatformConstants.RPR_MANUAL_ADJUDICATION_MODULE + "006", + "Missing Input Parameter - requesttime"), + + /** The rpr mvs missing input parameter id. */ + RPR_MVS_MISSING_INPUT_PARAMETER_ID(PlatformConstants.RPR_MANUAL_ADJUDICATION_MODULE + "007", + "Missing Input Parameter - id"), + + /** The rpr mvs invalid input parameter version. */ + RPR_MVS_INVALID_INPUT_PARAMETER_VERSION(PlatformConstants.RPR_MANUAL_ADJUDICATION_MODULE + "008", + "Invalid Input Parameter - version"), + + /** The rpr mvs invalid input parameter timestamp. */ + RPR_MVS_INVALID_INPUT_PARAMETER_TIMESTAMP(PlatformConstants.RPR_MANUAL_ADJUDICATION_MODULE + "009", + "Invalid Input Parameter - requesttime"), + + /** The rpr mvs invalid input parameter id. */ + RPR_MVS_INVALID_INPUT_PARAMETER_ID(PlatformConstants.RPR_MANUAL_ADJUDICATION_MODULE + "010", + "Invalid Input Parameter - id"), + + /** The rpr mvs invalid argument exception. */ + RPR_MVS_INVALID_ARGUMENT_EXCEPTION(PlatformConstants.RPR_MANUAL_ADJUDICATION_MODULE + "011", + "Invalid Argument Exception"), + + /** The rpr mvs unknown exception. */ + RPR_MVS_UNKNOWN_EXCEPTION(PlatformConstants.RPR_MANUAL_ADJUDICATION_MODULE + "012", "Unknown Exception"), + + /** The rpr mvs decode exception. */ + RPR_MVS_DECODE_EXCEPTION(PlatformConstants.RPR_MANUAL_ADJUDICATION_MODULE + "013", "Request Decoding Exception"), + /** The rpr mvs no user id present. */ + RPR_MVS_NO_USER_ID_PRESENT(PlatformConstants.RPR_MANUAL_ADJUDICATION_MODULE + "014", + "User Id does not exists master list"), + + /** The rpr mvs no user id should not empty or null. */ + RPR_MVS_NO_USER_ID_SHOULD_NOT_EMPTY_OR_NULL(PlatformConstants.RPR_MANUAL_ADJUDICATION_MODULE + "017", + "User Id should not empty or null "), + + /** The rpr mvs no registration id should not empty or null. */ + RPR_MVS_NO_RID_SHOULD_NOT_EMPTY_OR_NULL(PlatformConstants.RPR_MANUAL_ADJUDICATION_MODULE + "022", + "Registration Id should not empty or null "), + + /** The rpr mvs no matched ref id found for given ref id. */ + RPR_MVS_NO_MATCHEDRID_FOUND_FOR_GIVEN_RID(PlatformConstants.RPR_MANUAL_ADJUDICATION_MODULE + "023", + "No matched reference id found for given RID"), + /** The rpr mvs user status not active. */ + RPR_MVS_USER_STATUS_NOT_ACTIVE(PlatformConstants.RPR_MANUAL_ADJUDICATION_MODULE + "015", + "User is not in ACTIVE status"), + + /** The rpr mvs no match type present. */ + RPR_MVS_NO_MATCH_TYPE_PRESENT(PlatformConstants.RPR_MANUAL_ADJUDICATION_MODULE + "020", "Match Type is Invalid"), + + /** The rpr mvs reg id should not empty or null. */ + RPR_MVS_REG_ID_SHOULD_NOT_EMPTY_OR_NULL(PlatformConstants.RPR_MANUAL_ADJUDICATION_MODULE + "016", + "Reg Id should not be null or empty"), + + /** The rpr manual verification rejected. */ + RPR_MANUAL_VERIFICATION_REJECTED(PlatformConstants.RPR_MANUAL_ADJUDICATION_MODULE + "021", + "Manual verification rejected"), + + /** The rpr manual verification rejected. */ + RPR_MANUAL_VERIFICATION_RESEND(PlatformConstants.RPR_MANUAL_ADJUDICATION_MODULE + "025", + "Manual verification resend to queue."), + + /** The rpr table not accessible. */ + RPR_TABLE_NOT_ACCESSIBLE(PlatformConstants.RPR_MANUAL_ADJUDICATION_MODULE + "022", + "TablenotAccessibleException in Manual verification"), + + /** The rpr table not accessible. */ + RPR_INVALID_MESSSAGE(PlatformConstants.RPR_MANUAL_ADJUDICATION_MODULE + "023", + "Invalid message received from queue"), + + /** The rpr table not accessible. */ + RPR_INVALID_RID_FOUND(PlatformConstants.RPR_MANUAL_ADJUDICATION_MODULE + "024", + "Multiple rids found for a reference id"), + + MANUAL_VERIFICATION_FAILED(PlatformConstants.RPR_MANUAL_ADJUDICATION_MODULE + "025", + "Manual adjudication failed"), + + /** The rpr tem not found. */ + // Registration processor Message sender Exception error code + RPR_TEM_NOT_FOUND(PlatformConstants.RPR_MESSAGE_SENDER_TEMPLATE + "001", "Template was Not Found"), + + /** The rpr tem processing failure. */ + RPR_TEM_PROCESSING_FAILURE(PlatformConstants.RPR_MESSAGE_SENDER_TEMPLATE + "002", + "The Processing of Template Failed "), + /** The rpr tem packet store not accessible. */ + RPR_TEM_PACKET_STORE_NOT_ACCESSIBLE(PlatformConstants.RPR_MESSAGE_SENDER_TEMPLATE + "003", + "The Packet store set by the System is not accessible"), + /** The rpr sms template generation failure. */ + RPR_SMS_TEMPLATE_GENERATION_FAILURE(PlatformConstants.RPR_MESSAGE_SENDER_TEMPLATE + "001", + "Template Generation failed"), + + /** The rpr sms phone number not found. */ + RPR_SMS_PHONE_NUMBER_NOT_FOUND(PlatformConstants.RPR_MESSAGE_SENDER_TEMPLATE + "002", "Phone number was not found"), + + /** The rpr eml emailid not found. */ + RPR_EML_EMAILID_NOT_FOUND(PlatformConstants.RPR_MESSAGE_SENDER_TEMPLATE + "001", "Email Id was not found"), + + /** The rpr tem configuration not found. */ + RPR_TEM_CONFIGURATION_NOT_FOUND(PlatformConstants.RPR_MESSAGE_SENDER_TEMPLATE + "003", + "The Configuration and Language code not found"), + + /** The rpr notification failed for lost. */ + RPR_NOTIFICATION_FAILED_FOR_LOST(PlatformConstants.RPR_MESSAGE_SENDER_TEMPLATE + "004", + "Unable to Send Notification - UIN was not found for the Lost Packet"), + + /** The rpr template configuration not found. */ + RPR_TEMPLATE_CONFIGURATION_NOT_FOUND(PlatformConstants.RPR_MESSAGE_SENDER_TEMPLATE + "005", + "Template configuration and language not found"), + + /** The rpr message sender stage failed. */ + RPR_MESSAGE_SENDER_STAGE_FAILED(PlatformConstants.RPR_MESSAGE_SENDER_TEMPLATE + "006", + "Message Sender Stage failed"), + + /** The rpr email phone template notification missing. */ + RPR_EMAIL_PHONE_TEMPLATE_NOTIFICATION_MISSING(PlatformConstants.RPR_MESSAGE_SENDER_TEMPLATE + "007", + "Email ID or Phone or Template or Notification Type is Missing"), + + /** The rpr message sender email failed. */ + RPR_MESSAGE_SENDER_EMAIL_FAILED(PlatformConstants.RPR_MESSAGE_SENDER_TEMPLATE + "008", "Email Failed"), + + /** The rpr message sender sms failed. */ + RPR_MESSAGE_SENDER_SMS_FAILED(PlatformConstants.RPR_MESSAGE_SENDER_TEMPLATE + "009", "SMS failed"), + + /** The rpr pum packet not found exception. */ + RPR_PUM_PACKET_NOT_FOUND_EXCEPTION(PlatformConstants.RPR_PACKET_UPLOADER_MODULE + "001", + "Packet not found in LANDING_ZONE "), + + /** The rpr pum packet deletion info. */ + RPR_PUM_PACKET_DELETION_INFO(PlatformConstants.RPR_PACKET_UPLOADER_MODULE + "002", + "File is Already exists in File Store And its now Deleted from landing zone"), + + /** The rpr pum packet store not accessible. */ + RPR_PUM_PACKET_STORE_NOT_ACCESSIBLE(PlatformConstants.RPR_PACKET_UPLOADER_MODULE + "003", + "The Packet store set by the System is not accessible"), + + /** The prp pkr packet virus scan failed. */ + RPR_PUM_PACKET_VIRUS_SCAN_FAILED(PlatformConstants.RPR_PACKET_UPLOADER_MODULE + "004", + "The Registration Packet virus scan failed"), + + /** The rpr pum packet virus scanner service failed. */ + RPR_PUM_PACKET_VIRUS_SCANNER_SERVICE_FAILED(PlatformConstants.RPR_PACKET_UPLOADER_MODULE + "005", + "Virus scanner service failed"), + + /** The rpr pkm file not found in source. */ + RPR_PUM_JSCH_NOT_CONNECTED(PlatformConstants.RPR_PACKET_UPLOADER_MODULE + "006", "The JSCH connection failed"), + + /** The rpr pkm file not found in source. */ + RPR_PUM_NGINX_ACCESS_FAILED(PlatformConstants.RPR_PACKET_UPLOADER_MODULE + "007", + "Could not get the packet from nginx Url"), + + /** The rpr pum packet not yet sync. */ + RPR_PUM_PACKET_NOT_YET_SYNC(PlatformConstants.RPR_PACKET_UPLOADER_MODULE + "008", + "Registration packet is not in Sync with Sync table"), + + /** The rpr pum packet decryption failed. */ + RPR_PUM_PACKET_DECRYPTION_FAILED(PlatformConstants.RPR_PACKET_UPLOADER_MODULE + "009", + "Registration packet decryption failed"), + + /** The rpr pum packet deletion failed. */ + RPR_PUM_PACKET_DELETION_FAILED(PlatformConstants.RPR_PACKET_UPLOADER_MODULE + "010", + "packet upload failed during cleanup"), + + /** The rpr pum packet archival failed. */ + RPR_PUM_PACKET_ARCHIVAL_FAILED(PlatformConstants.RPR_PACKET_UPLOADER_MODULE + "010", + "packet upload failed during archival"), + + /** The rpr pum packet not found exception. */ + RPR_PUM_PACKET_UPLOAD_FAILURE(PlatformConstants.RPR_PACKET_UPLOADER_MODULE + "011", + "Failure in uploading the packet to Packet Store"), + + RPR_PUM_PACKET_RETRY_CNT_FAILURE(PlatformConstants.RPR_PACKET_UPLOADER_MODULE + "012", + "packet upload failed due to Retry count has exceeded the max limit specified"), + + /** The rpr bdd abis internal error. */ + RPR_BDD_ABIS_INTERNAL_ERROR(PlatformConstants.RPR_BIO_DEDUPE_SERVICE_MODULE + "001", + "ABIS for the Reference ID and Request ID threw an Internal Error"), + + /** The rpr bdd abis abort. */ + RPR_BDD_ABIS_ABORT(PlatformConstants.RPR_BIO_DEDUPE_SERVICE_MODULE + "002", + "ABIS for the Reference ID and Request ID was Abort"), + + /** The rpr bdd unexcepted error. */ + RPR_BDD_UNEXCEPTED_ERROR(PlatformConstants.RPR_BIO_DEDUPE_SERVICE_MODULE + "003", + "ABIS for the Reference ID and Request ID was Not able to Access Biometric Data"), + + /** The rpr bdd unable to serve request. */ + RPR_BDD_UNABLE_TO_SERVE_REQUEST(PlatformConstants.RPR_BIO_DEDUPE_SERVICE_MODULE + "004", + "ABIS for the Reference ID and Request ID was Unable to Execute the Request"), + + /** The unknown exception. */ + UNKNOWN_EXCEPTION(PlatformConstants.RPR_BIO_DEDUPE_SERVICE_MODULE + "005", + "un expected exception occured in biodedupe service"), + + /** The connection to MOSIP underlying queue not available. */ + RPR_MQI_CONNECTION_UNAVAILABLE(PlatformConstants.RPR_MOSIP_QUEUE_MODULE + "001", + "The connection to underlying queue not available"), + + /** The rpr mqi unable to send to queue. */ + RPR_MQI_UNABLE_TO_SEND_TO_QUEUE(PlatformConstants.RPR_MOSIP_QUEUE_MODULE + "003", + "Unable to send message to to queue"), + + /** The rpr mqi unable to consume from queue. */ + RPR_MQI_UNABLE_TO_CONSUME_FROM_QUEUE(PlatformConstants.RPR_MOSIP_QUEUE_MODULE + "004", + "Unable to consume message from queue"), + + /** The rpr mqi no files found in queue. */ + RPR_MQI_NO_FILES_FOUND_IN_QUEUE(PlatformConstants.RPR_MOSIP_QUEUE_MODULE + "005", + "There is no file available in queue"), + + /** The rpr mqi invalid connection. */ + RPR_MQI_INVALID_CONNECTION(PlatformConstants.RPR_MOSIP_QUEUE_MODULE + "002", + "Connection not obtained from ConnectionFactory"), + + /** The missing input parameter. */ + RPR_BDD_MISSING_INPUT_PARAMETER(PlatformConstants.RPR_BIO_DEDUPE_SERVICE_MODULE + "005", + "Missing Input Parameter - %s"), + + /** The invalid input parameter. */ + RPR_BDD_INVALID_INPUT_PARAMETER(PlatformConstants.RPR_BIO_DEDUPE_SERVICE_MODULE + "006", + "Invalid Input Parameter - %s"), + + /** The data validation failed. */ + RPR_BDD_DATA_VALIDATION_FAILED(PlatformConstants.RPR_BIO_DEDUPE_SERVICE_MODULE + "007", + "Input Data Validation Failed"), + + /** The rpr bdd json mapping exception. */ + RPR_BDD_JSON_MAPPING_EXCEPTION(PlatformConstants.RPR_BIO_DEDUPE_SERVICE_MODULE + "008", + "Json Data Mapping Exception"), + + /** The rpr bdd json parsing exception. */ + RPR_BDD_JSON_PARSING_EXCEPTION(PlatformConstants.RPR_BIO_DEDUPE_SERVICE_MODULE + "009", + "Json Data Parsing Exception"), + + /** The rpr bdd unknown exception. */ + RPR_BDD_UNKNOWN_EXCEPTION(PlatformConstants.RPR_BIO_DEDUPE_SERVICE_MODULE + "010", "Unknown Exception Occurs"), + + /** The rpr mvs file not present. */ + RPR_BDD_FILE_NOT_PRESENT(PlatformConstants.RPR_BIO_DEDUPE_SERVICE_MODULE + "011", "Requested file is not present"), + + /** *** System Exception ****. */ + + RPR_SYS_UNEXCEPTED_EXCEPTION(PlatformConstants.RPR_SYSTEM_EXCEPTION + "001", "Unexpected exception"), + + /** The rpr sys bad gateway. */ + RPR_SYS_BAD_GATEWAY(PlatformConstants.RPR_SYSTEM_EXCEPTION + "002", "Bad Gateway"), + + /** The rpr sys service unavailable. */ + RPR_SYS_SERVICE_UNAVAILABLE(PlatformConstants.RPR_SYSTEM_EXCEPTION + "003", "Service Unavailable"), + + /** The rpr sys server error. */ + RPR_SYS_SERVER_ERROR(PlatformConstants.RPR_SYSTEM_EXCEPTION + "004", "Internal Server Error"), + + /** The rpr sys timeout exception. */ + RPR_SYS_TIMEOUT_EXCEPTION(PlatformConstants.RPR_SYSTEM_EXCEPTION + "005", "Timeout Error"), + + /** The rpr sys identity json mapping exception. */ + RPR_SYS_IDENTITY_JSON_MAPPING_EXCEPTION(PlatformConstants.RPR_SYSTEM_EXCEPTION + "006", + "Error while mapping Identity Json"), + + /** The rpr sys instantiation exception. */ + RPR_SYS_INSTANTIATION_EXCEPTION(PlatformConstants.RPR_SYSTEM_EXCEPTION + "007", + "Error while creating object of JsonValue class"), + + /** The rpr sys no such field exception. */ + RPR_SYS_NO_SUCH_FIELD_EXCEPTION(PlatformConstants.RPR_SYSTEM_EXCEPTION + "008", "Could not find the field"), + + /** The rpr sys json parsing exception. */ + RPR_SYS_JSON_PARSING_EXCEPTION(PlatformConstants.RPR_SYSTEM_EXCEPTION + "009", "Error while parsing Json"), + + /** The rpr sys unable to convert stream to bytes. */ + RPR_SYS_UNABLE_TO_CONVERT_STREAM_TO_BYTES(PlatformConstants.RPR_SYSTEM_EXCEPTION + "010", + "Error while converting inputstream to bytes"), + + /** The rpr sys parsing date exception. */ + RPR_SYS_PARSING_DATE_EXCEPTION(PlatformConstants.RPR_SYSTEM_EXCEPTION + "011", "Error while parsing date "), + + /** The rpr sys io exception. */ + RPR_SYS_IO_EXCEPTION(PlatformConstants.RPR_SYSTEM_EXCEPTION + "012", "IO EXCEPTION "), + + /** The rpr sys data access exception. */ + RPR_SYS_DATA_ACCESS_EXCEPTION(PlatformConstants.RPR_SYSTEM_EXCEPTION + "013", "Data Access Exception"), + + /** The rpr sys api resource exception. */ + RPR_SYS_API_RESOURCE_EXCEPTION(PlatformConstants.RPR_SYSTEM_EXCEPTION + "014", "API Resource Exception"), + + /** The rpr sys illegal access exception. */ + RPR_SYS_ILLEGAL_ACCESS_EXCEPTION(PlatformConstants.RPR_SYSTEM_EXCEPTION + "015", "ILLEGAL ACCESS Exception"), + + /** The rpr sys Invocation target exception. */ + RPR_SYS_INVOCATION_TARGET_EXCEPTION(PlatformConstants.RPR_SYSTEM_EXCEPTION + "016", "Invocation target Exception"), + + /** The rpr sys Invocation target exception. */ + RPR_SYS_INTROSPECTION_EXCEPTION(PlatformConstants.RPR_SYSTEM_EXCEPTION + "017", "Introspection Exception"), + + /** The packet store not accessible. */ + OBJECT_STORE_NOT_ACCESSIBLE(PlatformConstants.RPR_SYSTEM_EXCEPTION + "018", + "Unable to Access Object Store"), + + /** The packet tags copying failed. */ + RPR_SYS_PACKET_TAGS_COPYING_FAILED(PlatformConstants.RPR_SYSTEM_EXCEPTION + "019", + "Packet tags copying to message event failed"), + + /** The message expired. */ + RPR_SYS_MESSAGE_EXPIRED(PlatformConstants.RPR_SYSTEM_EXCEPTION + "020", + "Message expired as per the last hop timestamp"), + + /** The stage processing failed. */ + RPR_SYS_STAGE_PROCESSING_FAILED(PlatformConstants.RPR_SYSTEM_EXCEPTION + "021", + "Stage processing of message failed with an exception"), + + /** The rpr sys connection exception. */ + RPR_SYS_QUEUE_CONNECTION_EXCEPTION(PlatformConstants.RPR_SYSTEM_EXCEPTION + "022", + "Error while connecting to active mq"), + + // Cbeff Util Exceptions + /** The rpr utl biometric tag match. */ + RPR_UTL_BIOMETRIC_TAG_MATCH(PlatformConstants.RPR_UTIL + "001", "Both Files have same biometrics"), + + /** The rpr utl cbeff version mismatch. */ + RPR_UTL_CBEFF_VERSION_MISMATCH(PlatformConstants.RPR_UTIL + "002", "Both Files have different versions"), + + /** The rpr utl digital sign exception. */ + RPR_UTL_DIGITAL_SIGN_EXCEPTION(PlatformConstants.RPR_UTIL + "003", "Failed to generate digital signature"), + + /** The rpr utl language exception. */ + RPR_UTL_LANGUAGE_EXCEPTION(PlatformConstants.RPR_UTIL + "004", "Failed to retrieve language details."), + + /** The rpr prt pdf not generated. */ + // Printing stage exceptions + RPR_PRT_PDF_NOT_GENERATED(PlatformConstants.RPR_PRINTING_MODULE + "001", "Error while generating PDF for UIN Card"), + + /** The rpr prt uin not found in database. */ + RPR_PRT_UIN_NOT_FOUND_IN_DATABASE(PlatformConstants.RPR_PRINTING_MODULE + "002", "UIN not found in database"), + + /** The rpr prt pdf generation failed. */ + RPR_PRT_PDF_GENERATION_FAILED(PlatformConstants.RPR_PRINTING_MODULE + "003", "PDF Generation Failed"), + + /** The rpr prt queue connection null. */ + RPR_PRT_QUEUE_CONNECTION_NULL(PlatformConstants.RPR_PRINTING_MODULE + "004", "Queue connection is null"), + + /** The rpr prt qrcode not generated. */ + RPR_PRT_QRCODE_NOT_GENERATED(PlatformConstants.RPR_PRINTING_MODULE + "005", "Error while generating QR Code"), + + /** The rpr prt applicant photo not set. */ + RPR_PRT_APPLICANT_PHOTO_NOT_SET(PlatformConstants.RPR_PRINTING_MODULE + "006", + "Error while setting applicant photo"), + + /** The rpr prt qrcode not set. */ + RPR_PRT_QRCODE_NOT_SET(PlatformConstants.RPR_PRINTING_MODULE + "007", "Error while setting qrCode for uin card"), + + /** The rpr prt idrepo response null. */ + RPR_PRT_IDREPO_RESPONSE_NULL(PlatformConstants.RPR_PRINTING_MODULE + "008", "ID Repo response is null"), + + /** The rpr prt idrepo documents absent. */ + RPR_PRT_IDREPO_DOCUMENT_ABSENT(PlatformConstants.RPR_PRINTING_MODULE + "009", "ID Repo response has no documents"), + + /** The print and postal acknowledment generation failed. */ + RPR_PRT_PRINT_POST_ACK_FAILED(PlatformConstants.RPR_PRINTING_MODULE + "010", + "Error while getting response from Print and Postal Service Provider"), + + /** The print validation failed. */ + RPR_PRT_DATA_VALIDATION_FAILED(PlatformConstants.RPR_PRINTING_MODULE + "011", "Error while print data validation"), + + /** The rpr prt cardtype validation failed. */ + RPR_PRT_CARDTYPE_VALIDATION_FAILED(PlatformConstants.RPR_PRINTING_MODULE + "012", + "Invalid CardType : Enter UIN or MASKED_UIN"), + + /** The rpr prt idtype validation failed. */ + RPR_PRT_IDTYPE_VALIDATION_FAILED(PlatformConstants.RPR_PRINTING_MODULE + "013", + "Invalid IdType : Enter UIN or VID or RID"), + + /** The rpr prt uin validation failed. */ + RPR_PRT_UIN_VALIDATION_FAILED(PlatformConstants.RPR_PRINTING_MODULE + "014", "UIN is not valid"), + + /** The rpr prt vid validation failed. */ + RPR_PRT_VID_VALIDATION_FAILED(PlatformConstants.RPR_PRINTING_MODULE + "015", "VID is not valid"), + + /** The rpr prt rid validation failed. */ + RPR_PRT_RID_VALIDATION_FAILED(PlatformConstants.RPR_PRINTING_MODULE + "016", "RID is not valid"), + + /** The rpr prt vid not generated. */ + RPR_PRT_VID_NOT_GENERATED(PlatformConstants.RPR_PRINTING_MODULE + "017", "Error while creating VID"), + + /** The rpr prt vid exception. */ + RPR_PRT_VID_EXCEPTION(PlatformConstants.RPR_PRINTING_MODULE + "018", + "Could not generate/regenerate VID as per policy,Please use existing VID"), + + /** The missing input parameter. */ + RPR_PRT_MISSING_INPUT_PARAMETER(PlatformConstants.RPR_PRINTING_MODULE + "019", "Missing Input Parameter - %s"), + + /** The missing input parameter. */ + RPR_PRT_INVALID_INPUT_PARAMETER(PlatformConstants.RPR_PRINTING_MODULE + "019", "Invalid Input Parameter - %s"), + + /** The missing input parameter. */ + RPR_PRT_PDF_NOT_ADDED(PlatformConstants.RPR_PRINTING_MODULE + "020", + "Pdf was not added to queue due to queue failure"), + + /** The missing input parameter. */ + RPR_PRT_RESEND_UIN_CARD(PlatformConstants.RPR_PRINTING_MODULE + "021", "Re-Send uin card for printing"), + + /** The rpr prt qr code generation error. */ + RPR_PRT_QR_CODE_GENERATION_ERROR(PlatformConstants.RPR_PRINTING_MODULE + "022", "Error while QR Code Generation"), + + /** The rpr prt vid creation error. */ + RPR_PRT_VID_CREATION_ERROR(PlatformConstants.RPR_PRINTING_MODULE + "023", "Error while creating VID"), + + + RPR_PRT_PDF_SIGNATURE_EXCEPTION(PlatformConstants.RPR_PRINTING_MODULE + "024", "PDF Signature error"), + + RPR_PRT_PRINT_REQUEST_FAILED(PlatformConstants.RPR_PRINTING_MODULE + "025", "Print request failed"), + + RPR_PRT_API_RESOUCE_ACCESS_FAILED(PlatformConstants.RPR_PRINTING_MODULE + "026", + "Unable to Access API Resource"), + + /** The rpr prt vid exception. */ + RPR_PRT_VID_NOT_AVAILABLE_EXCEPTION(PlatformConstants.RPR_PRINTING_MODULE + "027", + "vid not available"), + + /** The rpr prt print issuer not found in property. */ + RPR_PRT_ISSUER_NOT_FOUND_IN_PROPERTY(PlatformConstants.RPR_PRINTING_MODULE + "028", "Print issuer property is not found"), + + RPR_PRT_PARSING_ADDITIONAL_CRED_CONFIG(PlatformConstants.RPR_PRINTING_MODULE + "029", "issue with metaInfoFields in credential partner profiles."), + + /** The rpr rgs registration connector not accessible. */ + RPR_RGS_REGISTRATION_CONNECTOR_NOT_ACCESSIBLE("", "Registration connector stage is not accessible "), + + /** The rpr pvm packet store not accessible. */ + RPR_PVM_PACKET_STORE_NOT_ACCESSIBLE(PlatformConstants.RPR_PACKET_VALIDATOR_MODULE + "001", + "The Packet store set by the System is not accessible"), + + /** The rpr ugs packet store not accessible. */ + RPR_UGS_PACKET_STORE_NOT_ACCESSIBLE(PlatformConstants.RPR_UIN_GENERATOR_STAGE + "001", + "The Packet store set by the System is not accessible"), + /** The rpr ugs json parser error. */ + RPR_UGS_JSON__PARSER_ERROR(PlatformConstants.RPR_UIN_GENERATOR_STAGE + "002", "Error while parsing Json"), + /** The rpr ugs api resource exception. */ + RPR_UGS_API_RESOURCE_EXCEPTION(PlatformConstants.RPR_UIN_GENERATOR_STAGE + "003", + "Not able to access the API resource"), + /** The rpr ugs io exception. */ + RPR_UGS_IO_EXCEPTION(PlatformConstants.RPR_UIN_GENERATOR_STAGE + "004", "IO exception"), + /** The rpr ugs vid exception. */ + RPR_UGS_VID_EXCEPTION(PlatformConstants.RPR_UIN_GENERATOR_STAGE + "005", "VID status is not active"), + + /** The rpr ugs uin update failure. */ + RPR_UGS_UIN_UPDATE_FAILURE(PlatformConstants.RPR_UIN_GENERATOR_STAGE + "006", "UIN updation failure"), + + /** The uin already activated. */ + UIN_ALREADY_ACTIVATED(PlatformConstants.RPR_UIN_GENERATOR_STAGE + "007", "UIN is already Activated"), + + /** The uin already deactivated. */ + UIN_ALREADY_DEACTIVATED(PlatformConstants.RPR_UIN_GENERATOR_STAGE + "008", "UIN already deactivated"), + + /** The uin activated failed. */ + UIN_ACTIVATED_FAILED(PlatformConstants.RPR_UIN_GENERATOR_STAGE + "009", "UIN Activation Failed"), + + /** The uin reactivation failed. */ + UIN_REACTIVATION_FAILED(PlatformConstants.RPR_UIN_GENERATOR_STAGE + "010", "UIN Reactivation failed"), + + /** The uin deactivation failed. */ + UIN_DEACTIVATION_FAILED(PlatformConstants.RPR_UIN_GENERATOR_STAGE + "011", "UIN Deactivation failed"), + + /** The link rid for lost packet failed. */ + LINK_RID_FOR_LOST_PACKET_FAILED(PlatformConstants.RPR_UIN_GENERATOR_STAGE + "012", + "UIn not found the the matched RID"), + + /** The uin generation failed. */ + UIN_GENERATION_FAILED(PlatformConstants.RPR_UIN_GENERATOR_STAGE + "013", "UIN Generation failed"), + + VID_CREATION_FAILED(PlatformConstants.RPR_UIN_GENERATOR_STAGE + "014", "VID creation failed"), + + + DRAFT_CHECK_FAILED(PlatformConstants.RPR_UIN_GENERATOR_STAGE + "015", "Could not check if draft is present or not"), + + /** The rpr pgs file not present. */ + RPR_PGS_FILE_NOT_PRESENT(PlatformConstants.RPR_PACKET_GENERATOR_MODULE + "001", + "The Packet store set by the System is not accessible"), + + /** The rpr pgs invalid key illegal argument. */ + RPR_PGS_INVALID_KEY_ILLEGAL_ARGUMENT(PlatformConstants.RPR_PACKET_GENERATOR_MODULE + "002", + "The key is invalid or illegal argument"), + + /** The rpr pgs api resource not available. */ + RPR_PGS_API_RESOURCE_NOT_AVAILABLE(PlatformConstants.RPR_PACKET_GENERATOR_MODULE + "003", + "The Api resource is not available"), + + /** The rpr pgs reg base exception. */ + RPR_PGS_REG_BASE_EXCEPTION(PlatformConstants.RPR_PACKET_GENERATOR_MODULE + "004", "reg Based checked exception"), + + /** The rpr pgs json processing exception. */ + RPR_PGS_JSON_PROCESSING_EXCEPTION(PlatformConstants.RPR_PACKET_GENERATOR_MODULE + "005", + "Exception while parsing object to JSON"), + + /** The rpr pgs json validator error code. */ + RPR_PGS_JSON_VALIDATOR_ERROR_CODE(PlatformConstants.RPR_PACKET_GENERATOR_MODULE + "006", + "Exception while validating ID json file"), + + /** The rpr pgs encryptor invlaid data exception. */ + RPR_PGS_ENCRYPTOR_INVLAID_DATA_EXCEPTION(PlatformConstants.RPR_PACKET_GENERATOR_MODULE + "007", + "Exception occured while encryting the data"), + + /** The rpr pgs encryptor invlaid key exception. */ + RPR_PGS_ENCRYPTOR_INVLAID_KEY_EXCEPTION(PlatformConstants.RPR_PACKET_GENERATOR_MODULE + "008", + "Exception occured while encryting the packet Invalid Key"), + + /** The rpr pgs packet meta convertor exception. */ + RPR_PGS_PACKET_META_CONVERTOR_EXCEPTION(PlatformConstants.RPR_PACKET_GENERATOR_MODULE + "009", + "Packet meta info converter error"), + + /** The missing input parameter. */ + RPR_PGS_MISSING_INPUT_PARAMETER(PlatformConstants.RPR_PACKET_GENERATOR_MODULE + "010", + "Missing Input Parameter - %s"), + + /** The invalid input parameter. */ + RPR_PGS_INVALID_INPUT_PARAMETER(PlatformConstants.RPR_PACKET_GENERATOR_MODULE + "011", + "Invalid Input Parameter - %s"), + /** The data validation failed. */ + RPR_PGS_DATA_VALIDATION_FAILED(PlatformConstants.RPR_PACKET_GENERATOR_MODULE + "012", + "Input Data Validation Failed"), + + /** The rpr pgs vid exception. */ + RPR_PGS_VID_EXCEPTION(PlatformConstants.RPR_PACKET_GENERATOR_MODULE + "013", + "Could not generate/regenerate VID as per policy,Please use existing VID"), + + /** The rpr pgs vid creation exception. */ + RPR_PGS_VID_CREATION_EXCEPTION(PlatformConstants.RPR_PACKET_GENERATOR_MODULE + "014", "VID creation Exception"), + + /** The rpr pgs id object exception. */ + RPR_PGS_ID_OBJECT_EXCEPTION(PlatformConstants.RPR_PACKET_GENERATOR_MODULE + "015", "ID Object Validation failed"), + + /** The rpr pgs id type exception. */ + RPR_PGS_ID_TYPE_EXCEPTION(PlatformConstants.RPR_PACKET_GENERATOR_MODULE + "016", + "Invalid Input Value - ID Type: Enter UIN or RID"), + + /** The rpr pgs contact type exception. */ + RPR_PGS_CONTACT_TYPE_EXCEPTION(PlatformConstants.RPR_PACKET_GENERATOR_MODULE + "017", + "Invalid Input Value - Contact Type : Enter Email or Phone"), + /** The rpr pgs name exception. */ + RPR_PGS_NAME_EXCEPTION(PlatformConstants.RPR_PACKET_GENERATOR_MODULE + "018", + "Invalid Input Value - Name cannot be NULL or Empty"), + /** The rpr pgs contactvalue exception. */ + RPR_PGS_CONTACTVALUE_EXCEPTION(PlatformConstants.RPR_PACKET_GENERATOR_MODULE + "019", + "Invalid Input Value - contactValue cannot be NULL or Empty"), + /** The rpr pgs postalcode exception. */ + RPR_PGS_POSTALCODE_EXCEPTION(PlatformConstants.RPR_PACKET_GENERATOR_MODULE + "020", + "Invalid Input Value - postalCode cannot be NULL or Empty"), + + /** The rpr pgs no records exception. */ + RPR_PGS_NO_RECORDS_EXCEPTION(PlatformConstants.RPR_PACKET_GENERATOR_MODULE + "021", "No Records Found"), + + /** The rpr pgs no records exception. */ + RPR_PGS_MULTIPLE_RECORDS_EXCEPTION(PlatformConstants.RPR_PACKET_GENERATOR_MODULE + "022", "Multiple Records Found"), + + /** The rpr ugs api resource exception. */ + RPR_PGS_API_RESOURCE_EXCEPTION(PlatformConstants.RPR_PACKET_GENERATOR_MODULE + "023", + "Not able to access the API resource"), + /** The rpr ugs io exception. */ + RPR_PGS_IO_EXCEPTION(PlatformConstants.RPR_PACKET_GENERATOR_MODULE + "024", "IO exception"), + + /** The rpr pis identity not found. */ + RPR_PGS_IDENTITY_NOT_FOUND(PlatformConstants.RPR_PACKET_GENERATOR_MODULE + "025", + "Unable to Find Identity Field in ID JSON"), + + /** Idrepo draft creation exception. */ + IDREPO_DRAFT_EXCEPTION(PlatformConstants.RPR_PACKET_GENERATOR_MODULE + "026", + "Exception while updating idrepo draft"), + + /** invalid token present in header. */ + RPR_AUT_INVALID_TOKEN(PlatformConstants.RPR_AUTHENTICATION + "01", "Invalid Token Present"), + + /** Access denied for the token present. */ + RPR_AUT_ACCESS_DENIED(PlatformConstants.RPR_AUTHENTICATION + "02", "Access Denied For Role - %s"), + + /** Reprocessor Stage Failed. */ + REPROCESSOR_VERTICLE_FAILED(PlatformConstants.RPR_REPROCESSOR_VERTICLE + "000", "Reprocessor Verticle Failed"), + + RPR_WIA_DATE_TIME_EXCEPTION(PlatformConstants.RPR_WORKFLOW_INTERNAL_ACTION + "000", + "Error while parsing event or resume timestamp"), + + RPR_WORKFLOW_INTERNAL_ACTION_FAILED(PlatformConstants.RPR_WORKFLOW_INTERNAL_ACTION + "001", + "Work flow internal action failed"), + + RPR_WIA_UNKNOWN_WORKFLOW_ACTION(PlatformConstants.RPR_WORKFLOW_INTERNAL_ACTION + "002", "Unknown Exception"), + + RPR_WIA_ADDITIONALINFOPROCESS_NOT_FOUND(PlatformConstants.RPR_WORKFLOW_INTERNAL_ACTION + "003", + "AdditionalInfoProcess not found"), + + RPR_WIA_ADDITIONALINFOPROCESS_CANNOT_REQUEST(PlatformConstants.RPR_WORKFLOW_INTERNAL_ACTION + "004", + "AdditionalInfoProcess cannot be paused for one more additional info so it is failed"), + + RPR_WAA_MISSING_INPUT_PARAMETER(PlatformConstants.RPR_WORKFLOW_ACTION_API + "000", + "Missing Request Value - %s"), + + RPR_WAA_INVALID_INPUT_PARAMETER(PlatformConstants.RPR_WORKFLOW_ACTION_API + "001", + "Invalid Request Value - %s"), + + RPR_WAA_UNKNOWN_EXCEPTION(PlatformConstants.RPR_WORKFLOW_ACTION_API + "002", "Unknown Exception"), + + RPR_WAS_UNKNOWN_WORKFLOW_ACTION(PlatformConstants.RPR_WORKFLOW_ACTION_SERVICE + "000", + "Workflow Action not supported"), + + RPR_WAS_REMOVE_HOTLISTED_TAG_FAILED(PlatformConstants.RPR_WORKFLOW_ACTION_SERVICE + "001", + "Removing hotlisted tag failed"), + + RPR_WAA_WORKFLOW_ID_NOT_FOUND(PlatformConstants.RPR_WORKFLOW_ACTION_API + "003", + "Workflow id %s not found in registration table"), + + RPR_WAS_UNKNOWN_EXCEPTION(PlatformConstants.RPR_WORKFLOW_ACTION_SERVICE + "003", "Unknown Exception"), + + RPR_WAS_REPROCESS_FAILED(PlatformConstants.RPR_WORKFLOW_ACTION_SERVICE + "004", + "When REPROCESS_FAILED then Resume should not occur"), + + RPR_WAA_NOT_PAUSED(PlatformConstants.RPR_WORKFLOW_ACTION_API + "004", + "Workflow id %s is not PAUSED"), + + RPR_WAA_VALIDATION_SUCCESS(PlatformConstants.RPR_WORKFLOW_ACTION_API + "005", "Workflow id validated successfully"), + + RPR_WORKFLOW_ACTION_JOB_FAILED(PlatformConstants.RPR_WORKFLOW_ACTION_JOB, "Workflow action job failed"), + + /** The external stage failed. */ + EXTERNAL_STAGE_FAILED("", "External Stage Failed"), + + /** internal error for unknown reason. */ + INTERNAL_ERROR_UNKNOWN(PlatformConstants.ABIS + "01", "internal error for reason - %s"), + + /** request aborted. */ + ABORTED(PlatformConstants.ABIS + "02", "request aborted"), + + /** Unexpected error - Unable to access biometric data. */ + UNEXPECTED_ERROR(PlatformConstants.ABIS + "03", "Unexpected error - Unable to access biometric data for - %s"), + + /** Unable to serve the request. */ + UNABLE_TO_SERVE_REQUEST(PlatformConstants.ABIS + "04", "Unable to serve the request"), + + /** Invalid request. */ + INVALID_REQUEST(PlatformConstants.ABIS + "05", "Invalid request / Missing mandatory fields - %S"), + + /** Unauthorized Access. */ + UNAUTHORIZED_ACCESS(PlatformConstants.ABIS + "06", "Unauthorized Access"), + + /** Unable to fetch biometric details. */ + UNABLE_TO_FETCH_BIO_INFO(PlatformConstants.ABIS + "07", "Unable to fetch biometric details"), + + /** The missing mandatory fields. */ + MISSING_MANDATORY_FIELDS(PlatformConstants.ABIS + "08", "Mandatory request fields are missing"), + + /** The transactions not available. */ + TRANSACTIONS_NOT_AVAILABLE(PlatformConstants.REGISTRATION_TRANSACTIONS_SERVICE + "001", "RID Not Found"), + + /** The rpr rts unknown exception. */ + RPR_RTS_UNKNOWN_EXCEPTION(PlatformConstants.REGISTRATION_TRANSACTIONS_SERVICE + "002", "Unknown Exception Occured"), + + /** The rpr rts invalid request. */ + RPR_RTS_INVALID_REQUEST(PlatformConstants.REGISTRATION_TRANSACTIONS_SERVICE + "003", "Invalid request"), + + /** The rpr rts data population exception. */ + RPR_RTS_DATA_POPULATION_EXCEPTION(PlatformConstants.REGISTRATION_TRANSACTIONS_SERVICE + "004", + "globalMessages not found for input langCode"), + + /** The rpr rhs reg base exception. */ + RPR_RHS_REG_BASE_EXCEPTION(PlatformConstants.RPR_PACKET_REQUEST_HANDLER_MODULE + "004", + "reg Based checked exception"), + + /** The rpr details not found. */ + RPR_DETAILS_NOT_FOUND(PlatformConstants.RPR_ABIS_HANDLER + "001", "Abis Queue details not found"), + + /** The rpr no record found. */ + RPR_NO_RECORD_FOUND(PlatformConstants.RPR_ABIS_HANDLER + "002", + "Potential Match Records are Not Found for Demo Dedupe Potential Match"), + + /** The rpr error in abis handler identify request. */ + RPR_ERROR_IN_ABIS_HANDLER_IDENTIFY_REQUEST(PlatformConstants.RPR_ABIS_HANDLER + "004", + "Internal Error occured in Abis Handler identify request"), + + /** The rpr demo sending for manual. */ + RPR_DEMO_SENDING_FOR_MANUAL(PlatformConstants.RPR_DEMO_DEDUPE_MODULE + "001", + "ABIS response Details found. Hence sending to manual adjudication"), + + RPR_DEMO_API_RESOUCE_ACCESS_FAILED(PlatformConstants.RPR_DEMO_DEDUPE_MODULE + "002", + "Unable to Access API Resource"), + + RPR_SECUREZONE_FAILURE(PlatformConstants.RPR_SECUREZONE_NOTIFICATION_MODULE + "001", + "Exception occured in securezone notification stage. Check logs for more info"), + + RPR_SECUREZONE_DUPLICATE_PACKET(PlatformConstants.RPR_SECUREZONE_NOTIFICATION_MODULE + "002", + "Duplicate Packet against same additional info request Id."), + + RPR_AUTH_SYSTEM_EXCEPTION(PlatformConstants.RPR_AUTHENTICATION + "03", "Request could not be processed. Please try again"), + + /** The queue json validation failed. */ + QUEUE_JSON_VALIDATION_FAILED(PlatformConstants.RPR_MA_MIDDLEWARE + "004", + "Unable to find Connection Properties"), + + RPR_BIOMETRIC_EXTRACTION_FAILED(PlatformConstants.RPR_BIOMETRIC_EXTRACTION_STAGE + "000", + "biometric extraction failed"), + + RPR_BIOMETRIC_EXTRACTION_DRAFT_REQUEST_UNAVAILABLE(PlatformConstants.RPR_BIOMETRIC_EXTRACTION_STAGE + "001", + "Draft request is unavaialble in id-repo draft repository."), + /** The rpr ugs api resource exception. */ + RPR_BIOMETRIC_EXTRACTION_API_RESOURCE_EXCEPTION(PlatformConstants.RPR_BIOMETRIC_EXTRACTION_STAGE + "002", + "Not able to access the API resource"), + RPR_BIOMETRIC_EXTRACTION_NULL_RESPONSE(PlatformConstants.RPR_BIOMETRIC_EXTRACTION_STAGE + "003", + "null response from idrepo "), + RPR_PMS_BIOMETRIC_EXTRACTION_NULL_RESPONSE(PlatformConstants.RPR_BIOMETRIC_EXTRACTION_STAGE + "003", + "null response from partner service "), + /** The rpr finalization exception. */ + RPR_FINALIZATION_FAILED(PlatformConstants.RPR_FINALIZATION_STAGE + "001", + "finalization failed"), + RPR_FINALIZATION_FAILED_NULL_RESPONSE(PlatformConstants.RPR_FINALIZATION_STAGE + "002", + "null response from idrepo "), + RPR_FINALIZATION_STAGE_DRAFT_REQUEST_UNAVAILABLE(PlatformConstants.RPR_FINALIZATION_STAGE + "003", + "Draft request is unavaialble in id-repo draft repository."), + RPR_FINALIZATION_STAGE_API_RESOURCE_EXCEPTION(PlatformConstants.RPR_FINALIZATION_STAGE + "004", + "Not able to access the API resource"), + + INDIVIDUAL_BIOMETRIC_AUTHENTICATION_FAILED(PlatformConstants.RPR_BIOMETRIC_AUTHENTICATION_MODULE + "004", + "Bio authentication failed") + ; + + + + /** The error message. */ + private final String errorMessage; + + /** The error code. */ + private final String errorCode; + + /** + * Instantiates a new platform error messages. + * + * @param errorCode + * the error code + * @param errorMsg + * the error msg + */ + private PlatformErrorMessages(String errorCode, String errorMsg) { + this.errorCode = errorCode; + this.errorMessage = errorMsg; + } + + /** + * Gets the error message. + * + * @return the error message + */ + public String getMessage() { + return this.errorMessage; + } + + /** + * Gets the error code. + * + * @return the error code + */ + public String getCode() { + return this.errorCode; + } + } \ No newline at end of file diff --git a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/logger/RegProcessorLogger.java b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/logger/RegProcessorLogger.java index d201b3ddb20..fa5579de122 100644 --- a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/logger/RegProcessorLogger.java +++ b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/logger/RegProcessorLogger.java @@ -1,17 +1,15 @@ package io.mosip.registration.processor.core.logger; -import io.mosip.kernel.core.logger.spi.Logger; -import org.slf4j.LoggerFactory; -import io.mosip.kernel.logger.logback.factory.Logfactory; - - - -import java.util.stream.Collectors; import java.util.HashMap; import java.util.Map; +import java.util.stream.Collectors; + +import org.slf4j.LoggerFactory; import ch.qos.logback.classic.Level; import ch.qos.logback.classic.LoggerContext; +import io.mosip.kernel.core.logger.spi.Logger; +import io.mosip.kernel.logger.logback.factory.Logfactory; /** @@ -21,9 +19,9 @@ public final class RegProcessorLogger { public static final String PROP_PREFIX = "logging.level."; - + public static Map loggingLevelMap=new HashMap(); - + /** * Instantiates a new reg processor logger. */ diff --git a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/spi/restclient/RegistrationProcessorRestClientService.java b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/spi/restclient/RegistrationProcessorRestClientService.java index 3db41c9bedb..b2b0019d1f3 100644 --- a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/spi/restclient/RegistrationProcessorRestClientService.java +++ b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/spi/restclient/RegistrationProcessorRestClientService.java @@ -187,4 +187,7 @@ public T postApi(String url, MediaType mediaType, List pathsegments, Lis T requestedData, Class responseType) throws ApisResourceAccessException; public Integer headApi(ApiName apiName, List pathsegments, List queryParamName, List queryParamValue) throws ApisResourceAccessException; -} + + public T deleteApi(ApiName apiName, List pathsegments, String queryParam, String queryParamValue, + Class responseType) throws ApisResourceAccessException; + } diff --git a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/token/validation/TokenValidator.java b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/token/validation/TokenValidator.java index 55de1463312..82e9fd12c39 100644 --- a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/token/validation/TokenValidator.java +++ b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/token/validation/TokenValidator.java @@ -104,6 +104,20 @@ public String validate(String token, String url) { return userId; } + public String getRole(String url) { + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", + "TokenValidator::validateAccess()::entry"); + if (url.contains("receiver")) + return String.join(",", APIAuthorityList.PACKETRECEIVER.getList()); + else if (url.contains("securezone")) + return String.join(",", APIAuthorityList.SECUREZONENOTIFICATION.getList()); + else if (url.contains("workflowaction")) + return String.join(",", APIAuthorityList.WORKFLOWACTION.getList()); + else if (url.contains("workflow/search")) + return String.join(",", APIAuthorityList.WORKFLOWSEARCH.getList()); + return null; + } + public boolean validateAccess(String url, String role) { regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", "TokenValidator::validateAccess()::entry"); diff --git a/registration-processor/registration-processor-core/src/test/java/io/mosip/registration/processor/core/eventbus/KafkaMosipEventBusTest.java b/registration-processor/registration-processor-core/src/test/java/io/mosip/registration/processor/core/eventbus/KafkaMosipEventBusTest.java index a2230c78b40..540171fda6f 100644 --- a/registration-processor/registration-processor-core/src/test/java/io/mosip/registration/processor/core/eventbus/KafkaMosipEventBusTest.java +++ b/registration-processor/registration-processor-core/src/test/java/io/mosip/registration/processor/core/eventbus/KafkaMosipEventBusTest.java @@ -639,8 +639,7 @@ public void testConsumerHealthCheck(TestContext testContext) { AsyncResult>> asyncResult = Mockito.mock(AsyncResult.class); Mockito.when(asyncResult.succeeded()).thenReturn(true); doAnswer((Answer>>>) arguments -> { - ((Handler>>>) arguments.getArgument(0)) - .handle(asyncResult); + ((Handler>>>) arguments.getArgument(0)).handle(asyncResult); if (!async.isCompleted()) async.complete(); return null; @@ -682,7 +681,7 @@ public void testConsumerHealthCheckWithTimeout(TestContext testContext) { kafkaMosipEventBus = new KafkaMosipEventBus(vertx, "localhost:9091", "group_1", "batch", "100", 60000, eventTracingHandler); Handler eventHandler = Mockito.mock(Handler.class); - TimeoutException timeout=new TimeoutException(); + TimeoutException timeout = new TimeoutException(); Mockito.when(kafkaConsumer.listTopics(any())).thenThrow(timeout); kafkaMosipEventBus.consumerHealthCheck(eventHandler, MessageBusAddress.PACKET_VALIDATOR_BUS_IN.toString()); verify(kafkaConsumer, times(1)).listTopics(any()); diff --git a/registration-processor/registration-processor-info-storage-service/src/main/java/io/mosip/registration/processor/packet/storage/utils/Utilities.java b/registration-processor/registration-processor-info-storage-service/src/main/java/io/mosip/registration/processor/packet/storage/utils/Utilities.java index a0818625144..b4418f83811 100644 --- a/registration-processor/registration-processor-info-storage-service/src/main/java/io/mosip/registration/processor/packet/storage/utils/Utilities.java +++ b/registration-processor/registration-processor-info-storage-service/src/main/java/io/mosip/registration/processor/packet/storage/utils/Utilities.java @@ -1,6 +1,30 @@ package io.mosip.registration.processor.packet.storage.utils; +import java.io.IOException; +import java.text.DateFormat; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.time.Duration; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.Period; +import java.util.ArrayList; +import java.util.Date; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import org.apache.commons.lang.StringUtils; +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; +import org.json.simple.parser.JSONParser; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; +import org.springframework.web.client.RestTemplate; + import com.fasterxml.jackson.databind.ObjectMapper; + import io.mosip.kernel.core.exception.ExceptionUtils; import io.mosip.kernel.core.logger.spi.Logger; import io.mosip.kernel.core.util.exception.JsonProcessingException; @@ -37,24 +61,6 @@ import io.mosip.registration.processor.status.dto.InternalRegistrationStatusDto; import io.mosip.registration.processor.status.entity.RegistrationStatusEntity; import lombok.Data; -import org.apache.commons.lang.StringUtils; -import org.json.simple.JSONArray; -import org.json.simple.JSONObject; -import org.json.simple.parser.JSONParser; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.stereotype.Component; -import org.springframework.web.client.RestTemplate; - -import java.io.IOException; -import java.text.DateFormat; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.time.Duration; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.time.Period; -import java.util.*; /** * The Class Utilities. @@ -445,7 +451,7 @@ public List retrieveI /** * Check if uin is present in idrepo - * + * * @param uin * @return * @throws ApisResourceAccessException @@ -457,7 +463,7 @@ public boolean uinPresentInIdRepo(String uin) throws ApisResourceAccessException /** * Check if uin is missing from Id - * + * * @param errorCode * @param id * @param idType diff --git a/registration-processor/registration-processor-message-sender-impl/src/main/java/io/mosip/registration/processor/message/sender/service/impl/MessageNotificationServiceImpl.java b/registration-processor/registration-processor-message-sender-impl/src/main/java/io/mosip/registration/processor/message/sender/service/impl/MessageNotificationServiceImpl.java index e0c25f6c7c4..0d39ace1ed8 100644 --- a/registration-processor/registration-processor-message-sender-impl/src/main/java/io/mosip/registration/processor/message/sender/service/impl/MessageNotificationServiceImpl.java +++ b/registration-processor/registration-processor-message-sender-impl/src/main/java/io/mosip/registration/processor/message/sender/service/impl/MessageNotificationServiceImpl.java @@ -128,7 +128,7 @@ public class MessageNotificationServiceImpl @Autowired private SyncRegistrationService syncRegistrationService; - + @Autowired private Decryptor decryptor; /** The template generator. */ @@ -141,17 +141,17 @@ public class MessageNotificationServiceImpl /** The utility. */ @Autowired private Utilities utility; - + @Autowired private LanguageUtility languageUtility; /** The rest client service. */ @Autowired private RegistrationProcessorRestClientService restClientService; - + @Value("${mosip.default.template-languages:#{null}}") private String defaultTemplateLanguages; - + @Value("${mosip.default.user-preferred-language-attribute:#{null}}") private String userPreferredLanguageAttribute; @@ -208,7 +208,7 @@ public SmsResponseDto sendSmsNotification(String templateTypeCode, String id, St } smsDto.setNumber(phoneNumber.toString()); } - + smsDto.setMessage(artifact); requestWrapper.setId(env.getProperty(SMS_SERVICE_ID)); @@ -244,8 +244,8 @@ public SmsResponseDto sendSmsNotification(String templateTypeCode, String id, St regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), id, PlatformErrorMessages.RPR_PGS_API_RESOURCE_NOT_AVAILABLE.name() + e.getMessage() + ExceptionUtils.getStackTrace(e)); - - + + } return response; @@ -268,7 +268,7 @@ public ResponseDto sendEmailNotification(String templateTypeCode, String id, Str "MessageNotificationServiceImpl::sendEmailNotification()::entry"); try { List preferredLanguages= getPreferredLanguages(id,process); - + String artifact=""; String subject=""; for(String lang: preferredLanguages) { @@ -277,11 +277,11 @@ public ResponseDto sendEmailNotification(String templateTypeCode, String id, Str Map attributesLang=new HashMap<>(attributes); setAttributes(id, process,lang, idType, attributesLang, regType, phoneNumber, emailId); InputStream stream = templateGenerator.getTemplate(templateTypeCode, attributesLang, lang); - + artifact = IOUtils.toString(stream, ENCODING); - + InputStream subStream = templateGenerator.getTemplate(subjectCode, attributesLang, lang); - + subject=IOUtils.toString(subStream, ENCODING); if (emailId == null || emailId.length() == 0) { throw new EmailIdNotFoundException(PlatformErrorMessages.RPR_EML_EMAILID_NOT_FOUND.getCode()); @@ -291,7 +291,7 @@ public ResponseDto sendEmailNotification(String templateTypeCode, String id, Str response = sendEmail(mailTo, mailCc, subject, artifact, attachment); } - + } catch (TemplateNotFoundException | TemplateProcessingFailureException e) { regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), @@ -310,12 +310,12 @@ public ResponseDto sendEmailNotification(String templateTypeCode, String id, Str return response; } - - private List getPreferredLanguages(String id, String process) throws ApisResourceAccessException, + + private List getPreferredLanguages(String id, String process) throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { if(userPreferredLanguageAttribute!=null && !userPreferredLanguageAttribute.isBlank()) { try { - String preferredLang=packetManagerService.getField(id, userPreferredLanguageAttribute, process, + String preferredLang=packetManagerService.getField(id, userPreferredLanguageAttribute, process, ProviderStageName.MESSAGE_SENDER); if(preferredLang!=null && !preferredLang.isBlank()) { List codes=new ArrayList<>(); @@ -331,12 +331,12 @@ private List getPreferredLanguages(String id, String process) throws Api id, PlatformErrorMessages.RPR_PGS_API_RESOURCE_NOT_AVAILABLE.name() + e.getMessage() + ExceptionUtils.getStackTrace(e)); } - + } if(defaultTemplateLanguages!=null && !defaultTemplateLanguages.isBlank()) { return List.of(defaultTemplateLanguages.split(",")); } - Map idValuesMap=packetManagerService.getAllFieldsByMappingJsonKeys(id, process, + Map idValuesMap=packetManagerService.getAllFieldsByMappingJsonKeys(id, process, ProviderStageName.MESSAGE_SENDER); List idValues=new ArrayList<>(); for(Entry entry: idValuesMap.entrySet()) { @@ -349,18 +349,18 @@ private List getPreferredLanguages(String id, String process) throws Api if(idValue!=null&& !idValue.isBlank() ) { if(isJSONArrayValid(idValue)) { JSONArray array=mapper.readValue(idValue, JSONArray.class); - for(Object obj:array) { + for(Object obj:array) { JSONObject json= new JSONObject( (Map) obj); - langSet.add( (String) json.get("language")); + langSet.add( (String) json.get("language")); } } } } return new ArrayList<>(langSet); } - - - + + + public boolean isJSONArrayValid(String jsonArrayString) { try { new org.json.JSONArray(jsonArrayString); @@ -396,17 +396,17 @@ private ResponseDto sendEmail(String[] mailTo, String[] mailCc, String subject, UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(apiHost); for (String item : mailTo) { - builder.queryParam("mailTo", item); + params.add("mailTo", item); } if (mailCc != null) { for (String item : mailCc) { - builder.queryParam("mailCc", item); + params.add("mailCc", item); } } - builder.queryParam("mailSubject", subject); - builder.queryParam("mailContent", artifact); + params.add("mailSubject", subject); + params.add("mailContent", artifact); params.add("attachments", attachment); regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", @@ -427,7 +427,7 @@ private ResponseDto sendEmail(String[] mailTo, String[] mailCc, String subject, * Gets the template json. * * @param id the id - * @param lang + * @param lang * @param idType the id type * @param attributes the attributes * @param regType the reg typesetAttributes @@ -436,10 +436,10 @@ private ResponseDto sendEmail(String[] mailTo, String[] mailCc, String subject, * has occurred. * @throws ApisResourceAccessException * @throws io.mosip.kernel.core.exception.IOException - * @throws io.mosip.kernel.core.exception.IOException - * @throws JsonMappingException - * @throws JsonParseException - * @throws PacketDecryptionFailureException + * @throws io.mosip.kernel.core.exception.IOException + * @throws JsonMappingException + * @throws JsonParseException + * @throws PacketDecryptionFailureException * @throws RegistrationProcessorCheckedException * @throws IdRepoAppException */ @@ -482,7 +482,7 @@ private Map setAttributes(String id, String process, String lang * the attributes * @param regType * the reg type - * @param lang + * @param lang * @return the map * @throws IOException * Signals that an I/O exception has occurred. @@ -531,7 +531,7 @@ private Map setAttributesFromIdRepo(String uin, Map setAttributesFromSync(String id, String process, Map attribute, String regType, String lang, StringBuilder phoneNumber, StringBuilder emailId) throws PacketDecryptionFailureException, ApisResourceAccessException, IOException, JsonParseException, JsonMappingException, io.mosip.kernel.core.exception.IOException { SyncRegistrationEntity regEntity = syncRegistrationService.findByRegistrationId(id).get(0); @@ -705,7 +705,7 @@ private Map setAttributesFromSync(String id, String process, Map } } return attribute; - + } private String getVid(String uin) throws ApisResourceAccessException { diff --git a/registration-processor/registration-processor-packet-manager/src/main/java/io/mosip/registration/processor/packet/manager/idreposervice/IdrepoDraftService.java b/registration-processor/registration-processor-packet-manager/src/main/java/io/mosip/registration/processor/packet/manager/idreposervice/IdrepoDraftService.java index 062b0b0640f..c1112974e5f 100644 --- a/registration-processor/registration-processor-packet-manager/src/main/java/io/mosip/registration/processor/packet/manager/idreposervice/IdrepoDraftService.java +++ b/registration-processor/registration-processor-packet-manager/src/main/java/io/mosip/registration/processor/packet/manager/idreposervice/IdrepoDraftService.java @@ -33,12 +33,14 @@ public class IdrepoDraftService { private static final Integer IDREPO_DRAFT_FOUND = 200; private static final Integer IDREPO_DRAFT_NOT_FOUND = 204; private static Logger regProcLogger = RegProcessorLogger.getLogger(IdrepoDraftService.class); - private static final String ID_REPO_KEY_MANAGER_ERROR = "IDR-IDS-003"; + private static final String ID_REPO_KEY_MANAGER_ERROR = "IDR-IDS-003"; @Autowired private ObjectMapper mapper; - /** The registration processor rest client service. */ + /** + * The registration processor rest client service. + */ @Autowired private RegistrationProcessorRestClientService registrationProcessorRestClientService; @@ -58,28 +60,38 @@ public boolean idrepoHasDraft(String id) throws ApisResourceAccessException, Idr return hasDraft; } - public ResponseDTO idrepoGetDraft(String id) throws ApisResourceAccessException { + public ResponseDTO idrepoGetDraft(String id) throws ApisResourceAccessException, IdrepoDraftException { regProcLogger.debug("idrepoGetDraft entry " + id); IdResponseDTO idResponseDTO = (IdResponseDTO) registrationProcessorRestClientService.getApi( ApiName.IDREPOGETDRAFT, Lists.newArrayList(id), Lists.emptyList(), null, IdResponseDTO.class); + if (idResponseDTO.getErrors() != null && !idResponseDTO.getErrors().isEmpty()) { + ErrorDTO error = idResponseDTO.getErrors().get(0); + regProcLogger.error("Error occured while getting draft for id : " + id, error.toString()); + throw new IdrepoDraftException(error.getErrorCode(), error.getMessage()); + } + regProcLogger.debug("idrepoGetDraft exit " + id); + return idResponseDTO.getResponse(); + } - regProcLogger.debug("idrepoGetDraft exit " + id); - return idResponseDTO.getResponse(); - } - public boolean idrepoCreateDraft(String id, String uin) throws ApisResourceAccessException { + public boolean idrepoCreateDraft(String id, String uin) throws ApisResourceAccessException, IdrepoDraftException { regProcLogger.debug("idrepoCreateDraft entry " + id); String queryParam = uin != null ? UIN : null; String queryParamValue = uin != null ? uin : null; ResponseWrapper response = (ResponseWrapper) registrationProcessorRestClientService.postApi( ApiName.IDREPOCREATEDRAFT, Lists.newArrayList(id), queryParam, queryParamValue, null, ResponseWrapper.class); - - return (response.getErrors() == null || response.getErrors().isEmpty()); + if (response.getErrors() != null && !response.getErrors().isEmpty()) + { + List error=response.getErrors(); + regProcLogger.error("Error while creating draft for id " + id); + throw new IdrepoDraftException(error.get(0).getErrorCode(), error.get(0).getMessage()); + } + return (response.getErrors() == null || response.getErrors().isEmpty()); } - public IdResponseDTO idrepoUpdateDraft(String id, String uin, IdRequestDto idRequestDto) - throws ApisResourceAccessException, IdrepoDraftException, IOException, IdrepoDraftReprocessableException { + public IdResponseDTO idrepoUpdateDraft(String id, String uin, IdRequestDto idRequestDto) + throws ApisResourceAccessException, IdrepoDraftException, IOException, IdrepoDraftReprocessableException { regProcLogger.debug("idrepoUpdateDraft entry " + id); if (!idrepoHasDraft(id)) { regProcLogger.info("Existing draft not found for id " + id + ". Creating new draft."); @@ -93,49 +105,70 @@ public IdResponseDTO idrepoUpdateDraft(String id, String uin, IdRequestDto idReq JSONObject existingIdentity = mapper.readValue(mapper.writeValueAsString(responseDTO.getIdentity()), JSONObject.class); JSONObject newIdentity = mapper.readValue(mapper.writeValueAsString(idRequestDto.getRequest().getIdentity()), JSONObject.class); newIdentity.put(UIN, existingIdentity.get(UIN)); - idRequestDto.getRequest().setIdentity(newIdentity); +// setting the identity to request while updating the draft. + requestDto.setIdentity(newIdentity); requestDto.setRegistrationId(responseDTO.getRegistrationId()); requestDto.setStatus(responseDTO.getStatus()); requestDto.setUin(responseDTO.getUin()); idRequestDto.setRequest(requestDto); - } - IdResponseDTO response = (IdResponseDTO) registrationProcessorRestClientService.patchApi( - ApiName.IDREPOUPDATEDRAFT, Lists.newArrayList(id), null, null, idRequestDto, IdResponseDTO.class); - if (response.getErrors() != null && !response.getErrors().isEmpty()) { - ErrorDTO error = response.getErrors().get(0); - regProcLogger.error("Error occured while updating draft for id : " + id, error.toString()); - if (response.getErrors().get(0).getErrorCode().equalsIgnoreCase(ID_REPO_KEY_MANAGER_ERROR)) { - throw new IdrepoDraftReprocessableException(error.getErrorCode(), error.getMessage()); - } else { - throw new IdrepoDraftException(error.getErrorCode(), error.getMessage()); - } + ApiName.IDREPOUPDATEDRAFT, Lists.newArrayList(id), null, null, idRequestDto, IdResponseDTO.class); + if (response.getErrors() != null && !response.getErrors().isEmpty()) { + regProcLogger.info("Error while updating the drant " + id); + regProcLogger.info(id+" Discarding the draft because of "+response.getErrors().get(0).getMessage()); + idrepoDiscardDraft(id); + ErrorDTO error = response.getErrors().get(0); + regProcLogger.error("Error occured while updating draft for id : " + id, error.toString()); + if (response.getErrors().get(0).getErrorCode().equalsIgnoreCase(ID_REPO_KEY_MANAGER_ERROR)) { + regProcLogger.error("Error occured Deleting the Draft : " + id, error.toString()); + throw new IdrepoDraftReprocessableException(error.getErrorCode(), error.getMessage()); + } else { + throw new IdrepoDraftException(error.getErrorCode(), error.getMessage()); + } } - regProcLogger.debug("idrepoUpdateDraft exit " + id); return response; } - - public IdResponseDTO idrepoPublishDraft(String id) - throws ApisResourceAccessException, IdrepoDraftException, IdrepoDraftReprocessableException { - regProcLogger.debug("idrepoPublishDraft entry " + id); - List pathsegments=new ArrayList(); - pathsegments.add(id); - IdResponseDTO response = (IdResponseDTO) registrationProcessorRestClientService. - getApi(ApiName.IDREPOPUBLISHDRAFT, pathsegments, "", "", IdResponseDTO.class); - if (response.getErrors() != null && !response.getErrors().isEmpty()) { - ErrorDTO error = response.getErrors().get(0); - regProcLogger.error("Error occured while updating draft for id : " + id, error.toString()); - if (response.getErrors().get(0).getErrorCode().equalsIgnoreCase(ID_REPO_KEY_MANAGER_ERROR)) { - throw new IdrepoDraftReprocessableException(error.getErrorCode(), error.getMessage()); - } else { - throw new IdrepoDraftException(error.getErrorCode(), error.getMessage()); - } + public IdResponseDTO idrepoPublishDraft(String id) + throws ApisResourceAccessException, IdrepoDraftException, IdrepoDraftReprocessableException { + regProcLogger.debug("idrepoPublishDraft entry " + id); + List pathsegments = new ArrayList(); + pathsegments.add(id); + IdResponseDTO response = (IdResponseDTO) registrationProcessorRestClientService. + getApi(ApiName.IDREPOPUBLISHDRAFT, pathsegments, "", "", IdResponseDTO.class); + + if(response.getErrors()!=null && !response.getErrors().isEmpty()) + { + ErrorDTO error=response.getErrors().get(0); + regProcLogger.error("Error occured while publishing the Draft : " + id, error.toString()); + if (response.getErrors().get(0).getErrorCode().equalsIgnoreCase(ID_REPO_KEY_MANAGER_ERROR)) { + throw new IdrepoDraftReprocessableException(error.getErrorCode(), error.getMessage()); + } else { + idrepoDiscardDraft(id); + throw new IdrepoDraftException(error.getErrorCode(), error.getMessage()); + } } - regProcLogger.debug("idrepoPublishDraft exit " + id); return response; - } + } + + public Boolean idrepoDiscardDraft(String id) throws ApisResourceAccessException, IdrepoDraftReprocessableException, IdrepoDraftException { + regProcLogger.debug("idrepoDiscardDraft entry " + id); + List pathsegments = new ArrayList(); + pathsegments.add(id); + IdResponseDTO response = (IdResponseDTO) registrationProcessorRestClientService. + deleteApi(ApiName.IDREPODISCARDDRAFT, pathsegments, "", "", IdResponseDTO.class); + if (response.getErrors() != null && !response.getErrors().isEmpty()) { + ErrorDTO error = response.getErrors().get(0); + regProcLogger.error("Error occured while discarding draft for id : " + id, error.toString()); + if (response.getErrors().get(0).getErrorCode().equalsIgnoreCase(ID_REPO_KEY_MANAGER_ERROR)) { + throw new IdrepoDraftReprocessableException(error.getErrorCode(), error.getMessage()); + } else { + throw new IdrepoDraftException(error.getErrorCode(), error.getMessage()); + } + } + return true; + } } diff --git a/registration-processor/registration-processor-packet-manager/src/test/java/io/mosip/registration/processor/packet/manager/service/impl/test/IdrepoDraftServiceTest.java b/registration-processor/registration-processor-packet-manager/src/test/java/io/mosip/registration/processor/packet/manager/service/impl/test/IdrepoDraftServiceTest.java index 580e2b3c17d..87adaf1902b 100644 --- a/registration-processor/registration-processor-packet-manager/src/test/java/io/mosip/registration/processor/packet/manager/service/impl/test/IdrepoDraftServiceTest.java +++ b/registration-processor/registration-processor-packet-manager/src/test/java/io/mosip/registration/processor/packet/manager/service/impl/test/IdrepoDraftServiceTest.java @@ -3,7 +3,7 @@ import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.when; +import static org.mockito.Mockito.*; import java.io.IOException; @@ -15,6 +15,7 @@ import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; +import org.mockito.Mockito; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; @@ -101,6 +102,7 @@ public void idrepoDraftCheckExceptionTest() throws ApisResourceAccessException, when(registrationProcessorRestClientService.headApi (ApiName.IDREPOHASDRAFT, Lists.newArrayList(ID), null, null)).thenReturn(500); + idrepoDraftService.idrepoHasDraft(ID); } @@ -142,8 +144,23 @@ public void idrepoPublishDraftExceptionTest() idResponseDTO1.setErrors(Lists.newArrayList(errorDTO)); when(registrationProcessorRestClientService.getApi( ApiName.IDREPOPUBLISHDRAFT, Lists.newArrayList(ID), "", "", IdResponseDTO.class)).thenReturn(idResponseDTO1); + ResponseDTO discardresponseDTO = new ResponseDTO(); + discardresponseDTO.setStatus("Drafted"); + discardresponseDTO.setRegistrationId(ID); + + JSONObject jsonObject1 = new JSONObject(); + jsonObject1.put("UIN", "1234"); + discardresponseDTO.setIdentity(jsonObject1); + IdResponseDTO discardIdresponseDto=new IdResponseDTO(); + discardIdresponseDto = new IdResponseDTO(); + discardIdresponseDto.setErrors(null); + discardIdresponseDto.setId("id.uin.update"); + discardIdresponseDto.setResponse(discardresponseDTO); + when(registrationProcessorRestClientService. + deleteApi(ApiName.IDREPODISCARDDRAFT, Lists.newArrayList(ID), "", "", IdResponseDTO.class)).thenReturn(discardIdresponseDto); idrepoDraftService.idrepoPublishDraft(ID); + Mockito.verify(idrepoDraftService.idrepoDiscardDraft(any()),times(1)); } @Test @@ -154,7 +171,6 @@ public void idrepoCreateDraftSuccessTest() throws ApisResourceAccessException, I ApiName.IDREPOCREATEDRAFT, Lists.newArrayList(ID), null, null, null, ResponseWrapper.class)).thenReturn(responseWrapper); boolean result = idrepoDraftService.idrepoCreateDraft(ID, null); - assertTrue(result); } @@ -199,7 +215,24 @@ public void idrepoUpdateDraftExceptionTest() when(registrationProcessorRestClientService.patchApi( any(), any(), any(), any(), any(), any())).thenReturn(idResponseDTO1); - idrepoDraftService.idrepoUpdateDraft(ID, null, idRequestDto); + ResponseDTO discardresponseDTO = new ResponseDTO(); + discardresponseDTO.setStatus("Drafted"); + discardresponseDTO.setRegistrationId(ID); + + JSONObject jsonObject1 = new JSONObject(); + jsonObject1.put("UIN", "1234"); + discardresponseDTO.setIdentity(jsonObject1); + IdResponseDTO discardIdresponseDto=new IdResponseDTO(); + discardIdresponseDto = new IdResponseDTO(); + discardIdresponseDto.setErrors(null); + discardIdresponseDto.setId("id.uin.update"); + discardIdresponseDto.setResponse(discardresponseDTO); + when(registrationProcessorRestClientService. + deleteApi(ApiName.IDREPODISCARDDRAFT, Lists.newArrayList(ID), "", "", IdResponseDTO.class)).thenReturn(discardIdresponseDto); + + + IdResponseDTO idResponseDTO2=idrepoDraftService.idrepoUpdateDraft(ID, null, idRequestDto); + verify(idrepoDraftService.idrepoDiscardDraft(any()),times(1)); } @@ -223,9 +256,39 @@ public void idrepoDraftReprocessableExceptionTest() Lists.emptyList(), null, IdResponseDTO.class)).thenReturn(idResponseDTO); when(registrationProcessorRestClientService.patchApi(any(), any(), any(), any(), any(), any())) .thenReturn(idResponseDTO1); + ResponseDTO discardresponseDTO = new ResponseDTO(); + discardresponseDTO.setRegistrationId(ID); + JSONObject jsonObject1 = new JSONObject(); + jsonObject1.put("UIN", "1234"); + discardresponseDTO.setIdentity(jsonObject1); + IdResponseDTO discardIdresponseDto= new IdResponseDTO(); + discardIdresponseDto.setErrors(null); + discardIdresponseDto.setId("id.uin.update"); + discardIdresponseDto.setResponse(discardresponseDTO); + when(registrationProcessorRestClientService. + deleteApi(ApiName.IDREPODISCARDDRAFT, Lists.newArrayList(ID), "", "", IdResponseDTO.class)).thenReturn(discardIdresponseDto); idrepoDraftService.idrepoUpdateDraft(ID, null, idRequestDto); + Mockito.verify(idrepoDraftService.idrepoDiscardDraft(any()),times(1)); } - + @Test + public void discardDraftSuccessTest() throws IdrepoDraftReprocessableException, IdrepoDraftException, ApisResourceAccessException { + ResponseDTO discardresponseDTO = new ResponseDTO(); + discardresponseDTO.setStatus("Drafted"); + discardresponseDTO.setRegistrationId(ID); + + JSONObject jsonObject1 = new JSONObject(); + jsonObject1.put("UIN", "1234"); + discardresponseDTO.setIdentity(jsonObject1); + IdResponseDTO discardIdresponseDto= new IdResponseDTO(); + discardIdresponseDto.setErrors(null); + discardIdresponseDto.setId("id.uin.update"); + discardIdresponseDto.setResponse(discardresponseDTO); + when(registrationProcessorRestClientService. + deleteApi(ApiName.IDREPODISCARDDRAFT, Lists.newArrayList(ID), "", "", IdResponseDTO.class)).thenReturn(discardIdresponseDto); + + Boolean result= idrepoDraftService.idrepoDiscardDraft(ID); + assertTrue(result); + } } diff --git a/registration-processor/registration-processor-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/code/RegistrationStatusCode.java b/registration-processor/registration-processor-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/code/RegistrationStatusCode.java index c7d8923bcb9..98a4266f953 100644 --- a/registration-processor/registration-processor-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/code/RegistrationStatusCode.java +++ b/registration-processor/registration-processor-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/code/RegistrationStatusCode.java @@ -21,7 +21,7 @@ public enum RegistrationStatusCode { PROCESSED, REPROCESS_FAILED, - + PAUSED, RESUMABLE, diff --git a/registration-processor/registration-processor-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/service/impl/InternalAuthDelegateServiceImpl.java b/registration-processor/registration-processor-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/service/impl/InternalAuthDelegateServiceImpl.java index 56ccd3afc26..6f34b871d06 100644 --- a/registration-processor/registration-processor-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/service/impl/InternalAuthDelegateServiceImpl.java +++ b/registration-processor/registration-processor-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/service/impl/InternalAuthDelegateServiceImpl.java @@ -165,7 +165,7 @@ private String getIndividualIdByUserId(String userid) throws ApisResourceAccessE } catch (IOException e) { throw new IOException(PlatformErrorMessages.RPR_RGS_IOEXCEPTION.getMessage()); } - + logger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), userid, "InternalAuthDelegateServiceImpl::getIndividualIdByUserId()::exit"); return individualId; diff --git a/registration-processor/registration-processor-rest-client/src/main/java/io/mosip/registration/processor/rest/client/audit/builder/AuditLogRequestBuilder.java b/registration-processor/registration-processor-rest-client/src/main/java/io/mosip/registration/processor/rest/client/audit/builder/AuditLogRequestBuilder.java index f9ad556b53c..ed2670b8b2a 100644 --- a/registration-processor/registration-processor-rest-client/src/main/java/io/mosip/registration/processor/rest/client/audit/builder/AuditLogRequestBuilder.java +++ b/registration-processor/registration-processor-rest-client/src/main/java/io/mosip/registration/processor/rest/client/audit/builder/AuditLogRequestBuilder.java @@ -220,7 +220,7 @@ public ResponseWrapper createAuditRequestBuilder(String descri return responseWrapper; } - + @SuppressWarnings("unchecked") public ResponseWrapper createAuditRequestBuilder(String description, String eventId, String eventName, String eventType, String moduleId, String moduleName, String registrationId) { diff --git a/registration-processor/registration-processor-rest-client/src/main/java/io/mosip/registration/processor/rest/client/service/impl/RegistrationProcessorRestClientServiceImpl.java b/registration-processor/registration-processor-rest-client/src/main/java/io/mosip/registration/processor/rest/client/service/impl/RegistrationProcessorRestClientServiceImpl.java index 81681958f63..8fa682884f1 100644 --- a/registration-processor/registration-processor-rest-client/src/main/java/io/mosip/registration/processor/rest/client/service/impl/RegistrationProcessorRestClientServiceImpl.java +++ b/registration-processor/registration-processor-rest-client/src/main/java/io/mosip/registration/processor/rest/client/service/impl/RegistrationProcessorRestClientServiceImpl.java @@ -521,4 +521,58 @@ public Integer headApi(ApiName apiName, List pathsegments, List return obj; } + + @Override + public Object deleteApi(ApiName apiName, List pathsegments, String queryParamName, String queryParamValue, + Class responseType) throws ApisResourceAccessException { + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", + "RegistrationProcessorRestClientServiceImpl::deleteApi()::entry"); + Object obj = null; + String apiHostIpPort = env.getProperty(apiName.name()); + + UriComponentsBuilder builder = null; + UriComponents uriComponents = null; + if (apiHostIpPort != null) { + + builder = UriComponentsBuilder.fromUriString(apiHostIpPort); + if (!((pathsegments == null) || (pathsegments.isEmpty()))) { + for (String segment : pathsegments) { + if (!((segment == null) || (("").equals(segment)))) { + builder.pathSegment(segment); + } + } + + } + + if (!((queryParamName == null) || (("").equals(queryParamName)))) { + + String[] queryParamNameArr = queryParamName.split(","); + String[] queryParamValueArr = queryParamValue.split(","); + for (int i = 0; i < queryParamNameArr.length; i++) { + builder.queryParam(queryParamNameArr[i], queryParamValueArr[i]); + } + + } + + try { + + uriComponents = builder.build(false).encode(); + regProcLogger.debug(uriComponents.toUri().toString(), "URI", "", ""); + obj = restApiClient.deleteApi(uriComponents.toUri(), responseType); + + } catch (Exception e) { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString(), "", + e.getMessage() + ExceptionUtils.getStackTrace(e)); + + throw new ApisResourceAccessException( + PlatformErrorMessages.RPR_RCT_UNKNOWN_RESOURCE_EXCEPTION.getCode(), e); + + } + } + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", + "RegistrationProcessorRestClientServiceImpl::deleteApi::exit"); + return obj; + } + } \ No newline at end of file diff --git a/registration-processor/registration-processor-rest-client/src/main/java/io/mosip/registration/processor/rest/client/utils/RestApiClient.java b/registration-processor/registration-processor-rest-client/src/main/java/io/mosip/registration/processor/rest/client/utils/RestApiClient.java index 419c533200f..177d44c140b 100644 --- a/registration-processor/registration-processor-rest-client/src/main/java/io/mosip/registration/processor/rest/client/utils/RestApiClient.java +++ b/registration-processor/registration-processor-rest-client/src/main/java/io/mosip/registration/processor/rest/client/utils/RestApiClient.java @@ -6,7 +6,6 @@ import java.util.List; import org.apache.commons.lang3.exception.ExceptionUtils; -import org.apache.directory.api.util.Strings; import org.apache.http.Header; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; @@ -313,4 +312,21 @@ public void tokenExceptionHandler(Exception e) { } } + + public T deleteApi(URI uri, Class responseType) throws Exception { + T result = null; + + try { + result = (T) localRestTemplate.exchange(uri, HttpMethod.DELETE, setRequestHeader(null, null), responseType) + .getBody(); + } catch (Exception e) { + logger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), + LoggerFileConstant.APPLICATIONID.toString(), e.getMessage() + ExceptionUtils.getStackTrace(e)); + tokenExceptionHandler(e); + throw e; + } + return result; + } + + } diff --git a/registration-processor/registration-processor-rest-client/src/test/java/io/mosip/registration/processor/rest/client/service/RegistrationProcessorRestClientServiceTest.java b/registration-processor/registration-processor-rest-client/src/test/java/io/mosip/registration/processor/rest/client/service/RegistrationProcessorRestClientServiceTest.java index a4127a1e060..ee3d0932f2f 100644 --- a/registration-processor/registration-processor-rest-client/src/test/java/io/mosip/registration/processor/rest/client/service/RegistrationProcessorRestClientServiceTest.java +++ b/registration-processor/registration-processor-rest-client/src/test/java/io/mosip/registration/processor/rest/client/service/RegistrationProcessorRestClientServiceTest.java @@ -32,11 +32,15 @@ public class RegistrationProcessorRestClientServiceTest { @InjectMocks RegistrationProcessorRestClientService registrationProcessorRestClientService = new RegistrationProcessorRestClientServiceImpl(); - /** The rest api client. */ + /** + * The rest api client. + */ @Mock private RestApiClient restApiClient; - /** The env. */ + /** + * The env. + */ @Mock private Environment env; private AuditResponseDto auditResponseDto; @@ -89,7 +93,7 @@ public void postObjecTestFailureTest() throws Exception { registrationProcessorRestClientService.postApi(ApiName.AUDIT, "query1", "12345", auditRequestDto, AuditResponseDto.class); } - + @Test public void getObjectForArgListSuccessTest() throws Exception { @@ -135,7 +139,7 @@ public void postObjectTestFailureTest() throws Exception { registrationProcessorRestClientService.postApi(ApiName.AUDIT, pathSegments, "query1", "12345", auditRequestDto, AuditResponseDto.class); } - + @Test public void postObjectForArgListSuccessTest() throws Exception { AuditRequestDto auditRequestDto = new AuditRequestDto(); @@ -162,7 +166,7 @@ public void postObjectForArgListTestFailureTest() throws Exception { registrationProcessorRestClientService.postApi(ApiName.AUDIT, null, pathSegments, Arrays.asList("query1"), Arrays.asList("12345"), auditRequestDto, AuditResponseDto.class); } - + @Test public void patchObjectSuccessTest() throws Exception { AuditRequestDto auditRequestDto = new AuditRequestDto(); @@ -175,7 +179,7 @@ public void patchObjectSuccessTest() throws Exception { pathSegments, "query1", "12345", auditRequestDto, AuditResponseDto.class); assertEquals(true, resultDto.isStatus()); } - + @Test(expected = ApisResourceAccessException.class) public void patchObjectTestFailureTest() throws Exception { AuditRequestDto auditRequestDto = new AuditRequestDto(); @@ -188,20 +192,20 @@ public void patchObjectTestFailureTest() throws Exception { registrationProcessorRestClientService.patchApi(ApiName.AUDIT, pathSegments, "query1", "12345", auditRequestDto, AuditResponseDto.class); } - + @Test public void putObjectSuccessTest() throws Exception { AuditRequestDto auditRequestDto = new AuditRequestDto(); Mockito.when(env.getProperty(ArgumentMatchers.any())).thenReturn("AUDIT"); - Mockito.when(restApiClient.putApi(ArgumentMatchers.any(),ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.any())) + Mockito.when(restApiClient.putApi(ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.any())) .thenReturn(auditResponseDto); List pathSegments = new ArrayList<>(); pathSegments.add("test"); AuditResponseDto resultDto = (AuditResponseDto) registrationProcessorRestClientService.putApi(ApiName.AUDIT, - pathSegments, "query1", "12345", auditRequestDto, AuditResponseDto.class,null); + pathSegments, "query1", "12345", auditRequestDto, AuditResponseDto.class, null); assertEquals(true, resultDto.isStatus()); } - + @Test(expected = ApisResourceAccessException.class) public void putObjectTestFailureTest() throws Exception { AuditRequestDto auditRequestDto = new AuditRequestDto(); @@ -212,9 +216,9 @@ public void putObjectTestFailureTest() throws Exception { Mockito.when(restApiClient.putApi(ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.any())) .thenThrow(exp); registrationProcessorRestClientService.putApi(ApiName.AUDIT, pathSegments, "query1", "12345", auditRequestDto, - AuditResponseDto.class,null); + AuditResponseDto.class, null); } - + @Test public void postObjectForUrlSuccessTest() throws Exception { AuditRequestDto auditRequestDto = new AuditRequestDto(); @@ -261,4 +265,23 @@ public void headObjectTestFailureTest() throws Exception { registrationProcessorRestClientService.headApi(ApiName.AUDIT, pathSegments, Arrays.asList("query1"), Arrays.asList("12345")); } + + @Test + public void deleteObjecSuccessTest() throws Exception { + + Mockito.when(env.getProperty(ArgumentMatchers.any())).thenReturn("AUDIT"); + Mockito.when(restApiClient.deleteApi(ArgumentMatchers.any(), ArgumentMatchers.any())).thenReturn(auditResponseDto); + AuditResponseDto resultDto = (AuditResponseDto) registrationProcessorRestClientService.deleteApi(ApiName.AUDIT, + null, "query1", "12345", AuditResponseDto.class); + assertEquals(true, resultDto.isStatus()); + } + + @Test(expected = ApisResourceAccessException.class) + public void deleteObjecTestFailureTest() throws Exception { + Mockito.when(env.getProperty(ArgumentMatchers.any())).thenReturn("AUDIT"); + ResourceAccessException exp = new ResourceAccessException("errorMessage"); + Mockito.when(restApiClient.deleteApi(ArgumentMatchers.any(), ArgumentMatchers.any())).thenThrow(exp); + + registrationProcessorRestClientService.deleteApi(ApiName.AUDIT, Arrays.asList("abc", "def"), "query1", "12345", + AuditResponseDto.class); } } diff --git a/registration-processor/workflow-engine/registration-processor-reprocessor/src/test/java/io/mosip/registration/processor/reprocessor/verticle/ReprocessingSchedulerTest.java b/registration-processor/workflow-engine/registration-processor-reprocessor/src/test/java/io/mosip/registration/processor/reprocessor/verticle/ReprocessingSchedulerTest.java index 26feed23ce4..97b7f86193a 100644 --- a/registration-processor/workflow-engine/registration-processor-reprocessor/src/test/java/io/mosip/registration/processor/reprocessor/verticle/ReprocessingSchedulerTest.java +++ b/registration-processor/workflow-engine/registration-processor-reprocessor/src/test/java/io/mosip/registration/processor/reprocessor/verticle/ReprocessingSchedulerTest.java @@ -1,305 +1,306 @@ -package io.mosip.registration.processor.reprocessor.verticle; - -import static org.junit.Assert.assertNotNull; - -import org.assertj.core.api.Assertions; -import org.assertj.core.groups.Tuple; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.runners.MockitoJUnitRunner; -import org.slf4j.LoggerFactory; -import org.springframework.core.env.Environment; - -import ch.qos.logback.classic.Level; -import ch.qos.logback.classic.Logger; -import ch.qos.logback.classic.spi.ILoggingEvent; -import ch.qos.logback.core.read.ListAppender; -import io.mosip.registration.processor.core.abstractverticle.EventDTO; -import io.mosip.registration.processor.core.abstractverticle.HealthCheckDTO; -import io.mosip.registration.processor.core.abstractverticle.MessageBusAddress; -import io.mosip.registration.processor.core.abstractverticle.MessageDTO; -import io.mosip.registration.processor.core.abstractverticle.MosipEventBus; -import io.mosip.registration.processor.core.spi.eventbus.EventHandler; -import io.vertx.core.AsyncResult; -import io.vertx.core.Handler; -import io.vertx.core.Vertx; -import io.vertx.core.eventbus.DeliveryContext; -import io.vertx.core.eventbus.DeliveryOptions; -import io.vertx.core.eventbus.EventBus; -import io.vertx.core.eventbus.Message; -import io.vertx.core.eventbus.MessageCodec; -import io.vertx.core.eventbus.MessageConsumer; -import io.vertx.core.eventbus.MessageProducer; - -/** - * Test class for scheduler - * - * @author Pranav Kumar - * @since 0.10.0 - * - */ -@RunWith(MockitoJUnitRunner.class) -public class ReprocessingSchedulerTest { - - /** - * Mocked Vertx instance - */ - @Mock - public Vertx vertx; - - /** - * Mocked Vertx Async Handler - */ - @Mock - AsyncResult res; - - /** - * Mocked Spring Environment - */ - @Mock - Environment env; - - private Logger fooLogger; - - private ListAppender listAppender; - - /** - * Setup for test - */ - @Before - public void setup() { - fooLogger = (Logger) LoggerFactory.getLogger(ReprocessorVerticle.class); - listAppender = new ListAppender<>(); - Mockito.when(vertx.eventBus()).thenReturn(Vertx.vertx().eventBus()); - } - - /** - * Mocked instance of Reprocessor Verticle - */ - @InjectMocks - ReprocessorVerticle reprocessorVerticle = new ReprocessorVerticle() { - /* (non-Javadoc) - * @see io.mosip.registration.processor.core.abstractverticle.MosipVerticleManager#getEventBus(java.lang.Object, java.lang.String) - */ - @Override - public MosipEventBus getEventBus(Object verticleName, String clusterManagerUrl) { - vertx = Vertx.vertx(); - - return new MosipEventBus() { - - @Override - public Vertx getEventbus() { - return vertx; - } - - @Override - public void consume(MessageBusAddress fromAddress, - EventHandler>> eventHandler) { - - } - - @Override - public void consumeAndSend(MessageBusAddress fromAddress, MessageBusAddress toAddress, - EventHandler>> eventHandler) { - - } - - @Override - public void send(MessageBusAddress toAddress, MessageDTO message) { - - } - @Override - public void consumerHealthCheck(Handler eventHandler, String address) { - // TODO Auto-generated method stub - - } - - @Override - public void senderHealthCheck(Handler eventHandler, String address) { - // TODO Auto-generated method stub - - } - }; - } - }; - - /** - * Success Test for deployment of ReprocessorVerticle - */ - @Test - public void testDeploySuccess() { - reprocessorVerticle.deployVerticle(); - assertNotNull(reprocessorVerticle.mosipEventBus); - } - - /** - * Success Test for Chime Scheduler deployment - */ - @Test - public void testDeploySchedulerTest() { - listAppender.start(); - fooLogger.addAppender(listAppender); - Mockito.when(res.succeeded()).thenReturn(true); - Mockito.when(vertx.eventBus()).thenReturn(getMockEventBus()); - reprocessorVerticle.schedulerResult(res); - Assertions.assertThat(listAppender.list).extracting(ILoggingEvent::getLevel, ILoggingEvent::getFormattedMessage) - .contains(Tuple.tuple(Level.INFO, - "ReprocessorVerticle::schedular()::deployed")); - } - - /** - * Failure Test for Chime Scheduler deployment - */ - @Test - @Ignore - public void testDeploySchedulerFailureTest() { - listAppender.start(); - fooLogger.addAppender(listAppender); - Mockito.when(res.succeeded()).thenReturn(false); - Mockito.when(res.cause()).thenReturn(new Exception("Exception")); - //Mockito.when(vertx.eventBus()).thenReturn(getMockEventBus()); - reprocessorVerticle.schedulerResult(res); - Assertions.assertThat(listAppender.list).extracting(ILoggingEvent::getLevel, ILoggingEvent::getFormattedMessage) - .contains(Tuple.tuple(Level.ERROR, - "ReprocessorVerticle::schedular()::deployment failure Exception")); - } - /** - * Returns dummy eventbus instance - * @return Eventbus - */ - public EventBus getMockEventBus() { - return new EventBus() { - - @Override - public boolean isMetricsEnabled() { - return false; - } - - @Override - public EventBus unregisterDefaultCodec(Class clazz) { - return null; - } - - @Override - public EventBus unregisterCodec(String name) { - return null; - } - - @Override - public void start(Handler> completionHandler) { - } - - @Override - public MessageProducer sender(String address, DeliveryOptions options) { - return null; - } - - @Override - public MessageProducer sender(String address) { - return null; - } - - @Override - public EventBus send(String address, Object message, DeliveryOptions options, - Handler>> replyHandler) { - return null; - } - - @Override - public EventBus send(String address, Object message, DeliveryOptions options) { - return null; - } - - @Override - public EventBus send(String address, Object message, - Handler>> replyHandler) { - return null; - } - - @Override - public EventBus send(String address, Object message) { - return null; - } - - @Override - public EventBus registerDefaultCodec(Class clazz, MessageCodec codec) { - return null; - } - - @Override - public EventBus registerCodec(MessageCodec codec) { - return null; - } - - @Override - public MessageProducer publisher(String address, DeliveryOptions options) { - return null; - } - - @Override - public MessageProducer publisher(String address) { - return null; - } - - @Override - public EventBus publish(String address, Object message, DeliveryOptions options) { - return null; - } - - @Override - public EventBus publish(String address, Object message) { - return null; - } - - @Override - public MessageConsumer localConsumer(String address, Handler> handler) { - return null; - } - - @Override - public MessageConsumer localConsumer(String address) { - return null; - } - - @Override - public MessageConsumer consumer(String address, Handler> handler) { - return null; - } - - @Override - public MessageConsumer consumer(String address) { - return null; - } - - @Override - public void close(Handler> completionHandler) { - } - - @Override - public EventBus addOutboundInterceptor(Handler> interceptor) { - return null; - } - - @Override - public EventBus removeOutboundInterceptor(Handler> interceptor) { - return null; - } - - @Override - public EventBus addInboundInterceptor(Handler> interceptor) { - return null; - } - - @Override - public EventBus removeInboundInterceptor(Handler> interceptor) { - return null; - } - - }; - } -} +package io.mosip.registration.processor.reprocessor.verticle; + +import static org.junit.Assert.assertNotNull; + +import org.assertj.core.api.Assertions; +import org.assertj.core.groups.Tuple; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.runners.MockitoJUnitRunner; +import org.slf4j.LoggerFactory; +import org.springframework.core.env.Environment; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.read.ListAppender; +import io.mosip.registration.processor.core.abstractverticle.EventDTO; +import io.mosip.registration.processor.core.abstractverticle.HealthCheckDTO; +import io.mosip.registration.processor.core.abstractverticle.MessageBusAddress; +import io.mosip.registration.processor.core.abstractverticle.MessageDTO; +import io.mosip.registration.processor.core.abstractverticle.MosipEventBus; +import io.mosip.registration.processor.core.spi.eventbus.EventHandler; +import io.vertx.core.AsyncResult; +import io.vertx.core.Handler; +import io.vertx.core.Vertx; +import io.vertx.core.eventbus.DeliveryContext; +import io.vertx.core.eventbus.DeliveryOptions; +import io.vertx.core.eventbus.EventBus; +import io.vertx.core.eventbus.Message; +import io.vertx.core.eventbus.MessageCodec; +import io.vertx.core.eventbus.MessageConsumer; +import io.vertx.core.eventbus.MessageProducer; + +/** + * Test class for scheduler + * + * @author Pranav Kumar + * @since 0.10.0 + * + */ +@RunWith(MockitoJUnitRunner.class) +public class ReprocessingSchedulerTest { + + /** + * Mocked Vertx instance + */ + @Mock + public Vertx vertx; + + /** + * Mocked Vertx Async Handler + */ + @Mock + AsyncResult res; + + /** + * Mocked Spring Environment + */ + @Mock + Environment env; + + private Logger fooLogger; + + private ListAppender listAppender; + + /** + * Setup for test + */ + @Before + public void setup() { + fooLogger = (Logger) LoggerFactory.getLogger(ReprocessorVerticle.class); + listAppender = new ListAppender<>(); + Mockito.when(vertx.eventBus()).thenReturn(Vertx.vertx().eventBus()); + } + + /** + * Mocked instance of Reprocessor Verticle + */ + @InjectMocks + ReprocessorVerticle reprocessorVerticle = new ReprocessorVerticle() { + /* (non-Javadoc) + * @see io.mosip.registration.processor.core.abstractverticle.MosipVerticleManager#getEventBus(java.lang.Object, java.lang.String) + */ + @Override + public MosipEventBus getEventBus(Object verticleName, String clusterManagerUrl) { + vertx = Vertx.vertx(); + + return new MosipEventBus() { + + @Override + public Vertx getEventbus() { + return vertx; + } + + @Override + public void consume(MessageBusAddress fromAddress, + EventHandler>> eventHandler) { + + } + + @Override + public void consumeAndSend(MessageBusAddress fromAddress, MessageBusAddress toAddress, + EventHandler>> eventHandler) { + + } + + @Override + public void send(MessageBusAddress toAddress, MessageDTO message) { + + } + + @Override + public void consumerHealthCheck(Handler eventHandler, String address) { + // TODO Auto-generated method stub + + } + + @Override + public void senderHealthCheck(Handler eventHandler, String address) { + // TODO Auto-generated method stub + + } + }; + } + }; + + /** + * Success Test for deployment of ReprocessorVerticle + */ + @Test + public void testDeploySuccess() { + reprocessorVerticle.deployVerticle(); + assertNotNull(reprocessorVerticle.mosipEventBus); + } + + /** + * Success Test for Chime Scheduler deployment + */ + @Test + public void testDeploySchedulerTest() { + listAppender.start(); + fooLogger.addAppender(listAppender); + Mockito.when(res.succeeded()).thenReturn(true); + Mockito.when(vertx.eventBus()).thenReturn(getMockEventBus()); + reprocessorVerticle.schedulerResult(res); + Assertions.assertThat(listAppender.list).extracting(ILoggingEvent::getLevel, ILoggingEvent::getFormattedMessage) + .contains(Tuple.tuple(Level.INFO, + "ReprocessorVerticle::schedular()::deployed")); + } + + /** + * Failure Test for Chime Scheduler deployment + */ + @Test + @Ignore + public void testDeploySchedulerFailureTest() { + listAppender.start(); + fooLogger.addAppender(listAppender); + Mockito.when(res.succeeded()).thenReturn(false); + Mockito.when(res.cause()).thenReturn(new Exception("Exception")); + //Mockito.when(vertx.eventBus()).thenReturn(getMockEventBus()); + reprocessorVerticle.schedulerResult(res); + Assertions.assertThat(listAppender.list).extracting(ILoggingEvent::getLevel, ILoggingEvent::getFormattedMessage) + .contains(Tuple.tuple(Level.ERROR, + "ReprocessorVerticle::schedular()::deployment failure Exception")); + } + /** + * Returns dummy eventbus instance + * @return Eventbus + */ + public EventBus getMockEventBus() { + return new EventBus() { + + @Override + public boolean isMetricsEnabled() { + return false; + } + + @Override + public EventBus unregisterDefaultCodec(Class clazz) { + return null; + } + + @Override + public EventBus unregisterCodec(String name) { + return null; + } + + @Override + public void start(Handler> completionHandler) { + } + + @Override + public MessageProducer sender(String address, DeliveryOptions options) { + return null; + } + + @Override + public MessageProducer sender(String address) { + return null; + } + + @Override + public EventBus send(String address, Object message, DeliveryOptions options, + Handler>> replyHandler) { + return null; + } + + @Override + public EventBus send(String address, Object message, DeliveryOptions options) { + return null; + } + + @Override + public EventBus send(String address, Object message, + Handler>> replyHandler) { + return null; + } + + @Override + public EventBus send(String address, Object message) { + return null; + } + + @Override + public EventBus registerDefaultCodec(Class clazz, MessageCodec codec) { + return null; + } + + @Override + public EventBus registerCodec(MessageCodec codec) { + return null; + } + + @Override + public MessageProducer publisher(String address, DeliveryOptions options) { + return null; + } + + @Override + public MessageProducer publisher(String address) { + return null; + } + + @Override + public EventBus publish(String address, Object message, DeliveryOptions options) { + return null; + } + + @Override + public EventBus publish(String address, Object message) { + return null; + } + + @Override + public MessageConsumer localConsumer(String address, Handler> handler) { + return null; + } + + @Override + public MessageConsumer localConsumer(String address) { + return null; + } + + @Override + public MessageConsumer consumer(String address, Handler> handler) { + return null; + } + + @Override + public MessageConsumer consumer(String address) { + return null; + } + + @Override + public void close(Handler> completionHandler) { + } + + @Override + public EventBus addOutboundInterceptor(Handler> interceptor) { + return null; + } + + @Override + public EventBus removeOutboundInterceptor(Handler> interceptor) { + return null; + } + + @Override + public EventBus addInboundInterceptor(Handler> interceptor) { + return null; + } + + @Override + public EventBus removeInboundInterceptor(Handler> interceptor) { + return null; + } + + }; + } +}