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..a1d64390871 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 @@ -575,13 +575,15 @@ private String getUUID() { } private String getDataShareUrl(String id, String process) throws Exception { - Map> typeAndSubtypMap = createTypeSubtypeMapping(); + Map> policyTypeAndSubTypeMap = createTypeSubtypeMapping(); List modalities = new ArrayList<>(); - for (Map.Entry> entry : typeAndSubtypMap.entrySet()) { + List policyTypeAndSubTypeList = new ArrayList<>(); + modalities.addAll(policyTypeAndSubTypeMap.keySet()); + for (Map.Entry> entry : policyTypeAndSubTypeMap.entrySet()) { if (entry.getValue() == null) { - modalities.add(entry.getKey()); + policyTypeAndSubTypeList.add(entry.getKey()); } else { - modalities.addAll(entry.getValue()); + policyTypeAndSubTypeList.addAll(entry.getValue()); } } JSONObject regProcessorIdentityJson = utility @@ -590,19 +592,20 @@ private String getDataShareUrl(String id, String process) throws Exception { JsonUtil.getJSONObject(regProcessorIdentityJson, MappingJsonConstants.INDIVIDUAL_BIOMETRICS), MappingJsonConstants.VALUE); BiometricRecord biometricRecord = priorityBasedPacketManagerService.getBiometrics(id, individualBiometricsLabel, - modalities, process, ProviderStageName.BIO_DEDUPE); + policyTypeAndSubTypeList, process, ProviderStageName.BIO_DEDUPE); Map tags = packetManagerService.getAllTags(id); String ageGroup = tags.get("AGE_GROUP"); - Map> biometricModalitySegmentsMap; + Map> ageGroupModalitySegmentMap; if(biometricModalitySegmentsMapforAgeGroup.containsKey(ageGroup)){ - biometricModalitySegmentsMap = biometricModalitySegmentsMapforAgeGroup.get(ageGroup); + ageGroupModalitySegmentMap = biometricModalitySegmentsMapforAgeGroup.get(ageGroup); } else { - biometricModalitySegmentsMap = biometricModalitySegmentsMapforAgeGroup.get("DEFAULT"); + ageGroupModalitySegmentMap = biometricModalitySegmentsMapforAgeGroup.get("DEFAULT"); } - validateBiometricRecord(biometricRecord, modalities, biometricModalitySegmentsMap, - priorityBasedPacketManagerService.getMetaInfo(id, process, ProviderStageName.BIO_DEDUPE)); + validateBiometricRecord(biometricRecord, modalities, ageGroupModalitySegmentMap, + priorityBasedPacketManagerService.getMetaInfo(id, process, ProviderStageName.BIO_DEDUPE), + policyTypeAndSubTypeMap); byte[] content = cbeffutil.createXML(filterExceptionBiometrics(biometricRecord,id,process).getSegments()); @@ -640,7 +643,8 @@ public String getFilename() { @SuppressWarnings("deprecation") private void validateBiometricRecord(BiometricRecord biometricRecord, List modalities, - Map> biometricModalitySegmentsMap, Map metaInfoMap) + 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"); @@ -660,11 +664,18 @@ private void validateBiometricRecord(BiometricRecord biometricRecord, 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() 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..eedd7c44f46 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 @@ -128,7 +128,7 @@ public class AbisMiddleWareStage extends MosipVerticleAPIManager { /** The core audit request builder. */ @Autowired private AuditLogRequestBuilder auditLogRequestBuilder; - + @Autowired private PacketInfoDao packetInfoDao; @@ -206,7 +206,7 @@ public void start() { router.setRoute(this.postUrl(getVertx(), MessageBusAddress.ABIS_MIDDLEWARE_BUS_IN, MessageBusAddress.ABIS_MIDDLEWARE_BUS_OUT)); this.createServer(router.getRouter(), getPort()); - + } @Override @@ -631,7 +631,7 @@ private void updteAbisRequestProcessed(AbisCommonResponseDto abisCommonResponseD + io.mosip.registartion.processor.abis.middleware.constants.FailureReason .getValueFromKey(abisCommonResponseDto.getFailureReason()), "AbisMiddleWareStage::updteAbisRequestProcessed()"); - + } abisReqEntity.setAbisAppCode(abisCommonRequestDto.getAbisAppCode()); abisReqEntity.setRequestType(abisCommonRequestDto.getRequestType()); @@ -704,7 +704,7 @@ private AbisResponseDto updateAbisResponseEntity(AbisCommonResponseDto abisCommo abisResponseDto.setId(RegistrationUtility.generateId()); abisResponseDto.setRespText(response.getBytes()); - + if (isInsertSuccess(abisCommonResponseDto)) { abisResponseDto.setStatusCode(AbisStatusCode.SUCCESS.toString()); } else { @@ -716,7 +716,7 @@ private AbisResponseDto updateAbisResponseEntity(AbisCommonResponseDto abisCommo .getValueFromKey(abisCommonResponseDto.getFailureReason()), "AbisMiddleWareStage::updateAbisResponseEntity()"); } - + abisResponseDto.setStatusComment(io.mosip.registartion.processor.abis.middleware.constants.FailureReason.getValueFromKey(abisCommonResponseDto.getFailureReason())); abisResponseDto.setLangCode("eng"); abisResponseDto.setCrBy(SYSTEM); 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..c27e3e375d6 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 @@ -63,13 +63,19 @@ public void validateBiometrics(String id, String process) 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(); - } - } + 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; 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/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 cadca1ffe62..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 @@ -143,8 +143,6 @@ public void senderHealthCheck(Handler eventHandler, String addre // TODO Auto-generated method stub } - - }; } diff --git a/registration-processor/core-processor/registration-processor-demo-dedupe-stage/src/test/java/io/mosip/registrationprocessor/stages/demodedupe/DemodedupeProcessorTest.java b/registration-processor/core-processor/registration-processor-demo-dedupe-stage/src/test/java/io/mosip/registrationprocessor/stages/demodedupe/DemodedupeProcessorTest.java index 69787f9dc25..9f0bc8ef386 100644 --- a/registration-processor/core-processor/registration-processor-demo-dedupe-stage/src/test/java/io/mosip/registrationprocessor/stages/demodedupe/DemodedupeProcessorTest.java +++ b/registration-processor/core-processor/registration-processor-demo-dedupe-stage/src/test/java/io/mosip/registrationprocessor/stages/demodedupe/DemodedupeProcessorTest.java @@ -1,902 +1,902 @@ -package io.mosip.registrationprocessor.stages.demodedupe; - -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.anyInt; -import static org.mockito.ArgumentMatchers.anySet; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.doNothing; -import static org.mockito.Mockito.when; - -import java.beans.IntrospectionException; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.lang.reflect.InvocationTargetException; -import java.text.ParseException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import org.apache.commons.io.IOUtils; -import org.json.simple.JSONArray; -import org.json.simple.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; -import org.springframework.core.env.Environment; -import org.springframework.test.util.ReflectionTestUtils; - -import com.fasterxml.jackson.databind.ObjectMapper; - -import io.mosip.kernel.core.fsadapter.exception.FSAdapterException; -import io.mosip.kernel.core.util.HMACUtils2; -import io.mosip.kernel.core.util.exception.JsonProcessingException; -import io.mosip.registration.processor.core.abstractverticle.MessageDTO; -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.RegistrationExceptionTypeCode; -import io.mosip.registration.processor.core.constant.AbisConstant; -import io.mosip.registration.processor.core.constant.MappingJsonConstants; -import io.mosip.registration.processor.core.constant.PacketFiles; -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.http.ResponseWrapper; -import io.mosip.registration.processor.core.logger.LogDescription; -import io.mosip.registration.processor.core.packet.dto.FieldValue; -import io.mosip.registration.processor.core.packet.dto.FieldValueArray; -import io.mosip.registration.processor.core.packet.dto.Identity; -import io.mosip.registration.processor.core.packet.dto.PacketMetaInfo; -import io.mosip.registration.processor.core.packet.dto.abis.AbisResponseDetDto; -import io.mosip.registration.processor.core.packet.dto.abis.AbisResponseDto; -import io.mosip.registration.processor.core.packet.dto.demographicinfo.DemographicInfoDto; -import io.mosip.registration.processor.core.packet.dto.demographicinfo.IndividualDemographicDedupe; -import io.mosip.registration.processor.core.packet.dto.demographicinfo.JsonValue; -import io.mosip.registration.processor.core.packet.dto.demographicinfo.identify.IdentityJsonValues; -import io.mosip.registration.processor.core.packet.dto.idjson.Document; -import io.mosip.registration.processor.core.spi.packetmanager.PacketInfoManager; -import io.mosip.registration.processor.core.util.JsonUtil; -import io.mosip.registration.processor.core.util.RegistrationExceptionMapperUtil; -import io.mosip.registration.processor.packet.storage.dto.ApplicantInfoDto; -import io.mosip.registration.processor.packet.storage.entity.IndividualDemographicDedupeEntity; -import io.mosip.registration.processor.packet.storage.entity.ManualVerificationEntity; -import io.mosip.registration.processor.packet.storage.repository.BasePacketRepository; -import io.mosip.registration.processor.packet.storage.utils.ABISHandlerUtil; -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.stages.demodedupe.DemoDedupe; -import io.mosip.registration.processor.stages.demodedupe.DemodedupeProcessor; -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.service.RegistrationStatusService; - -/** - * The Class DemodedupeStageTest. - */ -@RunWith(PowerMockRunner.class) -@PowerMockIgnore({ "javax.management.*", "javax.net.ssl.*","com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", }) -@PrepareForTest({ JsonUtil.class, IOUtils.class, HMACUtils2.class }) -public class DemodedupeProcessorTest { - - /** The registration status service. */ - @Mock - private RegistrationStatusService registrationStatusService; - - @Mock - private PacketInfoManager packetInfoManager; - - /** The manual verfication repository. */ - @Mock - private BasePacketRepository manualVerficationRepository; - - /** The demographic dedupe repository. */ - @Mock - private BasePacketRepository demographicDedupeRepository; - - /** The demo dedupe. */ - @Mock - private DemoDedupe demoDedupe; - - @Mock - private InputStream inputStream; - - private static final String source = "reg_client"; - - - - /** The dto. */ - private MessageDTO dto = new MessageDTO(); - - /** The duplicate dtos. */ - private List duplicateDtos = new ArrayList<>(); - - /** The audit log request builder. */ - @Mock - private AuditLogRequestBuilder auditLogRequestBuilder; - - @Mock - RegistrationExceptionMapperUtil registrationStatusMapperUtil; - - @InjectMocks - private DemodedupeProcessor demodedupeProcessor; - - @Mock - private ABISHandlerUtil abisHandlerUtil; - - @Mock - private RegistrationStatusDao registrationStatusDao; - - @Mock - private Utilities utility; - - private InternalRegistrationStatusDto registrationStatusDto; - - private Identity identity = new Identity(); - - private PacketMetaInfo packetMetaInfo; - - RegistrationStatusEntity entity = new RegistrationStatusEntity(); - - private String stageName = "DemoDedupeStage"; - - private IndividualDemographicDedupe individualDemoDedupe; - - @Mock - LogDescription description; - - @Mock - private Environment env; - - private static final String DEMODEDUPEENABLE = "mosip.registration.processor.demographic.deduplication.enable"; - - - - - /** - * Sets the up. - * - * @throws Exception - * the exception - */ - @Before - public void setUp() throws Exception { - when(utility.getDefaultSource(any(), any())).thenReturn(source); - ReflectionTestUtils.setField(demodedupeProcessor, "infantDedupe", "Y"); - ReflectionTestUtils.setField(demodedupeProcessor, "ageLimit", "4"); - dto.setRid("2018701130000410092018110735"); - - MockitoAnnotations.initMocks(this); - - DemographicInfoDto dto1 = new DemographicInfoDto(); - dto1.setRegId("2018701130000413092018110263"); - DemographicInfoDto dto2 = new DemographicInfoDto(); - dto2.setRegId("2018701130000418092018110863"); - - duplicateDtos.add(dto1); - duplicateDtos.add(dto2); - - registrationStatusDto = new InternalRegistrationStatusDto(); - registrationStatusDto.setRegistrationType("NEW"); - registrationStatusDto.setRegistrationId("2018701130000410092018110735"); - - packetMetaInfo = new PacketMetaInfo(); - - FieldValue registrationType = new FieldValue(); - registrationType.setLabel("registrationType"); - registrationType.setValue("New"); - - FieldValue applicantType = new FieldValue(); - applicantType.setLabel("applicantType"); - applicantType.setValue("Child"); - - FieldValue isVerified = new FieldValue(); - isVerified.setLabel("isVerified"); - isVerified.setValue("Verified"); - - FieldValue preRegistrationId = new FieldValue(); - preRegistrationId.setLabel("preRegistrationId"); - preRegistrationId.setValue("2018701130000410092018110736"); - - entity.setLatestRegistrationTransactionId("5d936385-7ee6-4b51-b21f-c20b0cfbcc11"); - - identity.setMetaData(Arrays.asList(registrationType, applicantType, isVerified, preRegistrationId)); - - Document documentPob = new Document(); - documentPob.setDocumentCategory("PROOFOFDATEOFBIRTH"); - documentPob.setDocumentName("ProofOfBirth"); - Document document = new Document(); - document.setDocumentCategory("PROOFOFRELATIONSHIP"); - document.setDocumentName("ProofOfRelation"); - List documents = new ArrayList(); - documents.add(documentPob); - documents.add(document); - individualDemoDedupe = new IndividualDemographicDedupe(); - - JsonValue[] jsonArray = new JsonValue[1]; - JsonValue[] jsonArray1 = new JsonValue[1]; - - JsonValue jsonValue1 = new JsonValue(); - JsonValue jsonValue2 = new JsonValue(); - - jsonValue1.setLanguage("eng"); - jsonValue1.setValue("name"); - jsonArray[0] = jsonValue1; - - jsonValue2.setLanguage("eng"); - jsonValue2.setValue("gender"); - jsonArray1[0] = jsonValue2; - List jsonArrayList = new ArrayList<>(); - jsonArrayList.add(jsonArray); - - individualDemoDedupe.setName(jsonArrayList); - individualDemoDedupe.setDateOfBirth("dateOfBirth"); - individualDemoDedupe.setPhone("phone"); - individualDemoDedupe.setEmail("email"); - individualDemoDedupe.setGender(jsonArray1); - List fieldValueArrayList = new ArrayList(); - - FieldValueArray applicantBiometric = new FieldValueArray(); - applicantBiometric.setLabel(PacketFiles.APPLICANTBIOMETRICSEQUENCE.name()); - List applicantBiometricValues = new ArrayList(); - applicantBiometricValues.add(PacketFiles.BOTHTHUMBS.name()); - applicantBiometric.setValue(applicantBiometricValues); - fieldValueArrayList.add(applicantBiometric); - FieldValueArray introducerBiometric = new FieldValueArray(); - introducerBiometric.setLabel(PacketFiles.INTRODUCERBIOMETRICSEQUENCE.name()); - List introducerBiometricValues = new ArrayList(); - introducerBiometricValues.add("introducerLeftThumb"); - introducerBiometric.setValue(introducerBiometricValues); - fieldValueArrayList.add(introducerBiometric); - FieldValueArray applicantDemographic = new FieldValueArray(); - applicantDemographic.setLabel(PacketFiles.APPLICANTDEMOGRAPHICSEQUENCE.name()); - List applicantDemographicValues = new ArrayList(); - applicantDemographicValues.add(PacketFiles.APPLICANTPHOTO.name()); - applicantDemographicValues.add("ProofOfBirth"); - applicantDemographicValues.add("ProofOfRelation"); - applicantDemographicValues.add("ProofOfAddress"); - applicantDemographicValues.add("ProofOfIdentity"); - applicantDemographic.setValue(applicantDemographicValues); - fieldValueArrayList.add(applicantDemographic); - identity.setHashSequence(fieldValueArrayList); - List sequence2 = new ArrayList<>(); - sequence2.add("audit"); - List fieldValueArrayListSequence = new ArrayList(); - FieldValueArray hashsequence2 = new FieldValueArray(); - hashsequence2.setValue(sequence2); - fieldValueArrayListSequence.add(hashsequence2); - identity.setHashSequence2(fieldValueArrayListSequence); - packetMetaInfo.setIdentity(identity); - - Mockito.when(registrationStatusMapperUtil.getStatusCode(any())).thenReturn("ERROR"); - - AuditResponseDto auditResponseDto = new AuditResponseDto(); - ResponseWrapper responseWrapper = new ResponseWrapper<>(); - responseWrapper.setResponse(auditResponseDto); - Mockito.doReturn(responseWrapper).when(auditLogRequestBuilder).createAuditRequestBuilder( - "test case description", EventId.RPR_405.toString(), EventName.UPDATE.toString(), - EventType.BUSINESS.toString(), "1234testcase", ApiName.AUDIT); - Mockito.doNothing().when(description).setMessage(any()); - InternalRegistrationStatusDto registrationStatusDto = new InternalRegistrationStatusDto(); - - registrationStatusDto.setRetryCount(null); - Mockito.when(registrationStatusService.getRegistrationStatus(any(),any(),any(), any())).thenReturn(registrationStatusDto); - Mockito.doNothing().when(registrationStatusService).updateRegistrationStatus(any(), any(), any()); - ClassLoader classLoader = getClass().getClassLoader(); - File file = new File(classLoader.getResource("RegistrationProcessorIdentity.json").getFile()); - inputStream = new FileInputStream(file); - String mappingJsonString = IOUtils.toString(inputStream,"UTF-8"); - JSONObject mappingJsonObj= new ObjectMapper().readValue(mappingJsonString, JSONObject.class); - - Mockito.when(utility.getRegistrationProcessorMappingJson(anyString())).thenReturn(JsonUtil.getJSONObject(mappingJsonObj, MappingJsonConstants.IDENTITY)); - - - } - - /** - * Test demo dedupe success. - * - * @throws Exception - */ - @Test - public void testDemoDedupeNewPacketSuccess() throws Exception { - when(env.getProperty(DEMODEDUPEENABLE)).thenReturn("true"); - byte[] b = "sds".getBytes(); - List emptyDuplicateDtoSet = new ArrayList<>(); - Mockito.when(utility.getApplicantAge(anyString(),anyString(), any())).thenReturn(20); - PowerMockito.mockStatic(JsonUtil.class); - PowerMockito.mockStatic(IOUtils.class); - PowerMockito.when(JsonUtil.class, "inputStreamtoJavaObject", inputStream, PacketMetaInfo.class) - .thenReturn(packetMetaInfo); - PowerMockito.when(IOUtils.class, "toByteArray", inputStream).thenReturn(b); - Mockito.when(registrationStatusService.getRegistrationStatus(any(),any(),any(), any())).thenReturn(registrationStatusDto); - Mockito.when(abisHandlerUtil.getPacketStatus(any())).thenReturn(AbisConstant.PRE_ABIS_IDENTIFICATION); - Mockito.when(demoDedupe.performDedupe(anyString())).thenReturn(emptyDuplicateDtoSet); - - MessageDTO messageDto = demodedupeProcessor.process(dto, stageName); - assertTrue(messageDto.getIsValid()); - assertFalse(messageDto.getInternalError()); - - } - - @SuppressWarnings("unchecked") - @Test - public void testDemoDedupeUpdatePacketSuccess() throws Exception { - InternalRegistrationStatusDto registrationStatus = new InternalRegistrationStatusDto(); - registrationStatus.setRegistrationId("2018701130000410092018110736"); - registrationStatus.setRegistrationType(RegistrationType.UPDATE.name()); - - IdentityJsonValues identityJsonValues = new IdentityJsonValues(); - identityJsonValues.setValue("fullName"); - when(utility.getDefaultSource(any(), any())).thenReturn(source); - Mockito.when(utility.getUIn(anyString(), anyString(), any())).thenReturn("2345"); - - JSONArray arr = new JSONArray(); - arr.add("name"); - - JSONObject obj = new JSONObject(); - obj.put("fullName", arr); - Mockito.when(utility.retrieveIdrepoJson(anyString())).thenReturn(obj); - - byte[] b = "sds".getBytes(); - List emptyDuplicateDtoSet = new ArrayList<>(); - - PowerMockito.mockStatic(JsonUtil.class); - PowerMockito.mockStatic(IOUtils.class); - PowerMockito.when(JsonUtil.class, "inputStreamtoJavaObject", inputStream, PacketMetaInfo.class) - .thenReturn(packetMetaInfo); - PowerMockito.when(IOUtils.class, "toByteArray", inputStream).thenReturn(b); - Mockito.when(registrationStatusService.getRegistrationStatus(any(),any(),any(), any())).thenReturn(registrationStatus); - Mockito.when(demoDedupe.performDedupe(anyString())).thenReturn(emptyDuplicateDtoSet); - Mockito.when(packetInfoManager.getIdentityKeysAndFetchValuesFromJSON(any(),any(),any())).thenReturn(individualDemoDedupe); - Mockito.when(abisHandlerUtil.getPacketStatus(any())).thenReturn(AbisConstant.POST_ABIS_IDENTIFICATION); - MessageDTO messageDto = demodedupeProcessor.process(dto, stageName); - assertTrue(messageDto.getIsValid()); - assertFalse(messageDto.getInternalError()); - } - - @Test - public void testDemoDedupeUpdatePacketException() throws Exception { - InternalRegistrationStatusDto registrationStatus = new InternalRegistrationStatusDto(); - registrationStatus.setRegistrationId("2018701130000410092018110736"); - registrationStatus.setRegistrationType(RegistrationType.UPDATE.name()); - - IdentityJsonValues identityJsonValues = new IdentityJsonValues(); - identityJsonValues.setValue("fullName"); - when(utility.getDefaultSource(any(),any())).thenReturn(source); - Mockito.when(utility.getUIn(anyString(), anyString(), any())).thenReturn("2345"); - - Mockito.when(utility.retrieveIdrepoJson(any())).thenReturn(null); - - byte[] b = "sds".getBytes(); - List emptyDuplicateDtoSet = new ArrayList<>(); - - PowerMockito.mockStatic(JsonUtil.class); - PowerMockito.mockStatic(IOUtils.class); - PowerMockito.when(JsonUtil.class, "inputStreamtoJavaObject", inputStream, PacketMetaInfo.class) - .thenReturn(packetMetaInfo); - PowerMockito.when(IOUtils.class, "toByteArray", inputStream).thenReturn(b); - Mockito.when(registrationStatusService.getRegistrationStatus(any(),any(),any(), any())).thenReturn(registrationStatus); - Mockito.when(demoDedupe.performDedupe(anyString())).thenReturn(emptyDuplicateDtoSet); - Mockito.when(packetInfoManager.getIdentityKeysAndFetchValuesFromJSON(any(),any(),any())).thenReturn(individualDemoDedupe); - MessageDTO messageDto = demodedupeProcessor.process(dto, stageName); - assertFalse(messageDto.getIsValid()); - assertTrue(messageDto.getInternalError()); - } - - @SuppressWarnings("unchecked") - @Test - public void testDemoDedupeResUpdatePacketSuccess() throws Exception { - InternalRegistrationStatusDto registrationStatus = new InternalRegistrationStatusDto(); - registrationStatus.setRegistrationId("2018701130000410092018110736"); - registrationStatus.setRegistrationType(RegistrationType.RES_UPDATE.name()); - - IdentityJsonValues identityJsonValues = new IdentityJsonValues(); - identityJsonValues.setValue("fullName"); - when(utility.getDefaultSource(any(),any())).thenReturn(source); - Mockito.when(utility.getUIn(anyString(), anyString(), any())).thenReturn("2345"); - - JSONArray arr = new JSONArray(); - arr.add("name"); - - JSONObject obj = new JSONObject(); - obj.put("fullName", arr); - Mockito.when(utility.retrieveIdrepoJson(anyString())).thenReturn(obj); - - byte[] b = "sds".getBytes(); - List emptyDuplicateDtoSet = new ArrayList<>(); - - PowerMockito.mockStatic(JsonUtil.class); - PowerMockito.mockStatic(IOUtils.class); - PowerMockito.when(JsonUtil.getJSONValue(any(), any())).thenReturn("Test1,Test2"); - PowerMockito.when(JsonUtil.getJSONObject(any(), any())).thenReturn(obj); - JsonValue[] nameArray = new JsonValue[1]; - JsonValue jsonValue = new JsonValue(); - jsonValue.setLanguage("eng"); - jsonValue.setValue("test"); - nameArray[0] = jsonValue; - PowerMockito.when(JsonUtil.getJsonValues(any(),any())).thenReturn(nameArray); - PowerMockito.when(JsonUtil.class, "inputStreamtoJavaObject", inputStream, PacketMetaInfo.class) - .thenReturn(packetMetaInfo); - PowerMockito.when(IOUtils.class, "toByteArray", inputStream).thenReturn(b); - Mockito.when(registrationStatusService.getRegistrationStatus(any(),any(),any(), any())).thenReturn(registrationStatus); - Mockito.when(demoDedupe.performDedupe(anyString())).thenReturn(emptyDuplicateDtoSet); - IndividualDemographicDedupe demographicData = individualDemoDedupe; - demographicData.setName(null); - demographicData.setDateOfBirth(null); - demographicData.setGender(null); - demographicData.setPhone(null); - demographicData.setEmail(null); - Mockito.when(packetInfoManager.getIdentityKeysAndFetchValuesFromJSON(any(),any(), any())).thenReturn(demographicData); - Mockito.when(abisHandlerUtil.getPacketStatus(any())).thenReturn(AbisConstant.POST_ABIS_IDENTIFICATION); - MessageDTO messageDto = demodedupeProcessor.process(dto, stageName); - assertTrue(messageDto.getIsValid()); - assertFalse(messageDto.getInternalError()); - } - - @Test - public void testDemoDedupeSuccessNotDuplicateAfterAuth() throws Exception { - - byte[] b = "sds".getBytes(); - Mockito.when(utility.getApplicantAge(anyString(),anyString(), any())).thenReturn(20); - PowerMockito.mockStatic(JsonUtil.class); - PowerMockito.mockStatic(IOUtils.class); - PowerMockito.when(JsonUtil.class, "inputStreamtoJavaObject", inputStream, PacketMetaInfo.class) - .thenReturn(packetMetaInfo); - PowerMockito.when(IOUtils.class, "toByteArray", inputStream).thenReturn(b); - Mockito.when(registrationStatusService.getRegistrationStatus(any(),any(),any(), any())).thenReturn(registrationStatusDto); - Mockito.when(abisHandlerUtil.getPacketStatus(any())).thenReturn(AbisConstant.PRE_ABIS_IDENTIFICATION); - Mockito.when(demoDedupe.performDedupe(anyString())).thenReturn(duplicateDtos); - registrationStatusDto.setRegistrationType(RegistrationType.NEW.toString()); - Mockito.when(registrationStatusDao.find(any(),any(),any(),any())).thenReturn(entity); - MessageDTO messageDto = demodedupeProcessor.process(dto, stageName); - assertTrue(messageDto.getIsValid()); - assertFalse(messageDto.getInternalError()); - - } - - /** - * Test demo dedupe potential match. - * - * @throws Exception - */ - @Test - public void testDemoDedupePotentialMatchSuccess() throws Exception { - List abisResponseDtos = new ArrayList<>(); - AbisResponseDto abisResponseDto = new AbisResponseDto(); - abisResponseDto.setId("100"); - abisResponseDto.setStatusCode(AbisStatusCode.SUCCESS.toString()); - abisResponseDto.setLangCode("eng"); - abisResponseDtos.add(abisResponseDto); - - byte[] b = "sds".getBytes(); - - PowerMockito.mockStatic(JsonUtil.class); - PowerMockito.mockStatic(IOUtils.class); - PowerMockito.when(JsonUtil.class, "inputStreamtoJavaObject", inputStream, PacketMetaInfo.class) - .thenReturn(packetMetaInfo); - PowerMockito.when(IOUtils.class, "toByteArray", inputStream).thenReturn(b); - Mockito.when(registrationStatusService.getRegistrationStatus(any(),any(),any(), any())).thenReturn(registrationStatusDto); - Mockito.when(abisHandlerUtil.getPacketStatus(any())).thenReturn(AbisConstant.POST_ABIS_IDENTIFICATION); - Mockito.when(demoDedupe.performDedupe(anyString())).thenReturn(duplicateDtos); - registrationStatusDto.setRegistrationType(RegistrationType.NEW.toString()); - Mockito.when(registrationStatusDao.find(any(),any(),any(),any())).thenReturn(entity); - Mockito.when(packetInfoManager.getAbisResponseRecords(anyString(), anyString())).thenReturn(abisResponseDtos); - Mockito.when(utility.getApplicantAge(anyString(),anyString(), any())).thenReturn(20); - MessageDTO messageDto = demodedupeProcessor.process(dto, stageName); - - assertTrue(messageDto.getIsValid()); - assertFalse(messageDto.getInternalError()); - - } - - @Test - public void testDemoDedupePotentialMatchWithEmpty() throws Exception { - List abisResponseDtos = new ArrayList<>(); - List abisResponseDetDtos = new ArrayList<>(); - Set matchedRegIds = new HashSet<>(); - AbisResponseDto abisResponseDto = new AbisResponseDto(); - abisResponseDto.setId("100"); - abisResponseDto.setStatusCode(AbisStatusCode.SUCCESS.toString()); - abisResponseDto.setLangCode("eng"); - abisResponseDtos.add(abisResponseDto); - - matchedRegIds.add("2018701130000410092018110735"); - byte[] b = "sds".getBytes(); - - PowerMockito.mockStatic(JsonUtil.class); - PowerMockito.mockStatic(IOUtils.class); - PowerMockito.when(JsonUtil.class, "inputStreamtoJavaObject", inputStream, PacketMetaInfo.class) - .thenReturn(packetMetaInfo); - PowerMockito.when(IOUtils.class, "toByteArray", inputStream).thenReturn(b); - Mockito.when(registrationStatusService.getRegistrationStatus(any(),any(),any(), any())).thenReturn(registrationStatusDto); - Mockito.when(abisHandlerUtil.getPacketStatus(any())).thenReturn(AbisConstant.POST_ABIS_IDENTIFICATION); - Mockito.when(demoDedupe.performDedupe(anyString())).thenReturn(duplicateDtos); - registrationStatusDto.setRegistrationType(RegistrationType.NEW.toString()); - Mockito.when(registrationStatusDao.find(any(),any(),any(),any())).thenReturn(entity); - Mockito.when(packetInfoManager.getAbisResponseRecords(anyString(), anyString())).thenReturn(abisResponseDtos); - Mockito.when(packetInfoManager.getAbisResponseDetRecordsList(any())).thenReturn(abisResponseDetDtos); - Mockito.when(abisHandlerUtil.getUniqueRegIds(anyString(), anyString(), anyInt(), any(), any())) - .thenReturn(matchedRegIds); - doNothing().when(packetInfoManager).saveManualAdjudicationData(anySet(), any(), any(), any(), any(),any(),any()); - Mockito.when(utility.getApplicantAge(anyString(),anyString(), any())).thenReturn(20); - MessageDTO messageDto = demodedupeProcessor.process(dto, stageName); - - assertTrue(messageDto.getIsValid()); - assertFalse(messageDto.getInternalError()); - } - - @Test - public void testDemoDedupeWithOnePotentialMatch() throws Exception { - List abisResponseDtos = new ArrayList<>(); - List abisResponseDetDtos = new ArrayList<>(); - Set matchedRegIds = new HashSet<>(); - AbisResponseDto abisResponseDto = new AbisResponseDto(); - abisResponseDto.setId("100"); - abisResponseDto.setStatusCode(AbisStatusCode.SUCCESS.toString()); - abisResponseDto.setLangCode("eng"); - abisResponseDtos.add(abisResponseDto); - - AbisResponseDetDto abisResponseDetDto = new AbisResponseDetDto(); - abisResponseDetDto.setAbiRespId("1004"); - abisResponseDetDtos.add(abisResponseDetDto); - - matchedRegIds.add("2018701130000410092018110735"); - byte[] b = "sds".getBytes(); - - PowerMockito.mockStatic(JsonUtil.class); - PowerMockito.mockStatic(IOUtils.class); - PowerMockito.when(JsonUtil.class, "inputStreamtoJavaObject", inputStream, PacketMetaInfo.class) - .thenReturn(packetMetaInfo); - PowerMockito.when(IOUtils.class, "toByteArray", inputStream).thenReturn(b); - Mockito.when(registrationStatusService.getRegistrationStatus(any(),any(),any(), any())).thenReturn(registrationStatusDto); - Mockito.when(abisHandlerUtil.getPacketStatus(any())).thenReturn(AbisConstant.POST_ABIS_IDENTIFICATION); - Mockito.when(demoDedupe.performDedupe(anyString())).thenReturn(duplicateDtos); - registrationStatusDto.setRegistrationType(RegistrationType.NEW.toString()); - Mockito.when(registrationStatusDao.find(any(),any(),any(),any())).thenReturn(entity); - Mockito.when(packetInfoManager.getAbisResponseRecords(anyString(), anyString())).thenReturn(abisResponseDtos); - Mockito.when(packetInfoManager.getAbisResponseDetRecordsList(any())).thenReturn(abisResponseDetDtos); - Mockito.when(abisHandlerUtil.getUniqueRegIds(anyString(), anyString(), anyInt(), any(), any())) - .thenReturn(matchedRegIds); - doNothing().when(packetInfoManager).saveManualAdjudicationData(anySet(), any(), any(), any(), any(),any(),any()); - Mockito.when(utility.getApplicantAge(anyString(),anyString(), any())).thenReturn(20); - MessageDTO messageDto = demodedupeProcessor.process(dto, stageName); - - assertFalse(messageDto.getIsValid()); - assertFalse(messageDto.getInternalError()); - } - - @Test - public void testDemoDedupeEmptyMatch() throws Exception { - List abisResponseDtos = new ArrayList<>(); - List abisResponseDetDtos = new ArrayList<>(); - Set matchedRegIds = new HashSet<>(); - AbisResponseDto abisResponseDto = new AbisResponseDto(); - abisResponseDto.setId("100"); - abisResponseDto.setStatusCode(AbisStatusCode.SUCCESS.toString()); - abisResponseDto.setLangCode("eng"); - abisResponseDtos.add(abisResponseDto); - - byte[] b = "sds".getBytes(); - - PowerMockito.mockStatic(JsonUtil.class); - PowerMockito.mockStatic(IOUtils.class); - PowerMockito.when(JsonUtil.class, "inputStreamtoJavaObject", inputStream, PacketMetaInfo.class) - .thenReturn(packetMetaInfo); - PowerMockito.when(IOUtils.class, "toByteArray", inputStream).thenReturn(b); - Mockito.when(registrationStatusService.getRegistrationStatus(any(),any(),any(), any())).thenReturn(registrationStatusDto); - Mockito.when(abisHandlerUtil.getPacketStatus(any())).thenReturn(AbisConstant.POST_ABIS_IDENTIFICATION); - Mockito.when(demoDedupe.performDedupe(anyString())).thenReturn(duplicateDtos); - registrationStatusDto.setRegistrationType(RegistrationType.NEW.toString()); - Mockito.when(registrationStatusDao.find(any(),any(),any(),any())).thenReturn(entity); - Mockito.when(packetInfoManager.getAbisResponseRecords(anyString(), anyString())).thenReturn(abisResponseDtos); - Mockito.when(packetInfoManager.getAbisResponseDetRecordsList(any())).thenReturn(abisResponseDetDtos); - Mockito.when(abisHandlerUtil.getUniqueRegIds(anyString(), anyString(), anyInt(), any(), any())) - .thenReturn(matchedRegIds); - doNothing().when(packetInfoManager).saveManualAdjudicationData(anySet(), any(), any(), any(), any(),any(),any()); - Mockito.when(utility.getApplicantAge(anyString(),anyString(), any())).thenReturn(20); - MessageDTO messageDto = demodedupeProcessor.process(dto, stageName); - - assertTrue(messageDto.getIsValid()); - assertFalse(messageDto.getInternalError()); - } - - @Test - public void testDemoDedupePotentialMatchAbisResponseNotProcessed() throws Exception { - List abisResponseDtos = new ArrayList<>(); - AbisResponseDto abisResponseDto = new AbisResponseDto(); - abisResponseDto.setId("100"); - abisResponseDto.setStatusCode("ERROR"); - abisResponseDto.setLangCode("eng"); - abisResponseDtos.add(abisResponseDto); - - byte[] b = "sds".getBytes(); - - PowerMockito.mockStatic(JsonUtil.class); - PowerMockito.mockStatic(IOUtils.class); - PowerMockito.when(JsonUtil.class, "inputStreamtoJavaObject", inputStream, PacketMetaInfo.class) - .thenReturn(packetMetaInfo); - PowerMockito.when(IOUtils.class, "toByteArray", inputStream).thenReturn(b); - Mockito.when(registrationStatusService.getRegistrationStatus(any(),any(),any(), any())).thenReturn(registrationStatusDto); - Mockito.when(abisHandlerUtil.getPacketStatus(any())).thenReturn(AbisConstant.POST_ABIS_IDENTIFICATION); - Mockito.when(demoDedupe.performDedupe(anyString())).thenReturn(duplicateDtos); - registrationStatusDto.setRegistrationType(RegistrationType.NEW.toString()); - Mockito.when(registrationStatusDao.find(any(),any(),any(),any())).thenReturn(entity); - Mockito.when(packetInfoManager.getAbisResponseRecords(anyString(), anyString())).thenReturn(abisResponseDtos); - Mockito.when(utility.getApplicantAge(anyString(),anyString(), any())).thenReturn(20); - MessageDTO messageDto = demodedupeProcessor.process(dto, stageName); - - assertTrue(messageDto.getIsValid()); - assertFalse(messageDto.getInternalError()); - } - - /** - * Test demo dedupe failure. - * - * @throws ApisResourceAccessException the apis resource access - * exception - * @throws IOException Signals that an I/O exception - * has occurred. - * @throws IntrospectionException - * @throws ParseException - * @throws InvocationTargetException - * @throws IllegalArgumentException - * @throws IllegalAccessException - * @throws io.mosip.kernel.core.exception.IOException - * @throws RegistrationProcessorCheckedException - */ - @Test - public void testDemoDedupeFailure() throws ApisResourceAccessException, IOException, JsonProcessingException, PacketManagerException, PacketManagerException { - InternalRegistrationStatusDto registrationStatusDto = new InternalRegistrationStatusDto(); - - Mockito.when(demoDedupe.performDedupe(anyString())).thenReturn(duplicateDtos); - Mockito.when(abisHandlerUtil.getPacketStatus(any())).thenReturn(RegistrationType.NEW.toString()); - Mockito.when(registrationStatusService.getRegistrationStatus(any(),any(),any(), any())).thenReturn(registrationStatusDto); - registrationStatusDto.setRetryCount(3); - Mockito.when(utility.getApplicantAge(anyString(),anyString(), any())).thenReturn(20); - demodedupeProcessor.process(dto, stageName); - - } - - /** - * Test resource exception. - * - * @throws ApisResourceAccessException the apis resource access - * exception - * @throws IOException Signals that an I/O exception - * has occurred. - * @throws IntrospectionException - * @throws ParseException - * @throws InvocationTargetException - * @throws IllegalArgumentException - * @throws IllegalAccessException - * @throws io.mosip.kernel.core.exception.IOException - * @throws RegistrationProcessorCheckedException - */ - @Test - public void testResourceException() throws ApisResourceAccessException, IOException, JsonProcessingException, PacketManagerException { - when(env.getProperty(DEMODEDUPEENABLE)).thenReturn("true"); - - List emptyDuplicateDtoSet = new ArrayList<>(); - when(utility.getDefaultSource(any(),any())).thenReturn(source); - Mockito.when(utility.getApplicantAge(anyString(),anyString(), any())).thenReturn(20); - - Mockito.when(registrationStatusService.getRegistrationStatus(any(),any(),any(), any())).thenReturn(registrationStatusDto); - Mockito.when(abisHandlerUtil.getPacketStatus(any())).thenReturn(AbisConstant.PRE_ABIS_IDENTIFICATION); - Mockito.when(registrationStatusMapperUtil - .getStatusCode(RegistrationExceptionTypeCode.APIS_RESOURCE_ACCESS_EXCEPTION)).thenReturn("REPROCESS"); - Mockito.when(demoDedupe.performDedupe(anyString())).thenReturn(emptyDuplicateDtoSet); - when(utility.getDefaultSource(any(), any())).thenReturn(source); - ApisResourceAccessException exp = new ApisResourceAccessException("errorMessage"); - Mockito.doThrow(exp).when(utility).getApplicantAge(anyString(),anyString(), any()); - - - MessageDTO messageDto = demodedupeProcessor.process(dto, stageName); - assertEquals(true, messageDto.getInternalError()); - assertTrue(messageDto.getIsValid()); - } - - @Test - public void testFSAdapterExceptionException() - throws ApisResourceAccessException, IOException, JsonProcessingException, PacketManagerException { - Mockito.when(demoDedupe.performDedupe(anyString())).thenReturn(duplicateDtos); - - FSAdapterException exp = new FSAdapterException("errorMessage", "test"); - Mockito.doThrow(exp).when(abisHandlerUtil).getPacketStatus(any()); - registrationStatusDto.setRegistrationType(RegistrationType.NEW.toString()); - Mockito.when(registrationStatusService.getRegistrationStatus(any(),any(),any(), any())).thenReturn(registrationStatusDto); - Mockito.when(registrationStatusMapperUtil - .getStatusCode(RegistrationExceptionTypeCode.OBJECT_STORE_EXCEPTION)).thenReturn("REPROCESS"); - Mockito.when(utility.getApplicantAge(anyString(),anyString(), any())).thenReturn(20); - MessageDTO messageDto = demodedupeProcessor.process(dto, stageName); - assertEquals(true, messageDto.getInternalError()); - assertTrue(messageDto.getIsValid()); - } - - @Test - public void testIllegalArgumentException() throws ApisResourceAccessException, IOException, JsonProcessingException, PacketManagerException { - Mockito.when(demoDedupe.performDedupe(anyString())).thenReturn(duplicateDtos); - IllegalArgumentException exp = new IllegalArgumentException("errorMessage"); - Mockito.doThrow(exp).when(abisHandlerUtil).getPacketStatus(any()); - registrationStatusDto.setRegistrationType(RegistrationType.NEW.toString()); - Mockito.when(registrationStatusService.getRegistrationStatus(any(),any(),any(), any())).thenReturn(registrationStatusDto); - Mockito.when(registrationStatusMapperUtil - .getStatusCode(RegistrationExceptionTypeCode.ILLEGAL_ARGUMENT_EXCEPTION)).thenReturn("ERROR"); - Mockito.when(utility.getApplicantAge(anyString(),anyString(), any())).thenReturn(20); - MessageDTO messageDto = demodedupeProcessor.process(dto, stageName); - assertEquals(true, messageDto.getInternalError()); - assertFalse(messageDto.getIsValid()); - } - - /** - * Test demo dedupe success. - * - * @throws Exception - */ - @Test - public void testDemoDedupeNewPacketSkipped() throws Exception { - when(env.getProperty(DEMODEDUPEENABLE)).thenReturn("false"); - byte[] b = "sds".getBytes(); - - - PowerMockito.mockStatic(JsonUtil.class); - PowerMockito.mockStatic(IOUtils.class); - PowerMockito.when(JsonUtil.class, "inputStreamtoJavaObject", inputStream, PacketMetaInfo.class) - .thenReturn(packetMetaInfo); - PowerMockito.when(IOUtils.class, "toByteArray", inputStream).thenReturn(b); - Mockito.when(registrationStatusService.getRegistrationStatus(any(),any(),any(), any())).thenReturn(registrationStatusDto); - Mockito.when(abisHandlerUtil.getPacketStatus(any())).thenReturn(AbisConstant.PRE_ABIS_IDENTIFICATION); - Mockito.when(utility.getApplicantAge(anyString(),anyString(), any())).thenReturn(20); - MessageDTO messageDto = demodedupeProcessor.process(dto, stageName); - assertTrue(messageDto.getIsValid()); - assertFalse(messageDto.getInternalError()); - - } - /** - * Test demo dedupe success. - * - * @throws Exception - */ - @Test - public void testDemoDedupeNewPacketSuccessWithDuplicates() throws Exception { - when(env.getProperty(DEMODEDUPEENABLE)).thenReturn("true"); - byte[] b = "sds".getBytes(); - - - PowerMockito.mockStatic(JsonUtil.class); - PowerMockito.mockStatic(IOUtils.class); - PowerMockito.when(JsonUtil.class, "inputStreamtoJavaObject", inputStream, PacketMetaInfo.class) - .thenReturn(packetMetaInfo); - PowerMockito.when(IOUtils.class, "toByteArray", inputStream).thenReturn(b); - Mockito.when(registrationStatusService.getRegistrationStatus(any(),any(),any(), any())).thenReturn(registrationStatusDto); - Mockito.when(abisHandlerUtil.getPacketStatus(any())).thenReturn(AbisConstant.PRE_ABIS_IDENTIFICATION); - Mockito.when(demoDedupe.performDedupe(anyString())).thenReturn(duplicateDtos); - Mockito.when(utility.getApplicantAge(anyString(),anyString(), any())).thenReturn(20); - MessageDTO messageDto = demodedupeProcessor.process(dto, stageName); - assertTrue(messageDto.getIsValid()); - assertFalse(messageDto.getInternalError()); - } - /** - * Test demo dedupe success. - * - * @throws Exception - */ - @Test - public void testDemoDedupeNewPacketSuccessWithDuplicatesWithException() throws Exception { - when(env.getProperty(DEMODEDUPEENABLE)).thenReturn("true"); - byte[] b = "sds".getBytes(); - - - PowerMockito.mockStatic(JsonUtil.class); - PowerMockito.mockStatic(IOUtils.class); - PowerMockito.when(JsonUtil.class, "inputStreamtoJavaObject", inputStream, PacketMetaInfo.class) - .thenReturn(packetMetaInfo); - PowerMockito.when(IOUtils.class, "toByteArray", inputStream).thenReturn(b); - Mockito.when(registrationStatusService.getRegistrationStatus(any(),any(),any(), any())).thenReturn(registrationStatusDto); - Mockito.when(abisHandlerUtil.getPacketStatus(any())).thenReturn(AbisConstant.PRE_ABIS_IDENTIFICATION); - Mockito.when(demoDedupe.performDedupe(anyString())).thenReturn(duplicateDtos); - NullPointerException exp=new NullPointerException(); - Mockito.doThrow(exp).when(packetInfoManager).saveDemoDedupePotentialData(any(),anyString(),anyString()); - Mockito.when(utility.getApplicantAge(anyString(),anyString(), any())).thenReturn(20); - MessageDTO messageDto = demodedupeProcessor.process(dto, stageName); - assertTrue(messageDto.getIsValid()); - assertTrue(messageDto.getInternalError()); - - } - - @Test - public void testDemoDedupeNewChildPacketSuccess() throws Exception { - when(env.getProperty(DEMODEDUPEENABLE)).thenReturn("true"); - byte[] b = "sds".getBytes(); - List emptyDuplicateDtoSet = new ArrayList<>(); - Mockito.when(utility.getApplicantAge(anyString(),anyString(), any())).thenReturn(2); - PowerMockito.mockStatic(JsonUtil.class); - PowerMockito.mockStatic(IOUtils.class); - PowerMockito.when(JsonUtil.class, "inputStreamtoJavaObject", inputStream, PacketMetaInfo.class) - .thenReturn(packetMetaInfo); - PowerMockito.when(IOUtils.class, "toByteArray", inputStream).thenReturn(b); - Mockito.when(registrationStatusService.getRegistrationStatus(any(),any(),any(), any())).thenReturn(registrationStatusDto); - Mockito.when(abisHandlerUtil.getPacketStatus(any())).thenReturn(AbisConstant.PRE_ABIS_IDENTIFICATION); - Mockito.when(demoDedupe.performDedupe(anyString())).thenReturn(emptyDuplicateDtoSet); - - MessageDTO messageDto = demodedupeProcessor.process(dto, stageName); - assertTrue(messageDto.getIsValid()); - assertFalse(messageDto.getInternalError()); - - } - - @Test - public void testDemoDedupeDisabledSuccess() throws Exception { - when(env.getProperty(DEMODEDUPEENABLE)).thenReturn("false"); - byte[] b = "sds".getBytes(); - List emptyDuplicateDtoSet = new ArrayList<>(); - Mockito.when(utility.getApplicantAge(any(),any(), any())).thenReturn(20); - PowerMockito.mockStatic(JsonUtil.class); - PowerMockito.mockStatic(IOUtils.class); - PowerMockito.when(JsonUtil.class, "inputStreamtoJavaObject", inputStream, PacketMetaInfo.class) - .thenReturn(packetMetaInfo); - PowerMockito.when(IOUtils.class, "toByteArray", inputStream).thenReturn(b); - Mockito.when(registrationStatusService.getRegistrationStatus(any(),any(),any(), any())).thenReturn(registrationStatusDto); - Mockito.when(abisHandlerUtil.getPacketStatus(any())).thenReturn(AbisConstant.PRE_ABIS_IDENTIFICATION); - Mockito.when(demoDedupe.performDedupe(anyString())).thenReturn(emptyDuplicateDtoSet); - - MessageDTO messageDto = demodedupeProcessor.process(dto, stageName); - assertTrue(messageDto.getIsValid()); - assertFalse(messageDto.getInternalError()); - - } - - @Test - public void testDemoDedupeSuccess() throws Exception { - when(env.getProperty(DEMODEDUPEENABLE)).thenReturn("true"); - byte[] b = "sds".getBytes(); - List emptyDuplicateDtoSet = new ArrayList<>(); - Mockito.when(utility.getApplicantAge(any(), any(), any())).thenReturn(20); - PowerMockito.mockStatic(JsonUtil.class); - PowerMockito.mockStatic(IOUtils.class); - PowerMockito.when(JsonUtil.class, "inputStreamtoJavaObject", inputStream, PacketMetaInfo.class) - .thenReturn(packetMetaInfo); - PowerMockito.when(IOUtils.class, "toByteArray", inputStream).thenReturn(b); - Mockito.when(registrationStatusService.getRegistrationStatus(any(),any(),any(), any())).thenReturn(registrationStatusDto); - Mockito.when(abisHandlerUtil.getPacketStatus(any())).thenReturn(AbisConstant.PRE_ABIS_IDENTIFICATION); - Mockito.when(demoDedupe.performDedupe(anyString())).thenReturn(emptyDuplicateDtoSet); - - MessageDTO messageDto = demodedupeProcessor.process(dto, stageName); - assertTrue(messageDto.getIsValid()); - assertFalse(messageDto.getInternalError()); - - } - - @Test - public void testDemoDedupeNewDuplicatePacketSuccess() throws Exception { - when(env.getProperty(DEMODEDUPEENABLE)).thenReturn("true"); - - Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())) - .thenReturn(registrationStatusDto); - Mockito.when(abisHandlerUtil.getPacketStatus(any())).thenReturn(AbisConstant.DUPLICATE_FOR_SAME_TRANSACTION_ID); - - MessageDTO messageDto = demodedupeProcessor.process(dto, stageName); - assertTrue(messageDto.getInternalError()); - - } +package io.mosip.registrationprocessor.stages.demodedupe; + +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.anyInt; +import static org.mockito.ArgumentMatchers.anySet; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.when; + +import java.beans.IntrospectionException; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.lang.reflect.InvocationTargetException; +import java.text.ParseException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import org.apache.commons.io.IOUtils; +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.springframework.core.env.Environment; +import org.springframework.test.util.ReflectionTestUtils; + +import com.fasterxml.jackson.databind.ObjectMapper; + +import io.mosip.kernel.core.fsadapter.exception.FSAdapterException; +import io.mosip.kernel.core.util.HMACUtils2; +import io.mosip.kernel.core.util.exception.JsonProcessingException; +import io.mosip.registration.processor.core.abstractverticle.MessageDTO; +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.RegistrationExceptionTypeCode; +import io.mosip.registration.processor.core.constant.AbisConstant; +import io.mosip.registration.processor.core.constant.MappingJsonConstants; +import io.mosip.registration.processor.core.constant.PacketFiles; +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.http.ResponseWrapper; +import io.mosip.registration.processor.core.logger.LogDescription; +import io.mosip.registration.processor.core.packet.dto.FieldValue; +import io.mosip.registration.processor.core.packet.dto.FieldValueArray; +import io.mosip.registration.processor.core.packet.dto.Identity; +import io.mosip.registration.processor.core.packet.dto.PacketMetaInfo; +import io.mosip.registration.processor.core.packet.dto.abis.AbisResponseDetDto; +import io.mosip.registration.processor.core.packet.dto.abis.AbisResponseDto; +import io.mosip.registration.processor.core.packet.dto.demographicinfo.DemographicInfoDto; +import io.mosip.registration.processor.core.packet.dto.demographicinfo.IndividualDemographicDedupe; +import io.mosip.registration.processor.core.packet.dto.demographicinfo.JsonValue; +import io.mosip.registration.processor.core.packet.dto.demographicinfo.identify.IdentityJsonValues; +import io.mosip.registration.processor.core.packet.dto.idjson.Document; +import io.mosip.registration.processor.core.spi.packetmanager.PacketInfoManager; +import io.mosip.registration.processor.core.util.JsonUtil; +import io.mosip.registration.processor.core.util.RegistrationExceptionMapperUtil; +import io.mosip.registration.processor.packet.storage.dto.ApplicantInfoDto; +import io.mosip.registration.processor.packet.storage.entity.IndividualDemographicDedupeEntity; +import io.mosip.registration.processor.packet.storage.entity.ManualVerificationEntity; +import io.mosip.registration.processor.packet.storage.repository.BasePacketRepository; +import io.mosip.registration.processor.packet.storage.utils.ABISHandlerUtil; +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.stages.demodedupe.DemoDedupe; +import io.mosip.registration.processor.stages.demodedupe.DemodedupeProcessor; +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.service.RegistrationStatusService; + +/** + * The Class DemodedupeStageTest. + */ +@RunWith(PowerMockRunner.class) +@PowerMockIgnore({ "javax.management.*", "javax.net.ssl.*","com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", }) +@PrepareForTest({ JsonUtil.class, IOUtils.class, HMACUtils2.class }) +public class DemodedupeProcessorTest { + + /** The registration status service. */ + @Mock + private RegistrationStatusService registrationStatusService; + + @Mock + private PacketInfoManager packetInfoManager; + + /** The manual verfication repository. */ + @Mock + private BasePacketRepository manualVerficationRepository; + + /** The demographic dedupe repository. */ + @Mock + private BasePacketRepository demographicDedupeRepository; + + /** The demo dedupe. */ + @Mock + private DemoDedupe demoDedupe; + + @Mock + private InputStream inputStream; + + private static final String source = "reg_client"; + + + + /** The dto. */ + private MessageDTO dto = new MessageDTO(); + + /** The duplicate dtos. */ + private List duplicateDtos = new ArrayList<>(); + + /** The audit log request builder. */ + @Mock + private AuditLogRequestBuilder auditLogRequestBuilder; + + @Mock + RegistrationExceptionMapperUtil registrationStatusMapperUtil; + + @InjectMocks + private DemodedupeProcessor demodedupeProcessor; + + @Mock + private ABISHandlerUtil abisHandlerUtil; + + @Mock + private RegistrationStatusDao registrationStatusDao; + + @Mock + private Utilities utility; + + private InternalRegistrationStatusDto registrationStatusDto; + + private Identity identity = new Identity(); + + private PacketMetaInfo packetMetaInfo; + + RegistrationStatusEntity entity = new RegistrationStatusEntity(); + + private String stageName = "DemoDedupeStage"; + + private IndividualDemographicDedupe individualDemoDedupe; + + @Mock + LogDescription description; + + @Mock + private Environment env; + + private static final String DEMODEDUPEENABLE = "mosip.registration.processor.demographic.deduplication.enable"; + + + + + /** + * Sets the up. + * + * @throws Exception + * the exception + */ + @Before + public void setUp() throws Exception { + when(utility.getDefaultSource(any(), any())).thenReturn(source); + ReflectionTestUtils.setField(demodedupeProcessor, "infantDedupe", "Y"); + ReflectionTestUtils.setField(demodedupeProcessor, "ageLimit", "4"); + dto.setRid("2018701130000410092018110735"); + + MockitoAnnotations.initMocks(this); + + DemographicInfoDto dto1 = new DemographicInfoDto(); + dto1.setRegId("2018701130000413092018110263"); + DemographicInfoDto dto2 = new DemographicInfoDto(); + dto2.setRegId("2018701130000418092018110863"); + + duplicateDtos.add(dto1); + duplicateDtos.add(dto2); + + registrationStatusDto = new InternalRegistrationStatusDto(); + registrationStatusDto.setRegistrationType("NEW"); + registrationStatusDto.setRegistrationId("2018701130000410092018110735"); + + packetMetaInfo = new PacketMetaInfo(); + + FieldValue registrationType = new FieldValue(); + registrationType.setLabel("registrationType"); + registrationType.setValue("New"); + + FieldValue applicantType = new FieldValue(); + applicantType.setLabel("applicantType"); + applicantType.setValue("Child"); + + FieldValue isVerified = new FieldValue(); + isVerified.setLabel("isVerified"); + isVerified.setValue("Verified"); + + FieldValue preRegistrationId = new FieldValue(); + preRegistrationId.setLabel("preRegistrationId"); + preRegistrationId.setValue("2018701130000410092018110736"); + + entity.setLatestRegistrationTransactionId("5d936385-7ee6-4b51-b21f-c20b0cfbcc11"); + + identity.setMetaData(Arrays.asList(registrationType, applicantType, isVerified, preRegistrationId)); + + Document documentPob = new Document(); + documentPob.setDocumentCategory("PROOFOFDATEOFBIRTH"); + documentPob.setDocumentName("ProofOfBirth"); + Document document = new Document(); + document.setDocumentCategory("PROOFOFRELATIONSHIP"); + document.setDocumentName("ProofOfRelation"); + List documents = new ArrayList(); + documents.add(documentPob); + documents.add(document); + individualDemoDedupe = new IndividualDemographicDedupe(); + + JsonValue[] jsonArray = new JsonValue[1]; + JsonValue[] jsonArray1 = new JsonValue[1]; + + JsonValue jsonValue1 = new JsonValue(); + JsonValue jsonValue2 = new JsonValue(); + + jsonValue1.setLanguage("eng"); + jsonValue1.setValue("name"); + jsonArray[0] = jsonValue1; + + jsonValue2.setLanguage("eng"); + jsonValue2.setValue("gender"); + jsonArray1[0] = jsonValue2; + List jsonArrayList = new ArrayList<>(); + jsonArrayList.add(jsonArray); + + individualDemoDedupe.setName(jsonArrayList); + individualDemoDedupe.setDateOfBirth("dateOfBirth"); + individualDemoDedupe.setPhone("phone"); + individualDemoDedupe.setEmail("email"); + individualDemoDedupe.setGender(jsonArray1); + List fieldValueArrayList = new ArrayList(); + + FieldValueArray applicantBiometric = new FieldValueArray(); + applicantBiometric.setLabel(PacketFiles.APPLICANTBIOMETRICSEQUENCE.name()); + List applicantBiometricValues = new ArrayList(); + applicantBiometricValues.add(PacketFiles.BOTHTHUMBS.name()); + applicantBiometric.setValue(applicantBiometricValues); + fieldValueArrayList.add(applicantBiometric); + FieldValueArray introducerBiometric = new FieldValueArray(); + introducerBiometric.setLabel(PacketFiles.INTRODUCERBIOMETRICSEQUENCE.name()); + List introducerBiometricValues = new ArrayList(); + introducerBiometricValues.add("introducerLeftThumb"); + introducerBiometric.setValue(introducerBiometricValues); + fieldValueArrayList.add(introducerBiometric); + FieldValueArray applicantDemographic = new FieldValueArray(); + applicantDemographic.setLabel(PacketFiles.APPLICANTDEMOGRAPHICSEQUENCE.name()); + List applicantDemographicValues = new ArrayList(); + applicantDemographicValues.add(PacketFiles.APPLICANTPHOTO.name()); + applicantDemographicValues.add("ProofOfBirth"); + applicantDemographicValues.add("ProofOfRelation"); + applicantDemographicValues.add("ProofOfAddress"); + applicantDemographicValues.add("ProofOfIdentity"); + applicantDemographic.setValue(applicantDemographicValues); + fieldValueArrayList.add(applicantDemographic); + identity.setHashSequence(fieldValueArrayList); + List sequence2 = new ArrayList<>(); + sequence2.add("audit"); + List fieldValueArrayListSequence = new ArrayList(); + FieldValueArray hashsequence2 = new FieldValueArray(); + hashsequence2.setValue(sequence2); + fieldValueArrayListSequence.add(hashsequence2); + identity.setHashSequence2(fieldValueArrayListSequence); + packetMetaInfo.setIdentity(identity); + + Mockito.when(registrationStatusMapperUtil.getStatusCode(any())).thenReturn("ERROR"); + + AuditResponseDto auditResponseDto = new AuditResponseDto(); + ResponseWrapper responseWrapper = new ResponseWrapper<>(); + responseWrapper.setResponse(auditResponseDto); + Mockito.doReturn(responseWrapper).when(auditLogRequestBuilder).createAuditRequestBuilder( + "test case description", EventId.RPR_405.toString(), EventName.UPDATE.toString(), + EventType.BUSINESS.toString(), "1234testcase", ApiName.AUDIT); + Mockito.doNothing().when(description).setMessage(any()); + InternalRegistrationStatusDto registrationStatusDto = new InternalRegistrationStatusDto(); + + registrationStatusDto.setRetryCount(null); + Mockito.when(registrationStatusService.getRegistrationStatus(any(),any(),any(), any())).thenReturn(registrationStatusDto); + Mockito.doNothing().when(registrationStatusService).updateRegistrationStatus(any(), any(), any()); + ClassLoader classLoader = getClass().getClassLoader(); + File file = new File(classLoader.getResource("RegistrationProcessorIdentity.json").getFile()); + inputStream = new FileInputStream(file); + String mappingJsonString = IOUtils.toString(inputStream,"UTF-8"); + JSONObject mappingJsonObj= new ObjectMapper().readValue(mappingJsonString, JSONObject.class); + + Mockito.when(utility.getRegistrationProcessorMappingJson(anyString())).thenReturn(JsonUtil.getJSONObject(mappingJsonObj, MappingJsonConstants.IDENTITY)); + + + } + + /** + * Test demo dedupe success. + * + * @throws Exception + */ + @Test + public void testDemoDedupeNewPacketSuccess() throws Exception { + when(env.getProperty(DEMODEDUPEENABLE)).thenReturn("true"); + byte[] b = "sds".getBytes(); + List emptyDuplicateDtoSet = new ArrayList<>(); + Mockito.when(utility.getApplicantAge(anyString(),anyString(), any())).thenReturn(20); + PowerMockito.mockStatic(JsonUtil.class); + PowerMockito.mockStatic(IOUtils.class); + PowerMockito.when(JsonUtil.class, "inputStreamtoJavaObject", inputStream, PacketMetaInfo.class) + .thenReturn(packetMetaInfo); + PowerMockito.when(IOUtils.class, "toByteArray", inputStream).thenReturn(b); + Mockito.when(registrationStatusService.getRegistrationStatus(any(),any(),any(), any())).thenReturn(registrationStatusDto); + Mockito.when(abisHandlerUtil.getPacketStatus(any())).thenReturn(AbisConstant.PRE_ABIS_IDENTIFICATION); + Mockito.when(demoDedupe.performDedupe(anyString())).thenReturn(emptyDuplicateDtoSet); + + MessageDTO messageDto = demodedupeProcessor.process(dto, stageName); + assertTrue(messageDto.getIsValid()); + assertFalse(messageDto.getInternalError()); + + } + + @SuppressWarnings("unchecked") + @Test + public void testDemoDedupeUpdatePacketSuccess() throws Exception { + InternalRegistrationStatusDto registrationStatus = new InternalRegistrationStatusDto(); + registrationStatus.setRegistrationId("2018701130000410092018110736"); + registrationStatus.setRegistrationType(RegistrationType.UPDATE.name()); + + IdentityJsonValues identityJsonValues = new IdentityJsonValues(); + identityJsonValues.setValue("fullName"); + when(utility.getDefaultSource(any(), any())).thenReturn(source); + Mockito.when(utility.getUIn(anyString(), anyString(), any())).thenReturn("2345"); + + JSONArray arr = new JSONArray(); + arr.add("name"); + + JSONObject obj = new JSONObject(); + obj.put("fullName", arr); + Mockito.when(utility.retrieveIdrepoJson(anyString())).thenReturn(obj); + + byte[] b = "sds".getBytes(); + List emptyDuplicateDtoSet = new ArrayList<>(); + + PowerMockito.mockStatic(JsonUtil.class); + PowerMockito.mockStatic(IOUtils.class); + PowerMockito.when(JsonUtil.class, "inputStreamtoJavaObject", inputStream, PacketMetaInfo.class) + .thenReturn(packetMetaInfo); + PowerMockito.when(IOUtils.class, "toByteArray", inputStream).thenReturn(b); + Mockito.when(registrationStatusService.getRegistrationStatus(any(),any(),any(), any())).thenReturn(registrationStatus); + Mockito.when(demoDedupe.performDedupe(anyString())).thenReturn(emptyDuplicateDtoSet); + Mockito.when(packetInfoManager.getIdentityKeysAndFetchValuesFromJSON(any(),any(),any())).thenReturn(individualDemoDedupe); + Mockito.when(abisHandlerUtil.getPacketStatus(any())).thenReturn(AbisConstant.POST_ABIS_IDENTIFICATION); + MessageDTO messageDto = demodedupeProcessor.process(dto, stageName); + assertTrue(messageDto.getIsValid()); + assertFalse(messageDto.getInternalError()); + } + + @Test + public void testDemoDedupeUpdatePacketException() throws Exception { + InternalRegistrationStatusDto registrationStatus = new InternalRegistrationStatusDto(); + registrationStatus.setRegistrationId("2018701130000410092018110736"); + registrationStatus.setRegistrationType(RegistrationType.UPDATE.name()); + + IdentityJsonValues identityJsonValues = new IdentityJsonValues(); + identityJsonValues.setValue("fullName"); + when(utility.getDefaultSource(any(),any())).thenReturn(source); + Mockito.when(utility.getUIn(anyString(), anyString(), any())).thenReturn("2345"); + + Mockito.when(utility.retrieveIdrepoJson(any())).thenReturn(null); + + byte[] b = "sds".getBytes(); + List emptyDuplicateDtoSet = new ArrayList<>(); + + PowerMockito.mockStatic(JsonUtil.class); + PowerMockito.mockStatic(IOUtils.class); + PowerMockito.when(JsonUtil.class, "inputStreamtoJavaObject", inputStream, PacketMetaInfo.class) + .thenReturn(packetMetaInfo); + PowerMockito.when(IOUtils.class, "toByteArray", inputStream).thenReturn(b); + Mockito.when(registrationStatusService.getRegistrationStatus(any(),any(),any(), any())).thenReturn(registrationStatus); + Mockito.when(demoDedupe.performDedupe(anyString())).thenReturn(emptyDuplicateDtoSet); + Mockito.when(packetInfoManager.getIdentityKeysAndFetchValuesFromJSON(any(),any(),any())).thenReturn(individualDemoDedupe); + MessageDTO messageDto = demodedupeProcessor.process(dto, stageName); + assertFalse(messageDto.getIsValid()); + assertTrue(messageDto.getInternalError()); + } + + @SuppressWarnings("unchecked") + @Test + public void testDemoDedupeResUpdatePacketSuccess() throws Exception { + InternalRegistrationStatusDto registrationStatus = new InternalRegistrationStatusDto(); + registrationStatus.setRegistrationId("2018701130000410092018110736"); + registrationStatus.setRegistrationType(RegistrationType.RES_UPDATE.name()); + + IdentityJsonValues identityJsonValues = new IdentityJsonValues(); + identityJsonValues.setValue("fullName"); + when(utility.getDefaultSource(any(),any())).thenReturn(source); + Mockito.when(utility.getUIn(anyString(), anyString(), any())).thenReturn("2345"); + + JSONArray arr = new JSONArray(); + arr.add("name"); + + JSONObject obj = new JSONObject(); + obj.put("fullName", arr); + Mockito.when(utility.retrieveIdrepoJson(anyString())).thenReturn(obj); + + byte[] b = "sds".getBytes(); + List emptyDuplicateDtoSet = new ArrayList<>(); + + PowerMockito.mockStatic(JsonUtil.class); + PowerMockito.mockStatic(IOUtils.class); + PowerMockito.when(JsonUtil.getJSONValue(any(), any())).thenReturn("Test1,Test2"); + PowerMockito.when(JsonUtil.getJSONObject(any(), any())).thenReturn(obj); + JsonValue[] nameArray = new JsonValue[1]; + JsonValue jsonValue = new JsonValue(); + jsonValue.setLanguage("eng"); + jsonValue.setValue("test"); + nameArray[0] = jsonValue; + PowerMockito.when(JsonUtil.getJsonValues(any(),any())).thenReturn(nameArray); + PowerMockito.when(JsonUtil.class, "inputStreamtoJavaObject", inputStream, PacketMetaInfo.class) + .thenReturn(packetMetaInfo); + PowerMockito.when(IOUtils.class, "toByteArray", inputStream).thenReturn(b); + Mockito.when(registrationStatusService.getRegistrationStatus(any(),any(),any(), any())).thenReturn(registrationStatus); + Mockito.when(demoDedupe.performDedupe(anyString())).thenReturn(emptyDuplicateDtoSet); + IndividualDemographicDedupe demographicData = individualDemoDedupe; + demographicData.setName(null); + demographicData.setDateOfBirth(null); + demographicData.setGender(null); + demographicData.setPhone(null); + demographicData.setEmail(null); + Mockito.when(packetInfoManager.getIdentityKeysAndFetchValuesFromJSON(any(),any(), any())).thenReturn(demographicData); + Mockito.when(abisHandlerUtil.getPacketStatus(any())).thenReturn(AbisConstant.POST_ABIS_IDENTIFICATION); + MessageDTO messageDto = demodedupeProcessor.process(dto, stageName); + assertTrue(messageDto.getIsValid()); + assertFalse(messageDto.getInternalError()); + } + + @Test + public void testDemoDedupeSuccessNotDuplicateAfterAuth() throws Exception { + + byte[] b = "sds".getBytes(); + Mockito.when(utility.getApplicantAge(anyString(),anyString(), any())).thenReturn(20); + PowerMockito.mockStatic(JsonUtil.class); + PowerMockito.mockStatic(IOUtils.class); + PowerMockito.when(JsonUtil.class, "inputStreamtoJavaObject", inputStream, PacketMetaInfo.class) + .thenReturn(packetMetaInfo); + PowerMockito.when(IOUtils.class, "toByteArray", inputStream).thenReturn(b); + Mockito.when(registrationStatusService.getRegistrationStatus(any(),any(),any(), any())).thenReturn(registrationStatusDto); + Mockito.when(abisHandlerUtil.getPacketStatus(any())).thenReturn(AbisConstant.PRE_ABIS_IDENTIFICATION); + Mockito.when(demoDedupe.performDedupe(anyString())).thenReturn(duplicateDtos); + registrationStatusDto.setRegistrationType(RegistrationType.NEW.toString()); + Mockito.when(registrationStatusDao.find(any(),any(),any(),any())).thenReturn(entity); + MessageDTO messageDto = demodedupeProcessor.process(dto, stageName); + assertTrue(messageDto.getIsValid()); + assertFalse(messageDto.getInternalError()); + + } + + /** + * Test demo dedupe potential match. + * + * @throws Exception + */ + @Test + public void testDemoDedupePotentialMatchSuccess() throws Exception { + List abisResponseDtos = new ArrayList<>(); + AbisResponseDto abisResponseDto = new AbisResponseDto(); + abisResponseDto.setId("100"); + abisResponseDto.setStatusCode(AbisStatusCode.SUCCESS.toString()); + abisResponseDto.setLangCode("eng"); + abisResponseDtos.add(abisResponseDto); + + byte[] b = "sds".getBytes(); + + PowerMockito.mockStatic(JsonUtil.class); + PowerMockito.mockStatic(IOUtils.class); + PowerMockito.when(JsonUtil.class, "inputStreamtoJavaObject", inputStream, PacketMetaInfo.class) + .thenReturn(packetMetaInfo); + PowerMockito.when(IOUtils.class, "toByteArray", inputStream).thenReturn(b); + Mockito.when(registrationStatusService.getRegistrationStatus(any(),any(),any(), any())).thenReturn(registrationStatusDto); + Mockito.when(abisHandlerUtil.getPacketStatus(any())).thenReturn(AbisConstant.POST_ABIS_IDENTIFICATION); + Mockito.when(demoDedupe.performDedupe(anyString())).thenReturn(duplicateDtos); + registrationStatusDto.setRegistrationType(RegistrationType.NEW.toString()); + Mockito.when(registrationStatusDao.find(any(),any(),any(),any())).thenReturn(entity); + Mockito.when(packetInfoManager.getAbisResponseRecords(anyString(), anyString())).thenReturn(abisResponseDtos); + Mockito.when(utility.getApplicantAge(anyString(),anyString(), any())).thenReturn(20); + MessageDTO messageDto = demodedupeProcessor.process(dto, stageName); + + assertTrue(messageDto.getIsValid()); + assertFalse(messageDto.getInternalError()); + + } + + @Test + public void testDemoDedupePotentialMatchWithEmpty() throws Exception { + List abisResponseDtos = new ArrayList<>(); + List abisResponseDetDtos = new ArrayList<>(); + Set matchedRegIds = new HashSet<>(); + AbisResponseDto abisResponseDto = new AbisResponseDto(); + abisResponseDto.setId("100"); + abisResponseDto.setStatusCode(AbisStatusCode.SUCCESS.toString()); + abisResponseDto.setLangCode("eng"); + abisResponseDtos.add(abisResponseDto); + + matchedRegIds.add("2018701130000410092018110735"); + byte[] b = "sds".getBytes(); + + PowerMockito.mockStatic(JsonUtil.class); + PowerMockito.mockStatic(IOUtils.class); + PowerMockito.when(JsonUtil.class, "inputStreamtoJavaObject", inputStream, PacketMetaInfo.class) + .thenReturn(packetMetaInfo); + PowerMockito.when(IOUtils.class, "toByteArray", inputStream).thenReturn(b); + Mockito.when(registrationStatusService.getRegistrationStatus(any(),any(),any(), any())).thenReturn(registrationStatusDto); + Mockito.when(abisHandlerUtil.getPacketStatus(any())).thenReturn(AbisConstant.POST_ABIS_IDENTIFICATION); + Mockito.when(demoDedupe.performDedupe(anyString())).thenReturn(duplicateDtos); + registrationStatusDto.setRegistrationType(RegistrationType.NEW.toString()); + Mockito.when(registrationStatusDao.find(any(),any(),any(),any())).thenReturn(entity); + Mockito.when(packetInfoManager.getAbisResponseRecords(anyString(), anyString())).thenReturn(abisResponseDtos); + Mockito.when(packetInfoManager.getAbisResponseDetRecordsList(any())).thenReturn(abisResponseDetDtos); + Mockito.when(abisHandlerUtil.getUniqueRegIds(anyString(), anyString(), anyInt(), any(), any())) + .thenReturn(matchedRegIds); + doNothing().when(packetInfoManager).saveManualAdjudicationData(anySet(), any(), any(), any(), any(),any(),any()); + Mockito.when(utility.getApplicantAge(anyString(),anyString(), any())).thenReturn(20); + MessageDTO messageDto = demodedupeProcessor.process(dto, stageName); + + assertTrue(messageDto.getIsValid()); + assertFalse(messageDto.getInternalError()); + } + + @Test + public void testDemoDedupeWithOnePotentialMatch() throws Exception { + List abisResponseDtos = new ArrayList<>(); + List abisResponseDetDtos = new ArrayList<>(); + Set matchedRegIds = new HashSet<>(); + AbisResponseDto abisResponseDto = new AbisResponseDto(); + abisResponseDto.setId("100"); + abisResponseDto.setStatusCode(AbisStatusCode.SUCCESS.toString()); + abisResponseDto.setLangCode("eng"); + abisResponseDtos.add(abisResponseDto); + + AbisResponseDetDto abisResponseDetDto = new AbisResponseDetDto(); + abisResponseDetDto.setAbiRespId("1004"); + abisResponseDetDtos.add(abisResponseDetDto); + + matchedRegIds.add("2018701130000410092018110735"); + byte[] b = "sds".getBytes(); + + PowerMockito.mockStatic(JsonUtil.class); + PowerMockito.mockStatic(IOUtils.class); + PowerMockito.when(JsonUtil.class, "inputStreamtoJavaObject", inputStream, PacketMetaInfo.class) + .thenReturn(packetMetaInfo); + PowerMockito.when(IOUtils.class, "toByteArray", inputStream).thenReturn(b); + Mockito.when(registrationStatusService.getRegistrationStatus(any(),any(),any(), any())).thenReturn(registrationStatusDto); + Mockito.when(abisHandlerUtil.getPacketStatus(any())).thenReturn(AbisConstant.POST_ABIS_IDENTIFICATION); + Mockito.when(demoDedupe.performDedupe(anyString())).thenReturn(duplicateDtos); + registrationStatusDto.setRegistrationType(RegistrationType.NEW.toString()); + Mockito.when(registrationStatusDao.find(any(),any(),any(),any())).thenReturn(entity); + Mockito.when(packetInfoManager.getAbisResponseRecords(anyString(), anyString())).thenReturn(abisResponseDtos); + Mockito.when(packetInfoManager.getAbisResponseDetRecordsList(any())).thenReturn(abisResponseDetDtos); + Mockito.when(abisHandlerUtil.getUniqueRegIds(anyString(), anyString(), anyInt(), any(), any())) + .thenReturn(matchedRegIds); + doNothing().when(packetInfoManager).saveManualAdjudicationData(anySet(), any(), any(), any(), any(),any(),any()); + Mockito.when(utility.getApplicantAge(anyString(),anyString(), any())).thenReturn(20); + MessageDTO messageDto = demodedupeProcessor.process(dto, stageName); + + assertFalse(messageDto.getIsValid()); + assertFalse(messageDto.getInternalError()); + } + + @Test + public void testDemoDedupeEmptyMatch() throws Exception { + List abisResponseDtos = new ArrayList<>(); + List abisResponseDetDtos = new ArrayList<>(); + Set matchedRegIds = new HashSet<>(); + AbisResponseDto abisResponseDto = new AbisResponseDto(); + abisResponseDto.setId("100"); + abisResponseDto.setStatusCode(AbisStatusCode.SUCCESS.toString()); + abisResponseDto.setLangCode("eng"); + abisResponseDtos.add(abisResponseDto); + + byte[] b = "sds".getBytes(); + + PowerMockito.mockStatic(JsonUtil.class); + PowerMockito.mockStatic(IOUtils.class); + PowerMockito.when(JsonUtil.class, "inputStreamtoJavaObject", inputStream, PacketMetaInfo.class) + .thenReturn(packetMetaInfo); + PowerMockito.when(IOUtils.class, "toByteArray", inputStream).thenReturn(b); + Mockito.when(registrationStatusService.getRegistrationStatus(any(),any(),any(), any())).thenReturn(registrationStatusDto); + Mockito.when(abisHandlerUtil.getPacketStatus(any())).thenReturn(AbisConstant.POST_ABIS_IDENTIFICATION); + Mockito.when(demoDedupe.performDedupe(anyString())).thenReturn(duplicateDtos); + registrationStatusDto.setRegistrationType(RegistrationType.NEW.toString()); + Mockito.when(registrationStatusDao.find(any(),any(),any(),any())).thenReturn(entity); + Mockito.when(packetInfoManager.getAbisResponseRecords(anyString(), anyString())).thenReturn(abisResponseDtos); + Mockito.when(packetInfoManager.getAbisResponseDetRecordsList(any())).thenReturn(abisResponseDetDtos); + Mockito.when(abisHandlerUtil.getUniqueRegIds(anyString(), anyString(), anyInt(), any(), any())) + .thenReturn(matchedRegIds); + doNothing().when(packetInfoManager).saveManualAdjudicationData(anySet(), any(), any(), any(), any(),any(),any()); + Mockito.when(utility.getApplicantAge(anyString(),anyString(), any())).thenReturn(20); + MessageDTO messageDto = demodedupeProcessor.process(dto, stageName); + + assertTrue(messageDto.getIsValid()); + assertFalse(messageDto.getInternalError()); + } + + @Test + public void testDemoDedupePotentialMatchAbisResponseNotProcessed() throws Exception { + List abisResponseDtos = new ArrayList<>(); + AbisResponseDto abisResponseDto = new AbisResponseDto(); + abisResponseDto.setId("100"); + abisResponseDto.setStatusCode("ERROR"); + abisResponseDto.setLangCode("eng"); + abisResponseDtos.add(abisResponseDto); + + byte[] b = "sds".getBytes(); + + PowerMockito.mockStatic(JsonUtil.class); + PowerMockito.mockStatic(IOUtils.class); + PowerMockito.when(JsonUtil.class, "inputStreamtoJavaObject", inputStream, PacketMetaInfo.class) + .thenReturn(packetMetaInfo); + PowerMockito.when(IOUtils.class, "toByteArray", inputStream).thenReturn(b); + Mockito.when(registrationStatusService.getRegistrationStatus(any(),any(),any(), any())).thenReturn(registrationStatusDto); + Mockito.when(abisHandlerUtil.getPacketStatus(any())).thenReturn(AbisConstant.POST_ABIS_IDENTIFICATION); + Mockito.when(demoDedupe.performDedupe(anyString())).thenReturn(duplicateDtos); + registrationStatusDto.setRegistrationType(RegistrationType.NEW.toString()); + Mockito.when(registrationStatusDao.find(any(),any(),any(),any())).thenReturn(entity); + Mockito.when(packetInfoManager.getAbisResponseRecords(anyString(), anyString())).thenReturn(abisResponseDtos); + Mockito.when(utility.getApplicantAge(anyString(),anyString(), any())).thenReturn(20); + MessageDTO messageDto = demodedupeProcessor.process(dto, stageName); + + assertTrue(messageDto.getIsValid()); + assertFalse(messageDto.getInternalError()); + } + + /** + * Test demo dedupe failure. + * + * @throws ApisResourceAccessException the apis resource access + * exception + * @throws IOException Signals that an I/O exception + * has occurred. + * @throws IntrospectionException + * @throws ParseException + * @throws InvocationTargetException + * @throws IllegalArgumentException + * @throws IllegalAccessException + * @throws io.mosip.kernel.core.exception.IOException + * @throws RegistrationProcessorCheckedException + */ + @Test + public void testDemoDedupeFailure() throws ApisResourceAccessException, IOException, JsonProcessingException, PacketManagerException, PacketManagerException { + InternalRegistrationStatusDto registrationStatusDto = new InternalRegistrationStatusDto(); + + Mockito.when(demoDedupe.performDedupe(anyString())).thenReturn(duplicateDtos); + Mockito.when(abisHandlerUtil.getPacketStatus(any())).thenReturn(RegistrationType.NEW.toString()); + Mockito.when(registrationStatusService.getRegistrationStatus(any(),any(),any(), any())).thenReturn(registrationStatusDto); + registrationStatusDto.setRetryCount(3); + Mockito.when(utility.getApplicantAge(anyString(),anyString(), any())).thenReturn(20); + demodedupeProcessor.process(dto, stageName); + + } + + /** + * Test resource exception. + * + * @throws ApisResourceAccessException the apis resource access + * exception + * @throws IOException Signals that an I/O exception + * has occurred. + * @throws IntrospectionException + * @throws ParseException + * @throws InvocationTargetException + * @throws IllegalArgumentException + * @throws IllegalAccessException + * @throws io.mosip.kernel.core.exception.IOException + * @throws RegistrationProcessorCheckedException + */ + @Test + public void testResourceException() throws ApisResourceAccessException, IOException, JsonProcessingException, PacketManagerException { + when(env.getProperty(DEMODEDUPEENABLE)).thenReturn("true"); + + List emptyDuplicateDtoSet = new ArrayList<>(); + when(utility.getDefaultSource(any(),any())).thenReturn(source); + Mockito.when(utility.getApplicantAge(anyString(),anyString(), any())).thenReturn(20); + + Mockito.when(registrationStatusService.getRegistrationStatus(any(),any(),any(), any())).thenReturn(registrationStatusDto); + Mockito.when(abisHandlerUtil.getPacketStatus(any())).thenReturn(AbisConstant.PRE_ABIS_IDENTIFICATION); + Mockito.when(registrationStatusMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.APIS_RESOURCE_ACCESS_EXCEPTION)).thenReturn("REPROCESS"); + Mockito.when(demoDedupe.performDedupe(anyString())).thenReturn(emptyDuplicateDtoSet); + when(utility.getDefaultSource(any(), any())).thenReturn(source); + ApisResourceAccessException exp = new ApisResourceAccessException("errorMessage"); + Mockito.doThrow(exp).when(utility).getApplicantAge(anyString(),anyString(), any()); + + + MessageDTO messageDto = demodedupeProcessor.process(dto, stageName); + assertEquals(true, messageDto.getInternalError()); + assertTrue(messageDto.getIsValid()); + } + + @Test + public void testFSAdapterExceptionException() + throws ApisResourceAccessException, IOException, JsonProcessingException, PacketManagerException { + Mockito.when(demoDedupe.performDedupe(anyString())).thenReturn(duplicateDtos); + + FSAdapterException exp = new FSAdapterException("errorMessage", "test"); + Mockito.doThrow(exp).when(abisHandlerUtil).getPacketStatus(any()); + registrationStatusDto.setRegistrationType(RegistrationType.NEW.toString()); + Mockito.when(registrationStatusService.getRegistrationStatus(any(),any(),any(), any())).thenReturn(registrationStatusDto); + Mockito.when(registrationStatusMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.OBJECT_STORE_EXCEPTION)).thenReturn("REPROCESS"); + Mockito.when(utility.getApplicantAge(anyString(),anyString(), any())).thenReturn(20); + MessageDTO messageDto = demodedupeProcessor.process(dto, stageName); + assertEquals(true, messageDto.getInternalError()); + assertTrue(messageDto.getIsValid()); + } + + @Test + public void testIllegalArgumentException() throws ApisResourceAccessException, IOException, JsonProcessingException, PacketManagerException { + Mockito.when(demoDedupe.performDedupe(anyString())).thenReturn(duplicateDtos); + IllegalArgumentException exp = new IllegalArgumentException("errorMessage"); + Mockito.doThrow(exp).when(abisHandlerUtil).getPacketStatus(any()); + registrationStatusDto.setRegistrationType(RegistrationType.NEW.toString()); + Mockito.when(registrationStatusService.getRegistrationStatus(any(),any(),any(), any())).thenReturn(registrationStatusDto); + Mockito.when(registrationStatusMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.ILLEGAL_ARGUMENT_EXCEPTION)).thenReturn("ERROR"); + Mockito.when(utility.getApplicantAge(anyString(),anyString(), any())).thenReturn(20); + MessageDTO messageDto = demodedupeProcessor.process(dto, stageName); + assertEquals(true, messageDto.getInternalError()); + assertFalse(messageDto.getIsValid()); + } + + /** + * Test demo dedupe success. + * + * @throws Exception + */ + @Test + public void testDemoDedupeNewPacketSkipped() throws Exception { + when(env.getProperty(DEMODEDUPEENABLE)).thenReturn("false"); + byte[] b = "sds".getBytes(); + + + PowerMockito.mockStatic(JsonUtil.class); + PowerMockito.mockStatic(IOUtils.class); + PowerMockito.when(JsonUtil.class, "inputStreamtoJavaObject", inputStream, PacketMetaInfo.class) + .thenReturn(packetMetaInfo); + PowerMockito.when(IOUtils.class, "toByteArray", inputStream).thenReturn(b); + Mockito.when(registrationStatusService.getRegistrationStatus(any(),any(),any(), any())).thenReturn(registrationStatusDto); + Mockito.when(abisHandlerUtil.getPacketStatus(any())).thenReturn(AbisConstant.PRE_ABIS_IDENTIFICATION); + Mockito.when(utility.getApplicantAge(anyString(),anyString(), any())).thenReturn(20); + MessageDTO messageDto = demodedupeProcessor.process(dto, stageName); + assertTrue(messageDto.getIsValid()); + assertFalse(messageDto.getInternalError()); + + } + /** + * Test demo dedupe success. + * + * @throws Exception + */ + @Test + public void testDemoDedupeNewPacketSuccessWithDuplicates() throws Exception { + when(env.getProperty(DEMODEDUPEENABLE)).thenReturn("true"); + byte[] b = "sds".getBytes(); + + + PowerMockito.mockStatic(JsonUtil.class); + PowerMockito.mockStatic(IOUtils.class); + PowerMockito.when(JsonUtil.class, "inputStreamtoJavaObject", inputStream, PacketMetaInfo.class) + .thenReturn(packetMetaInfo); + PowerMockito.when(IOUtils.class, "toByteArray", inputStream).thenReturn(b); + Mockito.when(registrationStatusService.getRegistrationStatus(any(),any(),any(), any())).thenReturn(registrationStatusDto); + Mockito.when(abisHandlerUtil.getPacketStatus(any())).thenReturn(AbisConstant.PRE_ABIS_IDENTIFICATION); + Mockito.when(demoDedupe.performDedupe(anyString())).thenReturn(duplicateDtos); + Mockito.when(utility.getApplicantAge(anyString(),anyString(), any())).thenReturn(20); + MessageDTO messageDto = demodedupeProcessor.process(dto, stageName); + assertTrue(messageDto.getIsValid()); + assertFalse(messageDto.getInternalError()); + } + /** + * Test demo dedupe success. + * + * @throws Exception + */ + @Test + public void testDemoDedupeNewPacketSuccessWithDuplicatesWithException() throws Exception { + when(env.getProperty(DEMODEDUPEENABLE)).thenReturn("true"); + byte[] b = "sds".getBytes(); + + + PowerMockito.mockStatic(JsonUtil.class); + PowerMockito.mockStatic(IOUtils.class); + PowerMockito.when(JsonUtil.class, "inputStreamtoJavaObject", inputStream, PacketMetaInfo.class) + .thenReturn(packetMetaInfo); + PowerMockito.when(IOUtils.class, "toByteArray", inputStream).thenReturn(b); + Mockito.when(registrationStatusService.getRegistrationStatus(any(),any(),any(), any())).thenReturn(registrationStatusDto); + Mockito.when(abisHandlerUtil.getPacketStatus(any())).thenReturn(AbisConstant.PRE_ABIS_IDENTIFICATION); + Mockito.when(demoDedupe.performDedupe(anyString())).thenReturn(duplicateDtos); + NullPointerException exp=new NullPointerException(); + Mockito.doThrow(exp).when(packetInfoManager).saveDemoDedupePotentialData(any(),anyString(),anyString()); + Mockito.when(utility.getApplicantAge(anyString(),anyString(), any())).thenReturn(20); + MessageDTO messageDto = demodedupeProcessor.process(dto, stageName); + assertTrue(messageDto.getIsValid()); + assertTrue(messageDto.getInternalError()); + + } + + @Test + public void testDemoDedupeNewChildPacketSuccess() throws Exception { + when(env.getProperty(DEMODEDUPEENABLE)).thenReturn("true"); + byte[] b = "sds".getBytes(); + List emptyDuplicateDtoSet = new ArrayList<>(); + Mockito.when(utility.getApplicantAge(anyString(),anyString(), any())).thenReturn(2); + PowerMockito.mockStatic(JsonUtil.class); + PowerMockito.mockStatic(IOUtils.class); + PowerMockito.when(JsonUtil.class, "inputStreamtoJavaObject", inputStream, PacketMetaInfo.class) + .thenReturn(packetMetaInfo); + PowerMockito.when(IOUtils.class, "toByteArray", inputStream).thenReturn(b); + Mockito.when(registrationStatusService.getRegistrationStatus(any(),any(),any(), any())).thenReturn(registrationStatusDto); + Mockito.when(abisHandlerUtil.getPacketStatus(any())).thenReturn(AbisConstant.PRE_ABIS_IDENTIFICATION); + Mockito.when(demoDedupe.performDedupe(anyString())).thenReturn(emptyDuplicateDtoSet); + + MessageDTO messageDto = demodedupeProcessor.process(dto, stageName); + assertTrue(messageDto.getIsValid()); + assertFalse(messageDto.getInternalError()); + + } + + @Test + public void testDemoDedupeDisabledSuccess() throws Exception { + when(env.getProperty(DEMODEDUPEENABLE)).thenReturn("false"); + byte[] b = "sds".getBytes(); + List emptyDuplicateDtoSet = new ArrayList<>(); + Mockito.when(utility.getApplicantAge(any(),any(), any())).thenReturn(20); + PowerMockito.mockStatic(JsonUtil.class); + PowerMockito.mockStatic(IOUtils.class); + PowerMockito.when(JsonUtil.class, "inputStreamtoJavaObject", inputStream, PacketMetaInfo.class) + .thenReturn(packetMetaInfo); + PowerMockito.when(IOUtils.class, "toByteArray", inputStream).thenReturn(b); + Mockito.when(registrationStatusService.getRegistrationStatus(any(),any(),any(), any())).thenReturn(registrationStatusDto); + Mockito.when(abisHandlerUtil.getPacketStatus(any())).thenReturn(AbisConstant.PRE_ABIS_IDENTIFICATION); + Mockito.when(demoDedupe.performDedupe(anyString())).thenReturn(emptyDuplicateDtoSet); + + MessageDTO messageDto = demodedupeProcessor.process(dto, stageName); + assertTrue(messageDto.getIsValid()); + assertFalse(messageDto.getInternalError()); + + } + + @Test + public void testDemoDedupeSuccess() throws Exception { + when(env.getProperty(DEMODEDUPEENABLE)).thenReturn("true"); + byte[] b = "sds".getBytes(); + List emptyDuplicateDtoSet = new ArrayList<>(); + Mockito.when(utility.getApplicantAge(any(), any(), any())).thenReturn(20); + PowerMockito.mockStatic(JsonUtil.class); + PowerMockito.mockStatic(IOUtils.class); + PowerMockito.when(JsonUtil.class, "inputStreamtoJavaObject", inputStream, PacketMetaInfo.class) + .thenReturn(packetMetaInfo); + PowerMockito.when(IOUtils.class, "toByteArray", inputStream).thenReturn(b); + Mockito.when(registrationStatusService.getRegistrationStatus(any(),any(),any(), any())).thenReturn(registrationStatusDto); + Mockito.when(abisHandlerUtil.getPacketStatus(any())).thenReturn(AbisConstant.PRE_ABIS_IDENTIFICATION); + Mockito.when(demoDedupe.performDedupe(anyString())).thenReturn(emptyDuplicateDtoSet); + + MessageDTO messageDto = demodedupeProcessor.process(dto, stageName); + assertTrue(messageDto.getIsValid()); + assertFalse(messageDto.getInternalError()); + + } + + @Test + public void testDemoDedupeNewDuplicatePacketSuccess() throws Exception { + when(env.getProperty(DEMODEDUPEENABLE)).thenReturn("true"); + + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())) + .thenReturn(registrationStatusDto); + Mockito.when(abisHandlerUtil.getPacketStatus(any())).thenReturn(AbisConstant.DUPLICATE_FOR_SAME_TRANSACTION_ID); + + MessageDTO messageDto = demodedupeProcessor.process(dto, stageName); + assertTrue(messageDto.getInternalError()); + + } } \ 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/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..f0a8b5a6f39 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 @@ -26,7 +26,7 @@ ManualVerificationRequestValidator getManualVerificationRequestValidator() { ManualVerificationExceptionHandler getManualVerificationExceptionHandler() { return new ManualVerificationExceptionHandler(); } - + @Bean ManualVerificationUpdateUtility getManualVerificationUpdateUtility() { return new ManualVerificationUpdateUtility(); 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..db7bd9b3b01 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,6 +1,6 @@ package io.mosip.registration.processor.adjudication.util; - + import java.sql.Timestamp; import java.util.List; 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..e6e4e5d5da0 --- /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/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..02e944677cb 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,2478 +1,2478 @@ -package io.mosip.registration.processor.stages.uigenerator; - -import static org.junit.Assert.*; -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 java.io.ByteArrayInputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -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; -import java.util.LinkedHashMap; -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; -import org.json.simple.JSONObject; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.*; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; -import org.springframework.core.env.Environment; -import org.springframework.http.HttpStatus; -import org.springframework.test.util.ReflectionTestUtils; -import org.springframework.web.client.HttpClientErrorException; -import org.springframework.web.client.HttpServerErrorException; - -import com.fasterxml.jackson.databind.ObjectMapper; - -import io.mosip.kernel.biometrics.constant.BiometricType; -import io.mosip.kernel.biometrics.constant.QualityType; -import io.mosip.kernel.biometrics.entities.BDBInfo; -import io.mosip.kernel.biometrics.entities.BIR; -import io.mosip.kernel.biometrics.entities.BiometricRecord; -import io.mosip.kernel.biometrics.entities.RegistryIDType; -import io.mosip.kernel.biometrics.spi.CbeffUtil; -import io.mosip.kernel.core.util.HMACUtils2; -import io.mosip.kernel.core.util.exception.JsonProcessingException; -import io.mosip.kernel.dataaccess.hibernate.constant.HibernateErrorCode; -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.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.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.RegistrationType; -import io.mosip.registration.processor.core.exception.ApisResourceAccessException; -import io.mosip.registration.processor.core.exception.PacketManagerException; -import io.mosip.registration.processor.core.http.ResponseWrapper; -import io.mosip.registration.processor.core.idrepo.dto.Documents; -import io.mosip.registration.processor.core.logger.LogDescription; -import io.mosip.registration.processor.core.packet.dto.ApplicantDocument; -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.packetmanager.PacketInfoManager; -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.IdResponseDTO; -import io.mosip.registration.processor.packet.manager.dto.ResponseDTO; -import io.mosip.registration.processor.packet.manager.exception.IdrepoDraftException; -import io.mosip.registration.processor.packet.manager.exception.IdrepoDraftReprocessableException; -import io.mosip.registration.processor.packet.manager.idreposervice.IdRepoService; -import io.mosip.registration.processor.packet.manager.idreposervice.IdrepoDraftService; -import io.mosip.registration.processor.packet.storage.dto.ApplicantInfoDto; -import io.mosip.registration.processor.packet.storage.dto.ContainerInfoDto; -import io.mosip.registration.processor.packet.storage.dto.Document; -import io.mosip.registration.processor.packet.storage.entity.IndividualDemographicDedupeEntity; -import io.mosip.registration.processor.packet.storage.entity.RegLostUinDetEntity; -import io.mosip.registration.processor.packet.storage.repository.BasePacketRepository; -import io.mosip.registration.processor.packet.storage.utils.IdSchemaUtil; -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.rest.client.audit.dto.AuditResponseDto; -import io.mosip.registration.processor.stages.uingenerator.stage.UinGeneratorStage; -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; - -@RunWith(PowerMockRunner.class) -@PrepareForTest({ IOUtils.class, HMACUtils2.class, Utilities.class}) -@PowerMockIgnore({"com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "javax.management.*", "javax.net.ssl.*" }) -public class UinGeneratorStageTest { - - @InjectMocks - private UinGeneratorStage uinGeneratorStage = new UinGeneratorStage() { - @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) { - - - } - - @Override - public void senderHealthCheck(Handler eventHandler, String address) { - - - } - - }; - } - - @Override - public void consumeAndSend(MosipEventBus mosipEventBus, MessageBusAddress fromAddress, - MessageBusAddress toAddress, long messageExpiryTimeLimit) { - } - - @Override - public Integer getPort() { - return 8080; - } - }; - - /** The input stream. */ - @Mock - private InputStream inputStream; - - @Mock - private Object identity; - - @Mock - private PriorityBasedPacketManagerService packetManagerService; - - /** The registration status service. */ - @Mock - private RegistrationStatusService registrationStatusService; - - @Mock - private IdrepoDraftService idrepoDraftService; - - /** The identity json. */ - @Mock - private JSONObject identityJson; - - @Mock - private AuditLogRequestBuilder auditLogRequestBuilder; - - @Mock - private RegistrationProcessorRestClientService registrationProcessorRestClientService; - - @Mock - private List documents; - - @Mock - private JSONObject demographicIdentity; - - @Mock - private PacketInfoManager packetInfoManager; - - @Mock - private BasePacketRepository demographicDedupeRepository; - - @Mock - private BasePacketRepository regLostUinDetRepository; - - /** The registration status dto. */ - private InternalRegistrationStatusDto registrationStatusDto = new InternalRegistrationStatusDto(); - - @Mock - private Utilities utility; - - @Mock - private IdRepoService idRepoService; - - @Mock - private CbeffUtil cbeffutil; - - @Mock - private BasePacketRepository regLostUinDetEntity; - - /** The identitydemoinfo. */ - Identity identitydemoinfo = new Identity(); - - /** The Constant CONFIG_SERVER_URL. */ - private static final String CONFIG_SERVER_URL = "url"; - - private String identityMappingjsonString; - - @Mock - private Environment env; - - @Mock - private LogDescription description; - - @Mock - private RegistrationExceptionMapperUtil registrationStatusMapperUtil; - - @Mock - private IdSchemaUtil idSchemaUtil; - - @Spy - private ObjectMapper mapper = new ObjectMapper(); - - JSONObject documentObj; - JSONObject identityObj; - - @Before - public void setup() throws Exception { - ReflectionTestUtils.setField(uinGeneratorStage, "workerPoolSize", 10); - ReflectionTestUtils.setField(uinGeneratorStage, "messageExpiryTimeLimit", Long.valueOf(0)); - ReflectionTestUtils.setField(uinGeneratorStage, "clusterManagerUrl", "/dummyPath"); - ReflectionTestUtils.setField(uinGeneratorStage, "updateInfo", "phone"); - ClassLoader classLoader1 = getClass().getClassLoader(); - File idJsonFile1 = new File(classLoader1.getResource("RegistrationProcessorIdentity.json").getFile()); - InputStream idJsonStream1 = new FileInputStream(idJsonFile1); - LinkedHashMap hm = new ObjectMapper().readValue(idJsonStream1, LinkedHashMap.class); - JSONObject jsonObject = new JSONObject(hm); - identityMappingjsonString = jsonObject.toJSONString(); - documentObj = JsonUtil.getJSONObject(new ObjectMapper().readValue(identityMappingjsonString, JSONObject.class), MappingJsonConstants.DOCUMENT); - identityObj = JsonUtil.getJSONObject(new ObjectMapper().readValue(identityMappingjsonString, JSONObject.class), MappingJsonConstants.IDENTITY); - when(utility.getRegistrationProcessorMappingJson(MappingJsonConstants.IDENTITY)).thenReturn(identityObj); - when(utility.getRegistrationProcessorMappingJson(MappingJsonConstants.DOCUMENT)).thenReturn(documentObj); - - String str = "{\"id\":\"mosip.id.read\",\"version\":\"1.0\",\"responsetime\":\"2019-04-05\",\"metadata\":null,\"response\":{\"uin\":\"2812936908\"},\"errors\":[{\"errorCode\":null,\"errorMessage\":null}]}"; - when(registrationProcessorRestClientService.getApi(any(), any(), anyString(), - anyString(), any(Class.class))).thenReturn(str); - - //when(registrationStatusMapperUtil.getStatusCode(any())).thenReturn("EXCEPTION"); - Mockito.doNothing().when(description).setCode(Mockito.anyString()); - Mockito.doNothing().when(description).setMessage(Mockito.anyString()); - when(description.getCode()).thenReturn("CODE"); - when(description.getMessage()).thenReturn("MESSAGE"); - MockitoAnnotations.initMocks(this); - 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); - - registrationStatusDto.setLatestTransactionStatusCode("SUCCESS"); - when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); - - PowerMockito.mockStatic(Utilities.class); - PowerMockito.when(Utilities.class, "getJson", CONFIG_SERVER_URL, "RegistrationProcessorIdentity.json") - .thenReturn(identityMappingjsonString); - when(utility.getGetRegProcessorDemographicIdentity()).thenReturn("identity"); - - when(identityJson.get(anyString())).thenReturn(demographicIdentity); - List applicantDocument = new ArrayList<>(); - ApplicantDocument appDocument = new ApplicantDocument(); - appDocument.setIsActive(true); - appDocument.setDocName("POA"); - appDocument.setDocStore("ProofOfAddress".getBytes()); - applicantDocument.add(appDocument); - when(env.getProperty("registration.processor.id.repo.generate")).thenReturn("mosip.vid.create"); - when(env.getProperty("mosip.registration.processor.datetime.pattern")) - .thenReturn("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); - when(env.getProperty("registration.processor.id.repo.vidVersion")).thenReturn("v1"); - when(regLostUinDetRepository.getLostUinMatchedRegIdByWorkflowId(anyString())) - .thenReturn("27847657360002520181210094052"); - demographicIdentity.put("UIN", Long.parseLong("9403107397")); - - when(idRepoService.getUinByRid(anyString(), anyString())).thenReturn("9403107397"); - - List birTypeList = new ArrayList<>(); - BIR birType1 = new BIR.BIRBuilder().build(); - BDBInfo bdbInfoType1 = new BDBInfo.BDBInfoBuilder().build(); - RegistryIDType registryIDType = new RegistryIDType(); - registryIDType.setOrganization("Mosip"); - registryIDType.setType("257"); - QualityType quality = new QualityType(); - quality.setAlgorithm(registryIDType); - quality.setScore(90l); - bdbInfoType1.setQuality(quality); - BiometricType singleType1 = BiometricType.FINGER; - List singleTypeList1 = new ArrayList<>(); - singleTypeList1.add(singleType1); - List subtype1 = new ArrayList<>(Arrays.asList("Left", "RingFinger")); - bdbInfoType1.setSubtype(subtype1); - bdbInfoType1.setType(singleTypeList1); - birType1.setBdbInfo(bdbInfoType1); - birTypeList.add(birType1); - - BiometricRecord biometricRecord = new BiometricRecord(); - biometricRecord.setSegments(birTypeList); - - Document document = new Document(); - document.setDocument("document".getBytes()); - - Map fieldMap = new HashMap<>(); - fieldMap.put("name", "mono"); - fieldMap.put("email", "mono@mono.com"); - fieldMap.put("phone", "23456"); - fieldMap.put("dob", "11/11/2011"); - - List defaultFields = new ArrayList<>(); - defaultFields.add("name"); - defaultFields.add("dob"); - defaultFields.add("gender"); - - - when(packetManagerService.getFieldByMappingJsonKey(anyString(),anyString(),any(),any())).thenReturn("0.1"); - when(packetManagerService.getFields(any(), any(), any(), any())).thenReturn(fieldMap); - when(packetManagerService.getDocument(anyString(),anyString(),anyString(),any())).thenReturn(document); - when(packetManagerService.getBiometrics(anyString(),anyString(),any(),any())).thenReturn(biometricRecord); - when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); - when(utility.getMappingJsonValue(anyString(), any())).thenReturn("UIN"); - - ContainerInfoDto containerInfoDto = new ContainerInfoDto(); - containerInfoDto.setSource("REGISTRATION_CLIENT"); - containerInfoDto.setProcess("NEW"); - - when(packetManagerService.getBiometrics(anyString(),any(), any(), any())).thenReturn(biometricRecord); - when(cbeffutil.createXML(any())).thenReturn("String".getBytes()); - - } - - @Test - public void testUinGenerationSuccessWithoutUIN() throws Exception { - MessageDTO messageDTO = new MessageDTO(); - messageDTO.setRid("27847657360002520181210094052"); - messageDTO.setReg_type(RegistrationType.NEW.name()); - - IdResponseDTO idResponseDTO = new IdResponseDTO(); - ResponseDTO responseDTO = new ResponseDTO(); - responseDTO.setStatus("ACTIVATED"); - idResponseDTO.setErrors(null); - idResponseDTO.setId("mosip.id.update"); - idResponseDTO.setResponse(responseDTO); - idResponseDTO.setResponsetime("2019-01-17T06:29:01.940Z"); - idResponseDTO.setVersion("1.0"); - - when(idrepoDraftService.idrepoUpdateDraft(anyString(), any(), any())).thenReturn(idResponseDTO); - when(utility.getRegistrationProcessorMappingJson(MappingJsonConstants.IDENTITY)).thenReturn(identityObj); - when(utility.getRegistrationProcessorMappingJson(MappingJsonConstants.DOCUMENT)).thenReturn(documentObj); - - MessageDTO result = uinGeneratorStage.process(messageDTO); - assertFalse(result.getInternalError()); - assertTrue(result.getIsValid()); - } - - @Test - public void testUinGenerationIDRepoDraftException() throws Exception { - MessageDTO messageDTO = new MessageDTO(); - messageDTO.setRid("27847657360002520181210094052"); - messageDTO.setReg_type(RegistrationType.NEW.name()); - - when(registrationStatusMapperUtil - .getStatusCode(RegistrationExceptionTypeCode.IDREPO_DRAFT_EXCEPTION)).thenReturn("FAILED"); - when(idrepoDraftService.idrepoUpdateDraft(anyString(), any(), any())).thenThrow(IdrepoDraftException.class); - when(utility.getRegistrationProcessorMappingJson(MappingJsonConstants.IDENTITY)).thenReturn(identityObj); - when(utility.getRegistrationProcessorMappingJson(MappingJsonConstants.DOCUMENT)).thenReturn(documentObj); - - MessageDTO result = uinGeneratorStage.process(messageDTO); - assertTrue(result.getInternalError()); - assertFalse(result.getIsValid()); - } - - @Test - public void testUinGenerationIDRepoDraftAPiResourceException() throws Exception { - - ApisResourceAccessException apisResourceAccessException = Mockito.mock(ApisResourceAccessException.class); - HttpServerErrorException httpServerErrorException = new HttpServerErrorException( - HttpStatus.INTERNAL_SERVER_ERROR, "KER-FSE-004:encrypted data is corrupted or not base64 encoded"); - when(apisResourceAccessException.getCause()).thenReturn(httpServerErrorException); - - Map fieldMap = new HashMap<>(); - fieldMap.put("UIN", "123456"); - fieldMap.put("name", "mono"); - fieldMap.put("email", "mono@mono.com"); - - List defaultFields = new ArrayList<>(); - defaultFields.add("name"); - defaultFields.add("dob"); - defaultFields.add("gender"); - defaultFields.add("UIN"); - - - when(packetManagerService.getFieldByMappingJsonKey(anyString(),anyString(),any(),any())).thenReturn("0.1"); - when(packetManagerService.getFields(any(), any(), any(), any())).thenReturn(fieldMap); - when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); - - MessageDTO messageDTO = new MessageDTO(); - messageDTO.setRid("27847657360002520181210094052"); - messageDTO.setReg_type(RegistrationType.UPDATE.name()); - - when(registrationStatusMapperUtil - .getStatusCode(RegistrationExceptionTypeCode.APIS_RESOURCE_ACCESS_EXCEPTION)).thenReturn("REPROCESS"); - when(idrepoDraftService.idrepoUpdateDraft(anyString(), any(), any())).thenThrow(apisResourceAccessException); - when(utility.getRegistrationProcessorMappingJson(MappingJsonConstants.IDENTITY)).thenReturn(identityObj); - when(utility.getRegistrationProcessorMappingJson(MappingJsonConstants.DOCUMENT)).thenReturn(documentObj); - - MessageDTO result = uinGeneratorStage.process(messageDTO); - assertTrue(result.getInternalError()); - assertTrue(result.getIsValid()); - } - - @Test - public void testUinReActivationifAlreadyActivatedSuccess() throws Exception { - - MessageDTO messageDTO = new MessageDTO(); - messageDTO.setRid("27847657360002520181210094052"); - messageDTO.setReg_type(RegistrationType.valueOf("ACTIVATED").name()); - - IdResponseDTO idResponseDTO = new IdResponseDTO(); - ResponseDTO responseDTO = new ResponseDTO(); - idResponseDTO.setErrors(null); - idResponseDTO.setId("mosip.id.update"); - responseDTO.setStatus("ACTIVATED"); - idResponseDTO.setResponse(responseDTO); - idResponseDTO.setResponsetime("2019-01-17T06:29:01.940Z"); - idResponseDTO.setVersion("1.0"); - - Map fieldMap = new HashMap<>(); - fieldMap.put("UIN", "123456"); - fieldMap.put("name", "mono"); - fieldMap.put("email", "mono@mono.com"); - - List defaultFields = new ArrayList<>(); - defaultFields.add("name"); - defaultFields.add("dob"); - defaultFields.add("gender"); - defaultFields.add("UIN"); - - - when(packetManagerService.getFieldByMappingJsonKey(anyString(),anyString(),any(),any())).thenReturn("0.1"); - when(packetManagerService.getFields(any(), any(), any(), any())).thenReturn(fieldMap); - when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); - when(idrepoDraftService.idrepoUpdateDraft(anyString(), any(), any())).thenReturn(idResponseDTO); - - when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); - - when(registrationProcessorRestClientService.getApi(any(), any(), anyString(), any(), any())) - .thenReturn(idResponseDTO); - when(idrepoDraftService.idrepoUpdateDraft(anyString(), any(), any())).thenReturn(idResponseDTO); - - String idJsonData = "{\"identity\":{\"IDSchemaVersion\":1.0,\"UIN\":4215839851}}"; - - when(registrationProcessorRestClientService.postApi(any(), any(), any(), any(), any())) - .thenReturn(idResponseDTO); - MessageDTO result = uinGeneratorStage.process(messageDTO); - assertFalse(result.getIsValid()); - assertFalse(result.getInternalError()); - } - - @Test - public void testUinReActivationResponseStatusAsActivated() throws Exception { - Map fieldMap = new HashMap<>(); - fieldMap.put("UIN", "123456"); - fieldMap.put("name", "mono"); - fieldMap.put("email", "mono@mono.com"); - - List defaultFields = new ArrayList<>(); - defaultFields.add("name"); - defaultFields.add("dob"); - defaultFields.add("gender"); - defaultFields.add("UIN"); - - - when(packetManagerService.getFieldByMappingJsonKey(anyString(),anyString(),any(),any())).thenReturn("0.1"); - when(packetManagerService.getFields(any(), any(), any(), any())).thenReturn(fieldMap); - when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); - - MessageDTO messageDTO = new MessageDTO(); - messageDTO.setRid("27847657360002520181210094052"); - messageDTO.setReg_type(RegistrationType.valueOf("ACTIVATED").name()); - - IdResponseDTO idResponseDTO = new IdResponseDTO(); - ResponseDTO responseDTO = new ResponseDTO(); - idResponseDTO.setErrors(null); - idResponseDTO.setId("mosip.id.update"); - responseDTO.setStatus("ACTIVATED"); - idResponseDTO.setResponse(responseDTO); - idResponseDTO.setResponsetime("2019-01-17T06:29:01.940Z"); - idResponseDTO.setVersion("1.0"); - - when(registrationProcessorRestClientService.getApi(any(), any(), anyString(), any(), any())) - .thenReturn(idResponseDTO); - - when(idrepoDraftService.idrepoUpdateDraft(anyString(), any(), any())).thenReturn(idResponseDTO); - MessageDTO result = uinGeneratorStage.process(messageDTO); - assertFalse(result.getIsValid()); - assertFalse(result.getInternalError()); - } - - @Test - public void testUinReActivationIDraftResponseActivated() throws Exception { - Map fieldMap = new HashMap<>(); - fieldMap.put("UIN", "123456"); - fieldMap.put("name", "mono"); - fieldMap.put("email", "mono@mono.com"); - - List defaultFields = new ArrayList<>(); - defaultFields.add("name"); - defaultFields.add("dob"); - defaultFields.add("gender"); - defaultFields.add("UIN"); - - when(packetManagerService.getFieldByMappingJsonKey(anyString(),anyString(),any(),any())).thenReturn("0.1"); - when(packetManagerService.getFields(any(), any(), any(), any())).thenReturn(fieldMap); - when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); - - MessageDTO messageDTO = new MessageDTO(); - messageDTO.setRid("27847657360002520181210094052"); - messageDTO.setReg_type(RegistrationType.valueOf("ACTIVATED").name()); - - IdResponseDTO idResponseDTO = new IdResponseDTO(); - ResponseDTO responseDTO = new ResponseDTO(); - idResponseDTO.setErrors(null); - idResponseDTO.setId("mosip.id.update"); - responseDTO.setStatus("ACTIVATED"); - idResponseDTO.setResponse(responseDTO); - idResponseDTO.setResponsetime("2019-01-17T06:29:01.940Z"); - idResponseDTO.setVersion("1.0"); - - IdResponseDTO idResponseDTO1 = new IdResponseDTO(); - ResponseDTO responseDTO1 = new ResponseDTO(); - idResponseDTO1.setErrors(null); - idResponseDTO1.setId("mosip.id.update"); - responseDTO1.setStatus("ACTIVATED"); - idResponseDTO1.setResponse(responseDTO1); - - idResponseDTO1.setResponsetime("2019-01-17T06:29:01.940Z"); - idResponseDTO1.setVersion("1.0"); - - when(registrationProcessorRestClientService.getApi(any(), any(), anyString(), any(), any())) - .thenReturn(idResponseDTO); - - String idJsonData = "{\"identity\":{\"IDSchemaVersion\":1.0,\"UIN\":\"4215839851\"}}"; - - when(idrepoDraftService.idrepoUpdateDraft(anyString(), any(), any())).thenReturn(idResponseDTO); - when(registrationProcessorRestClientService.patchApi(any(), any(), any(), any(), any(), any())) - .thenReturn(idResponseDTO1); - MessageDTO result = uinGeneratorStage.process(messageDTO); - assertFalse(result.getIsValid()); - assertFalse(result.getInternalError()); - } - - @Test - public void testUinReActivationWithoutResponseDTO() throws Exception { - - Map fieldMap = new HashMap<>(); - fieldMap.put("UIN", "123456"); - fieldMap.put("name", "mono"); - fieldMap.put("email", "mono@mono.com"); - - List defaultFields = new ArrayList<>(); - defaultFields.add("name"); - defaultFields.add("dob"); - defaultFields.add("gender"); - defaultFields.add("UIN"); - - - when(packetManagerService.getFieldByMappingJsonKey(anyString(),anyString(),any(),any())).thenReturn("0.1"); - when(packetManagerService.getFields(any(), any(), any(), any())).thenReturn(fieldMap); - when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); - - when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); - - MessageDTO messageDTO = new MessageDTO(); - messageDTO.setRid("27847657360002520181210094052"); - messageDTO.setReg_type(RegistrationType.valueOf("ACTIVATED").name()); - - IdResponseDTO idResponseDTO = new IdResponseDTO(); - ResponseDTO responseDTO = new ResponseDTO(); - idResponseDTO.setErrors(null); - idResponseDTO.setId("mosip.id.update"); - responseDTO.setStatus("ANY"); - idResponseDTO.setResponse(responseDTO); - idResponseDTO.setResponsetime("2019-01-17T06:29:01.940Z"); - idResponseDTO.setVersion("1.0"); - - IdResponseDTO idResponseDTO1 = new IdResponseDTO(); - ResponseDTO responseDTO1 = new ResponseDTO(); - idResponseDTO1.setErrors(null); - idResponseDTO1.setId("mosip.id.update"); - responseDTO1.setStatus("ACTIVATED"); - idResponseDTO1.setResponse(null); - - idResponseDTO1.setResponsetime("2019-01-17T06:29:01.940Z"); - idResponseDTO1.setVersion("1.0"); - - when(registrationProcessorRestClientService.getApi(any(), any(), anyString(), any(), any())) - .thenReturn(idResponseDTO); - - String idJsonData = "{\"identity\":{\"IDSchemaVersion\":1.0,\"UIN\":\"4215839851\"}}";; - - when(idrepoDraftService.idrepoUpdateDraft(anyString(), any(), any())).thenReturn(idResponseDTO); - when(registrationProcessorRestClientService.patchApi(any(), any(), any(), any(), any(), any())) - .thenReturn(idResponseDTO1); - MessageDTO result = uinGeneratorStage.process(messageDTO); - assertFalse(result.getIsValid()); - assertFalse(result.getInternalError()); - } - - @Test - public void testUinReActivationWithResponseDTONull() throws Exception { - - Map fieldMap = new HashMap<>(); - fieldMap.put("UIN", "123456"); - fieldMap.put("name", "mono"); - fieldMap.put("email", "mono@mono.com"); - - List defaultFields = new ArrayList<>(); - defaultFields.add("name"); - defaultFields.add("dob"); - defaultFields.add("gender"); - defaultFields.add("UIN"); - - - when(packetManagerService.getFieldByMappingJsonKey(anyString(),anyString(),any(),any())).thenReturn("0.1"); - when(packetManagerService.getFields(any(), any(), any(), any())).thenReturn(fieldMap); - when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); - - MessageDTO messageDTO = new MessageDTO(); - messageDTO.setRid("27847657360002520181210094052"); - messageDTO.setReg_type(RegistrationType.valueOf("ACTIVATED").name()); - - IdResponseDTO idResponseDTO = new IdResponseDTO(); - ResponseDTO responseDTO = new ResponseDTO(); - idResponseDTO.setErrors(null); - idResponseDTO.setId("mosip.id.update"); - responseDTO.setStatus("ANY"); - idResponseDTO.setResponse(responseDTO); - idResponseDTO.setResponsetime("2019-01-17T06:29:01.940Z"); - idResponseDTO.setVersion("1.0"); - - IdResponseDTO idResponseDTO1 = new IdResponseDTO(); - idResponseDTO1.setResponse(null); - - when(registrationProcessorRestClientService.getApi(any(), any(), anyString(), any(), any())) - .thenReturn(idResponseDTO); - - when(idrepoDraftService.idrepoUpdateDraft(anyString(), any(), any())).thenReturn(idResponseDTO1); - MessageDTO result = uinGeneratorStage.process(messageDTO); - assertFalse(result.getIsValid()); - assertFalse(result.getInternalError()); - } - - - @Test - public void testUinReActivationWithStatusAsAny() throws Exception { - - Map fieldMaps = new HashMap<>(); - fieldMaps.put("UIN", "123456"); - fieldMaps.put("name", "mono"); - fieldMaps.put("email", "mono@mono.com"); - - List defaultFields = new ArrayList<>(); - defaultFields.add("name"); - defaultFields.add("dob"); - defaultFields.add("gender"); - defaultFields.add("UIN"); - - - when(packetManagerService.getFieldByMappingJsonKey(anyString(),anyString(),any(),any())).thenReturn("0.1"); - when(packetManagerService.getFields(any(), any(), any(), any())).thenReturn(fieldMaps); - when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); - - when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); - - MessageDTO messageDTO = new MessageDTO(); - messageDTO.setRid("27847657360002520181210094052"); - messageDTO.setReg_type(RegistrationType.valueOf("ACTIVATED").name()); - - IdResponseDTO idResponseDTO = new IdResponseDTO(); - ResponseDTO responseDTO = new ResponseDTO(); - idResponseDTO.setErrors(null); - idResponseDTO.setId("mosip.id.update"); - responseDTO.setStatus("ANY"); - idResponseDTO.setResponse(responseDTO); - idResponseDTO.setResponsetime("2019-01-17T06:29:01.940Z"); - idResponseDTO.setVersion("1.0"); - - IdResponseDTO idResponseDTO1 = new IdResponseDTO(); - ResponseDTO responseDTO1 = new ResponseDTO(); - idResponseDTO1.setErrors(null); - idResponseDTO1.setId("mosip.id.update"); - responseDTO1.setStatus("ANY"); - idResponseDTO1.setResponse(responseDTO1); - - idResponseDTO1.setResponsetime("2019-01-17T06:29:01.940Z"); - idResponseDTO1.setVersion("1.0"); - - when(registrationProcessorRestClientService.getApi(any(), any(), anyString(), any(), any())) - .thenReturn(idResponseDTO); - String idJsonData = "{\"identity\":{\"IDSchemaVersion\":1.0,\"UIN\":\"4215839851\"}}"; - - when(idrepoDraftService.idrepoUpdateDraft(anyString(), any(), any())).thenReturn(idResponseDTO); - when(registrationProcessorRestClientService.patchApi(any(), any(), any(), any(), any(), any())) - .thenReturn(idResponseDTO1); - - MessageDTO result = uinGeneratorStage.process(messageDTO); - assertFalse(result.getIsValid()); - assertFalse(result.getInternalError()); - } - - @Test - @Ignore - public void testUinReActivationIfNotActivatedSuccess() throws Exception { - - MessageDTO messageDTO = new MessageDTO(); - messageDTO.setRid("27847657360002520181210094052"); - messageDTO.setReg_type(RegistrationType.valueOf("ACTIVATED").name()); - - IdResponseDTO idResponseDTO = new IdResponseDTO(); - ResponseDTO responseDTO = new ResponseDTO(); - idResponseDTO.setErrors(null); - idResponseDTO.setId("mosip.id.update"); - responseDTO.setStatus("ANY"); - idResponseDTO.setResponse(responseDTO); - idResponseDTO.setResponsetime("2019-01-17T06:29:01.940Z"); - idResponseDTO.setVersion("1.0"); - - IdResponseDTO idResponseDTO1 = new IdResponseDTO(); - ResponseDTO responseDTO1 = new ResponseDTO(); - idResponseDTO1.setErrors(null); - idResponseDTO1.setId("mosip.id.update"); - responseDTO1.setStatus("ACTIVATED"); - idResponseDTO1.setResponse(responseDTO1); - - idResponseDTO1.setResponsetime("2019-01-17T06:29:01.940Z"); - idResponseDTO1.setVersion("1.0"); - - Map fieldMap = new HashMap<>(); - fieldMap.put("UIN", "123456"); - fieldMap.put("name", "mono"); - fieldMap.put("email", "mono@mono.com"); - - List defaultFields = new ArrayList<>(); - defaultFields.add("name"); - defaultFields.add("dob"); - defaultFields.add("gender"); - defaultFields.add("UIN"); - - when(idrepoDraftService.idrepoUpdateDraft(anyString(), any(), any())).thenReturn(idResponseDTO); - when(packetManagerService.getFields(any(), any(), any(), any())).thenReturn(fieldMap); - - when(packetManagerService.getFieldByMappingJsonKey(anyString(),anyString(),any(),any())).thenReturn("0.1"); - when(packetManagerService.getFields(anyString(),anyList(),anyString(),any())).thenReturn(fieldMap); - when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); - - when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); - - when(registrationProcessorRestClientService.getApi(any(), any(), anyString(), any(), any())) - .thenReturn(idResponseDTO); - - when(registrationProcessorRestClientService.patchApi(any(), any(), any(), any(), any(), any())) - .thenReturn(idResponseDTO1); - - MessageDTO result = uinGeneratorStage.process(messageDTO); - assertTrue(result.getIsValid()); - assertFalse(result.getInternalError()); - } - @Test - public void testUinReActivationIfNotGotActivatedStaus() throws Exception { - - Map fieldMap = new HashMap<>(); - fieldMap.put("UIN", "123456"); - fieldMap.put("name", "mono"); - fieldMap.put("email", "mono@mono.com"); - - List defaultFields = new ArrayList<>(); - defaultFields.add("name"); - defaultFields.add("dob"); - defaultFields.add("gender"); - defaultFields.add("UIN"); - - - when(packetManagerService.getFieldByMappingJsonKey(anyString(),anyString(),any(),any())).thenReturn("0.1"); - when(packetManagerService.getFields(any(), any(), any(), any())).thenReturn(fieldMap); - when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); - - when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); - - MessageDTO messageDTO = new MessageDTO(); - messageDTO.setRid("27847657360002520181210094052"); - messageDTO.setReg_type(RegistrationType.valueOf("ACTIVATED").name()); - - IdResponseDTO idResponseDTO = new IdResponseDTO(); - ResponseDTO responseDTO = new ResponseDTO(); - idResponseDTO.setErrors(null); - idResponseDTO.setId("mosip.id.update"); - responseDTO.setStatus("ANY"); - idResponseDTO.setResponse(responseDTO); - idResponseDTO.setResponsetime("2019-01-17T06:29:01.940Z"); - idResponseDTO.setVersion("1.0"); - - IdResponseDTO idResponseDTO1 = new IdResponseDTO(); - ResponseDTO responseDTO1 = new ResponseDTO(); - idResponseDTO1.setErrors(null); - idResponseDTO1.setId("mosip.id.update"); - responseDTO1.setStatus("ANY"); - idResponseDTO1.setResponse(responseDTO1); - idResponseDTO1.setResponsetime("2019-01-17T06:29:01.940Z"); - idResponseDTO1.setVersion("1.0"); - - when(registrationProcessorRestClientService.getApi(any(), any(), anyString(), any(), any())) - .thenReturn(idResponseDTO); - - String idJsonData = "{\"identity\":{\"IDSchemaVersion\":1.0,\"UIN\":4215839851}}"; - - when(idrepoDraftService.idrepoUpdateDraft(anyString(), any(), any())).thenReturn(idResponseDTO); - when(registrationProcessorRestClientService.patchApi(any(), any(), any(), any(), any(), any())) - .thenReturn(idResponseDTO1); - MessageDTO result = uinGeneratorStage.process(messageDTO); - assertFalse(result.getIsValid()); - assertFalse(result.getInternalError()); - } - - @Test - public void testUinReActivationFailure() throws Exception { - Map fieldMap = new HashMap<>(); - fieldMap.put("UIN", "123456"); - fieldMap.put("name", "mono"); - fieldMap.put("email", "mono@mono.com"); - - List defaultFields = new ArrayList<>(); - defaultFields.add("name"); - defaultFields.add("dob"); - defaultFields.add("gender"); - defaultFields.add("UIN"); - - - when(packetManagerService.getFieldByMappingJsonKey(anyString(),anyString(),any(),any())).thenReturn("0.1"); - when(packetManagerService.getFields(any(),any(),any(),any())).thenReturn(fieldMap); - when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); - - when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); - - MessageDTO messageDTO = new MessageDTO(); - messageDTO.setRid("27847657360002520181210094052"); - messageDTO.setReg_type(RegistrationType.valueOf("ACTIVATED").name()); - - IdResponseDTO idResponseDTO = new IdResponseDTO(); - ResponseDTO responseDTO = new ResponseDTO(); - idResponseDTO.setErrors(null); - idResponseDTO.setId("mosip.id.update"); - responseDTO.setStatus("ANY"); - idResponseDTO.setResponse(responseDTO); - idResponseDTO.setResponsetime("2019-01-17T06:29:01.940Z"); - idResponseDTO.setVersion("1.0"); - - IdResponseDTO idResponseDTO1 = new IdResponseDTO(); - List errors = new ArrayList<>(); - ErrorDTO errorDTO = new ErrorDTO("tets", "error"); - errors.add(errorDTO); - idResponseDTO1.setErrors(errors); - idResponseDTO1.setId("mosip.id.update"); - idResponseDTO1.setResponse(null); - idResponseDTO1.setResponsetime("2019-01-17T06:29:01.940Z"); - idResponseDTO1.setVersion("1.0"); - - when(registrationProcessorRestClientService.getApi(any(), any(), anyString(), any(), any())) - .thenReturn(idResponseDTO); - - String idJsonData = "{\"identity\":{\"IDSchemaVersion\":1.0,\"UIN\":4215839851}}"; - - when(idrepoDraftService.idrepoUpdateDraft(anyString(), any(), any())).thenReturn(idResponseDTO); - when(registrationProcessorRestClientService.patchApi(any(), any(), any(), any(), any(), any())) - .thenReturn(idResponseDTO1); - Mockito.when(registrationStatusMapperUtil - .getStatusCode(RegistrationExceptionTypeCode.PACKET_UIN_GENERATION_REPROCESS)).thenReturn("REPROCESS"); - MessageDTO result = uinGeneratorStage.process(messageDTO); - assertFalse(result.getIsValid()); - assertFalse(result.getInternalError()); - } - - @Test - public void testExceptionInProcessTest() throws Exception { - ApisResourceAccessException exp = new ApisResourceAccessException( - HibernateErrorCode.ERR_DATABASE.getErrorCode()); - - when(registrationProcessorRestClientService.getApi(any(), any(), anyString(), any(), any())).thenReturn(exp); - Mockito.when(registrationStatusMapperUtil - .getStatusCode(RegistrationExceptionTypeCode.PACKET_UIN_GENERATION_REPROCESS)).thenReturn("REPROCESS"); - - MessageDTO messageDTO = new MessageDTO(); - messageDTO.setRid("27847657360002520181210094052"); - MessageDTO result = uinGeneratorStage.process(messageDTO); - assertTrue(result.getInternalError()); - assertTrue(result.getIsValid()); - } - - @Test - public void testApiResourceExceptionInSendIdRepoTest() throws Exception { - - ApisResourceAccessException exp = new ApisResourceAccessException( - HibernateErrorCode.ERR_DATABASE.getErrorCode()); - String Str = "{\"uin\":\"6517036426\"}"; - - when(registrationProcessorRestClientService.postApi(any(), any(), any(), any(), any())).thenThrow(exp); - Mockito.when(registrationStatusMapperUtil - .getStatusCode(RegistrationExceptionTypeCode.PACKET_UIN_GENERATION_REPROCESS)).thenReturn("REPROCESS"); - - MessageDTO messageDTO = new MessageDTO(); - messageDTO.setRid("27847657360002520181210094052"); - MessageDTO result = uinGeneratorStage.process(messageDTO); - assertTrue(result.getInternalError()); - assertTrue(result.getIsValid()); - } - - @Test - public void testApiResourceExceptionInUpdateIdRepoTest() throws Exception { - ApisResourceAccessException exp = new ApisResourceAccessException( - HibernateErrorCode.ERR_DATABASE.getErrorCode()); - - when(registrationProcessorRestClientService.postApi(any(), any(), any(), any(), any())).thenThrow(exp); - MessageDTO messageDTO = new MessageDTO(); - messageDTO.setRid("27847657360002520181210094052"); - Mockito.when(registrationStatusMapperUtil - .getStatusCode(RegistrationExceptionTypeCode.PACKET_UIN_GENERATION_REPROCESS)).thenReturn("REPROCESS"); - MessageDTO result = uinGeneratorStage.process(messageDTO); - assertTrue(result.getInternalError()); - assertTrue(result.getIsValid()); - } - - @Test - public void deactivateTestSuccess() throws ApisResourceAccessException, IOException, JSONException, - JsonProcessingException, PacketManagerException, IdrepoDraftException, IdrepoDraftReprocessableException { - - Map fieldMap = new HashMap<>(); - fieldMap.put("UIN", "123456"); - fieldMap.put("name", "mono"); - fieldMap.put("email", "mono@mono.com"); - - List defaultFields = new ArrayList<>(); - defaultFields.add("name"); - defaultFields.add("dob"); - defaultFields.add("gender"); - defaultFields.add("UIN"); - - when(packetManagerService.getFields(any(), any(), any(), any())).thenReturn(fieldMap); - - - when(packetManagerService.getFieldByMappingJsonKey(anyString(),anyString(),any(),any())).thenReturn("0.1"); - when(packetManagerService.getFields(anyString(),anyList(),anyString(),any())).thenReturn(fieldMap); - when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); - - when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); - MessageDTO messageDTO = new MessageDTO(); - messageDTO.setRid("10031100110005020190313110030"); - messageDTO.setReg_type(RegistrationType.valueOf("DEACTIVATED").name()); - IdResponseDTO responsedto = new IdResponseDTO(); - String idJson = "{\"identity\":{\"IDSchemaVersion\":1.0,\"UIN\":\"4215839851\"}}"; - InputStream idJsonStream1 = new ByteArrayInputStream(idJson.getBytes(StandardCharsets.UTF_8)); - - IdResponseDTO idResponseDTO = new IdResponseDTO(); - ResponseDTO responseDTO = new ResponseDTO(); - idResponseDTO.setErrors(null); - idResponseDTO.setId("mosip.id.update"); - responseDTO.setStatus("DEACTIVATED"); - idResponseDTO.setResponse(responseDTO); - idResponseDTO.setResponsetime("2019-03-12T06:49:30.779Z"); - idResponseDTO.setVersion("1.0"); - - when(idrepoDraftService.idrepoUpdateDraft(anyString(), any(), any())).thenReturn(idResponseDTO); - when(registrationProcessorRestClientService.getApi(any(), any(), anyString(), any(), any())) - .thenReturn(responsedto); - when(registrationProcessorRestClientService.patchApi(any(), any(), any(), any(), any(), any())) - .thenReturn(idResponseDTO); - - MessageDTO result = uinGeneratorStage.process(messageDTO); - assertTrue(result.getIsValid()); - assertFalse(result.getInternalError()); - } - - @Test - public void checkIsUinDeactivatedSuccess() throws ApisResourceAccessException, IOException, JSONException, JsonProcessingException, PacketManagerException { - - Map fieldMap = new HashMap<>(); - fieldMap.put("UIN", "123456"); - fieldMap.put("name", "mono"); - fieldMap.put("email", "mono@mono.com"); - - List defaultFields = new ArrayList<>(); - defaultFields.add("name"); - defaultFields.add("dob"); - defaultFields.add("gender"); - defaultFields.add("UIN"); - - - when(packetManagerService.getFieldByMappingJsonKey(anyString(),anyString(),any(),any())).thenReturn("0.1"); - when(packetManagerService.getFields(any(), any(), any(), any())).thenReturn(fieldMap); - when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); - - when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); - - MessageDTO messageDTO = new MessageDTO(); - messageDTO.setRid("10031100110005020190313110030"); - messageDTO.setReg_type(RegistrationType.valueOf("DEACTIVATED").name()); - - String idJson = "{\"identity\":{\"IDSchemaVersion\":1.0,\"UIN\":4215839851}}"; - ResponseDTO responseDTO = new ResponseDTO(); - - responseDTO.setStatus("DEACTIVATED"); - IdResponseDTO responsedto = new IdResponseDTO(); - responsedto.setResponse(responseDTO); - - when(registrationProcessorRestClientService.getApi(any(), any(), anyString(), any(), any(Class.class))) - .thenReturn(responsedto); - MessageDTO result = uinGeneratorStage.process(messageDTO); - assertFalse(result.getIsValid()); - assertFalse(result.getInternalError()); - } - @Test - public void deactivateTestWithDeactivate() throws ApisResourceAccessException, IOException, JSONException, - JsonProcessingException, PacketManagerException, IdrepoDraftException, IdrepoDraftReprocessableException { - Map fieldMap = new HashMap<>(); - fieldMap.put("UIN", "123456"); - fieldMap.put("name", "mono"); - fieldMap.put("email", "mono@mono.com"); - - List defaultFields = new ArrayList<>(); - defaultFields.add("name"); - defaultFields.add("dob"); - defaultFields.add("gender"); - defaultFields.add("UIN"); - - - when(packetManagerService.getFieldByMappingJsonKey(anyString(),anyString(),any(),any())).thenReturn("0.1"); - when(packetManagerService.getFields(any(), any(), any(), any())).thenReturn(fieldMap); - when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); - - when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); - - MessageDTO messageDTO = new MessageDTO(); - messageDTO.setRid("10031100110005020190313110030"); - messageDTO.setReg_type(RegistrationType.valueOf("DEACTIVATED").name()); - IdResponseDTO responsedto = new IdResponseDTO(); - ResponseDTO responseDTO1 = new ResponseDTO(); - responseDTO1.setStatus("DEACTIVATED"); - responsedto.setResponse(responseDTO1); - String idJson = "{\"identity\":{\"IDSchemaVersion\":1.0,\"UIN\":\"4215839851\"}}"; - InputStream idJsonStream1 = new ByteArrayInputStream(idJson.getBytes(StandardCharsets.UTF_8)); - - IdResponseDTO idResponseDTO = new IdResponseDTO(); - ResponseDTO responseDTO = new ResponseDTO(); - idResponseDTO.setErrors(null); - idResponseDTO.setId("mosip.id.update"); - responseDTO.setStatus("DEACTIVATED"); - idResponseDTO.setResponse(responseDTO); - idResponseDTO.setResponsetime("2019-03-12T06:49:30.779Z"); - idResponseDTO.setVersion("1.0"); - - when(idrepoDraftService.idrepoUpdateDraft(anyString(), any(), any())).thenReturn(idResponseDTO); - when(registrationProcessorRestClientService.getApi(any(), any(), anyString(), any(), any())) - .thenReturn(responsedto); - when(registrationProcessorRestClientService.patchApi(any(), any(), any(), any(), any(), any())) - .thenReturn(idResponseDTO); - MessageDTO result = uinGeneratorStage.process(messageDTO); - assertFalse(result.getIsValid()); - assertFalse(result.getInternalError()); - } - - @Test - public void deactivateTestWithNullResponseDTO() - throws ApisResourceAccessException, PacketManagerException, IOException, JsonProcessingException, - JSONException, IdrepoDraftException, IdrepoDraftReprocessableException { - Map fieldMap = new HashMap<>(); - fieldMap.put("UIN", "123456"); - fieldMap.put("name", "mono"); - fieldMap.put("email", "mono@mono.com"); - - List defaultFields = new ArrayList<>(); - defaultFields.add("name"); - defaultFields.add("dob"); - defaultFields.add("gender"); - defaultFields.add("UIN"); - - - when(packetManagerService.getFieldByMappingJsonKey(anyString(),anyString(),any(),any())).thenReturn("0.1"); - when(packetManagerService.getFields(any(), any(), any(), any())).thenReturn(fieldMap); - when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); - - when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); - MessageDTO messageDTO = new MessageDTO(); - messageDTO.setRid("10031100110005020190313110030"); - messageDTO.setReg_type(RegistrationType.valueOf("DEACTIVATED").name()); - IdResponseDTO responsedto = new IdResponseDTO(); - String idJson = "{\"identity\":{\"IDSchemaVersion\":1.0,\"UIN\":\"4215839851\"}}"; - InputStream idJsonStream1 = new ByteArrayInputStream(idJson.getBytes(StandardCharsets.UTF_8)); - - IdResponseDTO idResponseDTO = new IdResponseDTO(); - ResponseDTO responseDTO = new ResponseDTO(); - idResponseDTO.setErrors(null); - idResponseDTO.setId("mosip.id.update"); - responseDTO.setStatus("DEACTIVATED"); - idResponseDTO.setResponse(null); - idResponseDTO.setResponsetime("2019-03-12T06:49:30.779Z"); - idResponseDTO.setVersion("1.0"); - - when(idrepoDraftService.idrepoUpdateDraft(anyString(), any(), any())).thenReturn(idResponseDTO); - when(registrationProcessorRestClientService.getApi(any(), any(), anyString(), any(), any())) - .thenReturn(responsedto); - when(registrationProcessorRestClientService.patchApi(any(), any(), any(), any(), any(), any())) - .thenReturn(idResponseDTO); - Mockito.when(registrationStatusMapperUtil - .getStatusCode(RegistrationExceptionTypeCode.PACKET_UIN_GENERATION_REPROCESS)).thenReturn("REPROCESS"); - MessageDTO result = uinGeneratorStage.process(messageDTO); - assertFalse(result.getIsValid()); - assertFalse(result.getInternalError()); - } - - @Test - public void deactivateTestForExistingUinTestSuccess() - throws ApisResourceAccessException, PacketManagerException, IOException, JsonProcessingException, - JSONException, IdrepoDraftException, IdrepoDraftReprocessableException { - MessageDTO messageDTO = new MessageDTO(); - messageDTO.setRid("10031100110005020190313110030"); - messageDTO.setReg_type(RegistrationType.valueOf("DEACTIVATED").name()); - - ErrorDTO errorDto = new ErrorDTO(); - errorDto.setErrorCode("KER-IDR-001"); - errorDto.setMessage("Record already Exists in DB"); - - List errors = new ArrayList<>(); - errors.add(errorDto); - - IdResponseDTO idResponseDTO = new IdResponseDTO(); - ResponseDTO responseDTO = new ResponseDTO(); - idResponseDTO.setErrors(errors); - idResponseDTO.setId("mosip.id.update"); - ResponseDTO responseDTO1 = new ResponseDTO(); - responseDTO1.setStatus("DEACTIVATED"); - idResponseDTO.setResponse(responseDTO1); - idResponseDTO.setResponsetime("2019-03-12T06:49:30.779Z"); - idResponseDTO.setVersion("1.0"); - - Map fieldMap = new HashMap<>(); - fieldMap.put("UIN", "123456"); - fieldMap.put("name", "mono"); - fieldMap.put("email", "mono@mono.com"); - - List defaultFields = new ArrayList<>(); - defaultFields.add("name"); - defaultFields.add("dob"); - defaultFields.add("gender"); - defaultFields.add("UIN"); - - when(idrepoDraftService.idrepoUpdateDraft(anyString(), any(), any())).thenReturn(idResponseDTO); - - when(packetManagerService.getFieldByMappingJsonKey(anyString(),anyString(),any(),any())).thenReturn("0.1"); - when(packetManagerService.getFields(any(), any(), any(), any())).thenReturn(fieldMap); - when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); - - when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); - when(registrationProcessorRestClientService.patchApi(any(), any(), any(), any(), any(), any())) - .thenReturn(idResponseDTO); - when(registrationProcessorRestClientService.getApi(any(), any(), anyString(), any(), any())) - .thenReturn(idResponseDTO); - MessageDTO result = uinGeneratorStage.process(messageDTO); - assertFalse(result.getIsValid()); - assertFalse(result.getInternalError()); - } - - @Test - public void deactivateTestFailure() throws ApisResourceAccessException, PacketManagerException, IOException, - JsonProcessingException, JSONException, IdrepoDraftException, IdrepoDraftReprocessableException { - - Map fieldMap = new HashMap<>(); - fieldMap.put("UIN", "123456"); - fieldMap.put("name", "mono"); - fieldMap.put("email", "mono@mono.com"); - - List defaultFields = new ArrayList<>(); - defaultFields.add("name"); - defaultFields.add("dob"); - defaultFields.add("gender"); - defaultFields.add("UIN"); - - - when(packetManagerService.getFieldByMappingJsonKey(anyString(),anyString(),any(),any())).thenReturn("0.1"); - when(packetManagerService.getFields(any(),any(),any(),any())).thenReturn(fieldMap); - when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); - - when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); - - ApisResourceAccessException exp = new ApisResourceAccessException( - HibernateErrorCode.ERR_DATABASE.getErrorCode()); - - MessageDTO messageDTO = new MessageDTO(); - messageDTO.setRid("10031100110005020190313110030"); - messageDTO.setReg_type(RegistrationType.valueOf("DEACTIVATED").name()); - - String idJson = "{\"identity\":{\"IDSchemaVersion\":1.0,\"UIN\":4215839851}}"; - InputStream idJsonStream1 = new ByteArrayInputStream(idJson.getBytes(StandardCharsets.UTF_8)); - - ErrorDTO errorDto = new ErrorDTO(); - errorDto.setErrorCode("KER-IDR-001"); - errorDto.setMessage("Record already Exists in DB"); - - List errors = new ArrayList<>(); - errors.add(errorDto); - - IdResponseDTO idResponseDTO = new IdResponseDTO(); - ResponseDTO responseDTO = new ResponseDTO(); - idResponseDTO.setErrors(errors); - idResponseDTO.setId("mosip.id.update"); - responseDTO.setStatus("DEACTIVATED"); - idResponseDTO.setResponse(responseDTO); - idResponseDTO.setResponsetime("2019-03-12T06:49:30.779Z"); - idResponseDTO.setVersion("1.0"); - - when(idrepoDraftService.idrepoUpdateDraft(anyString(), any(), any())).thenReturn(idResponseDTO); - when(registrationProcessorRestClientService.getApi(any(), any(), anyString(), any(), any())) - .thenReturn(idResponseDTO); - - when(registrationProcessorRestClientService.patchApi(any(), any(), any(), any(), any(), any())) - .thenThrow(exp); - Mockito.when(registrationStatusMapperUtil - .getStatusCode(RegistrationExceptionTypeCode.PACKET_UIN_GENERATION_REPROCESS)).thenReturn("REPROCESS"); - MessageDTO result = uinGeneratorStage.process(messageDTO); - assertFalse(result.getInternalError()); - assertFalse(result.getIsValid()); - } - - @Test - public void apisResourceAccessExceptionTest() - throws ApisResourceAccessException, IOException, IdrepoDraftException, IdrepoDraftReprocessableException { - - ApisResourceAccessException apisResourceAccessException = Mockito.mock(ApisResourceAccessException.class); - HttpServerErrorException httpServerErrorException = new HttpServerErrorException( - HttpStatus.INTERNAL_SERVER_ERROR, "KER-FSE-004:encrypted data is corrupted or not base64 encoded"); - when(apisResourceAccessException.getCause()).thenReturn(httpServerErrorException); - - MessageDTO messageDTO = new MessageDTO(); - messageDTO.setRid("10031100110005020190313110030"); - messageDTO.setReg_type(RegistrationType.valueOf("DEACTIVATED").name()); - - when(idrepoDraftService.idrepoUpdateDraft(anyString(), any(), any())).thenThrow(apisResourceAccessException); - Mockito.when(registrationStatusMapperUtil - .getStatusCode(RegistrationExceptionTypeCode.APIS_RESOURCE_ACCESS_EXCEPTION)).thenReturn("REPROCESS"); - when(utility.getRegistrationProcessorMappingJson(MappingJsonConstants.IDENTITY)).thenReturn(identityObj); - when(utility.getRegistrationProcessorMappingJson(MappingJsonConstants.DOCUMENT)).thenReturn(documentObj); - - MessageDTO result = uinGeneratorStage.process(messageDTO); - assertTrue(result.getInternalError()); - assertTrue(result.getIsValid()); - } - - - @Test - public void testHttpServerErrorException() throws Exception { - - ApisResourceAccessException apisResourceAccessException = Mockito.mock(ApisResourceAccessException.class); - HttpServerErrorException httpServerErrorException = new HttpServerErrorException( - HttpStatus.INTERNAL_SERVER_ERROR, "KER-FSE-004:encrypted data is corrupted or not base64 encoded"); - when(apisResourceAccessException.getCause()).thenReturn(httpServerErrorException); - MessageDTO messageDTO = new MessageDTO(); - messageDTO.setRid("27847657360002520181210094052"); - messageDTO.setReg_type(RegistrationType.valueOf("ACTIVATED").name()); - - when(idrepoDraftService.idrepoUpdateDraft(anyString(), any(), any())).thenThrow(apisResourceAccessException); - Mockito.when(registrationStatusMapperUtil - .getStatusCode(RegistrationExceptionTypeCode.APIS_RESOURCE_ACCESS_EXCEPTION)).thenReturn("REPROCESS"); - when(utility.getRegistrationProcessorMappingJson(MappingJsonConstants.IDENTITY)).thenReturn(identityObj); - when(utility.getRegistrationProcessorMappingJson(MappingJsonConstants.DOCUMENT)).thenReturn(documentObj); - - MessageDTO result = uinGeneratorStage.process(messageDTO); - assertTrue(result.getInternalError()); - assertTrue(result.getIsValid()); - - } - @Test - public void testHttpClientErrorException() throws Exception { - - ApisResourceAccessException apisResourceAccessException = Mockito.mock(ApisResourceAccessException.class); - HttpClientErrorException httpClientErrorException = new HttpClientErrorException( - HttpStatus.INTERNAL_SERVER_ERROR, "KER-FSE-004:encrypted data is corrupted or not base64 encoded"); - when(apisResourceAccessException.getCause()).thenReturn(httpClientErrorException); - MessageDTO messageDTO = new MessageDTO(); - messageDTO.setRid("27847657360002520181210094052"); - messageDTO.setReg_type(RegistrationType.valueOf("ACTIVATED").name()); - String idJsonData = "{\"identity\":{\"IDSchemaVersion\":1.0,\"UIN\":\"4215839851\"}}"; - - when(idrepoDraftService.idrepoUpdateDraft(anyString(), any(), any())).thenThrow(apisResourceAccessException); - when(utility.getRegistrationProcessorMappingJson(MappingJsonConstants.IDENTITY)).thenReturn(identityObj); - when(utility.getRegistrationProcessorMappingJson(MappingJsonConstants.DOCUMENT)).thenReturn(documentObj); - - Mockito.when(registrationStatusMapperUtil - .getStatusCode(RegistrationExceptionTypeCode.APIS_RESOURCE_ACCESS_EXCEPTION)).thenReturn("REPROCESS"); - MessageDTO result = uinGeneratorStage.process(messageDTO); - assertTrue(result.getInternalError()); - assertTrue(result.getIsValid()); - - } - - @Test - public void testUinGenerationHttpClientErrorException() throws Exception { - MessageDTO messageDTO = new MessageDTO(); - messageDTO.setRid("27847657360002520181210094052"); - String str = "{\"id\":\"mosip.id.read\",\"version\":\"1.0\",\"responsetime\":\"2019-04-05\",\"metadata\":null,\"response\":{\"uin\":\"2812936908\"},\"errors\":[{\"errorCode\":null,\"errorMessage\":null}]}"; - - ApisResourceAccessException apisResourceAccessException = Mockito.mock(ApisResourceAccessException.class); - HttpClientErrorException httpClientErrorException = new HttpClientErrorException( - HttpStatus.INTERNAL_SERVER_ERROR, "KER-FSE-004:encrypted data is corrupted or not base64 encoded"); - when(apisResourceAccessException.getCause()).thenReturn(httpClientErrorException); - when(idrepoDraftService.idrepoUpdateDraft(anyString(), any(), any())).thenThrow(apisResourceAccessException); - when(utility.getRegistrationProcessorMappingJson(MappingJsonConstants.IDENTITY)).thenReturn(identityObj); - when(utility.getRegistrationProcessorMappingJson(MappingJsonConstants.DOCUMENT)).thenReturn(documentObj); - - messageDTO.setReg_type(RegistrationType.NEW.name()); - Mockito.when(registrationStatusMapperUtil - .getStatusCode(RegistrationExceptionTypeCode.APIS_RESOURCE_ACCESS_EXCEPTION)).thenReturn("REPROCESS"); - MessageDTO result = uinGeneratorStage.process(messageDTO); - assertTrue(result.getInternalError()); - assertTrue(result.getIsValid()); - - } - - @Test - public void testUinGenerationHttpServerErrorException() throws Exception { - MessageDTO messageDTO = new MessageDTO(); - messageDTO.setRid("27847657360002520181210094052"); - String str = "{\"id\":\"mosip.id.read\",\"version\":\"1.0\",\"responsetime\":\"2019-04-05\",\"metadata\":null,\"response\":{\"uin\":\"2812936908\"},\"errors\":[{\"errorCode\":null,\"errorMessage\":null}]}"; - - ApisResourceAccessException apisResourceAccessException = Mockito.mock(ApisResourceAccessException.class); - HttpServerErrorException httpServerErrorException = new HttpServerErrorException( - HttpStatus.INTERNAL_SERVER_ERROR, "KER-FSE-004:encrypted data is corrupted or not base64 encoded"); - when(apisResourceAccessException.getCause()).thenReturn(httpServerErrorException); - - when(idrepoDraftService.idrepoUpdateDraft(anyString(), any(), any())).thenThrow(apisResourceAccessException); - Mockito.when(registrationStatusMapperUtil - .getStatusCode(RegistrationExceptionTypeCode.APIS_RESOURCE_ACCESS_EXCEPTION)).thenReturn("REPROCESS"); - messageDTO.setReg_type(RegistrationType.NEW.name()); - when(utility.getRegistrationProcessorMappingJson(MappingJsonConstants.IDENTITY)).thenReturn(identityObj); - when(utility.getRegistrationProcessorMappingJson(MappingJsonConstants.DOCUMENT)).thenReturn(documentObj); - - MessageDTO result = uinGeneratorStage.process(messageDTO); - assertTrue(result.getInternalError()); - assertTrue(result.getIsValid()); - } - - - @Test - public void clientErrorExceptionTest() - throws ApisResourceAccessException, IOException, IdrepoDraftException, IdrepoDraftReprocessableException { - - ApisResourceAccessException apisResourceAccessException = Mockito.mock(ApisResourceAccessException.class); - HttpClientErrorException httpErrorErrorException = new HttpClientErrorException( - HttpStatus.INTERNAL_SERVER_ERROR, "KER-FSE-004:encrypted data is corrupted or not base64 encoded"); - when(apisResourceAccessException.getCause()).thenReturn(httpErrorErrorException); - - MessageDTO messageDTO = new MessageDTO(); - messageDTO.setRid("10031100110005020190313110030"); - messageDTO.setReg_type(RegistrationType.valueOf("DEACTIVATED").name()); - - when(idrepoDraftService.idrepoUpdateDraft(anyString(), any(), any())).thenThrow(apisResourceAccessException); - Mockito.when(registrationStatusMapperUtil - .getStatusCode(RegistrationExceptionTypeCode.APIS_RESOURCE_ACCESS_EXCEPTION)).thenReturn("REPROCESS"); - when(utility.getRegistrationProcessorMappingJson(MappingJsonConstants.IDENTITY)).thenReturn(identityObj); - when(utility.getRegistrationProcessorMappingJson(MappingJsonConstants.DOCUMENT)).thenReturn(documentObj); - - MessageDTO result = uinGeneratorStage.process(messageDTO); - assertTrue(result.getInternalError()); - assertTrue(result.getIsValid()); - } - - @Test - public void testIOException() { - IOException exception = new IOException("File not found"); - - Mockito.when(registrationStatusMapperUtil - .getStatusCode(RegistrationExceptionTypeCode.PACKET_UIN_GENERATION_REPROCESS)).thenReturn("REPROCESS"); - MessageDTO messageDTO = new MessageDTO(); - messageDTO.setRid("27847657360002520181210094052"); - messageDTO.setReg_type(RegistrationType.valueOf("DEACTIVATED").name()); - MessageDTO result = uinGeneratorStage.process(messageDTO); - assertTrue(result.getInternalError()); - assertTrue(result.getIsValid()); - } - - - @Test - public void testDeployVerticle() { - uinGeneratorStage.deployVerticle(); - } - - @Test - @Ignore - public void testApiResourceException() - throws ApisResourceAccessException, IOException, IdrepoDraftException, IdrepoDraftReprocessableException { - MessageDTO messageDTO = new MessageDTO(); - messageDTO.setRid("10031100110005020190313110030"); - messageDTO.setReg_type(RegistrationType.valueOf("DEACTIVATED").name()); - IdResponseDTO responsedto = new IdResponseDTO(); - String idJson = "{\"identity\":{\"IDSchemaVersion\":1.0,\"UIN\":\"4215839851\"}}"; - - IdResponseDTO idResponseDTO = new IdResponseDTO(); - ResponseDTO responseDTO = new ResponseDTO(); - idResponseDTO.setErrors(null); - idResponseDTO.setId("mosip.id.update"); - responseDTO.setStatus("DEACTIVATED"); - idResponseDTO.setResponse(responseDTO); - idResponseDTO.setResponsetime("2019-03-12T06:49:30.779Z"); - idResponseDTO.setVersion("1.0"); - - when(idrepoDraftService.idrepoUpdateDraft(anyString(), any(), any())).thenReturn(idResponseDTO); - when(registrationProcessorRestClientService.getApi(any(), any(), anyString(), any(), any())) - .thenReturn(responsedto); - when(registrationProcessorRestClientService.patchApi(any(), any(), any(), any(), any(), any())) - .thenReturn(idResponseDTO); - - MessageDTO result = uinGeneratorStage.process(messageDTO); - assertTrue(result.getInternalError()); - assertTrue(result.getIsValid()); - } - - @Test - public void testApisResourceAccessExceptionPostApi() - throws ApisResourceAccessException, IOException, IdrepoDraftException, IdrepoDraftReprocessableException { - ApisResourceAccessException exc = new ApisResourceAccessException(); - MessageDTO messageDTO = new MessageDTO(); - messageDTO.setRid("27847657360002520181210094052"); - - when(registrationProcessorRestClientService.putApi(any(), any(), any(), any(), any(), any(), any())) - .thenThrow(exc); - - IdResponseDTO idResponseDTO = new IdResponseDTO(); - ResponseDTO responseDTO = null; - idResponseDTO.setErrors(null); - idResponseDTO.setId("mosip.id.update"); - idResponseDTO.setResponse(responseDTO); - idResponseDTO.setResponsetime("2019-01-17T06:29:01.940Z"); - idResponseDTO.setVersion("1.0"); - - when(idrepoDraftService.idrepoUpdateDraft(anyString(), any(), any())).thenReturn(idResponseDTO); - when(registrationProcessorRestClientService.postApi(any(), any(), any(), any(), any())) - .thenReturn(idResponseDTO); - Mockito.when(registrationStatusMapperUtil - .getStatusCode(RegistrationExceptionTypeCode.PACKET_UIN_GENERATION_REPROCESS)).thenReturn("REPROCESS"); - MessageDTO result = uinGeneratorStage.process(messageDTO); - assertTrue(result.getInternalError()); - assertTrue(result.getIsValid()); - } - - @Test - public void testLinkSuccessForLostUin() throws Exception { - Map fieldMap = new HashMap<>(); - fieldMap.put("UIN", "123456"); - fieldMap.put("name", "mono"); - fieldMap.put("email", "mono@mono.com"); - - List defaultFields = new ArrayList<>(); - defaultFields.add("name"); - defaultFields.add("dob"); - defaultFields.add("gender"); - defaultFields.add("UIN"); - - - when(packetManagerService.getFieldByMappingJsonKey(anyString(),anyString(),any(),any())).thenReturn("0.1"); - when(packetManagerService.getFields(anyString(),anyList(),anyString(),any())).thenReturn(fieldMap); - when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); - - when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); - MessageDTO messageDTO = new MessageDTO(); - messageDTO.setRid("27847657360002520181210094052"); - messageDTO.setReg_type(RegistrationType.LOST.name()); - String str = "{\"id\":\"mosip.id.read\",\"version\":\"1.0\",\"responsetime\":\"2019-04-05\",\"metadata\":null,\"response\":{\"uin\":\"2812936908\"},\"errors\":[{\"errorCode\":null,\"errorMessage\":null}]}"; - String response = "{\"timestamp\":1553771083721,\"status\":404,\"errors\":[{\"errorCode\":\"KER-UIG-004\",\"errorMessage\":\"Given UIN is not in ISSUED status\"}]}"; - - - when(registrationProcessorRestClientService.putApi(any(), any(), any(), any(), any(), any(), any())) - .thenReturn(response); - - IdResponseDTO idResponseDTO = new IdResponseDTO(); - ResponseDTO responseDTO = new ResponseDTO(); - idResponseDTO.setErrors(null); - idResponseDTO.setId("mosip.id.update"); - responseDTO.setStatus("ACTIVATED"); - idResponseDTO.setResponse(responseDTO); - idResponseDTO.setResponsetime("2019-01-17T06:29:01.940Z"); - idResponseDTO.setVersion("1.0"); - - when(idrepoDraftService.idrepoUpdateDraft(anyString(), any(), any())).thenReturn(idResponseDTO); - when(registrationProcessorRestClientService.postApi(any(), any(), any(), any(), any(Class.class))) - .thenReturn(idResponseDTO); - when(registrationProcessorRestClientService.getApi(any(), any(), anyString(), any(), any(Class.class))) - .thenReturn(idResponseDTO); - when( - registrationProcessorRestClientService.patchApi(any(), any(), any(), any(), any(), any(Class.class))) - .thenReturn(idResponseDTO); - when(regLostUinDetEntity.getLostUinMatchedRegIdByWorkflowId(any())).thenReturn("27847657360002520181210094052"); - MessageDTO result = uinGeneratorStage.process(messageDTO); - assertFalse(result.getInternalError()); - assertTrue(result.getIsValid()); - } - - @Test - public void testLinkSuccessForLostUinAndUpdateContactInfo() throws Exception { - Map fieldMap = new HashMap<>(); - fieldMap.put("UIN", "123456"); - fieldMap.put("name", "mono"); - fieldMap.put("email", "mono@mono.com"); - - List defaultFields = new ArrayList<>(); - defaultFields.add("name"); - defaultFields.add("dob"); - defaultFields.add("gender"); - defaultFields.add("UIN"); - when(idRepoService.getUinByRid(anyString(), anyString())).thenReturn("9403107397"); - - - when(packetManagerService.getFieldByMappingJsonKey(anyString(),anyString(),any(),any())).thenReturn("0.1"); - when(packetManagerService.getFields(anyString(),anyList(),anyString(),any())).thenReturn(fieldMap); - when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); - - when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); - MessageDTO messageDTO = new MessageDTO(); - messageDTO.setRid("27847657360002520181210094052"); - messageDTO.setReg_type(RegistrationType.LOST.name()); - String str = "{\"id\":\"mosip.id.read\",\"version\":\"1.0\",\"responsetime\":\"2019-04-05\",\"metadata\":null,\"response\":{\"uin\":\"2812936908\"},\"errors\":[{\"errorCode\":null,\"errorMessage\":null}]}"; - String response = "{\"timestamp\":1553771083721,\"status\":404,\"errors\":[{\"errorCode\":\"KER-UIG-004\",\"errorMessage\":\"Given UIN is not in ISSUED status\"}]}"; - - when(utility.getRegistrationProcessorMappingJson(MappingJsonConstants.IDENTITY)).thenReturn(identityObj); - when(registrationProcessorRestClientService.putApi(any(), any(), any(), any(), any(), any(), any())) - .thenReturn(response); - - IdResponseDTO idResponseDTO = new IdResponseDTO(); - ResponseDTO responseDTO = new ResponseDTO(); - idResponseDTO.setErrors(null); - idResponseDTO.setId("mosip.id.update"); - responseDTO.setStatus("ACTIVATED"); - 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(idrepoDraftService.idrepoUpdateDraft(anyString(), any(), any())).thenReturn(idResponseDTO); - when(registrationProcessorRestClientService.postApi(any(), any(), any(), any(), any(Class.class))) - .thenReturn(idResponseDTO); - when(registrationProcessorRestClientService.getApi(any(), any(), anyString(), any(), any(Class.class))) - .thenReturn(idResponseDTO); - when( - registrationProcessorRestClientService.patchApi(any(), any(), any(), any(), any(), any(Class.class))) - .thenReturn(idResponseDTO); - when(packetManagerService.getFieldByMappingJsonKey(any(), any(), any(), any())).thenReturn("1.0"); - when(regLostUinDetEntity.getLostUinMatchedRegIdByWorkflowId(any())).thenReturn("27847657360002520181210094052"); - MessageDTO result = uinGeneratorStage.process(messageDTO); - assertFalse(result.getInternalError()); - assertTrue(result.getIsValid()); - } - - @Test - public void updateTestSuccess() throws ApisResourceAccessException, IOException, JsonProcessingException, - PacketManagerException, JSONException, IdrepoDraftException, IdrepoDraftReprocessableException { - Map fieldMap = new HashMap<>(); - fieldMap.put("UIN", "123456"); - fieldMap.put("name", "mono"); - fieldMap.put("email", "mono@mono.com"); - - List defaultFields = new ArrayList<>(); - defaultFields.add("name"); - defaultFields.add("dob"); - defaultFields.add("gender"); - defaultFields.add("UIN"); - - when(packetManagerService.getFields(any(), any(), any(), any())).thenReturn(fieldMap); - - when(packetManagerService.getFieldByMappingJsonKey(anyString(),anyString(),any(),any())).thenReturn("0.1"); - when(packetManagerService.getFields(anyString(),anyList(),anyString(),any())).thenReturn(fieldMap); - when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); - - when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); - MessageDTO messageDTO = new MessageDTO(); - messageDTO.setRid("10031100110005020190313110030"); - messageDTO.setReg_type(RegistrationType.valueOf("UPDATE").name()); - IdResponseDTO responsedto = new IdResponseDTO(); - - IdResponseDTO idResponseDTO = new IdResponseDTO(); - ResponseDTO responseDTO = new ResponseDTO(); - idResponseDTO.setErrors(null); - idResponseDTO.setId("mosip.id.update"); - responseDTO.setStatus("ACTIVATED"); - idResponseDTO.setResponse(responseDTO); - idResponseDTO.setResponsetime("2019-03-12T06:49:30.779Z"); - idResponseDTO.setVersion("1.0"); - - when(idrepoDraftService.idrepoUpdateDraft(anyString(), any(), any())).thenReturn(idResponseDTO); - when(registrationProcessorRestClientService.getApi(any(), any(), anyString(), any(), any())) - .thenReturn(responsedto); - when(registrationProcessorRestClientService.patchApi(any(), any(), any(), any(), any(), any())) - .thenReturn(idResponseDTO); - when(utility.getRegistrationProcessorMappingJson(MappingJsonConstants.IDENTITY)).thenReturn(identityObj); - when(utility.getRegistrationProcessorMappingJson(MappingJsonConstants.DOCUMENT)).thenReturn(documentObj); - - MessageDTO result = uinGeneratorStage.process(messageDTO); - assertTrue(result.getIsValid()); - assertFalse(result.getInternalError()); - } - - @Test - public void testLinkSuccessForLostUinisNull() throws Exception { - MessageDTO messageDTO = new MessageDTO(); - messageDTO.setRid("27847657360002520181210094052"); - messageDTO.setReg_type(RegistrationType.LOST.name()); - String str = "{\"id\":\"mosip.id.read\",\"version\":\"1.0\",\"responsetime\":\"2019-04-05\",\"metadata\":null,\"response\":{\"uin\":\"2812936908\"},\"errors\":[{\"errorCode\":null,\"errorMessage\":null}]}"; - String response = "{\"timestamp\":1553771083721,\"status\":404,\"errors\":[{\"errorCode\":\"KER-UIG-004\",\"errorMessage\":\"Given UIN is not in ISSUED status\"}]}"; - when(idRepoService.getUinByRid(anyString(), anyString())).thenReturn(null); - when(regLostUinDetEntity.getLostUinMatchedRegIdByWorkflowId(any())).thenReturn("27847657360002520181210094052"); - - when(registrationProcessorRestClientService.putApi(any(), any(), any(), any(), any(), any(), any())) - .thenReturn(response); - - IdResponseDTO idResponseDTO = new IdResponseDTO(); - ResponseDTO responseDTO = new ResponseDTO(); - idResponseDTO.setErrors(null); - idResponseDTO.setId("mosip.id.update"); - responseDTO.setStatus("ACTIVATED"); - idResponseDTO.setResponse(responseDTO); - idResponseDTO.setResponsetime("2019-01-17T06:29:01.940Z"); - idResponseDTO.setVersion("1.0"); - - when(idrepoDraftService.idrepoUpdateDraft(anyString(), any(), any())).thenReturn(idResponseDTO); - when(registrationProcessorRestClientService.postApi(any(), any(), any(), any(), any(Class.class))) - .thenReturn(idResponseDTO); - when(registrationProcessorRestClientService.getApi(any(), any(), anyString(), any(), any(Class.class))) - .thenReturn(idResponseDTO); - when( - registrationProcessorRestClientService.patchApi(any(), any(), any(), any(), any(), any(Class.class))) - .thenReturn(idResponseDTO); - MessageDTO result = uinGeneratorStage.process(messageDTO); - assertFalse(result.getIsValid()); - assertFalse(result.getInternalError()); - } - - @Test - public void testLinkSuccessForLostUinIdResponseIsNUll() throws Exception { - MessageDTO messageDTO = new MessageDTO(); - messageDTO.setRid("27847657360002520181210094052"); - messageDTO.setReg_type(RegistrationType.LOST.name()); - String str = "{\"id\":\"mosip.id.read\",\"version\":\"1.0\",\"responsetime\":\"2019-04-05\",\"metadata\":null,\"response\":{\"uin\":\"2812936908\"},\"errors\":[{\"errorCode\":null,\"errorMessage\":null}]}"; - String response = "{\"timestamp\":1553771083721,\"status\":404,\"errors\":[{\"errorCode\":\"KER-UIG-004\",\"errorMessage\":\"Given UIN is not in ISSUED status\"}]}"; - - - when(registrationProcessorRestClientService.putApi(any(), any(), any(), any(), any(), any(), any())) - .thenReturn(response); - when(regLostUinDetEntity.getLostUinMatchedRegIdByWorkflowId(any())).thenReturn("27847657360002520181210094052"); - - IdResponseDTO idResponseDTO = new IdResponseDTO(); - ResponseDTO responseDTO = new ResponseDTO(); - idResponseDTO.setErrors(null); - idResponseDTO.setId("mosip.id.update"); - responseDTO.setStatus("ACTIVATED"); - idResponseDTO.setResponse(responseDTO); - idResponseDTO.setResponsetime("2019-01-17T06:29:01.940Z"); - idResponseDTO.setVersion("1.0"); - - when(idrepoDraftService.idrepoUpdateDraft(anyString(), any(), any())).thenReturn(idResponseDTO); - when(registrationProcessorRestClientService.postApi(any(), any(), any(), any(), any(Class.class))) - .thenReturn(idResponseDTO); - when(registrationProcessorRestClientService.getApi(any(), any(), anyString(), any(), any(Class.class))) - .thenReturn(idResponseDTO); - when( - registrationProcessorRestClientService.patchApi(any(), any(), any(), any(), any(), any(Class.class))) - .thenReturn(null); - MessageDTO result = uinGeneratorStage.process(messageDTO); - assertTrue(result.getIsValid()); - assertFalse(result.getInternalError()); - } - - @Test - public void testUpdateSuccess() throws Exception { - - MessageDTO messageDTO = new MessageDTO(); - messageDTO.setRid("10031100110005020190313110030"); - messageDTO.setReg_type(RegistrationType.UPDATE.name()); - - Map fieldMap = new HashMap<>(); - fieldMap.put("UIN", "123456"); - fieldMap.put("name", "mono"); - fieldMap.put("email", "mono@mono.com"); - - List defaultFields = new ArrayList<>(); - defaultFields.add("name"); - defaultFields.add("dob"); - defaultFields.add("gender"); - defaultFields.add("UIN"); - - when(packetManagerService.getFields(any(), any(), any(), any())).thenReturn(fieldMap); - - when(packetManagerService.getFieldByMappingJsonKey(anyString(),anyString(),any(),any())).thenReturn("0.1"); - when(packetManagerService.getFields(anyString(),anyList(),anyString(),any())).thenReturn(fieldMap); - when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); - - when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); - - - IdResponseDTO idResponseDTO = new IdResponseDTO(); - ResponseDTO responseDTO = new ResponseDTO(); - responseDTO.setStatus("ACTIVATED"); - idResponseDTO.setErrors(null); - idResponseDTO.setId("mosip.id.update"); - - idResponseDTO.setErrors(null); - idResponseDTO.setResponse(responseDTO); - idResponseDTO.setResponsetime("2019-03-12T06:49:30.779Z"); - idResponseDTO.setVersion("1.0"); - - when(idrepoDraftService.idrepoUpdateDraft(anyString(), any(), any())).thenReturn(idResponseDTO); - when(registrationProcessorRestClientService.getApi(any(), any(), anyString(), any(), any())) - .thenReturn(idResponseDTO); - - IdResponseDTO idResponseDTO1 = new IdResponseDTO(); - ResponseDTO responseDTO1 = new ResponseDTO(); - idResponseDTO1.setErrors(null); - idResponseDTO1.setId("mosip.id.update"); - responseDTO1.setStatus("ACTIVATED"); - idResponseDTO1.setResponse(responseDTO1); - idResponseDTO1.setResponsetime("2019-01-17T06:29:01.940Z"); - idResponseDTO1.setVersion("1.0"); - - when(utility.getRegistrationProcessorMappingJson(MappingJsonConstants.IDENTITY)).thenReturn(identityObj); - when(utility.getRegistrationProcessorMappingJson(MappingJsonConstants.DOCUMENT)).thenReturn(documentObj); - when(registrationProcessorRestClientService.patchApi(any(), any(), any(), any(), any(), any())) - .thenReturn(idResponseDTO1); - - MessageDTO result = uinGeneratorStage.process(messageDTO); - assertFalse(result.getInternalError()); - assertTrue(result.getIsValid()); - } - - - @Test - public void testUpdateDraftFailed() throws Exception { - Map fieldMap = new HashMap<>(); - fieldMap.put("UIN", "123456"); - fieldMap.put("name", "mono"); - fieldMap.put("email", "mono@mono.com"); - - List defaultFields = new ArrayList<>(); - defaultFields.add("name"); - defaultFields.add("dob"); - defaultFields.add("gender"); - defaultFields.add("UIN"); - - when(packetManagerService.getFields(any(), any(), any(), any())).thenReturn(fieldMap); - - when(packetManagerService.getFieldByMappingJsonKey(anyString(),anyString(),any(),any())).thenReturn("0.1"); - when(packetManagerService.getFields(anyString(),anyList(),anyString(),any())).thenReturn(fieldMap); - when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); - - when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); - MessageDTO messageDTO = new MessageDTO(); - messageDTO.setRid("10031100110005020190313110030"); - messageDTO.setReg_type(RegistrationType.UPDATE.name()); - - IdResponseDTO responsedto = new IdResponseDTO(); - ErrorDTO errorDTO = new ErrorDTO(); - errorDTO.setErrorCode("ERROR"); - errorDTO.setMessage("ERROR message"); - responsedto.setErrors(Lists.newArrayList(errorDTO)); - when(idrepoDraftService.idrepoUpdateDraft(any(), any(), any())) - .thenReturn(responsedto); - - IdResponseDTO idResponseDTO1 = new IdResponseDTO(); - - when(registrationProcessorRestClientService.patchApi(any(), any(), any(), any(), any(), any())) - .thenReturn(idResponseDTO1); - when(utility.getRegistrationProcessorMappingJson(MappingJsonConstants.IDENTITY)).thenReturn(identityObj); - when(utility.getRegistrationProcessorMappingJson(MappingJsonConstants.DOCUMENT)).thenReturn(documentObj); - - MessageDTO result = uinGeneratorStage.process(messageDTO); - assertFalse(result.getInternalError()); - assertFalse(result.getIsValid()); - } - - @Test - public void testUinAlreadyExists() throws Exception { - Map fieldMap = new HashMap<>(); - fieldMap.put("UIN", "123456"); - fieldMap.put("name", "mono"); - fieldMap.put("email", "mono@mono.com"); - - List defaultFields = new ArrayList<>(); - defaultFields.add("name"); - defaultFields.add("dob"); - defaultFields.add("gender"); - defaultFields.add("UIN"); - - - when(packetManagerService.getFieldByMappingJsonKey(anyString(),anyString(),any(),any())).thenReturn("0.1"); - when(packetManagerService.getFields(anyString(),anyList(),anyString(),any())).thenReturn(fieldMap); - when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); - when(utility.getRegistrationProcessorMappingJson(MappingJsonConstants.IDENTITY)).thenReturn(identityObj); - when(utility.getRegistrationProcessorMappingJson(MappingJsonConstants.DOCUMENT)).thenReturn(documentObj); - - when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); - MessageDTO messageDTO = new MessageDTO(); - messageDTO.setRid("27847657360002520181210094052"); - messageDTO.setReg_type(RegistrationType.NEW.name()); - String response = "{\"timestamp\":1553771083721,\"status\":404,\"errors\":[{\"errorCode\":\"KER-UIG-004\",\"errorMessage\":\"Given UIN is not in ISSUED status\"}]}"; - - - when(registrationProcessorRestClientService.putApi(any(), any(), any(), any(), any(), any(), any())) - .thenReturn(response); - - IdResponseDTO idResponseDTO = new IdResponseDTO(); - idResponseDTO.setErrors(null); - idResponseDTO.setId("mosip.id.update"); - ErrorDTO errorDTO = new ErrorDTO("IDR-IDC-012", "Record already exists in DB"); - idResponseDTO.setErrors(Lists.newArrayList(errorDTO)); - idResponseDTO.setResponsetime("2019-01-17T06:29:01.940Z"); - idResponseDTO.setVersion("1.0"); - - when(idrepoDraftService.idrepoUpdateDraft(anyString(), any(), any())).thenReturn(idResponseDTO); - - MessageDTO result = uinGeneratorStage.process(messageDTO); - assertTrue(result.getIsValid()); - assertFalse(result.getInternalError()); - } - - - @Test - public void testUinGenerationSuccessWithAllDocuments() throws Exception { - Map fieldMap = new HashMap<>(); - fieldMap.put("name", "mono"); - fieldMap.put("email", "mono@mono.com"); - fieldMap.put("phone", "23456"); - fieldMap.put("dob", "11/11/2011"); - fieldMap.put("proofOfIdentity", "{\"value\":\"POA_Rental contract\",\"type\":\"Rental contract\",\"format\":\"jpg\"}"); - fieldMap.put("proofOfRelationship", "{\"value\":\"POA_Rental contract\",\"type\":\"Rental contract\",\"format\":\"jpg\"}"); - fieldMap.put("proofOfDateOfBirth", "{\"value\":\"POA_Rental contract\",\"type\":\"Rental contract\",\"format\":\"jpg\"}"); - fieldMap.put("proofOfException", "{\"value\":\"POA_Rental contract\",\"type\":\"Rental contract\",\"format\":\"jpg\"}"); - fieldMap.put("proofOfAddress", "{\"value\":\"POA_Rental contract\",\"type\":\"Rental contract\",\"format\":\"jpg\"}"); - fieldMap.put("individualBiometrics", "{\"format\":\"cbeff\",\"version\":1,\"value\":\"applicant_bio_CBEFF\"}"); - - MessageDTO messageDTO = new MessageDTO(); - messageDTO.setRid("27847657360002520181210094052"); - messageDTO.setReg_type(RegistrationType.NEW.name()); - - IdResponseDTO idResponseDTO = new IdResponseDTO(); - ResponseDTO responseDTO = new ResponseDTO(); - responseDTO.setStatus("ACTIVATED"); - idResponseDTO.setErrors(null); - idResponseDTO.setId("mosip.id.update"); - idResponseDTO.setResponse(responseDTO); - idResponseDTO.setResponsetime("2019-01-17T06:29:01.940Z"); - idResponseDTO.setVersion("1.0"); - - when(packetManagerService.getFields(any(), any(), any(), any())).thenReturn(fieldMap); - when(idrepoDraftService.idrepoUpdateDraft(anyString(), any(), any())).thenReturn(idResponseDTO); - - String str = "{\"id\":\"mosip.id.read\",\"version\":\"1.0\",\"responsetime\":\"2019-04-05\",\"metadata\":null,\"response\":{\"uin\":\"2812936908\"},\"errors\":[{\"errorCode\":null,\"errorMessage\":null}]}"; - when(registrationProcessorRestClientService.getApi(any(), any(), anyString(), - anyString(), any(Class.class))).thenReturn(str); - when(utility.getRegistrationProcessorMappingJson(MappingJsonConstants.IDENTITY)).thenReturn(identityObj); - when(utility.getRegistrationProcessorMappingJson(MappingJsonConstants.DOCUMENT)).thenReturn(documentObj); - - MessageDTO result = uinGeneratorStage.process(messageDTO); - assertFalse(result.getInternalError()); - assertTrue(result.getIsValid()); - } - - @Test - public void testPacketFetchingException() throws Exception { - when(packetManagerService.getFieldByMappingJsonKey(any(), any(),any(), any())).thenThrow(new PacketManagerException("", "")); - MessageDTO messageDTO = new MessageDTO(); - messageDTO.setRid("27847657360002520181210094052"); - messageDTO.setReg_type(RegistrationType.NEW.name()); - Mockito.when(registrationStatusMapperUtil - .getStatusCode(RegistrationExceptionTypeCode.PACKET_MANAGER_EXCEPTION)).thenReturn("REPROCESS"); - MessageDTO result = uinGeneratorStage.process(messageDTO); - assertTrue(result.getInternalError()); - assertTrue(result.getIsValid()); - } - - @Test - public void testJsonProcessingException() throws ApisResourceAccessException, IOException, PacketManagerException, JsonProcessingException { - - when(packetManagerService.getFieldByMappingJsonKey(any(), any(),any(), any())).thenThrow(new io.mosip.kernel.core.util.exception.JsonProcessingException("")); - MessageDTO messageDTO = new MessageDTO(); - messageDTO.setRid("27847657360002520181210094052"); - Mockito.when(registrationStatusMapperUtil - .getStatusCode(RegistrationExceptionTypeCode.JSON_PROCESSING_EXCEPTION)).thenReturn("ERROR"); - MessageDTO result = uinGeneratorStage.process(messageDTO); - assertTrue(result.getInternalError()); - assertFalse(result.getIsValid()); - } - - @Test - public void testUinReActivationWithoutIDResponseDTO() throws Exception { - - Map fieldMap = new HashMap<>(); - fieldMap.put("UIN", "123456"); - fieldMap.put("name", "mono"); - fieldMap.put("email", "mono@mono.com"); - - List defaultFields = new ArrayList<>(); - defaultFields.add("name"); - defaultFields.add("dob"); - defaultFields.add("gender"); - defaultFields.add("UIN"); - - - when(packetManagerService.getFieldByMappingJsonKey(anyString(), anyString(), any(), any())).thenReturn("0.1"); - when(packetManagerService.getFields(any(), any(), any(), any())).thenReturn(fieldMap); - when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); - - when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); - - MessageDTO messageDTO = new MessageDTO(); - messageDTO.setRid("27847657360002520181210094052"); - messageDTO.setReg_type(RegistrationType.valueOf("ACTIVATED").name()); - - IdResponseDTO idResponseDTO = new IdResponseDTO(); - idResponseDTO.setResponse(null); - - IdResponseDTO idResponseDTO1 = new IdResponseDTO(); - ResponseDTO responseDTO1 = new ResponseDTO(); - idResponseDTO1.setErrors(null); - idResponseDTO1.setId("mosip.id.update"); - responseDTO1.setStatus("ACTIVATED"); - idResponseDTO1.setResponse(null); - - idResponseDTO1.setResponsetime("2019-01-17T06:29:01.940Z"); - idResponseDTO1.setVersion("1.0"); - - when(idrepoDraftService.idrepoUpdateDraft(anyString(), any(), any())).thenReturn(idResponseDTO); - when(registrationProcessorRestClientService.getApi(any(), any(), anyString(), any(), any())) - .thenReturn(idResponseDTO); - - String idJsonData = "{\"identity\":{\"IDSchemaVersion\":1.0,\"UIN\":\"4215839851\"}}"; - InputStream idJsonStream = new ByteArrayInputStream(idJsonData.getBytes(StandardCharsets.UTF_8)); - - - - when(registrationProcessorRestClientService.patchApi(any(), any(), any(), any(), any(), any())) - .thenReturn(idResponseDTO1); - - MessageDTO result = uinGeneratorStage.process(messageDTO); - assertFalse(result.getIsValid()); - assertFalse(result.getInternalError()); - } - - - - @Test - public void deactivateTestWithNullResponseDTOBeforeDeactivate() throws ApisResourceAccessException, - PacketManagerException, - IOException, JsonProcessingException, JSONException, IdrepoDraftException, - IdrepoDraftReprocessableException { - Map fieldMap = new HashMap<>(); - fieldMap.put("UIN", "123456"); - fieldMap.put("name", "mono"); - fieldMap.put("email", "mono@mono.com"); - - List defaultFields = new ArrayList<>(); - defaultFields.add("name"); - defaultFields.add("dob"); - defaultFields.add("gender"); - defaultFields.add("UIN"); - - - when(packetManagerService.getFieldByMappingJsonKey(anyString(), anyString(), any(), any())).thenReturn("0.1"); - when(packetManagerService.getFields(any(), any(), any(), any())).thenReturn(fieldMap); - when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); - - when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); - MessageDTO messageDTO = new MessageDTO(); - messageDTO.setRid("10031100110005020190313110030"); - messageDTO.setReg_type(RegistrationType.valueOf("DEACTIVATED").name()); - IdResponseDTO responsedto = new IdResponseDTO(); - String idJson = "{\"identity\":{\"IDSchemaVersion\":1.0,\"UIN\":\"4215839851\"}}"; - InputStream idJsonStream1 = new ByteArrayInputStream(idJson.getBytes(StandardCharsets.UTF_8)); - - IdResponseDTO idResponseDTO = new IdResponseDTO(); - ResponseDTO responseDTO = new ResponseDTO(); - idResponseDTO.setErrors(null); - idResponseDTO.setId("mosip.id.update"); - responseDTO.setStatus("DEACTIVATED"); - idResponseDTO.setResponse(null); - idResponseDTO.setResponsetime("2019-03-12T06:49:30.779Z"); - idResponseDTO.setVersion("1.0"); - - when(idrepoDraftService.idrepoUpdateDraft(anyString(), any(), any())).thenReturn(idResponseDTO); - when(registrationProcessorRestClientService.getApi(any(), any(), anyString(), any(), any())) - .thenReturn(responsedto); - when(registrationProcessorRestClientService.patchApi(any(), any(), any(), any(), any(), any())) - .thenReturn(idResponseDTO); - - - MessageDTO result = uinGeneratorStage.process(messageDTO); - assertFalse(result.getIsValid()); - assertFalse(result.getInternalError()); - } - - @Test - public void deactivateTesApiResourceClientException() throws ApisResourceAccessException, - PacketManagerException, - IOException, JsonProcessingException, JSONException, IdrepoDraftException, - IdrepoDraftReprocessableException { - Map fieldMap = new HashMap<>(); - fieldMap.put("UIN", "123456"); - fieldMap.put("name", "mono"); - fieldMap.put("email", "mono@mono.com"); - - List defaultFields = new ArrayList<>(); - defaultFields.add("name"); - defaultFields.add("dob"); - defaultFields.add("gender"); - defaultFields.add("UIN"); - - - when(packetManagerService.getFieldByMappingJsonKey(anyString(), anyString(), any(), any())).thenReturn("0.1"); - when(packetManagerService.getFields(any(), any(), any(), any())).thenReturn(fieldMap); - when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); - - when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); - MessageDTO messageDTO = new MessageDTO(); - messageDTO.setRid("10031100110005020190313110030"); - messageDTO.setReg_type(RegistrationType.valueOf("DEACTIVATED").name()); - IdResponseDTO responsedto = new IdResponseDTO(); - String idJson = "{\"identity\":{\"IDSchemaVersion\":1.0,\"UIN\":\"4215839851\"}}"; - InputStream idJsonStream1 = new ByteArrayInputStream(idJson.getBytes(StandardCharsets.UTF_8)); - - IdResponseDTO idResponseDTO = new IdResponseDTO(); - ResponseDTO responseDTO = new ResponseDTO(); - idResponseDTO.setErrors(null); - idResponseDTO.setId("mosip.id.update"); - responseDTO.setStatus("DEACTIVATED"); - idResponseDTO.setResponse(null); - idResponseDTO.setResponsetime("2019-03-12T06:49:30.779Z"); - idResponseDTO.setVersion("1.0"); - - when(idrepoDraftService.idrepoUpdateDraft(anyString(), any(), any())).thenReturn(idResponseDTO); - ApisResourceAccessException ex=new ApisResourceAccessException("", new HttpClientErrorException(HttpStatus.BAD_REQUEST)); - when(registrationProcessorRestClientService.getApi(any(), any(), anyString(), any(), any())) - .thenThrow(ex); - Mockito.when(registrationStatusMapperUtil - .getStatusCode(RegistrationExceptionTypeCode.APIS_RESOURCE_ACCESS_EXCEPTION)).thenReturn("REPROCESS"); - - - MessageDTO result = uinGeneratorStage.process(messageDTO); - assertTrue(result.getIsValid()); - assertTrue(result.getInternalError()); - } - - @Test - public void deactivateTesApiResourceServerException() throws ApisResourceAccessException, - PacketManagerException, - IOException, JsonProcessingException, JSONException, IdrepoDraftException, - IdrepoDraftReprocessableException { - Map fieldMap = new HashMap<>(); - fieldMap.put("UIN", "123456"); - fieldMap.put("name", "mono"); - fieldMap.put("email", "mono@mono.com"); - - List defaultFields = new ArrayList<>(); - defaultFields.add("name"); - defaultFields.add("dob"); - defaultFields.add("gender"); - defaultFields.add("UIN"); - - - when(packetManagerService.getFieldByMappingJsonKey(anyString(), anyString(), any(), any())).thenReturn("0.1"); - when(packetManagerService.getFields(any(), any(), any(), any())).thenReturn(fieldMap); - when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); - - when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); - MessageDTO messageDTO = new MessageDTO(); - messageDTO.setRid("10031100110005020190313110030"); - messageDTO.setReg_type(RegistrationType.valueOf("DEACTIVATED").name()); - String idJson = "{\"identity\":{\"IDSchemaVersion\":1.0,\"UIN\":\"4215839851\"}}"; - - IdResponseDTO idResponseDTO = new IdResponseDTO(); - ResponseDTO responseDTO = new ResponseDTO(); - idResponseDTO.setErrors(null); - idResponseDTO.setId("mosip.id.update"); - responseDTO.setStatus("DEACTIVATED"); - idResponseDTO.setResponse(null); - idResponseDTO.setResponsetime("2019-03-12T06:49:30.779Z"); - idResponseDTO.setVersion("1.0"); - - when(idrepoDraftService.idrepoUpdateDraft(anyString(), any(), any())).thenReturn(idResponseDTO); - ApisResourceAccessException ex=new ApisResourceAccessException("", new HttpServerErrorException(HttpStatus.INTERNAL_SERVER_ERROR)); - when(registrationProcessorRestClientService.getApi(any(), any(), anyString(), any(), any())) - .thenThrow(ex); - Mockito.when(registrationStatusMapperUtil - .getStatusCode(RegistrationExceptionTypeCode.APIS_RESOURCE_ACCESS_EXCEPTION)).thenReturn("REPROCESS"); - - - MessageDTO result = uinGeneratorStage.process(messageDTO); - assertTrue(result.getIsValid()); - assertTrue(result.getInternalError()); - } - - @Test - public void deactivateTesApiResourceException() throws ApisResourceAccessException, - PacketManagerException, - IOException, JsonProcessingException, JSONException, IdrepoDraftException, - IdrepoDraftReprocessableException { - Map fieldMap = new HashMap<>(); - fieldMap.put("UIN", "123456"); - fieldMap.put("name", "mono"); - fieldMap.put("email", "mono@mono.com"); - - List defaultFields = new ArrayList<>(); - defaultFields.add("name"); - defaultFields.add("dob"); - defaultFields.add("gender"); - defaultFields.add("UIN"); - - - when(packetManagerService.getFieldByMappingJsonKey(anyString(), anyString(), any(), any())).thenReturn("0.1"); - when(packetManagerService.getFields(any(), any(), any(), any())).thenReturn(fieldMap); - when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); - - when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); - MessageDTO messageDTO = new MessageDTO(); - messageDTO.setRid("10031100110005020190313110030"); - messageDTO.setReg_type(RegistrationType.valueOf("DEACTIVATED").name()); - String idJson = "{\"identity\":{\"IDSchemaVersion\":1.0,\"UIN\":\"4215839851\"}}"; - - IdResponseDTO idResponseDTO = new IdResponseDTO(); - ResponseDTO responseDTO = new ResponseDTO(); - idResponseDTO.setErrors(null); - idResponseDTO.setId("mosip.id.update"); - responseDTO.setStatus("DEACTIVATED"); - idResponseDTO.setResponse(null); - idResponseDTO.setResponsetime("2019-03-12T06:49:30.779Z"); - idResponseDTO.setVersion("1.0"); - - when(idrepoDraftService.idrepoUpdateDraft(anyString(), any(), any())).thenReturn(idResponseDTO); - ApisResourceAccessException ex=new ApisResourceAccessException(""); - when(registrationProcessorRestClientService.getApi(any(), any(), anyString(), any(), any())) - .thenThrow(ex); - Mockito.when(registrationStatusMapperUtil - .getStatusCode(RegistrationExceptionTypeCode.APIS_RESOURCE_ACCESS_EXCEPTION)).thenReturn("REPROCESS"); - - - MessageDTO result = uinGeneratorStage.process(messageDTO); - assertTrue(result.getIsValid()); - assertTrue(result.getInternalError()); - } - - @Test - public void deactivateTestAlreadyDeactivated() throws ApisResourceAccessException, - PacketManagerException, - IOException, JsonProcessingException, JSONException, IdrepoDraftException, - IdrepoDraftReprocessableException { - Map fieldMap = new HashMap<>(); - fieldMap.put("UIN", "123456"); - fieldMap.put("name", "mono"); - fieldMap.put("email", "mono@mono.com"); - - List defaultFields = new ArrayList<>(); - defaultFields.add("name"); - defaultFields.add("dob"); - defaultFields.add("gender"); - defaultFields.add("UIN"); - - - when(packetManagerService.getFieldByMappingJsonKey(anyString(), anyString(), any(), any())).thenReturn("0.1"); - when(packetManagerService.getFields(any(), any(), any(), any())).thenReturn(fieldMap); - when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); - - when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); - MessageDTO messageDTO = new MessageDTO(); - messageDTO.setRid("10031100110005020190313110030"); - messageDTO.setReg_type(RegistrationType.valueOf("DEACTIVATED").name()); - IdResponseDTO responsedto = new IdResponseDTO(); - ResponseDTO dto=new ResponseDTO(); - dto.setStatus("DEACTIVATED"); - responsedto.setResponse(dto); - String idJson = "{\"identity\":{\"IDSchemaVersion\":1.0,\"UIN\":\"4215839851\"}}"; - - IdResponseDTO idResponseDTO = new IdResponseDTO(); - ResponseDTO responseDTO = new ResponseDTO(); - idResponseDTO.setErrors(null); - idResponseDTO.setId("mosip.id.update"); - responseDTO.setStatus("DEACTIVATED"); - idResponseDTO.setResponse(null); - idResponseDTO.setResponsetime("2019-03-12T06:49:30.779Z"); - idResponseDTO.setVersion("1.0"); - - when(idrepoDraftService.idrepoUpdateDraft(anyString(), any(), any())).thenReturn(idResponseDTO); - when(registrationProcessorRestClientService.getApi(any(), any(), anyString(), any(), any())) - .thenReturn(responsedto); - when(registrationProcessorRestClientService.patchApi(any(), any(), any(), any(), any(), any())) - .thenReturn(idResponseDTO); - - - MessageDTO result = uinGeneratorStage.process(messageDTO); - assertFalse(result.getIsValid()); - assertFalse(result.getInternalError()); - } - - @Test - public void testUinAlreadyDeactivated() throws ApisResourceAccessException, PacketManagerException, IOException, - JsonProcessingException, JSONException, IdrepoDraftException, IdrepoDraftReprocessableException { - Map fieldsMap = new HashMap<>(); - fieldsMap.put("UIN", "123456"); - fieldsMap.put("name", "mono"); - fieldsMap.put("email", "mono@mono.com"); - - List defaultFields = new ArrayList<>(); - defaultFields.add("UIN"); - defaultFields.add("name"); - defaultFields.add("email"); - - when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); - MessageDTO messageDTO = new MessageDTO(); - messageDTO.setRid("10031100110005020190313110030"); - messageDTO.setReg_type(RegistrationType.valueOf("DEACTIVATED").name()); - - IdResponseDTO responsedto = new IdResponseDTO(); - ResponseDTO responseDTO1 = new ResponseDTO(); - responseDTO1.setStatus("DEACTIVATED"); - responsedto.setResponse(responseDTO1); - IdResponseDTO idResponseDTO = new IdResponseDTO(); - ResponseDTO responseDTO = null; - idResponseDTO.setErrors(null); - idResponseDTO.setId("mosip.id.update"); - ErrorDTO errorDto = new ErrorDTO(); - errorDto.setErrorCode("KER-IDR-001"); - errorDto.setMessage("Record not found in DB"); - - List errors = new ArrayList<>(); - errors.add(errorDto); - idResponseDTO.setErrors(errors); - idResponseDTO.setResponse(responseDTO); - idResponseDTO.setResponsetime("2019-03-12T06:49:30.779Z"); - idResponseDTO.setVersion("1.0"); - - when(idrepoDraftService.idrepoUpdateDraft(anyString(), any(), any())).thenReturn(idResponseDTO); - when(registrationProcessorRestClientService.getApi(any(), any(), anyString(), any(), any())) - .thenReturn(responsedto); - when(registrationProcessorRestClientService.patchApi(any(), any(), any(), any(), any(), any())) - .thenReturn(idResponseDTO); - Mockito.when(registrationStatusMapperUtil - .getStatusCode(RegistrationExceptionTypeCode.PACKET_UIN_GENERATION_REPROCESS)).thenReturn("REPROCESS"); - when(packetManagerService.getFields(any(), any(), any(), any())).thenReturn(fieldsMap); - - when(packetManagerService.getFieldByMappingJsonKey(anyString(),anyString(),any(),any())).thenReturn("0.1"); - when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); - - MessageDTO result = uinGeneratorStage.process(messageDTO); - - assertFalse(result.getIsValid()); - assertFalse(result.getInternalError()); - } - - @Test - public void testUinUpdationFaliure() throws Exception { - - Map fieldMap = new HashMap<>(); - fieldMap.put("UIN", "123456"); - fieldMap.put("name", "mono"); - fieldMap.put("email", "mono@mono.com"); - - List defaultFields = new ArrayList<>(); - defaultFields.add("name"); - defaultFields.add("dob"); - defaultFields.add("gender"); - defaultFields.add("UIN"); - - - when(packetManagerService.getFieldByMappingJsonKey(anyString(),anyString(),any(),any())).thenReturn("0.1"); - when(packetManagerService.getFields(any(),any(),any(),any())).thenReturn(fieldMap); - when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); - - when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); - - IdResponseDTO idResponseDTO = new IdResponseDTO(); - ResponseDTO responseDTO = new ResponseDTO(); - ErrorDTO errorDto = new ErrorDTO(); - errorDto.setErrorCode("KER-IDR-001"); - errorDto.setMessage("Record already Exists in DB"); - List errors = new ArrayList<>(); - errors.add(errorDto); - idResponseDTO.setErrors(errors); - idResponseDTO.setId("mosip.id.error"); - idResponseDTO.setResponse(null); - idResponseDTO.setResponsetime("2019-01-17T06:29:01.940Z"); - idResponseDTO.setVersion("1.0"); - when(registrationProcessorRestClientService.postApi(any(), any(), any(), any(), any())) - .thenReturn(idResponseDTO); - when(utility.getRegistrationProcessorMappingJson(MappingJsonConstants.IDENTITY)).thenReturn(identityObj); - when(utility.getRegistrationProcessorMappingJson(MappingJsonConstants.DOCUMENT)).thenReturn(documentObj); - - String Str = "{\"uin\":\"6517036426\"}"; - - Mockito.when(registrationStatusMapperUtil - .getStatusCode(RegistrationExceptionTypeCode.PACKET_UIN_GENERATION_REPROCESS)).thenReturn("REPROCESS"); - when(idrepoDraftService.idrepoUpdateDraft(anyString(), any(), any())).thenReturn(idResponseDTO); - - MessageDTO messageDTO = new MessageDTO(); - messageDTO.setRid("27847657360002520181210094052"); - messageDTO.setReg_type("UPDATE"); - - MessageDTO result = uinGeneratorStage.process(messageDTO); - - assertFalse(result.getInternalError()); - assertFalse(result.getIsValid()); - } - - @Test - public void testUinUpdationIDRepoFaliure() throws Exception { - - Map fieldMap = new HashMap<>(); - fieldMap.put("name", "mono"); - fieldMap.put("email", "mono@mono.com"); - - List defaultFields = new ArrayList<>(); - defaultFields.add("name"); - defaultFields.add("dob"); - defaultFields.add("gender"); - defaultFields.add("UIN"); - - - when(packetManagerService.getFieldByMappingJsonKey(anyString(),anyString(),any(),any())).thenReturn("0.1"); - when(packetManagerService.getFields(any(),any(),any(),any())).thenReturn(fieldMap); - when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); - - IdResponseDTO idResponseDTO = new IdResponseDTO(); - ErrorDTO errorDto = new ErrorDTO(); - errorDto.setErrorCode("IDR-IDC-001"); - errorDto.setMessage("Record already Exists in DB"); - List errors = new ArrayList<>(); - errors.add(errorDto); - idResponseDTO.setErrors(errors); - idResponseDTO.setId("mosip.id.error"); - idResponseDTO.setResponse(null); - idResponseDTO.setResponsetime("2019-01-17T06:29:01.940Z"); - idResponseDTO.setVersion("1.0"); - when(registrationProcessorRestClientService.postApi(any(), any(), any(), any(), any())) - .thenReturn(idResponseDTO); - - Mockito.when(registrationStatusMapperUtil - .getStatusCode(RegistrationExceptionTypeCode.PACKET_UIN_GENERATION_REPROCESS)).thenReturn("REPROCESS"); - when(idrepoDraftService.idrepoUpdateDraft(anyString(), any(), any())).thenReturn(idResponseDTO); - - MessageDTO messageDTO = new MessageDTO(); - messageDTO.setRid("27847657360002520181210094052"); - messageDTO.setReg_type("UPDATE"); - - MessageDTO result = uinGeneratorStage.process(messageDTO); - - assertTrue(result.getInternalError()); - assertTrue(result.getIsValid()); - } - - @Test - public void testUinUpdationIOExceptionFaliure() throws Exception { - - when(packetManagerService.getFieldByMappingJsonKey(anyString(), anyString(), any(), any())) - .thenThrow(IOException.class); - when(registrationStatusMapperUtil - .getStatusCode(RegistrationExceptionTypeCode.PACKET_UIN_GENERATION_REPROCESS)).thenReturn("REPROCESS"); - - MessageDTO messageDTO = new MessageDTO(); - messageDTO.setRid("27847657360002520181210094052"); - messageDTO.setReg_type("UPDATE"); - - MessageDTO result = uinGeneratorStage.process(messageDTO); - - assertTrue(result.getInternalError()); - assertTrue(result.getIsValid()); - } - - @Test - public void testUinGenerationIDRepoDraftReprocessableException() throws Exception { - MessageDTO messageDTO = new MessageDTO(); - messageDTO.setRid("27847657360002520181210094052"); - messageDTO.setReg_type(RegistrationType.NEW.name()); - - when(registrationStatusMapperUtil - .getStatusCode(RegistrationExceptionTypeCode.IDREPO_DRAFT_REPROCESSABLE_EXCEPTION)) - .thenReturn("REPROCESS"); - when(idrepoDraftService.idrepoUpdateDraft(anyString(), any(), any())) - .thenThrow(IdrepoDraftReprocessableException.class); - when(utility.getRegistrationProcessorMappingJson(MappingJsonConstants.IDENTITY)).thenReturn(identityObj); - when(utility.getRegistrationProcessorMappingJson(MappingJsonConstants.DOCUMENT)).thenReturn(documentObj); - - MessageDTO result = uinGeneratorStage.process(messageDTO); - assertTrue(result.getInternalError()); - assertTrue(result.getIsValid()); - } - - @Test - public void testUinGenerationSuccessWithEmptyName() throws Exception { - ReflectionTestUtils.setField(uinGeneratorStage,"trimWhitespaces",true); - Map fieldMap = new HashMap<>(); - fieldMap.put("firstName","[ {\n" + - " \"language\" : \"eng\",\n" + - " \"value\" : \" \"\n" + - "} ]"); - fieldMap.put("email", "mono@mono.com"); - fieldMap.put("phone", "23456"); - fieldMap.put("dob", "11/11/2011"); - when(packetManagerService.getFields(any(),any(),any(),any())).thenReturn(fieldMap); - ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(IdRequestDto.class); - - MessageDTO messageDTO = new MessageDTO(); - messageDTO.setRid("27847657360002520181210094052"); - messageDTO.setReg_type(RegistrationType.NEW.name()); - - IdResponseDTO idResponseDTO = new IdResponseDTO(); - ResponseDTO responseDTO = new ResponseDTO(); - responseDTO.setStatus("ACTIVATED"); - idResponseDTO.setErrors(null); - idResponseDTO.setId("mosip.id.update"); - idResponseDTO.setResponse(responseDTO); - idResponseDTO.setResponsetime("2019-01-17T06:29:01.940Z"); - idResponseDTO.setVersion("1.0"); - - when(idrepoDraftService.idrepoUpdateDraft(anyString(), any(), any())).thenReturn(idResponseDTO); - when(utility.getRegistrationProcessorMappingJson(MappingJsonConstants.IDENTITY)).thenReturn(identityObj); - when(utility.getRegistrationProcessorMappingJson(MappingJsonConstants.DOCUMENT)).thenReturn(documentObj); - - MessageDTO result = uinGeneratorStage.process(messageDTO); - verify(idrepoDraftService).idrepoUpdateDraft(any(), any(), argumentCaptor.capture()); - ObjectMapper objectMapper = new ObjectMapper(); - String jsonobject=objectMapper.writeValueAsString(argumentCaptor.getAllValues().get(0).getRequest().getIdentity()); - JsonNode jsonNode=objectMapper.readTree(jsonobject); - - assertEquals("",jsonNode.get("firstName").asText()); - assertFalse(result.getInternalError()); - assertTrue(result.getIsValid()); - } +package io.mosip.registration.processor.stages.uigenerator; + +import static org.junit.Assert.*; +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 java.io.ByteArrayInputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +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; +import java.util.LinkedHashMap; +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; +import org.json.simple.JSONObject; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.*; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.springframework.core.env.Environment; +import org.springframework.http.HttpStatus; +import org.springframework.test.util.ReflectionTestUtils; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.web.client.HttpServerErrorException; + +import com.fasterxml.jackson.databind.ObjectMapper; + +import io.mosip.kernel.biometrics.constant.BiometricType; +import io.mosip.kernel.biometrics.constant.QualityType; +import io.mosip.kernel.biometrics.entities.BDBInfo; +import io.mosip.kernel.biometrics.entities.BIR; +import io.mosip.kernel.biometrics.entities.BiometricRecord; +import io.mosip.kernel.biometrics.entities.RegistryIDType; +import io.mosip.kernel.biometrics.spi.CbeffUtil; +import io.mosip.kernel.core.util.HMACUtils2; +import io.mosip.kernel.core.util.exception.JsonProcessingException; +import io.mosip.kernel.dataaccess.hibernate.constant.HibernateErrorCode; +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.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.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.RegistrationType; +import io.mosip.registration.processor.core.exception.ApisResourceAccessException; +import io.mosip.registration.processor.core.exception.PacketManagerException; +import io.mosip.registration.processor.core.http.ResponseWrapper; +import io.mosip.registration.processor.core.idrepo.dto.Documents; +import io.mosip.registration.processor.core.logger.LogDescription; +import io.mosip.registration.processor.core.packet.dto.ApplicantDocument; +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.packetmanager.PacketInfoManager; +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.IdResponseDTO; +import io.mosip.registration.processor.packet.manager.dto.ResponseDTO; +import io.mosip.registration.processor.packet.manager.exception.IdrepoDraftException; +import io.mosip.registration.processor.packet.manager.exception.IdrepoDraftReprocessableException; +import io.mosip.registration.processor.packet.manager.idreposervice.IdRepoService; +import io.mosip.registration.processor.packet.manager.idreposervice.IdrepoDraftService; +import io.mosip.registration.processor.packet.storage.dto.ApplicantInfoDto; +import io.mosip.registration.processor.packet.storage.dto.ContainerInfoDto; +import io.mosip.registration.processor.packet.storage.dto.Document; +import io.mosip.registration.processor.packet.storage.entity.IndividualDemographicDedupeEntity; +import io.mosip.registration.processor.packet.storage.entity.RegLostUinDetEntity; +import io.mosip.registration.processor.packet.storage.repository.BasePacketRepository; +import io.mosip.registration.processor.packet.storage.utils.IdSchemaUtil; +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.rest.client.audit.dto.AuditResponseDto; +import io.mosip.registration.processor.stages.uingenerator.stage.UinGeneratorStage; +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; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({ IOUtils.class, HMACUtils2.class, Utilities.class}) +@PowerMockIgnore({"com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "javax.management.*", "javax.net.ssl.*" }) +public class UinGeneratorStageTest { + + @InjectMocks + private UinGeneratorStage uinGeneratorStage = new UinGeneratorStage() { + @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) { + + + } + + @Override + public void senderHealthCheck(Handler eventHandler, String address) { + + + } + + }; + } + + @Override + public void consumeAndSend(MosipEventBus mosipEventBus, MessageBusAddress fromAddress, + MessageBusAddress toAddress, long messageExpiryTimeLimit) { + } + + @Override + public Integer getPort() { + return 8080; + } + }; + + /** The input stream. */ + @Mock + private InputStream inputStream; + + @Mock + private Object identity; + + @Mock + private PriorityBasedPacketManagerService packetManagerService; + + /** The registration status service. */ + @Mock + private RegistrationStatusService registrationStatusService; + + @Mock + private IdrepoDraftService idrepoDraftService; + + /** The identity json. */ + @Mock + private JSONObject identityJson; + + @Mock + private AuditLogRequestBuilder auditLogRequestBuilder; + + @Mock + private RegistrationProcessorRestClientService registrationProcessorRestClientService; + + @Mock + private List documents; + + @Mock + private JSONObject demographicIdentity; + + @Mock + private PacketInfoManager packetInfoManager; + + @Mock + private BasePacketRepository demographicDedupeRepository; + + @Mock + private BasePacketRepository regLostUinDetRepository; + + /** The registration status dto. */ + private InternalRegistrationStatusDto registrationStatusDto = new InternalRegistrationStatusDto(); + + @Mock + private Utilities utility; + + @Mock + private IdRepoService idRepoService; + + @Mock + private CbeffUtil cbeffutil; + + @Mock + private BasePacketRepository regLostUinDetEntity; + + /** The identitydemoinfo. */ + Identity identitydemoinfo = new Identity(); + + /** The Constant CONFIG_SERVER_URL. */ + private static final String CONFIG_SERVER_URL = "url"; + + private String identityMappingjsonString; + + @Mock + private Environment env; + + @Mock + private LogDescription description; + + @Mock + private RegistrationExceptionMapperUtil registrationStatusMapperUtil; + + @Mock + private IdSchemaUtil idSchemaUtil; + + @Spy + private ObjectMapper mapper = new ObjectMapper(); + + JSONObject documentObj; + JSONObject identityObj; + + @Before + public void setup() throws Exception { + ReflectionTestUtils.setField(uinGeneratorStage, "workerPoolSize", 10); + ReflectionTestUtils.setField(uinGeneratorStage, "messageExpiryTimeLimit", Long.valueOf(0)); + ReflectionTestUtils.setField(uinGeneratorStage, "clusterManagerUrl", "/dummyPath"); + ReflectionTestUtils.setField(uinGeneratorStage, "updateInfo", "phone"); + ClassLoader classLoader1 = getClass().getClassLoader(); + File idJsonFile1 = new File(classLoader1.getResource("RegistrationProcessorIdentity.json").getFile()); + InputStream idJsonStream1 = new FileInputStream(idJsonFile1); + LinkedHashMap hm = new ObjectMapper().readValue(idJsonStream1, LinkedHashMap.class); + JSONObject jsonObject = new JSONObject(hm); + identityMappingjsonString = jsonObject.toJSONString(); + documentObj = JsonUtil.getJSONObject(new ObjectMapper().readValue(identityMappingjsonString, JSONObject.class), MappingJsonConstants.DOCUMENT); + identityObj = JsonUtil.getJSONObject(new ObjectMapper().readValue(identityMappingjsonString, JSONObject.class), MappingJsonConstants.IDENTITY); + when(utility.getRegistrationProcessorMappingJson(MappingJsonConstants.IDENTITY)).thenReturn(identityObj); + when(utility.getRegistrationProcessorMappingJson(MappingJsonConstants.DOCUMENT)).thenReturn(documentObj); + + String str = "{\"id\":\"mosip.id.read\",\"version\":\"1.0\",\"responsetime\":\"2019-04-05\",\"metadata\":null,\"response\":{\"uin\":\"2812936908\"},\"errors\":[{\"errorCode\":null,\"errorMessage\":null}]}"; + when(registrationProcessorRestClientService.getApi(any(), any(), anyString(), + anyString(), any(Class.class))).thenReturn(str); + + //when(registrationStatusMapperUtil.getStatusCode(any())).thenReturn("EXCEPTION"); + Mockito.doNothing().when(description).setCode(Mockito.anyString()); + Mockito.doNothing().when(description).setMessage(Mockito.anyString()); + when(description.getCode()).thenReturn("CODE"); + when(description.getMessage()).thenReturn("MESSAGE"); + MockitoAnnotations.initMocks(this); + 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); + + registrationStatusDto.setLatestTransactionStatusCode("SUCCESS"); + when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); + + PowerMockito.mockStatic(Utilities.class); + PowerMockito.when(Utilities.class, "getJson", CONFIG_SERVER_URL, "RegistrationProcessorIdentity.json") + .thenReturn(identityMappingjsonString); + when(utility.getGetRegProcessorDemographicIdentity()).thenReturn("identity"); + + when(identityJson.get(anyString())).thenReturn(demographicIdentity); + List applicantDocument = new ArrayList<>(); + ApplicantDocument appDocument = new ApplicantDocument(); + appDocument.setIsActive(true); + appDocument.setDocName("POA"); + appDocument.setDocStore("ProofOfAddress".getBytes()); + applicantDocument.add(appDocument); + when(env.getProperty("registration.processor.id.repo.generate")).thenReturn("mosip.vid.create"); + when(env.getProperty("mosip.registration.processor.datetime.pattern")) + .thenReturn("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); + when(env.getProperty("registration.processor.id.repo.vidVersion")).thenReturn("v1"); + when(regLostUinDetRepository.getLostUinMatchedRegIdByWorkflowId(anyString())) + .thenReturn("27847657360002520181210094052"); + demographicIdentity.put("UIN", Long.parseLong("9403107397")); + + when(idRepoService.getUinByRid(anyString(), anyString())).thenReturn("9403107397"); + + List birTypeList = new ArrayList<>(); + BIR birType1 = new BIR.BIRBuilder().build(); + BDBInfo bdbInfoType1 = new BDBInfo.BDBInfoBuilder().build(); + RegistryIDType registryIDType = new RegistryIDType(); + registryIDType.setOrganization("Mosip"); + registryIDType.setType("257"); + QualityType quality = new QualityType(); + quality.setAlgorithm(registryIDType); + quality.setScore(90l); + bdbInfoType1.setQuality(quality); + BiometricType singleType1 = BiometricType.FINGER; + List singleTypeList1 = new ArrayList<>(); + singleTypeList1.add(singleType1); + List subtype1 = new ArrayList<>(Arrays.asList("Left", "RingFinger")); + bdbInfoType1.setSubtype(subtype1); + bdbInfoType1.setType(singleTypeList1); + birType1.setBdbInfo(bdbInfoType1); + birTypeList.add(birType1); + + BiometricRecord biometricRecord = new BiometricRecord(); + biometricRecord.setSegments(birTypeList); + + Document document = new Document(); + document.setDocument("document".getBytes()); + + Map fieldMap = new HashMap<>(); + fieldMap.put("name", "mono"); + fieldMap.put("email", "mono@mono.com"); + fieldMap.put("phone", "23456"); + fieldMap.put("dob", "11/11/2011"); + + List defaultFields = new ArrayList<>(); + defaultFields.add("name"); + defaultFields.add("dob"); + defaultFields.add("gender"); + + + when(packetManagerService.getFieldByMappingJsonKey(anyString(),anyString(),any(),any())).thenReturn("0.1"); + when(packetManagerService.getFields(any(), any(), any(), any())).thenReturn(fieldMap); + when(packetManagerService.getDocument(anyString(),anyString(),anyString(),any())).thenReturn(document); + when(packetManagerService.getBiometrics(anyString(),anyString(),any(),any())).thenReturn(biometricRecord); + when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); + when(utility.getMappingJsonValue(anyString(), any())).thenReturn("UIN"); + + ContainerInfoDto containerInfoDto = new ContainerInfoDto(); + containerInfoDto.setSource("REGISTRATION_CLIENT"); + containerInfoDto.setProcess("NEW"); + + when(packetManagerService.getBiometrics(anyString(),any(), any(), any())).thenReturn(biometricRecord); + when(cbeffutil.createXML(any())).thenReturn("String".getBytes()); + + } + + @Test + public void testUinGenerationSuccessWithoutUIN() throws Exception { + MessageDTO messageDTO = new MessageDTO(); + messageDTO.setRid("27847657360002520181210094052"); + messageDTO.setReg_type(RegistrationType.NEW.name()); + + IdResponseDTO idResponseDTO = new IdResponseDTO(); + ResponseDTO responseDTO = new ResponseDTO(); + responseDTO.setStatus("ACTIVATED"); + idResponseDTO.setErrors(null); + idResponseDTO.setId("mosip.id.update"); + idResponseDTO.setResponse(responseDTO); + idResponseDTO.setResponsetime("2019-01-17T06:29:01.940Z"); + idResponseDTO.setVersion("1.0"); + + when(idrepoDraftService.idrepoUpdateDraft(anyString(), any(), any())).thenReturn(idResponseDTO); + when(utility.getRegistrationProcessorMappingJson(MappingJsonConstants.IDENTITY)).thenReturn(identityObj); + when(utility.getRegistrationProcessorMappingJson(MappingJsonConstants.DOCUMENT)).thenReturn(documentObj); + + MessageDTO result = uinGeneratorStage.process(messageDTO); + assertFalse(result.getInternalError()); + assertTrue(result.getIsValid()); + } + + @Test + public void testUinGenerationIDRepoDraftException() throws Exception { + MessageDTO messageDTO = new MessageDTO(); + messageDTO.setRid("27847657360002520181210094052"); + messageDTO.setReg_type(RegistrationType.NEW.name()); + + when(registrationStatusMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.IDREPO_DRAFT_EXCEPTION)).thenReturn("FAILED"); + when(idrepoDraftService.idrepoUpdateDraft(anyString(), any(), any())).thenThrow(IdrepoDraftException.class); + when(utility.getRegistrationProcessorMappingJson(MappingJsonConstants.IDENTITY)).thenReturn(identityObj); + when(utility.getRegistrationProcessorMappingJson(MappingJsonConstants.DOCUMENT)).thenReturn(documentObj); + + MessageDTO result = uinGeneratorStage.process(messageDTO); + assertTrue(result.getInternalError()); + assertFalse(result.getIsValid()); + } + + @Test + public void testUinGenerationIDRepoDraftAPiResourceException() throws Exception { + + ApisResourceAccessException apisResourceAccessException = Mockito.mock(ApisResourceAccessException.class); + HttpServerErrorException httpServerErrorException = new HttpServerErrorException( + HttpStatus.INTERNAL_SERVER_ERROR, "KER-FSE-004:encrypted data is corrupted or not base64 encoded"); + when(apisResourceAccessException.getCause()).thenReturn(httpServerErrorException); + + Map fieldMap = new HashMap<>(); + fieldMap.put("UIN", "123456"); + fieldMap.put("name", "mono"); + fieldMap.put("email", "mono@mono.com"); + + List defaultFields = new ArrayList<>(); + defaultFields.add("name"); + defaultFields.add("dob"); + defaultFields.add("gender"); + defaultFields.add("UIN"); + + + when(packetManagerService.getFieldByMappingJsonKey(anyString(),anyString(),any(),any())).thenReturn("0.1"); + when(packetManagerService.getFields(any(), any(), any(), any())).thenReturn(fieldMap); + when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); + + MessageDTO messageDTO = new MessageDTO(); + messageDTO.setRid("27847657360002520181210094052"); + messageDTO.setReg_type(RegistrationType.UPDATE.name()); + + when(registrationStatusMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.APIS_RESOURCE_ACCESS_EXCEPTION)).thenReturn("REPROCESS"); + when(idrepoDraftService.idrepoUpdateDraft(anyString(), any(), any())).thenThrow(apisResourceAccessException); + when(utility.getRegistrationProcessorMappingJson(MappingJsonConstants.IDENTITY)).thenReturn(identityObj); + when(utility.getRegistrationProcessorMappingJson(MappingJsonConstants.DOCUMENT)).thenReturn(documentObj); + + MessageDTO result = uinGeneratorStage.process(messageDTO); + assertTrue(result.getInternalError()); + assertTrue(result.getIsValid()); + } + + @Test + public void testUinReActivationifAlreadyActivatedSuccess() throws Exception { + + MessageDTO messageDTO = new MessageDTO(); + messageDTO.setRid("27847657360002520181210094052"); + messageDTO.setReg_type(RegistrationType.valueOf("ACTIVATED").name()); + + IdResponseDTO idResponseDTO = new IdResponseDTO(); + ResponseDTO responseDTO = new ResponseDTO(); + idResponseDTO.setErrors(null); + idResponseDTO.setId("mosip.id.update"); + responseDTO.setStatus("ACTIVATED"); + idResponseDTO.setResponse(responseDTO); + idResponseDTO.setResponsetime("2019-01-17T06:29:01.940Z"); + idResponseDTO.setVersion("1.0"); + + Map fieldMap = new HashMap<>(); + fieldMap.put("UIN", "123456"); + fieldMap.put("name", "mono"); + fieldMap.put("email", "mono@mono.com"); + + List defaultFields = new ArrayList<>(); + defaultFields.add("name"); + defaultFields.add("dob"); + defaultFields.add("gender"); + defaultFields.add("UIN"); + + + when(packetManagerService.getFieldByMappingJsonKey(anyString(),anyString(),any(),any())).thenReturn("0.1"); + when(packetManagerService.getFields(any(), any(), any(), any())).thenReturn(fieldMap); + when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); + when(idrepoDraftService.idrepoUpdateDraft(anyString(), any(), any())).thenReturn(idResponseDTO); + + when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); + + when(registrationProcessorRestClientService.getApi(any(), any(), anyString(), any(), any())) + .thenReturn(idResponseDTO); + when(idrepoDraftService.idrepoUpdateDraft(anyString(), any(), any())).thenReturn(idResponseDTO); + + String idJsonData = "{\"identity\":{\"IDSchemaVersion\":1.0,\"UIN\":4215839851}}"; + + when(registrationProcessorRestClientService.postApi(any(), any(), any(), any(), any())) + .thenReturn(idResponseDTO); + MessageDTO result = uinGeneratorStage.process(messageDTO); + assertFalse(result.getIsValid()); + assertFalse(result.getInternalError()); + } + + @Test + public void testUinReActivationResponseStatusAsActivated() throws Exception { + Map fieldMap = new HashMap<>(); + fieldMap.put("UIN", "123456"); + fieldMap.put("name", "mono"); + fieldMap.put("email", "mono@mono.com"); + + List defaultFields = new ArrayList<>(); + defaultFields.add("name"); + defaultFields.add("dob"); + defaultFields.add("gender"); + defaultFields.add("UIN"); + + + when(packetManagerService.getFieldByMappingJsonKey(anyString(),anyString(),any(),any())).thenReturn("0.1"); + when(packetManagerService.getFields(any(), any(), any(), any())).thenReturn(fieldMap); + when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); + + MessageDTO messageDTO = new MessageDTO(); + messageDTO.setRid("27847657360002520181210094052"); + messageDTO.setReg_type(RegistrationType.valueOf("ACTIVATED").name()); + + IdResponseDTO idResponseDTO = new IdResponseDTO(); + ResponseDTO responseDTO = new ResponseDTO(); + idResponseDTO.setErrors(null); + idResponseDTO.setId("mosip.id.update"); + responseDTO.setStatus("ACTIVATED"); + idResponseDTO.setResponse(responseDTO); + idResponseDTO.setResponsetime("2019-01-17T06:29:01.940Z"); + idResponseDTO.setVersion("1.0"); + + when(registrationProcessorRestClientService.getApi(any(), any(), anyString(), any(), any())) + .thenReturn(idResponseDTO); + + when(idrepoDraftService.idrepoUpdateDraft(anyString(), any(), any())).thenReturn(idResponseDTO); + MessageDTO result = uinGeneratorStage.process(messageDTO); + assertFalse(result.getIsValid()); + assertFalse(result.getInternalError()); + } + + @Test + public void testUinReActivationIDraftResponseActivated() throws Exception { + Map fieldMap = new HashMap<>(); + fieldMap.put("UIN", "123456"); + fieldMap.put("name", "mono"); + fieldMap.put("email", "mono@mono.com"); + + List defaultFields = new ArrayList<>(); + defaultFields.add("name"); + defaultFields.add("dob"); + defaultFields.add("gender"); + defaultFields.add("UIN"); + + when(packetManagerService.getFieldByMappingJsonKey(anyString(),anyString(),any(),any())).thenReturn("0.1"); + when(packetManagerService.getFields(any(), any(), any(), any())).thenReturn(fieldMap); + when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); + + MessageDTO messageDTO = new MessageDTO(); + messageDTO.setRid("27847657360002520181210094052"); + messageDTO.setReg_type(RegistrationType.valueOf("ACTIVATED").name()); + + IdResponseDTO idResponseDTO = new IdResponseDTO(); + ResponseDTO responseDTO = new ResponseDTO(); + idResponseDTO.setErrors(null); + idResponseDTO.setId("mosip.id.update"); + responseDTO.setStatus("ACTIVATED"); + idResponseDTO.setResponse(responseDTO); + idResponseDTO.setResponsetime("2019-01-17T06:29:01.940Z"); + idResponseDTO.setVersion("1.0"); + + IdResponseDTO idResponseDTO1 = new IdResponseDTO(); + ResponseDTO responseDTO1 = new ResponseDTO(); + idResponseDTO1.setErrors(null); + idResponseDTO1.setId("mosip.id.update"); + responseDTO1.setStatus("ACTIVATED"); + idResponseDTO1.setResponse(responseDTO1); + + idResponseDTO1.setResponsetime("2019-01-17T06:29:01.940Z"); + idResponseDTO1.setVersion("1.0"); + + when(registrationProcessorRestClientService.getApi(any(), any(), anyString(), any(), any())) + .thenReturn(idResponseDTO); + + String idJsonData = "{\"identity\":{\"IDSchemaVersion\":1.0,\"UIN\":\"4215839851\"}}"; + + when(idrepoDraftService.idrepoUpdateDraft(anyString(), any(), any())).thenReturn(idResponseDTO); + when(registrationProcessorRestClientService.patchApi(any(), any(), any(), any(), any(), any())) + .thenReturn(idResponseDTO1); + MessageDTO result = uinGeneratorStage.process(messageDTO); + assertFalse(result.getIsValid()); + assertFalse(result.getInternalError()); + } + + @Test + public void testUinReActivationWithoutResponseDTO() throws Exception { + + Map fieldMap = new HashMap<>(); + fieldMap.put("UIN", "123456"); + fieldMap.put("name", "mono"); + fieldMap.put("email", "mono@mono.com"); + + List defaultFields = new ArrayList<>(); + defaultFields.add("name"); + defaultFields.add("dob"); + defaultFields.add("gender"); + defaultFields.add("UIN"); + + + when(packetManagerService.getFieldByMappingJsonKey(anyString(),anyString(),any(),any())).thenReturn("0.1"); + when(packetManagerService.getFields(any(), any(), any(), any())).thenReturn(fieldMap); + when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); + + when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); + + MessageDTO messageDTO = new MessageDTO(); + messageDTO.setRid("27847657360002520181210094052"); + messageDTO.setReg_type(RegistrationType.valueOf("ACTIVATED").name()); + + IdResponseDTO idResponseDTO = new IdResponseDTO(); + ResponseDTO responseDTO = new ResponseDTO(); + idResponseDTO.setErrors(null); + idResponseDTO.setId("mosip.id.update"); + responseDTO.setStatus("ANY"); + idResponseDTO.setResponse(responseDTO); + idResponseDTO.setResponsetime("2019-01-17T06:29:01.940Z"); + idResponseDTO.setVersion("1.0"); + + IdResponseDTO idResponseDTO1 = new IdResponseDTO(); + ResponseDTO responseDTO1 = new ResponseDTO(); + idResponseDTO1.setErrors(null); + idResponseDTO1.setId("mosip.id.update"); + responseDTO1.setStatus("ACTIVATED"); + idResponseDTO1.setResponse(null); + + idResponseDTO1.setResponsetime("2019-01-17T06:29:01.940Z"); + idResponseDTO1.setVersion("1.0"); + + when(registrationProcessorRestClientService.getApi(any(), any(), anyString(), any(), any())) + .thenReturn(idResponseDTO); + + String idJsonData = "{\"identity\":{\"IDSchemaVersion\":1.0,\"UIN\":\"4215839851\"}}";; + + when(idrepoDraftService.idrepoUpdateDraft(anyString(), any(), any())).thenReturn(idResponseDTO); + when(registrationProcessorRestClientService.patchApi(any(), any(), any(), any(), any(), any())) + .thenReturn(idResponseDTO1); + MessageDTO result = uinGeneratorStage.process(messageDTO); + assertFalse(result.getIsValid()); + assertFalse(result.getInternalError()); + } + + @Test + public void testUinReActivationWithResponseDTONull() throws Exception { + + Map fieldMap = new HashMap<>(); + fieldMap.put("UIN", "123456"); + fieldMap.put("name", "mono"); + fieldMap.put("email", "mono@mono.com"); + + List defaultFields = new ArrayList<>(); + defaultFields.add("name"); + defaultFields.add("dob"); + defaultFields.add("gender"); + defaultFields.add("UIN"); + + + when(packetManagerService.getFieldByMappingJsonKey(anyString(),anyString(),any(),any())).thenReturn("0.1"); + when(packetManagerService.getFields(any(), any(), any(), any())).thenReturn(fieldMap); + when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); + + MessageDTO messageDTO = new MessageDTO(); + messageDTO.setRid("27847657360002520181210094052"); + messageDTO.setReg_type(RegistrationType.valueOf("ACTIVATED").name()); + + IdResponseDTO idResponseDTO = new IdResponseDTO(); + ResponseDTO responseDTO = new ResponseDTO(); + idResponseDTO.setErrors(null); + idResponseDTO.setId("mosip.id.update"); + responseDTO.setStatus("ANY"); + idResponseDTO.setResponse(responseDTO); + idResponseDTO.setResponsetime("2019-01-17T06:29:01.940Z"); + idResponseDTO.setVersion("1.0"); + + IdResponseDTO idResponseDTO1 = new IdResponseDTO(); + idResponseDTO1.setResponse(null); + + when(registrationProcessorRestClientService.getApi(any(), any(), anyString(), any(), any())) + .thenReturn(idResponseDTO); + + when(idrepoDraftService.idrepoUpdateDraft(anyString(), any(), any())).thenReturn(idResponseDTO1); + MessageDTO result = uinGeneratorStage.process(messageDTO); + assertFalse(result.getIsValid()); + assertFalse(result.getInternalError()); + } + + + @Test + public void testUinReActivationWithStatusAsAny() throws Exception { + + Map fieldMaps = new HashMap<>(); + fieldMaps.put("UIN", "123456"); + fieldMaps.put("name", "mono"); + fieldMaps.put("email", "mono@mono.com"); + + List defaultFields = new ArrayList<>(); + defaultFields.add("name"); + defaultFields.add("dob"); + defaultFields.add("gender"); + defaultFields.add("UIN"); + + + when(packetManagerService.getFieldByMappingJsonKey(anyString(),anyString(),any(),any())).thenReturn("0.1"); + when(packetManagerService.getFields(any(), any(), any(), any())).thenReturn(fieldMaps); + when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); + + when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); + + MessageDTO messageDTO = new MessageDTO(); + messageDTO.setRid("27847657360002520181210094052"); + messageDTO.setReg_type(RegistrationType.valueOf("ACTIVATED").name()); + + IdResponseDTO idResponseDTO = new IdResponseDTO(); + ResponseDTO responseDTO = new ResponseDTO(); + idResponseDTO.setErrors(null); + idResponseDTO.setId("mosip.id.update"); + responseDTO.setStatus("ANY"); + idResponseDTO.setResponse(responseDTO); + idResponseDTO.setResponsetime("2019-01-17T06:29:01.940Z"); + idResponseDTO.setVersion("1.0"); + + IdResponseDTO idResponseDTO1 = new IdResponseDTO(); + ResponseDTO responseDTO1 = new ResponseDTO(); + idResponseDTO1.setErrors(null); + idResponseDTO1.setId("mosip.id.update"); + responseDTO1.setStatus("ANY"); + idResponseDTO1.setResponse(responseDTO1); + + idResponseDTO1.setResponsetime("2019-01-17T06:29:01.940Z"); + idResponseDTO1.setVersion("1.0"); + + when(registrationProcessorRestClientService.getApi(any(), any(), anyString(), any(), any())) + .thenReturn(idResponseDTO); + String idJsonData = "{\"identity\":{\"IDSchemaVersion\":1.0,\"UIN\":\"4215839851\"}}"; + + when(idrepoDraftService.idrepoUpdateDraft(anyString(), any(), any())).thenReturn(idResponseDTO); + when(registrationProcessorRestClientService.patchApi(any(), any(), any(), any(), any(), any())) + .thenReturn(idResponseDTO1); + + MessageDTO result = uinGeneratorStage.process(messageDTO); + assertFalse(result.getIsValid()); + assertFalse(result.getInternalError()); + } + + @Test + @Ignore + public void testUinReActivationIfNotActivatedSuccess() throws Exception { + + MessageDTO messageDTO = new MessageDTO(); + messageDTO.setRid("27847657360002520181210094052"); + messageDTO.setReg_type(RegistrationType.valueOf("ACTIVATED").name()); + + IdResponseDTO idResponseDTO = new IdResponseDTO(); + ResponseDTO responseDTO = new ResponseDTO(); + idResponseDTO.setErrors(null); + idResponseDTO.setId("mosip.id.update"); + responseDTO.setStatus("ANY"); + idResponseDTO.setResponse(responseDTO); + idResponseDTO.setResponsetime("2019-01-17T06:29:01.940Z"); + idResponseDTO.setVersion("1.0"); + + IdResponseDTO idResponseDTO1 = new IdResponseDTO(); + ResponseDTO responseDTO1 = new ResponseDTO(); + idResponseDTO1.setErrors(null); + idResponseDTO1.setId("mosip.id.update"); + responseDTO1.setStatus("ACTIVATED"); + idResponseDTO1.setResponse(responseDTO1); + + idResponseDTO1.setResponsetime("2019-01-17T06:29:01.940Z"); + idResponseDTO1.setVersion("1.0"); + + Map fieldMap = new HashMap<>(); + fieldMap.put("UIN", "123456"); + fieldMap.put("name", "mono"); + fieldMap.put("email", "mono@mono.com"); + + List defaultFields = new ArrayList<>(); + defaultFields.add("name"); + defaultFields.add("dob"); + defaultFields.add("gender"); + defaultFields.add("UIN"); + + when(idrepoDraftService.idrepoUpdateDraft(anyString(), any(), any())).thenReturn(idResponseDTO); + when(packetManagerService.getFields(any(), any(), any(), any())).thenReturn(fieldMap); + + when(packetManagerService.getFieldByMappingJsonKey(anyString(),anyString(),any(),any())).thenReturn("0.1"); + when(packetManagerService.getFields(anyString(),anyList(),anyString(),any())).thenReturn(fieldMap); + when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); + + when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); + + when(registrationProcessorRestClientService.getApi(any(), any(), anyString(), any(), any())) + .thenReturn(idResponseDTO); + + when(registrationProcessorRestClientService.patchApi(any(), any(), any(), any(), any(), any())) + .thenReturn(idResponseDTO1); + + MessageDTO result = uinGeneratorStage.process(messageDTO); + assertTrue(result.getIsValid()); + assertFalse(result.getInternalError()); + } + @Test + public void testUinReActivationIfNotGotActivatedStaus() throws Exception { + + Map fieldMap = new HashMap<>(); + fieldMap.put("UIN", "123456"); + fieldMap.put("name", "mono"); + fieldMap.put("email", "mono@mono.com"); + + List defaultFields = new ArrayList<>(); + defaultFields.add("name"); + defaultFields.add("dob"); + defaultFields.add("gender"); + defaultFields.add("UIN"); + + + when(packetManagerService.getFieldByMappingJsonKey(anyString(),anyString(),any(),any())).thenReturn("0.1"); + when(packetManagerService.getFields(any(), any(), any(), any())).thenReturn(fieldMap); + when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); + + when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); + + MessageDTO messageDTO = new MessageDTO(); + messageDTO.setRid("27847657360002520181210094052"); + messageDTO.setReg_type(RegistrationType.valueOf("ACTIVATED").name()); + + IdResponseDTO idResponseDTO = new IdResponseDTO(); + ResponseDTO responseDTO = new ResponseDTO(); + idResponseDTO.setErrors(null); + idResponseDTO.setId("mosip.id.update"); + responseDTO.setStatus("ANY"); + idResponseDTO.setResponse(responseDTO); + idResponseDTO.setResponsetime("2019-01-17T06:29:01.940Z"); + idResponseDTO.setVersion("1.0"); + + IdResponseDTO idResponseDTO1 = new IdResponseDTO(); + ResponseDTO responseDTO1 = new ResponseDTO(); + idResponseDTO1.setErrors(null); + idResponseDTO1.setId("mosip.id.update"); + responseDTO1.setStatus("ANY"); + idResponseDTO1.setResponse(responseDTO1); + idResponseDTO1.setResponsetime("2019-01-17T06:29:01.940Z"); + idResponseDTO1.setVersion("1.0"); + + when(registrationProcessorRestClientService.getApi(any(), any(), anyString(), any(), any())) + .thenReturn(idResponseDTO); + + String idJsonData = "{\"identity\":{\"IDSchemaVersion\":1.0,\"UIN\":4215839851}}"; + + when(idrepoDraftService.idrepoUpdateDraft(anyString(), any(), any())).thenReturn(idResponseDTO); + when(registrationProcessorRestClientService.patchApi(any(), any(), any(), any(), any(), any())) + .thenReturn(idResponseDTO1); + MessageDTO result = uinGeneratorStage.process(messageDTO); + assertFalse(result.getIsValid()); + assertFalse(result.getInternalError()); + } + + @Test + public void testUinReActivationFailure() throws Exception { + Map fieldMap = new HashMap<>(); + fieldMap.put("UIN", "123456"); + fieldMap.put("name", "mono"); + fieldMap.put("email", "mono@mono.com"); + + List defaultFields = new ArrayList<>(); + defaultFields.add("name"); + defaultFields.add("dob"); + defaultFields.add("gender"); + defaultFields.add("UIN"); + + + when(packetManagerService.getFieldByMappingJsonKey(anyString(),anyString(),any(),any())).thenReturn("0.1"); + when(packetManagerService.getFields(any(),any(),any(),any())).thenReturn(fieldMap); + when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); + + when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); + + MessageDTO messageDTO = new MessageDTO(); + messageDTO.setRid("27847657360002520181210094052"); + messageDTO.setReg_type(RegistrationType.valueOf("ACTIVATED").name()); + + IdResponseDTO idResponseDTO = new IdResponseDTO(); + ResponseDTO responseDTO = new ResponseDTO(); + idResponseDTO.setErrors(null); + idResponseDTO.setId("mosip.id.update"); + responseDTO.setStatus("ANY"); + idResponseDTO.setResponse(responseDTO); + idResponseDTO.setResponsetime("2019-01-17T06:29:01.940Z"); + idResponseDTO.setVersion("1.0"); + + IdResponseDTO idResponseDTO1 = new IdResponseDTO(); + List errors = new ArrayList<>(); + ErrorDTO errorDTO = new ErrorDTO("tets", "error"); + errors.add(errorDTO); + idResponseDTO1.setErrors(errors); + idResponseDTO1.setId("mosip.id.update"); + idResponseDTO1.setResponse(null); + idResponseDTO1.setResponsetime("2019-01-17T06:29:01.940Z"); + idResponseDTO1.setVersion("1.0"); + + when(registrationProcessorRestClientService.getApi(any(), any(), anyString(), any(), any())) + .thenReturn(idResponseDTO); + + String idJsonData = "{\"identity\":{\"IDSchemaVersion\":1.0,\"UIN\":4215839851}}"; + + when(idrepoDraftService.idrepoUpdateDraft(anyString(), any(), any())).thenReturn(idResponseDTO); + when(registrationProcessorRestClientService.patchApi(any(), any(), any(), any(), any(), any())) + .thenReturn(idResponseDTO1); + Mockito.when(registrationStatusMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.PACKET_UIN_GENERATION_REPROCESS)).thenReturn("REPROCESS"); + MessageDTO result = uinGeneratorStage.process(messageDTO); + assertFalse(result.getIsValid()); + assertFalse(result.getInternalError()); + } + + @Test + public void testExceptionInProcessTest() throws Exception { + ApisResourceAccessException exp = new ApisResourceAccessException( + HibernateErrorCode.ERR_DATABASE.getErrorCode()); + + when(registrationProcessorRestClientService.getApi(any(), any(), anyString(), any(), any())).thenReturn(exp); + Mockito.when(registrationStatusMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.PACKET_UIN_GENERATION_REPROCESS)).thenReturn("REPROCESS"); + + MessageDTO messageDTO = new MessageDTO(); + messageDTO.setRid("27847657360002520181210094052"); + MessageDTO result = uinGeneratorStage.process(messageDTO); + assertTrue(result.getInternalError()); + assertTrue(result.getIsValid()); + } + + @Test + public void testApiResourceExceptionInSendIdRepoTest() throws Exception { + + ApisResourceAccessException exp = new ApisResourceAccessException( + HibernateErrorCode.ERR_DATABASE.getErrorCode()); + String Str = "{\"uin\":\"6517036426\"}"; + + when(registrationProcessorRestClientService.postApi(any(), any(), any(), any(), any())).thenThrow(exp); + Mockito.when(registrationStatusMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.PACKET_UIN_GENERATION_REPROCESS)).thenReturn("REPROCESS"); + + MessageDTO messageDTO = new MessageDTO(); + messageDTO.setRid("27847657360002520181210094052"); + MessageDTO result = uinGeneratorStage.process(messageDTO); + assertTrue(result.getInternalError()); + assertTrue(result.getIsValid()); + } + + @Test + public void testApiResourceExceptionInUpdateIdRepoTest() throws Exception { + ApisResourceAccessException exp = new ApisResourceAccessException( + HibernateErrorCode.ERR_DATABASE.getErrorCode()); + + when(registrationProcessorRestClientService.postApi(any(), any(), any(), any(), any())).thenThrow(exp); + MessageDTO messageDTO = new MessageDTO(); + messageDTO.setRid("27847657360002520181210094052"); + Mockito.when(registrationStatusMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.PACKET_UIN_GENERATION_REPROCESS)).thenReturn("REPROCESS"); + MessageDTO result = uinGeneratorStage.process(messageDTO); + assertTrue(result.getInternalError()); + assertTrue(result.getIsValid()); + } + + @Test + public void deactivateTestSuccess() throws ApisResourceAccessException, IOException, JSONException, + JsonProcessingException, PacketManagerException, IdrepoDraftException, IdrepoDraftReprocessableException { + + Map fieldMap = new HashMap<>(); + fieldMap.put("UIN", "123456"); + fieldMap.put("name", "mono"); + fieldMap.put("email", "mono@mono.com"); + + List defaultFields = new ArrayList<>(); + defaultFields.add("name"); + defaultFields.add("dob"); + defaultFields.add("gender"); + defaultFields.add("UIN"); + + when(packetManagerService.getFields(any(), any(), any(), any())).thenReturn(fieldMap); + + + when(packetManagerService.getFieldByMappingJsonKey(anyString(),anyString(),any(),any())).thenReturn("0.1"); + when(packetManagerService.getFields(anyString(),anyList(),anyString(),any())).thenReturn(fieldMap); + when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); + + when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); + MessageDTO messageDTO = new MessageDTO(); + messageDTO.setRid("10031100110005020190313110030"); + messageDTO.setReg_type(RegistrationType.valueOf("DEACTIVATED").name()); + IdResponseDTO responsedto = new IdResponseDTO(); + String idJson = "{\"identity\":{\"IDSchemaVersion\":1.0,\"UIN\":\"4215839851\"}}"; + InputStream idJsonStream1 = new ByteArrayInputStream(idJson.getBytes(StandardCharsets.UTF_8)); + + IdResponseDTO idResponseDTO = new IdResponseDTO(); + ResponseDTO responseDTO = new ResponseDTO(); + idResponseDTO.setErrors(null); + idResponseDTO.setId("mosip.id.update"); + responseDTO.setStatus("DEACTIVATED"); + idResponseDTO.setResponse(responseDTO); + idResponseDTO.setResponsetime("2019-03-12T06:49:30.779Z"); + idResponseDTO.setVersion("1.0"); + + when(idrepoDraftService.idrepoUpdateDraft(anyString(), any(), any())).thenReturn(idResponseDTO); + when(registrationProcessorRestClientService.getApi(any(), any(), anyString(), any(), any())) + .thenReturn(responsedto); + when(registrationProcessorRestClientService.patchApi(any(), any(), any(), any(), any(), any())) + .thenReturn(idResponseDTO); + + MessageDTO result = uinGeneratorStage.process(messageDTO); + assertTrue(result.getIsValid()); + assertFalse(result.getInternalError()); + } + + @Test + public void checkIsUinDeactivatedSuccess() throws ApisResourceAccessException, IOException, JSONException, JsonProcessingException, PacketManagerException { + + Map fieldMap = new HashMap<>(); + fieldMap.put("UIN", "123456"); + fieldMap.put("name", "mono"); + fieldMap.put("email", "mono@mono.com"); + + List defaultFields = new ArrayList<>(); + defaultFields.add("name"); + defaultFields.add("dob"); + defaultFields.add("gender"); + defaultFields.add("UIN"); + + + when(packetManagerService.getFieldByMappingJsonKey(anyString(),anyString(),any(),any())).thenReturn("0.1"); + when(packetManagerService.getFields(any(), any(), any(), any())).thenReturn(fieldMap); + when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); + + when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); + + MessageDTO messageDTO = new MessageDTO(); + messageDTO.setRid("10031100110005020190313110030"); + messageDTO.setReg_type(RegistrationType.valueOf("DEACTIVATED").name()); + + String idJson = "{\"identity\":{\"IDSchemaVersion\":1.0,\"UIN\":4215839851}}"; + ResponseDTO responseDTO = new ResponseDTO(); + + responseDTO.setStatus("DEACTIVATED"); + IdResponseDTO responsedto = new IdResponseDTO(); + responsedto.setResponse(responseDTO); + + when(registrationProcessorRestClientService.getApi(any(), any(), anyString(), any(), any(Class.class))) + .thenReturn(responsedto); + MessageDTO result = uinGeneratorStage.process(messageDTO); + assertFalse(result.getIsValid()); + assertFalse(result.getInternalError()); + } + @Test + public void deactivateTestWithDeactivate() throws ApisResourceAccessException, IOException, JSONException, + JsonProcessingException, PacketManagerException, IdrepoDraftException, IdrepoDraftReprocessableException { + Map fieldMap = new HashMap<>(); + fieldMap.put("UIN", "123456"); + fieldMap.put("name", "mono"); + fieldMap.put("email", "mono@mono.com"); + + List defaultFields = new ArrayList<>(); + defaultFields.add("name"); + defaultFields.add("dob"); + defaultFields.add("gender"); + defaultFields.add("UIN"); + + + when(packetManagerService.getFieldByMappingJsonKey(anyString(),anyString(),any(),any())).thenReturn("0.1"); + when(packetManagerService.getFields(any(), any(), any(), any())).thenReturn(fieldMap); + when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); + + when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); + + MessageDTO messageDTO = new MessageDTO(); + messageDTO.setRid("10031100110005020190313110030"); + messageDTO.setReg_type(RegistrationType.valueOf("DEACTIVATED").name()); + IdResponseDTO responsedto = new IdResponseDTO(); + ResponseDTO responseDTO1 = new ResponseDTO(); + responseDTO1.setStatus("DEACTIVATED"); + responsedto.setResponse(responseDTO1); + String idJson = "{\"identity\":{\"IDSchemaVersion\":1.0,\"UIN\":\"4215839851\"}}"; + InputStream idJsonStream1 = new ByteArrayInputStream(idJson.getBytes(StandardCharsets.UTF_8)); + + IdResponseDTO idResponseDTO = new IdResponseDTO(); + ResponseDTO responseDTO = new ResponseDTO(); + idResponseDTO.setErrors(null); + idResponseDTO.setId("mosip.id.update"); + responseDTO.setStatus("DEACTIVATED"); + idResponseDTO.setResponse(responseDTO); + idResponseDTO.setResponsetime("2019-03-12T06:49:30.779Z"); + idResponseDTO.setVersion("1.0"); + + when(idrepoDraftService.idrepoUpdateDraft(anyString(), any(), any())).thenReturn(idResponseDTO); + when(registrationProcessorRestClientService.getApi(any(), any(), anyString(), any(), any())) + .thenReturn(responsedto); + when(registrationProcessorRestClientService.patchApi(any(), any(), any(), any(), any(), any())) + .thenReturn(idResponseDTO); + MessageDTO result = uinGeneratorStage.process(messageDTO); + assertFalse(result.getIsValid()); + assertFalse(result.getInternalError()); + } + + @Test + public void deactivateTestWithNullResponseDTO() + throws ApisResourceAccessException, PacketManagerException, IOException, JsonProcessingException, + JSONException, IdrepoDraftException, IdrepoDraftReprocessableException { + Map fieldMap = new HashMap<>(); + fieldMap.put("UIN", "123456"); + fieldMap.put("name", "mono"); + fieldMap.put("email", "mono@mono.com"); + + List defaultFields = new ArrayList<>(); + defaultFields.add("name"); + defaultFields.add("dob"); + defaultFields.add("gender"); + defaultFields.add("UIN"); + + + when(packetManagerService.getFieldByMappingJsonKey(anyString(),anyString(),any(),any())).thenReturn("0.1"); + when(packetManagerService.getFields(any(), any(), any(), any())).thenReturn(fieldMap); + when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); + + when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); + MessageDTO messageDTO = new MessageDTO(); + messageDTO.setRid("10031100110005020190313110030"); + messageDTO.setReg_type(RegistrationType.valueOf("DEACTIVATED").name()); + IdResponseDTO responsedto = new IdResponseDTO(); + String idJson = "{\"identity\":{\"IDSchemaVersion\":1.0,\"UIN\":\"4215839851\"}}"; + InputStream idJsonStream1 = new ByteArrayInputStream(idJson.getBytes(StandardCharsets.UTF_8)); + + IdResponseDTO idResponseDTO = new IdResponseDTO(); + ResponseDTO responseDTO = new ResponseDTO(); + idResponseDTO.setErrors(null); + idResponseDTO.setId("mosip.id.update"); + responseDTO.setStatus("DEACTIVATED"); + idResponseDTO.setResponse(null); + idResponseDTO.setResponsetime("2019-03-12T06:49:30.779Z"); + idResponseDTO.setVersion("1.0"); + + when(idrepoDraftService.idrepoUpdateDraft(anyString(), any(), any())).thenReturn(idResponseDTO); + when(registrationProcessorRestClientService.getApi(any(), any(), anyString(), any(), any())) + .thenReturn(responsedto); + when(registrationProcessorRestClientService.patchApi(any(), any(), any(), any(), any(), any())) + .thenReturn(idResponseDTO); + Mockito.when(registrationStatusMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.PACKET_UIN_GENERATION_REPROCESS)).thenReturn("REPROCESS"); + MessageDTO result = uinGeneratorStage.process(messageDTO); + assertFalse(result.getIsValid()); + assertFalse(result.getInternalError()); + } + + @Test + public void deactivateTestForExistingUinTestSuccess() + throws ApisResourceAccessException, PacketManagerException, IOException, JsonProcessingException, + JSONException, IdrepoDraftException, IdrepoDraftReprocessableException { + MessageDTO messageDTO = new MessageDTO(); + messageDTO.setRid("10031100110005020190313110030"); + messageDTO.setReg_type(RegistrationType.valueOf("DEACTIVATED").name()); + + ErrorDTO errorDto = new ErrorDTO(); + errorDto.setErrorCode("KER-IDR-001"); + errorDto.setMessage("Record already Exists in DB"); + + List errors = new ArrayList<>(); + errors.add(errorDto); + + IdResponseDTO idResponseDTO = new IdResponseDTO(); + ResponseDTO responseDTO = new ResponseDTO(); + idResponseDTO.setErrors(errors); + idResponseDTO.setId("mosip.id.update"); + ResponseDTO responseDTO1 = new ResponseDTO(); + responseDTO1.setStatus("DEACTIVATED"); + idResponseDTO.setResponse(responseDTO1); + idResponseDTO.setResponsetime("2019-03-12T06:49:30.779Z"); + idResponseDTO.setVersion("1.0"); + + Map fieldMap = new HashMap<>(); + fieldMap.put("UIN", "123456"); + fieldMap.put("name", "mono"); + fieldMap.put("email", "mono@mono.com"); + + List defaultFields = new ArrayList<>(); + defaultFields.add("name"); + defaultFields.add("dob"); + defaultFields.add("gender"); + defaultFields.add("UIN"); + + when(idrepoDraftService.idrepoUpdateDraft(anyString(), any(), any())).thenReturn(idResponseDTO); + + when(packetManagerService.getFieldByMappingJsonKey(anyString(),anyString(),any(),any())).thenReturn("0.1"); + when(packetManagerService.getFields(any(), any(), any(), any())).thenReturn(fieldMap); + when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); + + when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); + when(registrationProcessorRestClientService.patchApi(any(), any(), any(), any(), any(), any())) + .thenReturn(idResponseDTO); + when(registrationProcessorRestClientService.getApi(any(), any(), anyString(), any(), any())) + .thenReturn(idResponseDTO); + MessageDTO result = uinGeneratorStage.process(messageDTO); + assertFalse(result.getIsValid()); + assertFalse(result.getInternalError()); + } + + @Test + public void deactivateTestFailure() throws ApisResourceAccessException, PacketManagerException, IOException, + JsonProcessingException, JSONException, IdrepoDraftException, IdrepoDraftReprocessableException { + + Map fieldMap = new HashMap<>(); + fieldMap.put("UIN", "123456"); + fieldMap.put("name", "mono"); + fieldMap.put("email", "mono@mono.com"); + + List defaultFields = new ArrayList<>(); + defaultFields.add("name"); + defaultFields.add("dob"); + defaultFields.add("gender"); + defaultFields.add("UIN"); + + + when(packetManagerService.getFieldByMappingJsonKey(anyString(),anyString(),any(),any())).thenReturn("0.1"); + when(packetManagerService.getFields(any(),any(),any(),any())).thenReturn(fieldMap); + when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); + + when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); + + ApisResourceAccessException exp = new ApisResourceAccessException( + HibernateErrorCode.ERR_DATABASE.getErrorCode()); + + MessageDTO messageDTO = new MessageDTO(); + messageDTO.setRid("10031100110005020190313110030"); + messageDTO.setReg_type(RegistrationType.valueOf("DEACTIVATED").name()); + + String idJson = "{\"identity\":{\"IDSchemaVersion\":1.0,\"UIN\":4215839851}}"; + InputStream idJsonStream1 = new ByteArrayInputStream(idJson.getBytes(StandardCharsets.UTF_8)); + + ErrorDTO errorDto = new ErrorDTO(); + errorDto.setErrorCode("KER-IDR-001"); + errorDto.setMessage("Record already Exists in DB"); + + List errors = new ArrayList<>(); + errors.add(errorDto); + + IdResponseDTO idResponseDTO = new IdResponseDTO(); + ResponseDTO responseDTO = new ResponseDTO(); + idResponseDTO.setErrors(errors); + idResponseDTO.setId("mosip.id.update"); + responseDTO.setStatus("DEACTIVATED"); + idResponseDTO.setResponse(responseDTO); + idResponseDTO.setResponsetime("2019-03-12T06:49:30.779Z"); + idResponseDTO.setVersion("1.0"); + + when(idrepoDraftService.idrepoUpdateDraft(anyString(), any(), any())).thenReturn(idResponseDTO); + when(registrationProcessorRestClientService.getApi(any(), any(), anyString(), any(), any())) + .thenReturn(idResponseDTO); + + when(registrationProcessorRestClientService.patchApi(any(), any(), any(), any(), any(), any())) + .thenThrow(exp); + Mockito.when(registrationStatusMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.PACKET_UIN_GENERATION_REPROCESS)).thenReturn("REPROCESS"); + MessageDTO result = uinGeneratorStage.process(messageDTO); + assertFalse(result.getInternalError()); + assertFalse(result.getIsValid()); + } + + @Test + public void apisResourceAccessExceptionTest() + throws ApisResourceAccessException, IOException, IdrepoDraftException, IdrepoDraftReprocessableException { + + ApisResourceAccessException apisResourceAccessException = Mockito.mock(ApisResourceAccessException.class); + HttpServerErrorException httpServerErrorException = new HttpServerErrorException( + HttpStatus.INTERNAL_SERVER_ERROR, "KER-FSE-004:encrypted data is corrupted or not base64 encoded"); + when(apisResourceAccessException.getCause()).thenReturn(httpServerErrorException); + + MessageDTO messageDTO = new MessageDTO(); + messageDTO.setRid("10031100110005020190313110030"); + messageDTO.setReg_type(RegistrationType.valueOf("DEACTIVATED").name()); + + when(idrepoDraftService.idrepoUpdateDraft(anyString(), any(), any())).thenThrow(apisResourceAccessException); + Mockito.when(registrationStatusMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.APIS_RESOURCE_ACCESS_EXCEPTION)).thenReturn("REPROCESS"); + when(utility.getRegistrationProcessorMappingJson(MappingJsonConstants.IDENTITY)).thenReturn(identityObj); + when(utility.getRegistrationProcessorMappingJson(MappingJsonConstants.DOCUMENT)).thenReturn(documentObj); + + MessageDTO result = uinGeneratorStage.process(messageDTO); + assertTrue(result.getInternalError()); + assertTrue(result.getIsValid()); + } + + + @Test + public void testHttpServerErrorException() throws Exception { + + ApisResourceAccessException apisResourceAccessException = Mockito.mock(ApisResourceAccessException.class); + HttpServerErrorException httpServerErrorException = new HttpServerErrorException( + HttpStatus.INTERNAL_SERVER_ERROR, "KER-FSE-004:encrypted data is corrupted or not base64 encoded"); + when(apisResourceAccessException.getCause()).thenReturn(httpServerErrorException); + MessageDTO messageDTO = new MessageDTO(); + messageDTO.setRid("27847657360002520181210094052"); + messageDTO.setReg_type(RegistrationType.valueOf("ACTIVATED").name()); + + when(idrepoDraftService.idrepoUpdateDraft(anyString(), any(), any())).thenThrow(apisResourceAccessException); + Mockito.when(registrationStatusMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.APIS_RESOURCE_ACCESS_EXCEPTION)).thenReturn("REPROCESS"); + when(utility.getRegistrationProcessorMappingJson(MappingJsonConstants.IDENTITY)).thenReturn(identityObj); + when(utility.getRegistrationProcessorMappingJson(MappingJsonConstants.DOCUMENT)).thenReturn(documentObj); + + MessageDTO result = uinGeneratorStage.process(messageDTO); + assertTrue(result.getInternalError()); + assertTrue(result.getIsValid()); + + } + @Test + public void testHttpClientErrorException() throws Exception { + + ApisResourceAccessException apisResourceAccessException = Mockito.mock(ApisResourceAccessException.class); + HttpClientErrorException httpClientErrorException = new HttpClientErrorException( + HttpStatus.INTERNAL_SERVER_ERROR, "KER-FSE-004:encrypted data is corrupted or not base64 encoded"); + when(apisResourceAccessException.getCause()).thenReturn(httpClientErrorException); + MessageDTO messageDTO = new MessageDTO(); + messageDTO.setRid("27847657360002520181210094052"); + messageDTO.setReg_type(RegistrationType.valueOf("ACTIVATED").name()); + String idJsonData = "{\"identity\":{\"IDSchemaVersion\":1.0,\"UIN\":\"4215839851\"}}"; + + when(idrepoDraftService.idrepoUpdateDraft(anyString(), any(), any())).thenThrow(apisResourceAccessException); + when(utility.getRegistrationProcessorMappingJson(MappingJsonConstants.IDENTITY)).thenReturn(identityObj); + when(utility.getRegistrationProcessorMappingJson(MappingJsonConstants.DOCUMENT)).thenReturn(documentObj); + + Mockito.when(registrationStatusMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.APIS_RESOURCE_ACCESS_EXCEPTION)).thenReturn("REPROCESS"); + MessageDTO result = uinGeneratorStage.process(messageDTO); + assertTrue(result.getInternalError()); + assertTrue(result.getIsValid()); + + } + + @Test + public void testUinGenerationHttpClientErrorException() throws Exception { + MessageDTO messageDTO = new MessageDTO(); + messageDTO.setRid("27847657360002520181210094052"); + String str = "{\"id\":\"mosip.id.read\",\"version\":\"1.0\",\"responsetime\":\"2019-04-05\",\"metadata\":null,\"response\":{\"uin\":\"2812936908\"},\"errors\":[{\"errorCode\":null,\"errorMessage\":null}]}"; + + ApisResourceAccessException apisResourceAccessException = Mockito.mock(ApisResourceAccessException.class); + HttpClientErrorException httpClientErrorException = new HttpClientErrorException( + HttpStatus.INTERNAL_SERVER_ERROR, "KER-FSE-004:encrypted data is corrupted or not base64 encoded"); + when(apisResourceAccessException.getCause()).thenReturn(httpClientErrorException); + when(idrepoDraftService.idrepoUpdateDraft(anyString(), any(), any())).thenThrow(apisResourceAccessException); + when(utility.getRegistrationProcessorMappingJson(MappingJsonConstants.IDENTITY)).thenReturn(identityObj); + when(utility.getRegistrationProcessorMappingJson(MappingJsonConstants.DOCUMENT)).thenReturn(documentObj); + + messageDTO.setReg_type(RegistrationType.NEW.name()); + Mockito.when(registrationStatusMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.APIS_RESOURCE_ACCESS_EXCEPTION)).thenReturn("REPROCESS"); + MessageDTO result = uinGeneratorStage.process(messageDTO); + assertTrue(result.getInternalError()); + assertTrue(result.getIsValid()); + + } + + @Test + public void testUinGenerationHttpServerErrorException() throws Exception { + MessageDTO messageDTO = new MessageDTO(); + messageDTO.setRid("27847657360002520181210094052"); + String str = "{\"id\":\"mosip.id.read\",\"version\":\"1.0\",\"responsetime\":\"2019-04-05\",\"metadata\":null,\"response\":{\"uin\":\"2812936908\"},\"errors\":[{\"errorCode\":null,\"errorMessage\":null}]}"; + + ApisResourceAccessException apisResourceAccessException = Mockito.mock(ApisResourceAccessException.class); + HttpServerErrorException httpServerErrorException = new HttpServerErrorException( + HttpStatus.INTERNAL_SERVER_ERROR, "KER-FSE-004:encrypted data is corrupted or not base64 encoded"); + when(apisResourceAccessException.getCause()).thenReturn(httpServerErrorException); + + when(idrepoDraftService.idrepoUpdateDraft(anyString(), any(), any())).thenThrow(apisResourceAccessException); + Mockito.when(registrationStatusMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.APIS_RESOURCE_ACCESS_EXCEPTION)).thenReturn("REPROCESS"); + messageDTO.setReg_type(RegistrationType.NEW.name()); + when(utility.getRegistrationProcessorMappingJson(MappingJsonConstants.IDENTITY)).thenReturn(identityObj); + when(utility.getRegistrationProcessorMappingJson(MappingJsonConstants.DOCUMENT)).thenReturn(documentObj); + + MessageDTO result = uinGeneratorStage.process(messageDTO); + assertTrue(result.getInternalError()); + assertTrue(result.getIsValid()); + } + + + @Test + public void clientErrorExceptionTest() + throws ApisResourceAccessException, IOException, IdrepoDraftException, IdrepoDraftReprocessableException { + + ApisResourceAccessException apisResourceAccessException = Mockito.mock(ApisResourceAccessException.class); + HttpClientErrorException httpErrorErrorException = new HttpClientErrorException( + HttpStatus.INTERNAL_SERVER_ERROR, "KER-FSE-004:encrypted data is corrupted or not base64 encoded"); + when(apisResourceAccessException.getCause()).thenReturn(httpErrorErrorException); + + MessageDTO messageDTO = new MessageDTO(); + messageDTO.setRid("10031100110005020190313110030"); + messageDTO.setReg_type(RegistrationType.valueOf("DEACTIVATED").name()); + + when(idrepoDraftService.idrepoUpdateDraft(anyString(), any(), any())).thenThrow(apisResourceAccessException); + Mockito.when(registrationStatusMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.APIS_RESOURCE_ACCESS_EXCEPTION)).thenReturn("REPROCESS"); + when(utility.getRegistrationProcessorMappingJson(MappingJsonConstants.IDENTITY)).thenReturn(identityObj); + when(utility.getRegistrationProcessorMappingJson(MappingJsonConstants.DOCUMENT)).thenReturn(documentObj); + + MessageDTO result = uinGeneratorStage.process(messageDTO); + assertTrue(result.getInternalError()); + assertTrue(result.getIsValid()); + } + + @Test + public void testIOException() { + IOException exception = new IOException("File not found"); + + Mockito.when(registrationStatusMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.PACKET_UIN_GENERATION_REPROCESS)).thenReturn("REPROCESS"); + MessageDTO messageDTO = new MessageDTO(); + messageDTO.setRid("27847657360002520181210094052"); + messageDTO.setReg_type(RegistrationType.valueOf("DEACTIVATED").name()); + MessageDTO result = uinGeneratorStage.process(messageDTO); + assertTrue(result.getInternalError()); + assertTrue(result.getIsValid()); + } + + + @Test + public void testDeployVerticle() { + uinGeneratorStage.deployVerticle(); + } + + @Test + @Ignore + public void testApiResourceException() + throws ApisResourceAccessException, IOException, IdrepoDraftException, IdrepoDraftReprocessableException { + MessageDTO messageDTO = new MessageDTO(); + messageDTO.setRid("10031100110005020190313110030"); + messageDTO.setReg_type(RegistrationType.valueOf("DEACTIVATED").name()); + IdResponseDTO responsedto = new IdResponseDTO(); + String idJson = "{\"identity\":{\"IDSchemaVersion\":1.0,\"UIN\":\"4215839851\"}}"; + + IdResponseDTO idResponseDTO = new IdResponseDTO(); + ResponseDTO responseDTO = new ResponseDTO(); + idResponseDTO.setErrors(null); + idResponseDTO.setId("mosip.id.update"); + responseDTO.setStatus("DEACTIVATED"); + idResponseDTO.setResponse(responseDTO); + idResponseDTO.setResponsetime("2019-03-12T06:49:30.779Z"); + idResponseDTO.setVersion("1.0"); + + when(idrepoDraftService.idrepoUpdateDraft(anyString(), any(), any())).thenReturn(idResponseDTO); + when(registrationProcessorRestClientService.getApi(any(), any(), anyString(), any(), any())) + .thenReturn(responsedto); + when(registrationProcessorRestClientService.patchApi(any(), any(), any(), any(), any(), any())) + .thenReturn(idResponseDTO); + + MessageDTO result = uinGeneratorStage.process(messageDTO); + assertTrue(result.getInternalError()); + assertTrue(result.getIsValid()); + } + + @Test + public void testApisResourceAccessExceptionPostApi() + throws ApisResourceAccessException, IOException, IdrepoDraftException, IdrepoDraftReprocessableException { + ApisResourceAccessException exc = new ApisResourceAccessException(); + MessageDTO messageDTO = new MessageDTO(); + messageDTO.setRid("27847657360002520181210094052"); + + when(registrationProcessorRestClientService.putApi(any(), any(), any(), any(), any(), any(), any())) + .thenThrow(exc); + + IdResponseDTO idResponseDTO = new IdResponseDTO(); + ResponseDTO responseDTO = null; + idResponseDTO.setErrors(null); + idResponseDTO.setId("mosip.id.update"); + idResponseDTO.setResponse(responseDTO); + idResponseDTO.setResponsetime("2019-01-17T06:29:01.940Z"); + idResponseDTO.setVersion("1.0"); + + when(idrepoDraftService.idrepoUpdateDraft(anyString(), any(), any())).thenReturn(idResponseDTO); + when(registrationProcessorRestClientService.postApi(any(), any(), any(), any(), any())) + .thenReturn(idResponseDTO); + Mockito.when(registrationStatusMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.PACKET_UIN_GENERATION_REPROCESS)).thenReturn("REPROCESS"); + MessageDTO result = uinGeneratorStage.process(messageDTO); + assertTrue(result.getInternalError()); + assertTrue(result.getIsValid()); + } + + @Test + public void testLinkSuccessForLostUin() throws Exception { + Map fieldMap = new HashMap<>(); + fieldMap.put("UIN", "123456"); + fieldMap.put("name", "mono"); + fieldMap.put("email", "mono@mono.com"); + + List defaultFields = new ArrayList<>(); + defaultFields.add("name"); + defaultFields.add("dob"); + defaultFields.add("gender"); + defaultFields.add("UIN"); + + + when(packetManagerService.getFieldByMappingJsonKey(anyString(),anyString(),any(),any())).thenReturn("0.1"); + when(packetManagerService.getFields(anyString(),anyList(),anyString(),any())).thenReturn(fieldMap); + when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); + + when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); + MessageDTO messageDTO = new MessageDTO(); + messageDTO.setRid("27847657360002520181210094052"); + messageDTO.setReg_type(RegistrationType.LOST.name()); + String str = "{\"id\":\"mosip.id.read\",\"version\":\"1.0\",\"responsetime\":\"2019-04-05\",\"metadata\":null,\"response\":{\"uin\":\"2812936908\"},\"errors\":[{\"errorCode\":null,\"errorMessage\":null}]}"; + String response = "{\"timestamp\":1553771083721,\"status\":404,\"errors\":[{\"errorCode\":\"KER-UIG-004\",\"errorMessage\":\"Given UIN is not in ISSUED status\"}]}"; + + + when(registrationProcessorRestClientService.putApi(any(), any(), any(), any(), any(), any(), any())) + .thenReturn(response); + + IdResponseDTO idResponseDTO = new IdResponseDTO(); + ResponseDTO responseDTO = new ResponseDTO(); + idResponseDTO.setErrors(null); + idResponseDTO.setId("mosip.id.update"); + responseDTO.setStatus("ACTIVATED"); + idResponseDTO.setResponse(responseDTO); + idResponseDTO.setResponsetime("2019-01-17T06:29:01.940Z"); + idResponseDTO.setVersion("1.0"); + + when(idrepoDraftService.idrepoUpdateDraft(anyString(), any(), any())).thenReturn(idResponseDTO); + when(registrationProcessorRestClientService.postApi(any(), any(), any(), any(), any(Class.class))) + .thenReturn(idResponseDTO); + when(registrationProcessorRestClientService.getApi(any(), any(), anyString(), any(), any(Class.class))) + .thenReturn(idResponseDTO); + when( + registrationProcessorRestClientService.patchApi(any(), any(), any(), any(), any(), any(Class.class))) + .thenReturn(idResponseDTO); + when(regLostUinDetEntity.getLostUinMatchedRegIdByWorkflowId(any())).thenReturn("27847657360002520181210094052"); + MessageDTO result = uinGeneratorStage.process(messageDTO); + assertFalse(result.getInternalError()); + assertTrue(result.getIsValid()); + } + + @Test + public void testLinkSuccessForLostUinAndUpdateContactInfo() throws Exception { + Map fieldMap = new HashMap<>(); + fieldMap.put("UIN", "123456"); + fieldMap.put("name", "mono"); + fieldMap.put("email", "mono@mono.com"); + + List defaultFields = new ArrayList<>(); + defaultFields.add("name"); + defaultFields.add("dob"); + defaultFields.add("gender"); + defaultFields.add("UIN"); + when(idRepoService.getUinByRid(anyString(), anyString())).thenReturn("9403107397"); + + + when(packetManagerService.getFieldByMappingJsonKey(anyString(),anyString(),any(),any())).thenReturn("0.1"); + when(packetManagerService.getFields(anyString(),anyList(),anyString(),any())).thenReturn(fieldMap); + when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); + + when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); + MessageDTO messageDTO = new MessageDTO(); + messageDTO.setRid("27847657360002520181210094052"); + messageDTO.setReg_type(RegistrationType.LOST.name()); + String str = "{\"id\":\"mosip.id.read\",\"version\":\"1.0\",\"responsetime\":\"2019-04-05\",\"metadata\":null,\"response\":{\"uin\":\"2812936908\"},\"errors\":[{\"errorCode\":null,\"errorMessage\":null}]}"; + String response = "{\"timestamp\":1553771083721,\"status\":404,\"errors\":[{\"errorCode\":\"KER-UIG-004\",\"errorMessage\":\"Given UIN is not in ISSUED status\"}]}"; + + when(utility.getRegistrationProcessorMappingJson(MappingJsonConstants.IDENTITY)).thenReturn(identityObj); + when(registrationProcessorRestClientService.putApi(any(), any(), any(), any(), any(), any(), any())) + .thenReturn(response); + + IdResponseDTO idResponseDTO = new IdResponseDTO(); + ResponseDTO responseDTO = new ResponseDTO(); + idResponseDTO.setErrors(null); + idResponseDTO.setId("mosip.id.update"); + responseDTO.setStatus("ACTIVATED"); + 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(idrepoDraftService.idrepoUpdateDraft(anyString(), any(), any())).thenReturn(idResponseDTO); + when(registrationProcessorRestClientService.postApi(any(), any(), any(), any(), any(Class.class))) + .thenReturn(idResponseDTO); + when(registrationProcessorRestClientService.getApi(any(), any(), anyString(), any(), any(Class.class))) + .thenReturn(idResponseDTO); + when( + registrationProcessorRestClientService.patchApi(any(), any(), any(), any(), any(), any(Class.class))) + .thenReturn(idResponseDTO); + when(packetManagerService.getFieldByMappingJsonKey(any(), any(), any(), any())).thenReturn("1.0"); + when(regLostUinDetEntity.getLostUinMatchedRegIdByWorkflowId(any())).thenReturn("27847657360002520181210094052"); + MessageDTO result = uinGeneratorStage.process(messageDTO); + assertFalse(result.getInternalError()); + assertTrue(result.getIsValid()); + } + + @Test + public void updateTestSuccess() throws ApisResourceAccessException, IOException, JsonProcessingException, + PacketManagerException, JSONException, IdrepoDraftException, IdrepoDraftReprocessableException { + Map fieldMap = new HashMap<>(); + fieldMap.put("UIN", "123456"); + fieldMap.put("name", "mono"); + fieldMap.put("email", "mono@mono.com"); + + List defaultFields = new ArrayList<>(); + defaultFields.add("name"); + defaultFields.add("dob"); + defaultFields.add("gender"); + defaultFields.add("UIN"); + + when(packetManagerService.getFields(any(), any(), any(), any())).thenReturn(fieldMap); + + when(packetManagerService.getFieldByMappingJsonKey(anyString(),anyString(),any(),any())).thenReturn("0.1"); + when(packetManagerService.getFields(anyString(),anyList(),anyString(),any())).thenReturn(fieldMap); + when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); + + when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); + MessageDTO messageDTO = new MessageDTO(); + messageDTO.setRid("10031100110005020190313110030"); + messageDTO.setReg_type(RegistrationType.valueOf("UPDATE").name()); + IdResponseDTO responsedto = new IdResponseDTO(); + + IdResponseDTO idResponseDTO = new IdResponseDTO(); + ResponseDTO responseDTO = new ResponseDTO(); + idResponseDTO.setErrors(null); + idResponseDTO.setId("mosip.id.update"); + responseDTO.setStatus("ACTIVATED"); + idResponseDTO.setResponse(responseDTO); + idResponseDTO.setResponsetime("2019-03-12T06:49:30.779Z"); + idResponseDTO.setVersion("1.0"); + + when(idrepoDraftService.idrepoUpdateDraft(anyString(), any(), any())).thenReturn(idResponseDTO); + when(registrationProcessorRestClientService.getApi(any(), any(), anyString(), any(), any())) + .thenReturn(responsedto); + when(registrationProcessorRestClientService.patchApi(any(), any(), any(), any(), any(), any())) + .thenReturn(idResponseDTO); + when(utility.getRegistrationProcessorMappingJson(MappingJsonConstants.IDENTITY)).thenReturn(identityObj); + when(utility.getRegistrationProcessorMappingJson(MappingJsonConstants.DOCUMENT)).thenReturn(documentObj); + + MessageDTO result = uinGeneratorStage.process(messageDTO); + assertTrue(result.getIsValid()); + assertFalse(result.getInternalError()); + } + + @Test + public void testLinkSuccessForLostUinisNull() throws Exception { + MessageDTO messageDTO = new MessageDTO(); + messageDTO.setRid("27847657360002520181210094052"); + messageDTO.setReg_type(RegistrationType.LOST.name()); + String str = "{\"id\":\"mosip.id.read\",\"version\":\"1.0\",\"responsetime\":\"2019-04-05\",\"metadata\":null,\"response\":{\"uin\":\"2812936908\"},\"errors\":[{\"errorCode\":null,\"errorMessage\":null}]}"; + String response = "{\"timestamp\":1553771083721,\"status\":404,\"errors\":[{\"errorCode\":\"KER-UIG-004\",\"errorMessage\":\"Given UIN is not in ISSUED status\"}]}"; + when(idRepoService.getUinByRid(anyString(), anyString())).thenReturn(null); + when(regLostUinDetEntity.getLostUinMatchedRegIdByWorkflowId(any())).thenReturn("27847657360002520181210094052"); + + when(registrationProcessorRestClientService.putApi(any(), any(), any(), any(), any(), any(), any())) + .thenReturn(response); + + IdResponseDTO idResponseDTO = new IdResponseDTO(); + ResponseDTO responseDTO = new ResponseDTO(); + idResponseDTO.setErrors(null); + idResponseDTO.setId("mosip.id.update"); + responseDTO.setStatus("ACTIVATED"); + idResponseDTO.setResponse(responseDTO); + idResponseDTO.setResponsetime("2019-01-17T06:29:01.940Z"); + idResponseDTO.setVersion("1.0"); + + when(idrepoDraftService.idrepoUpdateDraft(anyString(), any(), any())).thenReturn(idResponseDTO); + when(registrationProcessorRestClientService.postApi(any(), any(), any(), any(), any(Class.class))) + .thenReturn(idResponseDTO); + when(registrationProcessorRestClientService.getApi(any(), any(), anyString(), any(), any(Class.class))) + .thenReturn(idResponseDTO); + when( + registrationProcessorRestClientService.patchApi(any(), any(), any(), any(), any(), any(Class.class))) + .thenReturn(idResponseDTO); + MessageDTO result = uinGeneratorStage.process(messageDTO); + assertFalse(result.getIsValid()); + assertFalse(result.getInternalError()); + } + + @Test + public void testLinkSuccessForLostUinIdResponseIsNUll() throws Exception { + MessageDTO messageDTO = new MessageDTO(); + messageDTO.setRid("27847657360002520181210094052"); + messageDTO.setReg_type(RegistrationType.LOST.name()); + String str = "{\"id\":\"mosip.id.read\",\"version\":\"1.0\",\"responsetime\":\"2019-04-05\",\"metadata\":null,\"response\":{\"uin\":\"2812936908\"},\"errors\":[{\"errorCode\":null,\"errorMessage\":null}]}"; + String response = "{\"timestamp\":1553771083721,\"status\":404,\"errors\":[{\"errorCode\":\"KER-UIG-004\",\"errorMessage\":\"Given UIN is not in ISSUED status\"}]}"; + + + when(registrationProcessorRestClientService.putApi(any(), any(), any(), any(), any(), any(), any())) + .thenReturn(response); + when(regLostUinDetEntity.getLostUinMatchedRegIdByWorkflowId(any())).thenReturn("27847657360002520181210094052"); + + IdResponseDTO idResponseDTO = new IdResponseDTO(); + ResponseDTO responseDTO = new ResponseDTO(); + idResponseDTO.setErrors(null); + idResponseDTO.setId("mosip.id.update"); + responseDTO.setStatus("ACTIVATED"); + idResponseDTO.setResponse(responseDTO); + idResponseDTO.setResponsetime("2019-01-17T06:29:01.940Z"); + idResponseDTO.setVersion("1.0"); + + when(idrepoDraftService.idrepoUpdateDraft(anyString(), any(), any())).thenReturn(idResponseDTO); + when(registrationProcessorRestClientService.postApi(any(), any(), any(), any(), any(Class.class))) + .thenReturn(idResponseDTO); + when(registrationProcessorRestClientService.getApi(any(), any(), anyString(), any(), any(Class.class))) + .thenReturn(idResponseDTO); + when( + registrationProcessorRestClientService.patchApi(any(), any(), any(), any(), any(), any(Class.class))) + .thenReturn(null); + MessageDTO result = uinGeneratorStage.process(messageDTO); + assertTrue(result.getIsValid()); + assertFalse(result.getInternalError()); + } + + @Test + public void testUpdateSuccess() throws Exception { + + MessageDTO messageDTO = new MessageDTO(); + messageDTO.setRid("10031100110005020190313110030"); + messageDTO.setReg_type(RegistrationType.UPDATE.name()); + + Map fieldMap = new HashMap<>(); + fieldMap.put("UIN", "123456"); + fieldMap.put("name", "mono"); + fieldMap.put("email", "mono@mono.com"); + + List defaultFields = new ArrayList<>(); + defaultFields.add("name"); + defaultFields.add("dob"); + defaultFields.add("gender"); + defaultFields.add("UIN"); + + when(packetManagerService.getFields(any(), any(), any(), any())).thenReturn(fieldMap); + + when(packetManagerService.getFieldByMappingJsonKey(anyString(),anyString(),any(),any())).thenReturn("0.1"); + when(packetManagerService.getFields(anyString(),anyList(),anyString(),any())).thenReturn(fieldMap); + when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); + + when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); + + + IdResponseDTO idResponseDTO = new IdResponseDTO(); + ResponseDTO responseDTO = new ResponseDTO(); + responseDTO.setStatus("ACTIVATED"); + idResponseDTO.setErrors(null); + idResponseDTO.setId("mosip.id.update"); + + idResponseDTO.setErrors(null); + idResponseDTO.setResponse(responseDTO); + idResponseDTO.setResponsetime("2019-03-12T06:49:30.779Z"); + idResponseDTO.setVersion("1.0"); + + when(idrepoDraftService.idrepoUpdateDraft(anyString(), any(), any())).thenReturn(idResponseDTO); + when(registrationProcessorRestClientService.getApi(any(), any(), anyString(), any(), any())) + .thenReturn(idResponseDTO); + + IdResponseDTO idResponseDTO1 = new IdResponseDTO(); + ResponseDTO responseDTO1 = new ResponseDTO(); + idResponseDTO1.setErrors(null); + idResponseDTO1.setId("mosip.id.update"); + responseDTO1.setStatus("ACTIVATED"); + idResponseDTO1.setResponse(responseDTO1); + idResponseDTO1.setResponsetime("2019-01-17T06:29:01.940Z"); + idResponseDTO1.setVersion("1.0"); + + when(utility.getRegistrationProcessorMappingJson(MappingJsonConstants.IDENTITY)).thenReturn(identityObj); + when(utility.getRegistrationProcessorMappingJson(MappingJsonConstants.DOCUMENT)).thenReturn(documentObj); + when(registrationProcessorRestClientService.patchApi(any(), any(), any(), any(), any(), any())) + .thenReturn(idResponseDTO1); + + MessageDTO result = uinGeneratorStage.process(messageDTO); + assertFalse(result.getInternalError()); + assertTrue(result.getIsValid()); + } + + + @Test + public void testUpdateDraftFailed() throws Exception { + Map fieldMap = new HashMap<>(); + fieldMap.put("UIN", "123456"); + fieldMap.put("name", "mono"); + fieldMap.put("email", "mono@mono.com"); + + List defaultFields = new ArrayList<>(); + defaultFields.add("name"); + defaultFields.add("dob"); + defaultFields.add("gender"); + defaultFields.add("UIN"); + + when(packetManagerService.getFields(any(), any(), any(), any())).thenReturn(fieldMap); + + when(packetManagerService.getFieldByMappingJsonKey(anyString(),anyString(),any(),any())).thenReturn("0.1"); + when(packetManagerService.getFields(anyString(),anyList(),anyString(),any())).thenReturn(fieldMap); + when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); + + when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); + MessageDTO messageDTO = new MessageDTO(); + messageDTO.setRid("10031100110005020190313110030"); + messageDTO.setReg_type(RegistrationType.UPDATE.name()); + + IdResponseDTO responsedto = new IdResponseDTO(); + ErrorDTO errorDTO = new ErrorDTO(); + errorDTO.setErrorCode("ERROR"); + errorDTO.setMessage("ERROR message"); + responsedto.setErrors(Lists.newArrayList(errorDTO)); + when(idrepoDraftService.idrepoUpdateDraft(any(), any(), any())) + .thenReturn(responsedto); + + IdResponseDTO idResponseDTO1 = new IdResponseDTO(); + + when(registrationProcessorRestClientService.patchApi(any(), any(), any(), any(), any(), any())) + .thenReturn(idResponseDTO1); + when(utility.getRegistrationProcessorMappingJson(MappingJsonConstants.IDENTITY)).thenReturn(identityObj); + when(utility.getRegistrationProcessorMappingJson(MappingJsonConstants.DOCUMENT)).thenReturn(documentObj); + + MessageDTO result = uinGeneratorStage.process(messageDTO); + assertFalse(result.getInternalError()); + assertFalse(result.getIsValid()); + } + + @Test + public void testUinAlreadyExists() throws Exception { + Map fieldMap = new HashMap<>(); + fieldMap.put("UIN", "123456"); + fieldMap.put("name", "mono"); + fieldMap.put("email", "mono@mono.com"); + + List defaultFields = new ArrayList<>(); + defaultFields.add("name"); + defaultFields.add("dob"); + defaultFields.add("gender"); + defaultFields.add("UIN"); + + + when(packetManagerService.getFieldByMappingJsonKey(anyString(),anyString(),any(),any())).thenReturn("0.1"); + when(packetManagerService.getFields(anyString(),anyList(),anyString(),any())).thenReturn(fieldMap); + when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); + when(utility.getRegistrationProcessorMappingJson(MappingJsonConstants.IDENTITY)).thenReturn(identityObj); + when(utility.getRegistrationProcessorMappingJson(MappingJsonConstants.DOCUMENT)).thenReturn(documentObj); + + when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); + MessageDTO messageDTO = new MessageDTO(); + messageDTO.setRid("27847657360002520181210094052"); + messageDTO.setReg_type(RegistrationType.NEW.name()); + String response = "{\"timestamp\":1553771083721,\"status\":404,\"errors\":[{\"errorCode\":\"KER-UIG-004\",\"errorMessage\":\"Given UIN is not in ISSUED status\"}]}"; + + + when(registrationProcessorRestClientService.putApi(any(), any(), any(), any(), any(), any(), any())) + .thenReturn(response); + + IdResponseDTO idResponseDTO = new IdResponseDTO(); + idResponseDTO.setErrors(null); + idResponseDTO.setId("mosip.id.update"); + ErrorDTO errorDTO = new ErrorDTO("IDR-IDC-012", "Record already exists in DB"); + idResponseDTO.setErrors(Lists.newArrayList(errorDTO)); + idResponseDTO.setResponsetime("2019-01-17T06:29:01.940Z"); + idResponseDTO.setVersion("1.0"); + + when(idrepoDraftService.idrepoUpdateDraft(anyString(), any(), any())).thenReturn(idResponseDTO); + + MessageDTO result = uinGeneratorStage.process(messageDTO); + assertTrue(result.getIsValid()); + assertFalse(result.getInternalError()); + } + + + @Test + public void testUinGenerationSuccessWithAllDocuments() throws Exception { + Map fieldMap = new HashMap<>(); + fieldMap.put("name", "mono"); + fieldMap.put("email", "mono@mono.com"); + fieldMap.put("phone", "23456"); + fieldMap.put("dob", "11/11/2011"); + fieldMap.put("proofOfIdentity", "{\"value\":\"POA_Rental contract\",\"type\":\"Rental contract\",\"format\":\"jpg\"}"); + fieldMap.put("proofOfRelationship", "{\"value\":\"POA_Rental contract\",\"type\":\"Rental contract\",\"format\":\"jpg\"}"); + fieldMap.put("proofOfDateOfBirth", "{\"value\":\"POA_Rental contract\",\"type\":\"Rental contract\",\"format\":\"jpg\"}"); + fieldMap.put("proofOfException", "{\"value\":\"POA_Rental contract\",\"type\":\"Rental contract\",\"format\":\"jpg\"}"); + fieldMap.put("proofOfAddress", "{\"value\":\"POA_Rental contract\",\"type\":\"Rental contract\",\"format\":\"jpg\"}"); + fieldMap.put("individualBiometrics", "{\"format\":\"cbeff\",\"version\":1,\"value\":\"applicant_bio_CBEFF\"}"); + + MessageDTO messageDTO = new MessageDTO(); + messageDTO.setRid("27847657360002520181210094052"); + messageDTO.setReg_type(RegistrationType.NEW.name()); + + IdResponseDTO idResponseDTO = new IdResponseDTO(); + ResponseDTO responseDTO = new ResponseDTO(); + responseDTO.setStatus("ACTIVATED"); + idResponseDTO.setErrors(null); + idResponseDTO.setId("mosip.id.update"); + idResponseDTO.setResponse(responseDTO); + idResponseDTO.setResponsetime("2019-01-17T06:29:01.940Z"); + idResponseDTO.setVersion("1.0"); + + when(packetManagerService.getFields(any(), any(), any(), any())).thenReturn(fieldMap); + when(idrepoDraftService.idrepoUpdateDraft(anyString(), any(), any())).thenReturn(idResponseDTO); + + String str = "{\"id\":\"mosip.id.read\",\"version\":\"1.0\",\"responsetime\":\"2019-04-05\",\"metadata\":null,\"response\":{\"uin\":\"2812936908\"},\"errors\":[{\"errorCode\":null,\"errorMessage\":null}]}"; + when(registrationProcessorRestClientService.getApi(any(), any(), anyString(), + anyString(), any(Class.class))).thenReturn(str); + when(utility.getRegistrationProcessorMappingJson(MappingJsonConstants.IDENTITY)).thenReturn(identityObj); + when(utility.getRegistrationProcessorMappingJson(MappingJsonConstants.DOCUMENT)).thenReturn(documentObj); + + MessageDTO result = uinGeneratorStage.process(messageDTO); + assertFalse(result.getInternalError()); + assertTrue(result.getIsValid()); + } + + @Test + public void testPacketFetchingException() throws Exception { + when(packetManagerService.getFieldByMappingJsonKey(any(), any(),any(), any())).thenThrow(new PacketManagerException("", "")); + MessageDTO messageDTO = new MessageDTO(); + messageDTO.setRid("27847657360002520181210094052"); + messageDTO.setReg_type(RegistrationType.NEW.name()); + Mockito.when(registrationStatusMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.PACKET_MANAGER_EXCEPTION)).thenReturn("REPROCESS"); + MessageDTO result = uinGeneratorStage.process(messageDTO); + assertTrue(result.getInternalError()); + assertTrue(result.getIsValid()); + } + + @Test + public void testJsonProcessingException() throws ApisResourceAccessException, IOException, PacketManagerException, JsonProcessingException { + + when(packetManagerService.getFieldByMappingJsonKey(any(), any(),any(), any())).thenThrow(new io.mosip.kernel.core.util.exception.JsonProcessingException("")); + MessageDTO messageDTO = new MessageDTO(); + messageDTO.setRid("27847657360002520181210094052"); + Mockito.when(registrationStatusMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.JSON_PROCESSING_EXCEPTION)).thenReturn("ERROR"); + MessageDTO result = uinGeneratorStage.process(messageDTO); + assertTrue(result.getInternalError()); + assertFalse(result.getIsValid()); + } + + @Test + public void testUinReActivationWithoutIDResponseDTO() throws Exception { + + Map fieldMap = new HashMap<>(); + fieldMap.put("UIN", "123456"); + fieldMap.put("name", "mono"); + fieldMap.put("email", "mono@mono.com"); + + List defaultFields = new ArrayList<>(); + defaultFields.add("name"); + defaultFields.add("dob"); + defaultFields.add("gender"); + defaultFields.add("UIN"); + + + when(packetManagerService.getFieldByMappingJsonKey(anyString(), anyString(), any(), any())).thenReturn("0.1"); + when(packetManagerService.getFields(any(), any(), any(), any())).thenReturn(fieldMap); + when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); + + when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); + + MessageDTO messageDTO = new MessageDTO(); + messageDTO.setRid("27847657360002520181210094052"); + messageDTO.setReg_type(RegistrationType.valueOf("ACTIVATED").name()); + + IdResponseDTO idResponseDTO = new IdResponseDTO(); + idResponseDTO.setResponse(null); + + IdResponseDTO idResponseDTO1 = new IdResponseDTO(); + ResponseDTO responseDTO1 = new ResponseDTO(); + idResponseDTO1.setErrors(null); + idResponseDTO1.setId("mosip.id.update"); + responseDTO1.setStatus("ACTIVATED"); + idResponseDTO1.setResponse(null); + + idResponseDTO1.setResponsetime("2019-01-17T06:29:01.940Z"); + idResponseDTO1.setVersion("1.0"); + + when(idrepoDraftService.idrepoUpdateDraft(anyString(), any(), any())).thenReturn(idResponseDTO); + when(registrationProcessorRestClientService.getApi(any(), any(), anyString(), any(), any())) + .thenReturn(idResponseDTO); + + String idJsonData = "{\"identity\":{\"IDSchemaVersion\":1.0,\"UIN\":\"4215839851\"}}"; + InputStream idJsonStream = new ByteArrayInputStream(idJsonData.getBytes(StandardCharsets.UTF_8)); + + + + when(registrationProcessorRestClientService.patchApi(any(), any(), any(), any(), any(), any())) + .thenReturn(idResponseDTO1); + + MessageDTO result = uinGeneratorStage.process(messageDTO); + assertFalse(result.getIsValid()); + assertFalse(result.getInternalError()); + } + + + + @Test + public void deactivateTestWithNullResponseDTOBeforeDeactivate() throws ApisResourceAccessException, + PacketManagerException, + IOException, JsonProcessingException, JSONException, IdrepoDraftException, + IdrepoDraftReprocessableException { + Map fieldMap = new HashMap<>(); + fieldMap.put("UIN", "123456"); + fieldMap.put("name", "mono"); + fieldMap.put("email", "mono@mono.com"); + + List defaultFields = new ArrayList<>(); + defaultFields.add("name"); + defaultFields.add("dob"); + defaultFields.add("gender"); + defaultFields.add("UIN"); + + + when(packetManagerService.getFieldByMappingJsonKey(anyString(), anyString(), any(), any())).thenReturn("0.1"); + when(packetManagerService.getFields(any(), any(), any(), any())).thenReturn(fieldMap); + when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); + + when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); + MessageDTO messageDTO = new MessageDTO(); + messageDTO.setRid("10031100110005020190313110030"); + messageDTO.setReg_type(RegistrationType.valueOf("DEACTIVATED").name()); + IdResponseDTO responsedto = new IdResponseDTO(); + String idJson = "{\"identity\":{\"IDSchemaVersion\":1.0,\"UIN\":\"4215839851\"}}"; + InputStream idJsonStream1 = new ByteArrayInputStream(idJson.getBytes(StandardCharsets.UTF_8)); + + IdResponseDTO idResponseDTO = new IdResponseDTO(); + ResponseDTO responseDTO = new ResponseDTO(); + idResponseDTO.setErrors(null); + idResponseDTO.setId("mosip.id.update"); + responseDTO.setStatus("DEACTIVATED"); + idResponseDTO.setResponse(null); + idResponseDTO.setResponsetime("2019-03-12T06:49:30.779Z"); + idResponseDTO.setVersion("1.0"); + + when(idrepoDraftService.idrepoUpdateDraft(anyString(), any(), any())).thenReturn(idResponseDTO); + when(registrationProcessorRestClientService.getApi(any(), any(), anyString(), any(), any())) + .thenReturn(responsedto); + when(registrationProcessorRestClientService.patchApi(any(), any(), any(), any(), any(), any())) + .thenReturn(idResponseDTO); + + + MessageDTO result = uinGeneratorStage.process(messageDTO); + assertFalse(result.getIsValid()); + assertFalse(result.getInternalError()); + } + + @Test + public void deactivateTesApiResourceClientException() throws ApisResourceAccessException, + PacketManagerException, + IOException, JsonProcessingException, JSONException, IdrepoDraftException, + IdrepoDraftReprocessableException { + Map fieldMap = new HashMap<>(); + fieldMap.put("UIN", "123456"); + fieldMap.put("name", "mono"); + fieldMap.put("email", "mono@mono.com"); + + List defaultFields = new ArrayList<>(); + defaultFields.add("name"); + defaultFields.add("dob"); + defaultFields.add("gender"); + defaultFields.add("UIN"); + + + when(packetManagerService.getFieldByMappingJsonKey(anyString(), anyString(), any(), any())).thenReturn("0.1"); + when(packetManagerService.getFields(any(), any(), any(), any())).thenReturn(fieldMap); + when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); + + when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); + MessageDTO messageDTO = new MessageDTO(); + messageDTO.setRid("10031100110005020190313110030"); + messageDTO.setReg_type(RegistrationType.valueOf("DEACTIVATED").name()); + IdResponseDTO responsedto = new IdResponseDTO(); + String idJson = "{\"identity\":{\"IDSchemaVersion\":1.0,\"UIN\":\"4215839851\"}}"; + InputStream idJsonStream1 = new ByteArrayInputStream(idJson.getBytes(StandardCharsets.UTF_8)); + + IdResponseDTO idResponseDTO = new IdResponseDTO(); + ResponseDTO responseDTO = new ResponseDTO(); + idResponseDTO.setErrors(null); + idResponseDTO.setId("mosip.id.update"); + responseDTO.setStatus("DEACTIVATED"); + idResponseDTO.setResponse(null); + idResponseDTO.setResponsetime("2019-03-12T06:49:30.779Z"); + idResponseDTO.setVersion("1.0"); + + when(idrepoDraftService.idrepoUpdateDraft(anyString(), any(), any())).thenReturn(idResponseDTO); + ApisResourceAccessException ex=new ApisResourceAccessException("", new HttpClientErrorException(HttpStatus.BAD_REQUEST)); + when(registrationProcessorRestClientService.getApi(any(), any(), anyString(), any(), any())) + .thenThrow(ex); + Mockito.when(registrationStatusMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.APIS_RESOURCE_ACCESS_EXCEPTION)).thenReturn("REPROCESS"); + + + MessageDTO result = uinGeneratorStage.process(messageDTO); + assertTrue(result.getIsValid()); + assertTrue(result.getInternalError()); + } + + @Test + public void deactivateTesApiResourceServerException() throws ApisResourceAccessException, + PacketManagerException, + IOException, JsonProcessingException, JSONException, IdrepoDraftException, + IdrepoDraftReprocessableException { + Map fieldMap = new HashMap<>(); + fieldMap.put("UIN", "123456"); + fieldMap.put("name", "mono"); + fieldMap.put("email", "mono@mono.com"); + + List defaultFields = new ArrayList<>(); + defaultFields.add("name"); + defaultFields.add("dob"); + defaultFields.add("gender"); + defaultFields.add("UIN"); + + + when(packetManagerService.getFieldByMappingJsonKey(anyString(), anyString(), any(), any())).thenReturn("0.1"); + when(packetManagerService.getFields(any(), any(), any(), any())).thenReturn(fieldMap); + when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); + + when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); + MessageDTO messageDTO = new MessageDTO(); + messageDTO.setRid("10031100110005020190313110030"); + messageDTO.setReg_type(RegistrationType.valueOf("DEACTIVATED").name()); + String idJson = "{\"identity\":{\"IDSchemaVersion\":1.0,\"UIN\":\"4215839851\"}}"; + + IdResponseDTO idResponseDTO = new IdResponseDTO(); + ResponseDTO responseDTO = new ResponseDTO(); + idResponseDTO.setErrors(null); + idResponseDTO.setId("mosip.id.update"); + responseDTO.setStatus("DEACTIVATED"); + idResponseDTO.setResponse(null); + idResponseDTO.setResponsetime("2019-03-12T06:49:30.779Z"); + idResponseDTO.setVersion("1.0"); + + when(idrepoDraftService.idrepoUpdateDraft(anyString(), any(), any())).thenReturn(idResponseDTO); + ApisResourceAccessException ex=new ApisResourceAccessException("", new HttpServerErrorException(HttpStatus.INTERNAL_SERVER_ERROR)); + when(registrationProcessorRestClientService.getApi(any(), any(), anyString(), any(), any())) + .thenThrow(ex); + Mockito.when(registrationStatusMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.APIS_RESOURCE_ACCESS_EXCEPTION)).thenReturn("REPROCESS"); + + + MessageDTO result = uinGeneratorStage.process(messageDTO); + assertTrue(result.getIsValid()); + assertTrue(result.getInternalError()); + } + + @Test + public void deactivateTesApiResourceException() throws ApisResourceAccessException, + PacketManagerException, + IOException, JsonProcessingException, JSONException, IdrepoDraftException, + IdrepoDraftReprocessableException { + Map fieldMap = new HashMap<>(); + fieldMap.put("UIN", "123456"); + fieldMap.put("name", "mono"); + fieldMap.put("email", "mono@mono.com"); + + List defaultFields = new ArrayList<>(); + defaultFields.add("name"); + defaultFields.add("dob"); + defaultFields.add("gender"); + defaultFields.add("UIN"); + + + when(packetManagerService.getFieldByMappingJsonKey(anyString(), anyString(), any(), any())).thenReturn("0.1"); + when(packetManagerService.getFields(any(), any(), any(), any())).thenReturn(fieldMap); + when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); + + when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); + MessageDTO messageDTO = new MessageDTO(); + messageDTO.setRid("10031100110005020190313110030"); + messageDTO.setReg_type(RegistrationType.valueOf("DEACTIVATED").name()); + String idJson = "{\"identity\":{\"IDSchemaVersion\":1.0,\"UIN\":\"4215839851\"}}"; + + IdResponseDTO idResponseDTO = new IdResponseDTO(); + ResponseDTO responseDTO = new ResponseDTO(); + idResponseDTO.setErrors(null); + idResponseDTO.setId("mosip.id.update"); + responseDTO.setStatus("DEACTIVATED"); + idResponseDTO.setResponse(null); + idResponseDTO.setResponsetime("2019-03-12T06:49:30.779Z"); + idResponseDTO.setVersion("1.0"); + + when(idrepoDraftService.idrepoUpdateDraft(anyString(), any(), any())).thenReturn(idResponseDTO); + ApisResourceAccessException ex=new ApisResourceAccessException(""); + when(registrationProcessorRestClientService.getApi(any(), any(), anyString(), any(), any())) + .thenThrow(ex); + Mockito.when(registrationStatusMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.APIS_RESOURCE_ACCESS_EXCEPTION)).thenReturn("REPROCESS"); + + + MessageDTO result = uinGeneratorStage.process(messageDTO); + assertTrue(result.getIsValid()); + assertTrue(result.getInternalError()); + } + + @Test + public void deactivateTestAlreadyDeactivated() throws ApisResourceAccessException, + PacketManagerException, + IOException, JsonProcessingException, JSONException, IdrepoDraftException, + IdrepoDraftReprocessableException { + Map fieldMap = new HashMap<>(); + fieldMap.put("UIN", "123456"); + fieldMap.put("name", "mono"); + fieldMap.put("email", "mono@mono.com"); + + List defaultFields = new ArrayList<>(); + defaultFields.add("name"); + defaultFields.add("dob"); + defaultFields.add("gender"); + defaultFields.add("UIN"); + + + when(packetManagerService.getFieldByMappingJsonKey(anyString(), anyString(), any(), any())).thenReturn("0.1"); + when(packetManagerService.getFields(any(), any(), any(), any())).thenReturn(fieldMap); + when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); + + when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); + MessageDTO messageDTO = new MessageDTO(); + messageDTO.setRid("10031100110005020190313110030"); + messageDTO.setReg_type(RegistrationType.valueOf("DEACTIVATED").name()); + IdResponseDTO responsedto = new IdResponseDTO(); + ResponseDTO dto=new ResponseDTO(); + dto.setStatus("DEACTIVATED"); + responsedto.setResponse(dto); + String idJson = "{\"identity\":{\"IDSchemaVersion\":1.0,\"UIN\":\"4215839851\"}}"; + + IdResponseDTO idResponseDTO = new IdResponseDTO(); + ResponseDTO responseDTO = new ResponseDTO(); + idResponseDTO.setErrors(null); + idResponseDTO.setId("mosip.id.update"); + responseDTO.setStatus("DEACTIVATED"); + idResponseDTO.setResponse(null); + idResponseDTO.setResponsetime("2019-03-12T06:49:30.779Z"); + idResponseDTO.setVersion("1.0"); + + when(idrepoDraftService.idrepoUpdateDraft(anyString(), any(), any())).thenReturn(idResponseDTO); + when(registrationProcessorRestClientService.getApi(any(), any(), anyString(), any(), any())) + .thenReturn(responsedto); + when(registrationProcessorRestClientService.patchApi(any(), any(), any(), any(), any(), any())) + .thenReturn(idResponseDTO); + + + MessageDTO result = uinGeneratorStage.process(messageDTO); + assertFalse(result.getIsValid()); + assertFalse(result.getInternalError()); + } + + @Test + public void testUinAlreadyDeactivated() throws ApisResourceAccessException, PacketManagerException, IOException, + JsonProcessingException, JSONException, IdrepoDraftException, IdrepoDraftReprocessableException { + Map fieldsMap = new HashMap<>(); + fieldsMap.put("UIN", "123456"); + fieldsMap.put("name", "mono"); + fieldsMap.put("email", "mono@mono.com"); + + List defaultFields = new ArrayList<>(); + defaultFields.add("UIN"); + defaultFields.add("name"); + defaultFields.add("email"); + + when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); + MessageDTO messageDTO = new MessageDTO(); + messageDTO.setRid("10031100110005020190313110030"); + messageDTO.setReg_type(RegistrationType.valueOf("DEACTIVATED").name()); + + IdResponseDTO responsedto = new IdResponseDTO(); + ResponseDTO responseDTO1 = new ResponseDTO(); + responseDTO1.setStatus("DEACTIVATED"); + responsedto.setResponse(responseDTO1); + IdResponseDTO idResponseDTO = new IdResponseDTO(); + ResponseDTO responseDTO = null; + idResponseDTO.setErrors(null); + idResponseDTO.setId("mosip.id.update"); + ErrorDTO errorDto = new ErrorDTO(); + errorDto.setErrorCode("KER-IDR-001"); + errorDto.setMessage("Record not found in DB"); + + List errors = new ArrayList<>(); + errors.add(errorDto); + idResponseDTO.setErrors(errors); + idResponseDTO.setResponse(responseDTO); + idResponseDTO.setResponsetime("2019-03-12T06:49:30.779Z"); + idResponseDTO.setVersion("1.0"); + + when(idrepoDraftService.idrepoUpdateDraft(anyString(), any(), any())).thenReturn(idResponseDTO); + when(registrationProcessorRestClientService.getApi(any(), any(), anyString(), any(), any())) + .thenReturn(responsedto); + when(registrationProcessorRestClientService.patchApi(any(), any(), any(), any(), any(), any())) + .thenReturn(idResponseDTO); + Mockito.when(registrationStatusMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.PACKET_UIN_GENERATION_REPROCESS)).thenReturn("REPROCESS"); + when(packetManagerService.getFields(any(), any(), any(), any())).thenReturn(fieldsMap); + + when(packetManagerService.getFieldByMappingJsonKey(anyString(),anyString(),any(),any())).thenReturn("0.1"); + when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); + + MessageDTO result = uinGeneratorStage.process(messageDTO); + + assertFalse(result.getIsValid()); + assertFalse(result.getInternalError()); + } + + @Test + public void testUinUpdationFaliure() throws Exception { + + Map fieldMap = new HashMap<>(); + fieldMap.put("UIN", "123456"); + fieldMap.put("name", "mono"); + fieldMap.put("email", "mono@mono.com"); + + List defaultFields = new ArrayList<>(); + defaultFields.add("name"); + defaultFields.add("dob"); + defaultFields.add("gender"); + defaultFields.add("UIN"); + + + when(packetManagerService.getFieldByMappingJsonKey(anyString(),anyString(),any(),any())).thenReturn("0.1"); + when(packetManagerService.getFields(any(),any(),any(),any())).thenReturn(fieldMap); + when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); + + when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); + + IdResponseDTO idResponseDTO = new IdResponseDTO(); + ResponseDTO responseDTO = new ResponseDTO(); + ErrorDTO errorDto = new ErrorDTO(); + errorDto.setErrorCode("KER-IDR-001"); + errorDto.setMessage("Record already Exists in DB"); + List errors = new ArrayList<>(); + errors.add(errorDto); + idResponseDTO.setErrors(errors); + idResponseDTO.setId("mosip.id.error"); + idResponseDTO.setResponse(null); + idResponseDTO.setResponsetime("2019-01-17T06:29:01.940Z"); + idResponseDTO.setVersion("1.0"); + when(registrationProcessorRestClientService.postApi(any(), any(), any(), any(), any())) + .thenReturn(idResponseDTO); + when(utility.getRegistrationProcessorMappingJson(MappingJsonConstants.IDENTITY)).thenReturn(identityObj); + when(utility.getRegistrationProcessorMappingJson(MappingJsonConstants.DOCUMENT)).thenReturn(documentObj); + + String Str = "{\"uin\":\"6517036426\"}"; + + Mockito.when(registrationStatusMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.PACKET_UIN_GENERATION_REPROCESS)).thenReturn("REPROCESS"); + when(idrepoDraftService.idrepoUpdateDraft(anyString(), any(), any())).thenReturn(idResponseDTO); + + MessageDTO messageDTO = new MessageDTO(); + messageDTO.setRid("27847657360002520181210094052"); + messageDTO.setReg_type("UPDATE"); + + MessageDTO result = uinGeneratorStage.process(messageDTO); + + assertFalse(result.getInternalError()); + assertFalse(result.getIsValid()); + } + + @Test + public void testUinUpdationIDRepoFaliure() throws Exception { + + Map fieldMap = new HashMap<>(); + fieldMap.put("name", "mono"); + fieldMap.put("email", "mono@mono.com"); + + List defaultFields = new ArrayList<>(); + defaultFields.add("name"); + defaultFields.add("dob"); + defaultFields.add("gender"); + defaultFields.add("UIN"); + + + when(packetManagerService.getFieldByMappingJsonKey(anyString(),anyString(),any(),any())).thenReturn("0.1"); + when(packetManagerService.getFields(any(),any(),any(),any())).thenReturn(fieldMap); + when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(defaultFields); + + IdResponseDTO idResponseDTO = new IdResponseDTO(); + ErrorDTO errorDto = new ErrorDTO(); + errorDto.setErrorCode("IDR-IDC-001"); + errorDto.setMessage("Record already Exists in DB"); + List errors = new ArrayList<>(); + errors.add(errorDto); + idResponseDTO.setErrors(errors); + idResponseDTO.setId("mosip.id.error"); + idResponseDTO.setResponse(null); + idResponseDTO.setResponsetime("2019-01-17T06:29:01.940Z"); + idResponseDTO.setVersion("1.0"); + when(registrationProcessorRestClientService.postApi(any(), any(), any(), any(), any())) + .thenReturn(idResponseDTO); + + Mockito.when(registrationStatusMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.PACKET_UIN_GENERATION_REPROCESS)).thenReturn("REPROCESS"); + when(idrepoDraftService.idrepoUpdateDraft(anyString(), any(), any())).thenReturn(idResponseDTO); + + MessageDTO messageDTO = new MessageDTO(); + messageDTO.setRid("27847657360002520181210094052"); + messageDTO.setReg_type("UPDATE"); + + MessageDTO result = uinGeneratorStage.process(messageDTO); + + assertTrue(result.getInternalError()); + assertTrue(result.getIsValid()); + } + + @Test + public void testUinUpdationIOExceptionFaliure() throws Exception { + + when(packetManagerService.getFieldByMappingJsonKey(anyString(), anyString(), any(), any())) + .thenThrow(IOException.class); + when(registrationStatusMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.PACKET_UIN_GENERATION_REPROCESS)).thenReturn("REPROCESS"); + + MessageDTO messageDTO = new MessageDTO(); + messageDTO.setRid("27847657360002520181210094052"); + messageDTO.setReg_type("UPDATE"); + + MessageDTO result = uinGeneratorStage.process(messageDTO); + + assertTrue(result.getInternalError()); + assertTrue(result.getIsValid()); + } + + @Test + public void testUinGenerationIDRepoDraftReprocessableException() throws Exception { + MessageDTO messageDTO = new MessageDTO(); + messageDTO.setRid("27847657360002520181210094052"); + messageDTO.setReg_type(RegistrationType.NEW.name()); + + when(registrationStatusMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.IDREPO_DRAFT_REPROCESSABLE_EXCEPTION)) + .thenReturn("REPROCESS"); + when(idrepoDraftService.idrepoUpdateDraft(anyString(), any(), any())) + .thenThrow(IdrepoDraftReprocessableException.class); + when(utility.getRegistrationProcessorMappingJson(MappingJsonConstants.IDENTITY)).thenReturn(identityObj); + when(utility.getRegistrationProcessorMappingJson(MappingJsonConstants.DOCUMENT)).thenReturn(documentObj); + + MessageDTO result = uinGeneratorStage.process(messageDTO); + assertTrue(result.getInternalError()); + assertTrue(result.getIsValid()); + } + + @Test + public void testUinGenerationSuccessWithEmptyName() throws Exception { + ReflectionTestUtils.setField(uinGeneratorStage,"trimWhitespaces",true); + Map fieldMap = new HashMap<>(); + fieldMap.put("firstName","[ {\n" + + " \"language\" : \"eng\",\n" + + " \"value\" : \" \"\n" + + "} ]"); + fieldMap.put("email", "mono@mono.com"); + fieldMap.put("phone", "23456"); + fieldMap.put("dob", "11/11/2011"); + when(packetManagerService.getFields(any(),any(),any(),any())).thenReturn(fieldMap); + ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(IdRequestDto.class); + + MessageDTO messageDTO = new MessageDTO(); + messageDTO.setRid("27847657360002520181210094052"); + messageDTO.setReg_type(RegistrationType.NEW.name()); + + IdResponseDTO idResponseDTO = new IdResponseDTO(); + ResponseDTO responseDTO = new ResponseDTO(); + responseDTO.setStatus("ACTIVATED"); + idResponseDTO.setErrors(null); + idResponseDTO.setId("mosip.id.update"); + idResponseDTO.setResponse(responseDTO); + idResponseDTO.setResponsetime("2019-01-17T06:29:01.940Z"); + idResponseDTO.setVersion("1.0"); + + when(idrepoDraftService.idrepoUpdateDraft(anyString(), any(), any())).thenReturn(idResponseDTO); + when(utility.getRegistrationProcessorMappingJson(MappingJsonConstants.IDENTITY)).thenReturn(identityObj); + when(utility.getRegistrationProcessorMappingJson(MappingJsonConstants.DOCUMENT)).thenReturn(documentObj); + + MessageDTO result = uinGeneratorStage.process(messageDTO); + verify(idrepoDraftService).idrepoUpdateDraft(any(), any(), argumentCaptor.capture()); + ObjectMapper objectMapper = new ObjectMapper(); + String jsonobject=objectMapper.writeValueAsString(argumentCaptor.getAllValues().get(0).getRequest().getIdentity()); + JsonNode jsonNode=objectMapper.readTree(jsonobject); + + assertEquals("",jsonNode.get("firstName").asText()); + assertFalse(result.getInternalError()); + assertTrue(result.getIsValid()); + } } \ No newline at end of file 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..11f7889ae8d 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 @@ -1,788 +1,782 @@ -package io.mosip.registration.processor.verification.service.impl; - -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; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.UUID; -import java.util.stream.Collectors; - -import org.apache.commons.lang.StringUtils; -import org.apache.commons.lang3.exception.ExceptionUtils; -import org.json.simple.JSONObject; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.core.env.Environment; -import org.springframework.core.io.ByteArrayResource; -import org.springframework.http.MediaType; -import org.springframework.stereotype.Component; -import org.springframework.transaction.annotation.Transactional; -import org.springframework.util.CollectionUtils; -import org.springframework.util.LinkedMultiValueMap; -import org.springframework.util.MultiValueMap; - -import com.fasterxml.jackson.databind.ObjectMapper; -import com.google.common.collect.Lists; - -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; -import io.mosip.kernel.core.util.JsonUtils; -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.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.Identity; -import io.mosip.registration.processor.core.queue.factory.MosipQueue; -import io.mosip.registration.processor.core.spi.packetmanager.PacketInfoManager; -import io.mosip.registration.processor.core.spi.queue.MosipQueueManager; -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.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; -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.exception.TablenotAccessibleException; -import io.mosip.registration.processor.status.service.RegistrationStatusService; -import io.mosip.registration.processor.verification.constants.VerificationConstants; -import io.mosip.registration.processor.verification.dto.DataShareRequestDto; -import io.mosip.registration.processor.verification.dto.ManualVerificationStatus; -import io.mosip.registration.processor.verification.exception.DataShareException; -import io.mosip.registration.processor.verification.exception.InvalidFileNameException; -import io.mosip.registration.processor.verification.exception.InvalidRidException; -import io.mosip.registration.processor.verification.exception.NoRecordAssignedException; -import io.mosip.registration.processor.verification.request.dto.Filter; -import io.mosip.registration.processor.verification.request.dto.ShareableAttributes; -import io.mosip.registration.processor.verification.request.dto.Source; -import io.mosip.registration.processor.verification.request.dto.VerificationRequestDTO; -import io.mosip.registration.processor.verification.response.dto.VerificationResponseDTO; -import io.mosip.registration.processor.verification.service.VerificationService; -import io.mosip.registration.processor.verification.stage.VerificationStage; -import io.mosip.registration.processor.verification.util.SaveVerificationRecordUtility; - -/** - * The Class ManualAdjudicationServiceImpl. - */ -@Component -@Transactional -public class VerificationServiceImpl implements VerificationService { - - /** The logger. */ - private static Logger regProcLogger = RegProcessorLogger.getLogger(VerificationServiceImpl.class); - private LinkedHashMap policies = null; - private static final String VERIFICATION = "verification"; - private static final String VERIFICATION_COMMENT = "Packet marked for verification"; - - /** The Constant USER. */ - private static final String USER = "MOSIP_SYSTEM"; - private static final String TEXT_MESSAGE = "text"; - private static final String DATASHARE = "dataShare"; - private static final String ERRORS = "errors"; - private static final String URL = "url"; - private static final String META_INFO = "meta_info"; - private static final String AUDITS = "audits"; - - @Autowired - private Environment env; - - /** The address. */ - @Value("${registration.processor.queue.verification.request:mosip-to-verification}") - private String mvRequestAddress; - - /** - * Manual adjudication queue message expiry in seconds, if given 0 then message - * will never expire - */ - @Value("${registration.processor.queue.verification.request.messageTTL}") - private int mvRequestMessageTTL; - - @Value("${registration.processor.verification.policy.id:mpolicy-default-adjudication}") - private String policyId; - - @Value("${registration.processor.verification.subscriber.id:mpartner-default-adjudication}") - private String subscriberId; - - @Value("${activemq.message.format}") - private String messageFormat; - - @Value("${mosip.regproc.data.share.protocol}") - private String httpProtocol; - - @Value("${mosip.regproc.data.share.internal.domain.name}") - private String internalDomainName; - - @Autowired - private RegistrationProcessorRestClientService registrationProcessorRestClientService; - - @Autowired - private CbeffUtil cbeffutil; - - @Autowired - private Utilities utility; - - @Autowired - private MosipQueueManager mosipQueueManager; - - @Autowired - private PriorityBasedPacketManagerService packetManagerService; - - /** The audit log request builder. */ - @Autowired - private AuditLogRequestBuilder auditLogRequestBuilder; - - /** The registration status service. */ - @Autowired - private RegistrationStatusService registrationStatusService; - /** The base packet repository. */ - @Autowired - private BasePacketRepository basePacketRepository; - - /** The manual verification stage. */ - @Autowired - private VerificationStage verificationStage; - - @Autowired - private RegistrationProcessorRestClientService restClientService; - - @Autowired - private PacketInfoManager packetInfoManager; - - @Autowired - private ObjectMapper mapper; - - @Autowired - RegistrationExceptionMapperUtil registrationExceptionMapperUtil; - - @Autowired - SaveVerificationRecordUtility saveVerificationRecordUtility; - - /** The Constant PROTOCOL. */ - public static final String PROTOCOL = "https"; - - /* - * This method will be called from the event bus passing messageDTO object - * containing rid Based o Rid fetch match reference Id and form request which is - * pushed to queue and update Manual verification entity - */ - @Override - public MessageDTO process(MessageDTO messageDTO, MosipQueue queue, String stageName) { - messageDTO.setInternalError(false); - messageDTO.setIsValid(false); - messageDTO.setMessageBusAddress(MessageBusAddress.VERIFICATION_BUS_IN); - - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - messageDTO.getRid(), "VerificationServiceImpl::process()::entry"); - - boolean isTransactionSuccessful = true; - LogDescription description = new LogDescription(); - - InternalRegistrationStatusDto registrationStatusDto = registrationStatusService.getRegistrationStatus( - messageDTO.getRid(), messageDTO.getReg_type(), messageDTO.getIteration(), - messageDTO.getWorkflowInstanceId()); - try { - if (null == messageDTO.getRid() || messageDTO.getRid().isEmpty()) - throw new InvalidRidException(PlatformErrorMessages.RPR_MVS_NO_RID_SHOULD_NOT_EMPTY_OR_NULL.getCode(), - PlatformErrorMessages.RPR_MVS_NO_RID_SHOULD_NOT_EMPTY_OR_NULL.getMessage()); - VerificationRequestDTO mar = prepareVerificationRequest(messageDTO, registrationStatusDto); - saveVerificationRecordUtility.saveVerificationRecord(messageDTO, mar.getRequestId(), description); - regProcLogger.debug("Request : " + JsonUtils.javaObjectToJsonString(mar)); - - if (messageFormat.equalsIgnoreCase(TEXT_MESSAGE)) - mosipQueueManager.send(queue, JsonUtils.javaObjectToJsonString(mar), mvRequestAddress, - mvRequestMessageTTL); - else - mosipQueueManager.send(queue, JsonUtils.javaObjectToJsonString(mar).getBytes(), mvRequestAddress, - mvRequestMessageTTL); - - regProcLogger.info("ID : " + messageDTO.getRid() + " has been successfully sent for verification."); - - if (isTransactionSuccessful) { - registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); - registrationStatusDto.setSubStatusCode(StatusUtil.VERIFICATION_SENT.getCode()); - registrationStatusDto.setStatusComment(StatusUtil.VERIFICATION_SENT.getMessage()); - registrationStatusDto - .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.IN_PROGRESS.toString()); - } else { - registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.toString()); - registrationStatusDto.setSubStatusCode(StatusUtil.VERIFICATION_FAILED.getCode()); - registrationStatusDto.setStatusComment(StatusUtil.VERIFICATION_FAILED.getMessage()); - registrationStatusDto - .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.ERROR.toString()); - } - registrationStatusDto.setRegistrationStageName(stageName); - - } catch (DataShareException de) { - messageDTO.setInternalError(true); - isTransactionSuccessful = false; - description.setCode(de.getErrorCode()); - description.setMessage(de.getMessage()); - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - de.getErrorCode(), de.getErrorText()); - - } catch (InvalidRidException exp) { - isTransactionSuccessful = false; - description.setCode(exp.getErrorCode()); - description.setMessage(exp.getMessage()); - messageDTO.setInternalError(true); - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), null, exp.getErrorCode(), exp.getErrorText()); - - } catch (Exception e) { - isTransactionSuccessful = false; - description.setCode(PlatformSuccessMessages.RPR_VERIFICATION_SENT.getCode()); - description.setMessage(e.getMessage()); - messageDTO.setInternalError(true); - regProcLogger.error(ExceptionUtils.getStackTrace(e)); - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - e.getMessage(), e.getMessage()); - } finally { - if (isTransactionSuccessful) { - messageDTO.setIsValid(true); - description.setCode(PlatformSuccessMessages.RPR_VERIFICATION_SUCCESS.getCode()); - description.setMessage(PlatformSuccessMessages.RPR_VERIFICATION_SUCCESS.getMessage()); - } else - registrationStatusDto.setSubStatusCode(StatusUtil.VERIFICATION_FAILED.getCode()); - updateStatus(messageDTO, registrationStatusDto, isTransactionSuccessful, description, - PlatformSuccessMessages.RPR_VERIFICATION_SENT); - } - - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - messageDTO.getRid(), "VerificationServiceImpl::process()::entry"); - - return messageDTO; - } - - /* - * (non-Javadoc) - * - * @see io.mosip.registration.processor.verification.service. - * ManualAdjudicationService#updatePacketStatus(io.mosip.registration.processor. - * verification.dto.ManualVerificationDTO) - */ - @Override - public boolean updatePacketStatus(VerificationResponseDTO manualVerificationDTO, String stageName, - MosipQueue queue) { - - TrimExceptionMessage trimExceptionMessage = new TrimExceptionMessage(); - LogDescription description = new LogDescription(); - boolean isTransactionSuccessful = false; - - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REFERENCEID.toString(), - manualVerificationDTO.getRequestId(), "VerificationServiceImpl::updatePacketStatus()::entry"); - - VerificationEntity entity = validateRequestIdAndReturnRid(manualVerificationDTO.getRequestId()); - String regId = entity != null ? entity.getRegId() : null; - - MessageDTO messageDTO = new MessageDTO(); - InternalRegistrationStatusDto registrationStatusDto = null; - try { - registrationStatusDto = registrationStatusService.getRegistrationStatus( - (entity != null ? entity.getRegId() : null), null, null, - (entity != null ? (entity.getId() != null ? entity.getId().getWorkflowInstanceId() : null) : null)); - registrationStatusDto.setLatestTransactionTypeCode(RegistrationTransactionTypeCode.VERIFICATION.name()); - registrationStatusDto.setRegistrationStageName(stageName); - messageDTO.setInternalError(false); - messageDTO.setIsValid(false); - messageDTO.setRid(regId); - messageDTO.setReg_type(registrationStatusDto.getRegistrationType()); - - List entities = retrieveInqueuedRecordsByRid(regId); - - // check if response is marked for resend - if (isResendFlow(registrationStatusDto, manualVerificationDTO, entity)) { - registrationStatusDto.setStatusComment(StatusUtil.VERIFICATION_RESEND.getMessage()); - registrationStatusDto.setSubStatusCode(StatusUtil.VERIFICATION_RESEND.getCode()); - registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); - registrationStatusDto - .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.REPROCESS.toString()); - description.setMessage(StatusUtil.VERIFICATION_RESEND.getMessage()); - 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 - isTransactionSuccessful = successFlow(manualVerificationDTO, entity, registrationStatusDto, messageDTO, - description); - - registrationStatusDto.setUpdatedBy(USER); - regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), - LoggerFileConstant.REGISTRATIONID.toString(), regId, description.getMessage()); - } - - } catch (TablenotAccessibleException e) { - messageDTO.setInternalError(true); - registrationStatusDto.setLatestTransactionStatusCode(registrationExceptionMapperUtil - .getStatusCode(RegistrationExceptionTypeCode.TABLE_NOT_ACCESSIBLE_EXCEPTION)); - registrationStatusDto.setStatusComment(trimExceptionMessage - .trimExceptionMessage(StatusUtil.DB_NOT_ACCESSIBLE.getMessage() + e.getMessage())); - registrationStatusDto.setSubStatusCode(StatusUtil.DB_NOT_ACCESSIBLE.getCode()); - - description.setMessage(PlatformErrorMessages.RPR_TABLE_NOT_ACCESSIBLE.getMessage()); - description.setCode(PlatformErrorMessages.RPR_TABLE_NOT_ACCESSIBLE.getCode()); - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - regId, e.getMessage() + ExceptionUtils.getStackTrace(e)); - } catch (NoRecordAssignedException e) { - messageDTO.setIsValid(false); - messageDTO.setInternalError(false); - registrationStatusDto.setLatestTransactionStatusCode( - registrationExceptionMapperUtil.getStatusCode(RegistrationExceptionTypeCode.NO_RECORDS_ASSIGNED)); - registrationStatusDto.setStatusComment(trimExceptionMessage.trimExceptionMessage( - PlatformErrorMessages.RPR_MVS_NO_ASSIGNED_RECORD.getMessage() + e.getMessage())); - registrationStatusDto.setSubStatusCode(PlatformErrorMessages.RPR_MVS_NO_ASSIGNED_RECORD.getCode()); - - description.setMessage(PlatformErrorMessages.RPR_MVS_NO_ASSIGNED_RECORD.getMessage()); - description.setCode(PlatformErrorMessages.RPR_MVS_NO_ASSIGNED_RECORD.getCode()); - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - regId, e.getMessage() + ExceptionUtils.getStackTrace(e)); - } catch (Exception e) { - messageDTO.setInternalError(true); - registrationStatusDto.setLatestTransactionStatusCode( - registrationExceptionMapperUtil.getStatusCode(RegistrationExceptionTypeCode.EXCEPTION)); - registrationStatusDto.setStatusComment(trimExceptionMessage - .trimExceptionMessage(StatusUtil.UNKNOWN_EXCEPTION_OCCURED.getMessage() + e.getMessage())); - registrationStatusDto.setSubStatusCode(StatusUtil.UNKNOWN_EXCEPTION_OCCURED.getCode()); - - description.setMessage(PlatformErrorMessages.UNKNOWN_EXCEPTION.getMessage()); - description.setCode(PlatformErrorMessages.UNKNOWN_EXCEPTION.getCode()); - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - regId, e.getMessage() + ExceptionUtils.getStackTrace(e)); - } finally { - // TODO structure to not return in finally,ignore for sonar - updateStatus(messageDTO, registrationStatusDto, isTransactionSuccessful, description, - PlatformSuccessMessages.RPR_VERIFICATION_SUCCESS); - verificationStage.sendMessage(messageDTO); - } - return isTransactionSuccessful; - } - - private void updateStatus(MessageDTO messageDTO, InternalRegistrationStatusDto registrationStatusDto, - boolean isTransactionSuccessful, LogDescription description, - PlatformSuccessMessages platformSuccessMessages) { - if (messageDTO.getInternalError()) { - updateErrorFlags(registrationStatusDto, messageDTO); - } - registrationStatusDto.setLatestTransactionTypeCode(RegistrationTransactionTypeCode.VERIFICATION.toString()); - String regId = messageDTO.getRid(); - /** Module-Id can be Both Success/Error code */ - 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(); - String eventType = eventId.equalsIgnoreCase(EventId.RPR_402.toString()) ? EventType.BUSINESS.toString() - : EventType.SYSTEM.toString(); - - auditLogRequestBuilder.createAuditRequestBuilder(description.getMessage(), eventId, eventName, eventType, - moduleId, moduleName, regId); - - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - regId, "VerificationServiceImpl::updatePacketStatus()::exit"); - - } - - /** - * Basic validation of requestId received against the rid present in - * manual-adjudication table Returns the correct rid after successful validation - * - * @param reqId : the request id - * @return rid : the registration id - */ - private VerificationEntity validateRequestIdAndReturnRid(String reqId) { - List entities = basePacketRepository.getVerificationRecordByRequestId(reqId); - - if (CollectionUtils.isEmpty(entities) - || new HashSet<>(entities.stream().map(e -> e.getRegId()).collect(Collectors.toList())).size() != 1) { - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - entities != null ? entities.stream().map(e -> e.getRegId()).collect(Collectors.toList()) : null, - "Multiple rids found against request id : " + reqId); - throw new InvalidRidException(PlatformErrorMessages.RPR_INVALID_RID_FOUND.getCode(), - PlatformErrorMessages.RPR_INVALID_RID_FOUND.getCode()); - } - - VerificationEntity entity = entities.iterator().next(); - - if (entity != null && StringUtils.isEmpty(entity.getRegId())) { - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - entity.getRegId(), "VerificationServiceImpl::updatePacketStatus()::InvalidFileNameException" - + PlatformErrorMessages.RPR_MVS_REG_ID_SHOULD_NOT_EMPTY_OR_NULL.getMessage()); - throw new InvalidFileNameException(PlatformErrorMessages.RPR_MVS_REG_ID_SHOULD_NOT_EMPTY_OR_NULL.getCode(), - PlatformErrorMessages.RPR_MVS_REG_ID_SHOULD_NOT_EMPTY_OR_NULL.getMessage()); - } - return entity; - } - - private List retrieveInqueuedRecordsByRid(String regId) { - - List entities = basePacketRepository.getAssignedVerificationRecord(regId, - ManualVerificationStatus.INQUEUE.name()); - - if (CollectionUtils.isEmpty(entities)) { - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - regId, "VerificationServiceImpl::updatePacketStatus()" - + PlatformErrorMessages.RPR_MVS_NO_ASSIGNED_RECORD.getMessage()); - throw new NoRecordAssignedException(PlatformErrorMessages.RPR_MVS_NO_ASSIGNED_RECORD.getCode(), - PlatformErrorMessages.RPR_MVS_NO_ASSIGNED_RECORD.getMessage()); - } - - return entities; - } - - private String getDataShareUrl(String id, String process) throws Exception { - DataShareRequestDto requestDto = new DataShareRequestDto(); - - LinkedHashMap policy = getPolicy(); - - Map policyMap = getPolicyMap(policy); - - // set demographic - Map demographicMap = policyMap.entrySet().stream() - .filter(e -> e.getValue() != null - && (!META_INFO.equalsIgnoreCase(e.getValue()) && !AUDITS.equalsIgnoreCase(e.getValue()))) - .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue())); - requestDto.setIdentity( - packetManagerService.getFields(id, demographicMap.values().stream().collect(Collectors.toList()), - process, ProviderStageName.VERIFICATION)); - - // set documents - JSONObject docJson = utility.getRegistrationProcessorMappingJson(MappingJsonConstants.DOCUMENT); - for (Object doc : docJson.keySet()) { - if (doc != null) { - HashMap docmap = (HashMap) docJson.get(doc.toString()); - String docName = docmap != null && docmap.get(MappingJsonConstants.VALUE) != null - ? docmap.get(MappingJsonConstants.VALUE).toString() - : null; - if (policyMap.containsValue(docName)) { - Document document = packetManagerService.getDocument(id, docName, process, - ProviderStageName.VERIFICATION); - 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); - } - } - } - } - } - - // set audits - if (policyMap.containsValue(AUDITS)) - requestDto.setAudits(JsonUtils.javaObjectToJsonString( - packetManagerService.getAudits(id, process, ProviderStageName.VERIFICATION))); - - // set metainfo - if (policyMap.containsValue(META_INFO)) - requestDto.setMetaInfo(JsonUtils.javaObjectToJsonString( - packetManagerService.getMetaInfo(id, process, ProviderStageName.VERIFICATION))); - - // set biometrics - JSONObject regProcessorIdentityJson = utility - .getRegistrationProcessorMappingJson(MappingJsonConstants.IDENTITY); - String individualBiometricsLabel = JsonUtil.getJSONValue( - JsonUtil.getJSONObject(regProcessorIdentityJson, MappingJsonConstants.INDIVIDUAL_BIOMETRICS), - MappingJsonConstants.VALUE); - - if (policyMap.containsValue(individualBiometricsLabel)) { - List modalities = getModalities(policy); - BiometricRecord biometricRecord = packetManagerService.getBiometrics(id, individualBiometricsLabel, - modalities, process, ProviderStageName.VERIFICATION); - byte[] content = cbeffutil.createXML(biometricRecord.getSegments()); - requestDto.setBiometrics(content != null ? CryptoUtil.encodeToURLSafeBase64(content) : null); - } - - String req = JsonUtils.javaObjectToJsonString(requestDto); - - MultiValueMap map = new LinkedMultiValueMap<>(); - map.add("name", VERIFICATION); - map.add("filename", VERIFICATION); - - ByteArrayResource contentsAsResource = new ByteArrayResource(req.getBytes()) { - @Override - public String getFilename() { - return VERIFICATION; - } - }; - 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 (policy.get(PolicyConstant.DATASHARE_POLICIES) != null) { - LinkedHashMap datasharePolicies = (LinkedHashMap) policies - .get(PolicyConstant.DATASHARE_POLICIES); - if (!CollectionUtils.isEmpty(datasharePolicies) - && datasharePolicies.get(PolicyConstant.SHAREDOMAIN_WRITE) != null) - url = datasharePolicies.get(PolicyConstant.SHAREDOMAIN_WRITE) - + env.getProperty(ApiName.DATASHARECREATEURL.name()); - } - if (StringUtils.isEmpty(url)) - url = protocol + internalDomainName + env.getProperty(ApiName.DATASHARECREATEURL.name()); - url = url.replaceAll("[\\[\\]]", ""); - - LinkedHashMap response = (LinkedHashMap) registrationProcessorRestClientService.postApi(url, - MediaType.MULTIPART_FORM_DATA, pathSegments, null, null, map, LinkedHashMap.class); - if (response == null || (response.get(ERRORS) != null)) - throw new DataShareException( - response == null ? "Datashare response is null" : response.get(ERRORS).toString()); - - LinkedHashMap datashare = (LinkedHashMap) response.get(DATASHARE); - return datashare.get(URL) != null ? datashare.get(URL).toString() : null; - } - - private Map getPolicyMap(LinkedHashMap policies) throws IOException { - Map policyMap = new HashMap<>(); - List attributes = (List) policies.get(VerificationConstants.SHAREABLE_ATTRIBUTES); - for (LinkedHashMap map : attributes) { - ShareableAttributes shareableAttributes = mapper.readValue(mapper.writeValueAsString(map), - ShareableAttributes.class); - policyMap.put(shareableAttributes.getAttributeName(), - shareableAttributes.getSource().iterator().next().getAttribute()); - } - return policyMap; - - } - - private LinkedHashMap getPolicy() throws DataShareException, ApisResourceAccessException { - if (policies != null && policies.size() > 0) - return policies; - - 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(); - policies = (LinkedHashMap) responseMap.get(VerificationConstants.POLICIES); - } - return policies; - - } - - public List getModalities(LinkedHashMap policy) throws IOException { - Map> typeAndSubTypeMap = new HashMap<>(); - List attributes = (List) policy.get(VerificationConstants.SHAREABLE_ATTRIBUTES); - for (LinkedHashMap map : attributes) { - ShareableAttributes shareableAttributes = mapper.readValue(mapper.writeValueAsString(map), - 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); - } - }); - } - } - } - List modalities = new ArrayList<>(); - for (Map.Entry> entry : typeAndSubTypeMap.entrySet()) { - if (entry.getValue() == null) { - modalities.add(entry.getKey()); - } else { - modalities.addAll(entry.getValue()); - } - } - - return modalities; - - } - - /* - * Form manual adjudication request - */ - private VerificationRequestDTO prepareVerificationRequest(MessageDTO messageDTO, - InternalRegistrationStatusDto registrationStatusDto) throws Exception { - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), "", - "VerificationServiceImpl::formAdjudicationRequest()::entry"); - - VerificationRequestDTO req = new VerificationRequestDTO(); - List entities = basePacketRepository - .getVerificationRecordByWorkflowInstanceId(messageDTO.getWorkflowInstanceId()); - if (!CollectionUtils.isEmpty(entities)) - req.setRequestId(entities.get(0).getRequestId()); - else - req.setRequestId(UUID.randomUUID().toString()); - - req.setId(VerificationConstants.MANUAL_ADJUDICATION_ID); - req.setVersion(VerificationConstants.VERSION); - req.setRequesttime(DateUtils.getUTCCurrentDateTimeString(env.getProperty(DATETIME_PATTERN))); - req.setReferenceId(messageDTO.getRid()); - try { - req.setReferenceURL(getDataShareUrl(messageDTO.getRid(), registrationStatusDto.getRegistrationType())); - - } catch (PacketManagerException | ApisResourceAccessException ex) { - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - ex.getErrorCode(), ex.getErrorText()); - throw ex; - } - - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), "", - "VerificationServiceImpl::formAdjudicationRequest()::entry"); - - return req; - } - - /** - * Process response for success flow. - * - * @param entity - * @param manualVerificationDTO - * @param registrationStatusDto - * @param messageDTO - * @param description - * @return boolean - * @throws com.fasterxml.jackson.core.JsonProcessingException - */ - private boolean successFlow(VerificationResponseDTO manualVerificationDTO, VerificationEntity entity, - InternalRegistrationStatusDto registrationStatusDto, MessageDTO messageDTO, LogDescription description) - throws JsonProcessingException { - - boolean isTransactionSuccessful = false; - String statusCode = manualVerificationDTO.getReturnValue() == 1 ? ManualVerificationStatus.APPROVED.name() - : ManualVerificationStatus.REJECTED.name(); - - String responsetext = JsonUtils.javaObjectToJsonString(manualVerificationDTO); - responsetext = StringUtils.isNotEmpty(responsetext) ? responsetext.replaceAll("\\s+", "") : responsetext; - - entity.setStatusCode(statusCode); - entity.setReponseText(responsetext); - entity.setStatusComment(statusCode.equalsIgnoreCase(ManualVerificationStatus.APPROVED.name()) - ? StatusUtil.VERIFICATION_SUCCESS.getMessage() - : StatusUtil.VERIFICATION_FAILED.getMessage()); - - isTransactionSuccessful = true; - registrationStatusDto.setLatestTransactionTypeCode(RegistrationTransactionTypeCode.VERIFICATION.toString()); - registrationStatusDto.setRegistrationStageName(registrationStatusDto.getRegistrationStageName()); - - if (statusCode.equalsIgnoreCase(ManualVerificationStatus.APPROVED.name())) { - messageDTO.setIsValid(isTransactionSuccessful); - registrationStatusDto.setStatusComment(StatusUtil.VERIFICATION_SUCCESS.getMessage()); - registrationStatusDto.setSubStatusCode(StatusUtil.VERIFICATION_SUCCESS.getCode()); - registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); - registrationStatusDto.setLatestTransactionStatusCode(RegistrationTransactionStatusCode.SUCCESS.toString()); - - description.setMessage(PlatformSuccessMessages.RPR_VERIFICATION_SUCCESS.getMessage()); - description.setCode(PlatformSuccessMessages.RPR_VERIFICATION_SUCCESS.getCode()); - - } else if (statusCode.equalsIgnoreCase(ManualVerificationStatus.REJECTED.name())) { - registrationStatusDto.setStatusCode(RegistrationStatusCode.REJECTED.toString()); - registrationStatusDto.setStatusComment(StatusUtil.VERIFICATION_FAILED.getMessage()); - registrationStatusDto.setSubStatusCode(StatusUtil.VERIFICATION_FAILED.getCode()); - registrationStatusDto.setLatestTransactionStatusCode(RegistrationTransactionStatusCode.FAILED.toString()); - - description.setMessage(PlatformErrorMessages.RPR_MANUAL_VERIFICATION_REJECTED.getMessage()); - description.setCode(PlatformErrorMessages.RPR_MANUAL_VERIFICATION_REJECTED.getCode()); - messageDTO.setIsValid(Boolean.FALSE); - messageDTO.setInternalError(Boolean.FALSE); - } else { - registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); - registrationStatusDto.setStatusComment(StatusUtil.VERIFICATION_RESEND.getMessage()); - registrationStatusDto.setSubStatusCode(StatusUtil.VERIFICATION_RESEND.getCode()); - registrationStatusDto - .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.IN_PROGRESS.toString()); - - description.setMessage(PlatformErrorMessages.RPR_MANUAL_VERIFICATION_RESEND.getMessage()); - description.setCode(PlatformErrorMessages.RPR_MANUAL_VERIFICATION_RESEND.getCode()); - messageDTO.setIsValid(Boolean.FALSE); - } - basePacketRepository.update(entity); - - return isTransactionSuccessful; - } - - private void updateErrorFlags(InternalRegistrationStatusDto registrationStatusDto, MessageDTO object) { - object.setInternalError(true); - if (registrationStatusDto.getLatestTransactionStatusCode() - .equalsIgnoreCase(RegistrationTransactionStatusCode.REPROCESS.toString())) { - object.setIsValid(true); - } else { - object.setIsValid(false); - } - } - - /** - * This method would validate response and on failure it will mark the response - * for reprocessing. - * - * @param registrationStatusDto - * @param manualVerificationDTO - * @return boolean - * @throws JsonProcessingException - */ - public boolean isResendFlow(InternalRegistrationStatusDto registrationStatusDto, - VerificationResponseDTO manualVerificationDTO, VerificationEntity entity) throws JsonProcessingException { - boolean isResendFlow = false; - if (manualVerificationDTO.getReturnValue() == 2) { - regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - registrationStatusDto.getRegistrationId(), - "Received resend request from manual verification application. This will be marked for reprocessing."); - - // updating status code to pending so that it can be marked for manual - // verification again - registrationStatusDto.setLatestTransactionStatusCode(RegistrationTransactionStatusCode.REPROCESS.name()); - registrationStatusService.updateRegistrationStatus(registrationStatusDto, ModuleName.VERIFICATION.name(), - ModuleName.VERIFICATION.name()); - isResendFlow = true; - } - return isResendFlow; - } - - -} +package io.mosip.registration.processor.verification.service.impl; + +import static io.mosip.registration.processor.verification.constants.VerificationConstants.DATETIME_PATTERN; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.stream.Collectors; + +import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang3.exception.ExceptionUtils; +import org.json.simple.JSONObject; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.core.env.Environment; +import org.springframework.core.io.ByteArrayResource; +import org.springframework.http.MediaType; +import org.springframework.stereotype.Component; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.CollectionUtils; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.common.collect.Lists; + +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.CryptoUtil; +import io.mosip.kernel.core.util.DateUtils; +import io.mosip.kernel.core.util.JsonUtils; +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.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.Identity; +import io.mosip.registration.processor.core.queue.factory.MosipQueue; +import io.mosip.registration.processor.core.spi.packetmanager.PacketInfoManager; +import io.mosip.registration.processor.core.spi.queue.MosipQueueManager; +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.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.repository.BasePacketRepository; +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.code.RegistrationStatusCode; +import io.mosip.registration.processor.status.dto.InternalRegistrationStatusDto; +import io.mosip.registration.processor.status.dto.RegistrationStatusDto; +import io.mosip.registration.processor.status.exception.TablenotAccessibleException; +import io.mosip.registration.processor.status.service.RegistrationStatusService; +import io.mosip.registration.processor.verification.constants.VerificationConstants; +import io.mosip.registration.processor.verification.dto.DataShareRequestDto; +import io.mosip.registration.processor.verification.dto.ManualVerificationStatus; +import io.mosip.registration.processor.verification.exception.DataShareException; +import io.mosip.registration.processor.verification.exception.InvalidFileNameException; +import io.mosip.registration.processor.verification.exception.InvalidRidException; +import io.mosip.registration.processor.verification.exception.NoRecordAssignedException; +import io.mosip.registration.processor.verification.request.dto.Filter; +import io.mosip.registration.processor.verification.request.dto.ShareableAttributes; +import io.mosip.registration.processor.verification.request.dto.Source; +import io.mosip.registration.processor.verification.request.dto.VerificationRequestDTO; +import io.mosip.registration.processor.verification.response.dto.VerificationResponseDTO; +import io.mosip.registration.processor.verification.service.VerificationService; +import io.mosip.registration.processor.verification.stage.VerificationStage; +import io.mosip.registration.processor.verification.util.SaveVerificationRecordUtility; + +/** + * The Class ManualAdjudicationServiceImpl. + */ +@Component +@Transactional +public class VerificationServiceImpl implements VerificationService { + + /** The logger. */ + private static Logger regProcLogger = RegProcessorLogger.getLogger(VerificationServiceImpl.class); + private LinkedHashMap policies = null; + private static final String VERIFICATION = "verification"; + private static final String VERIFICATION_COMMENT = "Packet marked for verification"; + + /** The Constant USER. */ + private static final String USER = "MOSIP_SYSTEM"; + private static final String TEXT_MESSAGE = "text"; + private static final String DATASHARE = "dataShare"; + private static final String ERRORS = "errors"; + private static final String URL = "url"; + private static final String META_INFO = "meta_info"; + private static final String AUDITS = "audits"; + + @Autowired + private Environment env; + + /** The address. */ + @Value("${registration.processor.queue.verification.request:mosip-to-verification}") + private String mvRequestAddress; + + /** + * Manual adjudication queue message expiry in seconds, if given 0 then message + * will never expire + */ + @Value("${registration.processor.queue.verification.request.messageTTL}") + private int mvRequestMessageTTL; + + @Value("${registration.processor.verification.policy.id:mpolicy-default-adjudication}") + private String policyId; + + @Value("${registration.processor.verification.subscriber.id:mpartner-default-adjudication}") + private String subscriberId; + + @Value("${activemq.message.format}") + private String messageFormat; + + @Value("${mosip.regproc.data.share.protocol}") + private String httpProtocol; + + @Value("${mosip.regproc.data.share.internal.domain.name}") + private String internalDomainName; + + @Autowired + private RegistrationProcessorRestClientService registrationProcessorRestClientService; + + @Autowired + private CbeffUtil cbeffutil; + + @Autowired + private Utilities utility; + + @Autowired + private MosipQueueManager mosipQueueManager; + + @Autowired + private PriorityBasedPacketManagerService packetManagerService; + + /** The audit log request builder. */ + @Autowired + private AuditLogRequestBuilder auditLogRequestBuilder; + + /** The registration status service. */ + @Autowired + private RegistrationStatusService registrationStatusService; + /** The base packet repository. */ + @Autowired + private BasePacketRepository basePacketRepository; + + /** The manual verification stage. */ + @Autowired + private VerificationStage verificationStage; + + @Autowired + private RegistrationProcessorRestClientService restClientService; + + @Autowired + private PacketInfoManager packetInfoManager; + + @Autowired + private ObjectMapper mapper; + + @Autowired + RegistrationExceptionMapperUtil registrationExceptionMapperUtil; + + @Autowired + SaveVerificationRecordUtility saveVerificationRecordUtility; + + /** The Constant PROTOCOL. */ + public static final String PROTOCOL = "https"; + + /* + * This method will be called from the event bus passing messageDTO object + * containing rid Based o Rid fetch match reference Id and form request which is + * pushed to queue and update Manual verification entity + */ + @Override + public MessageDTO process(MessageDTO messageDTO, MosipQueue queue, String stageName) { + messageDTO.setInternalError(false); + messageDTO.setIsValid(false); + messageDTO.setMessageBusAddress(MessageBusAddress.VERIFICATION_BUS_IN); + + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + messageDTO.getRid(), "VerificationServiceImpl::process()::entry"); + + boolean isTransactionSuccessful = true; + LogDescription description = new LogDescription(); + + InternalRegistrationStatusDto registrationStatusDto = registrationStatusService.getRegistrationStatus( + messageDTO.getRid(), messageDTO.getReg_type(), messageDTO.getIteration(), + messageDTO.getWorkflowInstanceId()); + try { + if (null == messageDTO.getRid() || messageDTO.getRid().isEmpty()) + throw new InvalidRidException(PlatformErrorMessages.RPR_MVS_NO_RID_SHOULD_NOT_EMPTY_OR_NULL.getCode(), + PlatformErrorMessages.RPR_MVS_NO_RID_SHOULD_NOT_EMPTY_OR_NULL.getMessage()); + VerificationRequestDTO mar = prepareVerificationRequest(messageDTO, registrationStatusDto); + saveVerificationRecordUtility.saveVerificationRecord(messageDTO, mar.getRequestId(), description); + regProcLogger.debug("Request : " + JsonUtils.javaObjectToJsonString(mar)); + + if (messageFormat.equalsIgnoreCase(TEXT_MESSAGE)) + mosipQueueManager.send(queue, JsonUtils.javaObjectToJsonString(mar), mvRequestAddress, + mvRequestMessageTTL); + else + mosipQueueManager.send(queue, JsonUtils.javaObjectToJsonString(mar).getBytes(), mvRequestAddress, + mvRequestMessageTTL); + + regProcLogger.info("ID : " + messageDTO.getRid() + " has been successfully sent for verification."); + + if (isTransactionSuccessful) { + registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); + registrationStatusDto.setSubStatusCode(StatusUtil.VERIFICATION_SENT.getCode()); + registrationStatusDto.setStatusComment(StatusUtil.VERIFICATION_SENT.getMessage()); + registrationStatusDto + .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.IN_PROGRESS.toString()); + } else { + registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.toString()); + registrationStatusDto.setSubStatusCode(StatusUtil.VERIFICATION_FAILED.getCode()); + registrationStatusDto.setStatusComment(StatusUtil.VERIFICATION_FAILED.getMessage()); + registrationStatusDto + .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.ERROR.toString()); + } + registrationStatusDto.setRegistrationStageName(stageName); + + } catch (DataShareException de) { + messageDTO.setInternalError(true); + isTransactionSuccessful = false; + description.setCode(de.getErrorCode()); + description.setMessage(de.getMessage()); + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + de.getErrorCode(), de.getErrorText()); + + } catch (InvalidRidException exp) { + isTransactionSuccessful = false; + description.setCode(exp.getErrorCode()); + description.setMessage(exp.getMessage()); + messageDTO.setInternalError(true); + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), null, exp.getErrorCode(), exp.getErrorText()); + + } catch (Exception e) { + isTransactionSuccessful = false; + description.setCode(PlatformSuccessMessages.RPR_VERIFICATION_SENT.getCode()); + description.setMessage(e.getMessage()); + messageDTO.setInternalError(true); + regProcLogger.error(ExceptionUtils.getStackTrace(e)); + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + e.getMessage(), e.getMessage()); + } finally { + if (isTransactionSuccessful) { + messageDTO.setIsValid(true); + description.setCode(PlatformSuccessMessages.RPR_VERIFICATION_SUCCESS.getCode()); + description.setMessage(PlatformSuccessMessages.RPR_VERIFICATION_SUCCESS.getMessage()); + } else + registrationStatusDto.setSubStatusCode(StatusUtil.VERIFICATION_FAILED.getCode()); + updateStatus(messageDTO, registrationStatusDto, isTransactionSuccessful, description, + PlatformSuccessMessages.RPR_VERIFICATION_SENT); + } + + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + messageDTO.getRid(), "VerificationServiceImpl::process()::entry"); + + return messageDTO; + } + + /* + * (non-Javadoc) + * + * @see io.mosip.registration.processor.verification.service. + * ManualAdjudicationService#updatePacketStatus(io.mosip.registration.processor. + * verification.dto.ManualVerificationDTO) + */ + @Override + public boolean updatePacketStatus(VerificationResponseDTO manualVerificationDTO, String stageName, + MosipQueue queue) { + + TrimExceptionMessage trimExceptionMessage = new TrimExceptionMessage(); + LogDescription description = new LogDescription(); + boolean isTransactionSuccessful = false; + + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REFERENCEID.toString(), + manualVerificationDTO.getRequestId(), "VerificationServiceImpl::updatePacketStatus()::entry"); + + VerificationEntity entity = validateRequestIdAndReturnRid(manualVerificationDTO.getRequestId()); + String regId = entity != null ? entity.getRegId() : null; + + MessageDTO messageDTO = new MessageDTO(); + InternalRegistrationStatusDto registrationStatusDto = null; + try { + registrationStatusDto = registrationStatusService.getRegistrationStatus( + (entity != null ? entity.getRegId() : null), null, null, + (entity != null ? (entity.getId() != null ? entity.getId().getWorkflowInstanceId() : null) : null)); + registrationStatusDto.setLatestTransactionTypeCode(RegistrationTransactionTypeCode.VERIFICATION.name()); + registrationStatusDto.setRegistrationStageName(stageName); + messageDTO.setInternalError(false); + messageDTO.setIsValid(false); + messageDTO.setRid(regId); + messageDTO.setReg_type(registrationStatusDto.getRegistrationType()); + + List entities = retrieveInqueuedRecordsByRid(regId); + + // check if response is marked for resend + if (isResendFlow(registrationStatusDto, manualVerificationDTO, entity)) { + registrationStatusDto.setStatusComment(StatusUtil.VERIFICATION_RESEND.getMessage()); + registrationStatusDto.setSubStatusCode(StatusUtil.VERIFICATION_RESEND.getCode()); + registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); + registrationStatusDto + .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.REPROCESS.toString()); + description.setMessage(StatusUtil.VERIFICATION_RESEND.getMessage()); + 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 + isTransactionSuccessful = successFlow(manualVerificationDTO, entity, registrationStatusDto, messageDTO, + description); + + registrationStatusDto.setUpdatedBy(USER); + regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString(), regId, description.getMessage()); + } + + } catch (TablenotAccessibleException e) { + messageDTO.setInternalError(true); + registrationStatusDto.setLatestTransactionStatusCode(registrationExceptionMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.TABLE_NOT_ACCESSIBLE_EXCEPTION)); + registrationStatusDto.setStatusComment(trimExceptionMessage + .trimExceptionMessage(StatusUtil.DB_NOT_ACCESSIBLE.getMessage() + e.getMessage())); + registrationStatusDto.setSubStatusCode(StatusUtil.DB_NOT_ACCESSIBLE.getCode()); + + description.setMessage(PlatformErrorMessages.RPR_TABLE_NOT_ACCESSIBLE.getMessage()); + description.setCode(PlatformErrorMessages.RPR_TABLE_NOT_ACCESSIBLE.getCode()); + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + regId, e.getMessage() + ExceptionUtils.getStackTrace(e)); + } catch (NoRecordAssignedException e) { + messageDTO.setIsValid(false); + messageDTO.setInternalError(false); + registrationStatusDto.setLatestTransactionStatusCode( + registrationExceptionMapperUtil.getStatusCode(RegistrationExceptionTypeCode.NO_RECORDS_ASSIGNED)); + registrationStatusDto.setStatusComment(trimExceptionMessage.trimExceptionMessage( + PlatformErrorMessages.RPR_MVS_NO_ASSIGNED_RECORD.getMessage() + e.getMessage())); + registrationStatusDto.setSubStatusCode(PlatformErrorMessages.RPR_MVS_NO_ASSIGNED_RECORD.getCode()); + + description.setMessage(PlatformErrorMessages.RPR_MVS_NO_ASSIGNED_RECORD.getMessage()); + description.setCode(PlatformErrorMessages.RPR_MVS_NO_ASSIGNED_RECORD.getCode()); + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + regId, e.getMessage() + ExceptionUtils.getStackTrace(e)); + } catch (Exception e) { + messageDTO.setInternalError(true); + registrationStatusDto.setLatestTransactionStatusCode( + registrationExceptionMapperUtil.getStatusCode(RegistrationExceptionTypeCode.EXCEPTION)); + registrationStatusDto.setStatusComment(trimExceptionMessage + .trimExceptionMessage(StatusUtil.UNKNOWN_EXCEPTION_OCCURED.getMessage() + e.getMessage())); + registrationStatusDto.setSubStatusCode(StatusUtil.UNKNOWN_EXCEPTION_OCCURED.getCode()); + + description.setMessage(PlatformErrorMessages.UNKNOWN_EXCEPTION.getMessage()); + description.setCode(PlatformErrorMessages.UNKNOWN_EXCEPTION.getCode()); + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + regId, e.getMessage() + ExceptionUtils.getStackTrace(e)); + } finally { + // TODO structure to not return in finally,ignore for sonar + updateStatus(messageDTO, registrationStatusDto, isTransactionSuccessful, description, + PlatformSuccessMessages.RPR_VERIFICATION_SUCCESS); + verificationStage.sendMessage(messageDTO); + } + return isTransactionSuccessful; + } + + private void updateStatus(MessageDTO messageDTO, InternalRegistrationStatusDto registrationStatusDto, + boolean isTransactionSuccessful, LogDescription description, + PlatformSuccessMessages platformSuccessMessages) { + if (messageDTO.getInternalError()) { + updateErrorFlags(registrationStatusDto, messageDTO); + } + registrationStatusDto.setLatestTransactionTypeCode(RegistrationTransactionTypeCode.VERIFICATION.toString()); + String regId = messageDTO.getRid(); + /** Module-Id can be Both Success/Error code */ + 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(); + String eventType = eventId.equalsIgnoreCase(EventId.RPR_402.toString()) ? EventType.BUSINESS.toString() + : EventType.SYSTEM.toString(); + + auditLogRequestBuilder.createAuditRequestBuilder(description.getMessage(), eventId, eventName, eventType, + moduleId, moduleName, regId); + + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + regId, "VerificationServiceImpl::updatePacketStatus()::exit"); + + } + + /** + * Basic validation of requestId received against the rid present in + * manual-adjudication table Returns the correct rid after successful validation + * + * @param reqId : the request id + * @return rid : the registration id + */ + private VerificationEntity validateRequestIdAndReturnRid(String reqId) { + List entities = basePacketRepository.getVerificationRecordByRequestId(reqId); + + if (CollectionUtils.isEmpty(entities) + || new HashSet<>(entities.stream().map(e -> e.getRegId()).collect(Collectors.toList())).size() != 1) { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + entities != null ? entities.stream().map(e -> e.getRegId()).collect(Collectors.toList()) : null, + "Multiple rids found against request id : " + reqId); + throw new InvalidRidException(PlatformErrorMessages.RPR_INVALID_RID_FOUND.getCode(), + PlatformErrorMessages.RPR_INVALID_RID_FOUND.getCode()); + } + + VerificationEntity entity = entities.iterator().next(); + + if (entity != null && StringUtils.isEmpty(entity.getRegId())) { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + entity.getRegId(), "VerificationServiceImpl::updatePacketStatus()::InvalidFileNameException" + + PlatformErrorMessages.RPR_MVS_REG_ID_SHOULD_NOT_EMPTY_OR_NULL.getMessage()); + throw new InvalidFileNameException(PlatformErrorMessages.RPR_MVS_REG_ID_SHOULD_NOT_EMPTY_OR_NULL.getCode(), + PlatformErrorMessages.RPR_MVS_REG_ID_SHOULD_NOT_EMPTY_OR_NULL.getMessage()); + } + return entity; + } + + private List retrieveInqueuedRecordsByRid(String regId) { + + List entities = basePacketRepository.getAssignedVerificationRecord(regId, + ManualVerificationStatus.INQUEUE.name()); + + if (CollectionUtils.isEmpty(entities)) { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + regId, "VerificationServiceImpl::updatePacketStatus()" + + PlatformErrorMessages.RPR_MVS_NO_ASSIGNED_RECORD.getMessage()); + throw new NoRecordAssignedException(PlatformErrorMessages.RPR_MVS_NO_ASSIGNED_RECORD.getCode(), + PlatformErrorMessages.RPR_MVS_NO_ASSIGNED_RECORD.getMessage()); + } + + return entities; + } + + private String getDataShareUrl(String id, String process) throws Exception { + DataShareRequestDto requestDto = new DataShareRequestDto(); + + LinkedHashMap policy = getPolicy(); + + Map policyMap = getPolicyMap(policy); + + // set demographic + Map demographicMap = policyMap.entrySet().stream() + .filter(e -> e.getValue() != null + && (!META_INFO.equalsIgnoreCase(e.getValue()) && !AUDITS.equalsIgnoreCase(e.getValue()))) + .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue())); + requestDto.setIdentity( + packetManagerService.getFields(id, demographicMap.values().stream().collect(Collectors.toList()), + process, ProviderStageName.VERIFICATION)); + + // set documents + JSONObject docJson = utility.getRegistrationProcessorMappingJson(MappingJsonConstants.DOCUMENT); + for (Object doc : docJson.keySet()) { + if (doc != null) { + HashMap docmap = (HashMap) docJson.get(doc.toString()); + String docName = docmap != null && docmap.get(MappingJsonConstants.VALUE) != null + ? docmap.get(MappingJsonConstants.VALUE).toString() + : null; + if (policyMap.containsValue(docName)) { + Document document = packetManagerService.getDocument(id, docName, process, + ProviderStageName.VERIFICATION); + 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); + } + } + } + } + } + + // set audits + if (policyMap.containsValue(AUDITS)) + requestDto.setAudits(JsonUtils.javaObjectToJsonString( + packetManagerService.getAudits(id, process, ProviderStageName.VERIFICATION))); + + // set metainfo + if (policyMap.containsValue(META_INFO)) + requestDto.setMetaInfo(JsonUtils.javaObjectToJsonString( + packetManagerService.getMetaInfo(id, process, ProviderStageName.VERIFICATION))); + + // set biometrics + JSONObject regProcessorIdentityJson = utility + .getRegistrationProcessorMappingJson(MappingJsonConstants.IDENTITY); + String individualBiometricsLabel = JsonUtil.getJSONValue( + JsonUtil.getJSONObject(regProcessorIdentityJson, MappingJsonConstants.INDIVIDUAL_BIOMETRICS), + MappingJsonConstants.VALUE); + + if (policyMap.containsValue(individualBiometricsLabel)) { + List modalities = getModalities(policy); + BiometricRecord biometricRecord = packetManagerService.getBiometrics(id, individualBiometricsLabel, + modalities, process, ProviderStageName.VERIFICATION); + byte[] content = cbeffutil.createXML(biometricRecord.getSegments()); + requestDto.setBiometrics(content != null ? CryptoUtil.encodeToURLSafeBase64(content) : null); + } + + String req = JsonUtils.javaObjectToJsonString(requestDto); + + MultiValueMap map = new LinkedMultiValueMap<>(); + map.add("name", VERIFICATION); + map.add("filename", VERIFICATION); + + ByteArrayResource contentsAsResource = new ByteArrayResource(req.getBytes()) { + @Override + public String getFilename() { + return VERIFICATION; + } + }; + 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 (policy.get(PolicyConstant.DATASHARE_POLICIES) != null) { + LinkedHashMap datasharePolicies = (LinkedHashMap) policies + .get(PolicyConstant.DATASHARE_POLICIES); + if (!CollectionUtils.isEmpty(datasharePolicies) + && datasharePolicies.get(PolicyConstant.SHAREDOMAIN_WRITE) != null) + url = datasharePolicies.get(PolicyConstant.SHAREDOMAIN_WRITE) + + env.getProperty(ApiName.DATASHARECREATEURL.name()); + } + if (StringUtils.isEmpty(url)) + url = protocol + internalDomainName + env.getProperty(ApiName.DATASHARECREATEURL.name()); + url = url.replaceAll("[\\[\\]]", ""); + + LinkedHashMap response = (LinkedHashMap) registrationProcessorRestClientService.postApi(url, + MediaType.MULTIPART_FORM_DATA, pathSegments, null, null, map, LinkedHashMap.class); + if (response == null || (response.get(ERRORS) != null)) + throw new DataShareException( + response == null ? "Datashare response is null" : response.get(ERRORS).toString()); + + LinkedHashMap datashare = (LinkedHashMap) response.get(DATASHARE); + return datashare.get(URL) != null ? datashare.get(URL).toString() : null; + } + + private Map getPolicyMap(LinkedHashMap policies) throws IOException { + Map policyMap = new HashMap<>(); + List attributes = (List) policies.get(VerificationConstants.SHAREABLE_ATTRIBUTES); + for (LinkedHashMap map : attributes) { + ShareableAttributes shareableAttributes = mapper.readValue(mapper.writeValueAsString(map), + ShareableAttributes.class); + policyMap.put(shareableAttributes.getAttributeName(), + shareableAttributes.getSource().iterator().next().getAttribute()); + } + return policyMap; + + } + + private LinkedHashMap getPolicy() throws DataShareException, ApisResourceAccessException { + if (policies != null && policies.size() > 0) + return policies; + + 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(); + policies = (LinkedHashMap) responseMap.get(VerificationConstants.POLICIES); + } + return policies; + + } + + public List getModalities(LinkedHashMap policy) throws IOException { + Map> typeAndSubTypeMap = new HashMap<>(); + List attributes = (List) policy.get(VerificationConstants.SHAREABLE_ATTRIBUTES); + for (LinkedHashMap map : attributes) { + ShareableAttributes shareableAttributes = mapper.readValue(mapper.writeValueAsString(map), + 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); + } + }); + } + } + } + List modalities = new ArrayList<>(); + for (Map.Entry> entry : typeAndSubTypeMap.entrySet()) { + if (entry.getValue() == null) { + modalities.add(entry.getKey()); + } else { + modalities.addAll(entry.getValue()); + } + } + + return modalities; + + } + + /* + * Form manual adjudication request + */ + private VerificationRequestDTO prepareVerificationRequest(MessageDTO messageDTO, + InternalRegistrationStatusDto registrationStatusDto) throws Exception { + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), "", + "VerificationServiceImpl::formAdjudicationRequest()::entry"); + + VerificationRequestDTO req = new VerificationRequestDTO(); + List entities = basePacketRepository + .getVerificationRecordByWorkflowInstanceId(messageDTO.getWorkflowInstanceId()); + if (!CollectionUtils.isEmpty(entities)) + req.setRequestId(entities.get(0).getRequestId()); + else + req.setRequestId(UUID.randomUUID().toString()); + + req.setId(VerificationConstants.MANUAL_ADJUDICATION_ID); + req.setVersion(VerificationConstants.VERSION); + req.setRequesttime(DateUtils.getUTCCurrentDateTimeString(env.getProperty(DATETIME_PATTERN))); + req.setReferenceId(messageDTO.getRid()); + try { + req.setReferenceURL(getDataShareUrl(messageDTO.getRid(), registrationStatusDto.getRegistrationType())); + + } catch (PacketManagerException | ApisResourceAccessException ex) { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + ex.getErrorCode(), ex.getErrorText()); + throw ex; + } + + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), "", + "VerificationServiceImpl::formAdjudicationRequest()::entry"); + + return req; + } + + /** + * Process response for success flow. + * + * @param entity + * @param manualVerificationDTO + * @param registrationStatusDto + * @param messageDTO + * @param description + * @return boolean + * @throws com.fasterxml.jackson.core.JsonProcessingException + */ + private boolean successFlow(VerificationResponseDTO manualVerificationDTO, VerificationEntity entity, + InternalRegistrationStatusDto registrationStatusDto, MessageDTO messageDTO, LogDescription description) + throws JsonProcessingException { + + boolean isTransactionSuccessful = false; + String statusCode = manualVerificationDTO.getReturnValue() == 1 ? ManualVerificationStatus.APPROVED.name() + : ManualVerificationStatus.REJECTED.name(); + + String responsetext = JsonUtils.javaObjectToJsonString(manualVerificationDTO); + responsetext = StringUtils.isNotEmpty(responsetext) ? responsetext.replaceAll("\\s+", "") : responsetext; + + entity.setStatusCode(statusCode); + entity.setReponseText(responsetext); + entity.setStatusComment(statusCode.equalsIgnoreCase(ManualVerificationStatus.APPROVED.name()) + ? StatusUtil.VERIFICATION_SUCCESS.getMessage() + : StatusUtil.VERIFICATION_FAILED.getMessage()); + + isTransactionSuccessful = true; + registrationStatusDto.setLatestTransactionTypeCode(RegistrationTransactionTypeCode.VERIFICATION.toString()); + registrationStatusDto.setRegistrationStageName(registrationStatusDto.getRegistrationStageName()); + + if (statusCode.equalsIgnoreCase(ManualVerificationStatus.APPROVED.name())) { + messageDTO.setIsValid(isTransactionSuccessful); + registrationStatusDto.setStatusComment(StatusUtil.VERIFICATION_SUCCESS.getMessage()); + registrationStatusDto.setSubStatusCode(StatusUtil.VERIFICATION_SUCCESS.getCode()); + registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); + registrationStatusDto.setLatestTransactionStatusCode(RegistrationTransactionStatusCode.SUCCESS.toString()); + + description.setMessage(PlatformSuccessMessages.RPR_VERIFICATION_SUCCESS.getMessage()); + description.setCode(PlatformSuccessMessages.RPR_VERIFICATION_SUCCESS.getCode()); + + } else if (statusCode.equalsIgnoreCase(ManualVerificationStatus.REJECTED.name())) { + registrationStatusDto.setStatusCode(RegistrationStatusCode.REJECTED.toString()); + registrationStatusDto.setStatusComment(StatusUtil.VERIFICATION_FAILED.getMessage()); + registrationStatusDto.setSubStatusCode(StatusUtil.VERIFICATION_FAILED.getCode()); + registrationStatusDto.setLatestTransactionStatusCode(RegistrationTransactionStatusCode.FAILED.toString()); + + description.setMessage(PlatformErrorMessages.RPR_MANUAL_VERIFICATION_REJECTED.getMessage()); + description.setCode(PlatformErrorMessages.RPR_MANUAL_VERIFICATION_REJECTED.getCode()); + messageDTO.setIsValid(Boolean.FALSE); + messageDTO.setInternalError(Boolean.FALSE); + } else { + registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); + registrationStatusDto.setStatusComment(StatusUtil.VERIFICATION_RESEND.getMessage()); + registrationStatusDto.setSubStatusCode(StatusUtil.VERIFICATION_RESEND.getCode()); + registrationStatusDto + .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.IN_PROGRESS.toString()); + + description.setMessage(PlatformErrorMessages.RPR_MANUAL_VERIFICATION_RESEND.getMessage()); + description.setCode(PlatformErrorMessages.RPR_MANUAL_VERIFICATION_RESEND.getCode()); + messageDTO.setIsValid(Boolean.FALSE); + } + basePacketRepository.update(entity); + + return isTransactionSuccessful; + } + + private void updateErrorFlags(InternalRegistrationStatusDto registrationStatusDto, MessageDTO object) { + object.setInternalError(true); + if (registrationStatusDto.getLatestTransactionStatusCode() + .equalsIgnoreCase(RegistrationTransactionStatusCode.REPROCESS.toString())) { + object.setIsValid(true); + } else { + object.setIsValid(false); + } + } + + /** + * This method would validate response and on failure it will mark the response + * for reprocessing. + * + * @param registrationStatusDto + * @param manualVerificationDTO + * @return boolean + * @throws JsonProcessingException + */ + public boolean isResendFlow(InternalRegistrationStatusDto registrationStatusDto, + VerificationResponseDTO manualVerificationDTO, VerificationEntity entity) throws JsonProcessingException { + boolean isResendFlow = false; + if (manualVerificationDTO.getReturnValue() == 2) { + regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + registrationStatusDto.getRegistrationId(), + "Received resend request from manual verification application. This will be marked for reprocessing."); + + // updating status code to pending so that it can be marked for manual + // verification again + registrationStatusDto.setLatestTransactionStatusCode(RegistrationTransactionStatusCode.REPROCESS.name()); + registrationStatusService.updateRegistrationStatus(registrationStatusDto, ModuleName.VERIFICATION.name(), + ModuleName.VERIFICATION.name()); + isResendFlow = true; + } + return isResendFlow; + } + + +} 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..d91d9ea2b48 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 @@ -1,528 +1,527 @@ -package io.mosip.registration.processor.verification.service; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyInt; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.eq; - -import java.sql.Timestamp; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Date; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -import org.apache.activemq.command.ActiveMQBytesMessage; -import org.apache.activemq.util.ByteSequence; -import org.json.simple.JSONObject; -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.Spy; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.modules.junit4.PowerMockRunner; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.core.env.Environment; -import org.springframework.test.util.ReflectionTestUtils; - -import com.fasterxml.jackson.databind.ObjectMapper; - -import ch.qos.logback.classic.Logger; -import ch.qos.logback.classic.spi.ILoggingEvent; -import ch.qos.logback.core.read.ListAppender; -import io.mosip.kernel.biometrics.constant.BiometricType; -import io.mosip.kernel.biometrics.constant.QualityType; -import io.mosip.kernel.biometrics.entities.BDBInfo; -import io.mosip.kernel.biometrics.entities.BIR; -import io.mosip.kernel.biometrics.entities.BiometricRecord; -import io.mosip.kernel.biometrics.entities.RegistryIDType; -import io.mosip.kernel.biometrics.spi.CbeffUtil; -import io.mosip.kernel.core.util.DateUtils; -import io.mosip.kernel.core.util.exception.JsonProcessingException; -import io.mosip.registration.processor.core.abstractverticle.MessageDTO; -import io.mosip.registration.processor.core.code.ApiName; -import io.mosip.registration.processor.core.code.RegistrationTransactionStatusCode; -import io.mosip.registration.processor.core.exception.ApisResourceAccessException; -import io.mosip.registration.processor.core.http.ResponseWrapper; -import io.mosip.registration.processor.core.kernel.master.dto.UserResponseDTO; -import io.mosip.registration.processor.core.kernel.master.dto.UserResponseDTOWrapper; -import io.mosip.registration.processor.core.logger.LogDescription; -import io.mosip.registration.processor.core.packet.dto.Identity; -import io.mosip.registration.processor.core.queue.factory.MosipQueue; -import io.mosip.registration.processor.core.spi.packetmanager.PacketInfoManager; -import io.mosip.registration.processor.core.spi.queue.MosipQueueManager; -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.storage.dto.ApplicantInfoDto; -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.repository.BasePacketRepository; -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; -import io.mosip.registration.processor.verification.dto.ManualVerificationDTO; -import io.mosip.registration.processor.verification.dto.ManualVerificationStatus; -import io.mosip.registration.processor.verification.dto.MatchDetail; -import io.mosip.registration.processor.verification.dto.UserDto; -import io.mosip.registration.processor.verification.dto.VerificationDecisionDto; -import io.mosip.registration.processor.verification.exception.InvalidRidException; -import io.mosip.registration.processor.verification.response.dto.VerificationResponseDTO; -import io.mosip.registration.processor.verification.service.impl.VerificationServiceImpl; -import io.mosip.registration.processor.verification.stage.VerificationStage; -import io.mosip.registration.processor.verification.util.SaveVerificationRecordUtility; - -@RunWith(PowerMockRunner.class) -@PowerMockIgnore({ "com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*","javax.management.*", "javax.net.ssl.*" }) -public class VerificationServiceTest { - - private static final String STAGE_NAME = "VerificationStage"; - private List entities; - private List entitiesTemp; - @InjectMocks - private VerificationService verificationService = new VerificationServiceImpl(); - - @Autowired - private ObjectMapper objectMapper = new ObjectMapper(); - - @Mock - UserDto dto; - - @Spy - private ObjectMapper mapper = new ObjectMapper(); - - @Mock - private VerificationStage manualAdjudicationStage; - - @Mock - VerificationService mockManualAdjudicationService; - - @Mock - AuditLogRequestBuilder auditLogRequestBuilder; - - @Mock - RegistrationStatusService registrationStatusService; - - @Mock - private Utilities utility; - - @Mock - private PacketInfoManager packetInfoManager; - - @Mock - private BasePacketRepository basePacketRepository; - - @Mock - private PriorityBasedPacketManagerService packetManagerService; - - @Mock - private JsonUtil jsonUtil; - - @Mock - private MosipQueueManager mosipQueueManager; - - @Mock - private RegistrationProcessorRestClientService registrationProcessorRestClientService; - - @Mock - SaveVerificationRecordUtility saveVerificationRecordUtility; - - - private InternalRegistrationStatusDto registrationStatusDto; - private VerificationPKEntity PKId; - private ManualVerificationDTO manualVerificationDTO; - private MatchDetail matchDetail=new MatchDetail(); - private VerificationEntity manualVerificationEntity; - private ListAppender listAppender; - private Logger regprocLogger; - ClassLoader classLoader; - - private String stageName = "ManualVerificationStage"; - - private ResponseWrapper responseWrapper = new ResponseWrapper<>(); - private UserResponseDTOWrapper userResponseDTOWrapper = new UserResponseDTOWrapper(); - private List userResponseDto = new ArrayList<>(); - private UserResponseDTO userResponseDTO = new UserResponseDTO(); - private VerificationDecisionDto verificationDecisionDto =new VerificationDecisionDto(); - private VerificationResponseDTO verificationResponseDTO=new VerificationResponseDTO(); - private MosipQueue queue; - LinkedHashMap dataShareResponse; - - @Mock - LogDescription description; - - @Mock - private Environment env; - - @Mock - private CbeffUtil cbeffutil; - - MessageDTO object; - - @Mock - RegistrationExceptionMapperUtil registrationExceptionMapperUtil; - - VerificationResponseDTO resp; - - @Before - public void setup() throws Exception { - - resp = new VerificationResponseDTO(); - resp.setId("verification"); - resp.setRequestId("e2e59a9b-ce7c-41ae-a953-effb854d1205"); - resp.setResponsetime(DateUtils.getCurrentDateTimeString()); - resp.setReturnValue(1); - - object = new MessageDTO(); - object.setReg_type("NEW"); - object.setRid("92379526572940"); - object.setIteration(1); - object.setWorkflowInstanceId("26fa3eff-f3b9-48f7-b365-d7f7c2e56e00"); - object.setIsValid(true); - object.setInternalError(false); - - queue=new MosipQueue() { - - @Override - public String getQueueName() { - return null; - } - - @Override - public void createConnection(String username, String password, String brokerUrl, - List trustedPackage) { - - } - }; - - ReflectionTestUtils.setField(verificationService, "messageFormat", "text"); - regprocLogger = (Logger) LoggerFactory.getLogger(VerificationServiceImpl.class); - listAppender = new ListAppender<>(); - classLoader = getClass().getClassLoader(); - - manualVerificationDTO = new ManualVerificationDTO(); - registrationStatusDto = new InternalRegistrationStatusDto(); - dto = new UserDto(); - - PKId = new VerificationPKEntity(); - PKId.setWorkflowInstanceId("WorkflowInstanceId"); - dto.setUserId("mvusr22"); - - entities = new ArrayList(); - entitiesTemp = new ArrayList(); - manualVerificationEntity = new VerificationEntity(); - manualVerificationEntity.setRegId("10002100741000320210107125533"); - manualVerificationEntity.setCrBy("regprc"); - Date date = new Date(); - manualVerificationEntity.setDelDtimes(new Timestamp(date.getTime())); - manualVerificationEntity.setStatusComment("test"); - manualVerificationEntity.setStatusCode(ManualVerificationStatus.PENDING.name()); - manualVerificationEntity.setReasonCode("test"); - manualVerificationEntity.setId(PKId); - entities.add(manualVerificationEntity); - - matchDetail.setMatchedRefType("Type"); - matchDetail.setMatchedRegId("RefID"); - matchDetail.setReasonCode(null); - matchDetail.setUrl(null); - manualVerificationDTO.setRegId("RegID"); - - manualVerificationDTO.setMvUsrId("test"); - registrationStatusDto.setStatusCode(ManualVerificationStatus.PENDING.name()); - registrationStatusDto.setStatusComment("test"); - registrationStatusDto.setRegistrationType("LOST"); - registrationStatusDto.setRegistrationId("10002100741000320210107125533"); - registrationStatusDto.setLatestTransactionStatusCode(RegistrationTransactionStatusCode.FAILED.toString()); - - List list=new ArrayList<>(); - list.add(matchDetail); - manualVerificationDTO.setGallery(list); - manualVerificationDTO.setStatusCode("PENDING"); - - Mockito.when(basePacketRepository.getFirstApplicantDetails(ManualVerificationStatus.PENDING.name(), "DEMO")) - .thenReturn(entities); - Mockito.when(basePacketRepository.getAssignedApplicantDetails(any(), any())).thenReturn(entities); - Mockito.doNothing().when(description).setMessage(any()); - Mockito.when(registrationExceptionMapperUtil.getStatusCode(any())).thenReturn("ERROR"); - userResponseDTO.setStatusCode("ACT"); - userResponseDTOWrapper.setUserResponseDto(userResponseDto); - responseWrapper.setResponse(userResponseDTOWrapper); - verificationDecisionDto.setMatchedRefType("Type"); - verificationDecisionDto.setMvUsrId("mvusr22"); - verificationDecisionDto.setReasonCode("test"); - verificationDecisionDto.setRegId("RegID"); - verificationDecisionDto.setStatusCode("APPROVED"); - verificationResponseDTO.setReturnValue(1); - verificationResponseDTO.setResponsetime(DateUtils.getCurrentDateTimeString()); - verificationResponseDTO.setId("mosip.manual.adjudication.adjudicate"); - verificationResponseDTO.setRequestId("4d4f27d3-ec73-41c4-a384-bf87fce4969e"); - - List birTypeList = new ArrayList<>(); - BIR birType1 = new BIR.BIRBuilder().build(); - io.mosip.kernel.biometrics.entities.BDBInfo bdbInfoType1 = new BDBInfo.BDBInfoBuilder().build(); - io.mosip.kernel.biometrics.entities.RegistryIDType registryIDType = new RegistryIDType(); - registryIDType.setOrganization("Mosip"); - registryIDType.setType("257"); - io.mosip.kernel.biometrics.constant.QualityType quality = new QualityType(); - quality.setAlgorithm(registryIDType); - quality.setScore(90l); - bdbInfoType1.setQuality(quality); - BiometricType singleType1 = BiometricType.FINGER; - List singleTypeList1 = new ArrayList<>(); - singleTypeList1.add(singleType1); - List subtype1 = new ArrayList<>(Arrays.asList("Left", "RingFinger")); - bdbInfoType1.setSubtype(subtype1); - bdbInfoType1.setType(singleTypeList1); - birType1.setBdbInfo(bdbInfoType1); - birTypeList.add(birType1); - - BiometricRecord biometricRecord = new BiometricRecord(); - biometricRecord.setSegments(birTypeList); - - JSONObject docObject = new JSONObject(); - HashMap docmap = new HashMap(); - docmap.put("documentType", "DOC005"); - docmap.put("documentCategory", "POI"); - docmap.put("documentName", "POI_DOC005"); - docObject.put("POI", docmap); - - JSONObject regProcessorIdentityJson = new JSONObject(); - LinkedHashMap bioIdentity = new LinkedHashMap(); - bioIdentity.put("value", "biometrics"); - regProcessorIdentityJson.put("individualBiometrics", bioIdentity); - - Map identity = new HashMap(); - identity.put("fullName", "Satish"); - - Map metaInfo = new HashMap(); - metaInfo.put("registrationId", "92379526572940"); - - dataShareResponse = new LinkedHashMap(); - LinkedHashMap datashareUrl = new LinkedHashMap(); - datashareUrl.put("url", "Http://....."); - dataShareResponse.put("dataShare", datashareUrl); - - Mockito.when(env.getProperty("mosip.registration.processor.datetime.pattern")).thenReturn("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); - Mockito.when(env.getProperty(ApiName.DATASHARECREATEURL.name())).thenReturn("/v1/datashare/create"); - Mockito.when(registrationStatusService.getRegistrationStatus(anyString(), any(), any(), any())) - .thenReturn(registrationStatusDto); - - Mockito.when(packetManagerService.getFields(anyString(), any(), anyString(), any())).thenReturn(identity); - Mockito.when(packetManagerService.getBiometrics(anyString(), anyString(), any(), anyString(), any())) - .thenReturn(biometricRecord); - Mockito.when(cbeffutil.createXML(any())).thenReturn(new byte[120]); - Mockito.when(packetManagerService.getMetaInfo(anyString(), anyString(), any())).thenReturn(metaInfo); - Mockito.when(utility.getRegistrationProcessorMappingJson(any())).thenReturn(docObject) - .thenReturn(regProcessorIdentityJson); - Mockito.when(mosipQueueManager.send(any(), anyString(), anyString(), anyInt())).thenReturn(true); - - ResponseWrapper policiesResponse = new ResponseWrapper(); - LinkedHashMap policiesMap = new LinkedHashMap(); - List attributeList = new ArrayList(); - LinkedHashMap shareableAttributes = new LinkedHashMap(); - LinkedHashMap attribute1 = new LinkedHashMap(); - attribute1.put("encrypted", "true"); - attribute1.put("attributeName", "fullName"); - LinkedHashMap source = new LinkedHashMap(); - source.put("attribute", "fullName"); - attribute1.put("source", Arrays.asList(source)); - LinkedHashMap attribute2 = new LinkedHashMap(); - attribute2.put("encrypted", "true"); - attribute2.put("attributeName", "meta_info"); - LinkedHashMap source2 = new LinkedHashMap(); - source2.put("attribute", "meta_info"); - attribute2.put("source", Arrays.asList(source2)); - LinkedHashMap attribute3 = new LinkedHashMap(); - attribute3.put("encrypted", "true"); - attribute3.put("attributeName", "biometrics"); - LinkedHashMap source31 = new LinkedHashMap(); - LinkedHashMap source32 = new LinkedHashMap(); - LinkedHashMap source33 = new LinkedHashMap(); - List filter1 = new ArrayList(); - List filter2 = new ArrayList(); - List filter3 = new ArrayList(); - LinkedHashMap type1 = new LinkedHashMap(); - type1.put("type", "Iris"); - filter1.add(type1); - LinkedHashMap type2 = new LinkedHashMap(); - type2.put("type", "Finger"); - filter2.add(type2); - LinkedHashMap type3 = new LinkedHashMap(); - type3.put("type", "Face"); - filter3.add(type3); - source31.put("attribute", "biometrics"); - source31.put("filter", filter1); - source32.put("attribute", "biometrics"); - source32.put("filter", filter2); - source33.put("attribute", "biometrics"); - source33.put("filter", filter3); - attribute3.put("source", Arrays.asList(source31, source32, source33)); - attributeList.add(attribute1); - attributeList.add(attribute2); - attributeList.add(attribute3); - shareableAttributes.put("shareableAttributes", attributeList); - policiesMap.put("policies", shareableAttributes); - policiesResponse.setResponse(policiesMap); - - Mockito.when(registrationProcessorRestClientService.getApi(any(), any(), anyString(), anyString(), - eq(ResponseWrapper.class))).thenReturn(policiesResponse); - - Mockito.when(basePacketRepository.getVerificationRecordByRequestId(resp.getRequestId())).thenReturn(entities); - - } - - @Test - public void testVerificationSuccess() throws ApisResourceAccessException { - - Mockito.when(registrationProcessorRestClientService.postApi(anyString(), any(), any(), any(), any(), any(), - eq(LinkedHashMap.class))).thenReturn(dataShareResponse); - - MessageDTO response = verificationService.process(object, queue, stageName); - - assertTrue(response.getIsValid()); - } - - @Test - public void testVerificationFailed() throws ApisResourceAccessException { - - Mockito.when(registrationProcessorRestClientService.postApi(anyString(), any(), any(), any(), any(), any(), - eq(LinkedHashMap.class))).thenThrow(new ApisResourceAccessException("exception")); - - MessageDTO response = verificationService.process(object, queue, stageName); - - assertFalse(response.getIsValid()); - assertTrue(response.getInternalError()); - } - - @Test - public void testVerificationDatashareException() throws ApisResourceAccessException { - LinkedHashMap dataShareResponse = new LinkedHashMap(); - LinkedHashMap datashareUrl = new LinkedHashMap(); - datashareUrl.put("errors", "Http://....."); - dataShareResponse.put("errors", datashareUrl); - - Mockito.when(registrationProcessorRestClientService.postApi(anyString(), any(), any(), any(), any(), any(), - eq(LinkedHashMap.class))).thenReturn(dataShareResponse); - - MessageDTO response = verificationService.process(object, queue, stageName); - - assertFalse(response.getIsValid()); - assertTrue(response.getInternalError()); - } - - @Test - public void testVerificationInvalidRId() { - object.setRid(""); - - MessageDTO response = verificationService.process(object, queue, stageName); - - assertFalse(response.getIsValid()); - assertTrue(response.getInternalError()); - } - - @Test(expected = InvalidRidException.class) - public void testInvalidRidException() throws JsonProcessingException, com.fasterxml.jackson.core.JsonProcessingException { - - - String response = objectMapper.writeValueAsString(resp); - - ActiveMQBytesMessage amq = new ActiveMQBytesMessage(); - ByteSequence byteSeq = new ByteSequence(); - byteSeq.setData(response.getBytes()); - amq.setContent(byteSeq); - - resp.setRequestId("2344"); - - boolean result = verificationService.updatePacketStatus(resp, stageName, queue); - } - - @Test - public void testNoRecordAssignedException() throws JsonProcessingException, com.fasterxml.jackson.core.JsonProcessingException { - - - String response = objectMapper.writeValueAsString(resp); - - ActiveMQBytesMessage amq = new ActiveMQBytesMessage(); - ByteSequence byteSeq = new ByteSequence(); - byteSeq.setData(response.getBytes()); - amq.setContent(byteSeq); - - boolean result = verificationService.updatePacketStatus(resp, stageName, queue); - - assertFalse(result); - } - - @Test - @Ignore - public void testUpdateStatusSuccess() throws com.fasterxml.jackson.core.JsonProcessingException { - - Mockito.when(basePacketRepository.getAssignedVerificationRecord(anyString(), anyString())).thenReturn(entities); - - String response = objectMapper.writeValueAsString(resp); - - ActiveMQBytesMessage amq = new ActiveMQBytesMessage(); - ByteSequence byteSeq = new ByteSequence(); - byteSeq.setData(response.getBytes()); - amq.setContent(byteSeq); - - boolean result = verificationService.updatePacketStatus(resp, stageName, queue); - - assertTrue(result); - } - - @Test - public void testUpdateStatusResend() throws com.fasterxml.jackson.core.JsonProcessingException { - - Mockito.when(basePacketRepository.getAssignedVerificationRecord(anyString(), anyString())).thenReturn(entities); - - String response = objectMapper.writeValueAsString(resp); - - ActiveMQBytesMessage amq = new ActiveMQBytesMessage(); - ByteSequence byteSeq = new ByteSequence(); - byteSeq.setData(response.getBytes()); - amq.setContent(byteSeq); - - // for resend - resp.setReturnValue(2); - - boolean result = verificationService.updatePacketStatus(resp, stageName, queue); - - assertFalse(result); - } - - - @Test - @Ignore - public void testUpdateStatusRejected() throws JsonProcessingException, com.fasterxml.jackson.core.JsonProcessingException { - - Mockito.when(basePacketRepository.getAssignedVerificationRecord(anyString(), anyString())).thenReturn(entities); - - String response = objectMapper.writeValueAsString(resp); - - ActiveMQBytesMessage amq = new ActiveMQBytesMessage(); - ByteSequence byteSeq = new ByteSequence(); - byteSeq.setData(response.getBytes()); - amq.setContent(byteSeq); - - // for rejected - resp.setReturnValue(3); - - boolean result = verificationService.updatePacketStatus(resp, stageName, queue); - - assertTrue(result); - } - -} - +package io.mosip.registration.processor.verification.service; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; + +import java.sql.Timestamp; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Date; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import org.apache.activemq.command.ActiveMQBytesMessage; +import org.apache.activemq.util.ByteSequence; +import org.json.simple.JSONObject; +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.Spy; +import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.modules.junit4.PowerMockRunner; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; +import org.springframework.test.util.ReflectionTestUtils; + +import com.fasterxml.jackson.databind.ObjectMapper; + +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.read.ListAppender; +import io.mosip.kernel.biometrics.constant.BiometricType; +import io.mosip.kernel.biometrics.constant.QualityType; +import io.mosip.kernel.biometrics.entities.BDBInfo; +import io.mosip.kernel.biometrics.entities.BIR; +import io.mosip.kernel.biometrics.entities.BiometricRecord; +import io.mosip.kernel.biometrics.entities.RegistryIDType; +import io.mosip.kernel.biometrics.spi.CbeffUtil; +import io.mosip.kernel.core.util.DateUtils; +import io.mosip.kernel.core.util.exception.JsonProcessingException; +import io.mosip.registration.processor.core.abstractverticle.MessageDTO; +import io.mosip.registration.processor.core.code.ApiName; +import io.mosip.registration.processor.core.code.RegistrationTransactionStatusCode; +import io.mosip.registration.processor.core.exception.ApisResourceAccessException; +import io.mosip.registration.processor.core.http.ResponseWrapper; +import io.mosip.registration.processor.core.kernel.master.dto.UserResponseDTO; +import io.mosip.registration.processor.core.kernel.master.dto.UserResponseDTOWrapper; +import io.mosip.registration.processor.core.logger.LogDescription; +import io.mosip.registration.processor.core.packet.dto.Identity; +import io.mosip.registration.processor.core.queue.factory.MosipQueue; +import io.mosip.registration.processor.core.spi.packetmanager.PacketInfoManager; +import io.mosip.registration.processor.core.spi.queue.MosipQueueManager; +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.storage.dto.ApplicantInfoDto; +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.repository.BasePacketRepository; +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; +import io.mosip.registration.processor.verification.dto.ManualVerificationDTO; +import io.mosip.registration.processor.verification.dto.ManualVerificationStatus; +import io.mosip.registration.processor.verification.dto.MatchDetail; +import io.mosip.registration.processor.verification.dto.UserDto; +import io.mosip.registration.processor.verification.dto.VerificationDecisionDto; +import io.mosip.registration.processor.verification.exception.InvalidRidException; +import io.mosip.registration.processor.verification.response.dto.VerificationResponseDTO; +import io.mosip.registration.processor.verification.service.impl.VerificationServiceImpl; +import io.mosip.registration.processor.verification.stage.VerificationStage; +import io.mosip.registration.processor.verification.util.SaveVerificationRecordUtility; + +@RunWith(PowerMockRunner.class) +@PowerMockIgnore({ "com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*","javax.management.*", "javax.net.ssl.*" }) +public class VerificationServiceTest { + + private static final String STAGE_NAME = "VerificationStage"; + private List entities; + private List entitiesTemp; + @InjectMocks + private VerificationService verificationService = new VerificationServiceImpl(); + + @Autowired + private ObjectMapper objectMapper = new ObjectMapper(); + + @Mock + UserDto dto; + + @Spy + private ObjectMapper mapper = new ObjectMapper(); + + @Mock + private VerificationStage manualAdjudicationStage; + + @Mock + VerificationService mockManualAdjudicationService; + + @Mock + AuditLogRequestBuilder auditLogRequestBuilder; + + @Mock + RegistrationStatusService registrationStatusService; + + @Mock + private Utilities utility; + + @Mock + private PacketInfoManager packetInfoManager; + + @Mock + private BasePacketRepository basePacketRepository; + + @Mock + private PriorityBasedPacketManagerService packetManagerService; + + @Mock + private JsonUtil jsonUtil; + + @Mock + private MosipQueueManager mosipQueueManager; + + @Mock + private RegistrationProcessorRestClientService registrationProcessorRestClientService; + + @Mock + SaveVerificationRecordUtility saveVerificationRecordUtility; + + private InternalRegistrationStatusDto registrationStatusDto; + private VerificationPKEntity PKId; + private ManualVerificationDTO manualVerificationDTO; + private MatchDetail matchDetail=new MatchDetail(); + private VerificationEntity manualVerificationEntity; + private ListAppender listAppender; + private Logger regprocLogger; + ClassLoader classLoader; + + private String stageName = "ManualVerificationStage"; + + private ResponseWrapper responseWrapper = new ResponseWrapper<>(); + private UserResponseDTOWrapper userResponseDTOWrapper = new UserResponseDTOWrapper(); + private List userResponseDto = new ArrayList<>(); + private UserResponseDTO userResponseDTO = new UserResponseDTO(); + private VerificationDecisionDto verificationDecisionDto =new VerificationDecisionDto(); + private VerificationResponseDTO verificationResponseDTO=new VerificationResponseDTO(); + private MosipQueue queue; + LinkedHashMap dataShareResponse; + + @Mock + LogDescription description; + + @Mock + private Environment env; + + @Mock + private CbeffUtil cbeffutil; + + MessageDTO object; + + @Mock + RegistrationExceptionMapperUtil registrationExceptionMapperUtil; + + VerificationResponseDTO resp; + + @Before + public void setup() throws Exception { + + resp = new VerificationResponseDTO(); + resp.setId("verification"); + resp.setRequestId("e2e59a9b-ce7c-41ae-a953-effb854d1205"); + resp.setResponsetime(DateUtils.getCurrentDateTimeString()); + resp.setReturnValue(1); + + object = new MessageDTO(); + object.setReg_type("NEW"); + object.setRid("92379526572940"); + object.setIteration(1); + object.setWorkflowInstanceId("26fa3eff-f3b9-48f7-b365-d7f7c2e56e00"); + object.setIsValid(true); + object.setInternalError(false); + + queue=new MosipQueue() { + + @Override + public String getQueueName() { + return null; + } + + @Override + public void createConnection(String username, String password, String brokerUrl, + List trustedPackage) { + + } + }; + + ReflectionTestUtils.setField(verificationService, "messageFormat", "text"); + regprocLogger = (Logger) LoggerFactory.getLogger(VerificationServiceImpl.class); + listAppender = new ListAppender<>(); + classLoader = getClass().getClassLoader(); + + manualVerificationDTO = new ManualVerificationDTO(); + registrationStatusDto = new InternalRegistrationStatusDto(); + dto = new UserDto(); + + PKId = new VerificationPKEntity(); + PKId.setWorkflowInstanceId("WorkflowInstanceId"); + dto.setUserId("mvusr22"); + + entities = new ArrayList(); + entitiesTemp = new ArrayList(); + manualVerificationEntity = new VerificationEntity(); + manualVerificationEntity.setRegId("10002100741000320210107125533"); + manualVerificationEntity.setCrBy("regprc"); + Date date = new Date(); + manualVerificationEntity.setDelDtimes(new Timestamp(date.getTime())); + manualVerificationEntity.setStatusComment("test"); + manualVerificationEntity.setStatusCode(ManualVerificationStatus.PENDING.name()); + manualVerificationEntity.setReasonCode("test"); + manualVerificationEntity.setId(PKId); + entities.add(manualVerificationEntity); + + matchDetail.setMatchedRefType("Type"); + matchDetail.setMatchedRegId("RefID"); + matchDetail.setReasonCode(null); + matchDetail.setUrl(null); + manualVerificationDTO.setRegId("RegID"); + + manualVerificationDTO.setMvUsrId("test"); + registrationStatusDto.setStatusCode(ManualVerificationStatus.PENDING.name()); + registrationStatusDto.setStatusComment("test"); + registrationStatusDto.setRegistrationType("LOST"); + registrationStatusDto.setRegistrationId("10002100741000320210107125533"); + registrationStatusDto.setLatestTransactionStatusCode(RegistrationTransactionStatusCode.FAILED.toString()); + + List list=new ArrayList<>(); + list.add(matchDetail); + manualVerificationDTO.setGallery(list); + manualVerificationDTO.setStatusCode("PENDING"); + + Mockito.when(basePacketRepository.getFirstApplicantDetails(ManualVerificationStatus.PENDING.name(), "DEMO")) + .thenReturn(entities); + Mockito.when(basePacketRepository.getAssignedApplicantDetails(any(), any())).thenReturn(entities); + Mockito.doNothing().when(description).setMessage(any()); + Mockito.when(registrationExceptionMapperUtil.getStatusCode(any())).thenReturn("ERROR"); + userResponseDTO.setStatusCode("ACT"); + userResponseDTOWrapper.setUserResponseDto(userResponseDto); + responseWrapper.setResponse(userResponseDTOWrapper); + verificationDecisionDto.setMatchedRefType("Type"); + verificationDecisionDto.setMvUsrId("mvusr22"); + verificationDecisionDto.setReasonCode("test"); + verificationDecisionDto.setRegId("RegID"); + verificationDecisionDto.setStatusCode("APPROVED"); + verificationResponseDTO.setReturnValue(1); + verificationResponseDTO.setResponsetime(DateUtils.getCurrentDateTimeString()); + verificationResponseDTO.setId("mosip.manual.adjudication.adjudicate"); + verificationResponseDTO.setRequestId("4d4f27d3-ec73-41c4-a384-bf87fce4969e"); + + List birTypeList = new ArrayList<>(); + BIR birType1 = new BIR.BIRBuilder().build(); + io.mosip.kernel.biometrics.entities.BDBInfo bdbInfoType1 = new BDBInfo.BDBInfoBuilder().build(); + io.mosip.kernel.biometrics.entities.RegistryIDType registryIDType = new RegistryIDType(); + registryIDType.setOrganization("Mosip"); + registryIDType.setType("257"); + io.mosip.kernel.biometrics.constant.QualityType quality = new QualityType(); + quality.setAlgorithm(registryIDType); + quality.setScore(90l); + bdbInfoType1.setQuality(quality); + BiometricType singleType1 = BiometricType.FINGER; + List singleTypeList1 = new ArrayList<>(); + singleTypeList1.add(singleType1); + List subtype1 = new ArrayList<>(Arrays.asList("Left", "RingFinger")); + bdbInfoType1.setSubtype(subtype1); + bdbInfoType1.setType(singleTypeList1); + birType1.setBdbInfo(bdbInfoType1); + birTypeList.add(birType1); + + BiometricRecord biometricRecord = new BiometricRecord(); + biometricRecord.setSegments(birTypeList); + + JSONObject docObject = new JSONObject(); + HashMap docmap = new HashMap(); + docmap.put("documentType", "DOC005"); + docmap.put("documentCategory", "POI"); + docmap.put("documentName", "POI_DOC005"); + docObject.put("POI", docmap); + + JSONObject regProcessorIdentityJson = new JSONObject(); + LinkedHashMap bioIdentity = new LinkedHashMap(); + bioIdentity.put("value", "biometrics"); + regProcessorIdentityJson.put("individualBiometrics", bioIdentity); + + Map identity = new HashMap(); + identity.put("fullName", "Satish"); + + Map metaInfo = new HashMap(); + metaInfo.put("registrationId", "92379526572940"); + + dataShareResponse = new LinkedHashMap(); + LinkedHashMap datashareUrl = new LinkedHashMap(); + datashareUrl.put("url", "Http://....."); + dataShareResponse.put("dataShare", datashareUrl); + + Mockito.when(env.getProperty("mosip.registration.processor.datetime.pattern")).thenReturn("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); + Mockito.when(env.getProperty(ApiName.DATASHARECREATEURL.name())).thenReturn("/v1/datashare/create"); + Mockito.when(registrationStatusService.getRegistrationStatus(anyString(), any(), any(), any())) + .thenReturn(registrationStatusDto); + + Mockito.when(packetManagerService.getFields(anyString(), any(), anyString(), any())).thenReturn(identity); + Mockito.when(packetManagerService.getBiometrics(anyString(), anyString(), any(), anyString(), any())) + .thenReturn(biometricRecord); + Mockito.when(cbeffutil.createXML(any())).thenReturn(new byte[120]); + Mockito.when(packetManagerService.getMetaInfo(anyString(), anyString(), any())).thenReturn(metaInfo); + Mockito.when(utility.getRegistrationProcessorMappingJson(any())).thenReturn(docObject) + .thenReturn(regProcessorIdentityJson); + Mockito.when(mosipQueueManager.send(any(), anyString(), anyString(), anyInt())).thenReturn(true); + + ResponseWrapper policiesResponse = new ResponseWrapper(); + LinkedHashMap policiesMap = new LinkedHashMap(); + List attributeList = new ArrayList(); + LinkedHashMap shareableAttributes = new LinkedHashMap(); + LinkedHashMap attribute1 = new LinkedHashMap(); + attribute1.put("encrypted", "true"); + attribute1.put("attributeName", "fullName"); + LinkedHashMap source = new LinkedHashMap(); + source.put("attribute", "fullName"); + attribute1.put("source", Arrays.asList(source)); + LinkedHashMap attribute2 = new LinkedHashMap(); + attribute2.put("encrypted", "true"); + attribute2.put("attributeName", "meta_info"); + LinkedHashMap source2 = new LinkedHashMap(); + source2.put("attribute", "meta_info"); + attribute2.put("source", Arrays.asList(source2)); + LinkedHashMap attribute3 = new LinkedHashMap(); + attribute3.put("encrypted", "true"); + attribute3.put("attributeName", "biometrics"); + LinkedHashMap source31 = new LinkedHashMap(); + LinkedHashMap source32 = new LinkedHashMap(); + LinkedHashMap source33 = new LinkedHashMap(); + List filter1 = new ArrayList(); + List filter2 = new ArrayList(); + List filter3 = new ArrayList(); + LinkedHashMap type1 = new LinkedHashMap(); + type1.put("type", "Iris"); + filter1.add(type1); + LinkedHashMap type2 = new LinkedHashMap(); + type2.put("type", "Finger"); + filter2.add(type2); + LinkedHashMap type3 = new LinkedHashMap(); + type3.put("type", "Face"); + filter3.add(type3); + source31.put("attribute", "biometrics"); + source31.put("filter", filter1); + source32.put("attribute", "biometrics"); + source32.put("filter", filter2); + source33.put("attribute", "biometrics"); + source33.put("filter", filter3); + attribute3.put("source", Arrays.asList(source31, source32, source33)); + attributeList.add(attribute1); + attributeList.add(attribute2); + attributeList.add(attribute3); + shareableAttributes.put("shareableAttributes", attributeList); + policiesMap.put("policies", shareableAttributes); + policiesResponse.setResponse(policiesMap); + + Mockito.when(registrationProcessorRestClientService.getApi(any(), any(), anyString(), anyString(), + eq(ResponseWrapper.class))).thenReturn(policiesResponse); + + Mockito.when(basePacketRepository.getVerificationRecordByRequestId(resp.getRequestId())).thenReturn(entities); + + } + + @Test + public void testVerificationSuccess() throws ApisResourceAccessException { + + Mockito.when(registrationProcessorRestClientService.postApi(anyString(), any(), any(), any(), any(), any(), + eq(LinkedHashMap.class))).thenReturn(dataShareResponse); + + MessageDTO response = verificationService.process(object, queue, stageName); + + assertTrue(response.getIsValid()); + } + + @Test + public void testVerificationFailed() throws ApisResourceAccessException { + + Mockito.when(registrationProcessorRestClientService.postApi(anyString(), any(), any(), any(), any(), any(), + eq(LinkedHashMap.class))).thenThrow(new ApisResourceAccessException("exception")); + + MessageDTO response = verificationService.process(object, queue, stageName); + + assertFalse(response.getIsValid()); + assertTrue(response.getInternalError()); + } + + @Test + public void testVerificationDatashareException() throws ApisResourceAccessException { + LinkedHashMap dataShareResponse = new LinkedHashMap(); + LinkedHashMap datashareUrl = new LinkedHashMap(); + datashareUrl.put("errors", "Http://....."); + dataShareResponse.put("errors", datashareUrl); + + Mockito.when(registrationProcessorRestClientService.postApi(anyString(), any(), any(), any(), any(), any(), + eq(LinkedHashMap.class))).thenReturn(dataShareResponse); + + MessageDTO response = verificationService.process(object, queue, stageName); + + assertFalse(response.getIsValid()); + assertTrue(response.getInternalError()); + } + + @Test + public void testVerificationInvalidRId() { + object.setRid(""); + + MessageDTO response = verificationService.process(object, queue, stageName); + + assertFalse(response.getIsValid()); + assertTrue(response.getInternalError()); + } + + @Test(expected = InvalidRidException.class) + public void testInvalidRidException() throws JsonProcessingException, com.fasterxml.jackson.core.JsonProcessingException { + + + String response = objectMapper.writeValueAsString(resp); + + ActiveMQBytesMessage amq = new ActiveMQBytesMessage(); + ByteSequence byteSeq = new ByteSequence(); + byteSeq.setData(response.getBytes()); + amq.setContent(byteSeq); + + resp.setRequestId("2344"); + + boolean result = verificationService.updatePacketStatus(resp, stageName, queue); + } + + @Test + public void testNoRecordAssignedException() throws JsonProcessingException, com.fasterxml.jackson.core.JsonProcessingException { + + + String response = objectMapper.writeValueAsString(resp); + + ActiveMQBytesMessage amq = new ActiveMQBytesMessage(); + ByteSequence byteSeq = new ByteSequence(); + byteSeq.setData(response.getBytes()); + amq.setContent(byteSeq); + + boolean result = verificationService.updatePacketStatus(resp, stageName, queue); + + assertFalse(result); + } + + @Test + @Ignore + public void testUpdateStatusSuccess() throws com.fasterxml.jackson.core.JsonProcessingException { + + Mockito.when(basePacketRepository.getAssignedVerificationRecord(anyString(), anyString())).thenReturn(entities); + + String response = objectMapper.writeValueAsString(resp); + + ActiveMQBytesMessage amq = new ActiveMQBytesMessage(); + ByteSequence byteSeq = new ByteSequence(); + byteSeq.setData(response.getBytes()); + amq.setContent(byteSeq); + + boolean result = verificationService.updatePacketStatus(resp, stageName, queue); + + assertTrue(result); + } + + @Test + public void testUpdateStatusResend() throws com.fasterxml.jackson.core.JsonProcessingException { + + Mockito.when(basePacketRepository.getAssignedVerificationRecord(anyString(), anyString())).thenReturn(entities); + + String response = objectMapper.writeValueAsString(resp); + + ActiveMQBytesMessage amq = new ActiveMQBytesMessage(); + ByteSequence byteSeq = new ByteSequence(); + byteSeq.setData(response.getBytes()); + amq.setContent(byteSeq); + + // for resend + resp.setReturnValue(2); + + boolean result = verificationService.updatePacketStatus(resp, stageName, queue); + + assertFalse(result); + } + + + @Test + @Ignore + public void testUpdateStatusRejected() throws JsonProcessingException, com.fasterxml.jackson.core.JsonProcessingException { + + Mockito.when(basePacketRepository.getAssignedVerificationRecord(anyString(), anyString())).thenReturn(entities); + + String response = objectMapper.writeValueAsString(resp); + + ActiveMQBytesMessage amq = new ActiveMQBytesMessage(); + ByteSequence byteSeq = new ByteSequence(); + byteSeq.setData(response.getBytes()); + amq.setContent(byteSeq); + + // for rejected + resp.setReturnValue(3); + + boolean result = verificationService.updatePacketStatus(resp, stageName, queue); + + 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 2932fe84bff..cdaf63b9e3c 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 @@ -6,10 +6,10 @@ import io.mosip.kernel.core.logger.spi.Logger; import io.mosip.kernel.core.util.DateUtils; import io.mosip.registration.processor.core.abstractverticle.*; -import io.mosip.registration.processor.core.code.*; 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.*; import io.mosip.registration.processor.core.common.rest.dto.ErrorDTO; import io.mosip.registration.processor.core.constant.*; import io.mosip.registration.processor.core.exception.ApisResourceAccessException; 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-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/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/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-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/utils/RestApiClient.java b/registration-processor/registration-processor-rest-client/src/main/java/io/mosip/registration/processor/rest/client/utils/RestApiClient.java index 3565023f627..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; 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; + } + + }; + } +}