From 81e10c8ab0b11e9ba27b53b1d1c55ccc57481814 Mon Sep 17 00:00:00 2001 From: Monobikash Das <43202165+MonobikashDas@users.noreply.github.com> Date: Fri, 11 Mar 2022 19:09:32 +0530 Subject: [PATCH 001/133] MOSIP-18793 : objectmapper afterburner usage (#1465) --- .../abis/handler/stage/AbisHandlerStage.java | 6 ++++-- .../handler/stage/test/AbisHandlerStageTest.java | 9 +++++---- .../impl/ManualAdjudicationServiceImpl.java | 2 -- .../uingenerator/stage/UinGeneratorStage.java | 7 +++++-- .../stages/uigenerator/UinGeneratorStageTest.java | 8 ++++---- .../service/impl/VerificationServiceImpl.java | 2 -- .../service/VerificationServiceTest.java | 4 ++++ .../api/controller/RegistrationSyncController.java | 5 +++-- .../message/sender/stage/MessageSenderStage.java | 8 +++++--- .../stages/cmdvalidator/CenterValidator.java | 3 ++- .../stages/cmdvalidator/DeviceValidator.java | 3 ++- .../stages/cmdvalidator/MachineValidator.java | 3 ++- .../cmdvalidator/CenterValidatorTest.java | 5 +++++ .../cmdvalidator/DeviceValidatorTests.java | 5 +++++ .../cmdvalidator/MachineValidatorTest.java | 5 +++++ .../stages/utils/NotificationUtility.java | 1 - .../processor/packet/storage/utils/AuthUtil.java | 5 +++-- .../impl/MessageNotificationServiceImpl.java | 3 +-- .../MessageNotificationServiceImplTest.java | 14 ++++---------- .../service/impl/NotificationServiceImpl.java | 4 +++- .../processor/status/encryptor/Encryptor.java | 6 ++++-- .../processor/status/encryptor/EncryptorTest.java | 5 +++++ 22 files changed, 71 insertions(+), 42 deletions(-) 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 8654f1b3c16..d8ce642334a 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 @@ -184,6 +184,9 @@ public class AbisHandlerStage extends MosipVerticleAPIManager { @Autowired private Utilities utility; + @Autowired + private ObjectMapper mapper; + /** The mosip event bus. */ MosipEventBus mosipEventBus = null; @@ -645,7 +648,7 @@ private void validateBiometricRecord(BiometricRecord biometricRecord, List> metaInfoExceptionBiometrics = metaInfoMap != null && metaInfoMap.containsKey("exceptionBiometrics") - ? new ObjectMapper().readValue(metaInfoMap.get("exceptionBiometrics"), + ? mapper.readValue(metaInfoMap.get("exceptionBiometrics"), new TypeReference>>() { }) : null; @@ -721,7 +724,6 @@ public Map> createTypeSubtypeMapping() throws ApisResourceA .get(PolicyConstant.POLICIES); List attributes = (List) policies.get(PolicyConstant.SHAREABLE_ATTRIBUTES); datasharePolicies = (LinkedHashMap) policies.get(PolicyConstant.DATASHARE_POLICIES); - ObjectMapper mapper = new ObjectMapper(); ShareableAttributes shareableAttributes = mapper.readValue(mapper.writeValueAsString(attributes.get(0)), ShareableAttributes.class); for (Source source : shareableAttributes.getSource()) { diff --git a/registration-processor/core-processor/registration-processor-abis-handler-stage/src/test/java/io/mosip/registration/processor/abis/handler/stage/test/AbisHandlerStageTest.java b/registration-processor/core-processor/registration-processor-abis-handler-stage/src/test/java/io/mosip/registration/processor/abis/handler/stage/test/AbisHandlerStageTest.java index ea6ff60d64f..687439a0632 100644 --- a/registration-processor/core-processor/registration-processor-abis-handler-stage/src/test/java/io/mosip/registration/processor/abis/handler/stage/test/AbisHandlerStageTest.java +++ b/registration-processor/core-processor/registration-processor-abis-handler-stage/src/test/java/io/mosip/registration/processor/abis/handler/stage/test/AbisHandlerStageTest.java @@ -20,14 +20,12 @@ import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; -import org.mockito.ArgumentMatchers; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Mockito; +import org.mockito.*; 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.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; import org.springframework.http.MediaType; import org.springframework.test.util.ReflectionTestUtils; @@ -105,6 +103,9 @@ public class AbisHandlerStageTest { @Mock private Utilities utility; + @Spy + private ObjectMapper mapper = new ObjectMapper(); + @Mock private PriorityBasedPacketManagerService packetManagerService; 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 4fbe28e8a27..eefac41ad96 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 @@ -557,7 +557,6 @@ public String getFilename() { private Map getPolicyMap(LinkedHashMap policies) throws DataShareException, IOException, ApisResourceAccessException { Map policyMap = new HashMap<>(); List attributes = (List) policies.get(ManualAdjudicationConstants.SHAREABLE_ATTRIBUTES); - ObjectMapper mapper = new ObjectMapper(); for (LinkedHashMap map : attributes) { ShareableAttributes shareableAttributes = mapper.readValue(mapper.writeValueAsString(map), ShareableAttributes.class); @@ -633,7 +632,6 @@ private LinkedHashMap getPolicy() throws DataShareException, Api public List getModalities(LinkedHashMap policy) throws IOException{ Map> typeAndSubTypeMap = new HashMap<>(); List attributes = (List) policy.get(ManualAdjudicationConstants.SHAREABLE_ATTRIBUTES); - ObjectMapper mapper = new ObjectMapper(); for (LinkedHashMap map : attributes) { ShareableAttributes shareableAttributes = mapper.readValue(mapper.writeValueAsString(map), ShareableAttributes.class); diff --git a/registration-processor/core-processor/registration-processor-uin-generator-stage/src/main/java/io/mosip/registration/processor/stages/uingenerator/stage/UinGeneratorStage.java b/registration-processor/core-processor/registration-processor-uin-generator-stage/src/main/java/io/mosip/registration/processor/stages/uingenerator/stage/UinGeneratorStage.java index 04771c4e785..88503906da1 100644 --- a/registration-processor/core-processor/registration-processor-uin-generator-stage/src/main/java/io/mosip/registration/processor/stages/uingenerator/stage/UinGeneratorStage.java +++ b/registration-processor/core-processor/registration-processor-uin-generator-stage/src/main/java/io/mosip/registration/processor/stages/uingenerator/stage/UinGeneratorStage.java @@ -198,6 +198,9 @@ public class UinGeneratorStage extends MosipVerticleAPIManager { @Autowired private IdSchemaUtil idSchemaUtil; + @Autowired + private ObjectMapper objectMapper; + private TrimExceptionMessage trimExceptionMessage = new TrimExceptionMessage(); /* @@ -448,7 +451,7 @@ private void loadDemographicIdentity(Map fieldMap, JSONObject de if (value != null) { Object json = new JSONTokener(value).nextValue(); if (json instanceof org.json.JSONObject) { - HashMap hashMap = new ObjectMapper().readValue(value, HashMap.class); + HashMap hashMap = objectMapper.readValue(value, HashMap.class); demographicIdentity.putIfAbsent(e.getKey(), hashMap); } else if (json instanceof JSONArray) { @@ -456,7 +459,7 @@ else if (json instanceof JSONArray) { JSONArray jsonArray = new JSONArray(value); for (int i = 0; i < jsonArray.length(); i++) { Object obj = jsonArray.get(i); - HashMap hashMap = new ObjectMapper().readValue(obj.toString(), HashMap.class); + HashMap hashMap = objectMapper.readValue(obj.toString(), HashMap.class); jsonList.add(hashMap); } demographicIdentity.putIfAbsent(e.getKey(), jsonList); 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 76c5a0fbfd8..52c7df763dc 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 @@ -30,10 +30,7 @@ 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.MockitoAnnotations; +import org.mockito.*; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; @@ -230,6 +227,9 @@ public Integer getPort() { @Mock private IdSchemaUtil idSchemaUtil; + @Spy + private ObjectMapper mapper = new ObjectMapper(); + JSONObject documentObj; JSONObject identityObj; 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 b3c51225c79..131518a5e1c 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 @@ -563,7 +563,6 @@ public String getFilename() { private Map getPolicyMap(LinkedHashMap policies) throws IOException { Map policyMap = new HashMap<>(); List attributes = (List) policies.get(VerificationConstants.SHAREABLE_ATTRIBUTES); - ObjectMapper mapper = new ObjectMapper(); for (LinkedHashMap map : attributes) { ShareableAttributes shareableAttributes = mapper.readValue(mapper.writeValueAsString(map), ShareableAttributes.class); @@ -596,7 +595,6 @@ private LinkedHashMap getPolicy() throws DataShareException, Api public List getModalities(LinkedHashMap policy) throws IOException { Map> typeAndSubTypeMap = new HashMap<>(); List attributes = (List) policy.get(VerificationConstants.SHAREABLE_ATTRIBUTES); - ObjectMapper mapper = new ObjectMapper(); for (LinkedHashMap map : attributes) { ShareableAttributes shareableAttributes = mapper.readValue(mapper.writeValueAsString(map), ShareableAttributes.class); 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 c2b39d3790b..0c1886ca76a 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 @@ -53,6 +53,7 @@ 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; @@ -84,6 +85,9 @@ public class VerificationServiceTest { @Mock UserDto dto; + @Spy + private ObjectMapper mapper = new ObjectMapper(); + @Mock private VerificationStage manualAdjudicationStage; diff --git a/registration-processor/init/registration-processor-registration-status-service/src/main/java/io/mosip/registration/processor/status/api/controller/RegistrationSyncController.java b/registration-processor/init/registration-processor-registration-status-service/src/main/java/io/mosip/registration/processor/status/api/controller/RegistrationSyncController.java index db15901a1d9..3c28e0f589d 100644 --- a/registration-processor/init/registration-processor-registration-status-service/src/main/java/io/mosip/registration/processor/status/api/controller/RegistrationSyncController.java +++ b/registration-processor/init/registration-processor-registration-status-service/src/main/java/io/mosip/registration/processor/status/api/controller/RegistrationSyncController.java @@ -60,6 +60,9 @@ public class RegistrationSyncController { @Autowired private Environment env; + @Autowired + private ObjectMapper objectMapper; + @Value("${registration.processor.signature.isEnabled}") @@ -107,7 +110,6 @@ public ResponseEntity syncRegistrationController( } if (isEnabled) { RegSyncResponseDTO responseDto = buildRegistrationSyncResponse(syncResponseList); - ObjectMapper objectMapper = new ObjectMapper(); HttpHeaders headers = new HttpHeaders(); headers.add(RESPONSE_SIGNATURE, digitalSignatureUtility.getDigitalSignature(objectMapper.writeValueAsString(responseDto))); @@ -155,7 +157,6 @@ public ResponseEntity syncRegistrationController2( } if (isEnabled) { RegSyncResponseDTO responseDto = buildRegistrationSyncResponse(syncResponseList); - ObjectMapper objectMapper = new ObjectMapper(); HttpHeaders headers = new HttpHeaders(); headers.add(RESPONSE_SIGNATURE, digitalSignatureUtility.getDigitalSignature(objectMapper.writeValueAsString(responseDto))); diff --git a/registration-processor/post-processor/registration-processor-message-sender-stage/src/main/java/io/mosip/registration/processor/message/sender/stage/MessageSenderStage.java b/registration-processor/post-processor/registration-processor-message-sender-stage/src/main/java/io/mosip/registration/processor/message/sender/stage/MessageSenderStage.java index f6830b3e0cd..9d64d932737 100644 --- a/registration-processor/post-processor/registration-processor-message-sender-stage/src/main/java/io/mosip/registration/processor/message/sender/stage/MessageSenderStage.java +++ b/registration-processor/post-processor/registration-processor-message-sender-stage/src/main/java/io/mosip/registration/processor/message/sender/stage/MessageSenderStage.java @@ -151,10 +151,13 @@ public class MessageSenderStage extends MosipVerticleAPIManager { /** Mosip router for APIs */ @Autowired - MosipRouter router; + private MosipRouter router; @Autowired - Environment env; + private Environment env; + + @Autowired + private ObjectMapper mapper; /** worker pool size. */ @Value("${worker.pool.size}") @@ -617,7 +620,6 @@ private boolean isTemplateAvailable(MessageSenderDto messageSenderDto) List pathSegments = new ArrayList<>(); ResponseWrapper responseWrapper; TemplateResponseDto templateResponseDto = null; - ObjectMapper mapper = new ObjectMapper(); responseWrapper = (ResponseWrapper) restClientService.getApi(ApiName.TEMPLATES, pathSegments, "", "", ResponseWrapper.class); diff --git a/registration-processor/pre-processor/registration-processor-cmd-validator-stage/src/main/java/io/mosip/registration/processor/stages/cmdvalidator/CenterValidator.java b/registration-processor/pre-processor/registration-processor-cmd-validator-stage/src/main/java/io/mosip/registration/processor/stages/cmdvalidator/CenterValidator.java index 9110e50988d..1c4505aec5d 100644 --- a/registration-processor/pre-processor/registration-processor-cmd-validator-stage/src/main/java/io/mosip/registration/processor/stages/cmdvalidator/CenterValidator.java +++ b/registration-processor/pre-processor/registration-processor-cmd-validator-stage/src/main/java/io/mosip/registration/processor/stages/cmdvalidator/CenterValidator.java @@ -33,7 +33,8 @@ public class CenterValidator { private static final String VALID = "Valid"; - ObjectMapper mapper = new ObjectMapper(); + @Autowired + ObjectMapper mapper; @Value("${mosip.regproc.cmd-validator.working-hour-validation-required}") private Boolean isWorkingHourValidationRequired; diff --git a/registration-processor/pre-processor/registration-processor-cmd-validator-stage/src/main/java/io/mosip/registration/processor/stages/cmdvalidator/DeviceValidator.java b/registration-processor/pre-processor/registration-processor-cmd-validator-stage/src/main/java/io/mosip/registration/processor/stages/cmdvalidator/DeviceValidator.java index 24a8e56a7bc..bfbd9f734ab 100644 --- a/registration-processor/pre-processor/registration-processor-cmd-validator-stage/src/main/java/io/mosip/registration/processor/stages/cmdvalidator/DeviceValidator.java +++ b/registration-processor/pre-processor/registration-processor-cmd-validator-stage/src/main/java/io/mosip/registration/processor/stages/cmdvalidator/DeviceValidator.java @@ -68,7 +68,8 @@ public class DeviceValidator { private static final String VALID = "Valid"; - ObjectMapper mapper = new ObjectMapper(); + @Autowired + ObjectMapper mapper; @Autowired private RegistrationProcessorRestClientService registrationProcessorRestService; diff --git a/registration-processor/pre-processor/registration-processor-cmd-validator-stage/src/main/java/io/mosip/registration/processor/stages/cmdvalidator/MachineValidator.java b/registration-processor/pre-processor/registration-processor-cmd-validator-stage/src/main/java/io/mosip/registration/processor/stages/cmdvalidator/MachineValidator.java index 09736e67854..4ecc4e92ff3 100644 --- a/registration-processor/pre-processor/registration-processor-cmd-validator-stage/src/main/java/io/mosip/registration/processor/stages/cmdvalidator/MachineValidator.java +++ b/registration-processor/pre-processor/registration-processor-cmd-validator-stage/src/main/java/io/mosip/registration/processor/stages/cmdvalidator/MachineValidator.java @@ -29,7 +29,8 @@ public class MachineValidator { private static Logger regProcLogger = RegProcessorLogger.getLogger(MachineValidator.class); - ObjectMapper mapper = new ObjectMapper(); + @Autowired + ObjectMapper mapper; @Autowired private RegistrationProcessorRestClientService registrationProcessorRestService; diff --git a/registration-processor/pre-processor/registration-processor-cmd-validator-stage/src/test/java/io/mosip/registration/processor/cmdvalidator/CenterValidatorTest.java b/registration-processor/pre-processor/registration-processor-cmd-validator-stage/src/test/java/io/mosip/registration/processor/cmdvalidator/CenterValidatorTest.java index e1f1206efe8..4abab54711b 100644 --- a/registration-processor/pre-processor/registration-processor-cmd-validator-stage/src/test/java/io/mosip/registration/processor/cmdvalidator/CenterValidatorTest.java +++ b/registration-processor/pre-processor/registration-processor-cmd-validator-stage/src/test/java/io/mosip/registration/processor/cmdvalidator/CenterValidatorTest.java @@ -6,12 +6,14 @@ import java.io.IOException; import java.util.List; +import com.fasterxml.jackson.databind.ObjectMapper; 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.Spy; import org.mockito.junit.MockitoJUnitRunner; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.util.ReflectionTestUtils; @@ -34,6 +36,9 @@ public class CenterValidatorTest { @InjectMocks private CenterValidator centerValidator; + @Spy + private ObjectMapper mapper = new ObjectMapper(); + @Mock private RegistrationProcessorRestClientService registrationProcessorRestService; RegOsiDto regOsi=new RegOsiDto(); diff --git a/registration-processor/pre-processor/registration-processor-cmd-validator-stage/src/test/java/io/mosip/registration/processor/cmdvalidator/DeviceValidatorTests.java b/registration-processor/pre-processor/registration-processor-cmd-validator-stage/src/test/java/io/mosip/registration/processor/cmdvalidator/DeviceValidatorTests.java index 6d50b14afa8..df3525a7da1 100644 --- a/registration-processor/pre-processor/registration-processor-cmd-validator-stage/src/test/java/io/mosip/registration/processor/cmdvalidator/DeviceValidatorTests.java +++ b/registration-processor/pre-processor/registration-processor-cmd-validator-stage/src/test/java/io/mosip/registration/processor/cmdvalidator/DeviceValidatorTests.java @@ -10,6 +10,7 @@ import java.util.HashMap; import java.util.Map; +import com.fasterxml.jackson.databind.ObjectMapper; import io.mosip.kernel.core.util.DateUtils; import io.mosip.registration.processor.core.packet.dto.AdditionalInfoRequestDto; import io.mosip.registration.processor.packet.storage.utils.OSIUtils; @@ -24,6 +25,7 @@ import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; +import org.mockito.Spy; import org.mockito.junit.MockitoJUnitRunner; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.core.env.Environment; @@ -60,6 +62,9 @@ public class DeviceValidatorTests { @Mock private OSIUtils osiUtils; + @Spy + private ObjectMapper mapper = new ObjectMapper(); + @Mock private AdditionalInfoRequestService additionalInfoRequestService; diff --git a/registration-processor/pre-processor/registration-processor-cmd-validator-stage/src/test/java/io/mosip/registration/processor/cmdvalidator/MachineValidatorTest.java b/registration-processor/pre-processor/registration-processor-cmd-validator-stage/src/test/java/io/mosip/registration/processor/cmdvalidator/MachineValidatorTest.java index 9ee20233d44..9e1610189c5 100644 --- a/registration-processor/pre-processor/registration-processor-cmd-validator-stage/src/test/java/io/mosip/registration/processor/cmdvalidator/MachineValidatorTest.java +++ b/registration-processor/pre-processor/registration-processor-cmd-validator-stage/src/test/java/io/mosip/registration/processor/cmdvalidator/MachineValidatorTest.java @@ -6,11 +6,13 @@ import java.io.IOException; import java.util.List; +import com.fasterxml.jackson.databind.ObjectMapper; 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.mockito.junit.MockitoJUnitRunner; import org.springframework.boot.test.context.SpringBootTest; @@ -30,6 +32,9 @@ public class MachineValidatorTest { @InjectMocks private MachineValidator machineValidator; + @Spy + private ObjectMapper mapper = new ObjectMapper(); + @Mock private RegistrationProcessorRestClientService registrationProcessorRestService; diff --git a/registration-processor/pre-processor/registration-processor-packet-validator-stage/src/main/java/io/mosip/registration/processor/stages/utils/NotificationUtility.java b/registration-processor/pre-processor/registration-processor-packet-validator-stage/src/main/java/io/mosip/registration/processor/stages/utils/NotificationUtility.java index 51cf62f00d2..2db51d91911 100644 --- a/registration-processor/pre-processor/registration-processor-packet-validator-stage/src/main/java/io/mosip/registration/processor/stages/utils/NotificationUtility.java +++ b/registration-processor/pre-processor/registration-processor-packet-validator-stage/src/main/java/io/mosip/registration/processor/stages/utils/NotificationUtility.java @@ -220,7 +220,6 @@ private List getPreferredLanguages(InternalRegistrationStatusDto registr for( String idValue:idValues) { if(idValue!=null&& !idValue.isBlank() ) { if(isJSONArrayValid(idValue)) { - ObjectMapper mapper=new ObjectMapper(); org.json.simple.JSONArray array=mapper.readValue(idValue, org.json.simple.JSONArray.class); for(Object obj:array) { org.json.simple.JSONObject json= new org.json.simple.JSONObject((Map) obj); diff --git a/registration-processor/registration-processor-info-storage-service/src/main/java/io/mosip/registration/processor/packet/storage/utils/AuthUtil.java b/registration-processor/registration-processor-info-storage-service/src/main/java/io/mosip/registration/processor/packet/storage/utils/AuthUtil.java index 1925ba4edcd..b5f6c1d1154 100644 --- a/registration-processor/registration-processor-info-storage-service/src/main/java/io/mosip/registration/processor/packet/storage/utils/AuthUtil.java +++ b/registration-processor/registration-processor-info-storage-service/src/main/java/io/mosip/registration/processor/packet/storage/utils/AuthUtil.java @@ -85,6 +85,9 @@ public class AuthUtil { @Autowired private KeyGenerator keyGenerator; + @Autowired + private ObjectMapper mapper; + /** The encryptor. */ @Autowired private CryptoCoreSpec encryptor; @@ -164,7 +167,6 @@ public AuthResponseDTO authByIdAuthentication(String individualId, String indivi RequestDTO request = new RequestDTO(); request.setBiometrics(biometrics); request.setTimestamp(DateUtils.formatToISOString(localdatetime)); - ObjectMapper mapper = new ObjectMapper(); String identityBlock = mapper.writeValueAsString(request); final SecretKey secretKey = keyGenerator.getSymmetricKey(); @@ -424,7 +426,6 @@ private X509Certificate getCertificate(String refId) // encrypt AES Session Key using RSA public key ResponseWrapper responseWrapper; CertificateResponseDto certificateResponseDto; - ObjectMapper mapper = new ObjectMapper(); responseWrapper = (ResponseWrapper) registrationProcessorRestClientService.getApi(ApiName.IDAUTHCERTIFICATE, null, "applicationId,referenceId", IDA_APP_ID + ',' + refId, ResponseWrapper.class); certificateResponseDto = mapper.readValue(mapper.writeValueAsString(responseWrapper.getResponse()), 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 462ee5e7592..e2f7a6de29c 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 @@ -340,7 +340,6 @@ private List getPreferredLanguages(String id, String process) throws Api for( String idValue:idValues) { if(idValue!=null&& !idValue.isBlank() ) { if(isJSONArrayValid(idValue)) { - ObjectMapper mapper=new ObjectMapper(); JSONArray array=mapper.readValue(idValue, JSONArray.class); for(Object obj:array) { JSONObject json= new JSONObject( (Map) obj); @@ -625,7 +624,7 @@ private Map setAttributesFromIdJson(String id, String process, M if (StringUtils.isNotEmpty(value)) { Object json = new JSONTokener(value).nextValue(); if (json instanceof org.json.JSONObject) { - HashMap hashMap = new ObjectMapper().readValue(value, HashMap.class); + HashMap hashMap = mapper.readValue(value, HashMap.class); attribute.putIfAbsent(e.getKey().toString(), hashMap.get(VALUE)); } else if (json instanceof org.json.JSONArray) { diff --git a/registration-processor/registration-processor-message-sender-impl/src/test/java/io/mosip/registration/processor/message/sender/test/service/MessageNotificationServiceImplTest.java b/registration-processor/registration-processor-message-sender-impl/src/test/java/io/mosip/registration/processor/message/sender/test/service/MessageNotificationServiceImplTest.java index 8fe0a8f724e..4f242aa7e98 100644 --- a/registration-processor/registration-processor-message-sender-impl/src/test/java/io/mosip/registration/processor/message/sender/test/service/MessageNotificationServiceImplTest.java +++ b/registration-processor/registration-processor-message-sender-impl/src/test/java/io/mosip/registration/processor/message/sender/test/service/MessageNotificationServiceImplTest.java @@ -30,6 +30,7 @@ import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; +import org.mockito.Spy; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; @@ -91,6 +92,9 @@ public class MessageNotificationServiceImplTest { @Mock private IdRepoService idRepoService; + @Spy + private ObjectMapper mapper = new ObjectMapper(); + /** The template generator. */ @Mock private TemplateGenerator templateGenerator; @@ -121,9 +125,6 @@ public class MessageNotificationServiceImplTest { @Mock private Environment env; - @Mock - private ObjectMapper mapper; - /** The attributes. */ private Map attributes = new HashMap<>(); @@ -274,9 +275,6 @@ public void testSendSmsNotificationSuccess() throws ApisResourceAccessException, Mockito.when(restClientService.postApi(any(), any(), anyString(), any(), any())) .thenReturn(wrapper); - Mockito.when(mapper.writeValueAsString(any())).thenReturn(smsResponseDto.toString()); - Mockito.when(mapper.readValue(anyString(), any(Class.class))).thenReturn(smsResponseDto); - SmsResponseDto resultResponse = messageNotificationServiceImpl.sendSmsNotification("RPR_UIN_GEN_SMS", "12345", "NEW",IdType.RID, attributes, RegistrationType.NEW.name()); assertEquals("Test for SMS Notification Success", "Success", resultResponse.getMessage()); @@ -301,8 +299,6 @@ public void testUINTypeMessage() throws ApisResourceAccessException, IOException // Mockito.when(abisHandlerUtil.getUinFromIDRepo(any())).thenReturn(1234567); Mockito.when(restClientService.postApi(any(), any(), any(), any(), any())) .thenReturn(wrapper); - Mockito.when(mapper.writeValueAsString(any())).thenReturn(smsResponseDto.toString()); - Mockito.when(mapper.readValue(anyString(), any(Class.class))).thenReturn(smsResponseDto); SmsResponseDto resultResponse = messageNotificationServiceImpl.sendSmsNotification("RPR_UIN_GEN_SMS", "27847657360002520181208094056", "NEW", IdType.UIN, attributes, RegistrationType.ACTIVATED.name()); @@ -325,8 +321,6 @@ public void testSendEmailNotificationSuccess() throws Exception { wrapper.setResponse(responseDto); Mockito.when(restApiClient.postApi(any(), any(), any(), any())).thenReturn(wrapper); - Mockito.when(mapper.writeValueAsString(any())).thenReturn(responseDto.toString()); - Mockito.when(mapper.readValue(anyString(), any(Class.class))).thenReturn(responseDto); ResponseDto resultResponse = messageNotificationServiceImpl.sendEmailNotification("RPR_UIN_GEN_EMAIL", "12345", "NEW", IdType.RID, attributes, mailCc, subject, null, RegistrationType.NEW.name()); diff --git a/registration-processor/registration-processor-notification-service/src/main/java/io/mosip/registration/processor/notification/service/impl/NotificationServiceImpl.java b/registration-processor/registration-processor-notification-service/src/main/java/io/mosip/registration/processor/notification/service/impl/NotificationServiceImpl.java index 60be2a032b7..adab4dc1097 100644 --- a/registration-processor/registration-processor-notification-service/src/main/java/io/mosip/registration/processor/notification/service/impl/NotificationServiceImpl.java +++ b/registration-processor/registration-processor-notification-service/src/main/java/io/mosip/registration/processor/notification/service/impl/NotificationServiceImpl.java @@ -99,6 +99,9 @@ public class NotificationServiceImpl implements NotificationService { @Autowired private AuditLogRequestBuilder auditLogRequestBuilder; + @Autowired + private ObjectMapper mapper; + /** The notification emails. */ @Value("${registration.processor.notification.emails}") private String notificationEmails; @@ -519,7 +522,6 @@ private boolean isTemplateAvailable(MessageSenderDto messageSenderDto) List pathSegments = new ArrayList<>(); ResponseWrapper responseWrapper; TemplateResponseDto templateResponseDto = null; - ObjectMapper mapper = new ObjectMapper(); responseWrapper = (ResponseWrapper) restClientService.getApi(ApiName.TEMPLATES, pathSegments, "", "", ResponseWrapper.class); diff --git a/registration-processor/registration-processor-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/encryptor/Encryptor.java b/registration-processor/registration-processor-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/encryptor/Encryptor.java index 758830423e8..61227611e5e 100644 --- a/registration-processor/registration-processor-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/encryptor/Encryptor.java +++ b/registration-processor/registration-processor-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/encryptor/Encryptor.java @@ -61,6 +61,9 @@ public class Encryptor { @Autowired private Environment env; + @Autowired + private ObjectMapper mapper; + private static final String DECRYPT_SERVICE_ID = "mosip.registration.processor.crypto.decrypt.id"; private static final String REG_PROC_APPLICATION_VERSION = "mosip.registration.processor.application.version"; private static final String DATETIME_PATTERN = "mosip.registration.processor.datetime.pattern"; @@ -78,8 +81,7 @@ public byte[] encrypt(String syncMetaInfo, String referenceId, String timeStamp) regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), "", "Encryptor::encrypt()::entry"); try { - ObjectMapper mapper = new ObjectMapper(); - + String syncInfo = CryptoUtil.encodeToURLSafeBase64(syncMetaInfo.getBytes()); CryptomanagerRequestDto cryptomanagerRequestDto = new CryptomanagerRequestDto(); diff --git a/registration-processor/registration-processor-registration-status-service-impl/src/test/java/io/mosip/registration/processor/status/encryptor/EncryptorTest.java b/registration-processor/registration-processor-registration-status-service-impl/src/test/java/io/mosip/registration/processor/status/encryptor/EncryptorTest.java index eada65d72e1..6aac0a48517 100644 --- a/registration-processor/registration-processor-registration-status-service-impl/src/test/java/io/mosip/registration/processor/status/encryptor/EncryptorTest.java +++ b/registration-processor/registration-processor-registration-status-service-impl/src/test/java/io/mosip/registration/processor/status/encryptor/EncryptorTest.java @@ -8,6 +8,7 @@ import java.io.FileNotFoundException; import java.io.IOException; +import com.fasterxml.jackson.databind.ObjectMapper; import io.mosip.kernel.core.util.CryptoUtil; import io.mosip.registration.processor.status.dto.DecryptResponseDto; import org.junit.Before; @@ -16,6 +17,7 @@ import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; +import org.mockito.Spy; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; @@ -40,6 +42,9 @@ public class EncryptorTest { @InjectMocks private Encryptor encryptor; + @Spy + private ObjectMapper mapper = new ObjectMapper(); + @Mock private RegistrationProcessorRestClientService restClientService; From 27eb398e4b1492f5026b349f12403a7457d63fa2 Mon Sep 17 00:00:00 2001 From: Monobikash Das <43202165+MonobikashDas@users.noreply.github.com> Date: Tue, 29 Mar 2022 11:18:17 +0530 Subject: [PATCH 002/133] MOSIP-19244 : added self token rest template (#1485) * MOSIP-18793 : objectmapper afterburner usage (#1465) (#1466) * MOSIP-19244 : using selfTokenRestTemplate (#1468) * MOSIP-19244 : using selfTokenRestTemplate (#1452) * MOSIP-19244 : using selfTokenRestTemplate * MOSIP-20472 : added vid in template * MOSIP-19244 : using selfTokenRestTemplate * MOSIP-19244 : updated pom versions * MOSIP-19244 : using selfTokenRestTemplate (#1470) * MOSIP-19244 : using selfTokenRestTemplate (#1471) * Added logger (#1474) * MOSIP-18661_disabled health check (#1473) * MOSIP-17897 * merge * merge * MOSIP-20157_added fix for language issue * Update MessageNotificationServiceImpl.java * Update NotificationUtility.java * Update MessageNotificationServiceImpl.java * Merge branch 'develop' of https://github.com/mosip/registration.git into develop * Update MessageNotificationServiceImpl.java * Update NotificationUtility.java * Update regprc-transaction_type.csv * MOSIP-18661 * MOSIP-18661 * MOSIP-18861 * Update MessageNotificationServiceImpl.java * Update NotificationUtility.java Co-authored-by: M1030448 Co-authored-by: Jyoti Prakash Nayak Co-authored-by: M1030448 * MOSIP-19244 : passing iam_adapter_url in dockerfile (#1483) * MOSIP-19244 : adding zip format (#1484) * MOSIP-19244 : passing iam_adapter_url in dockerfile * MOSIP-19244 : adding zip format Co-authored-by: JyotiPrakashNayak Co-authored-by: M1030448 Co-authored-by: Jyoti Prakash Nayak Co-authored-by: M1030448 --- .../dml/regprc-transaction_type.csv | 1 + .../abis/handler/stage/AbisHandlerStage.java | 3 +- .../middleware/stage/AbisMiddleWareStage.java | 3 +- .../biodedupe/stage/BioDedupeStage.java | 3 +- .../stage/BiometricAuthenticationStage.java | 3 +- .../stage/BiometricExtractionStage.java | 3 +- .../stages/demodedupe/DemoDedupeStage.java | 3 +- .../finalization/stage/FinalizationStage.java | 3 +- .../stage/ManualAdjudicationStage.java | 3 +- .../uingenerator/stage/UinGeneratorStage.java | 3 +- .../verification/stage/VerificationStage.java | 3 +- .../receiver/stage/PacketReceiverStage.java | 3 +- .../api/RegistrationStatusApiApplication.java | 9 +- .../sender/stage/MessageSenderStage.java | 3 +- .../processor/print/stage/PrintingStage.java | 3 +- .../stages/app/CMDValidatorStage.java | 3 +- .../IntroducerValidatorStage.java | 3 +- .../OperatorValidatorStage.java | 3 +- .../PacketClassifierStage.java | 3 +- .../uploader/stage/PacketUploaderStage.java | 3 +- .../stages/config/ValidatorConfig.java | 10 +- .../validator/PacketValidatorStage.java | 3 +- .../stages/utils/RestTemplateInterceptor.java | 47 --------- .../stage/QualityClassifierStage.java | 3 +- .../stage/SecurezoneNotificationStage.java | 3 +- .../SupervisorValidatorStage.java | 3 +- .../Dockerfile | 9 +- .../pom.xml | 37 ++------ .../bridge/MosipCamelBridgeApplication.java | 6 +- .../processor/core/config/CoreConfigBean.java | 2 +- .../PropertyLoaderConfig.java | 95 +++++++++++++++++++ .../config/reader/ConfigPropertyReader.java | 29 ++++++ .../packet/storage/utils/AuthUtil.java | 13 +-- .../impl/InternalAuthDelegateServiceImpl.java | 9 +- .../InternalAuthDelegateServiceImplTest.java | 11 --- .../pom.xml | 4 - .../rest/client/utils/RestApiClient.java | 42 ++------ .../Dockerfile | 2 + .../Dockerfile | 2 + .../Dockerfile | 6 +- .../Dockerfile | 2 + .../Dockerfile | 2 + .../Dockerfile | 2 + .../Dockerfile | 6 +- .../Dockerfile | 9 +- .../pom.xml | 4 +- .../reprocessor/ReprocessorApplication.java | 8 +- .../config/ReprocessorConfigBeans.java | 10 +- .../constants/ReprocessorConstants.java | 2 +- .../verticle/ReprocessorVerticle.java | 6 +- .../verticle/ReprocessingSchedulerTest.java | 2 + 51 files changed, 264 insertions(+), 189 deletions(-) delete mode 100644 registration-processor/pre-processor/registration-processor-packet-validator-stage/src/main/java/io/mosip/registration/processor/stages/utils/RestTemplateInterceptor.java create mode 100644 registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/config/configserverloader/PropertyLoaderConfig.java create mode 100644 registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/config/reader/ConfigPropertyReader.java rename registration-processor/workflow-engine/registration-processor-reprocessor/src/main/java/io/mosip/registration/processor/{retry/verticle => reprocessor}/constants/ReprocessorConstants.java (96%) diff --git a/db_scripts/mosip_regprc/dml/regprc-transaction_type.csv b/db_scripts/mosip_regprc/dml/regprc-transaction_type.csv index 8a112bb387c..feed8a93a80 100644 --- a/db_scripts/mosip_regprc/dml/regprc-transaction_type.csv +++ b/db_scripts/mosip_regprc/dml/regprc-transaction_type.csv @@ -31,3 +31,4 @@ 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/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 d8ce642334a..08130f6b4d4 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 @@ -103,7 +103,8 @@ @RefreshScope @Service @Configuration -@ComponentScan(basePackages = { "io.mosip.registration.processor.abis.handler.config", +@ComponentScan(basePackages = { "${mosip.auth.adapter.impl.basepackage}", + "io.mosip.registration.processor.abis.handler.config", "io.mosip.registration.processor.status.config", "io.mosip.registration.processor.rest.client.config", "io.mosip.registration.processor.packet.storage.config", "io.mosip.registration.processor.core.config", "io.mosip.registration.processor.core.kernel.beans", "io.mosip.kernel.packetmanager.config" }) 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 58ef1a19387..d39d99a5bc7 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 @@ -84,7 +84,8 @@ @RefreshScope @Service @Configuration -@ComponentScan(basePackages = { "io.mosip.registration.processor.abis.handler.config", +@ComponentScan(basePackages = { "${mosip.auth.adapter.impl.basepackage}", + "io.mosip.registration.processor.abis.handler.config", "io.mosip.registration.processor.status.config", "io.mosip.registration.processor.rest.client.config", "io.mosip.registration.processor.packet.storage.config", diff --git a/registration-processor/core-processor/registration-processor-bio-dedupe-stage/src/main/java/io/mosip/registration/processor/biodedupe/stage/BioDedupeStage.java b/registration-processor/core-processor/registration-processor-bio-dedupe-stage/src/main/java/io/mosip/registration/processor/biodedupe/stage/BioDedupeStage.java index 3db4333dd4b..5e3a59593fd 100644 --- a/registration-processor/core-processor/registration-processor-bio-dedupe-stage/src/main/java/io/mosip/registration/processor/biodedupe/stage/BioDedupeStage.java +++ b/registration-processor/core-processor/registration-processor-bio-dedupe-stage/src/main/java/io/mosip/registration/processor/biodedupe/stage/BioDedupeStage.java @@ -25,7 +25,8 @@ @RefreshScope @Service @Configuration -@ComponentScan(basePackages = { "io.mosip.registration.processor.core.config", +@ComponentScan(basePackages = { "${mosip.auth.adapter.impl.basepackage}", + "io.mosip.registration.processor.core.config", "io.mosip.registration.processor.biodedupe.config", "io.mosip.registration.processor.status.config", "io.mosip.registration.processor.rest.client.config", "io.mosip.registration.processor.packet.storage.config", diff --git a/registration-processor/core-processor/registration-processor-biometric-authentication-stage/src/main/java/io/mosip/registration/processor/biometric/authentication/stage/BiometricAuthenticationStage.java b/registration-processor/core-processor/registration-processor-biometric-authentication-stage/src/main/java/io/mosip/registration/processor/biometric/authentication/stage/BiometricAuthenticationStage.java index d9064ec9a8e..96afa46c7c2 100644 --- a/registration-processor/core-processor/registration-processor-biometric-authentication-stage/src/main/java/io/mosip/registration/processor/biometric/authentication/stage/BiometricAuthenticationStage.java +++ b/registration-processor/core-processor/registration-processor-biometric-authentication-stage/src/main/java/io/mosip/registration/processor/biometric/authentication/stage/BiometricAuthenticationStage.java @@ -67,7 +67,8 @@ @RefreshScope @Service @Configuration -@ComponentScan(basePackages = { "io.mosip.registration.processor.biometric.authentication.config", +@ComponentScan(basePackages = { "${mosip.auth.adapter.impl.basepackage}", + "io.mosip.registration.processor.biometric.authentication.config", "io.mosip.registration.processor.status.config", "io.mosip.registration.processor.rest.client.config", "io.mosip.registration.processor.packet.storage.config", "io.mosip.registration.processor.core.config", "io.mosip.registration.processor.core.kernel.beans", diff --git a/registration-processor/core-processor/registration-processor-biometric-extraction-stage/src/main/java/io/mosip/registration/processor/stages/biometric/extraction/stage/BiometricExtractionStage.java b/registration-processor/core-processor/registration-processor-biometric-extraction-stage/src/main/java/io/mosip/registration/processor/stages/biometric/extraction/stage/BiometricExtractionStage.java index a06693157de..bd355ca1600 100644 --- a/registration-processor/core-processor/registration-processor-biometric-extraction-stage/src/main/java/io/mosip/registration/processor/stages/biometric/extraction/stage/BiometricExtractionStage.java +++ b/registration-processor/core-processor/registration-processor-biometric-extraction-stage/src/main/java/io/mosip/registration/processor/stages/biometric/extraction/stage/BiometricExtractionStage.java @@ -61,7 +61,8 @@ @RefreshScope @Service @Configuration -@ComponentScan(basePackages = { "io.mosip.registration.processor.core.config", +@ComponentScan(basePackages = { "${mosip.auth.adapter.impl.basepackage}", + "io.mosip.registration.processor.core.config", "io.mosip.registration.processor.stages.biometric.extraction.config", "io.mosip.registration.processor.status.config", "io.mosip.registration.processor.rest.client.config", "io.mosip.registration.processor.packet.storage.config", diff --git a/registration-processor/core-processor/registration-processor-demo-dedupe-stage/src/main/java/io/mosip/registration/processor/stages/demodedupe/DemoDedupeStage.java b/registration-processor/core-processor/registration-processor-demo-dedupe-stage/src/main/java/io/mosip/registration/processor/stages/demodedupe/DemoDedupeStage.java index 7e24726b45e..845a3c5724a 100644 --- a/registration-processor/core-processor/registration-processor-demo-dedupe-stage/src/main/java/io/mosip/registration/processor/stages/demodedupe/DemoDedupeStage.java +++ b/registration-processor/core-processor/registration-processor-demo-dedupe-stage/src/main/java/io/mosip/registration/processor/stages/demodedupe/DemoDedupeStage.java @@ -22,7 +22,8 @@ @RefreshScope @Service @Configuration -@ComponentScan(basePackages = { "io.mosip.registration.processor.core.config", +@ComponentScan(basePackages = { "${mosip.auth.adapter.impl.basepackage}", + "io.mosip.registration.processor.core.config", "io.mosip.registration.processor.stages.config", "io.mosip.registration.processor.demo.dedupe.config", "io.mosip.registration.processor.status.config", "io.mosip.registration.processor.packet.storage.config", diff --git a/registration-processor/core-processor/registration-processor-finalization-stage/src/main/java/io/mosip/registration/processor/stages/finalization/stage/FinalizationStage.java b/registration-processor/core-processor/registration-processor-finalization-stage/src/main/java/io/mosip/registration/processor/stages/finalization/stage/FinalizationStage.java index 88a7e2bd8c7..38c81750354 100644 --- a/registration-processor/core-processor/registration-processor-finalization-stage/src/main/java/io/mosip/registration/processor/stages/finalization/stage/FinalizationStage.java +++ b/registration-processor/core-processor/registration-processor-finalization-stage/src/main/java/io/mosip/registration/processor/stages/finalization/stage/FinalizationStage.java @@ -42,7 +42,8 @@ @RefreshScope @Service @Configuration -@ComponentScan(basePackages = { "io.mosip.registration.processor.core.config", +@ComponentScan(basePackages = { "${mosip.auth.adapter.impl.basepackage}", + "io.mosip.registration.processor.core.config", "io.mosip.registration.processor.stages.finalization.config", "io.mosip.registration.processor.status.config", "io.mosip.registration.processor.rest.client.config", "io.mosip.registration.processor.packet.storage.config", diff --git a/registration-processor/core-processor/registration-processor-manual-adjudication-stage/src/main/java/io/mosip/registration/processor/adjudication/stage/ManualAdjudicationStage.java b/registration-processor/core-processor/registration-processor-manual-adjudication-stage/src/main/java/io/mosip/registration/processor/adjudication/stage/ManualAdjudicationStage.java index a4de2ca4a31..95777d68463 100644 --- a/registration-processor/core-processor/registration-processor-manual-adjudication-stage/src/main/java/io/mosip/registration/processor/adjudication/stage/ManualAdjudicationStage.java +++ b/registration-processor/core-processor/registration-processor-manual-adjudication-stage/src/main/java/io/mosip/registration/processor/adjudication/stage/ManualAdjudicationStage.java @@ -48,7 +48,8 @@ @RefreshScope @Service @Configuration -@ComponentScan(basePackages = { "io.mosip.registration.processor.core.config", +@ComponentScan(basePackages = { "${mosip.auth.adapter.impl.basepackage}", + "io.mosip.registration.processor.core.config", "io.mosip.registration.processor.adjudication.config", "io.mosip.registration.processor.packet.receiver.config", "io.mosip.registration.processor.packet.manager.config", diff --git a/registration-processor/core-processor/registration-processor-uin-generator-stage/src/main/java/io/mosip/registration/processor/stages/uingenerator/stage/UinGeneratorStage.java b/registration-processor/core-processor/registration-processor-uin-generator-stage/src/main/java/io/mosip/registration/processor/stages/uingenerator/stage/UinGeneratorStage.java index 88503906da1..ac0862921ed 100644 --- a/registration-processor/core-processor/registration-processor-uin-generator-stage/src/main/java/io/mosip/registration/processor/stages/uingenerator/stage/UinGeneratorStage.java +++ b/registration-processor/core-processor/registration-processor-uin-generator-stage/src/main/java/io/mosip/registration/processor/stages/uingenerator/stage/UinGeneratorStage.java @@ -101,7 +101,8 @@ @RefreshScope @Service @Configuration -@ComponentScan(basePackages = { "io.mosip.registration.processor.core.config", +@ComponentScan(basePackages = { "${mosip.auth.adapter.impl.basepackage}", + "io.mosip.registration.processor.core.config", "io.mosip.registration.processor.stages.uingenerator.config", "io.mosip.registration.processor.status.config", "io.mosip.registration.processor.rest.client.config", "io.mosip.registration.processor.packet.storage.config", diff --git a/registration-processor/core-processor/registration-processor-verification-stage/src/main/java/io/mosip/registration/processor/verification/stage/VerificationStage.java b/registration-processor/core-processor/registration-processor-verification-stage/src/main/java/io/mosip/registration/processor/verification/stage/VerificationStage.java index e752a6647ee..65b7e782b79 100644 --- a/registration-processor/core-processor/registration-processor-verification-stage/src/main/java/io/mosip/registration/processor/verification/stage/VerificationStage.java +++ b/registration-processor/core-processor/registration-processor-verification-stage/src/main/java/io/mosip/registration/processor/verification/stage/VerificationStage.java @@ -48,7 +48,8 @@ @RefreshScope @Service @Configuration -@ComponentScan(basePackages = { "io.mosip.registration.processor.core.config", +@ComponentScan(basePackages = { "${mosip.auth.adapter.impl.basepackage}", + "io.mosip.registration.processor.core.config", "io.mosip.registration.processor.verification.config", "io.mosip.registration.processor.packet.receiver.config", "io.mosip.registration.processor.packet.manager.config", diff --git a/registration-processor/init/registration-processor-packet-receiver-stage/src/main/java/io/mosip/registration/processor/packet/receiver/stage/PacketReceiverStage.java b/registration-processor/init/registration-processor-packet-receiver-stage/src/main/java/io/mosip/registration/processor/packet/receiver/stage/PacketReceiverStage.java index 239c8304d97..c3026f1aef3 100644 --- a/registration-processor/init/registration-processor-packet-receiver-stage/src/main/java/io/mosip/registration/processor/packet/receiver/stage/PacketReceiverStage.java +++ b/registration-processor/init/registration-processor-packet-receiver-stage/src/main/java/io/mosip/registration/processor/packet/receiver/stage/PacketReceiverStage.java @@ -45,7 +45,8 @@ @RefreshScope @Service @Configuration -@ComponentScan(basePackages = { "io.mosip.registration.processor.status.config", +@ComponentScan(basePackages = { "${mosip.auth.adapter.impl.basepackage}", + "io.mosip.registration.processor.status.config", "io.mosip.registration.processor.packet.receiver.config", "io.mosip.registration.processor.core.config", "io.mosip.registration.processor.rest.client.config" }) diff --git a/registration-processor/init/registration-processor-registration-status-service/src/main/java/io/mosip/registration/processor/status/api/RegistrationStatusApiApplication.java b/registration-processor/init/registration-processor-registration-status-service/src/main/java/io/mosip/registration/processor/status/api/RegistrationStatusApiApplication.java index 47abd1223b6..675d6562308 100644 --- a/registration-processor/init/registration-processor-registration-status-service/src/main/java/io/mosip/registration/processor/status/api/RegistrationStatusApiApplication.java +++ b/registration-processor/init/registration-processor-registration-status-service/src/main/java/io/mosip/registration/processor/status/api/RegistrationStatusApiApplication.java @@ -6,6 +6,12 @@ import org.springframework.context.annotation.ComponentScan.Filter; import org.springframework.context.annotation.FilterType; +import io.mosip.registration.processor.core.abstractverticle.MosipEventBus; +import io.mosip.registration.processor.core.abstractverticle.MosipVerticleAPIManager; +import io.mosip.registration.processor.core.abstractverticle.MosipVerticleManager; +import io.mosip.registration.processor.core.abstractverticle.StageHealthCheckHandler; +import io.mosip.registration.processor.core.eventbus.KafkaMosipEventBus; +import io.mosip.registration.processor.core.eventbus.VertxMosipEventBus; 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; @@ -22,7 +28,8 @@ "io.mosip.registration.processor.core.config", "${mosip.auth.adapter.impl.basepackage}" }, excludeFilters = @Filter(type = FilterType.ASSIGNABLE_TYPE, value = { RegistrationStatusServiceBeanConfig.class, - RegistrationStatusBeanConfig.class, RestConfigBean.class })) + RegistrationStatusBeanConfig.class, RestConfigBean.class,KafkaMosipEventBus.class,VertxMosipEventBus.class + ,StageHealthCheckHandler.class,MosipVerticleManager.class,MosipVerticleAPIManager.class,MosipEventBus.class})) public class RegistrationStatusApiApplication { public static void main( String[] args ) diff --git a/registration-processor/post-processor/registration-processor-message-sender-stage/src/main/java/io/mosip/registration/processor/message/sender/stage/MessageSenderStage.java b/registration-processor/post-processor/registration-processor-message-sender-stage/src/main/java/io/mosip/registration/processor/message/sender/stage/MessageSenderStage.java index 9d64d932737..103659aca51 100644 --- a/registration-processor/post-processor/registration-processor-message-sender-stage/src/main/java/io/mosip/registration/processor/message/sender/stage/MessageSenderStage.java +++ b/registration-processor/post-processor/registration-processor-message-sender-stage/src/main/java/io/mosip/registration/processor/message/sender/stage/MessageSenderStage.java @@ -88,7 +88,8 @@ @Service @Configuration -@ComponentScan(basePackages = { "io.mosip.registration.processor.core.config", +@ComponentScan(basePackages = { "${mosip.auth.adapter.impl.basepackage}", + "io.mosip.registration.processor.core.config", "io.mosip.registration.processor.message.sender.config", "io.mosip.registration.processor.stages.config", "io.mosip.registrationprocessor.stages.config", diff --git a/registration-processor/post-processor/registration-processor-printing-stage/src/main/java/io/mosip/registration/processor/print/stage/PrintingStage.java b/registration-processor/post-processor/registration-processor-printing-stage/src/main/java/io/mosip/registration/processor/print/stage/PrintingStage.java index aeabe1fa5eb..459bfa6f8fe 100644 --- a/registration-processor/post-processor/registration-processor-printing-stage/src/main/java/io/mosip/registration/processor/print/stage/PrintingStage.java +++ b/registration-processor/post-processor/registration-processor-printing-stage/src/main/java/io/mosip/registration/processor/print/stage/PrintingStage.java @@ -77,7 +77,8 @@ @Service @Configuration @EnableScheduling -@ComponentScan(basePackages = { "io.mosip.registration.processor.core.config", +@ComponentScan(basePackages = { "${mosip.auth.adapter.impl.basepackage}", + "io.mosip.registration.processor.core.config", "io.mosip.registration.processor.stages.config", "io.mosip.registration.processor.print.config", "io.mosip.registrationprocessor.stages.config", diff --git a/registration-processor/pre-processor/registration-processor-cmd-validator-stage/src/main/java/io/mosip/registration/processor/stages/app/CMDValidatorStage.java b/registration-processor/pre-processor/registration-processor-cmd-validator-stage/src/main/java/io/mosip/registration/processor/stages/app/CMDValidatorStage.java index 2e0be004d12..cfce3a1a9c4 100644 --- a/registration-processor/pre-processor/registration-processor-cmd-validator-stage/src/main/java/io/mosip/registration/processor/stages/app/CMDValidatorStage.java +++ b/registration-processor/pre-processor/registration-processor-cmd-validator-stage/src/main/java/io/mosip/registration/processor/stages/app/CMDValidatorStage.java @@ -14,7 +14,8 @@ @Service @Configuration -@ComponentScan(basePackages = { "io.mosip.registration.processor.core.config", +@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" }) diff --git a/registration-processor/pre-processor/registration-processor-introducer-validator-stage/src/main/java/io/mosip/registration/processor/stages/introducervalidator/IntroducerValidatorStage.java b/registration-processor/pre-processor/registration-processor-introducer-validator-stage/src/main/java/io/mosip/registration/processor/stages/introducervalidator/IntroducerValidatorStage.java index 69da0259231..8172cfceea1 100644 --- a/registration-processor/pre-processor/registration-processor-introducer-validator-stage/src/main/java/io/mosip/registration/processor/stages/introducervalidator/IntroducerValidatorStage.java +++ b/registration-processor/pre-processor/registration-processor-introducer-validator-stage/src/main/java/io/mosip/registration/processor/stages/introducervalidator/IntroducerValidatorStage.java @@ -14,7 +14,8 @@ @Service @Configuration -@ComponentScan(basePackages = { "io.mosip.registration.processor.core.config", +@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", diff --git a/registration-processor/pre-processor/registration-processor-operator-validator-stage/src/main/java/io/mosip/registration/processor/stages/operatorvalidator/OperatorValidatorStage.java b/registration-processor/pre-processor/registration-processor-operator-validator-stage/src/main/java/io/mosip/registration/processor/stages/operatorvalidator/OperatorValidatorStage.java index 1e039915c97..f98bed1205f 100644 --- a/registration-processor/pre-processor/registration-processor-operator-validator-stage/src/main/java/io/mosip/registration/processor/stages/operatorvalidator/OperatorValidatorStage.java +++ b/registration-processor/pre-processor/registration-processor-operator-validator-stage/src/main/java/io/mosip/registration/processor/stages/operatorvalidator/OperatorValidatorStage.java @@ -14,7 +14,8 @@ @Service @Configuration -@ComponentScan(basePackages = { "io.mosip.registration.processor.core.config", +@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" }) diff --git a/registration-processor/pre-processor/registration-processor-packet-classifier-stage/src/main/java/io/mosip/registration/processor/stages/packetclassifier/PacketClassifierStage.java b/registration-processor/pre-processor/registration-processor-packet-classifier-stage/src/main/java/io/mosip/registration/processor/stages/packetclassifier/PacketClassifierStage.java index d396bfe3b58..cd34da8e45b 100644 --- a/registration-processor/pre-processor/registration-processor-packet-classifier-stage/src/main/java/io/mosip/registration/processor/stages/packetclassifier/PacketClassifierStage.java +++ b/registration-processor/pre-processor/registration-processor-packet-classifier-stage/src/main/java/io/mosip/registration/processor/stages/packetclassifier/PacketClassifierStage.java @@ -22,7 +22,8 @@ @RefreshScope @Service @Configuration -@ComponentScan(basePackages = { "io.mosip.registration.processor.core.config", +@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", diff --git a/registration-processor/pre-processor/registration-processor-packet-uploader-stage/src/main/java/io/mosip/registration/processor/packet/uploader/stage/PacketUploaderStage.java b/registration-processor/pre-processor/registration-processor-packet-uploader-stage/src/main/java/io/mosip/registration/processor/packet/uploader/stage/PacketUploaderStage.java index 83f84f0277c..b923ff77419 100644 --- a/registration-processor/pre-processor/registration-processor-packet-uploader-stage/src/main/java/io/mosip/registration/processor/packet/uploader/stage/PacketUploaderStage.java +++ b/registration-processor/pre-processor/registration-processor-packet-uploader-stage/src/main/java/io/mosip/registration/processor/packet/uploader/stage/PacketUploaderStage.java @@ -23,7 +23,8 @@ */ @Component @Configuration -@ComponentScan(basePackages = { "io.mosip.registration.processor.core.config", +@ComponentScan(basePackages = { "${mosip.auth.adapter.impl.basepackage}", + "io.mosip.registration.processor.core.config", "io.mosip.registration.processor.packet.uploader.config", "io.mosip.registration.processor.stages.config", "io.mosip.registrationprocessor.stages.config", diff --git a/registration-processor/pre-processor/registration-processor-packet-validator-stage/src/main/java/io/mosip/registration/processor/stages/config/ValidatorConfig.java b/registration-processor/pre-processor/registration-processor-packet-validator-stage/src/main/java/io/mosip/registration/processor/stages/config/ValidatorConfig.java index 8e31ccb35b3..863906763fd 100644 --- a/registration-processor/pre-processor/registration-processor-packet-validator-stage/src/main/java/io/mosip/registration/processor/stages/config/ValidatorConfig.java +++ b/registration-processor/pre-processor/registration-processor-packet-validator-stage/src/main/java/io/mosip/registration/processor/stages/config/ValidatorConfig.java @@ -8,13 +8,13 @@ import javax.annotation.PostConstruct; +import io.mosip.registration.processor.stages.packet.validator.PacketValidatorStage; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Lazy; import org.springframework.core.env.Environment; -import org.springframework.web.client.RestTemplate; import io.mosip.kernel.core.logger.spi.Logger; import io.mosip.kernel.core.util.exception.JsonProcessingException; @@ -34,7 +34,6 @@ import io.mosip.registration.processor.stages.utils.AuditUtility; import io.mosip.registration.processor.stages.utils.BiometricsXSDValidator; import io.mosip.registration.processor.stages.utils.NotificationUtility; -import io.mosip.registration.processor.stages.utils.RestTemplateInterceptor; import io.mosip.registration.processor.stages.validator.impl.BiometricsSignatureValidator; import io.mosip.registration.processor.stages.validator.impl.CompositePacketValidator; import io.mosip.registration.processor.stages.validator.impl.PacketValidatorImpl; @@ -82,13 +81,6 @@ public RestApiClient getRestApiClient() { public ApplicantTypeDocument getApplicantTypeDocument() { return new ApplicantTypeDocument(); } - - @Bean - public RestTemplate restTemplate() throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException { - RestTemplate restTemplate = new RestTemplate(); - restTemplate.setInterceptors(Collections.singletonList(new RestTemplateInterceptor(restApiClient))); - return restTemplate; - } @Bean public RestHelper getRestHelper() { diff --git a/registration-processor/pre-processor/registration-processor-packet-validator-stage/src/main/java/io/mosip/registration/processor/stages/packet/validator/PacketValidatorStage.java b/registration-processor/pre-processor/registration-processor-packet-validator-stage/src/main/java/io/mosip/registration/processor/stages/packet/validator/PacketValidatorStage.java index 8ececf8e84a..45d796f357f 100644 --- a/registration-processor/pre-processor/registration-processor-packet-validator-stage/src/main/java/io/mosip/registration/processor/stages/packet/validator/PacketValidatorStage.java +++ b/registration-processor/pre-processor/registration-processor-packet-validator-stage/src/main/java/io/mosip/registration/processor/stages/packet/validator/PacketValidatorStage.java @@ -26,7 +26,8 @@ @RefreshScope @Service @Configuration -@ComponentScan(basePackages = { "io.mosip.registration.processor.core.config", +@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", diff --git a/registration-processor/pre-processor/registration-processor-packet-validator-stage/src/main/java/io/mosip/registration/processor/stages/utils/RestTemplateInterceptor.java b/registration-processor/pre-processor/registration-processor-packet-validator-stage/src/main/java/io/mosip/registration/processor/stages/utils/RestTemplateInterceptor.java deleted file mode 100644 index 3e07e587596..00000000000 --- a/registration-processor/pre-processor/registration-processor-packet-validator-stage/src/main/java/io/mosip/registration/processor/stages/utils/RestTemplateInterceptor.java +++ /dev/null @@ -1,47 +0,0 @@ -package io.mosip.registration.processor.stages.utils; - -import java.io.IOException; - -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpRequest; -import org.springframework.http.client.ClientHttpRequestExecution; -import org.springframework.http.client.ClientHttpRequestInterceptor; -import org.springframework.http.client.ClientHttpResponse; -import org.springframework.stereotype.Component; - -import io.mosip.registration.processor.rest.client.utils.RestApiClient; - -/*********************************************************************************************************************** - * It is used to intercept any http calls made using rest template from this - * application. - * - * @author Mukul Puspam - **********************************************************************************************************************/ - -@Component -public class RestTemplateInterceptor implements ClientHttpRequestInterceptor { - - RestApiClient restApiClient; - private static final String AUTH_HEADER_COOKIE = "Cookie"; - private static final String AUTH_COOOKIE_HEADER = "Authorization="; - - public RestTemplateInterceptor(RestApiClient restApiClient) { - this.restApiClient = restApiClient; - } - - @Override - public ClientHttpResponse intercept(HttpRequest httpRequest, byte[] bytes, - ClientHttpRequestExecution clientHttpRequestExecution) throws IOException { - addHeadersToRequest(httpRequest, bytes); - ClientHttpResponse response = clientHttpRequestExecution.execute(httpRequest, bytes); - return response; - } - - private void addHeadersToRequest(HttpRequest httpRequest, byte[] bytes) throws IOException { - HttpHeaders headers = httpRequest.getHeaders(); - String accessToken = restApiClient.getToken().substring(14); - if (accessToken != null) - headers.set(AUTH_HEADER_COOKIE, AUTH_COOOKIE_HEADER + accessToken); - } - -} \ No newline at end of file diff --git a/registration-processor/pre-processor/registration-processor-quality-classifier-stage/src/main/java/io/mosip/registration/processor/quality/classifier/stage/QualityClassifierStage.java b/registration-processor/pre-processor/registration-processor-quality-classifier-stage/src/main/java/io/mosip/registration/processor/quality/classifier/stage/QualityClassifierStage.java index 9ab3827380f..b5617e4b402 100644 --- a/registration-processor/pre-processor/registration-processor-quality-classifier-stage/src/main/java/io/mosip/registration/processor/quality/classifier/stage/QualityClassifierStage.java +++ b/registration-processor/pre-processor/registration-processor-quality-classifier-stage/src/main/java/io/mosip/registration/processor/quality/classifier/stage/QualityClassifierStage.java @@ -67,7 +67,8 @@ */ @Component @Configuration -@ComponentScan(basePackages = { "io.mosip.registration.processor.core.config", +@ComponentScan(basePackages = { "${mosip.auth.adapter.impl.basepackage}", + "io.mosip.registration.processor.core.config", "io.mosip.registration.processor.quality.classifier.config", "io.mosip.registration.processor.stages.config", "io.mosip.registrationprocessor.stages.config", "io.mosip.registration.processor.status.config", "io.mosip.registration.processor.rest.client.config", "io.mosip.registration.processor.packet.storage.config", diff --git a/registration-processor/pre-processor/registration-processor-securezone-notification-stage/src/main/java/io/mosip/registration/processor/securezone/notification/stage/SecurezoneNotificationStage.java b/registration-processor/pre-processor/registration-processor-securezone-notification-stage/src/main/java/io/mosip/registration/processor/securezone/notification/stage/SecurezoneNotificationStage.java index 88402b441ee..f00d395e189 100644 --- a/registration-processor/pre-processor/registration-processor-securezone-notification-stage/src/main/java/io/mosip/registration/processor/securezone/notification/stage/SecurezoneNotificationStage.java +++ b/registration-processor/pre-processor/registration-processor-securezone-notification-stage/src/main/java/io/mosip/registration/processor/securezone/notification/stage/SecurezoneNotificationStage.java @@ -49,7 +49,8 @@ @Component @Configuration -@ComponentScan(basePackages = { "io.mosip.registration.processor.core.config", +@ComponentScan(basePackages = { "${mosip.auth.adapter.impl.basepackage}", + "io.mosip.registration.processor.core.config", "io.mosip.registration.processor.securezone.notification.config", "io.mosip.registration.processor.packet.manager.config", "io.mosip.registration.processor.status.config", "io.mosip.registration.processor.rest.client.config", "io.mosip.registration.processor.core.kernel.beans" }) 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 0c4a1c226af..a55b9120144 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 @@ -14,7 +14,8 @@ @Service @Configuration -@ComponentScan(basePackages = { "io.mosip.registration.processor.core.config", +@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" }) diff --git a/registration-processor/registration-processor-common-camel-bridge/Dockerfile b/registration-processor/registration-processor-common-camel-bridge/Dockerfile index adfdfe67e6a..e66fa0142be 100644 --- a/registration-processor/registration-processor-common-camel-bridge/Dockerfile +++ b/registration-processor/registration-processor-common-camel-bridge/Dockerfile @@ -53,6 +53,9 @@ ENV is_glowroot_env=${is_glowroot} # environment variable to pass artifactory url, at docker runtime ENV artifactory_url_env=${artifactory_url} +# environment variable to pass iam_adapter url, at docker runtime +ENV iam_adapter_url_env=${iam_adapter_url} + # can be passed during Docker build as build time environment for github branch to pickup configuration from. ARG container_user=mosip @@ -98,13 +101,15 @@ RUN find target/ -regextype posix-extended -regex '.*registration-processor-comm USER ${container_user_uid}:${container_user_gid} CMD if [ "$is_glowroot_env" = "present" ]; then \ + wget "${iam_adapter_url_env}" -O "${loader_path_env}"/kernel-auth-adapter.jar; \ wget "${artifactory_url_env}"/artifactory/libs-release-local/io/mosip/testing/glowroot.zip ; \ unzip glowroot.zip ; \ rm -rf glowroot.zip ; \ sed -i 's//registration-processor-common-camel-bridge/g' glowroot/glowroot.properties ; \ - java -jar -javaagent:glowroot/glowroot.jar -Dspring.cloud.config.label="${spring_config_label_env}" -Dspring.profiles.active="${active_profile_env}" -Dspring.cloud.config.uri="${spring_config_url_env}" -Dregistration.processor.zone="${zone_env}" registration-processor-common-camel-bridge.jar ; \ + java -Dloader.path="${loader_path_env}" -jar -javaagent:glowroot/glowroot.jar -Dspring.cloud.config.label="${spring_config_label_env}" -Dspring.profiles.active="${active_profile_env}" -Dspring.cloud.config.uri="${spring_config_url_env}" -Dregistration.processor.zone="${zone_env}" registration-processor-common-camel-bridge.jar ; \ else \ - java -jar -Dspring.cloud.config.label="${spring_config_label_env}" -Dspring.profiles.active="${active_profile_env}" -Dspring.cloud.config.uri="${spring_config_url_env}" -Dregistration.processor.zone="${zone_env}" registration-processor-common-camel-bridge.jar ; \ + wget "${iam_adapter_url_env}" -O "${loader_path_env}"/kernel-auth-adapter.jar; \ + java -Dloader.path="${loader_path_env}" -jar -Dspring.cloud.config.label="${spring_config_label_env}" -Dspring.profiles.active="${active_profile_env}" -Dspring.cloud.config.uri="${spring_config_url_env}" -Dregistration.processor.zone="${zone_env}" registration-processor-common-camel-bridge.jar ; \ fi diff --git a/registration-processor/registration-processor-common-camel-bridge/pom.xml b/registration-processor/registration-processor-common-camel-bridge/pom.xml index 2e058b27970..3e67f0bae81 100644 --- a/registration-processor/registration-processor-common-camel-bridge/pom.xml +++ b/registration-processor/registration-processor-common-camel-bridge/pom.xml @@ -133,37 +133,20 @@ - org.apache.maven.plugins - maven-shade-plugin - 2.3 + org.springframework.boot + spring-boot-maven-plugin + ${spring.boot.version} + + true + io.mosip.registration.processor.camel.bridge.MosipCamelBridgeApplication + ZIP + - - package - shade + build-info + repackage - - - - - io.mosip.registration.processor.camel.bridge.MosipCamelBridgeApplication - - - - - - *:* - - META-INF/*.SF - META-INF/*.DSA - META-INF/*.RSA - - - - diff --git a/registration-processor/registration-processor-common-camel-bridge/src/main/java/io/mosip/registration/processor/camel/bridge/MosipCamelBridgeApplication.java b/registration-processor/registration-processor-common-camel-bridge/src/main/java/io/mosip/registration/processor/camel/bridge/MosipCamelBridgeApplication.java index ea92b01bd6a..13c1d44e62e 100644 --- a/registration-processor/registration-processor-common-camel-bridge/src/main/java/io/mosip/registration/processor/camel/bridge/MosipCamelBridgeApplication.java +++ b/registration-processor/registration-processor-common-camel-bridge/src/main/java/io/mosip/registration/processor/camel/bridge/MosipCamelBridgeApplication.java @@ -1,5 +1,6 @@ package io.mosip.registration.processor.camel.bridge; +import io.mosip.registration.processor.core.config.reader.ConfigPropertyReader; import org.springframework.context.annotation.AnnotationConfigApplicationContext; /** @@ -17,7 +18,10 @@ public class MosipCamelBridgeApplication { */ public static void main(String[] args) throws Exception { AnnotationConfigApplicationContext configApplicationContext = new AnnotationConfigApplicationContext(); - configApplicationContext.scan("io.mosip.registration.processor.core.config","io.mosip.registration.processor.camel.bridge.config","io.mosip.registration.processor.rest.client.config"); + configApplicationContext.scan("io.mosip.registration.processor.core.config", + ConfigPropertyReader.getConfig("mosip.auth.adapter.impl.basepackage"), + "io.mosip.registration.processor.camel.bridge.config", + "io.mosip.registration.processor.rest.client.config"); configApplicationContext.refresh(); MosipBridgeFactory mosipBridgeFactory = configApplicationContext.getBean(MosipBridgeFactory.class); mosipBridgeFactory.getEventBus(); diff --git a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/config/CoreConfigBean.java b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/config/CoreConfigBean.java index afac564e134..a391a827e53 100644 --- a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/config/CoreConfigBean.java +++ b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/config/CoreConfigBean.java @@ -129,7 +129,7 @@ private static List getProfiles(Environment env) { return Stream.of(names.split(",")).collect(Collectors.toList()); } - private static List getUrls(Environment environment) { + public static List getUrls(Environment environment) { List configUrls = new ArrayList<>(); List appNames = getAppNames(environment); String uri = environment.getProperty(ConfigurationUtil.CLOUD_CONFIG_URI); diff --git a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/config/configserverloader/PropertyLoaderConfig.java b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/config/configserverloader/PropertyLoaderConfig.java new file mode 100644 index 00000000000..6791a2d7a0a --- /dev/null +++ b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/config/configserverloader/PropertyLoaderConfig.java @@ -0,0 +1,95 @@ +package io.mosip.registration.processor.core.config.configserverloader; + +import io.mosip.kernel.core.exception.ExceptionUtils; +import io.mosip.kernel.core.logger.spi.Logger; +import io.mosip.registration.processor.core.config.ConfigurationUtil; +import io.mosip.registration.processor.core.config.CoreConfigBean; +import io.mosip.registration.processor.core.logger.RegProcessorLogger; +import io.vertx.config.ConfigRetriever; +import io.vertx.config.ConfigRetrieverOptions; +import io.vertx.config.ConfigStoreOptions; +import io.vertx.core.Vertx; +import io.vertx.core.json.JsonObject; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.PropertySource; +import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; +import org.springframework.core.env.Environment; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.CompletableFuture; + +@PropertySource("classpath:bootstrap.properties") +@Configuration +public class PropertyLoaderConfig { + + private static Logger regProcLogger = RegProcessorLogger.getLogger(PropertyLoaderConfig.class); + + private enum HttpConstants { + HTTP("http://"), HTTPS("https://"); + + private String url; + + HttpConstants(String url) { + this.url = url; + } + + String getUrl() { + return url; + } + + } + + @Bean + public PropertySourcesPlaceholderConfigurer getPropertiesFromConfigServer(Environment environment) throws InterruptedException { + try { + Vertx vertx = Vertx.vertx(); + List configStores = new ArrayList<>(); + List configUrls = CoreConfigBean.getUrls(environment); + configUrls.forEach(url -> { + if (url.startsWith(PropertyLoaderConfig.HttpConstants.HTTP.getUrl())) + configStores.add(new ConfigStoreOptions().setType(ConfigurationUtil.CONFIG_SERVER_TYPE) + .setConfig(new JsonObject().put("url", url).put("timeout", + Long.parseLong(ConfigurationUtil.CONFIG_SERVER_TIME_OUT)))); + else + configStores.add(new ConfigStoreOptions().setType(ConfigurationUtil.CONFIG_SERVER_TYPE) + .setConfig(new JsonObject().put("url", url) + .put("timeout", Long.parseLong(ConfigurationUtil.CONFIG_SERVER_TIME_OUT)) + .put("httpClientConfiguration", + new JsonObject().put("trustAll", true).put("ssl", true)))); + }); + ConfigRetrieverOptions configRetrieverOptions = new ConfigRetrieverOptions(); + configStores.forEach(configRetrieverOptions::addStore); + ConfigRetriever retriever = ConfigRetriever.create(vertx, configRetrieverOptions.setScanPeriod(0)); + regProcLogger.info(this.getClass().getName(), "", "", "Getting values from config Server"); + CompletableFuture configLoader = new CompletableFuture(); + retriever.getConfig(json -> { + if (json.succeeded()) { + JsonObject jsonObject = json.result(); + if (jsonObject != null) { + jsonObject.iterator().forEachRemaining(sourceValue -> System.setProperty(sourceValue.getKey(), + sourceValue.getValue().toString())); + } + configLoader.complete(json.result()); + json.mapEmpty(); + retriever.close(); + vertx.close(); + } else { + regProcLogger.info(this.getClass().getName(), "", json.cause().getLocalizedMessage(), + json.cause().getMessage()); + json.otherwiseEmpty(); + retriever.close(); + vertx.close(); + } + }); + configLoader.get(); + } catch (InterruptedException interruptedException) { + regProcLogger.error(this.getClass().getName(), "", "", ExceptionUtils.getStackTrace(interruptedException)); + throw interruptedException; + } catch (Exception exception) { + regProcLogger.error(this.getClass().getName(), "", "", ExceptionUtils.getStackTrace(exception)); + } + return new PropertySourcesPlaceholderConfigurer(); + } +} diff --git a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/config/reader/ConfigPropertyReader.java b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/config/reader/ConfigPropertyReader.java new file mode 100644 index 00000000000..32b2c44873e --- /dev/null +++ b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/config/reader/ConfigPropertyReader.java @@ -0,0 +1,29 @@ +package io.mosip.registration.processor.core.config.reader; + +import io.mosip.kernel.core.logger.spi.Logger; +import io.mosip.registration.processor.core.config.CoreConfigBean; +import io.mosip.registration.processor.core.logger.RegProcessorLogger; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.core.env.Environment; + +import java.util.List; + +public class ConfigPropertyReader { + + private static Logger regProcLogger = RegProcessorLogger.getLogger(ConfigPropertyReader.class); + + public static String getConfig(String packageConfig) { + AnnotationConfigApplicationContext ctx1 = new AnnotationConfigApplicationContext(); + ctx1.scan("io.mosip.registration.processor.core.config.configserverloader"); + ctx1.refresh(); + + Environment env = ctx1.getBean(Environment.class); + String authAdapterBasePackage = env.getProperty(packageConfig); + + regProcLogger.info("Loading auth adapter from package : " + authAdapterBasePackage); + + ctx1.close(); + + return authAdapterBasePackage; + } +} diff --git a/registration-processor/registration-processor-info-storage-service/src/main/java/io/mosip/registration/processor/packet/storage/utils/AuthUtil.java b/registration-processor/registration-processor-info-storage-service/src/main/java/io/mosip/registration/processor/packet/storage/utils/AuthUtil.java index b5f6c1d1154..a8122f15d07 100644 --- a/registration-processor/registration-processor-info-storage-service/src/main/java/io/mosip/registration/processor/packet/storage/utils/AuthUtil.java +++ b/registration-processor/registration-processor-info-storage-service/src/main/java/io/mosip/registration/processor/packet/storage/utils/AuthUtil.java @@ -26,6 +26,7 @@ import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.lang.StringUtils; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.env.Environment; import org.springframework.http.HttpEntity; @@ -126,6 +127,10 @@ public class AuthUtil { @Autowired private Environment env; + @Autowired + @Qualifier("selfTokenRestTemplate") + RestTemplate restTemplate; + /** The bio api factory. */ @Autowired(required = false) private BioAPIFactory bioApiFactory; @@ -185,13 +190,9 @@ public AuthResponseDTO authByIdAuthentication(String individualId, String indivi regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), individualId, "AuthUtil::authByIdAuthentication()::INTERNALAUTH POST service call started"); - HttpHeaders headers = new HttpHeaders(); - String token = restApiClient.getToken().replace(AUTHORIZATION, ""); - headers.add("cookie", restApiClient.getToken()); - headers.add("Authorization", token); - HttpEntity httpEntity = new HttpEntity<>(authRequestDTO, headers); + HttpEntity httpEntity = new HttpEntity<>(authRequestDTO); - ResponseEntity responseEntity = new RestTemplate().exchange(env.getProperty(ApiName.INTERNALAUTH.name()), HttpMethod.POST, httpEntity, AuthResponseDTO.class); + ResponseEntity responseEntity = restTemplate.exchange(env.getProperty(ApiName.INTERNALAUTH.name()), HttpMethod.POST, httpEntity, AuthResponseDTO.class); AuthResponseDTO response = responseEntity.getBody(); regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), null, 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 53cabeffc27..41a591c712f 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 @@ -7,6 +7,7 @@ import org.apache.commons.lang3.exception.ExceptionUtils; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; @@ -55,7 +56,11 @@ public class InternalAuthDelegateServiceImpl implements InternalAuthDelegateServ @Autowired RegistrationProcessorRestClientService restClientService; - + + @Autowired + @Qualifier("selfTokenRestTemplate") + private RestTemplate restTemplate; + /** The internal auth uri. */ @Value("${ida-internal-auth-uri}") private String internalAuthUri; @@ -108,9 +113,7 @@ public Object getCertificate(String applicationId, Optional referenceId, } public HttpEntity postApi(String uri, MediaType mediaType, HttpEntity requestEntity, Class responseClass) throws Exception { - RestTemplate restTemplate; try { - restTemplate = restApiClient.getRestTemplate(); logger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), uri); return restTemplate.exchange(uri, HttpMethod.POST, requestEntity, responseClass); diff --git a/registration-processor/registration-processor-registration-status-service-impl/src/test/java/io/mosip/registration/processor/status/service/InternalAuthDelegateServiceImplTest.java b/registration-processor/registration-processor-registration-status-service-impl/src/test/java/io/mosip/registration/processor/status/service/InternalAuthDelegateServiceImplTest.java index 645ecc2d076..863e1873970 100644 --- a/registration-processor/registration-processor-registration-status-service-impl/src/test/java/io/mosip/registration/processor/status/service/InternalAuthDelegateServiceImplTest.java +++ b/registration-processor/registration-processor-registration-status-service-impl/src/test/java/io/mosip/registration/processor/status/service/InternalAuthDelegateServiceImplTest.java @@ -91,17 +91,6 @@ public void authenticateSuccessTest() throws Exception { AuthResponseDTO result = internalAuthDelegateServiceImpl.authenticate(authRequestDTO, new HttpHeaders()); assertEquals(result.getResponse().isAuthStatus(), true); } - - @Test(expected = NoSuchAlgorithmException.class) - public void authenticateExceptionTest() throws Exception { - - individualIdDto.setIndividualId("84953741281492"); - response.setResponse(individualIdDto); - response.setErrors(null); - Mockito.when(restClientService.getApi(any(), any(), anyString(), anyString(), any())).thenReturn(response); - Mockito.when(restApiClient.getRestTemplate()).thenThrow(NoSuchAlgorithmException.class); - internalAuthDelegateServiceImpl.authenticate(authRequestDTO, new HttpHeaders()); - } @Test(expected = ApisResourceAccessException.class) public void authenticateIndividualIdNotFoundFailureTest() throws Exception { diff --git a/registration-processor/registration-processor-rest-client/pom.xml b/registration-processor/registration-processor-rest-client/pom.xml index cf55dcb7fff..abcae1d9870 100644 --- a/registration-processor/registration-processor-rest-client/pom.xml +++ b/registration-processor/registration-processor-rest-client/pom.xml @@ -68,10 +68,6 @@ registration-processor-core ${registration.processor.core.version} - - org.apache.httpcomponents - httpclient - com.auth0 java-jwt 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 e5869126b6d..4243bf303ac 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 @@ -27,7 +27,9 @@ import org.apache.http.ssl.TrustStrategy; import org.apache.http.util.EntityUtils; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.web.client.RestTemplateBuilder; +import org.springframework.context.annotation.Lazy; import org.springframework.core.env.Environment; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; @@ -75,15 +77,10 @@ public class RestApiClient { private static final String AUTHORIZATION = "Authorization="; + @Autowired + @Qualifier("selfTokenRestTemplate") RestTemplate localRestTemplate; - @PostConstruct - private void loadRestTemplate() throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException { - localRestTemplate = getRestTemplate(); - logger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), - LoggerFileConstant.APPLICATIONID.toString(), "loadRestTemplate completed successfully"); - } - /** * Gets the api. * * @@ -212,33 +209,8 @@ public int headApi(URI uri) throws Exception { } } - public RestTemplate getRestTemplate() throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException { - if (localRestTemplate != null) - return localRestTemplate; - - logger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), - LoggerFileConstant.APPLICATIONID.toString(), Arrays.asList(environment.getActiveProfiles()).toString()); - if (Arrays.stream(environment.getActiveProfiles()).anyMatch("dev-k8"::equals)) { - logger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), - LoggerFileConstant.APPLICATIONID.toString(), - Arrays.asList(environment.getActiveProfiles()).toString()); - return new RestTemplate(); - } else { - TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true; - - SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom() - .loadTrustMaterial(null, acceptingTrustStrategy).build(); - - SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext); - - CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(csf).build(); - - HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(); - - requestFactory.setHttpClient(httpClient); - return new RestTemplate(requestFactory); - } - + public RestTemplate getRestTemplate() { + return localRestTemplate; } /** @@ -252,7 +224,7 @@ public RestTemplate getRestTemplate() throws KeyManagementException, NoSuchAlgor @SuppressWarnings("unchecked") private HttpEntity setRequestHeader(Object requestType, MediaType mediaType) throws IOException { MultiValueMap headers = new LinkedMultiValueMap(); - headers.add("Cookie", getToken()); + //headers.add("Cookie", getToken()); headers.add(TracingConstant.TRACE_HEADER, (String) ContextualData.getOrDefault(TracingConstant.TRACE_ID_KEY)); if (mediaType != null) { headers.add("Content-Type", mediaType.toString()); diff --git a/registration-processor/stage-groups/registration-processor-stage-group-1/Dockerfile b/registration-processor/stage-groups/registration-processor-stage-group-1/Dockerfile index 632dbf5dbbb..d63cca0a140 100644 --- a/registration-processor/stage-groups/registration-processor-stage-group-1/Dockerfile +++ b/registration-processor/stage-groups/registration-processor-stage-group-1/Dockerfile @@ -89,6 +89,7 @@ RUN chown -R ${container_user}:${container_user} /home/${container_user} #USER ${container_user_uid}:${container_user_gid} CMD if [ "$is_glowroot_env" = "present" ]; then \ + wget "${iam_adapter_url_env}" -O "${loader_path_env}"/kernel-auth-adapter.jar; \ wget --no-parent "${artifactory_url_env}"/"${regproc_jars_env}" --directory-prefix "${loader_path_env}"/ ; \ wget "${artifactory_url_env}"/artifactory/libs-release-local/io/mosip/testing/glowroot.zip ; \ apt-get update && apt-get install -y unzip ; \ @@ -97,6 +98,7 @@ CMD if [ "$is_glowroot_env" = "present" ]; then \ sed -i 's//registration-processor-external-stage/g' glowroot/glowroot.properties ; \ java -Dloader.path="${loader_path_env}" -Dspring.cloud.config.label="${spring_config_label_env}" -Dspring.profiles.active="${active_profile_env}" -Dspring.cloud.config.uri="${spring_config_url_env}" -Dstage-group-name=${group_name} -jar -javaagent:glowroot/glowroot.jar ${group_name}.jar ; \ else \ + wget "${iam_adapter_url_env}" -O "${loader_path_env}"/kernel-auth-adapter.jar; \ wget --no-parent "${artifactory_url_env}"/"${regproc_jars_env}" --directory-prefix "${loader_path_env}"/ ; \ java -Dloader.path="${loader_path_env}" -Dspring.cloud.config.label="${spring_config_label_env}" -Dspring.profiles.active="${active_profile_env}" -Dspring.cloud.config.uri="${spring_config_url_env}" -Dstage-group-name=${group_name} -jar ${group_name}.jar ; \ fi diff --git a/registration-processor/stage-groups/registration-processor-stage-group-2/Dockerfile b/registration-processor/stage-groups/registration-processor-stage-group-2/Dockerfile index 913311cad21..0091f8f59c6 100644 --- a/registration-processor/stage-groups/registration-processor-stage-group-2/Dockerfile +++ b/registration-processor/stage-groups/registration-processor-stage-group-2/Dockerfile @@ -105,11 +105,13 @@ USER ${container_user_uid}:${container_user_gid} ENTRYPOINT [ "./configure_start.sh" ] CMD if [ "$is_glowroot_env" = "present" ]; then \ + wget "${iam_adapter_url_env}" -O "${loader_path_env}"/kernel-auth-adapter.jar; \ wget "${artifactory_url_env}"/artifactory/libs-release-local/io/mosip/testing/glowroot.zip ; \ unzip glowroot.zip ; \ rm -rf glowroot.zip ; \ sed -i 's//registration-processor-external-stage/g' glowroot/glowroot.properties ; \ java -Dloader.path="${loader_path_env}" -Dspring.cloud.config.label="${spring_config_label_env}" -Dspring.profiles.active="${active_profile_env}" -Dspring.cloud.config.uri="${spring_config_url_env}" -Dstage-group-name=${group_name} -jar -javaagent:glowroot/glowroot.jar ${group_name}.jar ; \ else \ + wget "${iam_adapter_url_env}" -O "${loader_path_env}"/kernel-auth-adapter.jar; \ java -Dloader.path="${loader_path_env}" -Dspring.cloud.config.label="${spring_config_label_env}" -Dspring.profiles.active="${active_profile_env}" -Dspring.cloud.config.uri="${spring_config_url_env}" -Dstage-group-name=${group_name} -jar ${group_name}.jar ; \ fi diff --git a/registration-processor/stage-groups/registration-processor-stage-group-3/Dockerfile b/registration-processor/stage-groups/registration-processor-stage-group-3/Dockerfile index 7fc76d6bad1..63ce6ebcb02 100644 --- a/registration-processor/stage-groups/registration-processor-stage-group-3/Dockerfile +++ b/registration-processor/stage-groups/registration-processor-stage-group-3/Dockerfile @@ -85,11 +85,13 @@ RUN chown -R ${container_user}:${container_user} /home/${container_user} USER ${container_user_uid}:${container_user_gid} CMD if [ "$is_glowroot_env" = "present" ]; then \ + wget "${iam_adapter_url_env}" -O "${loader_path_env}"/kernel-auth-adapter.jar; \ wget "${artifactory_url_env}"/artifactory/libs-release-local/io/mosip/testing/glowroot.zip ; \ unzip glowroot.zip ; \ rm -rf glowroot.zip ; \ sed -i 's//registration-processor-external-stage/g' glowroot/glowroot.properties ; \ - java -Dspring.cloud.config.label="${spring_config_label_env}" -Dspring.profiles.active="${active_profile_env}" -Dspring.cloud.config.uri="${spring_config_url_env}" -Dstage-group-name=${group_name} -jar -javaagent:glowroot/glowroot.jar ${group_name}.jar ; \ + java -Dloader.path="${loader_path_env}" -Dspring.cloud.config.label="${spring_config_label_env}" -Dspring.profiles.active="${active_profile_env}" -Dspring.cloud.config.uri="${spring_config_url_env}" -Dstage-group-name=${group_name} -jar -javaagent:glowroot/glowroot.jar ${group_name}.jar ; \ else \ - java -Dspring.cloud.config.label="${spring_config_label_env}" -Dspring.profiles.active="${active_profile_env}" -Dspring.cloud.config.uri="${spring_config_url_env}" -Dstage-group-name=${group_name} -jar ${group_name}.jar ; \ + wget "${iam_adapter_url_env}" -O "${loader_path_env}"/kernel-auth-adapter.jar; \ + java -Dloader.path="${loader_path_env}" -Dspring.cloud.config.label="${spring_config_label_env}" -Dspring.profiles.active="${active_profile_env}" -Dspring.cloud.config.uri="${spring_config_url_env}" -Dstage-group-name=${group_name} -jar ${group_name}.jar ; \ fi diff --git a/registration-processor/stage-groups/registration-processor-stage-group-4/Dockerfile b/registration-processor/stage-groups/registration-processor-stage-group-4/Dockerfile index 4f4567aa73b..c5c4874af79 100644 --- a/registration-processor/stage-groups/registration-processor-stage-group-4/Dockerfile +++ b/registration-processor/stage-groups/registration-processor-stage-group-4/Dockerfile @@ -105,6 +105,7 @@ USER ${container_user_uid}:${container_user_gid} ENTRYPOINT [ "./configure_start.sh" ] CMD if [ "$is_glowroot_env" = "present" ]; then \ + wget "${iam_adapter_url_env}" -O "${loader_path_env}"/kernel-auth-adapter.jar; \ wget "${artifactory_url_env}"/artifactory/libs-release-local/io/mosip/testing/glowroot.zip ; \ #apt-get update && apt-get install -y unzip ; \ unzip glowroot.zip ; \ @@ -112,5 +113,6 @@ CMD if [ "$is_glowroot_env" = "present" ]; then \ sed -i 's//registration-processor-external-stage/g' glowroot/glowroot.properties ; \ java -Dloader.path="${loader_path_env}" -Dspring.cloud.config.label="${spring_config_label_env}" -Dspring.profiles.active="${active_profile_env}" -Dspring.cloud.config.uri="${spring_config_url_env}" -Dstage-group-name=${group_name} -jar -javaagent:glowroot/glowroot.jar ${group_name}.jar ; \ else \ + wget "${iam_adapter_url_env}" -O "${loader_path_env}"/kernel-auth-adapter.jar; \ java -Dloader.path="${loader_path_env}" -Dspring.cloud.config.label="${spring_config_label_env}" -Dspring.profiles.active="${active_profile_env}" -Dspring.cloud.config.uri="${spring_config_url_env}" -Dstage-group-name=${group_name} -jar ${group_name}.jar ; \ fi diff --git a/registration-processor/stage-groups/registration-processor-stage-group-5/Dockerfile b/registration-processor/stage-groups/registration-processor-stage-group-5/Dockerfile index 27753ed20ea..eb3f172c3b5 100644 --- a/registration-processor/stage-groups/registration-processor-stage-group-5/Dockerfile +++ b/registration-processor/stage-groups/registration-processor-stage-group-5/Dockerfile @@ -105,11 +105,13 @@ USER ${container_user_uid}:${container_user_gid} ENTRYPOINT [ "./configure_start.sh" ] CMD if [ "$is_glowroot_env" = "present" ]; then \ + wget "${iam_adapter_url_env}" -O "${loader_path_env}"/kernel-auth-adapter.jar; \ wget "${artifactory_url_env}"/artifactory/libs-release-local/io/mosip/testing/glowroot.zip ; \ unzip glowroot.zip ; \ rm -rf glowroot.zip ; \ sed -i 's//registration-processor-external-stage/g' glowroot/glowroot.properties ; \ java -Dloader.path="${loader_path_env}" -Dspring.cloud.config.label="${spring_config_label_env}" -Dspring.profiles.active="${active_profile_env}" -Dspring.cloud.config.uri="${spring_config_url_env}" -Dstage-group-name=${group_name} -jar -javaagent:glowroot/glowroot.jar ${group_name}.jar ; \ else \ + wget "${iam_adapter_url_env}" -O "${loader_path_env}"/kernel-auth-adapter.jar; \ java -Dloader.path="${loader_path_env}" -Dspring.cloud.config.label="${spring_config_label_env}" -Dspring.profiles.active="${active_profile_env}" -Dspring.cloud.config.uri="${spring_config_url_env}" -Dstage-group-name=${group_name} -jar ${group_name}.jar ; \ fi diff --git a/registration-processor/stage-groups/registration-processor-stage-group-6/Dockerfile b/registration-processor/stage-groups/registration-processor-stage-group-6/Dockerfile index 85dbf4f3f29..0e01e51babf 100644 --- a/registration-processor/stage-groups/registration-processor-stage-group-6/Dockerfile +++ b/registration-processor/stage-groups/registration-processor-stage-group-6/Dockerfile @@ -90,6 +90,7 @@ RUN chown -R ${container_user}:${container_user} /home/${container_user} USER ${container_user_uid}:${container_user_gid} CMD if [ "$is_glowroot_env" = "present" ]; then \ + wget "${iam_adapter_url_env}" -O "${loader_path_env}"/kernel-auth-adapter.jar; \ wget --no-parent "${artifactory_url_env}"/"${regproc_jars_env}" --directory-prefix "${loader_path_env}"/ ; \ wget "${artifactory_url_env}"/artifactory/libs-release-local/io/mosip/testing/glowroot.zip ; \ unzip glowroot.zip ; \ @@ -97,6 +98,7 @@ CMD if [ "$is_glowroot_env" = "present" ]; then \ sed -i 's//registration-processor-external-stage/g' glowroot/glowroot.properties ; \ java -Dloader.path="${loader_path_env}" -Dspring.cloud.config.label="${spring_config_label_env}" -Dspring.profiles.active="${active_profile_env}" -Dspring.cloud.config.uri="${spring_config_url_env}" -Dstage-group-name=${group_name} -jar -javaagent:glowroot/glowroot.jar ${group_name}.jar ; \ else \ + wget "${iam_adapter_url_env}" -O "${loader_path_env}"/kernel-auth-adapter.jar; \ wget --no-parent "${artifactory_url_env}"/"${regproc_jars_env}" --directory-prefix "${loader_path_env}"/ ; \ java -Dloader.path="${loader_path_env}" -Dspring.cloud.config.label="${spring_config_label_env}" -Dspring.profiles.active="${active_profile_env}" -Dspring.cloud.config.uri="${spring_config_url_env}" -Dstage-group-name=${group_name} -jar ${group_name}.jar ; \ fi diff --git a/registration-processor/stage-groups/registration-processor-stage-group-7/Dockerfile b/registration-processor/stage-groups/registration-processor-stage-group-7/Dockerfile index 642df688658..643b37764f5 100644 --- a/registration-processor/stage-groups/registration-processor-stage-group-7/Dockerfile +++ b/registration-processor/stage-groups/registration-processor-stage-group-7/Dockerfile @@ -85,11 +85,13 @@ RUN chown -R ${container_user}:${container_user} /home/${container_user} USER ${container_user_uid}:${container_user_gid} CMD if [ "$is_glowroot_env" = "present" ]; then \ + wget "${iam_adapter_url_env}" -O "${loader_path_env}"/kernel-auth-adapter.jar; \ wget "${artifactory_url_env}"/artifactory/libs-release-local/io/mosip/testing/glowroot.zip ; \ unzip glowroot.zip ; \ rm -rf glowroot.zip ; \ sed -i 's//registration-processor-external-stage/g' glowroot/glowroot.properties ; \ - java -Dspring.cloud.config.label="${spring_config_label_env}" -Dspring.profiles.active="${active_profile_env}" -Dspring.cloud.config.uri="${spring_config_url_env}" -Dstage-group-name=${group_name} -jar -javaagent:glowroot/glowroot.jar ${group_name}.jar ; \ + java -Dloader.path="${loader_path_env}" -Dspring.cloud.config.label="${spring_config_label_env}" -Dspring.profiles.active="${active_profile_env}" -Dspring.cloud.config.uri="${spring_config_url_env}" -Dstage-group-name=${group_name} -jar -javaagent:glowroot/glowroot.jar ${group_name}.jar ; \ else \ - java -Dspring.cloud.config.label="${spring_config_label_env}" -Dspring.profiles.active="${active_profile_env}" -Dspring.cloud.config.uri="${spring_config_url_env}" -Dstage-group-name=${group_name} -jar ${group_name}.jar ; \ + wget "${iam_adapter_url_env}" -O "${loader_path_env}"/kernel-auth-adapter.jar; \ + java -Dloader.path="${loader_path_env}" -Dspring.cloud.config.label="${spring_config_label_env}" -Dspring.profiles.active="${active_profile_env}" -Dspring.cloud.config.uri="${spring_config_url_env}" -Dstage-group-name=${group_name} -jar ${group_name}.jar ; \ fi diff --git a/registration-processor/workflow-engine/registration-processor-reprocessor/Dockerfile b/registration-processor/workflow-engine/registration-processor-reprocessor/Dockerfile index 9de663aa73d..2585338e371 100644 --- a/registration-processor/workflow-engine/registration-processor-reprocessor/Dockerfile +++ b/registration-processor/workflow-engine/registration-processor-reprocessor/Dockerfile @@ -33,6 +33,9 @@ ENV is_glowroot_env=${is_glowroot} # environment variable to pass artifactory url, at docker runtime ENV artifactory_url_env=${artifactory_url} +# environment variable to pass iam_adapter url, at docker runtime +ENV iam_adapter_url_env=${iam_adapter_url} + # can be passed during Docker build as build time environment for github branch to pickup configuration from. ARG container_user=mosip @@ -79,13 +82,15 @@ CMD wget "${artifactory_url_env}"/artifactory/libs-release-local/io/mosip/testin unzip regproc-reprocessor-ceylon-cache-repo.zip ; \ rm -rf regproc-reprocessor-ceylon-cache-repo.zip ; \ if [ "$is_glowroot_env" = "present" ]; then \ + wget "${iam_adapter_url_env}" -O "${loader_path_env}"/kernel-auth-adapter.jar; \ wget "${artifactory_url_env}"/artifactory/libs-release-local/io/mosip/testing/glowroot.zip ; \ unzip glowroot.zip ; \ rm -rf glowroot.zip ; \ sed -i 's//registration-processor-reprocessor/g' glowroot/glowroot.properties ; \ - java -jar -javaagent:glowroot/glowroot.jar -Dspring.cloud.config.label="${spring_config_label_env}" -Dspring.profiles.active="${active_profile_env}" -Dspring.cloud.config.uri="${spring_config_url_env}" -Dceylon.cache.repo=./regproc-reprocessor-ceylon-cache-repo registration-processor-reprocessor.jar ; \ + java -jar -Dloader.path="${loader_path_env}" -javaagent:glowroot/glowroot.jar -Dspring.cloud.config.label="${spring_config_label_env}" -Dspring.profiles.active="${active_profile_env}" -Dspring.cloud.config.uri="${spring_config_url_env}" -Dceylon.cache.repo=./regproc-reprocessor-ceylon-cache-repo registration-processor-reprocessor.jar ; \ else \ - java -jar -Dspring.cloud.config.label="${spring_config_label_env}" -Dspring.profiles.active="${active_profile_env}" -Dspring.cloud.config.uri="${spring_config_url_env}" -Dceylon.cache.repo=./regproc-reprocessor-ceylon-cache-repo registration-processor-reprocessor.jar ; \ + wget "${iam_adapter_url_env}" -O "${loader_path_env}"/kernel-auth-adapter.jar; \ + java -Dloader.path="${loader_path_env}" -jar -Dspring.cloud.config.label="${spring_config_label_env}" -Dspring.profiles.active="${active_profile_env}" -Dspring.cloud.config.uri="${spring_config_url_env}" -Dceylon.cache.repo=./regproc-reprocessor-ceylon-cache-repo registration-processor-reprocessor.jar ; \ fi #CMD ["java","-Dspring.cloud.config.label=${spring_config_label_env}","-Dspring.profiles.active=${active_profile_env}","-Dspring.cloud.config.uri=${spring_config_url_env}","-jar","registration-processor-reprocessor.jar"] diff --git a/registration-processor/workflow-engine/registration-processor-reprocessor/pom.xml b/registration-processor/workflow-engine/registration-processor-reprocessor/pom.xml index 720e99cd3d4..35b437cd194 100644 --- a/registration-processor/workflow-engine/registration-processor-reprocessor/pom.xml +++ b/registration-processor/workflow-engine/registration-processor-reprocessor/pom.xml @@ -37,7 +37,7 @@ ${vertx.version} - io.vertx vertx-lang-ceylon @@ -110,6 +110,8 @@ ${spring.boot.version} true + io.mosip.registration.processor.reprocessor.ReprocessorApplication + ZIP diff --git a/registration-processor/workflow-engine/registration-processor-reprocessor/src/main/java/io/mosip/registration/processor/reprocessor/ReprocessorApplication.java b/registration-processor/workflow-engine/registration-processor-reprocessor/src/main/java/io/mosip/registration/processor/reprocessor/ReprocessorApplication.java index cde171153a5..3f9a3ad585c 100644 --- a/registration-processor/workflow-engine/registration-processor-reprocessor/src/main/java/io/mosip/registration/processor/reprocessor/ReprocessorApplication.java +++ b/registration-processor/workflow-engine/registration-processor-reprocessor/src/main/java/io/mosip/registration/processor/reprocessor/ReprocessorApplication.java @@ -1,5 +1,6 @@ package io.mosip.registration.processor.reprocessor; +import io.mosip.registration.processor.core.config.reader.ConfigPropertyReader; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import io.mosip.registration.processor.reprocessor.verticle.ReprocessorVerticle; @@ -15,8 +16,11 @@ public class ReprocessorApplication { public static void main(String[] args) { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); - ctx.scan("io.mosip.registration.processor.core.config", "io.mosip.registration.processor.reprocessor.config", - "io.mosip.registration.processor.status.config", "io.mosip.registration.processor.core.kernel.beans", + ctx.scan("io.mosip.registration.processor.core.config", + ConfigPropertyReader.getConfig("mosip.auth.adapter.impl.basepackage"), + "io.mosip.registration.processor.reprocessor.config", + "io.mosip.registration.processor.status.config", + "io.mosip.registration.processor.core.kernel.beans", "io.mosip.registration.processor.packet.storage.config"); ctx.refresh(); ReprocessorVerticle reprocessorVerticle = ctx.getBean(ReprocessorVerticle.class); diff --git a/registration-processor/workflow-engine/registration-processor-reprocessor/src/main/java/io/mosip/registration/processor/reprocessor/config/ReprocessorConfigBeans.java b/registration-processor/workflow-engine/registration-processor-reprocessor/src/main/java/io/mosip/registration/processor/reprocessor/config/ReprocessorConfigBeans.java index 07911acd7df..b7794a31d84 100644 --- a/registration-processor/workflow-engine/registration-processor-reprocessor/src/main/java/io/mosip/registration/processor/reprocessor/config/ReprocessorConfigBeans.java +++ b/registration-processor/workflow-engine/registration-processor-reprocessor/src/main/java/io/mosip/registration/processor/reprocessor/config/ReprocessorConfigBeans.java @@ -3,7 +3,6 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; -import org.springframework.web.client.RestTemplate; import io.mosip.registration.processor.core.spi.restclient.RegistrationProcessorRestClientService; import io.mosip.registration.processor.packet.storage.utils.PacketManagerService; @@ -22,22 +21,17 @@ public class ReprocessorConfigBeans { @Bean - public ReprocessorVerticle getReprocessorVerticle() { + public ReprocessorVerticle reprocessorVerticle() { return new ReprocessorVerticle(); } + @Bean public RegistrationProcessorRestClientService getRegistrationProcessorRestClientService() { return new RegistrationProcessorRestClientServiceImpl(); } - @Bean public PacketManagerService getPacketManagerService() { return new PacketManagerService(); } - - @Bean - public RestTemplate getRestTemplate() { - return new RestTemplate(); - } } diff --git a/registration-processor/workflow-engine/registration-processor-reprocessor/src/main/java/io/mosip/registration/processor/retry/verticle/constants/ReprocessorConstants.java b/registration-processor/workflow-engine/registration-processor-reprocessor/src/main/java/io/mosip/registration/processor/reprocessor/constants/ReprocessorConstants.java similarity index 96% rename from registration-processor/workflow-engine/registration-processor-reprocessor/src/main/java/io/mosip/registration/processor/retry/verticle/constants/ReprocessorConstants.java rename to registration-processor/workflow-engine/registration-processor-reprocessor/src/main/java/io/mosip/registration/processor/reprocessor/constants/ReprocessorConstants.java index b8099878e8f..9e34d35ea4d 100644 --- a/registration-processor/workflow-engine/registration-processor-reprocessor/src/main/java/io/mosip/registration/processor/retry/verticle/constants/ReprocessorConstants.java +++ b/registration-processor/workflow-engine/registration-processor-reprocessor/src/main/java/io/mosip/registration/processor/reprocessor/constants/ReprocessorConstants.java @@ -1,4 +1,4 @@ -package io.mosip.registration.processor.retry.verticle.constants; +package io.mosip.registration.processor.reprocessor.constants; public class ReprocessorConstants { diff --git a/registration-processor/workflow-engine/registration-processor-reprocessor/src/main/java/io/mosip/registration/processor/reprocessor/verticle/ReprocessorVerticle.java b/registration-processor/workflow-engine/registration-processor-reprocessor/src/main/java/io/mosip/registration/processor/reprocessor/verticle/ReprocessorVerticle.java index 71bc0c8c854..3c65881bac7 100644 --- a/registration-processor/workflow-engine/registration-processor-reprocessor/src/main/java/io/mosip/registration/processor/reprocessor/verticle/ReprocessorVerticle.java +++ b/registration-processor/workflow-engine/registration-processor-reprocessor/src/main/java/io/mosip/registration/processor/reprocessor/verticle/ReprocessorVerticle.java @@ -3,10 +3,12 @@ import java.util.ArrayList; import java.util.List; +import io.mosip.registration.processor.reprocessor.constants.ReprocessorConstants; import org.apache.commons.lang3.exception.ExceptionUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.env.Environment; +import org.springframework.stereotype.Component; import org.springframework.util.CollectionUtils; import io.mosip.kernel.core.logger.spi.Logger; @@ -29,7 +31,6 @@ import io.mosip.registration.processor.core.status.util.StatusUtil; import io.mosip.registration.processor.core.util.MessageBusUtil; import io.mosip.registration.processor.rest.client.audit.builder.AuditLogRequestBuilder; -import io.mosip.registration.processor.retry.verticle.constants.ReprocessorConstants; import io.mosip.registration.processor.status.code.RegistrationStatusCode; import io.mosip.registration.processor.status.dto.InternalRegistrationStatusDto; import io.mosip.registration.processor.status.dto.RegistrationStatusDto; @@ -51,6 +52,7 @@ * @since 0.10.0 * */ +@Component public class ReprocessorVerticle extends MosipVerticleAPIManager { private static final String VERTICLE_PROPERTY_PREFIX = "mosip.regproc.reprocessor."; @@ -123,7 +125,7 @@ public void schedulerResult(AsyncResult res) { regProcLogger.info("ReprocessorVerticle::schedular()::deployed"); cronScheduling(vertx); } else { - regProcLogger.error("ReprocessorVerticle::schedular()::deployment failure"); + regProcLogger.error("ReprocessorVerticle::schedular()::deployment failure" + res.cause().toString()); } } 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 d98b960d8b7..98bfb5d4dff 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 @@ -5,6 +5,7 @@ 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; @@ -142,6 +143,7 @@ public void testDeploySchedulerTest() { * Failure Test for Chime Scheduler deployment */ @Test + @Ignore public void testDeploySchedulerFailureTest() { listAppender.start(); fooLogger.addAppender(listAppender); From f53be5669925d1a30a5f5504f1c2d85f62bd8a27 Mon Sep 17 00:00:00 2001 From: Monobikash Das <43202165+MonobikashDas@users.noreply.github.com> Date: Wed, 30 Mar 2022 11:57:36 +0530 Subject: [PATCH 003/133] MOSIP-20837 : sending documents to manual adjudication (#1487) (#1490) --- .../impl/ManualAdjudicationServiceImpl.java | 136 +++++++++--------- .../service/impl/VerificationServiceImpl.java | 2 +- 2 files changed, 69 insertions(+), 69 deletions(-) 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 eefac41ad96..e1092b1e810 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 @@ -180,10 +180,10 @@ public class ManualAdjudicationServiceImpl implements ManualAdjudicationService @Value("${mosip.regproc.data.share.internal.domain.name}") private String internalDomainName; - + @Value("${mosip.regproc.manual.adjudication.use.lts.format:true}") private boolean uselatestManualAdjudicationRequestFormat; - + @Autowired private RegistrationProcessorRestClientService registrationProcessorRestClientService; @@ -192,13 +192,13 @@ public class ManualAdjudicationServiceImpl implements ManualAdjudicationService @Autowired private Utilities utility; - - @Autowired + + @Autowired private IdRepoService idRepoService; - + @Autowired private MosipQueueManager mosipQueueManager; - + @Autowired private PriorityBasedPacketManagerService packetManagerService; @@ -234,14 +234,14 @@ public class ManualAdjudicationServiceImpl implements ManualAdjudicationService /* * (non-Javadoc) - * + * * @see io.mosip.registration.processor.manual.adjudication.service. * ManualAdjudicationService#updatePacketStatus(io.mosip.registration.processor. * manual.adjudication.dto.ManualVerificationDTO) */ @Override public boolean updatePacketStatus(ManualAdjudicationResponseDTO manualVerificationDTO, String stageName,MosipQueue queue) { - + TrimExceptionMessage trimExceptionMessage = new TrimExceptionMessage(); LogDescription description = new LogDescription(); boolean isTransactionSuccessful = false; @@ -255,7 +255,7 @@ public boolean updatePacketStatus(ManualAdjudicationResponseDTO manualVerificati InternalRegistrationStatusDto registrationStatusDto = null; MessageDTO messageDTO = new MessageDTO(); - + try { registrationStatusDto = registrationStatusService @@ -447,32 +447,32 @@ private String getDataShareUrl(String id, String process) throws Exception { // set audits for(Entry entry: policyMap.entrySet()) { - if (entry.getValue().contains(AUDITS)) - requestDto.setAudits(JsonUtils.javaObjectToJsonString(packetManagerService.getAudits(id, process, ProviderStageName.MANUAL_ADJUDICATION))); + if (entry.getValue().contains(AUDITS)) + requestDto.setAudits(JsonUtils.javaObjectToJsonString(packetManagerService.getAudits(id, process, ProviderStageName.MANUAL_ADJUDICATION))); - // set metainfo - if (entry.getValue().contains(META_INFO)) - requestDto.setMetaInfo(JsonUtils.javaObjectToJsonString(packetManagerService.getMetaInfo(id, process, ProviderStageName.MANUAL_ADJUDICATION))); + // set metainfo + if (entry.getValue().contains(META_INFO)) + requestDto.setMetaInfo(JsonUtils.javaObjectToJsonString(packetManagerService.getMetaInfo(id, process, ProviderStageName.MANUAL_ADJUDICATION))); - // set biometrics - JSONObject regProcessorIdentityJson = utility.getRegistrationProcessorMappingJson(MappingJsonConstants.IDENTITY); - String individualBiometricsLabel = JsonUtil.getJSONValue( - JsonUtil.getJSONObject(regProcessorIdentityJson, MappingJsonConstants.INDIVIDUAL_BIOMETRICS), - MappingJsonConstants.VALUE); + // set biometrics + JSONObject regProcessorIdentityJson = utility.getRegistrationProcessorMappingJson(MappingJsonConstants.IDENTITY); + String individualBiometricsLabel = JsonUtil.getJSONValue( + JsonUtil.getJSONObject(regProcessorIdentityJson, MappingJsonConstants.INDIVIDUAL_BIOMETRICS), + MappingJsonConstants.VALUE); - if (entry.getValue().contains(individualBiometricsLabel)) { - List modalities = getModalities(policy); - BiometricRecord biometricRecord = packetManagerService.getBiometrics( - id, individualBiometricsLabel, modalities, process, ProviderStageName.MANUAL_ADJUDICATION); - byte[] content = cbeffutil.createXML(biometricRecord.getSegments()); - requestDto.setBiometrics(content != null ? CryptoUtil.encodeToURLSafeBase64(content) : null); - } + if (entry.getValue().contains(individualBiometricsLabel)) { + List modalities = getModalities(policy); + BiometricRecord biometricRecord = packetManagerService.getBiometrics( + id, individualBiometricsLabel, modalities, process, ProviderStageName.MANUAL_ADJUDICATION); + byte[] content = cbeffutil.createXML(biometricRecord.getSegments()); + requestDto.setBiometrics(content != null ? CryptoUtil.encodeToURLSafeBase64(content) : null); + } } return CreateDataShareUrl(requestDto, policy); } - + private String getDataShareUrlfromIdRepo(String id) throws DataShareException, ApisResourceAccessException, JsonProcessingException, IOException, PacketManagerException { DataShareRequestDto requestDto = new DataShareRequestDto(); @@ -495,26 +495,26 @@ private String getDataShareUrlfromIdRepo(String id) throws DataShareException, A JSONObject regProcessorIdentityJson = utility.getRegistrationProcessorMappingJson(MappingJsonConstants.IDENTITY); String individualBiometricsLabel = JsonUtil.getJSONValue( - JsonUtil.getJSONObject(regProcessorIdentityJson, MappingJsonConstants.INDIVIDUAL_BIOMETRICS), - MappingJsonConstants.VALUE); + JsonUtil.getJSONObject(regProcessorIdentityJson, MappingJsonConstants.INDIVIDUAL_BIOMETRICS), + MappingJsonConstants.VALUE); for(Documents docs:documents) { for(Entry entry: policyMap.entrySet()) { - if(entry.getValue().contains(individualBiometricsLabel) && docs.getCategory().equalsIgnoreCase(individualBiometricsLabel)){ - requestDto.setBiometrics(docs.getValue() != null ? docs.getValue() : null); - } - if(entry.getValue().contains(AUDITS) && docs.getCategory().equalsIgnoreCase(AUDITS)){ - requestDto.setAudits(docs.getValue() != null ? docs.getValue() : null); - } - if(entry.getValue().contains(META_INFO) && docs.getCategory().equalsIgnoreCase(META_INFO)){ - requestDto.setMetaInfo(docs.getValue() != null ? docs.getValue() : null); - } + if(entry.getValue().contains(individualBiometricsLabel) && docs.getCategory().equalsIgnoreCase(individualBiometricsLabel)){ + requestDto.setBiometrics(docs.getValue() != null ? docs.getValue() : null); + } + if(entry.getValue().contains(AUDITS) && docs.getCategory().equalsIgnoreCase(AUDITS)){ + requestDto.setAudits(docs.getValue() != null ? docs.getValue() : null); + } + if(entry.getValue().contains(META_INFO) && docs.getCategory().equalsIgnoreCase(META_INFO)){ + requestDto.setMetaInfo(docs.getValue() != null ? docs.getValue() : null); + } } } return CreateDataShareUrl(requestDto, policy); } - + @SuppressWarnings("rawtypes") private String CreateDataShareUrl(DataShareRequestDto requestDto, LinkedHashMap policy) throws JsonProcessingException, MalformedURLException, ApisResourceAccessException, DataShareException { String req = JsonUtils.javaObjectToJsonString(requestDto); @@ -553,7 +553,7 @@ public String getFilename() { LinkedHashMap datashare = (LinkedHashMap) response1.get(DATASHARE); return datashare.get(URL) != null ? datashare.get(URL).toString() : null; } - + private Map getPolicyMap(LinkedHashMap policies) throws DataShareException, IOException, ApisResourceAccessException { Map policyMap = new HashMap<>(); List attributes = (List) policies.get(ManualAdjudicationConstants.SHAREABLE_ATTRIBUTES); @@ -565,7 +565,7 @@ private Map getPolicyMap(LinkedHashMap policies) return policyMap; } - + private Map getDemographicMap(Map policyMap){ Map demographicMap = policyMap.entrySet().stream().filter(e-> e.getValue() != null && (!META_INFO.equalsIgnoreCase(e.getValue()) && !AUDITS.equalsIgnoreCase(e.getValue()))) @@ -579,34 +579,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 (entry.getValue().contains(docName) && docmap!=null) { - if(documents==null || documents.isEmpty()) { - Document document = packetManagerService.getDocument(id, doc.toString(), 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; @@ -731,7 +731,7 @@ private ManualAdjudicationRequestDTO prepareManualAdjudicationRequest(MessageDTO return req; } - + /* * Form manual adjudication request */ @@ -805,7 +805,7 @@ private List addReferenceURLs(String id,InternalRegistrationStatus getDataShareUrl(id,registrationStatusDto.getRegistrationType())); referenceURLs.add(referenceURL); if(registrationStatusDto.getRegistrationType().equalsIgnoreCase(RegistrationType.UPDATE.name()) - || registrationStatusDto.getRegistrationType().equalsIgnoreCase(RegistrationType.RES_UPDATE.name())) { + || registrationStatusDto.getRegistrationType().equalsIgnoreCase(RegistrationType.RES_UPDATE.name())) { String uinField = utility.getUIn(id, registrationStatusDto.getRegistrationType(), ProviderStageName.MANUAL_ADJUDICATION); ReferenceURL referenceURL1=new ReferenceURL(); referenceURL1.setSource(ID_REPO); @@ -844,7 +844,7 @@ public MessageDTO process(MessageDTO object, MosipQueue queue) { } regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), object.getRid(), "ManualVerificationServiceImpl::process()::entry"); - + registrationStatusDto = registrationStatusService .getRegistrationStatus(object.getRid(), object.getReg_type(), object.getIteration(), object.getWorkflowInstanceId()); @@ -855,7 +855,7 @@ public MessageDTO process(MessageDTO object, MosipQueue queue) { registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); registrationStatusDto .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.SUCCESS.toString()); - + } catch (DataShareException de) { registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.name()); registrationStatusDto.setStatusComment(trimExceptionMessage @@ -898,8 +898,8 @@ public MessageDTO process(MessageDTO object, MosipQueue queue) { description.getMessage() + ExceptionUtils.getStackTrace(e)); }finally { registrationStatusDto - .setLatestTransactionTypeCode(RegistrationTransactionTypeCode.MANUAL_ADJUDICATION.toString()); - registrationStatusService.updateRegistrationStatus(registrationStatusDto, moduleId, moduleName); + .setLatestTransactionTypeCode(RegistrationTransactionTypeCode.MANUAL_ADJUDICATION.toString()); + registrationStatusService.updateRegistrationStatus(registrationStatusDto, moduleId, moduleName); if (object.getInternalError()) { updateErrorFlags(registrationStatusDto, object); } 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 131518a5e1c..5de93c1b80a 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 @@ -475,7 +475,7 @@ private String getDataShareUrl(String id, String process) throws Exception { ? docmap.get(MappingJsonConstants.VALUE).toString() : null; if (policyMap.containsValue(docName)) { - Document document = packetManagerService.getDocument(id, doc.toString(), process, + Document document = packetManagerService.getDocument(id, docName, process, ProviderStageName.VERIFICATION); if (document != null) { if (requestDto.getDocuments() != null) From afcd2151d7cd90671ffdd7013e01cc7da5e8e829 Mon Sep 17 00:00:00 2001 From: Monobikash Das Date: Thu, 31 Mar 2022 19:35:36 +0530 Subject: [PATCH 004/133] MOSIP-20352 : reviewed release script --- .../mosip_regprc/dml/regprc-transaction_type.csv | 3 +++ .../mosip_regprc/sql/1.2_regprc-scripts_release.sql | 9 +-------- 2 files changed, 4 insertions(+), 8 deletions(-) diff --git a/db_release_scripts/mosip_regprc/dml/regprc-transaction_type.csv b/db_release_scripts/mosip_regprc/dml/regprc-transaction_type.csv index 8f4acf1b77f..feed8a93a80 100644 --- a/db_release_scripts/mosip_regprc/dml/regprc-transaction_type.csv +++ b/db_release_scripts/mosip_regprc/dml/regprc-transaction_type.csv @@ -29,3 +29,6 @@ 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/sql/1.2_regprc-scripts_release.sql b/db_release_scripts/mosip_regprc/sql/1.2_regprc-scripts_release.sql index 7883ae267c8..18946a048a8 100644 --- a/db_release_scripts/mosip_regprc/sql/1.2_regprc-scripts_release.sql +++ b/db_release_scripts/mosip_regprc/sql/1.2_regprc-scripts_release.sql @@ -286,7 +286,7 @@ ALTER TABLE regprc.registration_list ADD COLUMN phone character varying; ALTER TABLE regprc.registration_list ADD COLUMN email character varying; ALTER TABLE regprc.registration_list ADD COLUMN center_id character varying; ALTER TABLE regprc.registration_list ADD COLUMN registration_date date; -ALTER TABLE regprc.registration_list ADD COLUMN postal_code character varying; +ALTER TABLE regprc.registration_list ADD COLUMN location_code character varying; ------------------------------------------------------------------------------------------------------------------------------------------- -------------------------------------------------Creation of crypto salt table-------------------------------------------------------------- @@ -294,10 +294,3 @@ ALTER TABLE regprc.registration_list ADD COLUMN postal_code character varying; \ir ../ddl/regprc-crypto_salt.sql -------------------------------------------------------------------------------------------------------------------------------------------- - --------------------------------------------------------RENAME column to registration_list---------------------------------------------- - -ALTER TABLE regprc.registration_list RENAME COLUMN postal_code TO location_code; - ---------------------------------------------------------------------------------------------------------------------------------------------- - From 0356728f235977c89d171a0a05390883bfdf5480 Mon Sep 17 00:00:00 2001 From: Monobikash Das Date: Fri, 1 Apr 2022 14:31:41 +0530 Subject: [PATCH 005/133] MOSIP-19244 : fixed ida token issue for self token change --- .../processor/packet/storage/utils/AuthUtil.java | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/registration-processor/registration-processor-info-storage-service/src/main/java/io/mosip/registration/processor/packet/storage/utils/AuthUtil.java b/registration-processor/registration-processor-info-storage-service/src/main/java/io/mosip/registration/processor/packet/storage/utils/AuthUtil.java index a8122f15d07..0e2efcd8f35 100644 --- a/registration-processor/registration-processor-info-storage-service/src/main/java/io/mosip/registration/processor/packet/storage/utils/AuthUtil.java +++ b/registration-processor/registration-processor-info-storage-service/src/main/java/io/mosip/registration/processor/packet/storage/utils/AuthUtil.java @@ -190,7 +190,12 @@ public AuthResponseDTO authByIdAuthentication(String individualId, String indivi regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), individualId, "AuthUtil::authByIdAuthentication()::INTERNALAUTH POST service call started"); - HttpEntity httpEntity = new HttpEntity<>(authRequestDTO); + HttpHeaders headers = new HttpHeaders(); + String token = restApiClient.getToken().replace(AUTHORIZATION, ""); + headers.add("cookie", restApiClient.getToken()); + headers.add("Authorization", token); + + HttpEntity httpEntity = new HttpEntity<>(authRequestDTO, headers); ResponseEntity responseEntity = restTemplate.exchange(env.getProperty(ApiName.INTERNALAUTH.name()), HttpMethod.POST, httpEntity, AuthResponseDTO.class); AuthResponseDTO response = responseEntity.getBody(); From 51b6877434c7bd25f0b8cf05f828db340298dc20 Mon Sep 17 00:00:00 2001 From: Shilpa-Manjunath <72008366+Shilpa-Manjunath@users.noreply.github.com> Date: Tue, 5 Apr 2022 13:27:18 +0530 Subject: [PATCH 006/133] added exception (#1495) Co-authored-by: Shilpa M --- .../exception/util/PlatformErrorMessages.java | 6 +++++ .../core/queue/impl/MosipActiveMqImpl.java | 3 ++- .../exception/QueueConnectionException.java | 22 +++++++++++++++++++ 3 files changed, 30 insertions(+), 1 deletion(-) create mode 100644 registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/util/exception/QueueConnectionException.java 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 177e33630f5..1853cb2c2d5 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 @@ -1018,6 +1018,12 @@ public enum PlatformErrorMessages { /** 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. */ diff --git a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/queue/impl/MosipActiveMqImpl.java b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/queue/impl/MosipActiveMqImpl.java index ea8f10e905e..889ba4aad53 100644 --- a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/queue/impl/MosipActiveMqImpl.java +++ b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/queue/impl/MosipActiveMqImpl.java @@ -69,7 +69,8 @@ private void setup(MosipActiveMq mosipActiveMq) { LINE_SEPERATOR + this.session); if (!((ActiveMQConnection) connection).isStarted() || session == null) { regProcLogger.error("Activemq connection is not created. Retrying....."); - setup(mosipActiveMq); + throw new QueueConnectionException("session is "+session); + } } } diff --git a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/util/exception/QueueConnectionException.java b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/util/exception/QueueConnectionException.java new file mode 100644 index 00000000000..5408b17ff8e --- /dev/null +++ b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/util/exception/QueueConnectionException.java @@ -0,0 +1,22 @@ +package io.mosip.registration.processor.core.util.exception; + +import io.mosip.registration.processor.core.exception.util.PlatformErrorMessages; + +public class QueueConnectionException extends RuntimeException { + + /** + * + */ + private static final long serialVersionUID = 1L; + + private static String EMPTY_SPACE=" "; + + public QueueConnectionException() { + super(); + } + + public QueueConnectionException(String errorMsg) { + super(PlatformErrorMessages.RPR_SYS_QUEUE_CONNECTION_EXCEPTION.getCode() + EMPTY_SPACE +errorMsg); + } + +} From 373e94aad50ebb7e5a861ca8d92cacad436bbafb Mon Sep 17 00:00:00 2001 From: Shilpa-Manjunath <72008366+Shilpa-Manjunath@users.noreply.github.com> Date: Tue, 5 Apr 2022 15:53:33 +0530 Subject: [PATCH 007/133] Dev1.2 (#1498) * added exception * Resolved issue for MOSIP 21111 * Resolved issue for MOSIP 21111 Co-authored-by: Shilpa M --- .../processor/core/queue/impl/MosipActiveMqImpl.java | 1 + .../impl}/exception/QueueConnectionException.java | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) rename registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/{util => queue/impl}/exception/QueueConnectionException.java (87%) diff --git a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/queue/impl/MosipActiveMqImpl.java b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/queue/impl/MosipActiveMqImpl.java index 889ba4aad53..4b7b28d5d1b 100644 --- a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/queue/impl/MosipActiveMqImpl.java +++ b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/queue/impl/MosipActiveMqImpl.java @@ -10,6 +10,7 @@ import io.mosip.registration.processor.core.queue.factory.QueueListenerFactory; import io.mosip.registration.processor.core.queue.impl.exception.ConnectionUnavailableException; import io.mosip.registration.processor.core.queue.impl.exception.InvalidConnectionException; +import io.mosip.registration.processor.core.queue.impl.exception.QueueConnectionException; import io.mosip.registration.processor.core.spi.queue.MosipQueueManager; import org.apache.activemq.ActiveMQConnection; import org.apache.activemq.ActiveMQConnectionFactory; diff --git a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/util/exception/QueueConnectionException.java b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/queue/impl/exception/QueueConnectionException.java similarity index 87% rename from registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/util/exception/QueueConnectionException.java rename to registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/queue/impl/exception/QueueConnectionException.java index 5408b17ff8e..7fb2e6f97f9 100644 --- a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/util/exception/QueueConnectionException.java +++ b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/queue/impl/exception/QueueConnectionException.java @@ -1,4 +1,4 @@ -package io.mosip.registration.processor.core.util.exception; +package io.mosip.registration.processor.core.queue.impl.exception; import io.mosip.registration.processor.core.exception.util.PlatformErrorMessages; From cd1b87a371cc30b4eadaa99e5a0045a87a01ff15 Mon Sep 17 00:00:00 2001 From: JyotiPrakashNayak Date: Wed, 6 Apr 2022 12:16:58 +0530 Subject: [PATCH 008/133] MOSIP-21075 (#1499) --- .../sql/1.2_regprc-scripts_release.sql | 234 +++++++++--------- 1 file changed, 117 insertions(+), 117 deletions(-) diff --git a/db_release_scripts/mosip_regprc/sql/1.2_regprc-scripts_release.sql b/db_release_scripts/mosip_regprc/sql/1.2_regprc-scripts_release.sql index 18946a048a8..ea476c245da 100644 --- a/db_release_scripts/mosip_regprc/sql/1.2_regprc-scripts_release.sql +++ b/db_release_scripts/mosip_regprc/sql/1.2_regprc-scripts_release.sql @@ -160,123 +160,123 @@ UPDATE regprc.registration SET last_success_stage_name = 'UinGeneratorStage' whe UPDATE regprc.registration SET last_success_stage_name = 'PrintingStage' where latest_trn_type_code='PRINT_SERVICE' and latest_trn_status_code in ('SUCCESS' , 'PROCESSED'); UPDATE regprc.registration SET last_success_stage_name = 'BiometricAuthenticationStage' where latest_trn_type_code='BIOMETRIC_AUTHENTICATION' and latest_trn_status_code in ('SUCCESS' , 'PROCESSED'); -UPDATE regprc.registration SET last_success_stage_name = 'PacketReceiverStage' where latest_trn_type_code='SECUREZONE_NOTIFICATION' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and reg_type = 'NEW'; -UPDATE regprc.registration SET last_success_stage_name = 'SecurezoneNotificationStage' where latest_trn_type_code='UPLOAD_PACKET' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and reg_type = 'NEW'; -UPDATE regprc.registration SET last_success_stage_name = 'PacketUploaderStage' where latest_trn_type_code='VALIDATE_PACKET' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and reg_type = 'NEW'; -UPDATE regprc.registration SET last_success_stage_name = 'PacketValidatorStage' where latest_trn_type_code='PACKET_CLASSIFICATION' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and reg_type = 'NEW'; -UPDATE regprc.registration SET last_success_stage_name = 'PacketClassifierStage' where latest_trn_type_code='QUALITY_CHECK' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and reg_type = 'NEW'; -UPDATE regprc.registration SET last_success_stage_name = 'QualityCheckerStage' where latest_trn_type_code='OSI_VALIDATE' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and reg_type = 'NEW'; -UPDATE regprc.registration SET last_success_stage_name = 'OSIValidatorStage' where latest_trn_type_code='EXTERNAL_INTEGRATION' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and reg_type = 'NEW'; -UPDATE regprc.registration SET last_success_stage_name = 'ExternalStage' where latest_trn_type_code='DEMOGRAPHIC_VERIFICATION' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and reg_type = 'NEW'; -UPDATE regprc.registration SET last_success_stage_name = 'DemoDedupeStage' where latest_trn_type_code='BIOGRAPHIC_VERIFICATION' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and reg_type = 'NEW'; -UPDATE regprc.registration SET last_success_stage_name = 'BioDedupeStage' where latest_trn_type_code='MANUAL_VERIFICATION' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and reg_type = 'NEW'; -UPDATE regprc.registration SET last_success_stage_name = 'BioDedupeStage' where latest_trn_type_code='UIN_GENERATOR' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and reg_type = 'NEW'; -UPDATE regprc.registration SET last_success_stage_name = 'UinGeneratorStage' where latest_trn_type_code='PRINT_SERVICE' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and reg_type = 'NEW'; - -UPDATE regprc.registration SET last_success_stage_name = 'PacketReceiverStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='SecurezoneNotificationStage' and reg_type = 'NEW'; -UPDATE regprc.registration SET last_success_stage_name = 'SecurezoneNotificationStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='PacketUploaderStage' and reg_type = 'NEW'; -UPDATE regprc.registration SET last_success_stage_name = 'PacketUploaderStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='PacketValidatorStage' and reg_type = 'NEW'; -UPDATE regprc.registration SET last_success_stage_name = 'PacketValidatorStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='PacketClassifierStage' and reg_type = 'NEW'; -UPDATE regprc.registration SET last_success_stage_name = 'PacketClassifierStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='QualityCheckerStage' and reg_type = 'NEW'; -UPDATE regprc.registration SET last_success_stage_name = 'QualityCheckerStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='OSIValidatorStage' and reg_type = 'NEW'; -UPDATE regprc.registration SET last_success_stage_name = 'OSIValidatorStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='ExternalStage' and reg_type = 'NEW'; -UPDATE regprc.registration SET last_success_stage_name = 'ExternalStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='DemoDedupeStage' and reg_type = 'NEW'; -UPDATE regprc.registration SET last_success_stage_name = 'DemoDedupeStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='BioDedupeStage' and reg_type = 'NEW'; -UPDATE regprc.registration SET last_success_stage_name = 'BioDedupeStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='ManualVerificationStage' and reg_type = 'NEW'; -UPDATE regprc.registration SET last_success_stage_name = 'BioDedupeStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='UinGeneratorStage' and reg_type = 'NEW'; -UPDATE regprc.registration SET last_success_stage_name = 'UinGeneratorStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='PrintingStage' and reg_type = 'NEW'; - -UPDATE regprc.registration SET last_success_stage_name = 'PacketReceiverStage' where latest_trn_type_code='SECUREZONE_NOTIFICATION' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and reg_type = 'UPDATE'; -UPDATE regprc.registration SET last_success_stage_name = 'SecurezoneNotificationStage' where latest_trn_type_code='UPLOAD_PACKET' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and reg_type = 'UPDATE'; -UPDATE regprc.registration SET last_success_stage_name = 'PacketUploaderStage' where latest_trn_type_code='VALIDATE_PACKET' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and reg_type = 'UPDATE'; -UPDATE regprc.registration SET last_success_stage_name = 'PacketValidatorStage' where latest_trn_type_code='PACKET_CLASSIFICATION' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and reg_type = 'UPDATE'; -UPDATE regprc.registration SET last_success_stage_name = 'PacketClassifierStage' where latest_trn_type_code='QUALITY_CHECK' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and reg_type = 'UPDATE'; -UPDATE regprc.registration SET last_success_stage_name = 'QualityCheckerStage' where latest_trn_type_code='OSI_VALIDATE' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and reg_type = 'UPDATE'; -UPDATE regprc.registration SET last_success_stage_name = 'OSIValidatorStage' where latest_trn_type_code='BIOMETRIC_AUTHENTICATION' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and reg_type = 'UPDATE'; -UPDATE regprc.registration SET last_success_stage_name = 'BiometricAuthenticationStage' where latest_trn_type_code='DEMOGRAPHIC_VERIFICATION' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and reg_type = 'UPDATE'; -UPDATE regprc.registration SET last_success_stage_name = 'DemoDedupeStage' where latest_trn_type_code='BIOGRAPHIC_VERIFICATION' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and reg_type = 'UPDATE'; -UPDATE regprc.registration SET last_success_stage_name = 'BioDedupeStage' where latest_trn_type_code='MANUAL_VERIFICATION' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and reg_type = 'UPDATE'; -UPDATE regprc.registration SET last_success_stage_name = 'BioDedupeStage' where latest_trn_type_code='UIN_GENERATOR' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and reg_type = 'UPDATE'; -UPDATE regprc.registration SET last_success_stage_name = 'UinGeneratorStage' where latest_trn_type_code='PRINT_SERVICE' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and reg_type = 'UPDATE'; - -UPDATE regprc.registration SET last_success_stage_name = 'PacketReceiverStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='SecurezoneNotificationStage' and reg_type = 'UPDATE'; -UPDATE regprc.registration SET last_success_stage_name = 'SecurezoneNotificationStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='PacketUploaderStage' and reg_type = 'UPDATE'; -UPDATE regprc.registration SET last_success_stage_name = 'PacketUploaderStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='PacketValidatorStage' and reg_type = 'UPDATE'; -UPDATE regprc.registration SET last_success_stage_name = 'PacketValidatorStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='PacketClassifierStage' and reg_type = 'UPDATE'; -UPDATE regprc.registration SET last_success_stage_name = 'PacketClassifierStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='QualityCheckerStage' and reg_type = 'UPDATE'; -UPDATE regprc.registration SET last_success_stage_name = 'QualityCheckerStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='OSIValidatorStage' and reg_type = 'UPDATE'; -UPDATE regprc.registration SET last_success_stage_name = 'OSIValidatorStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='BiometricAuthenticationStage' and reg_type = 'UPDATE'; -UPDATE regprc.registration SET last_success_stage_name = 'BiometricAuthenticationStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='DemoDedupeStage' and reg_type = 'UPDATE'; -UPDATE regprc.registration SET last_success_stage_name = 'DemoDedupeStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='BioDedupeStage' and reg_type = 'UPDATE'; -UPDATE regprc.registration SET last_success_stage_name = 'BioDedupeStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='ManualVerificationStage' and reg_type = 'UPDATE'; -UPDATE regprc.registration SET last_success_stage_name = 'BioDedupeStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='UinGeneratorStage' and reg_type = 'UPDATE'; -UPDATE regprc.registration SET last_success_stage_name = 'UinGeneratorStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='PrintingStage' and reg_type = 'UPDATE'; - -UPDATE regprc.registration SET last_success_stage_name = 'PacketReceiverStage' where latest_trn_type_code='SECUREZONE_NOTIFICATION' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and reg_type = 'LOST'; -UPDATE regprc.registration SET last_success_stage_name = 'SecurezoneNotificationStage' where latest_trn_type_code='UPLOAD_PACKET' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and reg_type = 'LOST'; -UPDATE regprc.registration SET last_success_stage_name = 'PacketUploaderStage' where latest_trn_type_code='VALIDATE_PACKET' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and reg_type = 'LOST'; -UPDATE regprc.registration SET last_success_stage_name = 'PacketValidatorStage' where latest_trn_type_code='PACKET_CLASSIFICATION' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and reg_type = 'LOST'; -UPDATE regprc.registration SET last_success_stage_name = 'PacketClassifierStage' where latest_trn_type_code='QUALITY_CHECK' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and reg_type = 'LOST'; -UPDATE regprc.registration SET last_success_stage_name = 'QualityCheckerStage' where latest_trn_type_code='OSI_VALIDATE' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and reg_type = 'LOST'; -UPDATE regprc.registration SET last_success_stage_name = 'OSIValidatorStage' where latest_trn_type_code='BIOGRAPHIC_VERIFICATION' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and reg_type = 'LOST'; -UPDATE regprc.registration SET last_success_stage_name = 'BioDedupeStage' where latest_trn_type_code='MANUAL_VERIFICATION' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and reg_type = 'LOST'; -UPDATE regprc.registration SET last_success_stage_name = 'BioDedupeStage' where latest_trn_type_code='UIN_GENERATOR' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and reg_type = 'LOST'; -UPDATE regprc.registration SET last_success_stage_name = 'UinGeneratorStage' where latest_trn_type_code='PRINT_SERVICE' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and reg_type = 'LOST'; - -UPDATE regprc.registration SET last_success_stage_name = 'PacketReceiverStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='SecurezoneNotificationStage' and reg_type = 'LOST'; -UPDATE regprc.registration SET last_success_stage_name = 'SecurezoneNotificationStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='PacketUploaderStage' and reg_type = 'LOST'; -UPDATE regprc.registration SET last_success_stage_name = 'PacketUploaderStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='PacketValidatorStage' and reg_type = 'LOST'; -UPDATE regprc.registration SET last_success_stage_name = 'PacketValidatorStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='PacketClassifierStage' and reg_type = 'LOST'; -UPDATE regprc.registration SET last_success_stage_name = 'PacketClassifierStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='QualityCheckerStage' and reg_type = 'LOST'; -UPDATE regprc.registration SET last_success_stage_name = 'QualityCheckerStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='OSIValidatorStage' and reg_type = 'LOST'; -UPDATE regprc.registration SET last_success_stage_name = 'OSIValidatorStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='BioDedupeStage' and reg_type = 'LOST'; -UPDATE regprc.registration SET last_success_stage_name = 'BioDedupeStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='ManualVerificationStage' and reg_type = 'LOST'; -UPDATE regprc.registration SET last_success_stage_name = 'BioDedupeStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='UinGeneratorStage' and reg_type = 'LOST'; -UPDATE regprc.registration SET last_success_stage_name = 'UinGeneratorStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='PrintingStage' and reg_type = 'LOST'; - -UPDATE regprc.registration SET last_success_stage_name = 'PacketReceiverStage' where latest_trn_type_code='SECUREZONE_NOTIFICATION' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and reg_type = 'RES_UPDATE'; -UPDATE regprc.registration SET last_success_stage_name = 'SecurezoneNotificationStage' where latest_trn_type_code='UPLOAD_PACKET' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and reg_type = 'RES_UPDATE'; -UPDATE regprc.registration SET last_success_stage_name = 'PacketUploaderStage' where latest_trn_type_code='VALIDATE_PACKET' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and reg_type = 'RES_UPDATE'; -UPDATE regprc.registration SET last_success_stage_name = 'PacketValidatorStage' where latest_trn_type_code='DEMOGRAPHIC_VERIFICATION' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and reg_type = 'RES_UPDATE'; -UPDATE regprc.registration SET last_success_stage_name = 'DemoDedupeStage' where latest_trn_type_code='MANUAL_VERIFICATION' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and reg_type = 'RES_UPDATE'; -UPDATE regprc.registration SET last_success_stage_name = 'DemoDedupeStage' where latest_trn_type_code='UIN_GENERATOR' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and reg_type = 'RES_UPDATE'; -UPDATE regprc.registration SET last_success_stage_name = 'UinGeneratorStage' where latest_trn_type_code='PRINT_SERVICE' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and reg_type = 'RES_UPDATE'; - -UPDATE regprc.registration SET last_success_stage_name = 'PacketReceiverStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='SecurezoneNotificationStage' and reg_type = 'RES_UPDATE'; -UPDATE regprc.registration SET last_success_stage_name = 'SecurezoneNotificationStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='PacketUploaderStage' and reg_type = 'RES_UPDATE'; -UPDATE regprc.registration SET last_success_stage_name = 'PacketUploaderStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='PacketValidatorStage' and reg_type = 'RES_UPDATE'; -UPDATE regprc.registration SET last_success_stage_name = 'PacketValidatorStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='DemoDedupeStage' and reg_type = 'RES_UPDATE'; -UPDATE regprc.registration SET last_success_stage_name = 'DemoDedupeStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='ManualVerificationStage' and reg_type = 'RES_UPDATE'; -UPDATE regprc.registration SET last_success_stage_name = 'DemoDedupeStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='UinGeneratorStage' and reg_type = 'RES_UPDATE'; -UPDATE regprc.registration SET last_success_stage_name = 'UinGeneratorStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='PrintingStage' and reg_type = 'RES_UPDATE'; - -UPDATE regprc.registration SET last_success_stage_name = 'PacketReceiverStage' where latest_trn_type_code='SECUREZONE_NOTIFICATION' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and reg_type = 'RES_REPRINT'; -UPDATE regprc.registration SET last_success_stage_name = 'SecurezoneNotificationStage' where latest_trn_type_code='UPLOAD_PACKET' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and reg_type = 'RES_REPRINT'; -UPDATE regprc.registration SET last_success_stage_name = 'PacketUploaderStage' where latest_trn_type_code='PRINT_SERVICE' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and reg_type = 'RES_REPRINT'; - -UPDATE regprc.registration SET last_success_stage_name = 'PacketReceiverStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='SecurezoneNotificationStage' and reg_type = 'RES_REPRINT'; -UPDATE regprc.registration SET last_success_stage_name = 'SecurezoneNotificationStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='PacketUploaderStage' and reg_type = 'RES_REPRINT'; -UPDATE regprc.registration SET last_success_stage_name = 'PacketUploaderStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='PrintingStage' and reg_type = 'RES_REPRINT'; - -UPDATE regprc.registration SET last_success_stage_name = 'PacketReceiverStage' where latest_trn_type_code='SECUREZONE_NOTIFICATION' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and reg_type= 'ACTIVATED'; -UPDATE regprc.registration SET last_success_stage_name = 'SecurezoneNotificationStage' where latest_trn_type_code='UPLOAD_PACKET' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and reg_type= 'ACTIVATED'; -UPDATE regprc.registration SET last_success_stage_name = 'PacketUploaderStage' where latest_trn_type_code='UIN_GENERATOR' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and reg_type= 'ACTIVATED'; -UPDATE regprc.registration SET last_success_stage_name = 'UinGeneratorStage' where latest_trn_type_code='PRINT_SERVICE' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and reg_type= 'ACTIVATED'; - -UPDATE regprc.registration SET last_success_stage_name = 'PacketReceiverStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='SecurezoneNotificationStage' and reg_type= 'ACTIVATED'; -UPDATE regprc.registration SET last_success_stage_name = 'SecurezoneNotificationStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='PacketUploaderStage' and reg_type= 'ACTIVATED'; -UPDATE regprc.registration SET last_success_stage_name = 'PacketUploaderStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='UinGeneratorStage' and reg_type= 'ACTIVATED'; -UPDATE regprc.registration SET last_success_stage_name = 'UinGeneratorStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='PrintingStage' and reg_type= 'ACTIVATED'; - -UPDATE regprc.registration SET last_success_stage_name = 'PacketReceiverStage' where latest_trn_type_code='SECUREZONE_NOTIFICATION' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and reg_type ='DEACTIVATED'; -UPDATE regprc.registration SET last_success_stage_name = 'SecurezoneNotificationStage' where latest_trn_type_code='UPLOAD_PACKET' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and reg_type ='DEACTIVATED'; -UPDATE regprc.registration SET last_success_stage_name = 'PacketUploaderStage' where latest_trn_type_code='UIN_GENERATOR' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and reg_type ='DEACTIVATED'; -UPDATE regprc.registration SET last_success_stage_name = 'UinGeneratorStage' where latest_trn_type_code='PRINT_SERVICE' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and reg_type ='DEACTIVATED'; - -UPDATE regprc.registration SET last_success_stage_name = 'PacketReceiverStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='SecurezoneNotificationStage' and reg_type ='DEACTIVATED'; -UPDATE regprc.registration SET last_success_stage_name = 'SecurezoneNotificationStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='PacketUploaderStage' and reg_type ='DEACTIVATED'; -UPDATE regprc.registration SET last_success_stage_name = 'PacketUploaderStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='UinGeneratorStage' and reg_type = 'DEACTIVATED'; -UPDATE regprc.registration SET last_success_stage_name = 'UinGeneratorStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='PrintingStage' and reg_type = 'DEACTIVATED'; +UPDATE regprc.registration SET last_success_stage_name = 'PacketReceiverStage' where latest_trn_type_code='SECUREZONE_NOTIFICATION' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'NEW'; +UPDATE regprc.registration SET last_success_stage_name = 'SecurezoneNotificationStage' where latest_trn_type_code='UPLOAD_PACKET' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'NEW'; +UPDATE regprc.registration SET last_success_stage_name = 'PacketUploaderStage' where latest_trn_type_code='VALIDATE_PACKET' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'NEW'; +UPDATE regprc.registration SET last_success_stage_name = 'PacketValidatorStage' where latest_trn_type_code='PACKET_CLASSIFICATION' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'NEW'; +UPDATE regprc.registration SET last_success_stage_name = 'PacketClassifierStage' where latest_trn_type_code='QUALITY_CHECK' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'NEW'; +UPDATE regprc.registration SET last_success_stage_name = 'QualityCheckerStage' where latest_trn_type_code='OSI_VALIDATE' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'NEW'; +UPDATE regprc.registration SET last_success_stage_name = 'OSIValidatorStage' where latest_trn_type_code='EXTERNAL_INTEGRATION' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'NEW'; +UPDATE regprc.registration SET last_success_stage_name = 'ExternalStage' where latest_trn_type_code='DEMOGRAPHIC_VERIFICATION' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'NEW'; +UPDATE regprc.registration SET last_success_stage_name = 'DemoDedupeStage' where latest_trn_type_code='BIOGRAPHIC_VERIFICATION' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'NEW'; +UPDATE regprc.registration SET last_success_stage_name = 'BioDedupeStage' where latest_trn_type_code='MANUAL_VERIFICATION' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'NEW'; +UPDATE regprc.registration SET last_success_stage_name = 'BioDedupeStage' where latest_trn_type_code='UIN_GENERATOR' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'NEW'; +UPDATE regprc.registration SET last_success_stage_name = 'UinGeneratorStage' where latest_trn_type_code='PRINT_SERVICE' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'NEW'; + +UPDATE regprc.registration SET last_success_stage_name = 'PacketReceiverStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='SecurezoneNotificationStage' and process = 'NEW'; +UPDATE regprc.registration SET last_success_stage_name = 'SecurezoneNotificationStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='PacketUploaderStage' and process = 'NEW'; +UPDATE regprc.registration SET last_success_stage_name = 'PacketUploaderStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='PacketValidatorStage' and process = 'NEW'; +UPDATE regprc.registration SET last_success_stage_name = 'PacketValidatorStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='PacketClassifierStage' and process = 'NEW'; +UPDATE regprc.registration SET last_success_stage_name = 'PacketClassifierStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='QualityCheckerStage' and process = 'NEW'; +UPDATE regprc.registration SET last_success_stage_name = 'QualityCheckerStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='OSIValidatorStage' and process = 'NEW'; +UPDATE regprc.registration SET last_success_stage_name = 'OSIValidatorStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='ExternalStage' and process = 'NEW'; +UPDATE regprc.registration SET last_success_stage_name = 'ExternalStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='DemoDedupeStage' and process = 'NEW'; +UPDATE regprc.registration SET last_success_stage_name = 'DemoDedupeStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='BioDedupeStage' and process = 'NEW'; +UPDATE regprc.registration SET last_success_stage_name = 'BioDedupeStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='ManualVerificationStage' and process = 'NEW'; +UPDATE regprc.registration SET last_success_stage_name = 'BioDedupeStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='UinGeneratorStage' and process = 'NEW'; +UPDATE regprc.registration SET last_success_stage_name = 'UinGeneratorStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='PrintingStage' and process = 'NEW'; + +UPDATE regprc.registration SET last_success_stage_name = 'PacketReceiverStage' where latest_trn_type_code='SECUREZONE_NOTIFICATION' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'UPDATE'; +UPDATE regprc.registration SET last_success_stage_name = 'SecurezoneNotificationStage' where latest_trn_type_code='UPLOAD_PACKET' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'UPDATE'; +UPDATE regprc.registration SET last_success_stage_name = 'PacketUploaderStage' where latest_trn_type_code='VALIDATE_PACKET' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'UPDATE'; +UPDATE regprc.registration SET last_success_stage_name = 'PacketValidatorStage' where latest_trn_type_code='PACKET_CLASSIFICATION' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'UPDATE'; +UPDATE regprc.registration SET last_success_stage_name = 'PacketClassifierStage' where latest_trn_type_code='QUALITY_CHECK' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'UPDATE'; +UPDATE regprc.registration SET last_success_stage_name = 'QualityCheckerStage' where latest_trn_type_code='OSI_VALIDATE' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'UPDATE'; +UPDATE regprc.registration SET last_success_stage_name = 'OSIValidatorStage' where latest_trn_type_code='BIOMETRIC_AUTHENTICATION' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'UPDATE'; +UPDATE regprc.registration SET last_success_stage_name = 'BiometricAuthenticationStage' where latest_trn_type_code='DEMOGRAPHIC_VERIFICATION' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'UPDATE'; +UPDATE regprc.registration SET last_success_stage_name = 'DemoDedupeStage' where latest_trn_type_code='BIOGRAPHIC_VERIFICATION' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'UPDATE'; +UPDATE regprc.registration SET last_success_stage_name = 'BioDedupeStage' where latest_trn_type_code='MANUAL_VERIFICATION' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'UPDATE'; +UPDATE regprc.registration SET last_success_stage_name = 'BioDedupeStage' where latest_trn_type_code='UIN_GENERATOR' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'UPDATE'; +UPDATE regprc.registration SET last_success_stage_name = 'UinGeneratorStage' where latest_trn_type_code='PRINT_SERVICE' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'UPDATE'; + +UPDATE regprc.registration SET last_success_stage_name = 'PacketReceiverStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='SecurezoneNotificationStage' and process = 'UPDATE'; +UPDATE regprc.registration SET last_success_stage_name = 'SecurezoneNotificationStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='PacketUploaderStage' and process = 'UPDATE'; +UPDATE regprc.registration SET last_success_stage_name = 'PacketUploaderStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='PacketValidatorStage' and process = 'UPDATE'; +UPDATE regprc.registration SET last_success_stage_name = 'PacketValidatorStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='PacketClassifierStage' and process = 'UPDATE'; +UPDATE regprc.registration SET last_success_stage_name = 'PacketClassifierStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='QualityCheckerStage' and process = 'UPDATE'; +UPDATE regprc.registration SET last_success_stage_name = 'QualityCheckerStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='OSIValidatorStage' and process = 'UPDATE'; +UPDATE regprc.registration SET last_success_stage_name = 'OSIValidatorStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='BiometricAuthenticationStage' and process = 'UPDATE'; +UPDATE regprc.registration SET last_success_stage_name = 'BiometricAuthenticationStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='DemoDedupeStage' and process = 'UPDATE'; +UPDATE regprc.registration SET last_success_stage_name = 'DemoDedupeStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='BioDedupeStage' and process = 'UPDATE'; +UPDATE regprc.registration SET last_success_stage_name = 'BioDedupeStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='ManualVerificationStage' and process = 'UPDATE'; +UPDATE regprc.registration SET last_success_stage_name = 'BioDedupeStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='UinGeneratorStage' and process = 'UPDATE'; +UPDATE regprc.registration SET last_success_stage_name = 'UinGeneratorStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='PrintingStage' and process = 'UPDATE'; + +UPDATE regprc.registration SET last_success_stage_name = 'PacketReceiverStage' where latest_trn_type_code='SECUREZONE_NOTIFICATION' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'LOST'; +UPDATE regprc.registration SET last_success_stage_name = 'SecurezoneNotificationStage' where latest_trn_type_code='UPLOAD_PACKET' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'LOST'; +UPDATE regprc.registration SET last_success_stage_name = 'PacketUploaderStage' where latest_trn_type_code='VALIDATE_PACKET' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'LOST'; +UPDATE regprc.registration SET last_success_stage_name = 'PacketValidatorStage' where latest_trn_type_code='PACKET_CLASSIFICATION' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'LOST'; +UPDATE regprc.registration SET last_success_stage_name = 'PacketClassifierStage' where latest_trn_type_code='QUALITY_CHECK' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'LOST'; +UPDATE regprc.registration SET last_success_stage_name = 'QualityCheckerStage' where latest_trn_type_code='OSI_VALIDATE' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'LOST'; +UPDATE regprc.registration SET last_success_stage_name = 'OSIValidatorStage' where latest_trn_type_code='BIOGRAPHIC_VERIFICATION' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'LOST'; +UPDATE regprc.registration SET last_success_stage_name = 'BioDedupeStage' where latest_trn_type_code='MANUAL_VERIFICATION' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'LOST'; +UPDATE regprc.registration SET last_success_stage_name = 'BioDedupeStage' where latest_trn_type_code='UIN_GENERATOR' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'LOST'; +UPDATE regprc.registration SET last_success_stage_name = 'UinGeneratorStage' where latest_trn_type_code='PRINT_SERVICE' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'LOST'; + +UPDATE regprc.registration SET last_success_stage_name = 'PacketReceiverStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='SecurezoneNotificationStage' and process = 'LOST'; +UPDATE regprc.registration SET last_success_stage_name = 'SecurezoneNotificationStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='PacketUploaderStage' and process = 'LOST'; +UPDATE regprc.registration SET last_success_stage_name = 'PacketUploaderStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='PacketValidatorStage' and process = 'LOST'; +UPDATE regprc.registration SET last_success_stage_name = 'PacketValidatorStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='PacketClassifierStage' and process = 'LOST'; +UPDATE regprc.registration SET last_success_stage_name = 'PacketClassifierStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='QualityCheckerStage' and process = 'LOST'; +UPDATE regprc.registration SET last_success_stage_name = 'QualityCheckerStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='OSIValidatorStage' and process = 'LOST'; +UPDATE regprc.registration SET last_success_stage_name = 'OSIValidatorStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='BioDedupeStage' and process = 'LOST'; +UPDATE regprc.registration SET last_success_stage_name = 'BioDedupeStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='ManualVerificationStage' and process = 'LOST'; +UPDATE regprc.registration SET last_success_stage_name = 'BioDedupeStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='UinGeneratorStage' and process = 'LOST'; +UPDATE regprc.registration SET last_success_stage_name = 'UinGeneratorStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='PrintingStage' and process = 'LOST'; + +UPDATE regprc.registration SET last_success_stage_name = 'PacketReceiverStage' where latest_trn_type_code='SECUREZONE_NOTIFICATION' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'RES_UPDATE'; +UPDATE regprc.registration SET last_success_stage_name = 'SecurezoneNotificationStage' where latest_trn_type_code='UPLOAD_PACKET' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'RES_UPDATE'; +UPDATE regprc.registration SET last_success_stage_name = 'PacketUploaderStage' where latest_trn_type_code='VALIDATE_PACKET' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'RES_UPDATE'; +UPDATE regprc.registration SET last_success_stage_name = 'PacketValidatorStage' where latest_trn_type_code='DEMOGRAPHIC_VERIFICATION' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'RES_UPDATE'; +UPDATE regprc.registration SET last_success_stage_name = 'DemoDedupeStage' where latest_trn_type_code='MANUAL_VERIFICATION' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'RES_UPDATE'; +UPDATE regprc.registration SET last_success_stage_name = 'DemoDedupeStage' where latest_trn_type_code='UIN_GENERATOR' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'RES_UPDATE'; +UPDATE regprc.registration SET last_success_stage_name = 'UinGeneratorStage' where latest_trn_type_code='PRINT_SERVICE' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'RES_UPDATE'; + +UPDATE regprc.registration SET last_success_stage_name = 'PacketReceiverStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='SecurezoneNotificationStage' and process = 'RES_UPDATE'; +UPDATE regprc.registration SET last_success_stage_name = 'SecurezoneNotificationStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='PacketUploaderStage' and process = 'RES_UPDATE'; +UPDATE regprc.registration SET last_success_stage_name = 'PacketUploaderStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='PacketValidatorStage' and process = 'RES_UPDATE'; +UPDATE regprc.registration SET last_success_stage_name = 'PacketValidatorStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='DemoDedupeStage' and process = 'RES_UPDATE'; +UPDATE regprc.registration SET last_success_stage_name = 'DemoDedupeStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='ManualVerificationStage' and process = 'RES_UPDATE'; +UPDATE regprc.registration SET last_success_stage_name = 'DemoDedupeStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='UinGeneratorStage' and process = 'RES_UPDATE'; +UPDATE regprc.registration SET last_success_stage_name = 'UinGeneratorStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='PrintingStage' and process = 'RES_UPDATE'; + +UPDATE regprc.registration SET last_success_stage_name = 'PacketReceiverStage' where latest_trn_type_code='SECUREZONE_NOTIFICATION' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'RES_REPRINT'; +UPDATE regprc.registration SET last_success_stage_name = 'SecurezoneNotificationStage' where latest_trn_type_code='UPLOAD_PACKET' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'RES_REPRINT'; +UPDATE regprc.registration SET last_success_stage_name = 'PacketUploaderStage' where latest_trn_type_code='PRINT_SERVICE' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'RES_REPRINT'; + +UPDATE regprc.registration SET last_success_stage_name = 'PacketReceiverStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='SecurezoneNotificationStage' and process = 'RES_REPRINT'; +UPDATE regprc.registration SET last_success_stage_name = 'SecurezoneNotificationStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='PacketUploaderStage' and process = 'RES_REPRINT'; +UPDATE regprc.registration SET last_success_stage_name = 'PacketUploaderStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='PrintingStage' and process = 'RES_REPRINT'; + +UPDATE regprc.registration SET last_success_stage_name = 'PacketReceiverStage' where latest_trn_type_code='SECUREZONE_NOTIFICATION' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process= 'ACTIVATED'; +UPDATE regprc.registration SET last_success_stage_name = 'SecurezoneNotificationStage' where latest_trn_type_code='UPLOAD_PACKET' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process= 'ACTIVATED'; +UPDATE regprc.registration SET last_success_stage_name = 'PacketUploaderStage' where latest_trn_type_code='UIN_GENERATOR' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process= 'ACTIVATED'; +UPDATE regprc.registration SET last_success_stage_name = 'UinGeneratorStage' where latest_trn_type_code='PRINT_SERVICE' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process= 'ACTIVATED'; + +UPDATE regprc.registration SET last_success_stage_name = 'PacketReceiverStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='SecurezoneNotificationStage' and process= 'ACTIVATED'; +UPDATE regprc.registration SET last_success_stage_name = 'SecurezoneNotificationStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='PacketUploaderStage' and process= 'ACTIVATED'; +UPDATE regprc.registration SET last_success_stage_name = 'PacketUploaderStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='UinGeneratorStage' and process= 'ACTIVATED'; +UPDATE regprc.registration SET last_success_stage_name = 'UinGeneratorStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='PrintingStage' and process= 'ACTIVATED'; + +UPDATE regprc.registration SET last_success_stage_name = 'PacketReceiverStage' where latest_trn_type_code='SECUREZONE_NOTIFICATION' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process ='DEACTIVATED'; +UPDATE regprc.registration SET last_success_stage_name = 'SecurezoneNotificationStage' where latest_trn_type_code='UPLOAD_PACKET' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process ='DEACTIVATED'; +UPDATE regprc.registration SET last_success_stage_name = 'PacketUploaderStage' where latest_trn_type_code='UIN_GENERATOR' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process ='DEACTIVATED'; +UPDATE regprc.registration SET last_success_stage_name = 'UinGeneratorStage' where latest_trn_type_code='PRINT_SERVICE' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process ='DEACTIVATED'; + +UPDATE regprc.registration SET last_success_stage_name = 'PacketReceiverStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='SecurezoneNotificationStage' and process ='DEACTIVATED'; +UPDATE regprc.registration SET last_success_stage_name = 'SecurezoneNotificationStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='PacketUploaderStage' and process ='DEACTIVATED'; +UPDATE regprc.registration SET last_success_stage_name = 'PacketUploaderStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='UinGeneratorStage' and process = 'DEACTIVATED'; +UPDATE regprc.registration SET last_success_stage_name = 'UinGeneratorStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='PrintingStage' and process = 'DEACTIVATED'; ------------------------------------------------------------------------------------------------------------------------------------- -------------------------------------------------------Add columns to registration_list---------------------------------------------- From abf5a6d5ee537a926f20d35e77d348886b4788b7 Mon Sep 17 00:00:00 2001 From: JyotiPrakashNayak Date: Thu, 7 Apr 2022 14:31:18 +0530 Subject: [PATCH 009/133] MOSIP-21075_modified release script (#1502) * Update 1.2_regprc-scripts_release.sql * Update regprc-individual_demographic_dedup.sql * MOSIP-21075_modified release script --- .../sql/1.2_regprc-scripts_release.sql | 67 ++++++++++--------- .../regprc-individual_demographic_dedup.sql | 3 +- 2 files changed, 38 insertions(+), 32 deletions(-) diff --git a/db_release_scripts/mosip_regprc/sql/1.2_regprc-scripts_release.sql b/db_release_scripts/mosip_regprc/sql/1.2_regprc-scripts_release.sql index ea476c245da..c264a66f7c8 100644 --- a/db_release_scripts/mosip_regprc/sql/1.2_regprc-scripts_release.sql +++ b/db_release_scripts/mosip_regprc/sql/1.2_regprc-scripts_release.sql @@ -18,6 +18,7 @@ -- 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 @@ -33,6 +34,8 @@ ALTER TABLE regprc.registration_transaction DROP CONSTRAINT IF EXISTS fk_regtrn_ \ir ../ddl/regprc-anonymous_profile.sql +\ir ../ddl/regprc-reg_verification.sql + 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); @@ -65,20 +68,24 @@ UPDATE regprc.reg_manual_verification a SET workflow_instance_id = b.workflow_in UPDATE regprc.reg_lost_uin_det a SET workflow_instance_id = b.workflow_instance_id FROM regprc.registration_list b WHERE a.reg_id = b.reg_id; UPDATE regprc.reg_bio_ref a SET workflow_instance_id = b.workflow_instance_id FROM regprc.registration_list b WHERE a.reg_id = b.reg_id; -create index idx_rbioref_crdtimes on regprc.reg_bio_ref (cr_dtimes); - -DROP INDEX idx_idemogd_namedobgender; -create index idx_idemogd_namedobgender on regprc.individual_demographic_dedup (name, dob,gender); - -create index idx_rbioref_crdtimes on regprc.reg_bio_ref (cr_dtimes); - -create index idx_rmanvrn_reqid on regprc.reg_manual_verification (request_id); - -DROP INDEX idx_rgstrn_ltstrbcode_ltststscode; -CREATE INDEX idx_reg_upd_trn_dtimes_asc ON regprc.registration USING btree (upd_dtimes asc,latest_trn_dtimes asc) -create index idx_rgstrnlst_pcktid on regprc.registration_list (packet_id); -create index idx_rgstrnlst_aireqid on regprc.registration_list (additional_info_req_id); -create index idx_reg_verification_reqId on regprc.reg_verification (verification_req_id); +CREATE INDEX IF NOT EXISTS idx_rbioref_crdtimes on regprc.reg_bio_ref (cr_dtimes); +CREATE INDEX IF NOT EXISTS idx_bio_ref_id ON regprc.reg_bio_ref USING btree (bio_ref_id); +DROP INDEX IF EXISTS idx_idemogd_namedobgender; +CREATE INDEX IF NOT EXISTS idx_idemogd_namedobgender on regprc.individual_demographic_dedup (name, dob,gender); +CREATE INDEX IF NOT EXISTS idx_rbioref_crdtimes on regprc.reg_bio_ref (cr_dtimes); +CREATE INDEX IF NOT EXISTS idx_rmanvrn_reqid on regprc.reg_manual_verification (request_id); +DROP INDEX IF EXISTS idx_rgstrn_ltstrbcode_ltststscode; +CREATE INDEX IF NOT EXISTS idx_rgstrn_ltstrbcode_ltststscode on regprc.registration (latest_trn_dtimes, latest_trn_status_code); +CREATE INDEX IF NOT EXISTS idx_reg_latest_trn_dtimes ON regprc.registration USING btree (latest_trn_dtimes); +CREATE INDEX IF NOT EXISTS idx_rgstrnlst_pcktid on regprc.registration_list (packet_id); +CREATE INDEX IF NOT EXISTS idx_rgstrnlst_aireqid on regprc.registration_list (additional_info_req_id); +CREATE INDEX IF NOT EXISTS idx_reg_verification_reqId on regprc.reg_verification (verification_req_id); +CREATE INDEX IF NOT EXISTS idx_reg_trn_reg_id ON regprc.registration_transaction USING btree (reg_id); +CREATE INDEX IF NOT EXISTS idx_reg_trn_status_code ON regprc.registration_transaction USING btree (status_code); +CREATE INDEX IF NOT EXISTS idx_reg_trn_trntypecode ON regprc.registration_transaction USING btree (trn_type_code); +CREATE INDEX IF NOT EXISTS idx_reg_trn_upd_dtimes ON regprc.registration_transaction USING btree (upd_dtimes); +CREATE INDEX IF NOT EXISTS idx_user_detail_cntr_id ON regprc.abis_request USING btree (bio_ref_id); +CREATE INDEX IF NOT EXISTS idx_abis_req_regtrn_id ON regprc.abis_request USING btree (ref_regtrn_id); ALTER TABLE regprc.individual_demographic_dedup DROP CONSTRAINT pk_idemogd_id; ALTER TABLE regprc.individual_demographic_dedup ALTER COLUMN workflow_instance_id SET NOT NULL; @@ -96,7 +103,7 @@ ALTER TABLE regprc.reg_manual_verification DROP CONSTRAINT pk_rmnlver_id; ALTER TABLE regprc.reg_manual_verification ALTER COLUMN workflow_instance_id SET NOT NULL; ALTER TABLE regprc.reg_manual_verification ADD CONSTRAINT pk_rmnlver_id PRIMARY KEY (workflow_instance_id,matched_ref_id,matched_ref_type); -ALTER TABLE regprc.registration DROP CONSTRAINT pk_reg_id; +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); @@ -140,7 +147,21 @@ TRUNCATE TABLE regprc.transaction_type cascade ; ALTER TABLE regprc.registration ADD COLUMN last_success_stage_name CHARACTER VARYING(50); -ALTER TABLE regprc.reg_manual_verification RENAME TO reg_manual_adjudication; +-------------------------------------------------------Add columns to registration_list---------------------------------------------- + +ALTER TABLE regprc.registration_list ADD COLUMN name character varying; +ALTER TABLE regprc.registration_list ADD COLUMN phone character varying; +ALTER TABLE regprc.registration_list ADD COLUMN email character varying; +ALTER TABLE regprc.registration_list ADD COLUMN center_id character varying; +ALTER TABLE regprc.registration_list ADD COLUMN registration_date date; +ALTER TABLE regprc.registration_list ADD COLUMN location_code character varying; + +------------------------------------------------------------------------------------------------------------------------------------------- +-------------------------------------------------Creation of crypto salt table-------------------------------------------------------------- + +\ir ../ddl/regprc-crypto_salt.sql + +-------------------------------------------------------------------------------------------------------------------------------------------- ---------------------------------------------------------FOR HISTORY DATA---------------------------------------------- @@ -279,18 +300,4 @@ 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'; ------------------------------------------------------------------------------------------------------------------------------------- --------------------------------------------------------Add columns to registration_list---------------------------------------------- -ALTER TABLE regprc.registration_list ADD COLUMN name character varying; -ALTER TABLE regprc.registration_list ADD COLUMN phone character varying; -ALTER TABLE regprc.registration_list ADD COLUMN email character varying; -ALTER TABLE regprc.registration_list ADD COLUMN center_id character varying; -ALTER TABLE regprc.registration_list ADD COLUMN registration_date date; -ALTER TABLE regprc.registration_list ADD COLUMN location_code character varying; - -------------------------------------------------------------------------------------------------------------------------------------------- --------------------------------------------------Creation of crypto salt table-------------------------------------------------------------- - -\ir ../ddl/regprc-crypto_salt.sql - --------------------------------------------------------------------------------------------------------------------------------------------- diff --git a/db_scripts/mosip_regprc/ddl/regprc-individual_demographic_dedup.sql b/db_scripts/mosip_regprc/ddl/regprc-individual_demographic_dedup.sql index f49cc64da66..223951e3552 100644 --- a/db_scripts/mosip_regprc/ddl/regprc-individual_demographic_dedup.sql +++ b/db_scripts/mosip_regprc/ddl/regprc-individual_demographic_dedup.sql @@ -26,8 +26,7 @@ CREATE TABLE regprc.individual_demographic_dedup( ); -- indexes section ------------------------------------------------- -CREATE INDEX IF NOT EXISTS idx_idemogd_namedob ON regprc.individual_demographic_dedup (name, dob,gender); - +CREATE index IF NOT EXISTS idx_idemogd_namedobgender on regprc.individual_demographic_dedup (name, dob,gender); -- ddl-end -- COMMENT ON TABLE regprc.individual_demographic_dedup IS 'Individual Demographic Dedupe: Table stores applicant demographic details for deduplication, Only required information for dedupe is stored. '; -- ddl-end -- From 4c1b2dfe0af89c7a2b91e073dcfccbc59558fe89 Mon Sep 17 00:00:00 2001 From: JyotiPrakashNayak Date: Thu, 14 Apr 2022 14:48:54 +0530 Subject: [PATCH 010/133] MOSIP-21075_modified release script (#1506) * Update 1.2_regprc-scripts_release.sql * Update regprc-individual_demographic_dedup.sql * MOSIP-21075_modified release script * MOSIP-21075 --- .../sql/1.2_regprc-scripts_release.sql | 21 +++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/db_release_scripts/mosip_regprc/sql/1.2_regprc-scripts_release.sql b/db_release_scripts/mosip_regprc/sql/1.2_regprc-scripts_release.sql index c264a66f7c8..872697386c5 100644 --- a/db_release_scripts/mosip_regprc/sql/1.2_regprc-scripts_release.sql +++ b/db_release_scripts/mosip_regprc/sql/1.2_regprc-scripts_release.sql @@ -138,10 +138,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; +\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; ------------------------------------------------------------------------------------------------------ @@ -300,4 +318,3 @@ 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'; ------------------------------------------------------------------------------------------------------------------------------------- - From 9dfd57df350d25b7e6baf83e1deda8bff6a150cb Mon Sep 17 00:00:00 2001 From: JyotiPrakashNayak Date: Thu, 14 Apr 2022 17:23:01 +0530 Subject: [PATCH 011/133] MOSIP-21056_changed machine and center validation code (#1507) * Update 1.2_regprc-scripts_release.sql * Update regprc-individual_demographic_dedup.sql * MOSIP-21075_modified release script * MOSIP-21075 * MOSIP-21056 * MOSIP-21056 --- .../stages/cmdvalidator/CenterValidator.java | 6 +++++- .../stages/cmdvalidator/MachineValidator.java | 13 ++++++++++--- 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/registration-processor/pre-processor/registration-processor-cmd-validator-stage/src/main/java/io/mosip/registration/processor/stages/cmdvalidator/CenterValidator.java b/registration-processor/pre-processor/registration-processor-cmd-validator-stage/src/main/java/io/mosip/registration/processor/stages/cmdvalidator/CenterValidator.java index 1c4505aec5d..c288e2812b4 100644 --- a/registration-processor/pre-processor/registration-processor-cmd-validator-stage/src/main/java/io/mosip/registration/processor/stages/cmdvalidator/CenterValidator.java +++ b/registration-processor/pre-processor/registration-processor-cmd-validator-stage/src/main/java/io/mosip/registration/processor/stages/cmdvalidator/CenterValidator.java @@ -3,6 +3,7 @@ import java.io.IOException; import java.util.ArrayList; import java.util.List; +import java.util.stream.Collectors; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; @@ -76,7 +77,10 @@ private void validateRegistrationCenter(String registrationCenterId, String lang RegistrationCenterResponseDto.class); if (responseWrapper.getErrors() == null) { - if (!rcpdto.getRegistrationCentersHistory().get(0).getIsActive()) { + rcpdto.setRegistrationCentersHistory(rcpdto.getRegistrationCentersHistory().stream().filter(c-> + c!=null && c.getId()!=null && c.getIsActive()!=null && c.getIsActive() && c.getId().equalsIgnoreCase(registrationCenterId)).collect(Collectors.toList())); + + if (rcpdto.getRegistrationCentersHistory()==null || rcpdto.getRegistrationCentersHistory().isEmpty()) { throw new ValidationFailedException(StatusUtil.CENTER_ID_INACTIVE.getMessage(), StatusUtil.CENTER_ID_INACTIVE.getCode()); } diff --git a/registration-processor/pre-processor/registration-processor-cmd-validator-stage/src/main/java/io/mosip/registration/processor/stages/cmdvalidator/MachineValidator.java b/registration-processor/pre-processor/registration-processor-cmd-validator-stage/src/main/java/io/mosip/registration/processor/stages/cmdvalidator/MachineValidator.java index 4ecc4e92ff3..7d3d9a625ad 100644 --- a/registration-processor/pre-processor/registration-processor-cmd-validator-stage/src/main/java/io/mosip/registration/processor/stages/cmdvalidator/MachineValidator.java +++ b/registration-processor/pre-processor/registration-processor-cmd-validator-stage/src/main/java/io/mosip/registration/processor/stages/cmdvalidator/MachineValidator.java @@ -3,6 +3,7 @@ import java.io.IOException; import java.util.ArrayList; import java.util.List; +import java.util.stream.Collectors; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @@ -68,10 +69,16 @@ public void validate(String machineId, String langCode, String effdatetimes, Str mhrdto = mapper.readValue(mapper.writeValueAsString(responseWrapper.getResponse()), MachineHistoryResponseDto.class); if (responseWrapper.getErrors() == null) { - MachineHistoryDto dto = mhrdto.getMachineHistoryDetails().get(0); + + mhrdto.setMachineHistoryDetails(mhrdto.getMachineHistoryDetails().stream().filter(m -> + m!=null && m.getId()!=null && m.getId().equalsIgnoreCase(machineId)).collect(Collectors.toList())); - if (dto.getId() != null && dto.getId().matches(machineId)) { - if (!dto.getIsActive()) { + if (mhrdto.getMachineHistoryDetails()!=null && !mhrdto.getMachineHistoryDetails().isEmpty()) { + + mhrdto.setMachineHistoryDetails(mhrdto.getMachineHistoryDetails().stream().filter(m -> + m.getIsActive()!=null && m.getIsActive() ).collect(Collectors.toList())); + + if (mhrdto.getMachineHistoryDetails()==null || mhrdto.getMachineHistoryDetails().isEmpty()) { throw new ValidationFailedException(StatusUtil.MACHINE_ID_NOT_ACTIVE.getMessage() + machineId, StatusUtil.MACHINE_ID_NOT_ACTIVE.getCode()); } From 0d281d4225fe31a22922ca4058f192310e1528ec Mon Sep 17 00:00:00 2001 From: JyotiPrakashNayak Date: Tue, 19 Apr 2022 15:53:29 +0530 Subject: [PATCH 012/133] MOSIP-21056_changed umc validation code (#1511) * Update 1.2_regprc-scripts_release.sql * Update regprc-individual_demographic_dedup.sql * MOSIP-21075_modified release script * MOSIP-21075 * MOSIP-21056 * MOSIP-21056 * Update OperatorValidator.java * Update SupervisorValidator.java --- .../processor/stages/operatorvalidator/OperatorValidator.java | 3 ++- .../stages/supervisorvalidator/SupervisorValidator.java | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) 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 78d6348edf9..df78eea9540 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 @@ -377,7 +377,8 @@ private boolean validateMapping(List pathsegments, InternalRegistrationS throw new BaseCheckedException(error.get(0).getMessage(), StatusUtil.CENTER_DEVICE_MAPPING_NOT_FOUND.getCode()); } else if (userDto != null) { - isValidUser = userDto.getRegistrationCenters().get(0).getIsActive(); + 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"); 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 0ce43ca3c33..354a838bc93 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 @@ -380,7 +380,8 @@ private boolean validateMapping(List pathsegments, InternalRegistrationS throw new BaseCheckedException(error.get(0).getMessage(), StatusUtil.CENTER_DEVICE_MAPPING_NOT_FOUND.getCode()); } else if (userDto != null) { - isValidUser = userDto.getRegistrationCenters().get(0).getIsActive(); + 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"); From ea93e6a3bb5cb490a139f73888141b6bf151665a Mon Sep 17 00:00:00 2001 From: Keshav Mishra Date: Thu, 12 May 2022 15:58:04 +0530 Subject: [PATCH 013/133] [MOSIP-20020] Update release_changes.yml --- .github/workflows/release_changes.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/release_changes.yml b/.github/workflows/release_changes.yml index cc9c2956d9e..e75a616c583 100644 --- a/.github/workflows/release_changes.yml +++ b/.github/workflows/release_changes.yml @@ -48,7 +48,7 @@ jobs: uses: peter-evans/create-pull-request@v3 with: token: ${{ secrets.ACTION_PAT }} - commit-message: Updated Pom versions for release changes + commit-message: Release Bot Pre-release changes title: Release changes body: Automated PR for ${{ github.event.inputs.releaseTags }} release. branch: release-branch From 704bc23917704a8135b987d7d57c913b3c129956 Mon Sep 17 00:00:00 2001 From: syed-salman-technoforte Date: Tue, 17 May 2022 16:22:48 +0530 Subject: [PATCH 014/133] [ MOSIP-20026 ] updated push_trigger.yml --- .github/workflows/push_trigger.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/push_trigger.yml b/.github/workflows/push_trigger.yml index 296b982e759..a156b7e58dd 100644 --- a/.github/workflows/push_trigger.yml +++ b/.github/workflows/push_trigger.yml @@ -1,8 +1,8 @@ name: Maven Package upon a push on: - pull_request: - types: [closed] + #pull_request: + #types: [closed] push: branches: - '!release-branch' From b5e4c91f0588059b49b58177e93e68e637fbb1d5 Mon Sep 17 00:00:00 2001 From: Keshav Mishra Date: Tue, 17 May 2022 16:26:58 +0530 Subject: [PATCH 015/133] Revert "[ MOSIP-20026 ] updated push_trigger.yml" --- .github/workflows/push_trigger.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/push_trigger.yml b/.github/workflows/push_trigger.yml index a156b7e58dd..296b982e759 100644 --- a/.github/workflows/push_trigger.yml +++ b/.github/workflows/push_trigger.yml @@ -1,8 +1,8 @@ name: Maven Package upon a push on: - #pull_request: - #types: [closed] + pull_request: + types: [closed] push: branches: - '!release-branch' From ebb9c8a9b40fd3aa6175ea0ce293262529f3aad9 Mon Sep 17 00:00:00 2001 From: syed-salman-technoforte Date: Thu, 19 May 2022 16:11:25 +0530 Subject: [PATCH 016/133] [ MOSIP-20021 ] updated release_changes.yml to update README.md badges --- .github/workflows/release_changes.yml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/.github/workflows/release_changes.yml b/.github/workflows/release_changes.yml index e75a616c583..5d8e1a32989 100644 --- a/.github/workflows/release_changes.yml +++ b/.github/workflows/release_changes.yml @@ -27,6 +27,11 @@ jobs: echo "BRANCH_NAME=$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')" >> $GITHUB_ENV echo "GPG_TTY=$(tty)" >> $GITHUB_ENV + - name: update Branch name in badges + run: | + sed -i 's/branch=.*)]/branch=${{ env.BRANCH_NAME }}\)]/g' README.md + sed -i 's/branch=.*\&/branch=${{ env.BRANCH_NAME }}\&/g' README.md + - name: Mannualy changing the pom versions run: find . -type f -name "*pom.xml" -print0 | xargs -0 sed -i "s/${{ github.event.inputs.snapshotTags }}/${{ github.event.inputs.releaseTags }}/g" From af469f29dcf7cccf611c10dae7ce519875d0e27c Mon Sep 17 00:00:00 2001 From: JyotiPrakashNayak Date: Wed, 8 Jun 2022 18:03:28 +0530 Subject: [PATCH 017/133] Quality_classifier stage fix (#1548) * quality * MOSIP-22116 --- .../quality/classifier/stage/QualityClassifierStage.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/registration-processor/pre-processor/registration-processor-quality-classifier-stage/src/main/java/io/mosip/registration/processor/quality/classifier/stage/QualityClassifierStage.java b/registration-processor/pre-processor/registration-processor-quality-classifier-stage/src/main/java/io/mosip/registration/processor/quality/classifier/stage/QualityClassifierStage.java index b5617e4b402..f80106eec83 100644 --- a/registration-processor/pre-processor/registration-processor-quality-classifier-stage/src/main/java/io/mosip/registration/processor/quality/classifier/stage/QualityClassifierStage.java +++ b/registration-processor/pre-processor/registration-processor-quality-classifier-stage/src/main/java/io/mosip/registration/processor/quality/classifier/stage/QualityClassifierStage.java @@ -442,6 +442,7 @@ private Map getQualityTags(List birs) throws BiometricExcep BiometricType biometricType = bir.getBdbInfo().getType().get(0); BIR[] birArray = new BIR[1]; birArray[0] = bir; + if(!biometricType.name().equalsIgnoreCase(BiometricType.EXCEPTION_PHOTO.name()) ) { float[] qualityScoreresponse = getBioSdkInstance(biometricType).getSegmentQuality(birArray, null); float score = qualityScoreresponse[0]; @@ -452,7 +453,7 @@ private Map getQualityTags(List birs) throws BiometricExcep bioTypeMinScoreMap.put(bioType, storedMinScore == null ? score : storedMinScore > score ? score : storedMinScore); - + } } for (Entry bioTypeMinEntry : bioTypeMinScoreMap.entrySet()) { From 964348949219e288f766aeea00226c9d2f5a4ddc Mon Sep 17 00:00:00 2001 From: Monobikash Das <43202165+MonobikashDas@users.noreply.github.com> Date: Wed, 29 Jun 2022 11:07:33 +0530 Subject: [PATCH 018/133] MOSIP-22216 : added ref_id in release script --- .../mosip_regprc/sql/1.2_regprc-scripts_release.sql | 1 + 1 file changed, 1 insertion(+) diff --git a/db_release_scripts/mosip_regprc/sql/1.2_regprc-scripts_release.sql b/db_release_scripts/mosip_regprc/sql/1.2_regprc-scripts_release.sql index 872697386c5..5b4bc6dbb84 100644 --- a/db_release_scripts/mosip_regprc/sql/1.2_regprc-scripts_release.sql +++ b/db_release_scripts/mosip_regprc/sql/1.2_regprc-scripts_release.sql @@ -41,6 +41,7 @@ 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; From 1e19a6d1816179aea3900930cc8f38df489c350f Mon Sep 17 00:00:00 2001 From: Monobikash Das Date: Thu, 30 Jun 2022 21:20:15 +0530 Subject: [PATCH 019/133] MOSIP-22432 : using auth adapter --- .../PacketReceiverExceptionHandler.java | 9 ++++ .../receiver/stage/PacketReceiverStage.java | 5 ++- .../core/abstractverticle/MosipRouter.java | 43 +++---------------- .../core/token/validation/TokenValidator.java | 14 ++++++ 4 files changed, 33 insertions(+), 38 deletions(-) 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/stage/PacketReceiverStage.java b/registration-processor/init/registration-processor-packet-receiver-stage/src/main/java/io/mosip/registration/processor/packet/receiver/stage/PacketReceiverStage.java index c3026f1aef3..dc9619f1009 100644 --- a/registration-processor/init/registration-processor-packet-receiver-stage/src/main/java/io/mosip/registration/processor/packet/receiver/stage/PacketReceiverStage.java +++ b/registration-processor/init/registration-processor-packet-receiver-stage/src/main/java/io/mosip/registration/processor/packet/receiver/stage/PacketReceiverStage.java @@ -141,7 +141,9 @@ private void routes(MosipRouter router) { public void failure(RoutingContext routingContext) { try { Entry 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/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/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"); From 6f82a0f80803d1900e14ecf3d8ba54fc364a1744 Mon Sep 17 00:00:00 2001 From: Monobikash Das Date: Fri, 1 Jul 2022 14:58:00 +0530 Subject: [PATCH 020/133] MOSIP-22432 : using auth adapter --- .../config/RegistrationStatusConfigTest.java | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) 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..7c6b35978b5 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,7 +1,14 @@ package io.mosip.registration.processor.status.api.config; +import io.mosip.kernel.core.authmanager.authadapter.spi.VertxAuthenticationProvider; 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; import org.springframework.boot.test.mock.mockito.MockBean; +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; @@ -19,5 +26,30 @@ 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; + } + }; + } + } From 3744b6ccabf17004adf1abe7e5e171b62c2842ad Mon Sep 17 00:00:00 2001 From: NishantKumar4559 <100404536+NishantKumar4559@users.noreply.github.com> Date: Thu, 14 Jul 2022 15:17:26 +0530 Subject: [PATCH 021/133] Update ddl.sql (#1569) added reg_verification --- db_scripts/mosip_regprc/ddl.sql | 1 + 1 file changed, 1 insertion(+) diff --git a/db_scripts/mosip_regprc/ddl.sql b/db_scripts/mosip_regprc/ddl.sql index ff684db6f2f..2346d444f82 100644 --- a/db_scripts/mosip_regprc/ddl.sql +++ b/db_scripts/mosip_regprc/ddl.sql @@ -5,6 +5,7 @@ \ir ddl/regprc-registration_list.sql \ir ddl/regprc-registration_transaction.sql \ir ddl/regprc-reg_manual_verification.sql +\ir ddl/regprc-reg_verification.sql \ir ddl/regprc-transaction_type.sql \ir ddl/regprc-rid_seq.sql \ir ddl/regprc-reg_bio_ref.sql From 28de8569ef07224189d215beab97de07f281e1fb Mon Sep 17 00:00:00 2001 From: NishantKumar4559 <100404536+NishantKumar4559@users.noreply.github.com> Date: Thu, 14 Jul 2022 18:57:52 +0530 Subject: [PATCH 022/133] validateBiometrics() fix (#1570) * validateBiometrics() fix * validateBiometrics() fixes Co-authored-by: Nishant Kumar (IN64559) --- .../CbeffValidateAndVerificatonService.java | 20 ++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) 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; From 1dabb60a6007dc92d8380dc5abdbb36a28d50a34 Mon Sep 17 00:00:00 2001 From: Keshav Mishra Date: Mon, 18 Jul 2022 10:28:57 +0530 Subject: [PATCH 023/133] [MOSIP-20028] added action for tagging --- .github/workflows/tag.yaml | 43 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 .github/workflows/tag.yaml diff --git a/.github/workflows/tag.yaml b/.github/workflows/tag.yaml new file mode 100644 index 00000000000..e9bba0e65a0 --- /dev/null +++ b/.github/workflows/tag.yaml @@ -0,0 +1,43 @@ +name: Tagging of repos + +env: + tag: v1.2.3 + +on: + workflow_dispatch: + inputs: + tag: + description: 'Tag to be published' + required: true + default: 'v1.2.3' + type: string + body: + description: 'Release body message' + required: true + default: 'Changes in this Release' + type: string + pre-release: + description: 'Pre-release? True/False' + required: true + default: False + type: string + +jobs: + build: + name: Create Release + runs-on: ubuntu-latest + steps: + - name: Checkout code + uses: actions/checkout@v2 + - name: Create Release + id: create_release + uses: actions/create-release@v1 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # This token is provided by Actions, you do not need to create your own token + with: + tag_name: ${{ github.event.inputs.tag }} + release_name: ${{ github.event.inputs.tag }} + body: | + ${{ github.event.inputs.body }} + draft: false + prerelease: ${{fromJSON(github.event.inputs.pre-release)}} From 6d6a31b6d0cdc665f37e8130333c65ea635d5334 Mon Sep 17 00:00:00 2001 From: NishantKumar4559 <100404536+NishantKumar4559@users.noreply.github.com> Date: Tue, 19 Jul 2022 18:46:56 +0530 Subject: [PATCH 024/133] Updated MANUAL_VERIFICATION to VERIFICATION (#1572) --- db_release_scripts/mosip_regprc/dml/regprc-transaction_type.csv | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/db_release_scripts/mosip_regprc/dml/regprc-transaction_type.csv b/db_release_scripts/mosip_regprc/dml/regprc-transaction_type.csv index feed8a93a80..9637e52692d 100644 --- a/db_release_scripts/mosip_regprc/dml/regprc-transaction_type.csv +++ b/db_release_scripts/mosip_regprc/dml/regprc-transaction_type.csv @@ -12,7 +12,7 @@ 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() -MANUAL_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() From d321dcf0526baa23033f608dc42dafba6ec52cf5 Mon Sep 17 00:00:00 2001 From: NishantKumar4559 <100404536+NishantKumar4559@users.noreply.github.com> Date: Tue, 19 Jul 2022 19:16:41 +0530 Subject: [PATCH 025/133] Updated Manual_verification to verification (#1574) --- db_scripts/mosip_regprc/dml/regprc-transaction_type.csv | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/db_scripts/mosip_regprc/dml/regprc-transaction_type.csv b/db_scripts/mosip_regprc/dml/regprc-transaction_type.csv index feed8a93a80..9637e52692d 100644 --- a/db_scripts/mosip_regprc/dml/regprc-transaction_type.csv +++ b/db_scripts/mosip_regprc/dml/regprc-transaction_type.csv @@ -12,7 +12,7 @@ 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() -MANUAL_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() From 0396aa5db14f0780734476f36dc8a7ebaa256398 Mon Sep 17 00:00:00 2001 From: Shilpa-Manjunath <72008366+Shilpa-Manjunath@users.noreply.github.com> Date: Wed, 8 Jun 2022 19:49:13 +0530 Subject: [PATCH 026/133] MOSIP 20897 Investigate error condtion in validate stage (#1547) * MOSIP 20897 Investigate error condtion in validate stage * Mosip 22127 Avoid getting the biometrics and creating a datashare in case of already processed insert in ABIS handler stage * MOSIP 22326 Investigate the Error in BIOGRAPHIC_Verification stage having Insert Response Failed and Identify Response Failed * MOSIP 20897 Investigate error condtion in validate stage * MOSIP 22326 Investigate the Error in BIOGRAPHIC_Verification stage having Insert Response Failed and Identify Response Failed * changed error code Co-authored-by: Shilpa M --- .../abis/handler/stage/AbisHandlerStage.java | 17 +- .../middleware/constants/FailureReason.java | 4 +- .../middleware/stage/AbisMiddleWareStage.java | 35 +- .../validator/PacketValidateProcessor.java | 1172 ++++++++--------- .../status/code/RegistrationStatusCode.java | 2 +- 5 files changed, 628 insertions(+), 602 deletions(-) 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 08130f6b4d4..39e41132de0 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 @@ -502,9 +502,6 @@ private void createInsertRequest(List abisQueueDetails, String abisRequestDto.setReqBatchId(batchId); abisRequestDto.setRefRegtrnId(transactionId); - byte[] abisInsertRequestBytes = getInsertRequestBytes(regId, id, process, bioRefId, description); - abisRequestDto.setReqText(abisInsertRequestBytes); - abisRequestDto.setStatusCode(AbisStatusCode.IN_PROGRESS.toString()); abisRequestDto.setStatusComment(null); abisRequestDto.setLangCode(AbisHandlerStageConstant.ENG); @@ -513,13 +510,18 @@ private void createInsertRequest(List abisQueueDetails, String abisRequestDto.setIsDeleted(Boolean.FALSE); String moduleId = PlatformSuccessMessages.RPR_ABIS_HANDLER_STAGE_SUCCESS.getCode(); String moduleName = ModuleName.ABIS_HANDLER.toString(); + byte[] abisInsertRequestBytes=null; if (abisProcessedInsertAppCodeList != null && abisProcessedInsertAppCodeList.contains(appCode)) { + abisInsertRequestBytes = getInsertRequestBytes(regId, id, process, bioRefId, description,AbisStatusCode.ALREADY_PROCESSED.toString()); abisRequestDto.setStatusCode(AbisStatusCode.ALREADY_PROCESSED.toString()); - packetInfoManager.saveAbisRequest(abisRequestDto, moduleId, moduleName); + } else { + abisInsertRequestBytes = getInsertRequestBytes(regId, id, process, bioRefId, description,AbisStatusCode.IN_PROGRESS.toString()); abisRequestDto.setStatusCode(AbisStatusCode.IN_PROGRESS.toString()); - packetInfoManager.saveAbisRequest(abisRequestDto, moduleId, moduleName); + } + abisRequestDto.setReqText(abisInsertRequestBytes); + packetInfoManager.saveAbisRequest(abisRequestDto, moduleId, moduleName); } @@ -536,12 +538,11 @@ private void createInsertRequest(List abisQueueDetails, String * @param description * @return the insert request bytes */ - private byte[] getInsertRequestBytes(String regId, String id, String process, String bioRefId, - LogDescription description) throws Exception { + private byte[] getInsertRequestBytes(String regId, String id, String process, String bioRefId, LogDescription description,String status) throws Exception { AbisInsertRequestDto abisInsertRequestDto = new AbisInsertRequestDto(); abisInsertRequestDto.setId(AbisHandlerStageConstant.MOSIP_ABIS_INSERT); abisInsertRequestDto.setReferenceId(bioRefId); - abisInsertRequestDto.setReferenceURL(getDataShareUrl(regId, process)); + abisInsertRequestDto.setReferenceURL(status.equalsIgnoreCase(AbisStatusCode.IN_PROGRESS.toString())?getDataShareUrl(regId, process):null); abisInsertRequestDto.setRequestId(id); abisInsertRequestDto.setRequesttime(DateUtils.getUTCCurrentDateTimeString(env.getProperty(DATETIME_PATTERN))); abisInsertRequestDto.setVersion(AbisHandlerStageConstant.VERSION); diff --git a/registration-processor/core-processor/registration-processor-abis-middleware-stage/src/main/java/io/mosip/registartion/processor/abis/middleware/constants/FailureReason.java b/registration-processor/core-processor/registration-processor-abis-middleware-stage/src/main/java/io/mosip/registartion/processor/abis/middleware/constants/FailureReason.java index 6e5ae0c2a03..8ab2f2682c0 100644 --- a/registration-processor/core-processor/registration-processor-abis-middleware-stage/src/main/java/io/mosip/registartion/processor/abis/middleware/constants/FailureReason.java +++ b/registration-processor/core-processor/registration-processor-abis-middleware-stage/src/main/java/io/mosip/registartion/processor/abis/middleware/constants/FailureReason.java @@ -13,8 +13,8 @@ public enum FailureReason { INTERNAL_ERROR("1", "Internal error - Unknown"), ABORTED("2","Aborted"), - UNEXPECTED_ERROR("3","Unexpected error - Unable to access biometric data"), - UNABLE_TO_SERVE("4","Unable to serve the request"), + UNEXPECTED_ERROR("3","Unexpected error"), + UNABLE_TO_SERVE("4","Unable to serve the request - invalid request structure"), MISSING_REFERENCEID("5","missing referenceId (in request body)"), MISSING_REQUESTID("6","missing requestId (in request body)"), UNABLE_TO_FETCH("7","unable to fetch biometric details (using referenceURL)"), 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 d39d99a5bc7..a0c5ce83249 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 @@ -432,7 +432,7 @@ public void consumerListener(Message message, String abisInBoundAddress, MosipQu internalRegStatusDto .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.REPROCESS.toString()); internalRegStatusDto.setStatusComment( - StatusUtil.INSERT_RESPONSE_FAILED.getMessage() + abisCommonRequestDto.getId()); + StatusUtil.INSERT_RESPONSE_FAILED.getMessage() + abisCommonRequestDto.getId()+"-"+abisInsertResponseDto.getFailureReason()+"-"+io.mosip.registartion.processor.abis.middleware.constants.FailureReason.getValueFromKey(abisInsertResponseDto.getFailureReason())); internalRegStatusDto.setSubStatusCode(StatusUtil.SYSTEM_EXCEPTION_OCCURED.getCode()); moduleId = PlatformErrorMessages.SYSTEM_EXCEPTION_OCCURED.getCode(); registrationStatusService.updateRegistrationStatus(internalRegStatusDto, moduleId, moduleName); @@ -463,7 +463,7 @@ public void consumerListener(Message message, String abisInBoundAddress, MosipQu internalRegStatusDto .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.REPROCESS.toString()); internalRegStatusDto.setStatusComment( - StatusUtil.IDENTIFY_RESPONSE_FAILED.getMessage() + abisCommonRequestDto.getId()); + StatusUtil.IDENTIFY_RESPONSE_FAILED.getMessage() + abisCommonRequestDto.getId()+"-"+abisIdentifyResponseDto.getFailureReason()+"-"+io.mosip.registartion.processor.abis.middleware.constants.FailureReason.getValueFromKey(abisIdentifyResponseDto.getFailureReason())); internalRegStatusDto.setSubStatusCode(StatusUtil.SYSTEM_EXCEPTION_OCCURED.getCode()); moduleId = PlatformErrorMessages.SYSTEM_EXCEPTION_OCCURED.getCode(); registrationStatusService.updateRegistrationStatus(internalRegStatusDto, moduleId, moduleName); @@ -617,6 +617,21 @@ private void updteAbisRequestProcessed(AbisCommonResponseDto abisCommonResponseD abisReqEntity.setStatusComment( abisCommonResponseDto.getReturnValue().equalsIgnoreCase("1") ? StatusUtil.INSERT_IDENTIFY_RESPONSE_SUCCESS.getMessage() : io.mosip.registartion.processor.abis.middleware.constants.FailureReason.getValueFromKey(abisCommonResponseDto.getFailureReason())); + if(abisCommonResponseDto.getReturnValue().equalsIgnoreCase("1")) + { + abisReqEntity.setStatusComment(StatusUtil.INSERT_IDENTIFY_RESPONSE_SUCCESS.getMessage()); + } + else { + abisReqEntity.setStatusComment(io.mosip.registartion.processor.abis.middleware.constants.FailureReason + .getValueFromKey(abisCommonResponseDto.getFailureReason())); + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), + "Abis response failed for "+packetInfoDao.getRegIdByBioRefId(abisCommonRequestDto.getBioRefId())+" due to " + abisCommonResponseDto.getFailureReason() + "-" + + io.mosip.registartion.processor.abis.middleware.constants.FailureReason + .getValueFromKey(abisCommonResponseDto.getFailureReason()), + "AbisMiddleWareStage::updteAbisRequestProcessed()"); + + } + abisReqEntity.setAbisAppCode(abisCommonRequestDto.getAbisAppCode()); abisReqEntity.setRequestType(abisCommonRequestDto.getRequestType()); abisReqEntity.setRequestDtimes(abisCommonRequestDto.getRequestDtimes()); @@ -688,9 +703,19 @@ private AbisResponseDto updateAbisResponseEntity(AbisCommonResponseDto abisCommo abisResponseDto.setId(RegistrationUtility.generateId()); abisResponseDto.setRespText(response.getBytes()); - - abisResponseDto.setStatusCode(isInsertSuccess(abisCommonResponseDto) ? - AbisStatusCode.SUCCESS.toString() : AbisStatusCode.FAILED.toString()); + + if (isInsertSuccess(abisCommonResponseDto)) { + abisResponseDto.setStatusCode(AbisStatusCode.SUCCESS.toString()); + } else { + abisResponseDto.setStatusCode(AbisStatusCode.FAILED.toString()); + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), + "Abis response failed for request Id " + abisCommonResponseDto.getRequestId() + " due to " + + abisCommonResponseDto.getFailureReason() + "-" + + io.mosip.registartion.processor.abis.middleware.constants.FailureReason + .getValueFromKey(abisCommonResponseDto.getFailureReason()), + "AbisMiddleWareStage::updateAbisResponseEntity()"); + } + abisResponseDto.setStatusComment(io.mosip.registartion.processor.abis.middleware.constants.FailureReason.getValueFromKey(abisCommonResponseDto.getFailureReason())); abisResponseDto.setLangCode("eng"); abisResponseDto.setCrBy(SYSTEM); 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 9a11f31062e..6815fc5635a 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,586 +1,586 @@ -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.util.Arrays; -import java.util.Date; -import java.util.Map; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - -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; - - 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()); - - 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()); - } 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 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) { - 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); - } else { - isProcessingSuccess = false; - notificationUtility.sendNotification(registrationAdditionalInfoDTO, registrationStatusDto, - regEntity, allNotificationTypes, isProcessingSuccess); - } - 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.util.Arrays; +import java.util.Date; +import java.util.Map; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +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; + + 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()); + + 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()); + } 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 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) { + 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); + } else { + isProcessingSuccess = false; + notificationUtility.sendNotification(registrationAdditionalInfoDTO, registrationStatusDto, + regEntity, allNotificationTypes, isProcessingSuccess); + } + 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/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, From cc3435657b4cc7ad27b24dc6bd410e48ea9aa3d1 Mon Sep 17 00:00:00 2001 From: JyotiPrakashNayak Date: Fri, 27 May 2022 14:51:22 +0530 Subject: [PATCH 027/133] MOSIP-22192_modified update verification code (#1541) * Release-fix * # WARNING: head commit changed in the meantime Merge branch '1.1.5.6' of https://github.com/mosip/registration.git into 1.1.5.6 * MOSIP-22192 Co-authored-by: M1030448 --- .../impl/ManualAdjudicationServiceImpl.java | 129 ++++-------------- .../util/ManualVerificationUpdateUtility.java | 46 +++++++ .../ManualAdjudicationServiceTest.java | 6 + .../config/ManualVerificationConfigBean.java | 44 ++++++ 4 files changed, 126 insertions(+), 99 deletions(-) create mode 100644 registration-processor/core-processor/registration-processor-manual-adjudication-stage/src/main/java/io/mosip/registration/processor/adjudication/util/ManualVerificationUpdateUtility.java create mode 100644 registration-processor/core-processor/registration-processor-manual-verification-stage/src/main/java/io/mosip/registration/processor/manual/verification/config/ManualVerificationConfigBean.java 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 e1092b1e810..6e576774774 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 @@ -1,56 +1,7 @@ package io.mosip.registration.processor.adjudication.service.impl; -import static io.mosip.registration.processor.adjudication.constants.ManualAdjudicationConstants.DATETIME_PATTERN; - -import java.io.IOException; -import java.net.MalformedURLException; -import java.net.URL; -import java.sql.Timestamp; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.UUID; -import java.util.stream.Collectors; - -import io.mosip.registration.processor.core.constant.PolicyConstant; -import io.mosip.registration.processor.core.constant.ProviderStageName; -import io.mosip.registration.processor.packet.storage.utils.PriorityBasedPacketManagerService; -import io.mosip.registration.processor.adjudication.dto.DataShareRequestDto; -import io.mosip.registration.processor.adjudication.dto.DataShareResponseDto; -import io.mosip.registration.processor.adjudication.dto.ManualVerificationStatus; -import io.mosip.registration.processor.adjudication.dto.UserDto; -import io.mosip.registration.processor.adjudication.exception.MatchedRefNotExistsException; -import io.mosip.registration.processor.adjudication.request.dto.Filter; -import io.mosip.registration.processor.adjudication.request.dto.Gallery; -import io.mosip.registration.processor.adjudication.request.dto.ManualAdjudicationRequestDTO; -import io.mosip.registration.processor.adjudication.request.dto.ReferenceIds; -import io.mosip.registration.processor.adjudication.request.dto.ReferenceURL; -import io.mosip.registration.processor.adjudication.request.dto.ShareableAttributes; -import io.mosip.registration.processor.adjudication.request.dto.Source; -import io.mosip.registration.processor.adjudication.service.ManualAdjudicationService; -import io.mosip.registration.processor.adjudication.stage.ManualAdjudicationStage; -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; @@ -61,37 +12,20 @@ import io.mosip.registration.processor.adjudication.constants.ManualAdjudicationConstants; import io.mosip.registration.processor.adjudication.dto.DataShareRequestDto; import io.mosip.registration.processor.adjudication.dto.ManualVerificationStatus; -import io.mosip.registration.processor.adjudication.exception.DataShareException; -import io.mosip.registration.processor.adjudication.exception.InvalidFileNameException; -import io.mosip.registration.processor.adjudication.exception.InvalidRidException; -import io.mosip.registration.processor.adjudication.exception.MatchedRefNotExistsException; -import io.mosip.registration.processor.adjudication.exception.NoRecordAssignedException; -import io.mosip.registration.processor.adjudication.request.dto.Filter; -import io.mosip.registration.processor.adjudication.request.dto.Gallery; -import io.mosip.registration.processor.adjudication.request.dto.ManualAdjudicationRequestDTO; -import io.mosip.registration.processor.adjudication.request.dto.ReferenceIds; -import io.mosip.registration.processor.adjudication.request.dto.ReferenceURL; -import io.mosip.registration.processor.adjudication.request.dto.ShareableAttributes; -import io.mosip.registration.processor.adjudication.request.dto.Source; +import io.mosip.registration.processor.adjudication.exception.*; +import io.mosip.registration.processor.adjudication.request.dto.*; import io.mosip.registration.processor.adjudication.response.dto.Candidate; import io.mosip.registration.processor.adjudication.response.dto.ManualAdjudicationResponseDTO; import io.mosip.registration.processor.adjudication.service.ManualAdjudicationService; import io.mosip.registration.processor.adjudication.stage.ManualAdjudicationStage; +import io.mosip.registration.processor.adjudication.util.ManualVerificationUpdateUtility; 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.*; 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.constant.RegistrationType; +import io.mosip.registration.processor.core.constant.*; 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; @@ -99,7 +33,6 @@ import io.mosip.registration.processor.core.http.ResponseWrapper; import io.mosip.registration.processor.core.idrepo.dto.Documents; import io.mosip.registration.processor.core.idrepo.dto.ResponseDTO; -import io.mosip.registration.processor.core.kernel.master.dto.UserResponseDTOWrapper; 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; @@ -111,13 +44,6 @@ 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.adjudication.constants.ManualAdjudicationConstants; -import io.mosip.registration.processor.adjudication.exception.DataShareException; -import io.mosip.registration.processor.adjudication.exception.InvalidFileNameException; -import io.mosip.registration.processor.adjudication.exception.InvalidRidException; -import io.mosip.registration.processor.adjudication.exception.NoRecordAssignedException; -import io.mosip.registration.processor.adjudication.exception.UserIDNotPresentException; -import io.mosip.registration.processor.adjudication.response.dto.ManualAdjudicationResponseDTO; import io.mosip.registration.processor.packet.manager.idreposervice.IdRepoService; import io.mosip.registration.processor.packet.storage.dto.ApplicantInfoDto; import io.mosip.registration.processor.packet.storage.dto.Document; @@ -131,6 +57,27 @@ 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 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 java.io.IOException; +import java.net.MalformedURLException; +import java.util.*; +import java.util.Map.Entry; +import java.util.stream.Collectors; + +import static io.mosip.registration.processor.adjudication.constants.ManualAdjudicationConstants.DATETIME_PATTERN; /** * The Class ManualAdjudicationServiceImpl. @@ -229,6 +176,9 @@ public class ManualAdjudicationServiceImpl implements ManualAdjudicationService @Autowired RegistrationExceptionMapperUtil registrationExceptionMapperUtil; + @Autowired + private ManualVerificationUpdateUtility manualVerificationUpdateUtility; + /** The Constant PROTOCOL. */ public static final String PROTOCOL = "https"; @@ -421,14 +371,13 @@ private void pushRequestToQueue(MessageDTO messageDTO, MosipQueue queue) throws String requestId = UUID.randomUUID().toString(); mar.setRequestId(requestId); regProcLogger.info("Request : " + JsonUtils.javaObjectToJsonString(mar)); + manualVerificationUpdateUtility.updateManualVerificationEntityRID(mves, requestId); if (messageFormat.equalsIgnoreCase(TEXT_MESSAGE)) mosipQueueManager.send(queue, JsonUtils.javaObjectToJsonString(mar), mvRequestAddress, mvRequestMessageTTL); else mosipQueueManager.send(queue, JsonUtils.javaObjectToJsonString(mar).getBytes(), mvRequestAddress, mvRequestMessageTTL); regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), refId, "ManualVerificationServiceImpl::pushRequestToQueue()::entry"); - - updateManualVerificationEntityRID(mves, requestId); } private String getDataShareUrl(String id, String process) throws Exception { @@ -924,24 +873,6 @@ public MessageDTO process(MessageDTO object, MosipQueue queue) { return object; } - /* - * Update manual verification entity once request is pushed to queue for a given - * RID - */ - private void updateManualVerificationEntityRID(List mves, String requestId) { - mves.stream().forEach(mve -> { - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - mve.getRegId(), "ManualVerificationServiceImpl::updateManualVerificationEntityRID()::entry"); - mve.setStatusCode(ManualVerificationStatus.INQUEUE.name()); - mve.setStatusComment("Sent to manual adjudication queue"); - mve.setUpdDtimes(Timestamp.valueOf(DateUtils.getUTCCurrentDateTime())); - mve.setRequestId(requestId); - basePacketRepository.update(mve); - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - mve.getRegId(), "ManualVerificationServiceImpl::updateManualVerificationEntityRID()::exit"); - }); - } - /** * Process response for success flow. * 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 new file mode 100644 index 00000000000..8a57bf1aae8 --- /dev/null +++ b/registration-processor/core-processor/registration-processor-manual-adjudication-stage/src/main/java/io/mosip/registration/processor/adjudication/util/ManualVerificationUpdateUtility.java @@ -0,0 +1,46 @@ +package io.mosip.registration.processor.adjudication.util; + +import java.sql.Timestamp; +import java.util.List; + +import io.mosip.registration.processor.adjudication.dto.ManualVerificationStatus; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; + +import io.mosip.kernel.core.logger.spi.Logger; +import io.mosip.kernel.core.util.DateUtils; +import io.mosip.registration.processor.core.constant.LoggerFileConstant; +import io.mosip.registration.processor.core.logger.RegProcessorLogger; +import io.mosip.registration.processor.packet.storage.entity.ManualVerificationEntity; +import io.mosip.registration.processor.packet.storage.repository.BasePacketRepository; + +@Component +@Transactional(propagation=Propagation.REQUIRES_NEW) +public class ManualVerificationUpdateUtility { + /** The logger. */ + private static Logger regProcLogger = RegProcessorLogger.getLogger(ManualVerificationUpdateUtility.class); + + /** The base packet repository. */ + @Autowired + private BasePacketRepository basePacketRepository; + + /** + * Update manual verification entity once request is pushed to queue for a given + * RID + */ + public void updateManualVerificationEntityRID(List mves, String requestId) { + mves.stream().forEach(mve -> { + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + mve.getRegId(), "ManualVerificationUpdateUtility::updateManualVerificationEntityRID()::entry"); + mve.setStatusCode(ManualVerificationStatus.INQUEUE.name()); + mve.setStatusComment("Sent to manual adjudication queue"); + mve.setUpdDtimes(Timestamp.valueOf(DateUtils.getUTCCurrentDateTime())); + mve.setRequestId(requestId); + basePacketRepository.update(mve); + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + mve.getRegId(), "ManualVerificationUpdateUtility::updateManualVerificationEntityRID()::exit"); + }); + } +} diff --git a/registration-processor/core-processor/registration-processor-manual-adjudication-stage/src/test/java/io/mosip/registration/processor/verification/service/ManualAdjudicationServiceTest.java b/registration-processor/core-processor/registration-processor-manual-adjudication-stage/src/test/java/io/mosip/registration/processor/verification/service/ManualAdjudicationServiceTest.java index bc6807713e6..33e3ea2323b 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 @@ -22,6 +22,7 @@ import java.util.List; import java.util.Map; +import io.mosip.registration.processor.adjudication.util.ManualVerificationUpdateUtility; import org.apache.commons.io.IOUtils; import org.assertj.core.groups.Tuple; import org.assertj.core.util.Lists; @@ -112,6 +113,9 @@ public class ManualAdjudicationServiceTest { @Mock UserDto dto; + @Mock + private ManualVerificationUpdateUtility manualVerificationUpdateUtility; + @Mock ManualAdjudicationStage manualAdjudicationStage; @@ -270,6 +274,8 @@ 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()); } 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 From 6fc60176cf6f5f056ad2fa9a37c3d386716fc7d9 Mon Sep 17 00:00:00 2001 From: JyotiPrakashNayak Date: Mon, 4 Apr 2022 16:50:55 +0530 Subject: [PATCH 028/133] MOSIP-21070_modified request structure (#1497) * modified auth util * MOSIP-20615 * MOSIP-12261_added temporary file delete code * MOSIP-20634 * MOSIP-20634 * MOSIP-20634 * MOSIP-21070 Co-authored-by: M1030448 Co-authored-by: M1030448 Co-authored-by: Jyoti Prakash Nayak --- .../impl/MessageNotificationServiceImpl.java | 70 +++++++++---------- 1 file changed, 35 insertions(+), 35 deletions(-) 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 e2f7a6de29c..0e1f79aa780 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 @@ -124,7 +124,7 @@ public class MessageNotificationServiceImpl @Autowired private SyncRegistrationService syncRegistrationService; - + @Autowired private Decryptor decryptor; /** The template generator. */ @@ -137,17 +137,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; @@ -200,7 +200,7 @@ public SmsResponseDto sendSmsNotification(String templateTypeCode, String id, St } smsDto.setNumber(phoneNumber.toString()); } - + smsDto.setMessage(artifact); requestWrapper.setId(env.getProperty(SMS_SERVICE_ID)); @@ -236,8 +236,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; @@ -260,7 +260,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) { @@ -269,11 +269,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()); @@ -283,7 +283,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(), @@ -302,12 +302,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<>(); @@ -323,12 +323,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()) { @@ -341,18 +341,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); @@ -388,17 +388,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(), "", @@ -419,7 +419,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 @@ -428,10 +428,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 */ @@ -474,7 +474,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. @@ -523,7 +523,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); @@ -690,7 +690,7 @@ private Map setAttributesFromSync(String id, String process, Map } } return attribute; - + } private String getVid(String uin) throws ApisResourceAccessException { From 583566f87969a5737d876440c972f64168bdf92f Mon Sep 17 00:00:00 2001 From: Shilpa-Manjunath <72008366+Shilpa-Manjunath@users.noreply.github.com> Date: Mon, 20 Jun 2022 18:55:59 +0530 Subject: [PATCH 029/133] Mosip 22417 Ref_id is missing in REGISTRATION_PROCESSOR audit logs (#1554) Co-authored-by: Shilpa M --- .../abis/handler/stage/test/AbisHandlerStageTest.java | 3 +-- .../processor/reprocessor/verticle/ReprocessorVerticle.java | 5 ++++- .../workflowmanager/verticle/WorkflowActionJob.java | 1 + 3 files changed, 6 insertions(+), 3 deletions(-) diff --git a/registration-processor/core-processor/registration-processor-abis-handler-stage/src/test/java/io/mosip/registration/processor/abis/handler/stage/test/AbisHandlerStageTest.java b/registration-processor/core-processor/registration-processor-abis-handler-stage/src/test/java/io/mosip/registration/processor/abis/handler/stage/test/AbisHandlerStageTest.java index 687439a0632..edcffd7501d 100644 --- a/registration-processor/core-processor/registration-processor-abis-handler-stage/src/test/java/io/mosip/registration/processor/abis/handler/stage/test/AbisHandlerStageTest.java +++ b/registration-processor/core-processor/registration-processor-abis-handler-stage/src/test/java/io/mosip/registration/processor/abis/handler/stage/test/AbisHandlerStageTest.java @@ -471,8 +471,7 @@ public void testReprocessInsert() throws ApisResourceAccessException, PacketMana dto.setRid("10003100030001520190422074511"); MessageDTO result = abisHandlerStage.process(dto); - assertTrue(result.getInternalError()); - assertTrue(result.getIsValid()); + assertTrue(result.getMessageBusAddress().getAddress().equalsIgnoreCase("abis-middle-ware-bus-in")); } @Test diff --git a/registration-processor/workflow-engine/registration-processor-reprocessor/src/main/java/io/mosip/registration/processor/reprocessor/verticle/ReprocessorVerticle.java b/registration-processor/workflow-engine/registration-processor-reprocessor/src/main/java/io/mosip/registration/processor/reprocessor/verticle/ReprocessorVerticle.java index 3c65881bac7..fd497b3b402 100644 --- a/registration-processor/workflow-engine/registration-processor-reprocessor/src/main/java/io/mosip/registration/processor/reprocessor/verticle/ReprocessorVerticle.java +++ b/registration-processor/workflow-engine/registration-processor-reprocessor/src/main/java/io/mosip/registration/processor/reprocessor/verticle/ReprocessorVerticle.java @@ -212,6 +212,7 @@ public MessageDTO process(MessageDTO object) { statusList.add(RegistrationTransactionStatusCode.IN_PROGRESS.toString()); regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), "", "ReprocessorVerticle::process()::entry"); + StringBuffer ridSb=new StringBuffer(); try { reprocessorDtoList = registrationStatusService.getResumablePackets(fetchSize); if (!CollectionUtils.isEmpty(reprocessorDtoList)) { @@ -231,6 +232,8 @@ public MessageDTO process(MessageDTO object) { if (!CollectionUtils.isEmpty(reprocessorDtoList)) { reprocessorDtoList.forEach(dto -> { String registrationId = dto.getRegistrationId(); + ridSb.append(registrationId); + ridSb.append(","); MessageDTO messageDTO = new MessageDTO(); messageDTO.setRid(registrationId); messageDTO.setReg_type(dto.getRegistrationType()); @@ -325,7 +328,7 @@ public MessageDTO process(MessageDTO object) { : description.getCode(); String moduleName = ModuleName.RE_PROCESSOR.toString(); auditLogRequestBuilder.createAuditRequestBuilder(description.getMessage(), eventId, eventName, eventType, - moduleId, moduleName, ""); + moduleId, moduleName, (ridSb.toString().length()>1?ridSb.substring(0,ridSb.length()-1):"")); } return object; diff --git a/registration-processor/workflow-engine/registration-processor-workflow-manager-service/src/main/java/io/mosip/registration/processor/workflowmanager/verticle/WorkflowActionJob.java b/registration-processor/workflow-engine/registration-processor-workflow-manager-service/src/main/java/io/mosip/registration/processor/workflowmanager/verticle/WorkflowActionJob.java index 425ba5a29ea..55b77018366 100644 --- a/registration-processor/workflow-engine/registration-processor-workflow-manager-service/src/main/java/io/mosip/registration/processor/workflowmanager/verticle/WorkflowActionJob.java +++ b/registration-processor/workflow-engine/registration-processor-workflow-manager-service/src/main/java/io/mosip/registration/processor/workflowmanager/verticle/WorkflowActionJob.java @@ -172,6 +172,7 @@ public MessageDTO process(MessageDTO object) { LogDescription description = new LogDescription(); regProcLogger.debug("WorkflowActionJob::process()::entry"); + registrationId=object.getRid(); try { processActionablePausedPackets(); isTransactionSuccessful = true; From 71d8c7e57beef5f446bbb076791d8b8882a37a0d Mon Sep 17 00:00:00 2001 From: Monobikash Das Date: Wed, 27 Jul 2022 19:05:36 +0530 Subject: [PATCH 030/133] MOSIP-22432 : using auth adapter --- .../adjudication/config/ManualAdjudicationConfigBean.java | 6 ++++++ 1 file changed, 6 insertions(+) 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 c3773f0712f..816498db74d 100644 --- a/registration-processor/core-processor/registration-processor-manual-adjudication-stage/src/main/java/io/mosip/registration/processor/adjudication/config/ManualAdjudicationConfigBean.java +++ b/registration-processor/core-processor/registration-processor-manual-adjudication-stage/src/main/java/io/mosip/registration/processor/adjudication/config/ManualAdjudicationConfigBean.java @@ -1,6 +1,7 @@ package io.mosip.registration.processor.adjudication.config; import io.mosip.registration.processor.adjudication.util.ManualVerificationRequestValidator; +import io.mosip.registration.processor.adjudication.util.ManualVerificationUpdateUtility; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -25,4 +26,9 @@ ManualVerificationRequestValidator getManualVerificationRequestValidator() { ManualVerificationExceptionHandler getManualVerificationExceptionHandler() { return new ManualVerificationExceptionHandler(); } + + @Bean + ManualVerificationUpdateUtility manualVerificationUpdateUtility() { + return new ManualVerificationUpdateUtility(); + } } \ No newline at end of file From bd17dbc2efb866daa944c9af97ff4ed2537950f3 Mon Sep 17 00:00:00 2001 From: Monobikash Das Date: Fri, 5 Aug 2022 18:57:49 +0530 Subject: [PATCH 031/133] MOSIP-23025 : healthcheck and retry fix for activemq connection --- .../MosipVerticleAPIManager.java | 6 +- .../StageHealthCheckHandler.java | 74 +++++++++++-------- .../core/queue/impl/MosipActiveMqImpl.java | 16 +++- 3 files changed, 60 insertions(+), 36 deletions(-) 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 22416fcea07..6aedfbbd3ca 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 @@ -2,6 +2,7 @@ import io.mosip.kernel.core.virusscanner.spi.VirusScanner; import io.mosip.registration.processor.core.queue.factory.MosipQueue; +import io.mosip.registration.processor.core.spi.queue.MosipQueueConnectionFactory; import io.mosip.registration.processor.core.spi.queue.MosipQueueManager; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; @@ -40,6 +41,9 @@ public abstract class MosipVerticleAPIManager extends MosipVerticleManager { @Autowired ObjectMapper objectMapper; + @Autowired + private MosipQueueConnectionFactory mosipConnectionFactory; + @Autowired private Tracing tracing; @@ -128,7 +132,7 @@ public void configureHealthCheckEndpoint(Vertx vertx, Router router, final Strin future -> healthCheckHandler.senderHealthHandler(future, vertx, sendAddress)); } if (servletPath.contains("print") || servletPath.contains("abismiddleware")) { - healthCheckHandler.register("queuecheck", future -> healthCheckHandler.queueHealthChecker(future, mosipQueueManager)); + healthCheckHandler.register("queuecheck", future -> healthCheckHandler.queueHealthChecker(future, mosipQueueManager, mosipConnectionFactory)); healthCheckHandler.register( servletPath.substring(servletPath.lastIndexOf("/") + 1, servletPath.length()) + "Verticle", future -> healthCheckHandler.consumerHealthHandler(future, vertx, consumeAddress)); 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 761776b584e..9f02ca4822b 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 @@ -15,16 +15,16 @@ import java.sql.SQLException; import java.sql.Statement; -import javax.jms.BytesMessage; -import javax.jms.MessageConsumer; -import javax.jms.MessageProducer; -import javax.jms.Queue; -import javax.jms.Session; +import javax.jms.*; +import io.mosip.kernel.core.exception.ExceptionUtils; import io.mosip.kernel.core.virusscanner.spi.VirusScanner; +import io.mosip.registration.processor.core.constant.LoggerFileConstant; import io.mosip.registration.processor.core.queue.factory.MosipActiveMq; import io.mosip.registration.processor.core.queue.factory.MosipQueue; +import io.mosip.registration.processor.core.queue.factory.QueueListener; import io.mosip.registration.processor.core.queue.impl.TransportExceptionListener; +import io.mosip.registration.processor.core.spi.queue.MosipQueueConnectionFactory; import io.mosip.registration.processor.core.spi.queue.MosipQueueManager; import org.apache.activemq.ActiveMQConnection; import org.apache.activemq.ActiveMQConnectionFactory; @@ -68,6 +68,9 @@ */ public class StageHealthCheckHandler implements HealthCheckHandler { private HealthChecks healthChecks; + + MosipQueue mosipQueue = null; + boolean isConsumerStarted = false; private final AuthProvider authProvider; private ObjectMapper objectMapper; private String driver; @@ -144,39 +147,48 @@ public StageHealthCheckHandler register(String name, long timeout, Handler promise, MosipQueueManager mosipQueueManager) { - try { + public void queueHealthChecker(Promise promise, MosipQueueManager mosipQueueManager, MosipQueueConnectionFactory mosipConnectionFactory) { - String message = "Ping"; - MosipQueue mosipQueue = new MosipActiveMq(HealthConstant.QUEUE_ADDRESS, queueUsername, queuePassword, queueBrokerUrl); - mosipQueueManager.send(mosipQueue, message.getBytes(), HealthConstant.QUEUE_ADDRESS); - - ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(queueUsername, - queuePassword, queueBrokerUrl); - ActiveMQConnection activemQConn = (ActiveMQConnection) connection; - if (activemQConn == null || activemQConn.isClosed()) { - connection = activeMQConnectionFactory.createConnection(); - activemQConn = (ActiveMQConnection) connection; - activemQConn.addTransportListener(new TransportExceptionListener()); - if (session == null) { - connection.start(); - this.session = this.connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Queue destination = session.createQueue(HealthConstant.QUEUE_ADDRESS); - messageConsumer = session.createConsumer(destination); - } - } - String res = new String(((ActiveMQBytesMessage) messageConsumer.receive()).getContent().data); - if (res == null || !message.equalsIgnoreCase(res)) { - final JsonObject result = resultBuilder.create().add(HealthConstant.ERROR, "Could not read response from queue").build(); - promise.complete(Status.KO(result)); + try { + final String msg = "Ping"; + + if (mosipQueue == null) + mosipQueue = mosipConnectionFactory.createConnection("ACTIVEMQ", queueUsername, + queuePassword, queueBrokerUrl); + + mosipQueueManager.send(mosipQueue, msg.getBytes(), HealthConstant.QUEUE_ADDRESS); + + if (!isConsumerStarted) { + QueueListener listener = new QueueListener() { + @Override + public void setListener(Message message) { + try { + consumerListener(message, promise, msg); + } catch (Exception e) { + LOGGER.error(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString(), "Unable to check activemq health", ExceptionUtils.getStackTrace(e)); + } + } + }; + mosipQueueManager.consume(mosipQueue, HealthConstant.QUEUE_ADDRESS, listener); + isConsumerStarted = true; } - final JsonObject result = resultBuilder.create().add(HealthConstant.RESPONSE, res).build(); - promise.complete(Status.OK(result)); } catch (Exception e) { + isConsumerStarted = false; + mosipQueue = null; final JsonObject result = resultBuilder.create().add(HealthConstant.ERROR, e.getMessage()).build(); promise.complete(Status.KO(result)); } } + public void consumerListener(Message message, Promise promise, String msg) { + String res = new String(((ActiveMQBytesMessage) message).getContent().data); + if (res == null || !msg.equalsIgnoreCase(res)) { + final JsonObject result = resultBuilder.create().add(HealthConstant.ERROR, "Could not read response from queue").build(); + promise.complete(Status.KO(result)); + } + final JsonObject result = resultBuilder.create().add(HealthConstant.RESPONSE, res).build(); + promise.complete(Status.OK(result)); + } /** * @param configuration diff --git a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/queue/impl/MosipActiveMqImpl.java b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/queue/impl/MosipActiveMqImpl.java index 4b7b28d5d1b..58268659f41 100644 --- a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/queue/impl/MosipActiveMqImpl.java +++ b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/queue/impl/MosipActiveMqImpl.java @@ -43,6 +43,7 @@ public class MosipActiveMqImpl implements MosipQueueManager private Session session; private Destination destination; private static final String LINE_SEPERATOR = "----------------"; + private int retryCount = 10; /** * The method to set up session and destination @@ -204,16 +205,23 @@ public byte[] consume(MosipQueue mosipQueue, String address, QueueListener objec destination = session.createQueue(address); consumer = session.createConsumer(destination); consumer.setMessageListener(QueueListenerFactory.getListener(mosipQueue.getQueueName(), object)); - } catch (JMSException e) { - + } catch (JMSException | NullPointerException e) { regProcLogger.error("*******CONSUME EXCEPTION *****", "*******CONSUME EXCEPTION *****", "*******CONSUME EXCEPTION *****", ExceptionUtils.getFullStackTrace(e)); regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), "", "MosipActiveMqImpl::consume():: error with error message " + PlatformErrorMessages.RPR_MQI_UNABLE_TO_CONSUME_FROM_QUEUE.getMessage()); - throw new ConnectionUnavailableException( - PlatformErrorMessages.RPR_MQI_UNABLE_TO_CONSUME_FROM_QUEUE.getMessage()); + if (e instanceof NullPointerException && retryCount > 0) { + retryCount = retryCount - 1; + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + "", "Could not obtain queue connection. System will retry for 10 times. retrycount = " + + retryCount); + consume(mosipQueue, address, object); + } else { + throw new ConnectionUnavailableException( + PlatformErrorMessages.RPR_MQI_UNABLE_TO_CONSUME_FROM_QUEUE.getMessage()); + } } regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", "MosipActiveMqImpl::consume()::exit"); From c6c45fd20394898f46e66303f81227bd9cc072d0 Mon Sep 17 00:00:00 2001 From: Monobikash Das Date: Fri, 5 Aug 2022 18:57:49 +0530 Subject: [PATCH 032/133] MOSIP-23025 : healthcheck and retry fix for activemq connection --- .../MosipVerticleAPIManager.java | 6 +- .../StageHealthCheckHandler.java | 74 +++++++++++-------- .../core/queue/impl/MosipActiveMqImpl.java | 17 ++++- 3 files changed, 61 insertions(+), 36 deletions(-) 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 22416fcea07..6aedfbbd3ca 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 @@ -2,6 +2,7 @@ import io.mosip.kernel.core.virusscanner.spi.VirusScanner; import io.mosip.registration.processor.core.queue.factory.MosipQueue; +import io.mosip.registration.processor.core.spi.queue.MosipQueueConnectionFactory; import io.mosip.registration.processor.core.spi.queue.MosipQueueManager; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; @@ -40,6 +41,9 @@ public abstract class MosipVerticleAPIManager extends MosipVerticleManager { @Autowired ObjectMapper objectMapper; + @Autowired + private MosipQueueConnectionFactory mosipConnectionFactory; + @Autowired private Tracing tracing; @@ -128,7 +132,7 @@ public void configureHealthCheckEndpoint(Vertx vertx, Router router, final Strin future -> healthCheckHandler.senderHealthHandler(future, vertx, sendAddress)); } if (servletPath.contains("print") || servletPath.contains("abismiddleware")) { - healthCheckHandler.register("queuecheck", future -> healthCheckHandler.queueHealthChecker(future, mosipQueueManager)); + healthCheckHandler.register("queuecheck", future -> healthCheckHandler.queueHealthChecker(future, mosipQueueManager, mosipConnectionFactory)); healthCheckHandler.register( servletPath.substring(servletPath.lastIndexOf("/") + 1, servletPath.length()) + "Verticle", future -> healthCheckHandler.consumerHealthHandler(future, vertx, consumeAddress)); 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 761776b584e..9f02ca4822b 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 @@ -15,16 +15,16 @@ import java.sql.SQLException; import java.sql.Statement; -import javax.jms.BytesMessage; -import javax.jms.MessageConsumer; -import javax.jms.MessageProducer; -import javax.jms.Queue; -import javax.jms.Session; +import javax.jms.*; +import io.mosip.kernel.core.exception.ExceptionUtils; import io.mosip.kernel.core.virusscanner.spi.VirusScanner; +import io.mosip.registration.processor.core.constant.LoggerFileConstant; import io.mosip.registration.processor.core.queue.factory.MosipActiveMq; import io.mosip.registration.processor.core.queue.factory.MosipQueue; +import io.mosip.registration.processor.core.queue.factory.QueueListener; import io.mosip.registration.processor.core.queue.impl.TransportExceptionListener; +import io.mosip.registration.processor.core.spi.queue.MosipQueueConnectionFactory; import io.mosip.registration.processor.core.spi.queue.MosipQueueManager; import org.apache.activemq.ActiveMQConnection; import org.apache.activemq.ActiveMQConnectionFactory; @@ -68,6 +68,9 @@ */ public class StageHealthCheckHandler implements HealthCheckHandler { private HealthChecks healthChecks; + + MosipQueue mosipQueue = null; + boolean isConsumerStarted = false; private final AuthProvider authProvider; private ObjectMapper objectMapper; private String driver; @@ -144,39 +147,48 @@ public StageHealthCheckHandler register(String name, long timeout, Handler promise, MosipQueueManager mosipQueueManager) { - try { + public void queueHealthChecker(Promise promise, MosipQueueManager mosipQueueManager, MosipQueueConnectionFactory mosipConnectionFactory) { - String message = "Ping"; - MosipQueue mosipQueue = new MosipActiveMq(HealthConstant.QUEUE_ADDRESS, queueUsername, queuePassword, queueBrokerUrl); - mosipQueueManager.send(mosipQueue, message.getBytes(), HealthConstant.QUEUE_ADDRESS); - - ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(queueUsername, - queuePassword, queueBrokerUrl); - ActiveMQConnection activemQConn = (ActiveMQConnection) connection; - if (activemQConn == null || activemQConn.isClosed()) { - connection = activeMQConnectionFactory.createConnection(); - activemQConn = (ActiveMQConnection) connection; - activemQConn.addTransportListener(new TransportExceptionListener()); - if (session == null) { - connection.start(); - this.session = this.connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Queue destination = session.createQueue(HealthConstant.QUEUE_ADDRESS); - messageConsumer = session.createConsumer(destination); - } - } - String res = new String(((ActiveMQBytesMessage) messageConsumer.receive()).getContent().data); - if (res == null || !message.equalsIgnoreCase(res)) { - final JsonObject result = resultBuilder.create().add(HealthConstant.ERROR, "Could not read response from queue").build(); - promise.complete(Status.KO(result)); + try { + final String msg = "Ping"; + + if (mosipQueue == null) + mosipQueue = mosipConnectionFactory.createConnection("ACTIVEMQ", queueUsername, + queuePassword, queueBrokerUrl); + + mosipQueueManager.send(mosipQueue, msg.getBytes(), HealthConstant.QUEUE_ADDRESS); + + if (!isConsumerStarted) { + QueueListener listener = new QueueListener() { + @Override + public void setListener(Message message) { + try { + consumerListener(message, promise, msg); + } catch (Exception e) { + LOGGER.error(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString(), "Unable to check activemq health", ExceptionUtils.getStackTrace(e)); + } + } + }; + mosipQueueManager.consume(mosipQueue, HealthConstant.QUEUE_ADDRESS, listener); + isConsumerStarted = true; } - final JsonObject result = resultBuilder.create().add(HealthConstant.RESPONSE, res).build(); - promise.complete(Status.OK(result)); } catch (Exception e) { + isConsumerStarted = false; + mosipQueue = null; final JsonObject result = resultBuilder.create().add(HealthConstant.ERROR, e.getMessage()).build(); promise.complete(Status.KO(result)); } } + public void consumerListener(Message message, Promise promise, String msg) { + String res = new String(((ActiveMQBytesMessage) message).getContent().data); + if (res == null || !msg.equalsIgnoreCase(res)) { + final JsonObject result = resultBuilder.create().add(HealthConstant.ERROR, "Could not read response from queue").build(); + promise.complete(Status.KO(result)); + } + final JsonObject result = resultBuilder.create().add(HealthConstant.RESPONSE, res).build(); + promise.complete(Status.OK(result)); + } /** * @param configuration diff --git a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/queue/impl/MosipActiveMqImpl.java b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/queue/impl/MosipActiveMqImpl.java index 4b7b28d5d1b..4a54c65f1ae 100644 --- a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/queue/impl/MosipActiveMqImpl.java +++ b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/queue/impl/MosipActiveMqImpl.java @@ -15,6 +15,7 @@ import org.apache.activemq.ActiveMQConnection; import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.commons.lang.exception.ExceptionUtils; +import org.springframework.beans.factory.annotation.Value; import javax.jms.BytesMessage; import javax.jms.Connection; @@ -43,6 +44,8 @@ public class MosipActiveMqImpl implements MosipQueueManager private Session session; private Destination destination; private static final String LINE_SEPERATOR = "----------------"; + @Value("${registration.processor.queue.connection.retry.count:10}") + private int retryCount; /** * The method to set up session and destination @@ -204,16 +207,22 @@ public byte[] consume(MosipQueue mosipQueue, String address, QueueListener objec destination = session.createQueue(address); consumer = session.createConsumer(destination); consumer.setMessageListener(QueueListenerFactory.getListener(mosipQueue.getQueueName(), object)); - } catch (JMSException e) { - + } catch (JMSException | NullPointerException e) { regProcLogger.error("*******CONSUME EXCEPTION *****", "*******CONSUME EXCEPTION *****", "*******CONSUME EXCEPTION *****", ExceptionUtils.getFullStackTrace(e)); regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), "", "MosipActiveMqImpl::consume():: error with error message " + PlatformErrorMessages.RPR_MQI_UNABLE_TO_CONSUME_FROM_QUEUE.getMessage()); - throw new ConnectionUnavailableException( - PlatformErrorMessages.RPR_MQI_UNABLE_TO_CONSUME_FROM_QUEUE.getMessage()); + if (e instanceof NullPointerException && retryCount > 0) { + regProcLogger.warn(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + "", "Could not obtain queue connection. System will retry for "+ retryCount +" more times."); + retryCount = retryCount - 1; + consume(mosipQueue, address, object); + } else { + throw new ConnectionUnavailableException( + PlatformErrorMessages.RPR_MQI_UNABLE_TO_CONSUME_FROM_QUEUE.getMessage()); + } } regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", "MosipActiveMqImpl::consume()::exit"); From fb191c5dae0c6faca9f69aa689c1321bf3edee04 Mon Sep 17 00:00:00 2001 From: Monobikash Das Date: Tue, 9 Aug 2022 11:32:36 +0530 Subject: [PATCH 033/133] Added routing configuration for securezone --- .../notification/stage/SecurezoneNotificationStage.java | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/registration-processor/pre-processor/registration-processor-securezone-notification-stage/src/main/java/io/mosip/registration/processor/securezone/notification/stage/SecurezoneNotificationStage.java b/registration-processor/pre-processor/registration-processor-securezone-notification-stage/src/main/java/io/mosip/registration/processor/securezone/notification/stage/SecurezoneNotificationStage.java index f00d395e189..e7a12e896a4 100644 --- a/registration-processor/pre-processor/registration-processor-securezone-notification-stage/src/main/java/io/mosip/registration/processor/securezone/notification/stage/SecurezoneNotificationStage.java +++ b/registration-processor/pre-processor/registration-processor-securezone-notification-stage/src/main/java/io/mosip/registration/processor/securezone/notification/stage/SecurezoneNotificationStage.java @@ -80,6 +80,9 @@ public class SecurezoneNotificationStage extends MosipVerticleAPIManager { */ private MosipEventBus mosipEventBus; + @Value("${securezone.routing.enabled:true}") + private boolean routingEnabled; + /** * After this time intervel, message should be considered as expired (In * seconds). @@ -305,7 +308,8 @@ private void failure(RoutingContext routingContext) { * @param messageDTO the message DTO */ public void sendMessage(MessageDTO messageDTO) { - this.send(this.mosipEventBus, MessageBusAddress.SECUREZONE_NOTIFICATION_OUT, messageDTO); + if (routingEnabled) + this.send(this.mosipEventBus, MessageBusAddress.SECUREZONE_NOTIFICATION_OUT, messageDTO); } @Override From da718db314bea72a7c993fd714b3825efa476ae7 Mon Sep 17 00:00:00 2001 From: syed-salman-technoforte Date: Tue, 16 Aug 2022 12:13:04 +0530 Subject: [PATCH 034/133] [ MOSIP-23587 ] added healthcheck.txt under /home/mosip/landing --- .../init/registration-processor-dmz-packet-server/Dockerfile | 1 + .../registration-processor-dmz-packet-server/healthcheck.txt | 1 + 2 files changed, 2 insertions(+) create mode 100644 registration-processor/init/registration-processor-dmz-packet-server/healthcheck.txt diff --git a/registration-processor/init/registration-processor-dmz-packet-server/Dockerfile b/registration-processor/init/registration-processor-dmz-packet-server/Dockerfile index f0754330506..dc11c026753 100644 --- a/registration-processor/init/registration-processor-dmz-packet-server/Dockerfile +++ b/registration-processor/init/registration-processor-dmz-packet-server/Dockerfile @@ -2,4 +2,5 @@ FROM nginx VOLUME /home/mosip COPY nginx.conf /etc/nginx/nginx.conf +COPY healthcheck.txt /home/mosip/landing/healthcheck.txt EXPOSE 8082 diff --git a/registration-processor/init/registration-processor-dmz-packet-server/healthcheck.txt b/registration-processor/init/registration-processor-dmz-packet-server/healthcheck.txt new file mode 100644 index 00000000000..6e7150c9fc4 --- /dev/null +++ b/registration-processor/init/registration-processor-dmz-packet-server/healthcheck.txt @@ -0,0 +1 @@ +regproc dmz packet server is up !!! \ No newline at end of file From e2dbe5fd541af4492da792a098465f7bb94eb432 Mon Sep 17 00:00:00 2001 From: Keshav Mishra Date: Tue, 16 Aug 2022 12:22:46 +0530 Subject: [PATCH 035/133] Update version.xml --- .../init/registration-processor-dmz-packet-server/version.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/registration-processor/init/registration-processor-dmz-packet-server/version.xml b/registration-processor/init/registration-processor-dmz-packet-server/version.xml index d1e6928bf1a..f50eaa718f3 100644 --- a/registration-processor/init/registration-processor-dmz-packet-server/version.xml +++ b/registration-processor/init/registration-processor-dmz-packet-server/version.xml @@ -1,2 +1,2 @@ -1.2.0.1-SNAPSHOT +release-1.2.0.1 From a43a208c8db4cfd6cab16c40d6f142fb961d7208 Mon Sep 17 00:00:00 2001 From: Monobikash Das Date: Tue, 16 Aug 2022 13:46:28 +0530 Subject: [PATCH 036/133] MOSIP-23466 : updated the transaction type --- db_release_scripts/mosip_regprc/dml/regprc-transaction_type.csv | 2 ++ db_scripts/mosip_regprc/dml/regprc-transaction_type.csv | 2 ++ 2 files changed, 4 insertions(+) diff --git a/db_release_scripts/mosip_regprc/dml/regprc-transaction_type.csv b/db_release_scripts/mosip_regprc/dml/regprc-transaction_type.csv index 9637e52692d..8b812c5e06e 100644 --- a/db_release_scripts/mosip_regprc/dml/regprc-transaction_type.csv +++ b/db_release_scripts/mosip_regprc/dml/regprc-transaction_type.csv @@ -32,3 +32,5 @@ 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() +VERIFICATION,transaction done,eng,TRUE,MOSIP_SYSTEM,now() diff --git a/db_scripts/mosip_regprc/dml/regprc-transaction_type.csv b/db_scripts/mosip_regprc/dml/regprc-transaction_type.csv index 9637e52692d..8b812c5e06e 100644 --- a/db_scripts/mosip_regprc/dml/regprc-transaction_type.csv +++ b/db_scripts/mosip_regprc/dml/regprc-transaction_type.csv @@ -32,3 +32,5 @@ 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() +VERIFICATION,transaction done,eng,TRUE,MOSIP_SYSTEM,now() From a65222bb56aadb7bed7caaa3ccd0b678426ba2fb Mon Sep 17 00:00:00 2001 From: Shilpa M Date: Thu, 18 Aug 2022 17:31:49 +0530 Subject: [PATCH 037/133] scipt name changes --- .../{mosip_regprc_release_deploy.properties => deploy.properties} | 0 .../mosip_regprc/{mosip_regprc_release_db_deploy.sh => deploy.sh} | 0 .../mosip_regprc/{mosip_regprc_revoke_db_deploy.sh => revoke.sh} | 0 .../sql/{1.1.4_regprc-scripts_release.sql => 1.1.4_release.sql} | 0 .../sql/{1.1.4_regprc-scripts_revoke.sql => 1.1.4_revoke.sql} | 0 .../sql/{1.1.5_regprc-scripts_release.sql => 1.1.5_release.sql} | 0 .../sql/{1.1.5_regprc-scripts_revoke.sql => 1.1.5_revoke.sql} | 0 .../sql/{1.2_regprc-scripts_release.sql => 1.2.0_release.sql} | 0 .../sql/{1.2_regprc-scripts_revoke.sql => 1.2.0_revoke.sql} | 0 9 files changed, 0 insertions(+), 0 deletions(-) rename db_release_scripts/mosip_regprc/{mosip_regprc_release_deploy.properties => deploy.properties} (100%) rename db_release_scripts/mosip_regprc/{mosip_regprc_release_db_deploy.sh => deploy.sh} (100%) rename db_release_scripts/mosip_regprc/{mosip_regprc_revoke_db_deploy.sh => revoke.sh} (100%) rename db_release_scripts/mosip_regprc/sql/{1.1.4_regprc-scripts_release.sql => 1.1.4_release.sql} (100%) rename db_release_scripts/mosip_regprc/sql/{1.1.4_regprc-scripts_revoke.sql => 1.1.4_revoke.sql} (100%) rename db_release_scripts/mosip_regprc/sql/{1.1.5_regprc-scripts_release.sql => 1.1.5_release.sql} (100%) rename db_release_scripts/mosip_regprc/sql/{1.1.5_regprc-scripts_revoke.sql => 1.1.5_revoke.sql} (100%) rename db_release_scripts/mosip_regprc/sql/{1.2_regprc-scripts_release.sql => 1.2.0_release.sql} (100%) rename db_release_scripts/mosip_regprc/sql/{1.2_regprc-scripts_revoke.sql => 1.2.0_revoke.sql} (100%) diff --git a/db_release_scripts/mosip_regprc/mosip_regprc_release_deploy.properties b/db_release_scripts/mosip_regprc/deploy.properties similarity index 100% rename from db_release_scripts/mosip_regprc/mosip_regprc_release_deploy.properties rename to db_release_scripts/mosip_regprc/deploy.properties diff --git a/db_release_scripts/mosip_regprc/mosip_regprc_release_db_deploy.sh b/db_release_scripts/mosip_regprc/deploy.sh similarity index 100% rename from db_release_scripts/mosip_regprc/mosip_regprc_release_db_deploy.sh rename to db_release_scripts/mosip_regprc/deploy.sh diff --git a/db_release_scripts/mosip_regprc/mosip_regprc_revoke_db_deploy.sh b/db_release_scripts/mosip_regprc/revoke.sh similarity index 100% rename from db_release_scripts/mosip_regprc/mosip_regprc_revoke_db_deploy.sh rename to db_release_scripts/mosip_regprc/revoke.sh 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_release.sql similarity index 100% rename from db_release_scripts/mosip_regprc/sql/1.1.4_regprc-scripts_release.sql rename to db_release_scripts/mosip_regprc/sql/1.1.4_release.sql 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_revoke.sql similarity index 100% rename from db_release_scripts/mosip_regprc/sql/1.1.4_regprc-scripts_revoke.sql rename to db_release_scripts/mosip_regprc/sql/1.1.4_revoke.sql 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_release.sql similarity index 100% rename from db_release_scripts/mosip_regprc/sql/1.1.5_regprc-scripts_release.sql rename to db_release_scripts/mosip_regprc/sql/1.1.5_release.sql 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_revoke.sql similarity index 100% rename from db_release_scripts/mosip_regprc/sql/1.1.5_regprc-scripts_revoke.sql rename to db_release_scripts/mosip_regprc/sql/1.1.5_revoke.sql diff --git a/db_release_scripts/mosip_regprc/sql/1.2_regprc-scripts_release.sql b/db_release_scripts/mosip_regprc/sql/1.2.0_release.sql similarity index 100% rename from db_release_scripts/mosip_regprc/sql/1.2_regprc-scripts_release.sql rename to db_release_scripts/mosip_regprc/sql/1.2.0_release.sql diff --git a/db_release_scripts/mosip_regprc/sql/1.2_regprc-scripts_revoke.sql b/db_release_scripts/mosip_regprc/sql/1.2.0_revoke.sql similarity index 100% rename from db_release_scripts/mosip_regprc/sql/1.2_regprc-scripts_revoke.sql rename to db_release_scripts/mosip_regprc/sql/1.2.0_revoke.sql From 6c8c35a896f539a3ff5dbf66a7349fcd7d72108f Mon Sep 17 00:00:00 2001 From: Monobikash Das <43202165+MonobikashDas@users.noreply.github.com> Date: Tue, 23 Aug 2022 12:00:35 +0530 Subject: [PATCH 038/133] MOSIP-23655 : Added trancate --- db_scripts/mosip_regprc/dml.sql | 20 +------------------- 1 file changed, 1 insertion(+), 19 deletions(-) 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; - - - - - - - - - - - - - - - - - - From a8acb73ce1952092411204ec2ebcfbf616cc3c4c Mon Sep 17 00:00:00 2001 From: Monobikash Das <43202165+MonobikashDas@users.noreply.github.com> Date: Tue, 23 Aug 2022 17:34:35 +0530 Subject: [PATCH 039/133] removed duplicate --- db_scripts/mosip_regprc/dml/regprc-transaction_type.csv | 1 - 1 file changed, 1 deletion(-) diff --git a/db_scripts/mosip_regprc/dml/regprc-transaction_type.csv b/db_scripts/mosip_regprc/dml/regprc-transaction_type.csv index 8b812c5e06e..1d55586a892 100644 --- a/db_scripts/mosip_regprc/dml/regprc-transaction_type.csv +++ b/db_scripts/mosip_regprc/dml/regprc-transaction_type.csv @@ -33,4 +33,3 @@ 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() -VERIFICATION,transaction done,eng,TRUE,MOSIP_SYSTEM,now() From 36f0a41d40829c6b42021bdc1a6a850134f5ff29 Mon Sep 17 00:00:00 2001 From: Monobikash Das <43202165+MonobikashDas@users.noreply.github.com> Date: Tue, 23 Aug 2022 19:34:49 +0530 Subject: [PATCH 040/133] added source (#1598) --- db_scripts/mosip_regprc/ddl/regprc-reg_bio_ref.sql | 1 - db_scripts/mosip_regprc/ddl/regprc-registration_list.sql | 1 + 2 files changed, 1 insertion(+), 1 deletion(-) 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/ddl/regprc-registration_list.sql b/db_scripts/mosip_regprc/ddl/regprc-registration_list.sql index 77a0c84de58..d2ca73b380a 100644 --- a/db_scripts/mosip_regprc/ddl/regprc-registration_list.sql +++ b/db_scripts/mosip_regprc/ddl/regprc-registration_list.sql @@ -16,6 +16,7 @@ CREATE TABLE regprc.registration_list( upd_dtimes timestamp, is_deleted boolean DEFAULT FALSE, del_dtimes timestamp, + source character varying, name character varying, phone character varying, email character varying, From faea47dfbf72bb4a5611a5099ac05fdf61f75bd6 Mon Sep 17 00:00:00 2001 From: Monobikash Das Date: Tue, 6 Sep 2022 11:58:10 +0530 Subject: [PATCH 041/133] MOSIP-23584 : removed queue check for print stage health check --- .../core/abstractverticle/MosipVerticleAPIManager.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 6aedfbbd3ca..658271c303e 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 @@ -131,7 +131,7 @@ public void configureHealthCheckEndpoint(Vertx vertx, Router router, final Strin servletPath.substring(servletPath.lastIndexOf("/") + 1, servletPath.length()) + "Verticle", future -> healthCheckHandler.senderHealthHandler(future, vertx, sendAddress)); } - if (servletPath.contains("print") || servletPath.contains("abismiddleware")) { + if (servletPath.contains("abismiddleware")) { healthCheckHandler.register("queuecheck", future -> healthCheckHandler.queueHealthChecker(future, mosipQueueManager, mosipConnectionFactory)); healthCheckHandler.register( servletPath.substring(servletPath.lastIndexOf("/") + 1, servletPath.length()) + "Verticle", From 276d477332857c560024e4f0e08269ce7c361a40 Mon Sep 17 00:00:00 2001 From: Monobikash Das <43202165+MonobikashDas@users.noreply.github.com> Date: Tue, 6 Sep 2022 12:00:58 +0530 Subject: [PATCH 042/133] MOSIP-23584 : removed queue check for print stage health check (#1602) --- .../core/abstractverticle/MosipVerticleAPIManager.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 6aedfbbd3ca..658271c303e 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 @@ -131,7 +131,7 @@ public void configureHealthCheckEndpoint(Vertx vertx, Router router, final Strin servletPath.substring(servletPath.lastIndexOf("/") + 1, servletPath.length()) + "Verticle", future -> healthCheckHandler.senderHealthHandler(future, vertx, sendAddress)); } - if (servletPath.contains("print") || servletPath.contains("abismiddleware")) { + if (servletPath.contains("abismiddleware")) { healthCheckHandler.register("queuecheck", future -> healthCheckHandler.queueHealthChecker(future, mosipQueueManager, mosipConnectionFactory)); healthCheckHandler.register( servletPath.substring(servletPath.lastIndexOf("/") + 1, servletPath.length()) + "Verticle", From f333b3d41f6b833a6ae71f26aa228fa0d6753886 Mon Sep 17 00:00:00 2001 From: Monobikash Das Date: Wed, 7 Sep 2022 19:24:16 +0530 Subject: [PATCH 043/133] MOSIP-23749: resttemplate performance issue --- .../rest/client/utils/RestApiClient.java | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) 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 4243bf303ac..4e00986da0d 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 @@ -28,6 +28,7 @@ import org.apache.http.util.EntityUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.context.annotation.Lazy; import org.springframework.core.env.Environment; @@ -68,6 +69,12 @@ public class RestApiClient { /** The logger. */ private final Logger logger = RegProcessorLogger.getLogger(RestApiClient.class); + @Value("${registration.processor.httpclient.connections.max.per.host:20}") + private int maxConnectionPerRoute; + + @Value("${registration.processor.httpclient.connections.max:100}") + private int totalMaxConnection; + /** The builder. */ @Autowired RestTemplateBuilder builder; @@ -81,6 +88,14 @@ public class RestApiClient { @Qualifier("selfTokenRestTemplate") RestTemplate localRestTemplate; + @PostConstruct + private void loadRestTemplate() { + localRestTemplate = getRestTemplate(); + logger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), + LoggerFileConstant.APPLICATIONID.toString(), "loadRestTemplate completed successfully"); + } + + /** * Gets the api. * * @@ -210,6 +225,16 @@ public int headApi(URI uri) throws Exception { } public RestTemplate getRestTemplate() { + logger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), + LoggerFileConstant.APPLICATIONID.toString(), Arrays.asList(environment.getActiveProfiles()).toString()); + + CloseableHttpClient httpClient = HttpClients.custom() + .setMaxConnPerRoute(maxConnectionPerRoute).setMaxConnTotal(totalMaxConnection).build(); + + HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(); + + requestFactory.setHttpClient(httpClient); + localRestTemplate.setRequestFactory(requestFactory); return localRestTemplate; } From e37541b56575aecb1a085263cd8d63fc993da0e7 Mon Sep 17 00:00:00 2001 From: Monobikash Das <43202165+MonobikashDas@users.noreply.github.com> Date: Mon, 12 Sep 2022 18:18:04 +0530 Subject: [PATCH 044/133] removed duplicate source column --- db_scripts/mosip_regprc/ddl/regprc-registration_list.sql | 1 - 1 file changed, 1 deletion(-) diff --git a/db_scripts/mosip_regprc/ddl/regprc-registration_list.sql b/db_scripts/mosip_regprc/ddl/regprc-registration_list.sql index d2ca73b380a..77a0c84de58 100644 --- a/db_scripts/mosip_regprc/ddl/regprc-registration_list.sql +++ b/db_scripts/mosip_regprc/ddl/regprc-registration_list.sql @@ -16,7 +16,6 @@ CREATE TABLE regprc.registration_list( upd_dtimes timestamp, is_deleted boolean DEFAULT FALSE, del_dtimes timestamp, - source character varying, name character varying, phone character varying, email character varying, From 1b7d48c8002893445a75e80e3d5e24e8ee0237d1 Mon Sep 17 00:00:00 2001 From: urviljoshi Date: Fri, 16 Sep 2022 16:52:48 +0530 Subject: [PATCH 045/133] removed unnessasary bean overriding --- .../rest/client/utils/RestApiClient.java | 18 ------------------ 1 file changed, 18 deletions(-) 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 4e00986da0d..ccf2d90853f 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 @@ -88,14 +88,6 @@ public class RestApiClient { @Qualifier("selfTokenRestTemplate") RestTemplate localRestTemplate; - @PostConstruct - private void loadRestTemplate() { - localRestTemplate = getRestTemplate(); - logger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), - LoggerFileConstant.APPLICATIONID.toString(), "loadRestTemplate completed successfully"); - } - - /** * Gets the api. * * @@ -225,16 +217,6 @@ public int headApi(URI uri) throws Exception { } public RestTemplate getRestTemplate() { - logger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), - LoggerFileConstant.APPLICATIONID.toString(), Arrays.asList(environment.getActiveProfiles()).toString()); - - CloseableHttpClient httpClient = HttpClients.custom() - .setMaxConnPerRoute(maxConnectionPerRoute).setMaxConnTotal(totalMaxConnection).build(); - - HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(); - - requestFactory.setHttpClient(httpClient); - localRestTemplate.setRequestFactory(requestFactory); return localRestTemplate; } From 93216147940183dc256b245e25a49abf7b3a16a9 Mon Sep 17 00:00:00 2001 From: Monobikash Das Date: Fri, 23 Sep 2022 12:47:19 +0530 Subject: [PATCH 046/133] MOSIP-23943 : fixed global variable issue --- .../validator/PacketValidateProcessor.java | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) 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 6815fc5635a..bb63f76892d 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 @@ -154,8 +154,6 @@ public class PacketValidateProcessor { 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; @@ -172,6 +170,7 @@ 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 { @@ -199,9 +198,10 @@ public MessageDTO process(MessageDTO object, String stageName) { if (isValid) { // save audit details InternalRegistrationStatusDto finalRegistrationStatusDto = registrationStatusDto; + String finalRegistrationId = registrationId; Runnable r = () -> { try { - auditUtility.saveAuditDetails(registrationId, + auditUtility.saveAuditDetails(finalRegistrationId, finalRegistrationStatusDto.getRegistrationType()); } catch (Exception e) { regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), @@ -482,12 +482,12 @@ private void reverseDataSync(String id, String process, LogDescription descripti } } if (preRegId == null || preRegId.trim().isEmpty()) { - regProcLogger.info(LoggerFileConstant.REGISTRATIONID.toString(), registrationId, + regProcLogger.info(LoggerFileConstant.REGISTRATIONID.toString(), id, "Pre-registration id not present.", "Reverse datasync is not applicable for the registration id"); return; } - if (registrationId != null) { + if (id != null) { packetValidationDto.setTransactionSuccessful(false); MainResponseDTO mainResponseDto = null; if (preRegId != null && !preRegId.trim().isEmpty()) { @@ -499,14 +499,14 @@ private void reverseDataSync(String id, String process, LogDescription descripti reverseDataSyncRequestDto.setPreRegistrationIds(Arrays.asList(preRegId)); mainRequestDto.setRequest(reverseDataSyncRequestDto); regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), - LoggerFileConstant.REGISTRATIONID.toString(), registrationId, + 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(), registrationId, + LoggerFileConstant.REGISTRATIONID.toString(), id, "\"PacketValidateProcessor::reverseDataSync()::ReverseDataSync Api call ended with response data : " + JsonUtil.objectMapperObjectToJson(mainResponseDto)); packetValidationDto.setTransactionSuccessful(true); @@ -514,7 +514,7 @@ private void reverseDataSync(String id, String process, LogDescription descripti } if (mainResponseDto != null && mainResponseDto.getErrors() != null && mainResponseDto.getErrors().size() > 0) { - regProcLogger.error(LoggerFileConstant.REGISTRATIONID.toString(), registrationId, + regProcLogger.error(LoggerFileConstant.REGISTRATIONID.toString(), id, PlatformErrorMessages.REVERSE_DATA_SYNC_FAILED.getMessage(), mainResponseDto.getErrors().toString()); packetValidationDto.setTransactionSuccessful(false); @@ -526,7 +526,7 @@ private void reverseDataSync(String id, String process, LogDescription descripti + " null response from rest client "); } else { packetValidationDto.setTransactionSuccessful(true); - regProcLogger.info(LoggerFileConstant.REGISTRATIONID.toString(), registrationId, + regProcLogger.info(LoggerFileConstant.REGISTRATIONID.toString(), id, PlatformSuccessMessages.REVERSE_DATA_SYNC_SUCCESS.getMessage(), ""); } @@ -548,6 +548,7 @@ private void updateErrorFlags(InternalRegistrationStatusDto registrationStatusDt private void sendNotification(SyncRegistrationEntity regEntity, InternalRegistrationStatusDto registrationStatusDto, boolean isTransactionSuccessful) { try { + String registrationId = registrationStatusDto.getRegistrationId(); if (regEntity.getOptionalValues() != null) { String[] allNotificationTypes = notificationTypes.split("\\|"); boolean isProcessingSuccess; From 90f07580ac540592a8ea25de7a3d5042ce917774 Mon Sep 17 00:00:00 2001 From: pramod444 Date: Thu, 29 Sep 2022 10:25:59 +0000 Subject: [PATCH 047/133] Release Bot Pre-release changes --- README.md | 4 +- pom.xml | 2 +- registration-processor/core-processor/pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../registration-processor-abis/pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 2 +- .../pom.xml | 4 +- .../pom.xml | 2 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- registration-processor/init/pom.xml | 2 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../mosip-stage-executor/pom.xml | 4 +- registration-processor/pom.xml | 52 +++++++++---------- registration-processor/post-processor/pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- registration-processor/pre-processor/pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../qc-users-manger/pom.xml | 2 +- .../pom.xml | 4 +- .../dependency-reduced-pom.xml | 6 +-- .../pom.xml | 6 +-- .../registration-processor-core/pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 6 +-- .../pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- registration-processor/stage-groups/pom.xml | 4 +- .../pom.xml | 8 +-- .../pom.xml | 12 ++--- .../pom.xml | 14 ++--- .../pom.xml | 10 ++-- .../pom.xml | 16 +++--- .../pom.xml | 12 ++--- .../pom.xml | 14 ++--- .../workflow-engine/pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- 55 files changed, 161 insertions(+), 161 deletions(-) diff --git a/README.md b/README.md index b8d6b37cc06..0f6c7f9eb78 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&id=mosip_registration) # Registration Processor diff --git a/pom.xml b/pom.xml index 965197ff54e..ae08308e5ca 100644 --- a/pom.xml +++ b/pom.xml @@ -4,7 +4,7 @@ 4.0.0 io.mosip registration - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 pom MOSIP Registration Parent POM diff --git a/registration-processor/core-processor/pom.xml b/registration-processor/core-processor/pom.xml index 106d77739de..351e147b9d6 100644 --- a/registration-processor/core-processor/pom.xml +++ b/registration-processor/core-processor/pom.xml @@ -5,9 +5,9 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 core-processor core-processor diff --git a/registration-processor/core-processor/registration-processor-abis-handler-stage/pom.xml b/registration-processor/core-processor/registration-processor-abis-handler-stage/pom.xml index b49fc181c4d..772656286b9 100644 --- a/registration-processor/core-processor/registration-processor-abis-handler-stage/pom.xml +++ b/registration-processor/core-processor/registration-processor-abis-handler-stage/pom.xml @@ -5,11 +5,11 @@ io.mosip.registrationprocessor core-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-abis-handler-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 jar UTF-8 diff --git a/registration-processor/core-processor/registration-processor-abis-middleware-stage/pom.xml b/registration-processor/core-processor/registration-processor-abis-middleware-stage/pom.xml index 8495dd388f4..96485b993a8 100644 --- a/registration-processor/core-processor/registration-processor-abis-middleware-stage/pom.xml +++ b/registration-processor/core-processor/registration-processor-abis-middleware-stage/pom.xml @@ -5,10 +5,10 @@ io.mosip.registrationprocessor core-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-abis-middleware-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 jar UTF-8 diff --git a/registration-processor/core-processor/registration-processor-abis/pom.xml b/registration-processor/core-processor/registration-processor-abis/pom.xml index 29a7bcb63ff..9d0d4370574 100644 --- a/registration-processor/core-processor/registration-processor-abis/pom.xml +++ b/registration-processor/core-processor/registration-processor-abis/pom.xml @@ -8,10 +8,10 @@ io.mosip.registrationprocessor core-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-abis - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-abis UTF-8 diff --git a/registration-processor/core-processor/registration-processor-bio-dedupe-stage/pom.xml b/registration-processor/core-processor/registration-processor-bio-dedupe-stage/pom.xml index 737ae711b55..0f16b444e8f 100644 --- a/registration-processor/core-processor/registration-processor-bio-dedupe-stage/pom.xml +++ b/registration-processor/core-processor/registration-processor-bio-dedupe-stage/pom.xml @@ -5,11 +5,11 @@ io.mosip.registrationprocessor core-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-bio-dedupe-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 jar UTF-8 diff --git a/registration-processor/core-processor/registration-processor-biometric-authentication-stage/pom.xml b/registration-processor/core-processor/registration-processor-biometric-authentication-stage/pom.xml index 871df8996a9..06092177c26 100644 --- a/registration-processor/core-processor/registration-processor-biometric-authentication-stage/pom.xml +++ b/registration-processor/core-processor/registration-processor-biometric-authentication-stage/pom.xml @@ -5,10 +5,10 @@ io.mosip.registrationprocessor core-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-biometric-authentication-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 jar UTF-8 diff --git a/registration-processor/core-processor/registration-processor-biometric-extraction-stage/pom.xml b/registration-processor/core-processor/registration-processor-biometric-extraction-stage/pom.xml index b7c2f9d2ed0..bceda4de3de 100644 --- a/registration-processor/core-processor/registration-processor-biometric-extraction-stage/pom.xml +++ b/registration-processor/core-processor/registration-processor-biometric-extraction-stage/pom.xml @@ -5,7 +5,7 @@ io.mosip.registrationprocessor core-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-biometric-extraction-stage jar diff --git a/registration-processor/core-processor/registration-processor-demo-dedupe-stage/pom.xml b/registration-processor/core-processor/registration-processor-demo-dedupe-stage/pom.xml index bf2643428fd..32c7a9cdbb6 100644 --- a/registration-processor/core-processor/registration-processor-demo-dedupe-stage/pom.xml +++ b/registration-processor/core-processor/registration-processor-demo-dedupe-stage/pom.xml @@ -5,10 +5,10 @@ io.mosip.registrationprocessor core-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-demo-dedupe-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 jar UTF-8 diff --git a/registration-processor/core-processor/registration-processor-finalization-stage/pom.xml b/registration-processor/core-processor/registration-processor-finalization-stage/pom.xml index 1a52f000158..d6ec3d102a0 100644 --- a/registration-processor/core-processor/registration-processor-finalization-stage/pom.xml +++ b/registration-processor/core-processor/registration-processor-finalization-stage/pom.xml @@ -5,7 +5,7 @@ io.mosip.registrationprocessor core-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-finalization-stage registration-processor-finalization-stage diff --git a/registration-processor/core-processor/registration-processor-manual-adjudication-stage/pom.xml b/registration-processor/core-processor/registration-processor-manual-adjudication-stage/pom.xml index 1db77ee63d4..fda716669f3 100644 --- a/registration-processor/core-processor/registration-processor-manual-adjudication-stage/pom.xml +++ b/registration-processor/core-processor/registration-processor-manual-adjudication-stage/pom.xml @@ -8,11 +8,11 @@ io.mosip.registrationprocessor core-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-manual-adjudication-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 UTF-8 diff --git a/registration-processor/core-processor/registration-processor-uin-generator-stage/pom.xml b/registration-processor/core-processor/registration-processor-uin-generator-stage/pom.xml index abb698a38ad..ea0d5a2eb73 100644 --- a/registration-processor/core-processor/registration-processor-uin-generator-stage/pom.xml +++ b/registration-processor/core-processor/registration-processor-uin-generator-stage/pom.xml @@ -4,10 +4,10 @@ io.mosip.registrationprocessor core-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-uin-generator-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 jar UTF-8 diff --git a/registration-processor/core-processor/registration-processor-verification-stage/pom.xml b/registration-processor/core-processor/registration-processor-verification-stage/pom.xml index c4206b67be5..5eacfaf200b 100644 --- a/registration-processor/core-processor/registration-processor-verification-stage/pom.xml +++ b/registration-processor/core-processor/registration-processor-verification-stage/pom.xml @@ -8,11 +8,11 @@ io.mosip.registrationprocessor core-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-verification-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 UTF-8 diff --git a/registration-processor/init/pom.xml b/registration-processor/init/pom.xml index 494e4fea9da..acb9a8eaf40 100644 --- a/registration-processor/init/pom.xml +++ b/registration-processor/init/pom.xml @@ -6,7 +6,7 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 init diff --git a/registration-processor/init/registration-processor-packet-receiver-stage/pom.xml b/registration-processor/init/registration-processor-packet-receiver-stage/pom.xml index 906a591c711..8c01e101a59 100644 --- a/registration-processor/init/registration-processor-packet-receiver-stage/pom.xml +++ b/registration-processor/init/registration-processor-packet-receiver-stage/pom.xml @@ -7,11 +7,11 @@ io.mosip.registrationprocessor init - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-packet-receiver-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 jar registration-processor-packet-receiver-stage diff --git a/registration-processor/init/registration-processor-registration-status-service/pom.xml b/registration-processor/init/registration-processor-registration-status-service/pom.xml index 01e8d688bfd..cee40b9c641 100644 --- a/registration-processor/init/registration-processor-registration-status-service/pom.xml +++ b/registration-processor/init/registration-processor-registration-status-service/pom.xml @@ -8,10 +8,10 @@ io.mosip.registrationprocessor init - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-registration-status-service - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-registration-status-service diff --git a/registration-processor/mosip-stage-executor/pom.xml b/registration-processor/mosip-stage-executor/pom.xml index ce7f722007d..78dd5a1c966 100644 --- a/registration-processor/mosip-stage-executor/pom.xml +++ b/registration-processor/mosip-stage-executor/pom.xml @@ -5,11 +5,11 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 mosip-stage-executor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 diff --git a/registration-processor/pom.xml b/registration-processor/pom.xml index f9e4d379b60..506a510191f 100644 --- a/registration-processor/pom.xml +++ b/registration-processor/pom.xml @@ -5,12 +5,12 @@ io.mosip registration - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 io.mosip.registrationprocessor registration-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 pom registration-processor @@ -108,32 +108,32 @@ 0.1.55 - 1.2.0.1-SNAPSHOT - 1.2.0.1-SNAPSHOT - 1.2.0.1-SNAPSHOT - 1.2.0.1-SNAPSHOT - 1.2.0.1-SNAPSHOT - 1.2.0.1-SNAPSHOT - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 + 1.2.0.1-B1 + 1.2.0.1-B1 + 1.2.0.1-B1 + 1.2.0.1-B1 + 1.2.0.1-B1 + 1.2.0.1-B1 - 1.2.0.1-SNAPSHOT - 1.2.0.1-SNAPSHOT - 1.2.0.1-SNAPSHOT - 1.2.0.1-SNAPSHOT - 1.2.0.1-SNAPSHOT - 1.2.0.1-SNAPSHOT - 1.2.0.1-SNAPSHOT - 1.2.0.1-SNAPSHOT - 1.2.0.1-SNAPSHOT - 1.2.0.1-SNAPSHOT - 1.2.0.1-SNAPSHOT - 1.2.0.1-SNAPSHOT - 1.2.0.1-SNAPSHOT - 1.2.0.1-SNAPSHOT - 1.2.0.1-SNAPSHOT - 1.2.0.1-SNAPSHOT - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 + 1.2.0.1-B1 + 1.2.0.1-B1 + 1.2.0.1-B1 + 1.2.0.1-B1 + 1.2.0.1-B1 + 1.2.0.1-B1 + 1.2.0.1-B1 + 1.2.0.1-B1 + 1.2.0.1-B1 + 1.2.0.1-B1 + 1.2.0.1-B1 + 1.2.0.1-B1 + 1.2.0.1-B1 + 1.2.0.1-B1 + 1.2.0.1-B1 + 1.2.0.1-B1 **/dto/**, **/exception/*Exception.java, **/config/*Config.java, diff --git a/registration-processor/post-processor/pom.xml b/registration-processor/post-processor/pom.xml index f3d3bd158e6..ac3a2ba4971 100644 --- a/registration-processor/post-processor/pom.xml +++ b/registration-processor/post-processor/pom.xml @@ -6,9 +6,9 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 post-processor post-processor diff --git a/registration-processor/post-processor/registration-processor-message-sender-stage/pom.xml b/registration-processor/post-processor/registration-processor-message-sender-stage/pom.xml index 94b54a878aa..9078acad095 100644 --- a/registration-processor/post-processor/registration-processor-message-sender-stage/pom.xml +++ b/registration-processor/post-processor/registration-processor-message-sender-stage/pom.xml @@ -7,11 +7,11 @@ io.mosip.registrationprocessor post-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-message-sender-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 UTF-8 UTF-8 diff --git a/registration-processor/post-processor/registration-processor-printing-stage/pom.xml b/registration-processor/post-processor/registration-processor-printing-stage/pom.xml index 9ef76784ae8..0f16514303c 100644 --- a/registration-processor/post-processor/registration-processor-printing-stage/pom.xml +++ b/registration-processor/post-processor/registration-processor-printing-stage/pom.xml @@ -6,10 +6,10 @@ io.mosip.registrationprocessor post-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-printing-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 UTF-8 UTF-8 diff --git a/registration-processor/post-processor/registration-processor-registration-transaction-service/pom.xml b/registration-processor/post-processor/registration-processor-registration-transaction-service/pom.xml index 7722fe24934..9eeba25f5ac 100644 --- a/registration-processor/post-processor/registration-processor-registration-transaction-service/pom.xml +++ b/registration-processor/post-processor/registration-processor-registration-transaction-service/pom.xml @@ -5,10 +5,10 @@ io.mosip.registrationprocessor post-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-registration-transaction-service - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-registration-transaction-service UTF-8 diff --git a/registration-processor/pre-processor/pom.xml b/registration-processor/pre-processor/pom.xml index dbbd3483267..c9fcd668989 100644 --- a/registration-processor/pre-processor/pom.xml +++ b/registration-processor/pre-processor/pom.xml @@ -7,9 +7,9 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 pre-processor pre-processor diff --git a/registration-processor/pre-processor/registration-processor-cmd-validator-stage/pom.xml b/registration-processor/pre-processor/registration-processor-cmd-validator-stage/pom.xml index 6a5ecd53db8..5f80375a435 100644 --- a/registration-processor/pre-processor/registration-processor-cmd-validator-stage/pom.xml +++ b/registration-processor/pre-processor/registration-processor-cmd-validator-stage/pom.xml @@ -6,10 +6,10 @@ io.mosip.registrationprocessor pre-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-cmd-validator-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-cmd-validator-stage UTF-8 diff --git a/registration-processor/pre-processor/registration-processor-introducer-validator-stage/pom.xml b/registration-processor/pre-processor/registration-processor-introducer-validator-stage/pom.xml index 80f2a06dc20..3e312282a42 100644 --- a/registration-processor/pre-processor/registration-processor-introducer-validator-stage/pom.xml +++ b/registration-processor/pre-processor/registration-processor-introducer-validator-stage/pom.xml @@ -6,10 +6,10 @@ io.mosip.registrationprocessor pre-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-introducer-validator-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-introducer-validator-stage UTF-8 diff --git a/registration-processor/pre-processor/registration-processor-operator-validator-stage/pom.xml b/registration-processor/pre-processor/registration-processor-operator-validator-stage/pom.xml index f5c7d2ebf0d..bd76683991d 100644 --- a/registration-processor/pre-processor/registration-processor-operator-validator-stage/pom.xml +++ b/registration-processor/pre-processor/registration-processor-operator-validator-stage/pom.xml @@ -6,10 +6,10 @@ io.mosip.registrationprocessor pre-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-operator-validator-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-operator-validator-stage UTF-8 diff --git a/registration-processor/pre-processor/registration-processor-packet-classifier-stage/pom.xml b/registration-processor/pre-processor/registration-processor-packet-classifier-stage/pom.xml index a18de10078e..648118ceadb 100644 --- a/registration-processor/pre-processor/registration-processor-packet-classifier-stage/pom.xml +++ b/registration-processor/pre-processor/registration-processor-packet-classifier-stage/pom.xml @@ -7,10 +7,10 @@ io.mosip.registrationprocessor pre-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-packet-classifier-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 jar UTF-8 diff --git a/registration-processor/pre-processor/registration-processor-packet-uploader-stage/pom.xml b/registration-processor/pre-processor/registration-processor-packet-uploader-stage/pom.xml index cfe699815a0..58413e23803 100644 --- a/registration-processor/pre-processor/registration-processor-packet-uploader-stage/pom.xml +++ b/registration-processor/pre-processor/registration-processor-packet-uploader-stage/pom.xml @@ -9,9 +9,9 @@ io.mosip.registrationprocessor pre-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 UTF-8 diff --git a/registration-processor/pre-processor/registration-processor-packet-validator-stage/pom.xml b/registration-processor/pre-processor/registration-processor-packet-validator-stage/pom.xml index c62733d01d2..409c4bf220f 100644 --- a/registration-processor/pre-processor/registration-processor-packet-validator-stage/pom.xml +++ b/registration-processor/pre-processor/registration-processor-packet-validator-stage/pom.xml @@ -7,10 +7,10 @@ io.mosip.registrationprocessor pre-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-packet-validator-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 jar UTF-8 diff --git a/registration-processor/pre-processor/registration-processor-quality-classifier-stage/pom.xml b/registration-processor/pre-processor/registration-processor-quality-classifier-stage/pom.xml index 9f357aea6d6..833e75c92a3 100644 --- a/registration-processor/pre-processor/registration-processor-quality-classifier-stage/pom.xml +++ b/registration-processor/pre-processor/registration-processor-quality-classifier-stage/pom.xml @@ -5,11 +5,11 @@ io.mosip.registrationprocessor pre-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-quality-classifier-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 UTF-8 diff --git a/registration-processor/pre-processor/registration-processor-securezone-notification-stage/pom.xml b/registration-processor/pre-processor/registration-processor-securezone-notification-stage/pom.xml index adac7a92910..b3ab0e91704 100644 --- a/registration-processor/pre-processor/registration-processor-securezone-notification-stage/pom.xml +++ b/registration-processor/pre-processor/registration-processor-securezone-notification-stage/pom.xml @@ -5,10 +5,10 @@ pre-processor io.mosip.registrationprocessor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 4.0.0 - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-securezone-notification-stage diff --git a/registration-processor/pre-processor/registration-processor-supervisor-validator-stage/pom.xml b/registration-processor/pre-processor/registration-processor-supervisor-validator-stage/pom.xml index f1735ff282c..d4d05723920 100644 --- a/registration-processor/pre-processor/registration-processor-supervisor-validator-stage/pom.xml +++ b/registration-processor/pre-processor/registration-processor-supervisor-validator-stage/pom.xml @@ -6,10 +6,10 @@ io.mosip.registrationprocessor pre-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-supervisor-validator-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-supervisor-validator-stage UTF-8 diff --git a/registration-processor/qc-users-manger/pom.xml b/registration-processor/qc-users-manger/pom.xml index f1550c8fc4a..98ef5146ae5 100644 --- a/registration-processor/qc-users-manger/pom.xml +++ b/registration-processor/qc-users-manger/pom.xml @@ -8,7 +8,7 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 diff --git a/registration-processor/registration-processor-bio-dedupe-service-impl/pom.xml b/registration-processor/registration-processor-bio-dedupe-service-impl/pom.xml index b6d2f0eddd3..33f74594ab8 100644 --- a/registration-processor/registration-processor-bio-dedupe-service-impl/pom.xml +++ b/registration-processor/registration-processor-bio-dedupe-service-impl/pom.xml @@ -5,11 +5,11 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-bio-dedupe-service-impl - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-bio-dedupe-service-impl diff --git a/registration-processor/registration-processor-common-camel-bridge/dependency-reduced-pom.xml b/registration-processor/registration-processor-common-camel-bridge/dependency-reduced-pom.xml index 051ece7c025..6c645e5bfb2 100644 --- a/registration-processor/registration-processor-common-camel-bridge/dependency-reduced-pom.xml +++ b/registration-processor/registration-processor-common-camel-bridge/dependency-reduced-pom.xml @@ -3,11 +3,11 @@ registration-processor io.mosip.registrationprocessor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 4.0.0 registration-processor-common-camel-bridge - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 @@ -102,7 +102,7 @@ io.mosip.registration.processor.camel.bridge.MosipCamelBridge 1.0.5 - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 diff --git a/registration-processor/registration-processor-common-camel-bridge/pom.xml b/registration-processor/registration-processor-common-camel-bridge/pom.xml index 3e67f0bae81..4ec488235ab 100644 --- a/registration-processor/registration-processor-common-camel-bridge/pom.xml +++ b/registration-processor/registration-processor-common-camel-bridge/pom.xml @@ -6,16 +6,16 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-common-camel-bridge - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 jar io.mosip.registration.processor.camel.bridge.MosipCamelBridge 1.0.5 - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 diff --git a/registration-processor/registration-processor-core/pom.xml b/registration-processor/registration-processor-core/pom.xml index 41f0268f633..422e0df5f33 100644 --- a/registration-processor/registration-processor-core/pom.xml +++ b/registration-processor/registration-processor-core/pom.xml @@ -7,10 +7,10 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-core - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 org.mockito diff --git a/registration-processor/registration-processor-info-storage-service/pom.xml b/registration-processor/registration-processor-info-storage-service/pom.xml index 08a80dd04b5..81de5a580ad 100644 --- a/registration-processor/registration-processor-info-storage-service/pom.xml +++ b/registration-processor/registration-processor-info-storage-service/pom.xml @@ -7,10 +7,10 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-info-storage-service - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-info-storage-service UTF-8 diff --git a/registration-processor/registration-processor-message-sender-impl/pom.xml b/registration-processor/registration-processor-message-sender-impl/pom.xml index fa5a7b048dd..5132a6aa025 100644 --- a/registration-processor/registration-processor-message-sender-impl/pom.xml +++ b/registration-processor/registration-processor-message-sender-impl/pom.xml @@ -8,11 +8,11 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-message-sender-impl - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 UTF-8 diff --git a/registration-processor/registration-processor-notification-service/pom.xml b/registration-processor/registration-processor-notification-service/pom.xml index ed32e34884a..9e72de49c3f 100644 --- a/registration-processor/registration-processor-notification-service/pom.xml +++ b/registration-processor/registration-processor-notification-service/pom.xml @@ -8,15 +8,15 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-notification-service - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 UTF-8 UTF-8 - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 diff --git a/registration-processor/registration-processor-packet-manager/pom.xml b/registration-processor/registration-processor-packet-manager/pom.xml index c32bc40c734..dbef7053f11 100644 --- a/registration-processor/registration-processor-packet-manager/pom.xml +++ b/registration-processor/registration-processor-packet-manager/pom.xml @@ -7,12 +7,12 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-packet-manager registration-processor-packet-manager - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 UTF-8 diff --git a/registration-processor/registration-processor-registration-status-service-impl/pom.xml b/registration-processor/registration-processor-registration-status-service-impl/pom.xml index bdcbf23f5c3..cd6e25f01ba 100644 --- a/registration-processor/registration-processor-registration-status-service-impl/pom.xml +++ b/registration-processor/registration-processor-registration-status-service-impl/pom.xml @@ -8,10 +8,10 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-registration-status-service-impl - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 UTF-8 diff --git a/registration-processor/registration-processor-rest-client/pom.xml b/registration-processor/registration-processor-rest-client/pom.xml index abcae1d9870..bdd642bd8b4 100644 --- a/registration-processor/registration-processor-rest-client/pom.xml +++ b/registration-processor/registration-processor-rest-client/pom.xml @@ -9,12 +9,12 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-rest-client registration-processor-rest-client - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 UTF-8 diff --git a/registration-processor/stage-groups/pom.xml b/registration-processor/stage-groups/pom.xml index 8eb2b176739..f1dbd341adb 100644 --- a/registration-processor/stage-groups/pom.xml +++ b/registration-processor/stage-groups/pom.xml @@ -7,9 +7,9 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 stage-groups stage-groups diff --git a/registration-processor/stage-groups/registration-processor-stage-group-1/pom.xml b/registration-processor/stage-groups/registration-processor-stage-group-1/pom.xml index 2b85ca79676..ed78ae79825 100644 --- a/registration-processor/stage-groups/registration-processor-stage-group-1/pom.xml +++ b/registration-processor/stage-groups/registration-processor-stage-group-1/pom.xml @@ -5,11 +5,11 @@ io.mosip.registrationprocessor stage-groups - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-stage-group-1 - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 UTF-8 @@ -21,14 +21,14 @@ io.mosip.registrationprocessor mosip-stage-executor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 io.mosip.registrationprocessor registration-processor-packet-receiver-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 diff --git a/registration-processor/stage-groups/registration-processor-stage-group-2/pom.xml b/registration-processor/stage-groups/registration-processor-stage-group-2/pom.xml index 5a878a5566d..ada325f055d 100644 --- a/registration-processor/stage-groups/registration-processor-stage-group-2/pom.xml +++ b/registration-processor/stage-groups/registration-processor-stage-group-2/pom.xml @@ -5,11 +5,11 @@ io.mosip.registrationprocessor stage-groups - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-stage-group-2 - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 UTF-8 @@ -21,24 +21,24 @@ io.mosip.registrationprocessor mosip-stage-executor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 io.mosip.registrationprocessor registration-processor-quality-classifier-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 io.mosip.registrationprocessor registration-processor-securezone-notification-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 io.mosip.registrationprocessor registration-processor-message-sender-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 diff --git a/registration-processor/stage-groups/registration-processor-stage-group-3/pom.xml b/registration-processor/stage-groups/registration-processor-stage-group-3/pom.xml index 2adf6045d83..e1de3540c1d 100644 --- a/registration-processor/stage-groups/registration-processor-stage-group-3/pom.xml +++ b/registration-processor/stage-groups/registration-processor-stage-group-3/pom.xml @@ -5,11 +5,11 @@ io.mosip.registrationprocessor stage-groups - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-stage-group-3 - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 UTF-8 @@ -21,29 +21,29 @@ io.mosip.registrationprocessor mosip-stage-executor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 io.mosip.registrationprocessor registration-processor-abis-handler-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 io.mosip.registrationprocessor registration-processor-abis-middleware-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 io.mosip.registrationprocessor registration-processor-bio-dedupe-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 io.mosip.registrationprocessor registration-processor-manual-adjudication-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 diff --git a/registration-processor/stage-groups/registration-processor-stage-group-4/pom.xml b/registration-processor/stage-groups/registration-processor-stage-group-4/pom.xml index 3ffb388b565..85e97e9dee6 100644 --- a/registration-processor/stage-groups/registration-processor-stage-group-4/pom.xml +++ b/registration-processor/stage-groups/registration-processor-stage-group-4/pom.xml @@ -5,11 +5,11 @@ io.mosip.registrationprocessor stage-groups - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-stage-group-4 - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 UTF-8 @@ -21,19 +21,19 @@ io.mosip.registrationprocessor mosip-stage-executor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 io.mosip.registrationprocessor registration-processor-biometric-authentication-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 io.mosip.registrationprocessor registration-processor-demo-dedupe-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 diff --git a/registration-processor/stage-groups/registration-processor-stage-group-5/pom.xml b/registration-processor/stage-groups/registration-processor-stage-group-5/pom.xml index 201a885a1af..5de03453f5f 100644 --- a/registration-processor/stage-groups/registration-processor-stage-group-5/pom.xml +++ b/registration-processor/stage-groups/registration-processor-stage-group-5/pom.xml @@ -5,11 +5,11 @@ io.mosip.registrationprocessor stage-groups - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-stage-group-5 - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 UTF-8 @@ -21,34 +21,34 @@ io.mosip.registrationprocessor mosip-stage-executor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 io.mosip.registrationprocessor registration-processor-cmd-validator-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 io.mosip.registrationprocessor registration-processor-operator-validator-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 io.mosip.registrationprocessor registration-processor-supervisor-validator-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 io.mosip.registrationprocessor registration-processor-introducer-validator-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 io.mosip.registrationprocessor registration-processor-packet-validator-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 diff --git a/registration-processor/stage-groups/registration-processor-stage-group-6/pom.xml b/registration-processor/stage-groups/registration-processor-stage-group-6/pom.xml index 681015c8a46..f4ce7933f7a 100644 --- a/registration-processor/stage-groups/registration-processor-stage-group-6/pom.xml +++ b/registration-processor/stage-groups/registration-processor-stage-group-6/pom.xml @@ -5,11 +5,11 @@ io.mosip.registrationprocessor stage-groups - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-stage-group-6 - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 UTF-8 @@ -21,24 +21,24 @@ io.mosip.registrationprocessor mosip-stage-executor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 io.mosip.registrationprocessor registration-processor-packet-uploader-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 io.mosip.registrationprocessor registration-processor-packet-classifier-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 io.mosip.registrationprocessor registration-processor-verification-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 diff --git a/registration-processor/stage-groups/registration-processor-stage-group-7/pom.xml b/registration-processor/stage-groups/registration-processor-stage-group-7/pom.xml index 3c8ffc6f066..f22d032a05b 100644 --- a/registration-processor/stage-groups/registration-processor-stage-group-7/pom.xml +++ b/registration-processor/stage-groups/registration-processor-stage-group-7/pom.xml @@ -5,11 +5,11 @@ io.mosip.registrationprocessor stage-groups - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-stage-group-7 - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 UTF-8 @@ -21,29 +21,29 @@ io.mosip.registrationprocessor mosip-stage-executor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 io.mosip.registrationprocessor registration-processor-uin-generator-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 io.mosip.registrationprocessor registration-processor-biometric-extraction-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 io.mosip.registrationprocessor registration-processor-finalization-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 io.mosip.registrationprocessor registration-processor-printing-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 diff --git a/registration-processor/workflow-engine/pom.xml b/registration-processor/workflow-engine/pom.xml index b9485169347..7bb2d165aeb 100644 --- a/registration-processor/workflow-engine/pom.xml +++ b/registration-processor/workflow-engine/pom.xml @@ -5,9 +5,9 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 workflow-engine workflow-engine diff --git a/registration-processor/workflow-engine/registration-processor-reprocessor/pom.xml b/registration-processor/workflow-engine/registration-processor-reprocessor/pom.xml index 35b437cd194..fac36d647a2 100644 --- a/registration-processor/workflow-engine/registration-processor-reprocessor/pom.xml +++ b/registration-processor/workflow-engine/registration-processor-reprocessor/pom.xml @@ -7,10 +7,10 @@ io.mosip.registrationprocessor workflow-engine - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-reprocessor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-reprocessor UTF-8 diff --git a/registration-processor/workflow-engine/registration-processor-workflow-manager-service/pom.xml b/registration-processor/workflow-engine/registration-processor-workflow-manager-service/pom.xml index c69945fe557..c17473fbd1a 100644 --- a/registration-processor/workflow-engine/registration-processor-workflow-manager-service/pom.xml +++ b/registration-processor/workflow-engine/registration-processor-workflow-manager-service/pom.xml @@ -5,10 +5,10 @@ io.mosip.registrationprocessor workflow-engine - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-workflow-manager-service - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-workflow-manager-service UTF-8 From f00acb659b921192e0f5003a144a10610a7a4be5 Mon Sep 17 00:00:00 2001 From: Keshav Mishra Date: Thu, 29 Sep 2022 23:33:09 +0530 Subject: [PATCH 048/133] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 0f6c7f9eb78..c2570e151cb 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.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&id=mosip_registration) +[![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 From 7583d0a0f33cce2bdb4b189bfba71b22b545670b Mon Sep 17 00:00:00 2001 From: Monobikash Das Date: Fri, 30 Sep 2022 16:37:36 +0530 Subject: [PATCH 049/133] pointing to kernel-biosdk-provider 1.2.0 --- registration-processor/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/registration-processor/pom.xml b/registration-processor/pom.xml index 506a510191f..1cb99130a98 100644 --- a/registration-processor/pom.xml +++ b/registration-processor/pom.xml @@ -123,7 +123,7 @@ 1.2.0.1-B1 1.2.0.1-B1 1.2.0.1-B1 - 1.2.0.1-B1 + 1.2.0 1.2.0.1-B1 1.2.0.1-B1 1.2.0.1-B1 From cb504c8ef1a9bfed4c9dbd18fef93db4fe408343 Mon Sep 17 00:00:00 2001 From: Monobikash Das Date: Fri, 7 Oct 2022 16:40:47 +0530 Subject: [PATCH 050/133] Filter exception biometrics before sending to ABIS --- .../abis/handler/stage/AbisHandlerStage.java | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) 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 39e41132de0..cd0eb8d4d9a 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 @@ -603,7 +603,7 @@ private String getDataShareUrl(String id, String process) throws Exception { priorityBasedPacketManagerService.getMetaInfo(id, process, ProviderStageName.BIO_DEDUPE)); } - byte[] content = cbeffutil.createXML(biometricRecord.getSegments()); + byte[] content = cbeffutil.createXML(filterExceptionBiometrics(biometricRecord).getSegments()); MultiValueMap map = new LinkedMultiValueMap<>(); map.add("name", individualBiometricsLabel); @@ -706,6 +706,18 @@ private void validateBiometricRecord(BiometricRecord biometricRecord, List segments = biometricRecord.getSegments().stream().filter(bio -> { + Map othersMap = bio.getOthers().entrySet().stream() + .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue())); + return (othersMap == null || !othersMap.containsKey("EXCEPTION")) ? true + : !(Boolean.parseBoolean(othersMap.get("EXCEPTION"))); + }).collect(Collectors.toList()); + BiometricRecord biorecord = new BiometricRecord(); + biorecord.setSegments(segments); + return biorecord; + } + public Map> createTypeSubtypeMapping() throws ApisResourceAccessException, DataShareException, IOException { From fad10a629b26657f6e2d4895ce453ac6f6257058 Mon Sep 17 00:00:00 2001 From: ckm007 Date: Mon, 10 Oct 2022 09:01:27 +0000 Subject: [PATCH 051/133] [MOSIP-24254] reverted pom version --- .github/workflows/push_trigger.yml | 2 +- pom.xml | 2 +- registration-processor/core-processor/pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../registration-processor-abis/pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 2 +- .../pom.xml | 4 +- .../pom.xml | 2 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- registration-processor/init/pom.xml | 2 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../mosip-stage-executor/pom.xml | 4 +- registration-processor/pom.xml | 50 +++++++++---------- registration-processor/post-processor/pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- registration-processor/pre-processor/pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../qc-users-manger/pom.xml | 2 +- .../pom.xml | 4 +- .../dependency-reduced-pom.xml | 6 +-- .../pom.xml | 6 +-- .../registration-processor-core/pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 6 +-- .../pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- registration-processor/stage-groups/pom.xml | 4 +- .../pom.xml | 8 +-- .../pom.xml | 12 ++--- .../pom.xml | 14 +++--- .../pom.xml | 10 ++-- .../pom.xml | 16 +++--- .../pom.xml | 12 ++--- .../pom.xml | 14 +++--- .../workflow-engine/pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- 55 files changed, 159 insertions(+), 159 deletions(-) diff --git a/.github/workflows/push_trigger.yml b/.github/workflows/push_trigger.yml index 296b982e759..193b1799401 100644 --- a/.github/workflows/push_trigger.yml +++ b/.github/workflows/push_trigger.yml @@ -370,7 +370,7 @@ jobs: - name: Publish the maven package run: | - mvn deploy -DaltDeploymentRepository=ossrh::default::${{ secrets.RELEASE_URL }} -s $GITHUB_WORKSPACE/settings.xml -f pom.xml + mvn deploy -DaltDeploymentRepository=ossrh::default::${{ secrets.OSSRH_SNAPSHOT_URL }} -s $GITHUB_WORKSPACE/settings.xml -f pom.xml env: GITHUB_TOKEN: ${{ secrets.RELEASE_TOKEN }} GPG_TTY: $(tty) diff --git a/pom.xml b/pom.xml index ae08308e5ca..965197ff54e 100644 --- a/pom.xml +++ b/pom.xml @@ -4,7 +4,7 @@ 4.0.0 io.mosip registration - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT pom MOSIP Registration Parent POM diff --git a/registration-processor/core-processor/pom.xml b/registration-processor/core-processor/pom.xml index 351e147b9d6..106d77739de 100644 --- a/registration-processor/core-processor/pom.xml +++ b/registration-processor/core-processor/pom.xml @@ -5,9 +5,9 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT core-processor core-processor diff --git a/registration-processor/core-processor/registration-processor-abis-handler-stage/pom.xml b/registration-processor/core-processor/registration-processor-abis-handler-stage/pom.xml index 772656286b9..b49fc181c4d 100644 --- a/registration-processor/core-processor/registration-processor-abis-handler-stage/pom.xml +++ b/registration-processor/core-processor/registration-processor-abis-handler-stage/pom.xml @@ -5,11 +5,11 @@ io.mosip.registrationprocessor core-processor - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT registration-processor-abis-handler-stage - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT jar UTF-8 diff --git a/registration-processor/core-processor/registration-processor-abis-middleware-stage/pom.xml b/registration-processor/core-processor/registration-processor-abis-middleware-stage/pom.xml index 96485b993a8..8495dd388f4 100644 --- a/registration-processor/core-processor/registration-processor-abis-middleware-stage/pom.xml +++ b/registration-processor/core-processor/registration-processor-abis-middleware-stage/pom.xml @@ -5,10 +5,10 @@ io.mosip.registrationprocessor core-processor - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT registration-processor-abis-middleware-stage - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT jar UTF-8 diff --git a/registration-processor/core-processor/registration-processor-abis/pom.xml b/registration-processor/core-processor/registration-processor-abis/pom.xml index 9d0d4370574..29a7bcb63ff 100644 --- a/registration-processor/core-processor/registration-processor-abis/pom.xml +++ b/registration-processor/core-processor/registration-processor-abis/pom.xml @@ -8,10 +8,10 @@ io.mosip.registrationprocessor core-processor - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT registration-processor-abis - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT registration-processor-abis UTF-8 diff --git a/registration-processor/core-processor/registration-processor-bio-dedupe-stage/pom.xml b/registration-processor/core-processor/registration-processor-bio-dedupe-stage/pom.xml index 0f16b444e8f..737ae711b55 100644 --- a/registration-processor/core-processor/registration-processor-bio-dedupe-stage/pom.xml +++ b/registration-processor/core-processor/registration-processor-bio-dedupe-stage/pom.xml @@ -5,11 +5,11 @@ io.mosip.registrationprocessor core-processor - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT registration-processor-bio-dedupe-stage - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT jar UTF-8 diff --git a/registration-processor/core-processor/registration-processor-biometric-authentication-stage/pom.xml b/registration-processor/core-processor/registration-processor-biometric-authentication-stage/pom.xml index 06092177c26..871df8996a9 100644 --- a/registration-processor/core-processor/registration-processor-biometric-authentication-stage/pom.xml +++ b/registration-processor/core-processor/registration-processor-biometric-authentication-stage/pom.xml @@ -5,10 +5,10 @@ io.mosip.registrationprocessor core-processor - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT registration-processor-biometric-authentication-stage - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT jar UTF-8 diff --git a/registration-processor/core-processor/registration-processor-biometric-extraction-stage/pom.xml b/registration-processor/core-processor/registration-processor-biometric-extraction-stage/pom.xml index bceda4de3de..b7c2f9d2ed0 100644 --- a/registration-processor/core-processor/registration-processor-biometric-extraction-stage/pom.xml +++ b/registration-processor/core-processor/registration-processor-biometric-extraction-stage/pom.xml @@ -5,7 +5,7 @@ io.mosip.registrationprocessor core-processor - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT registration-processor-biometric-extraction-stage jar diff --git a/registration-processor/core-processor/registration-processor-demo-dedupe-stage/pom.xml b/registration-processor/core-processor/registration-processor-demo-dedupe-stage/pom.xml index 32c7a9cdbb6..bf2643428fd 100644 --- a/registration-processor/core-processor/registration-processor-demo-dedupe-stage/pom.xml +++ b/registration-processor/core-processor/registration-processor-demo-dedupe-stage/pom.xml @@ -5,10 +5,10 @@ io.mosip.registrationprocessor core-processor - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT registration-processor-demo-dedupe-stage - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT jar UTF-8 diff --git a/registration-processor/core-processor/registration-processor-finalization-stage/pom.xml b/registration-processor/core-processor/registration-processor-finalization-stage/pom.xml index d6ec3d102a0..1a52f000158 100644 --- a/registration-processor/core-processor/registration-processor-finalization-stage/pom.xml +++ b/registration-processor/core-processor/registration-processor-finalization-stage/pom.xml @@ -5,7 +5,7 @@ io.mosip.registrationprocessor core-processor - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT registration-processor-finalization-stage registration-processor-finalization-stage diff --git a/registration-processor/core-processor/registration-processor-manual-adjudication-stage/pom.xml b/registration-processor/core-processor/registration-processor-manual-adjudication-stage/pom.xml index fda716669f3..1db77ee63d4 100644 --- a/registration-processor/core-processor/registration-processor-manual-adjudication-stage/pom.xml +++ b/registration-processor/core-processor/registration-processor-manual-adjudication-stage/pom.xml @@ -8,11 +8,11 @@ io.mosip.registrationprocessor core-processor - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT registration-processor-manual-adjudication-stage - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT UTF-8 diff --git a/registration-processor/core-processor/registration-processor-uin-generator-stage/pom.xml b/registration-processor/core-processor/registration-processor-uin-generator-stage/pom.xml index ea0d5a2eb73..abb698a38ad 100644 --- a/registration-processor/core-processor/registration-processor-uin-generator-stage/pom.xml +++ b/registration-processor/core-processor/registration-processor-uin-generator-stage/pom.xml @@ -4,10 +4,10 @@ io.mosip.registrationprocessor core-processor - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT registration-processor-uin-generator-stage - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT jar UTF-8 diff --git a/registration-processor/core-processor/registration-processor-verification-stage/pom.xml b/registration-processor/core-processor/registration-processor-verification-stage/pom.xml index 5eacfaf200b..c4206b67be5 100644 --- a/registration-processor/core-processor/registration-processor-verification-stage/pom.xml +++ b/registration-processor/core-processor/registration-processor-verification-stage/pom.xml @@ -8,11 +8,11 @@ io.mosip.registrationprocessor core-processor - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT registration-processor-verification-stage - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT UTF-8 diff --git a/registration-processor/init/pom.xml b/registration-processor/init/pom.xml index acb9a8eaf40..494e4fea9da 100644 --- a/registration-processor/init/pom.xml +++ b/registration-processor/init/pom.xml @@ -6,7 +6,7 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT init diff --git a/registration-processor/init/registration-processor-packet-receiver-stage/pom.xml b/registration-processor/init/registration-processor-packet-receiver-stage/pom.xml index 8c01e101a59..906a591c711 100644 --- a/registration-processor/init/registration-processor-packet-receiver-stage/pom.xml +++ b/registration-processor/init/registration-processor-packet-receiver-stage/pom.xml @@ -7,11 +7,11 @@ io.mosip.registrationprocessor init - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT registration-processor-packet-receiver-stage - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT jar registration-processor-packet-receiver-stage diff --git a/registration-processor/init/registration-processor-registration-status-service/pom.xml b/registration-processor/init/registration-processor-registration-status-service/pom.xml index cee40b9c641..01e8d688bfd 100644 --- a/registration-processor/init/registration-processor-registration-status-service/pom.xml +++ b/registration-processor/init/registration-processor-registration-status-service/pom.xml @@ -8,10 +8,10 @@ io.mosip.registrationprocessor init - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT registration-processor-registration-status-service - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT registration-processor-registration-status-service diff --git a/registration-processor/mosip-stage-executor/pom.xml b/registration-processor/mosip-stage-executor/pom.xml index 78dd5a1c966..ce7f722007d 100644 --- a/registration-processor/mosip-stage-executor/pom.xml +++ b/registration-processor/mosip-stage-executor/pom.xml @@ -5,11 +5,11 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT mosip-stage-executor - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT diff --git a/registration-processor/pom.xml b/registration-processor/pom.xml index 1cb99130a98..9cd555ff9d2 100644 --- a/registration-processor/pom.xml +++ b/registration-processor/pom.xml @@ -5,12 +5,12 @@ io.mosip registration - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT io.mosip.registrationprocessor registration-processor - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT pom registration-processor @@ -108,32 +108,32 @@ 0.1.55 - 1.2.0.1-B1 - 1.2.0.1-B1 - 1.2.0.1-B1 - 1.2.0.1-B1 - 1.2.0.1-B1 - 1.2.0.1-B1 - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT + 1.2.0.1-SNAPSHOT + 1.2.0.1-SNAPSHOT + 1.2.0.1-SNAPSHOT + 1.2.0.1-SNAPSHOT + 1.2.0.1-SNAPSHOT + 1.2.0.1-SNAPSHOT - 1.2.0.1-B1 - 1.2.0.1-B1 - 1.2.0.1-B1 - 1.2.0.1-B1 - 1.2.0.1-B1 - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT + 1.2.0.1-SNAPSHOT + 1.2.0.1-SNAPSHOT + 1.2.0.1-SNAPSHOT + 1.2.0.1-SNAPSHOT + 1.2.0.1-SNAPSHOT 1.2.0 - 1.2.0.1-B1 - 1.2.0.1-B1 - 1.2.0.1-B1 - 1.2.0.1-B1 - 1.2.0.1-B1 - 1.2.0.1-B1 - 1.2.0.1-B1 - 1.2.0.1-B1 - 1.2.0.1-B1 - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT + 1.2.0.1-SNAPSHOT + 1.2.0.1-SNAPSHOT + 1.2.0.1-SNAPSHOT + 1.2.0.1-SNAPSHOT + 1.2.0.1-SNAPSHOT + 1.2.0.1-SNAPSHOT + 1.2.0.1-SNAPSHOT + 1.2.0.1-SNAPSHOT + 1.2.0.1-SNAPSHOT **/dto/**, **/exception/*Exception.java, **/config/*Config.java, diff --git a/registration-processor/post-processor/pom.xml b/registration-processor/post-processor/pom.xml index ac3a2ba4971..f3d3bd158e6 100644 --- a/registration-processor/post-processor/pom.xml +++ b/registration-processor/post-processor/pom.xml @@ -6,9 +6,9 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT post-processor post-processor diff --git a/registration-processor/post-processor/registration-processor-message-sender-stage/pom.xml b/registration-processor/post-processor/registration-processor-message-sender-stage/pom.xml index 9078acad095..94b54a878aa 100644 --- a/registration-processor/post-processor/registration-processor-message-sender-stage/pom.xml +++ b/registration-processor/post-processor/registration-processor-message-sender-stage/pom.xml @@ -7,11 +7,11 @@ io.mosip.registrationprocessor post-processor - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT registration-processor-message-sender-stage - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT UTF-8 UTF-8 diff --git a/registration-processor/post-processor/registration-processor-printing-stage/pom.xml b/registration-processor/post-processor/registration-processor-printing-stage/pom.xml index 0f16514303c..9ef76784ae8 100644 --- a/registration-processor/post-processor/registration-processor-printing-stage/pom.xml +++ b/registration-processor/post-processor/registration-processor-printing-stage/pom.xml @@ -6,10 +6,10 @@ io.mosip.registrationprocessor post-processor - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT registration-processor-printing-stage - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT UTF-8 UTF-8 diff --git a/registration-processor/post-processor/registration-processor-registration-transaction-service/pom.xml b/registration-processor/post-processor/registration-processor-registration-transaction-service/pom.xml index 9eeba25f5ac..7722fe24934 100644 --- a/registration-processor/post-processor/registration-processor-registration-transaction-service/pom.xml +++ b/registration-processor/post-processor/registration-processor-registration-transaction-service/pom.xml @@ -5,10 +5,10 @@ io.mosip.registrationprocessor post-processor - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT registration-processor-registration-transaction-service - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT registration-processor-registration-transaction-service UTF-8 diff --git a/registration-processor/pre-processor/pom.xml b/registration-processor/pre-processor/pom.xml index c9fcd668989..dbbd3483267 100644 --- a/registration-processor/pre-processor/pom.xml +++ b/registration-processor/pre-processor/pom.xml @@ -7,9 +7,9 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT pre-processor pre-processor diff --git a/registration-processor/pre-processor/registration-processor-cmd-validator-stage/pom.xml b/registration-processor/pre-processor/registration-processor-cmd-validator-stage/pom.xml index 5f80375a435..6a5ecd53db8 100644 --- a/registration-processor/pre-processor/registration-processor-cmd-validator-stage/pom.xml +++ b/registration-processor/pre-processor/registration-processor-cmd-validator-stage/pom.xml @@ -6,10 +6,10 @@ io.mosip.registrationprocessor pre-processor - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT registration-processor-cmd-validator-stage - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT registration-processor-cmd-validator-stage UTF-8 diff --git a/registration-processor/pre-processor/registration-processor-introducer-validator-stage/pom.xml b/registration-processor/pre-processor/registration-processor-introducer-validator-stage/pom.xml index 3e312282a42..80f2a06dc20 100644 --- a/registration-processor/pre-processor/registration-processor-introducer-validator-stage/pom.xml +++ b/registration-processor/pre-processor/registration-processor-introducer-validator-stage/pom.xml @@ -6,10 +6,10 @@ io.mosip.registrationprocessor pre-processor - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT registration-processor-introducer-validator-stage - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT registration-processor-introducer-validator-stage UTF-8 diff --git a/registration-processor/pre-processor/registration-processor-operator-validator-stage/pom.xml b/registration-processor/pre-processor/registration-processor-operator-validator-stage/pom.xml index bd76683991d..f5c7d2ebf0d 100644 --- a/registration-processor/pre-processor/registration-processor-operator-validator-stage/pom.xml +++ b/registration-processor/pre-processor/registration-processor-operator-validator-stage/pom.xml @@ -6,10 +6,10 @@ io.mosip.registrationprocessor pre-processor - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT registration-processor-operator-validator-stage - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT registration-processor-operator-validator-stage UTF-8 diff --git a/registration-processor/pre-processor/registration-processor-packet-classifier-stage/pom.xml b/registration-processor/pre-processor/registration-processor-packet-classifier-stage/pom.xml index 648118ceadb..a18de10078e 100644 --- a/registration-processor/pre-processor/registration-processor-packet-classifier-stage/pom.xml +++ b/registration-processor/pre-processor/registration-processor-packet-classifier-stage/pom.xml @@ -7,10 +7,10 @@ io.mosip.registrationprocessor pre-processor - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT registration-processor-packet-classifier-stage - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT jar UTF-8 diff --git a/registration-processor/pre-processor/registration-processor-packet-uploader-stage/pom.xml b/registration-processor/pre-processor/registration-processor-packet-uploader-stage/pom.xml index 58413e23803..cfe699815a0 100644 --- a/registration-processor/pre-processor/registration-processor-packet-uploader-stage/pom.xml +++ b/registration-processor/pre-processor/registration-processor-packet-uploader-stage/pom.xml @@ -9,9 +9,9 @@ io.mosip.registrationprocessor pre-processor - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT UTF-8 diff --git a/registration-processor/pre-processor/registration-processor-packet-validator-stage/pom.xml b/registration-processor/pre-processor/registration-processor-packet-validator-stage/pom.xml index 409c4bf220f..c62733d01d2 100644 --- a/registration-processor/pre-processor/registration-processor-packet-validator-stage/pom.xml +++ b/registration-processor/pre-processor/registration-processor-packet-validator-stage/pom.xml @@ -7,10 +7,10 @@ io.mosip.registrationprocessor pre-processor - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT registration-processor-packet-validator-stage - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT jar UTF-8 diff --git a/registration-processor/pre-processor/registration-processor-quality-classifier-stage/pom.xml b/registration-processor/pre-processor/registration-processor-quality-classifier-stage/pom.xml index 833e75c92a3..9f357aea6d6 100644 --- a/registration-processor/pre-processor/registration-processor-quality-classifier-stage/pom.xml +++ b/registration-processor/pre-processor/registration-processor-quality-classifier-stage/pom.xml @@ -5,11 +5,11 @@ io.mosip.registrationprocessor pre-processor - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT registration-processor-quality-classifier-stage - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT UTF-8 diff --git a/registration-processor/pre-processor/registration-processor-securezone-notification-stage/pom.xml b/registration-processor/pre-processor/registration-processor-securezone-notification-stage/pom.xml index b3ab0e91704..adac7a92910 100644 --- a/registration-processor/pre-processor/registration-processor-securezone-notification-stage/pom.xml +++ b/registration-processor/pre-processor/registration-processor-securezone-notification-stage/pom.xml @@ -5,10 +5,10 @@ pre-processor io.mosip.registrationprocessor - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT 4.0.0 - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT registration-processor-securezone-notification-stage diff --git a/registration-processor/pre-processor/registration-processor-supervisor-validator-stage/pom.xml b/registration-processor/pre-processor/registration-processor-supervisor-validator-stage/pom.xml index d4d05723920..f1735ff282c 100644 --- a/registration-processor/pre-processor/registration-processor-supervisor-validator-stage/pom.xml +++ b/registration-processor/pre-processor/registration-processor-supervisor-validator-stage/pom.xml @@ -6,10 +6,10 @@ io.mosip.registrationprocessor pre-processor - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT registration-processor-supervisor-validator-stage - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT registration-processor-supervisor-validator-stage UTF-8 diff --git a/registration-processor/qc-users-manger/pom.xml b/registration-processor/qc-users-manger/pom.xml index 98ef5146ae5..f1550c8fc4a 100644 --- a/registration-processor/qc-users-manger/pom.xml +++ b/registration-processor/qc-users-manger/pom.xml @@ -8,7 +8,7 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT diff --git a/registration-processor/registration-processor-bio-dedupe-service-impl/pom.xml b/registration-processor/registration-processor-bio-dedupe-service-impl/pom.xml index 33f74594ab8..b6d2f0eddd3 100644 --- a/registration-processor/registration-processor-bio-dedupe-service-impl/pom.xml +++ b/registration-processor/registration-processor-bio-dedupe-service-impl/pom.xml @@ -5,11 +5,11 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT registration-processor-bio-dedupe-service-impl - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT registration-processor-bio-dedupe-service-impl diff --git a/registration-processor/registration-processor-common-camel-bridge/dependency-reduced-pom.xml b/registration-processor/registration-processor-common-camel-bridge/dependency-reduced-pom.xml index 6c645e5bfb2..051ece7c025 100644 --- a/registration-processor/registration-processor-common-camel-bridge/dependency-reduced-pom.xml +++ b/registration-processor/registration-processor-common-camel-bridge/dependency-reduced-pom.xml @@ -3,11 +3,11 @@ registration-processor io.mosip.registrationprocessor - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT 4.0.0 registration-processor-common-camel-bridge - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT @@ -102,7 +102,7 @@ io.mosip.registration.processor.camel.bridge.MosipCamelBridge 1.0.5 - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT diff --git a/registration-processor/registration-processor-common-camel-bridge/pom.xml b/registration-processor/registration-processor-common-camel-bridge/pom.xml index 4ec488235ab..3e67f0bae81 100644 --- a/registration-processor/registration-processor-common-camel-bridge/pom.xml +++ b/registration-processor/registration-processor-common-camel-bridge/pom.xml @@ -6,16 +6,16 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT registration-processor-common-camel-bridge - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT jar io.mosip.registration.processor.camel.bridge.MosipCamelBridge 1.0.5 - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT diff --git a/registration-processor/registration-processor-core/pom.xml b/registration-processor/registration-processor-core/pom.xml index 422e0df5f33..41f0268f633 100644 --- a/registration-processor/registration-processor-core/pom.xml +++ b/registration-processor/registration-processor-core/pom.xml @@ -7,10 +7,10 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT registration-processor-core - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT org.mockito diff --git a/registration-processor/registration-processor-info-storage-service/pom.xml b/registration-processor/registration-processor-info-storage-service/pom.xml index 81de5a580ad..08a80dd04b5 100644 --- a/registration-processor/registration-processor-info-storage-service/pom.xml +++ b/registration-processor/registration-processor-info-storage-service/pom.xml @@ -7,10 +7,10 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT registration-processor-info-storage-service - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT registration-processor-info-storage-service UTF-8 diff --git a/registration-processor/registration-processor-message-sender-impl/pom.xml b/registration-processor/registration-processor-message-sender-impl/pom.xml index 5132a6aa025..fa5a7b048dd 100644 --- a/registration-processor/registration-processor-message-sender-impl/pom.xml +++ b/registration-processor/registration-processor-message-sender-impl/pom.xml @@ -8,11 +8,11 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT registration-processor-message-sender-impl - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT UTF-8 diff --git a/registration-processor/registration-processor-notification-service/pom.xml b/registration-processor/registration-processor-notification-service/pom.xml index 9e72de49c3f..ed32e34884a 100644 --- a/registration-processor/registration-processor-notification-service/pom.xml +++ b/registration-processor/registration-processor-notification-service/pom.xml @@ -8,15 +8,15 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT registration-processor-notification-service - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT UTF-8 UTF-8 - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT diff --git a/registration-processor/registration-processor-packet-manager/pom.xml b/registration-processor/registration-processor-packet-manager/pom.xml index dbef7053f11..c32bc40c734 100644 --- a/registration-processor/registration-processor-packet-manager/pom.xml +++ b/registration-processor/registration-processor-packet-manager/pom.xml @@ -7,12 +7,12 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT registration-processor-packet-manager registration-processor-packet-manager - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT UTF-8 diff --git a/registration-processor/registration-processor-registration-status-service-impl/pom.xml b/registration-processor/registration-processor-registration-status-service-impl/pom.xml index cd6e25f01ba..bdcbf23f5c3 100644 --- a/registration-processor/registration-processor-registration-status-service-impl/pom.xml +++ b/registration-processor/registration-processor-registration-status-service-impl/pom.xml @@ -8,10 +8,10 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT registration-processor-registration-status-service-impl - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT UTF-8 diff --git a/registration-processor/registration-processor-rest-client/pom.xml b/registration-processor/registration-processor-rest-client/pom.xml index bdd642bd8b4..abcae1d9870 100644 --- a/registration-processor/registration-processor-rest-client/pom.xml +++ b/registration-processor/registration-processor-rest-client/pom.xml @@ -9,12 +9,12 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT registration-processor-rest-client registration-processor-rest-client - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT UTF-8 diff --git a/registration-processor/stage-groups/pom.xml b/registration-processor/stage-groups/pom.xml index f1dbd341adb..8eb2b176739 100644 --- a/registration-processor/stage-groups/pom.xml +++ b/registration-processor/stage-groups/pom.xml @@ -7,9 +7,9 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT stage-groups stage-groups diff --git a/registration-processor/stage-groups/registration-processor-stage-group-1/pom.xml b/registration-processor/stage-groups/registration-processor-stage-group-1/pom.xml index ed78ae79825..2b85ca79676 100644 --- a/registration-processor/stage-groups/registration-processor-stage-group-1/pom.xml +++ b/registration-processor/stage-groups/registration-processor-stage-group-1/pom.xml @@ -5,11 +5,11 @@ io.mosip.registrationprocessor stage-groups - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT registration-processor-stage-group-1 - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT UTF-8 @@ -21,14 +21,14 @@ io.mosip.registrationprocessor mosip-stage-executor - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT io.mosip.registrationprocessor registration-processor-packet-receiver-stage - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT diff --git a/registration-processor/stage-groups/registration-processor-stage-group-2/pom.xml b/registration-processor/stage-groups/registration-processor-stage-group-2/pom.xml index ada325f055d..5a878a5566d 100644 --- a/registration-processor/stage-groups/registration-processor-stage-group-2/pom.xml +++ b/registration-processor/stage-groups/registration-processor-stage-group-2/pom.xml @@ -5,11 +5,11 @@ io.mosip.registrationprocessor stage-groups - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT registration-processor-stage-group-2 - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT UTF-8 @@ -21,24 +21,24 @@ io.mosip.registrationprocessor mosip-stage-executor - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT io.mosip.registrationprocessor registration-processor-quality-classifier-stage - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT io.mosip.registrationprocessor registration-processor-securezone-notification-stage - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT io.mosip.registrationprocessor registration-processor-message-sender-stage - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT diff --git a/registration-processor/stage-groups/registration-processor-stage-group-3/pom.xml b/registration-processor/stage-groups/registration-processor-stage-group-3/pom.xml index e1de3540c1d..2adf6045d83 100644 --- a/registration-processor/stage-groups/registration-processor-stage-group-3/pom.xml +++ b/registration-processor/stage-groups/registration-processor-stage-group-3/pom.xml @@ -5,11 +5,11 @@ io.mosip.registrationprocessor stage-groups - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT registration-processor-stage-group-3 - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT UTF-8 @@ -21,29 +21,29 @@ io.mosip.registrationprocessor mosip-stage-executor - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT io.mosip.registrationprocessor registration-processor-abis-handler-stage - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT io.mosip.registrationprocessor registration-processor-abis-middleware-stage - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT io.mosip.registrationprocessor registration-processor-bio-dedupe-stage - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT io.mosip.registrationprocessor registration-processor-manual-adjudication-stage - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT diff --git a/registration-processor/stage-groups/registration-processor-stage-group-4/pom.xml b/registration-processor/stage-groups/registration-processor-stage-group-4/pom.xml index 85e97e9dee6..3ffb388b565 100644 --- a/registration-processor/stage-groups/registration-processor-stage-group-4/pom.xml +++ b/registration-processor/stage-groups/registration-processor-stage-group-4/pom.xml @@ -5,11 +5,11 @@ io.mosip.registrationprocessor stage-groups - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT registration-processor-stage-group-4 - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT UTF-8 @@ -21,19 +21,19 @@ io.mosip.registrationprocessor mosip-stage-executor - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT io.mosip.registrationprocessor registration-processor-biometric-authentication-stage - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT io.mosip.registrationprocessor registration-processor-demo-dedupe-stage - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT diff --git a/registration-processor/stage-groups/registration-processor-stage-group-5/pom.xml b/registration-processor/stage-groups/registration-processor-stage-group-5/pom.xml index 5de03453f5f..201a885a1af 100644 --- a/registration-processor/stage-groups/registration-processor-stage-group-5/pom.xml +++ b/registration-processor/stage-groups/registration-processor-stage-group-5/pom.xml @@ -5,11 +5,11 @@ io.mosip.registrationprocessor stage-groups - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT registration-processor-stage-group-5 - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT UTF-8 @@ -21,34 +21,34 @@ io.mosip.registrationprocessor mosip-stage-executor - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT io.mosip.registrationprocessor registration-processor-cmd-validator-stage - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT io.mosip.registrationprocessor registration-processor-operator-validator-stage - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT io.mosip.registrationprocessor registration-processor-supervisor-validator-stage - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT io.mosip.registrationprocessor registration-processor-introducer-validator-stage - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT io.mosip.registrationprocessor registration-processor-packet-validator-stage - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT diff --git a/registration-processor/stage-groups/registration-processor-stage-group-6/pom.xml b/registration-processor/stage-groups/registration-processor-stage-group-6/pom.xml index f4ce7933f7a..681015c8a46 100644 --- a/registration-processor/stage-groups/registration-processor-stage-group-6/pom.xml +++ b/registration-processor/stage-groups/registration-processor-stage-group-6/pom.xml @@ -5,11 +5,11 @@ io.mosip.registrationprocessor stage-groups - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT registration-processor-stage-group-6 - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT UTF-8 @@ -21,24 +21,24 @@ io.mosip.registrationprocessor mosip-stage-executor - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT io.mosip.registrationprocessor registration-processor-packet-uploader-stage - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT io.mosip.registrationprocessor registration-processor-packet-classifier-stage - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT io.mosip.registrationprocessor registration-processor-verification-stage - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT diff --git a/registration-processor/stage-groups/registration-processor-stage-group-7/pom.xml b/registration-processor/stage-groups/registration-processor-stage-group-7/pom.xml index f22d032a05b..3c8ffc6f066 100644 --- a/registration-processor/stage-groups/registration-processor-stage-group-7/pom.xml +++ b/registration-processor/stage-groups/registration-processor-stage-group-7/pom.xml @@ -5,11 +5,11 @@ io.mosip.registrationprocessor stage-groups - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT registration-processor-stage-group-7 - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT UTF-8 @@ -21,29 +21,29 @@ io.mosip.registrationprocessor mosip-stage-executor - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT io.mosip.registrationprocessor registration-processor-uin-generator-stage - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT io.mosip.registrationprocessor registration-processor-biometric-extraction-stage - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT io.mosip.registrationprocessor registration-processor-finalization-stage - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT io.mosip.registrationprocessor registration-processor-printing-stage - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT diff --git a/registration-processor/workflow-engine/pom.xml b/registration-processor/workflow-engine/pom.xml index 7bb2d165aeb..b9485169347 100644 --- a/registration-processor/workflow-engine/pom.xml +++ b/registration-processor/workflow-engine/pom.xml @@ -5,9 +5,9 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT workflow-engine workflow-engine diff --git a/registration-processor/workflow-engine/registration-processor-reprocessor/pom.xml b/registration-processor/workflow-engine/registration-processor-reprocessor/pom.xml index fac36d647a2..35b437cd194 100644 --- a/registration-processor/workflow-engine/registration-processor-reprocessor/pom.xml +++ b/registration-processor/workflow-engine/registration-processor-reprocessor/pom.xml @@ -7,10 +7,10 @@ io.mosip.registrationprocessor workflow-engine - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT registration-processor-reprocessor - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT registration-processor-reprocessor UTF-8 diff --git a/registration-processor/workflow-engine/registration-processor-workflow-manager-service/pom.xml b/registration-processor/workflow-engine/registration-processor-workflow-manager-service/pom.xml index c17473fbd1a..c69945fe557 100644 --- a/registration-processor/workflow-engine/registration-processor-workflow-manager-service/pom.xml +++ b/registration-processor/workflow-engine/registration-processor-workflow-manager-service/pom.xml @@ -5,10 +5,10 @@ io.mosip.registrationprocessor workflow-engine - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT registration-processor-workflow-manager-service - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT registration-processor-workflow-manager-service UTF-8 From 79ff4e71ab8592f2d2f07b5b0c8dd77b9706660b Mon Sep 17 00:00:00 2001 From: ckm007 Date: Sat, 15 Oct 2022 16:48:49 +0530 Subject: [PATCH 052/133] [MOSIP-23833] renamed the sql files --- .../mosip_regprc/sql/1.1.4_upgrade.sql | 21 ++ .../mosip_regprc/sql/1.1.5_upgrade.sql | 23 ++ .../mosip_regprc/sql/1.2.0_upgrade.sql | 299 ++++++++++++++++++ db_release_scripts/mosip_regprc/upgrade.sh | 50 +++ 4 files changed, 393 insertions(+) create mode 100644 db_release_scripts/mosip_regprc/sql/1.1.4_upgrade.sql create mode 100644 db_release_scripts/mosip_regprc/sql/1.1.5_upgrade.sql create mode 100644 db_release_scripts/mosip_regprc/sql/1.2.0_upgrade.sql create mode 100644 db_release_scripts/mosip_regprc/upgrade.sh diff --git a/db_release_scripts/mosip_regprc/sql/1.1.4_upgrade.sql b/db_release_scripts/mosip_regprc/sql/1.1.4_upgrade.sql new file mode 100644 index 00000000000..6279fefa2aa --- /dev/null +++ b/db_release_scripts/mosip_regprc/sql/1.1.4_upgrade.sql @@ -0,0 +1,21 @@ +-- ------------------------------------------------------------------------------------------------- +-- 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.5_upgrade.sql b/db_release_scripts/mosip_regprc/sql/1.1.5_upgrade.sql new file mode 100644 index 00000000000..89fa3f3283e --- /dev/null +++ b/db_release_scripts/mosip_regprc/sql/1.1.5_upgrade.sql @@ -0,0 +1,23 @@ +-- ------------------------------------------------------------------------------------------------- +-- 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.2.0_upgrade.sql b/db_release_scripts/mosip_regprc/sql/1.2.0_upgrade.sql new file mode 100644 index 00000000000..d059a7740e8 --- /dev/null +++ b/db_release_scripts/mosip_regprc/sql/1.2.0_upgrade.sql @@ -0,0 +1,299 @@ +\c mosip_regprc sysadmin + +----------------------------------------------Multiple table level changes on regprc db------------------------------------------------------- + +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; + +\ir ../ddl/regprc-additional_info_request.sql + +\ir ../ddl/regprc-anonymous_profile.sql + +\ir ../ddl/regprc-reg_verification.sql + +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; +ALTER TABLE regprc.registration ADD COLUMN workflow_instance_id character varying(36); +ALTER TABLE regprc.registration ADD COLUMN source character varying; +ALTER TABLE regprc.registration ADD COLUMN iteration integer DEFAULT 1; + +ALTER TABLE regprc.individual_demographic_dedup ADD COLUMN workflow_instance_id character varying(36); +ALTER TABLE regprc.individual_demographic_dedup ADD COLUMN process character varying(36); +ALTER TABLE regprc.individual_demographic_dedup ADD COLUMN iteration integer DEFAULT 1; + + +ALTER TABLE regprc.reg_manual_verification ADD COLUMN workflow_instance_id character varying(36); + +ALTER TABLE regprc.reg_lost_uin_det ADD COLUMN workflow_instance_id character varying(36); + +ALTER TABLE regprc.reg_bio_ref ADD COLUMN workflow_instance_id character varying(36); +ALTER TABLE regprc.reg_bio_ref ADD COLUMN process character varying(36); +ALTER TABLE regprc.reg_bio_ref ADD COLUMN iteration integer DEFAULT 1; + +UPDATE regprc.registration_list SET packet_id = reg_id; +UPDATE regprc.registration a SET workflow_instance_id = b.workflow_instance_id FROM regprc.registration_list b WHERE a.reg_id = b.reg_id; +UPDATE regprc.individual_demographic_dedup a SET workflow_instance_id = b.workflow_instance_id FROM regprc.registration_list b WHERE a.reg_id = b.reg_id; +UPDATE regprc.reg_manual_verification a SET workflow_instance_id = b.workflow_instance_id FROM regprc.registration_list b WHERE a.reg_id = b.reg_id; +UPDATE regprc.reg_lost_uin_det a SET workflow_instance_id = b.workflow_instance_id FROM regprc.registration_list b WHERE a.reg_id = b.reg_id; +UPDATE regprc.reg_bio_ref a SET workflow_instance_id = b.workflow_instance_id FROM regprc.registration_list b WHERE a.reg_id = b.reg_id; + +CREATE INDEX IF NOT EXISTS idx_rbioref_crdtimes on regprc.reg_bio_ref (cr_dtimes); +CREATE INDEX IF NOT EXISTS idx_bio_ref_id ON regprc.reg_bio_ref USING btree (bio_ref_id); +DROP INDEX IF EXISTS idx_idemogd_namedobgender; +CREATE INDEX IF NOT EXISTS idx_idemogd_namedobgender on regprc.individual_demographic_dedup (name, dob,gender); +CREATE INDEX IF NOT EXISTS idx_rbioref_crdtimes on regprc.reg_bio_ref (cr_dtimes); +CREATE INDEX IF NOT EXISTS idx_rmanvrn_reqid on regprc.reg_manual_verification (request_id); +DROP INDEX IF EXISTS idx_rgstrn_ltstrbcode_ltststscode; +CREATE INDEX IF NOT EXISTS idx_rgstrn_ltstrbcode_ltststscode on regprc.registration (latest_trn_dtimes, latest_trn_status_code); +CREATE INDEX IF NOT EXISTS idx_reg_latest_trn_dtimes ON regprc.registration USING btree (latest_trn_dtimes); +CREATE INDEX IF NOT EXISTS idx_rgstrnlst_pcktid on regprc.registration_list (packet_id); +CREATE INDEX IF NOT EXISTS idx_rgstrnlst_aireqid on regprc.registration_list (additional_info_req_id); +CREATE INDEX IF NOT EXISTS idx_reg_verification_reqId on regprc.reg_verification (verification_req_id); +CREATE INDEX IF NOT EXISTS idx_reg_trn_reg_id ON regprc.registration_transaction USING btree (reg_id); +CREATE INDEX IF NOT EXISTS idx_reg_trn_status_code ON regprc.registration_transaction USING btree (status_code); +CREATE INDEX IF NOT EXISTS idx_reg_trn_trntypecode ON regprc.registration_transaction USING btree (trn_type_code); +CREATE INDEX IF NOT EXISTS idx_reg_trn_upd_dtimes ON regprc.registration_transaction USING btree (upd_dtimes); +CREATE INDEX IF NOT EXISTS idx_user_detail_cntr_id ON regprc.abis_request USING btree (bio_ref_id); +CREATE INDEX IF NOT EXISTS idx_abis_req_regtrn_id ON regprc.abis_request USING btree (ref_regtrn_id); + +ALTER TABLE regprc.individual_demographic_dedup DROP CONSTRAINT pk_idemogd_id; +ALTER TABLE regprc.individual_demographic_dedup ALTER COLUMN workflow_instance_id SET NOT NULL; +ALTER TABLE regprc.individual_demographic_dedup ADD CONSTRAINT pk_idemogd_id PRIMARY KEY (workflow_instance_id,lang_code); + +ALTER TABLE regprc.reg_bio_ref DROP CONSTRAINT pk_regbref_id; +ALTER TABLE regprc.reg_bio_ref ALTER COLUMN workflow_instance_id SET NOT NULL; +ALTER TABLE regprc.reg_bio_ref ADD CONSTRAINT pk_regbref_id PRIMARY KEY (bio_ref_id,workflow_instance_id); + +ALTER TABLE regprc.reg_lost_uin_det DROP CONSTRAINT pk_rlostd; +ALTER TABLE regprc.reg_lost_uin_det ALTER COLUMN workflow_instance_id SET NOT NULL; +ALTER TABLE regprc.reg_lost_uin_det ADD CONSTRAINT pk_rlostd PRIMARY KEY (workflow_instance_id); + +ALTER TABLE regprc.reg_manual_verification DROP CONSTRAINT pk_rmnlver_id; +ALTER TABLE regprc.reg_manual_verification ALTER COLUMN workflow_instance_id SET NOT NULL; +ALTER TABLE regprc.reg_manual_verification ADD CONSTRAINT pk_rmnlver_id PRIMARY KEY (workflow_instance_id,matched_ref_id,matched_ref_type); + +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; + +ALTER TABLE regprc.reg_manual_verification ADD CONSTRAINT fk_rmnlver_reg FOREIGN KEY (workflow_instance_id) +REFERENCES regprc.registration (workflow_instance_id) MATCH SIMPLE +ON DELETE NO ACTION ON UPDATE NO ACTION; + +ALTER TABLE regprc.reg_bio_ref ADD CONSTRAINT fk_regbrf_reg FOREIGN KEY (workflow_instance_id) +REFERENCES regprc.registration (workflow_instance_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 (workflow_instance_id) +REFERENCES regprc.registration (workflow_instance_id) MATCH SIMPLE +ON DELETE NO ACTION ON UPDATE NO ACTION; + +----------------------------------------------------------------------------------------------------------------------------------------- +ALTER TABLE regprc.registration ADD COLUMN resume_timestamp timestamp; +ALTER TABLE regprc.registration ADD COLUMN default_resume_action character varying(50); + + +--------------------------------------------------------------------------------------------------- + +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; + +------------------------------------------------------------------------------------------------------ + + +ALTER TABLE regprc.registration ADD COLUMN last_success_stage_name CHARACTER VARYING(50); +-------------------------------------------------------Add columns to registration_list---------------------------------------------- + +ALTER TABLE regprc.registration_list ADD COLUMN name character varying; +ALTER TABLE regprc.registration_list ADD COLUMN phone character varying; +ALTER TABLE regprc.registration_list ADD COLUMN email character varying; +ALTER TABLE regprc.registration_list ADD COLUMN center_id character varying; +ALTER TABLE regprc.registration_list ADD COLUMN registration_date date; +ALTER TABLE regprc.registration_list ADD COLUMN location_code character varying; + +------------------------------------------------------------------------------------------------------------------------------------------- +-------------------------------------------------Creation of crypto salt table-------------------------------------------------------------- + +\ir ../ddl/regprc-crypto_salt.sql + +-------------------------------------------------------------------------------------------------------------------------------------------- + +---------------------------------------------------------FOR HISTORY DATA---------------------------------------------- + + +UPDATE regprc.registration SET last_success_stage_name = 'PacketReceiverStage' where latest_trn_type_code='PACKET_RECEIVER' and latest_trn_status_code in ('SUCCESS' , 'PROCESSED'); +UPDATE regprc.registration SET last_success_stage_name = 'SecurezoneNotificationStage' where latest_trn_type_code='SECUREZONE_NOTIFICATION' and latest_trn_status_code in ('SUCCESS' , 'PROCESSED'); +UPDATE regprc.registration SET last_success_stage_name = 'PacketUploaderStage' where latest_trn_type_code='UPLOAD_PACKET' and latest_trn_status_code in ('SUCCESS' , 'PROCESSED'); +UPDATE regprc.registration SET last_success_stage_name = 'PacketValidatorStage' where latest_trn_type_code='VALIDATE_PACKET' and latest_trn_status_code in ('SUCCESS' , 'PROCESSED'); +UPDATE regprc.registration SET last_success_stage_name = 'PacketClassifierStage' where latest_trn_type_code='PACKET_CLASSIFICATION' and latest_trn_status_code in ('SUCCESS' , 'PROCESSED'); +UPDATE regprc.registration SET last_success_stage_name = 'QualityCheckerStage' where latest_trn_type_code='QUALITY_CHECK' and latest_trn_status_code in ('SUCCESS' , 'PROCESSED'); +UPDATE regprc.registration SET last_success_stage_name = 'OSIValidatorStage' where latest_trn_type_code='OSI_VALIDATE' and latest_trn_status_code in ('SUCCESS' , 'PROCESSED'); +UPDATE regprc.registration SET last_success_stage_name = 'ExternalStage' where latest_trn_type_code='EXTERNAL_INTEGRATION' and latest_trn_status_code in ('SUCCESS' , 'PROCESSED'); +UPDATE regprc.registration SET last_success_stage_name = 'DemoDedupeStage' where latest_trn_type_code='DEMOGRAPHIC_VERIFICATION' and latest_trn_status_code in ('SUCCESS' , 'PROCESSED'); +UPDATE regprc.registration SET last_success_stage_name = 'BioDedupeStage' where latest_trn_type_code='BIOGRAPHIC_VERIFICATION' and latest_trn_status_code in ('SUCCESS' , 'PROCESSED'); +UPDATE regprc.registration SET last_success_stage_name = 'ManualVerificationStage' where latest_trn_type_code='MANUAL_VERIFICATION' and latest_trn_status_code in ('SUCCESS' , 'PROCESSED'); +UPDATE regprc.registration SET last_success_stage_name = 'UinGeneratorStage' where latest_trn_type_code='UIN_GENERATOR' and latest_trn_status_code in ('SUCCESS' , 'PROCESSED'); +UPDATE regprc.registration SET last_success_stage_name = 'PrintingStage' where latest_trn_type_code='PRINT_SERVICE' and latest_trn_status_code in ('SUCCESS' , 'PROCESSED'); +UPDATE regprc.registration SET last_success_stage_name = 'BiometricAuthenticationStage' where latest_trn_type_code='BIOMETRIC_AUTHENTICATION' and latest_trn_status_code in ('SUCCESS' , 'PROCESSED'); + +UPDATE regprc.registration SET last_success_stage_name = 'PacketReceiverStage' where latest_trn_type_code='SECUREZONE_NOTIFICATION' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'NEW'; +UPDATE regprc.registration SET last_success_stage_name = 'SecurezoneNotificationStage' where latest_trn_type_code='UPLOAD_PACKET' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'NEW'; +UPDATE regprc.registration SET last_success_stage_name = 'PacketUploaderStage' where latest_trn_type_code='VALIDATE_PACKET' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'NEW'; +UPDATE regprc.registration SET last_success_stage_name = 'PacketValidatorStage' where latest_trn_type_code='PACKET_CLASSIFICATION' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'NEW'; +UPDATE regprc.registration SET last_success_stage_name = 'PacketClassifierStage' where latest_trn_type_code='QUALITY_CHECK' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'NEW'; +UPDATE regprc.registration SET last_success_stage_name = 'QualityCheckerStage' where latest_trn_type_code='OSI_VALIDATE' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'NEW'; +UPDATE regprc.registration SET last_success_stage_name = 'OSIValidatorStage' where latest_trn_type_code='EXTERNAL_INTEGRATION' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'NEW'; +UPDATE regprc.registration SET last_success_stage_name = 'ExternalStage' where latest_trn_type_code='DEMOGRAPHIC_VERIFICATION' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'NEW'; +UPDATE regprc.registration SET last_success_stage_name = 'DemoDedupeStage' where latest_trn_type_code='BIOGRAPHIC_VERIFICATION' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'NEW'; +UPDATE regprc.registration SET last_success_stage_name = 'BioDedupeStage' where latest_trn_type_code='MANUAL_VERIFICATION' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'NEW'; +UPDATE regprc.registration SET last_success_stage_name = 'BioDedupeStage' where latest_trn_type_code='UIN_GENERATOR' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'NEW'; +UPDATE regprc.registration SET last_success_stage_name = 'UinGeneratorStage' where latest_trn_type_code='PRINT_SERVICE' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'NEW'; + +UPDATE regprc.registration SET last_success_stage_name = 'PacketReceiverStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='SecurezoneNotificationStage' and process = 'NEW'; +UPDATE regprc.registration SET last_success_stage_name = 'SecurezoneNotificationStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='PacketUploaderStage' and process = 'NEW'; +UPDATE regprc.registration SET last_success_stage_name = 'PacketUploaderStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='PacketValidatorStage' and process = 'NEW'; +UPDATE regprc.registration SET last_success_stage_name = 'PacketValidatorStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='PacketClassifierStage' and process = 'NEW'; +UPDATE regprc.registration SET last_success_stage_name = 'PacketClassifierStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='QualityCheckerStage' and process = 'NEW'; +UPDATE regprc.registration SET last_success_stage_name = 'QualityCheckerStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='OSIValidatorStage' and process = 'NEW'; +UPDATE regprc.registration SET last_success_stage_name = 'OSIValidatorStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='ExternalStage' and process = 'NEW'; +UPDATE regprc.registration SET last_success_stage_name = 'ExternalStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='DemoDedupeStage' and process = 'NEW'; +UPDATE regprc.registration SET last_success_stage_name = 'DemoDedupeStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='BioDedupeStage' and process = 'NEW'; +UPDATE regprc.registration SET last_success_stage_name = 'BioDedupeStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='ManualVerificationStage' and process = 'NEW'; +UPDATE regprc.registration SET last_success_stage_name = 'BioDedupeStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='UinGeneratorStage' and process = 'NEW'; +UPDATE regprc.registration SET last_success_stage_name = 'UinGeneratorStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='PrintingStage' and process = 'NEW'; + +UPDATE regprc.registration SET last_success_stage_name = 'PacketReceiverStage' where latest_trn_type_code='SECUREZONE_NOTIFICATION' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'UPDATE'; +UPDATE regprc.registration SET last_success_stage_name = 'SecurezoneNotificationStage' where latest_trn_type_code='UPLOAD_PACKET' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'UPDATE'; +UPDATE regprc.registration SET last_success_stage_name = 'PacketUploaderStage' where latest_trn_type_code='VALIDATE_PACKET' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'UPDATE'; +UPDATE regprc.registration SET last_success_stage_name = 'PacketValidatorStage' where latest_trn_type_code='PACKET_CLASSIFICATION' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'UPDATE'; +UPDATE regprc.registration SET last_success_stage_name = 'PacketClassifierStage' where latest_trn_type_code='QUALITY_CHECK' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'UPDATE'; +UPDATE regprc.registration SET last_success_stage_name = 'QualityCheckerStage' where latest_trn_type_code='OSI_VALIDATE' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'UPDATE'; +UPDATE regprc.registration SET last_success_stage_name = 'OSIValidatorStage' where latest_trn_type_code='BIOMETRIC_AUTHENTICATION' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'UPDATE'; +UPDATE regprc.registration SET last_success_stage_name = 'BiometricAuthenticationStage' where latest_trn_type_code='DEMOGRAPHIC_VERIFICATION' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'UPDATE'; +UPDATE regprc.registration SET last_success_stage_name = 'DemoDedupeStage' where latest_trn_type_code='BIOGRAPHIC_VERIFICATION' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'UPDATE'; +UPDATE regprc.registration SET last_success_stage_name = 'BioDedupeStage' where latest_trn_type_code='MANUAL_VERIFICATION' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'UPDATE'; +UPDATE regprc.registration SET last_success_stage_name = 'BioDedupeStage' where latest_trn_type_code='UIN_GENERATOR' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'UPDATE'; +UPDATE regprc.registration SET last_success_stage_name = 'UinGeneratorStage' where latest_trn_type_code='PRINT_SERVICE' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'UPDATE'; + +UPDATE regprc.registration SET last_success_stage_name = 'PacketReceiverStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='SecurezoneNotificationStage' and process = 'UPDATE'; +UPDATE regprc.registration SET last_success_stage_name = 'SecurezoneNotificationStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='PacketUploaderStage' and process = 'UPDATE'; +UPDATE regprc.registration SET last_success_stage_name = 'PacketUploaderStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='PacketValidatorStage' and process = 'UPDATE'; +UPDATE regprc.registration SET last_success_stage_name = 'PacketValidatorStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='PacketClassifierStage' and process = 'UPDATE'; +UPDATE regprc.registration SET last_success_stage_name = 'PacketClassifierStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='QualityCheckerStage' and process = 'UPDATE'; +UPDATE regprc.registration SET last_success_stage_name = 'QualityCheckerStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='OSIValidatorStage' and process = 'UPDATE'; +UPDATE regprc.registration SET last_success_stage_name = 'OSIValidatorStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='BiometricAuthenticationStage' and process = 'UPDATE'; +UPDATE regprc.registration SET last_success_stage_name = 'BiometricAuthenticationStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='DemoDedupeStage' and process = 'UPDATE'; +UPDATE regprc.registration SET last_success_stage_name = 'DemoDedupeStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='BioDedupeStage' and process = 'UPDATE'; +UPDATE regprc.registration SET last_success_stage_name = 'BioDedupeStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='ManualVerificationStage' and process = 'UPDATE'; +UPDATE regprc.registration SET last_success_stage_name = 'BioDedupeStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='UinGeneratorStage' and process = 'UPDATE'; +UPDATE regprc.registration SET last_success_stage_name = 'UinGeneratorStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='PrintingStage' and process = 'UPDATE'; + +UPDATE regprc.registration SET last_success_stage_name = 'PacketReceiverStage' where latest_trn_type_code='SECUREZONE_NOTIFICATION' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'LOST'; +UPDATE regprc.registration SET last_success_stage_name = 'SecurezoneNotificationStage' where latest_trn_type_code='UPLOAD_PACKET' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'LOST'; +UPDATE regprc.registration SET last_success_stage_name = 'PacketUploaderStage' where latest_trn_type_code='VALIDATE_PACKET' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'LOST'; +UPDATE regprc.registration SET last_success_stage_name = 'PacketValidatorStage' where latest_trn_type_code='PACKET_CLASSIFICATION' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'LOST'; +UPDATE regprc.registration SET last_success_stage_name = 'PacketClassifierStage' where latest_trn_type_code='QUALITY_CHECK' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'LOST'; +UPDATE regprc.registration SET last_success_stage_name = 'QualityCheckerStage' where latest_trn_type_code='OSI_VALIDATE' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'LOST'; +UPDATE regprc.registration SET last_success_stage_name = 'OSIValidatorStage' where latest_trn_type_code='BIOGRAPHIC_VERIFICATION' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'LOST'; +UPDATE regprc.registration SET last_success_stage_name = 'BioDedupeStage' where latest_trn_type_code='MANUAL_VERIFICATION' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'LOST'; +UPDATE regprc.registration SET last_success_stage_name = 'BioDedupeStage' where latest_trn_type_code='UIN_GENERATOR' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'LOST'; +UPDATE regprc.registration SET last_success_stage_name = 'UinGeneratorStage' where latest_trn_type_code='PRINT_SERVICE' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'LOST'; + +UPDATE regprc.registration SET last_success_stage_name = 'PacketReceiverStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='SecurezoneNotificationStage' and process = 'LOST'; +UPDATE regprc.registration SET last_success_stage_name = 'SecurezoneNotificationStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='PacketUploaderStage' and process = 'LOST'; +UPDATE regprc.registration SET last_success_stage_name = 'PacketUploaderStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='PacketValidatorStage' and process = 'LOST'; +UPDATE regprc.registration SET last_success_stage_name = 'PacketValidatorStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='PacketClassifierStage' and process = 'LOST'; +UPDATE regprc.registration SET last_success_stage_name = 'PacketClassifierStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='QualityCheckerStage' and process = 'LOST'; +UPDATE regprc.registration SET last_success_stage_name = 'QualityCheckerStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='OSIValidatorStage' and process = 'LOST'; +UPDATE regprc.registration SET last_success_stage_name = 'OSIValidatorStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='BioDedupeStage' and process = 'LOST'; +UPDATE regprc.registration SET last_success_stage_name = 'BioDedupeStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='ManualVerificationStage' and process = 'LOST'; +UPDATE regprc.registration SET last_success_stage_name = 'BioDedupeStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='UinGeneratorStage' and process = 'LOST'; +UPDATE regprc.registration SET last_success_stage_name = 'UinGeneratorStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='PrintingStage' and process = 'LOST'; + +UPDATE regprc.registration SET last_success_stage_name = 'PacketReceiverStage' where latest_trn_type_code='SECUREZONE_NOTIFICATION' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'RES_UPDATE'; +UPDATE regprc.registration SET last_success_stage_name = 'SecurezoneNotificationStage' where latest_trn_type_code='UPLOAD_PACKET' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'RES_UPDATE'; +UPDATE regprc.registration SET last_success_stage_name = 'PacketUploaderStage' where latest_trn_type_code='VALIDATE_PACKET' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'RES_UPDATE'; +UPDATE regprc.registration SET last_success_stage_name = 'PacketValidatorStage' where latest_trn_type_code='DEMOGRAPHIC_VERIFICATION' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'RES_UPDATE'; +UPDATE regprc.registration SET last_success_stage_name = 'DemoDedupeStage' where latest_trn_type_code='MANUAL_VERIFICATION' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'RES_UPDATE'; +UPDATE regprc.registration SET last_success_stage_name = 'DemoDedupeStage' where latest_trn_type_code='UIN_GENERATOR' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'RES_UPDATE'; +UPDATE regprc.registration SET last_success_stage_name = 'UinGeneratorStage' where latest_trn_type_code='PRINT_SERVICE' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'RES_UPDATE'; + +UPDATE regprc.registration SET last_success_stage_name = 'PacketReceiverStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='SecurezoneNotificationStage' and process = 'RES_UPDATE'; +UPDATE regprc.registration SET last_success_stage_name = 'SecurezoneNotificationStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='PacketUploaderStage' and process = 'RES_UPDATE'; +UPDATE regprc.registration SET last_success_stage_name = 'PacketUploaderStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='PacketValidatorStage' and process = 'RES_UPDATE'; +UPDATE regprc.registration SET last_success_stage_name = 'PacketValidatorStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='DemoDedupeStage' and process = 'RES_UPDATE'; +UPDATE regprc.registration SET last_success_stage_name = 'DemoDedupeStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='ManualVerificationStage' and process = 'RES_UPDATE'; +UPDATE regprc.registration SET last_success_stage_name = 'DemoDedupeStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='UinGeneratorStage' and process = 'RES_UPDATE'; +UPDATE regprc.registration SET last_success_stage_name = 'UinGeneratorStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='PrintingStage' and process = 'RES_UPDATE'; + +UPDATE regprc.registration SET last_success_stage_name = 'PacketReceiverStage' where latest_trn_type_code='SECUREZONE_NOTIFICATION' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'RES_REPRINT'; +UPDATE regprc.registration SET last_success_stage_name = 'SecurezoneNotificationStage' where latest_trn_type_code='UPLOAD_PACKET' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'RES_REPRINT'; +UPDATE regprc.registration SET last_success_stage_name = 'PacketUploaderStage' where latest_trn_type_code='PRINT_SERVICE' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'RES_REPRINT'; + +UPDATE regprc.registration SET last_success_stage_name = 'PacketReceiverStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='SecurezoneNotificationStage' and process = 'RES_REPRINT'; +UPDATE regprc.registration SET last_success_stage_name = 'SecurezoneNotificationStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='PacketUploaderStage' and process = 'RES_REPRINT'; +UPDATE regprc.registration SET last_success_stage_name = 'PacketUploaderStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='PrintingStage' and process = 'RES_REPRINT'; + +UPDATE regprc.registration SET last_success_stage_name = 'PacketReceiverStage' where latest_trn_type_code='SECUREZONE_NOTIFICATION' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process= 'ACTIVATED'; +UPDATE regprc.registration SET last_success_stage_name = 'SecurezoneNotificationStage' where latest_trn_type_code='UPLOAD_PACKET' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process= 'ACTIVATED'; +UPDATE regprc.registration SET last_success_stage_name = 'PacketUploaderStage' where latest_trn_type_code='UIN_GENERATOR' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process= 'ACTIVATED'; +UPDATE regprc.registration SET last_success_stage_name = 'UinGeneratorStage' where latest_trn_type_code='PRINT_SERVICE' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process= 'ACTIVATED'; + +UPDATE regprc.registration SET last_success_stage_name = 'PacketReceiverStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='SecurezoneNotificationStage' and process= 'ACTIVATED'; +UPDATE regprc.registration SET last_success_stage_name = 'SecurezoneNotificationStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='PacketUploaderStage' and process= 'ACTIVATED'; +UPDATE regprc.registration SET last_success_stage_name = 'PacketUploaderStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='UinGeneratorStage' and process= 'ACTIVATED'; +UPDATE regprc.registration SET last_success_stage_name = 'UinGeneratorStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='PrintingStage' and process= 'ACTIVATED'; + +UPDATE regprc.registration SET last_success_stage_name = 'PacketReceiverStage' where latest_trn_type_code='SECUREZONE_NOTIFICATION' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process ='DEACTIVATED'; +UPDATE regprc.registration SET last_success_stage_name = 'SecurezoneNotificationStage' where latest_trn_type_code='UPLOAD_PACKET' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process ='DEACTIVATED'; +UPDATE regprc.registration SET last_success_stage_name = 'PacketUploaderStage' where latest_trn_type_code='UIN_GENERATOR' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process ='DEACTIVATED'; +UPDATE regprc.registration SET last_success_stage_name = 'UinGeneratorStage' where latest_trn_type_code='PRINT_SERVICE' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process ='DEACTIVATED'; + +UPDATE regprc.registration SET last_success_stage_name = 'PacketReceiverStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='SecurezoneNotificationStage' and process ='DEACTIVATED'; +UPDATE regprc.registration SET last_success_stage_name = 'SecurezoneNotificationStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='PacketUploaderStage' and process ='DEACTIVATED'; +UPDATE regprc.registration SET last_success_stage_name = 'PacketUploaderStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='UinGeneratorStage' and process = 'DEACTIVATED'; +UPDATE regprc.registration SET last_success_stage_name = 'UinGeneratorStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='PrintingStage' and process = 'DEACTIVATED'; + +------------------------------------------------------------------------------------------------------------------------------------- diff --git a/db_release_scripts/mosip_regprc/upgrade.sh b/db_release_scripts/mosip_regprc/upgrade.sh new file mode 100644 index 00000000000..308efcaf0d3 --- /dev/null +++ b/db_release_scripts/mosip_regprc/upgrade.sh @@ -0,0 +1,50 @@ +## Properties file +set -e +properties_file="$1" +release_version="$2" + echo "Properties File Name - $properties_file" + echo "DB Upgrade Version - $release_version" + +if [ -f "$properties_file" ] +then + echo "Property file \"$properties_file\" found." + while IFS='=' read -r key value + do + key=$(echo $key | tr '.' '_') + eval ${key}=\${value} + done < "$properties_file" +else + echo "Property file not found, Pass property file name as argument." + exit 0 +fi + +if [ $# -ge 2 ] +then + echo "DB upgrade version \"$release_version\" found." +else + echo "DB upgrade version not found, Pass upgrade version as argument." + exit 0 +fi + +## Terminate existing connections +echo "Terminating active connections" +CONN=$(PGPASSWORD=$SU_USER_PWD psql --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" + +## Executing DB Upgrade scripts +echo "Alter scripts deployment on $MOSIP_DB_NAME database is started....Upgrade Version...$release_version" +ALTER_SCRIPT_FILE="sql/${release_version}_${ALTER_SCRIPT_FILENAME}" +echo "Upgrade script considered for release deployment - $ALTER_SCRIPT_FILE" + +## Checking If Alter scripts are present +echo "Checking if script $ALTER_SCRIPT_FILE is present" +if [ -f "$ALTER_SCRIPT_FILE" ] +then + echo "SQL file "$ALTER_SCRIPT_FILE" found." +else + echo "SQL file not found, Since no SQL file present for \"$release_version\" hence exiting." + exit 0 +fi +echo Applying upgrade changes + +PGPASSWORD=$SU_USER_PWD psql --username=$SU_USER --host=$DB_SERVERIP --port=$DB_PORT --dbname=$DEFAULT_DB_NAME -a -b -f $ALTER_SCRIPT_FILE From a99b1eb1863aa6cfeb2125af3741d086b9bbf5d7 Mon Sep 17 00:00:00 2001 From: ckm007 Date: Sat, 15 Oct 2022 16:49:37 +0530 Subject: [PATCH 053/133] [MOSIP-23833] updated deploy and revoke scripts --- .../mosip_regprc/deploy.properties | 15 +- db_release_scripts/mosip_regprc/deploy.sh | 92 ----- db_release_scripts/mosip_regprc/revoke.sh | 96 ++---- .../mosip_regprc/sql/1.1.4_release.sql | 21 -- .../mosip_regprc/sql/1.1.5_release.sql | 23 -- .../mosip_regprc/sql/1.2.0_release.sql | 321 ------------------ .../mosip_regprc/sql/1.2.0_revoke.sql | 12 - 7 files changed, 31 insertions(+), 549 deletions(-) delete mode 100644 db_release_scripts/mosip_regprc/deploy.sh delete mode 100644 db_release_scripts/mosip_regprc/sql/1.1.4_release.sql delete mode 100644 db_release_scripts/mosip_regprc/sql/1.1.5_release.sql delete mode 100644 db_release_scripts/mosip_regprc/sql/1.2.0_release.sql diff --git a/db_release_scripts/mosip_regprc/deploy.properties b/db_release_scripts/mosip_regprc/deploy.properties index ef632c3b0de..ba91a70895b 100644 --- a/db_release_scripts/mosip_regprc/deploy.properties +++ b/db_release_scripts/mosip_regprc/deploy.properties @@ -1,14 +1,7 @@ -DB_SERVERIP= -DB_PORT=9001 +DB_SERVERIP=localhost +DB_PORT=5432 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 +ALTER_SCRIPT_FILENAME=upgrade.sql +REVOKE_SCRIPT_FILENAME=revoke.sql diff --git a/db_release_scripts/mosip_regprc/deploy.sh b/db_release_scripts/mosip_regprc/deploy.sh deleted file mode 100644 index 208e74e589a..00000000000 --- a/db_release_scripts/mosip_regprc/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/revoke.sh b/db_release_scripts/mosip_regprc/revoke.sh index 406088db04e..608f9423583 100644 --- a/db_release_scripts/mosip_regprc/revoke.sh +++ b/db_release_scripts/mosip_regprc/revoke.sh @@ -1,92 +1,50 @@ -### -- --------------------------------------------------------------------------------------------------------- -### -- 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 ############# +##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" +echo "Properties File Name - $properties_file" +echo "DB Revoke Version - $revoke_version" + if [ -f "$properties_file" ] then - echo `date "+%m/%d/%Y %H:%M:%S"` ": Property file \"$properties_file\" found." + echo "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." + echo "Property file not found, Pass property file name as argument." + exit 0 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 ] +if [ $# -ge 2 ] then -echo `date "+%m/%d/%Y %H:%M:%S"` ": Postgres database server and service is up and running" | tee -a $LOG 2>&1 + echo "DB revoke version \"$revoke_version\" found." else -echo `date "+%m/%d/%Y %H:%M:%S"` ": Postgres database server or service is not running" | tee -a $LOG 2>&1 + echo "DB revoke version not found, Pass revoke version as argument." + exit 0 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 +## Terminate existing connections +echo "Terminating active connections" +CONN=$(PGPASSWORD=$SU_USER_PWD psql --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" -cd /$BASEPATH/$MOSIP_DB_NAME/ +## Executing DB Revoke scripts +echo "Alter scripts deployment on $MOSIP_DB_NAME database is started. Revoke Version is $revoke_version" +ALTER_SCRIPT_FILE="sql/${revoke_version}_${REVOKE_SCRIPT_FILENAME}" +echo "Revoke script considered for DB changes - $ALTER_SCRIPT_FILE" -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 ] +## Checking If Alter scripts are present +echo "Checking if script $ALTER_SCRIPT_FILE is present" +if [ -f "$ALTER_SCRIPT_FILE" ] 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 + echo "SQL file "$ALTER_SCRIPT_FILE" found." 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 + echo "SQL file not found, Since no SQL file present for \"$revoke_version\" hence exiting." + exit 0 fi +echo Applying revoke changes -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 - - +PGPASSWORD=$SU_USER_PWD psql --username=$SU_USER --host=$DB_SERVERIP --port=$DB_PORT --dbname=$DEFAULT_DB_NAME -a -b -f $ALTER_SCRIPT_FILE diff --git a/db_release_scripts/mosip_regprc/sql/1.1.4_release.sql b/db_release_scripts/mosip_regprc/sql/1.1.4_release.sql deleted file mode 100644 index 6279fefa2aa..00000000000 --- a/db_release_scripts/mosip_regprc/sql/1.1.4_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.5_release.sql b/db_release_scripts/mosip_regprc/sql/1.1.5_release.sql deleted file mode 100644 index 89fa3f3283e..00000000000 --- a/db_release_scripts/mosip_regprc/sql/1.1.5_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.2.0_release.sql b/db_release_scripts/mosip_regprc/sql/1.2.0_release.sql deleted file mode 100644 index 5b4bc6dbb84..00000000000 --- a/db_release_scripts/mosip_regprc/sql/1.2.0_release.sql +++ /dev/null @@ -1,321 +0,0 @@ --- ------------------------------------------------------------------------------------------------- --- 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 - -----------------------------------------------Multiple table level changes on regprc db------------------------------------------------------- - -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; - -\ir ../ddl/regprc-additional_info_request.sql - -\ir ../ddl/regprc-anonymous_profile.sql - -\ir ../ddl/regprc-reg_verification.sql - -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; -ALTER TABLE regprc.registration ADD COLUMN workflow_instance_id character varying(36); -ALTER TABLE regprc.registration ADD COLUMN source character varying; -ALTER TABLE regprc.registration ADD COLUMN iteration integer DEFAULT 1; - -ALTER TABLE regprc.individual_demographic_dedup ADD COLUMN workflow_instance_id character varying(36); -ALTER TABLE regprc.individual_demographic_dedup ADD COLUMN process character varying(36); -ALTER TABLE regprc.individual_demographic_dedup ADD COLUMN iteration integer DEFAULT 1; - - -ALTER TABLE regprc.reg_manual_verification ADD COLUMN workflow_instance_id character varying(36); - -ALTER TABLE regprc.reg_lost_uin_det ADD COLUMN workflow_instance_id character varying(36); - -ALTER TABLE regprc.reg_bio_ref ADD COLUMN workflow_instance_id character varying(36); -ALTER TABLE regprc.reg_bio_ref ADD COLUMN process character varying(36); -ALTER TABLE regprc.reg_bio_ref ADD COLUMN iteration integer DEFAULT 1; - -UPDATE regprc.registration_list SET packet_id = reg_id; -UPDATE regprc.registration a SET workflow_instance_id = b.workflow_instance_id FROM regprc.registration_list b WHERE a.reg_id = b.reg_id; -UPDATE regprc.individual_demographic_dedup a SET workflow_instance_id = b.workflow_instance_id FROM regprc.registration_list b WHERE a.reg_id = b.reg_id; -UPDATE regprc.reg_manual_verification a SET workflow_instance_id = b.workflow_instance_id FROM regprc.registration_list b WHERE a.reg_id = b.reg_id; -UPDATE regprc.reg_lost_uin_det a SET workflow_instance_id = b.workflow_instance_id FROM regprc.registration_list b WHERE a.reg_id = b.reg_id; -UPDATE regprc.reg_bio_ref a SET workflow_instance_id = b.workflow_instance_id FROM regprc.registration_list b WHERE a.reg_id = b.reg_id; - -CREATE INDEX IF NOT EXISTS idx_rbioref_crdtimes on regprc.reg_bio_ref (cr_dtimes); -CREATE INDEX IF NOT EXISTS idx_bio_ref_id ON regprc.reg_bio_ref USING btree (bio_ref_id); -DROP INDEX IF EXISTS idx_idemogd_namedobgender; -CREATE INDEX IF NOT EXISTS idx_idemogd_namedobgender on regprc.individual_demographic_dedup (name, dob,gender); -CREATE INDEX IF NOT EXISTS idx_rbioref_crdtimes on regprc.reg_bio_ref (cr_dtimes); -CREATE INDEX IF NOT EXISTS idx_rmanvrn_reqid on regprc.reg_manual_verification (request_id); -DROP INDEX IF EXISTS idx_rgstrn_ltstrbcode_ltststscode; -CREATE INDEX IF NOT EXISTS idx_rgstrn_ltstrbcode_ltststscode on regprc.registration (latest_trn_dtimes, latest_trn_status_code); -CREATE INDEX IF NOT EXISTS idx_reg_latest_trn_dtimes ON regprc.registration USING btree (latest_trn_dtimes); -CREATE INDEX IF NOT EXISTS idx_rgstrnlst_pcktid on regprc.registration_list (packet_id); -CREATE INDEX IF NOT EXISTS idx_rgstrnlst_aireqid on regprc.registration_list (additional_info_req_id); -CREATE INDEX IF NOT EXISTS idx_reg_verification_reqId on regprc.reg_verification (verification_req_id); -CREATE INDEX IF NOT EXISTS idx_reg_trn_reg_id ON regprc.registration_transaction USING btree (reg_id); -CREATE INDEX IF NOT EXISTS idx_reg_trn_status_code ON regprc.registration_transaction USING btree (status_code); -CREATE INDEX IF NOT EXISTS idx_reg_trn_trntypecode ON regprc.registration_transaction USING btree (trn_type_code); -CREATE INDEX IF NOT EXISTS idx_reg_trn_upd_dtimes ON regprc.registration_transaction USING btree (upd_dtimes); -CREATE INDEX IF NOT EXISTS idx_user_detail_cntr_id ON regprc.abis_request USING btree (bio_ref_id); -CREATE INDEX IF NOT EXISTS idx_abis_req_regtrn_id ON regprc.abis_request USING btree (ref_regtrn_id); - -ALTER TABLE regprc.individual_demographic_dedup DROP CONSTRAINT pk_idemogd_id; -ALTER TABLE regprc.individual_demographic_dedup ALTER COLUMN workflow_instance_id SET NOT NULL; -ALTER TABLE regprc.individual_demographic_dedup ADD CONSTRAINT pk_idemogd_id PRIMARY KEY (workflow_instance_id,lang_code); - -ALTER TABLE regprc.reg_bio_ref DROP CONSTRAINT pk_regbref_id; -ALTER TABLE regprc.reg_bio_ref ALTER COLUMN workflow_instance_id SET NOT NULL; -ALTER TABLE regprc.reg_bio_ref ADD CONSTRAINT pk_regbref_id PRIMARY KEY (bio_ref_id,workflow_instance_id); - -ALTER TABLE regprc.reg_lost_uin_det DROP CONSTRAINT pk_rlostd; -ALTER TABLE regprc.reg_lost_uin_det ALTER COLUMN workflow_instance_id SET NOT NULL; -ALTER TABLE regprc.reg_lost_uin_det ADD CONSTRAINT pk_rlostd PRIMARY KEY (workflow_instance_id); - -ALTER TABLE regprc.reg_manual_verification DROP CONSTRAINT pk_rmnlver_id; -ALTER TABLE regprc.reg_manual_verification ALTER COLUMN workflow_instance_id SET NOT NULL; -ALTER TABLE regprc.reg_manual_verification ADD CONSTRAINT pk_rmnlver_id PRIMARY KEY (workflow_instance_id,matched_ref_id,matched_ref_type); - -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; - -ALTER TABLE regprc.reg_manual_verification ADD CONSTRAINT fk_rmnlver_reg FOREIGN KEY (workflow_instance_id) -REFERENCES regprc.registration (workflow_instance_id) MATCH SIMPLE -ON DELETE NO ACTION ON UPDATE NO ACTION; - -ALTER TABLE regprc.reg_bio_ref ADD CONSTRAINT fk_regbrf_reg FOREIGN KEY (workflow_instance_id) -REFERENCES regprc.registration (workflow_instance_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 (workflow_instance_id) -REFERENCES regprc.registration (workflow_instance_id) MATCH SIMPLE -ON DELETE NO ACTION ON UPDATE NO ACTION; - ------------------------------------------------------------------------------------------------------------------------------------------ -ALTER TABLE regprc.registration ADD COLUMN resume_timestamp timestamp; -ALTER TABLE regprc.registration ADD COLUMN default_resume_action character varying(50); - - ---------------------------------------------------------------------------------------------------- - -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; - ------------------------------------------------------------------------------------------------------- - - -ALTER TABLE regprc.registration ADD COLUMN last_success_stage_name CHARACTER VARYING(50); --------------------------------------------------------Add columns to registration_list---------------------------------------------- - -ALTER TABLE regprc.registration_list ADD COLUMN name character varying; -ALTER TABLE regprc.registration_list ADD COLUMN phone character varying; -ALTER TABLE regprc.registration_list ADD COLUMN email character varying; -ALTER TABLE regprc.registration_list ADD COLUMN center_id character varying; -ALTER TABLE regprc.registration_list ADD COLUMN registration_date date; -ALTER TABLE regprc.registration_list ADD COLUMN location_code character varying; - -------------------------------------------------------------------------------------------------------------------------------------------- --------------------------------------------------Creation of crypto salt table-------------------------------------------------------------- - -\ir ../ddl/regprc-crypto_salt.sql - --------------------------------------------------------------------------------------------------------------------------------------------- - ----------------------------------------------------------FOR HISTORY DATA---------------------------------------------- - - -UPDATE regprc.registration SET last_success_stage_name = 'PacketReceiverStage' where latest_trn_type_code='PACKET_RECEIVER' and latest_trn_status_code in ('SUCCESS' , 'PROCESSED'); -UPDATE regprc.registration SET last_success_stage_name = 'SecurezoneNotificationStage' where latest_trn_type_code='SECUREZONE_NOTIFICATION' and latest_trn_status_code in ('SUCCESS' , 'PROCESSED'); -UPDATE regprc.registration SET last_success_stage_name = 'PacketUploaderStage' where latest_trn_type_code='UPLOAD_PACKET' and latest_trn_status_code in ('SUCCESS' , 'PROCESSED'); -UPDATE regprc.registration SET last_success_stage_name = 'PacketValidatorStage' where latest_trn_type_code='VALIDATE_PACKET' and latest_trn_status_code in ('SUCCESS' , 'PROCESSED'); -UPDATE regprc.registration SET last_success_stage_name = 'PacketClassifierStage' where latest_trn_type_code='PACKET_CLASSIFICATION' and latest_trn_status_code in ('SUCCESS' , 'PROCESSED'); -UPDATE regprc.registration SET last_success_stage_name = 'QualityCheckerStage' where latest_trn_type_code='QUALITY_CHECK' and latest_trn_status_code in ('SUCCESS' , 'PROCESSED'); -UPDATE regprc.registration SET last_success_stage_name = 'OSIValidatorStage' where latest_trn_type_code='OSI_VALIDATE' and latest_trn_status_code in ('SUCCESS' , 'PROCESSED'); -UPDATE regprc.registration SET last_success_stage_name = 'ExternalStage' where latest_trn_type_code='EXTERNAL_INTEGRATION' and latest_trn_status_code in ('SUCCESS' , 'PROCESSED'); -UPDATE regprc.registration SET last_success_stage_name = 'DemoDedupeStage' where latest_trn_type_code='DEMOGRAPHIC_VERIFICATION' and latest_trn_status_code in ('SUCCESS' , 'PROCESSED'); -UPDATE regprc.registration SET last_success_stage_name = 'BioDedupeStage' where latest_trn_type_code='BIOGRAPHIC_VERIFICATION' and latest_trn_status_code in ('SUCCESS' , 'PROCESSED'); -UPDATE regprc.registration SET last_success_stage_name = 'ManualVerificationStage' where latest_trn_type_code='MANUAL_VERIFICATION' and latest_trn_status_code in ('SUCCESS' , 'PROCESSED'); -UPDATE regprc.registration SET last_success_stage_name = 'UinGeneratorStage' where latest_trn_type_code='UIN_GENERATOR' and latest_trn_status_code in ('SUCCESS' , 'PROCESSED'); -UPDATE regprc.registration SET last_success_stage_name = 'PrintingStage' where latest_trn_type_code='PRINT_SERVICE' and latest_trn_status_code in ('SUCCESS' , 'PROCESSED'); -UPDATE regprc.registration SET last_success_stage_name = 'BiometricAuthenticationStage' where latest_trn_type_code='BIOMETRIC_AUTHENTICATION' and latest_trn_status_code in ('SUCCESS' , 'PROCESSED'); - -UPDATE regprc.registration SET last_success_stage_name = 'PacketReceiverStage' where latest_trn_type_code='SECUREZONE_NOTIFICATION' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'NEW'; -UPDATE regprc.registration SET last_success_stage_name = 'SecurezoneNotificationStage' where latest_trn_type_code='UPLOAD_PACKET' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'NEW'; -UPDATE regprc.registration SET last_success_stage_name = 'PacketUploaderStage' where latest_trn_type_code='VALIDATE_PACKET' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'NEW'; -UPDATE regprc.registration SET last_success_stage_name = 'PacketValidatorStage' where latest_trn_type_code='PACKET_CLASSIFICATION' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'NEW'; -UPDATE regprc.registration SET last_success_stage_name = 'PacketClassifierStage' where latest_trn_type_code='QUALITY_CHECK' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'NEW'; -UPDATE regprc.registration SET last_success_stage_name = 'QualityCheckerStage' where latest_trn_type_code='OSI_VALIDATE' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'NEW'; -UPDATE regprc.registration SET last_success_stage_name = 'OSIValidatorStage' where latest_trn_type_code='EXTERNAL_INTEGRATION' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'NEW'; -UPDATE regprc.registration SET last_success_stage_name = 'ExternalStage' where latest_trn_type_code='DEMOGRAPHIC_VERIFICATION' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'NEW'; -UPDATE regprc.registration SET last_success_stage_name = 'DemoDedupeStage' where latest_trn_type_code='BIOGRAPHIC_VERIFICATION' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'NEW'; -UPDATE regprc.registration SET last_success_stage_name = 'BioDedupeStage' where latest_trn_type_code='MANUAL_VERIFICATION' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'NEW'; -UPDATE regprc.registration SET last_success_stage_name = 'BioDedupeStage' where latest_trn_type_code='UIN_GENERATOR' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'NEW'; -UPDATE regprc.registration SET last_success_stage_name = 'UinGeneratorStage' where latest_trn_type_code='PRINT_SERVICE' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'NEW'; - -UPDATE regprc.registration SET last_success_stage_name = 'PacketReceiverStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='SecurezoneNotificationStage' and process = 'NEW'; -UPDATE regprc.registration SET last_success_stage_name = 'SecurezoneNotificationStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='PacketUploaderStage' and process = 'NEW'; -UPDATE regprc.registration SET last_success_stage_name = 'PacketUploaderStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='PacketValidatorStage' and process = 'NEW'; -UPDATE regprc.registration SET last_success_stage_name = 'PacketValidatorStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='PacketClassifierStage' and process = 'NEW'; -UPDATE regprc.registration SET last_success_stage_name = 'PacketClassifierStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='QualityCheckerStage' and process = 'NEW'; -UPDATE regprc.registration SET last_success_stage_name = 'QualityCheckerStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='OSIValidatorStage' and process = 'NEW'; -UPDATE regprc.registration SET last_success_stage_name = 'OSIValidatorStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='ExternalStage' and process = 'NEW'; -UPDATE regprc.registration SET last_success_stage_name = 'ExternalStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='DemoDedupeStage' and process = 'NEW'; -UPDATE regprc.registration SET last_success_stage_name = 'DemoDedupeStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='BioDedupeStage' and process = 'NEW'; -UPDATE regprc.registration SET last_success_stage_name = 'BioDedupeStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='ManualVerificationStage' and process = 'NEW'; -UPDATE regprc.registration SET last_success_stage_name = 'BioDedupeStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='UinGeneratorStage' and process = 'NEW'; -UPDATE regprc.registration SET last_success_stage_name = 'UinGeneratorStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='PrintingStage' and process = 'NEW'; - -UPDATE regprc.registration SET last_success_stage_name = 'PacketReceiverStage' where latest_trn_type_code='SECUREZONE_NOTIFICATION' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'UPDATE'; -UPDATE regprc.registration SET last_success_stage_name = 'SecurezoneNotificationStage' where latest_trn_type_code='UPLOAD_PACKET' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'UPDATE'; -UPDATE regprc.registration SET last_success_stage_name = 'PacketUploaderStage' where latest_trn_type_code='VALIDATE_PACKET' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'UPDATE'; -UPDATE regprc.registration SET last_success_stage_name = 'PacketValidatorStage' where latest_trn_type_code='PACKET_CLASSIFICATION' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'UPDATE'; -UPDATE regprc.registration SET last_success_stage_name = 'PacketClassifierStage' where latest_trn_type_code='QUALITY_CHECK' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'UPDATE'; -UPDATE regprc.registration SET last_success_stage_name = 'QualityCheckerStage' where latest_trn_type_code='OSI_VALIDATE' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'UPDATE'; -UPDATE regprc.registration SET last_success_stage_name = 'OSIValidatorStage' where latest_trn_type_code='BIOMETRIC_AUTHENTICATION' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'UPDATE'; -UPDATE regprc.registration SET last_success_stage_name = 'BiometricAuthenticationStage' where latest_trn_type_code='DEMOGRAPHIC_VERIFICATION' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'UPDATE'; -UPDATE regprc.registration SET last_success_stage_name = 'DemoDedupeStage' where latest_trn_type_code='BIOGRAPHIC_VERIFICATION' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'UPDATE'; -UPDATE regprc.registration SET last_success_stage_name = 'BioDedupeStage' where latest_trn_type_code='MANUAL_VERIFICATION' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'UPDATE'; -UPDATE regprc.registration SET last_success_stage_name = 'BioDedupeStage' where latest_trn_type_code='UIN_GENERATOR' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'UPDATE'; -UPDATE regprc.registration SET last_success_stage_name = 'UinGeneratorStage' where latest_trn_type_code='PRINT_SERVICE' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'UPDATE'; - -UPDATE regprc.registration SET last_success_stage_name = 'PacketReceiverStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='SecurezoneNotificationStage' and process = 'UPDATE'; -UPDATE regprc.registration SET last_success_stage_name = 'SecurezoneNotificationStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='PacketUploaderStage' and process = 'UPDATE'; -UPDATE regprc.registration SET last_success_stage_name = 'PacketUploaderStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='PacketValidatorStage' and process = 'UPDATE'; -UPDATE regprc.registration SET last_success_stage_name = 'PacketValidatorStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='PacketClassifierStage' and process = 'UPDATE'; -UPDATE regprc.registration SET last_success_stage_name = 'PacketClassifierStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='QualityCheckerStage' and process = 'UPDATE'; -UPDATE regprc.registration SET last_success_stage_name = 'QualityCheckerStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='OSIValidatorStage' and process = 'UPDATE'; -UPDATE regprc.registration SET last_success_stage_name = 'OSIValidatorStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='BiometricAuthenticationStage' and process = 'UPDATE'; -UPDATE regprc.registration SET last_success_stage_name = 'BiometricAuthenticationStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='DemoDedupeStage' and process = 'UPDATE'; -UPDATE regprc.registration SET last_success_stage_name = 'DemoDedupeStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='BioDedupeStage' and process = 'UPDATE'; -UPDATE regprc.registration SET last_success_stage_name = 'BioDedupeStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='ManualVerificationStage' and process = 'UPDATE'; -UPDATE regprc.registration SET last_success_stage_name = 'BioDedupeStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='UinGeneratorStage' and process = 'UPDATE'; -UPDATE regprc.registration SET last_success_stage_name = 'UinGeneratorStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='PrintingStage' and process = 'UPDATE'; - -UPDATE regprc.registration SET last_success_stage_name = 'PacketReceiverStage' where latest_trn_type_code='SECUREZONE_NOTIFICATION' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'LOST'; -UPDATE regprc.registration SET last_success_stage_name = 'SecurezoneNotificationStage' where latest_trn_type_code='UPLOAD_PACKET' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'LOST'; -UPDATE regprc.registration SET last_success_stage_name = 'PacketUploaderStage' where latest_trn_type_code='VALIDATE_PACKET' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'LOST'; -UPDATE regprc.registration SET last_success_stage_name = 'PacketValidatorStage' where latest_trn_type_code='PACKET_CLASSIFICATION' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'LOST'; -UPDATE regprc.registration SET last_success_stage_name = 'PacketClassifierStage' where latest_trn_type_code='QUALITY_CHECK' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'LOST'; -UPDATE regprc.registration SET last_success_stage_name = 'QualityCheckerStage' where latest_trn_type_code='OSI_VALIDATE' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'LOST'; -UPDATE regprc.registration SET last_success_stage_name = 'OSIValidatorStage' where latest_trn_type_code='BIOGRAPHIC_VERIFICATION' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'LOST'; -UPDATE regprc.registration SET last_success_stage_name = 'BioDedupeStage' where latest_trn_type_code='MANUAL_VERIFICATION' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'LOST'; -UPDATE regprc.registration SET last_success_stage_name = 'BioDedupeStage' where latest_trn_type_code='UIN_GENERATOR' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'LOST'; -UPDATE regprc.registration SET last_success_stage_name = 'UinGeneratorStage' where latest_trn_type_code='PRINT_SERVICE' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'LOST'; - -UPDATE regprc.registration SET last_success_stage_name = 'PacketReceiverStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='SecurezoneNotificationStage' and process = 'LOST'; -UPDATE regprc.registration SET last_success_stage_name = 'SecurezoneNotificationStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='PacketUploaderStage' and process = 'LOST'; -UPDATE regprc.registration SET last_success_stage_name = 'PacketUploaderStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='PacketValidatorStage' and process = 'LOST'; -UPDATE regprc.registration SET last_success_stage_name = 'PacketValidatorStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='PacketClassifierStage' and process = 'LOST'; -UPDATE regprc.registration SET last_success_stage_name = 'PacketClassifierStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='QualityCheckerStage' and process = 'LOST'; -UPDATE regprc.registration SET last_success_stage_name = 'QualityCheckerStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='OSIValidatorStage' and process = 'LOST'; -UPDATE regprc.registration SET last_success_stage_name = 'OSIValidatorStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='BioDedupeStage' and process = 'LOST'; -UPDATE regprc.registration SET last_success_stage_name = 'BioDedupeStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='ManualVerificationStage' and process = 'LOST'; -UPDATE regprc.registration SET last_success_stage_name = 'BioDedupeStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='UinGeneratorStage' and process = 'LOST'; -UPDATE regprc.registration SET last_success_stage_name = 'UinGeneratorStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='PrintingStage' and process = 'LOST'; - -UPDATE regprc.registration SET last_success_stage_name = 'PacketReceiverStage' where latest_trn_type_code='SECUREZONE_NOTIFICATION' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'RES_UPDATE'; -UPDATE regprc.registration SET last_success_stage_name = 'SecurezoneNotificationStage' where latest_trn_type_code='UPLOAD_PACKET' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'RES_UPDATE'; -UPDATE regprc.registration SET last_success_stage_name = 'PacketUploaderStage' where latest_trn_type_code='VALIDATE_PACKET' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'RES_UPDATE'; -UPDATE regprc.registration SET last_success_stage_name = 'PacketValidatorStage' where latest_trn_type_code='DEMOGRAPHIC_VERIFICATION' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'RES_UPDATE'; -UPDATE regprc.registration SET last_success_stage_name = 'DemoDedupeStage' where latest_trn_type_code='MANUAL_VERIFICATION' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'RES_UPDATE'; -UPDATE regprc.registration SET last_success_stage_name = 'DemoDedupeStage' where latest_trn_type_code='UIN_GENERATOR' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'RES_UPDATE'; -UPDATE regprc.registration SET last_success_stage_name = 'UinGeneratorStage' where latest_trn_type_code='PRINT_SERVICE' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'RES_UPDATE'; - -UPDATE regprc.registration SET last_success_stage_name = 'PacketReceiverStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='SecurezoneNotificationStage' and process = 'RES_UPDATE'; -UPDATE regprc.registration SET last_success_stage_name = 'SecurezoneNotificationStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='PacketUploaderStage' and process = 'RES_UPDATE'; -UPDATE regprc.registration SET last_success_stage_name = 'PacketUploaderStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='PacketValidatorStage' and process = 'RES_UPDATE'; -UPDATE regprc.registration SET last_success_stage_name = 'PacketValidatorStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='DemoDedupeStage' and process = 'RES_UPDATE'; -UPDATE regprc.registration SET last_success_stage_name = 'DemoDedupeStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='ManualVerificationStage' and process = 'RES_UPDATE'; -UPDATE regprc.registration SET last_success_stage_name = 'DemoDedupeStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='UinGeneratorStage' and process = 'RES_UPDATE'; -UPDATE regprc.registration SET last_success_stage_name = 'UinGeneratorStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='PrintingStage' and process = 'RES_UPDATE'; - -UPDATE regprc.registration SET last_success_stage_name = 'PacketReceiverStage' where latest_trn_type_code='SECUREZONE_NOTIFICATION' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'RES_REPRINT'; -UPDATE regprc.registration SET last_success_stage_name = 'SecurezoneNotificationStage' where latest_trn_type_code='UPLOAD_PACKET' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'RES_REPRINT'; -UPDATE regprc.registration SET last_success_stage_name = 'PacketUploaderStage' where latest_trn_type_code='PRINT_SERVICE' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process = 'RES_REPRINT'; - -UPDATE regprc.registration SET last_success_stage_name = 'PacketReceiverStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='SecurezoneNotificationStage' and process = 'RES_REPRINT'; -UPDATE regprc.registration SET last_success_stage_name = 'SecurezoneNotificationStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='PacketUploaderStage' and process = 'RES_REPRINT'; -UPDATE regprc.registration SET last_success_stage_name = 'PacketUploaderStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='PrintingStage' and process = 'RES_REPRINT'; - -UPDATE regprc.registration SET last_success_stage_name = 'PacketReceiverStage' where latest_trn_type_code='SECUREZONE_NOTIFICATION' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process= 'ACTIVATED'; -UPDATE regprc.registration SET last_success_stage_name = 'SecurezoneNotificationStage' where latest_trn_type_code='UPLOAD_PACKET' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process= 'ACTIVATED'; -UPDATE regprc.registration SET last_success_stage_name = 'PacketUploaderStage' where latest_trn_type_code='UIN_GENERATOR' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process= 'ACTIVATED'; -UPDATE regprc.registration SET last_success_stage_name = 'UinGeneratorStage' where latest_trn_type_code='PRINT_SERVICE' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process= 'ACTIVATED'; - -UPDATE regprc.registration SET last_success_stage_name = 'PacketReceiverStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='SecurezoneNotificationStage' and process= 'ACTIVATED'; -UPDATE regprc.registration SET last_success_stage_name = 'SecurezoneNotificationStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='PacketUploaderStage' and process= 'ACTIVATED'; -UPDATE regprc.registration SET last_success_stage_name = 'PacketUploaderStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='UinGeneratorStage' and process= 'ACTIVATED'; -UPDATE regprc.registration SET last_success_stage_name = 'UinGeneratorStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='PrintingStage' and process= 'ACTIVATED'; - -UPDATE regprc.registration SET last_success_stage_name = 'PacketReceiverStage' where latest_trn_type_code='SECUREZONE_NOTIFICATION' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process ='DEACTIVATED'; -UPDATE regprc.registration SET last_success_stage_name = 'SecurezoneNotificationStage' where latest_trn_type_code='UPLOAD_PACKET' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process ='DEACTIVATED'; -UPDATE regprc.registration SET last_success_stage_name = 'PacketUploaderStage' where latest_trn_type_code='UIN_GENERATOR' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process ='DEACTIVATED'; -UPDATE regprc.registration SET last_success_stage_name = 'UinGeneratorStage' where latest_trn_type_code='PRINT_SERVICE' and latest_trn_status_code not in ('SUCCESS' , 'PROCESSED') and process ='DEACTIVATED'; - -UPDATE regprc.registration SET last_success_stage_name = 'PacketReceiverStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='SecurezoneNotificationStage' and process ='DEACTIVATED'; -UPDATE regprc.registration SET last_success_stage_name = 'SecurezoneNotificationStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='PacketUploaderStage' and process ='DEACTIVATED'; -UPDATE regprc.registration SET last_success_stage_name = 'PacketUploaderStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='UinGeneratorStage' and process = 'DEACTIVATED'; -UPDATE regprc.registration SET last_success_stage_name = 'UinGeneratorStage' where latest_trn_type_code='PACKET_REPROCESS' and reg_stage_name ='PrintingStage' and process = 'DEACTIVATED'; - -------------------------------------------------------------------------------------------------------------------------------------- diff --git a/db_release_scripts/mosip_regprc/sql/1.2.0_revoke.sql b/db_release_scripts/mosip_regprc/sql/1.2.0_revoke.sql index dc1f093e3bd..319309c57db 100644 --- a/db_release_scripts/mosip_regprc/sql/1.2.0_revoke.sql +++ b/db_release_scripts/mosip_regprc/sql/1.2.0_revoke.sql @@ -1,15 +1,3 @@ --- ------------------------------------------------------------------------------------------------- --- 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; From 5019ea41c99bcc4c2c85e0176ae4b93494e3eb91 Mon Sep 17 00:00:00 2001 From: ckm007 Date: Sat, 15 Oct 2022 17:04:23 +0530 Subject: [PATCH 054/133] [MOSIP-23833] added psql error handling --- db_release_scripts/mosip_regprc/revoke.sh | 4 ++-- db_release_scripts/mosip_regprc/upgrade.sh | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/db_release_scripts/mosip_regprc/revoke.sh b/db_release_scripts/mosip_regprc/revoke.sh index 608f9423583..cd6c36e7aaf 100644 --- a/db_release_scripts/mosip_regprc/revoke.sh +++ b/db_release_scripts/mosip_regprc/revoke.sh @@ -28,7 +28,7 @@ fi ## Terminate existing connections echo "Terminating active connections" -CONN=$(PGPASSWORD=$SU_USER_PWD psql --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;) +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" ## Executing DB Revoke scripts @@ -47,4 +47,4 @@ else fi echo Applying revoke changes -PGPASSWORD=$SU_USER_PWD psql --username=$SU_USER --host=$DB_SERVERIP --port=$DB_PORT --dbname=$DEFAULT_DB_NAME -a -b -f $ALTER_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 $ALTER_SCRIPT_FILE diff --git a/db_release_scripts/mosip_regprc/upgrade.sh b/db_release_scripts/mosip_regprc/upgrade.sh index 308efcaf0d3..23cd14cf24b 100644 --- a/db_release_scripts/mosip_regprc/upgrade.sh +++ b/db_release_scripts/mosip_regprc/upgrade.sh @@ -28,7 +28,7 @@ fi ## Terminate existing connections echo "Terminating active connections" -CONN=$(PGPASSWORD=$SU_USER_PWD psql --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;) +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" ## Executing DB Upgrade scripts @@ -47,4 +47,4 @@ else fi echo Applying upgrade changes -PGPASSWORD=$SU_USER_PWD psql --username=$SU_USER --host=$DB_SERVERIP --port=$DB_PORT --dbname=$DEFAULT_DB_NAME -a -b -f $ALTER_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 $ALTER_SCRIPT_FILE From c3b3a04395b4c2accba52c652d65012a748afa8b Mon Sep 17 00:00:00 2001 From: ckm007 Date: Sat, 15 Oct 2022 17:19:25 +0530 Subject: [PATCH 055/133] [MOSIP-23833] removed test entry --- db_release_scripts/mosip_regprc/deploy.properties | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/db_release_scripts/mosip_regprc/deploy.properties b/db_release_scripts/mosip_regprc/deploy.properties index ba91a70895b..72f9f4983d0 100644 --- a/db_release_scripts/mosip_regprc/deploy.properties +++ b/db_release_scripts/mosip_regprc/deploy.properties @@ -1,5 +1,5 @@ -DB_SERVERIP=localhost -DB_PORT=5432 +DB_SERVERIP= +DB_PORT= SU_USER=postgres DEFAULT_DB_NAME=postgres MOSIP_DB_NAME=mosip_regprc From 34e0fec247a6dba5354381d319eacd53b502f052 Mon Sep 17 00:00:00 2001 From: ckm007 Date: Tue, 25 Oct 2022 13:30:33 +0530 Subject: [PATCH 056/133] [MOSIP-23422] changes for including patch release --- db_release_scripts/mosip_regprc/revoke.sh | 29 ++++++++++++------- ...ade.sql => 1.1.5.5_to_1.2.0.1_upgrade.sql} | 0 ...voke.sql => 1.2.0.1_to_1.1.5.5_revoke.sql} | 0 db_release_scripts/mosip_regprc/upgrade.sh | 24 ++++++++++----- 4 files changed, 36 insertions(+), 17 deletions(-) rename db_release_scripts/mosip_regprc/sql/{1.2.0_upgrade.sql => 1.1.5.5_to_1.2.0.1_upgrade.sql} (100%) rename db_release_scripts/mosip_regprc/sql/{1.2.0_revoke.sql => 1.2.0.1_to_1.1.5.5_revoke.sql} (100%) diff --git a/db_release_scripts/mosip_regprc/revoke.sh b/db_release_scripts/mosip_regprc/revoke.sh index cd6c36e7aaf..12ae985490f 100644 --- a/db_release_scripts/mosip_regprc/revoke.sh +++ b/db_release_scripts/mosip_regprc/revoke.sh @@ -1,10 +1,11 @@ -##Properties file +## Properties file set -e properties_file="$1" -revoke_version="$2" -echo "Properties File Name - $properties_file" -echo "DB Revoke Version - $revoke_version" - +revoke_version="$3" +current_version="$2" + echo "Properties File Name - $properties_file" + echo "DB revoke Version - $revoke_version" + echo "DB current version - $current_version" if [ -f "$properties_file" ] then echo "Property file \"$properties_file\" found." @@ -18,7 +19,14 @@ else exit 0 fi -if [ $# -ge 2 ] +if [ $# -ge 2 ] +then + echo "DB current version \"$current_version\" found." +else + echo "DB current version not found, Pass current version as argument." + exit 0 +fi +if [ $# -ge 3 ] then echo "DB revoke version \"$revoke_version\" found." else @@ -31,10 +39,11 @@ 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" -## Executing DB Revoke scripts -echo "Alter scripts deployment on $MOSIP_DB_NAME database is started. Revoke Version is $revoke_version" -ALTER_SCRIPT_FILE="sql/${revoke_version}_${REVOKE_SCRIPT_FILENAME}" -echo "Revoke script considered for DB changes - $ALTER_SCRIPT_FILE" +## Executing DB revoke scripts +echo "Alter scripts deployment on $MOSIP_DB_NAME database from $current_version to $revoke_version started...." +ALTER_SCRIPT_FILE="sql/${current_version}_to_${revoke_version}_${REVOKE_SCRIPT_FILENAME}" + +echo "revoke script considered for release deployment - $ALTER_SCRIPT_FILE" ## Checking If Alter scripts are present echo "Checking if script $ALTER_SCRIPT_FILE is present" diff --git a/db_release_scripts/mosip_regprc/sql/1.2.0_upgrade.sql b/db_release_scripts/mosip_regprc/sql/1.1.5.5_to_1.2.0.1_upgrade.sql similarity index 100% rename from db_release_scripts/mosip_regprc/sql/1.2.0_upgrade.sql rename to db_release_scripts/mosip_regprc/sql/1.1.5.5_to_1.2.0.1_upgrade.sql diff --git a/db_release_scripts/mosip_regprc/sql/1.2.0_revoke.sql b/db_release_scripts/mosip_regprc/sql/1.2.0.1_to_1.1.5.5_revoke.sql similarity index 100% rename from db_release_scripts/mosip_regprc/sql/1.2.0_revoke.sql rename to db_release_scripts/mosip_regprc/sql/1.2.0.1_to_1.1.5.5_revoke.sql diff --git a/db_release_scripts/mosip_regprc/upgrade.sh b/db_release_scripts/mosip_regprc/upgrade.sh index 23cd14cf24b..90df3b59ddd 100644 --- a/db_release_scripts/mosip_regprc/upgrade.sh +++ b/db_release_scripts/mosip_regprc/upgrade.sh @@ -1,10 +1,11 @@ ## Properties file set -e properties_file="$1" -release_version="$2" +upgrade_version="$3" +current_version="$2" echo "Properties File Name - $properties_file" - echo "DB Upgrade Version - $release_version" - + echo "DB Upgrade Version - $upgrade_version" + echo "DB current version - $current_version" if [ -f "$properties_file" ] then echo "Property file \"$properties_file\" found." @@ -20,20 +21,29 @@ fi if [ $# -ge 2 ] then - echo "DB upgrade version \"$release_version\" found." + echo "DB current version \"$current_version\" found." +else + echo "DB current version not found, Pass current version as argument." + exit 0 +fi +if [ $# -ge 3 ] +then + echo "DB upgrade version \"$upgrade_version\" found." else echo "DB upgrade version not found, Pass upgrade version as argument." exit 0 fi + ## 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" ## Executing DB Upgrade scripts -echo "Alter scripts deployment on $MOSIP_DB_NAME database is started....Upgrade Version...$release_version" -ALTER_SCRIPT_FILE="sql/${release_version}_${ALTER_SCRIPT_FILENAME}" +echo "Alter scripts deployment on $MOSIP_DB_NAME database from $current_version to $upgrade_version started...." +ALTER_SCRIPT_FILE="sql/${current_version}_to_${upgrade_version}_${ALTER_SCRIPT_FILENAME}" + echo "Upgrade script considered for release deployment - $ALTER_SCRIPT_FILE" ## Checking If Alter scripts are present @@ -42,7 +52,7 @@ if [ -f "$ALTER_SCRIPT_FILE" ] then echo "SQL file "$ALTER_SCRIPT_FILE" found." else - echo "SQL file not found, Since no SQL file present for \"$release_version\" hence exiting." + echo "SQL file not found, Since no SQL file present for \"$upgrade_version\" hence exiting." exit 0 fi echo Applying upgrade changes From d7c37d4e1a739227d2b64d4df0880e7fa72a2c9a Mon Sep 17 00:00:00 2001 From: M1022006 Date: Thu, 10 Nov 2022 13:15:55 +0530 Subject: [PATCH 057/133] MOSIP-22417 code changes --- .../client/audit/builder/AuditLogRequestBuilder.java | 9 +++++++-- .../workflowmanager/verticle/WorkflowActionJob.java | 3 ++- .../workflowmanager/verticle/WorkflowActionJobTest.java | 5 +++-- 3 files changed, 12 insertions(+), 5 deletions(-) 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 80f49777ec2..ddc7796f584 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 @@ -111,7 +111,7 @@ public ResponseWrapper createAuditRequestBuilder(String descri @SuppressWarnings("unchecked") public ResponseWrapper createAuditRequestBuilder(String description, String eventId, - String eventName, String eventType, String moduleId, String moduleName, String registrationId) { + String eventName, String eventType, String moduleId, String moduleName, String registrationId,AuditLogConstant auditLogConstant) { regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), registrationId, "AuditLogRequestBuilder:: createAuditRequestBuilder(String description, String eventId, String eventName, String eventType,String moduleId,String moduleName,\r\n" @@ -135,7 +135,7 @@ public ResponseWrapper createAuditRequestBuilder(String descri auditRequestDto.setHostIp(ServerUtil.getServerUtilInstance().getServerIp()); auditRequestDto.setHostName(ServerUtil.getServerUtilInstance().getServerName()); auditRequestDto.setId(registrationId); - auditRequestDto.setIdType(AuditLogConstant.REGISTRATION_ID.toString()); + auditRequestDto.setIdType(auditLogConstant.toString()); auditRequestDto.setModuleId(moduleId); auditRequestDto.setModuleName(moduleName); auditRequestDto.setSessionUserId(AuditLogConstant.SYSTEM.toString()); @@ -220,4 +220,9 @@ 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) { + return createAuditRequestBuilder(description, eventId, eventName, eventType, moduleId, moduleName, registrationId, AuditLogConstant.REGISTRATION_ID); + } } diff --git a/registration-processor/workflow-engine/registration-processor-workflow-manager-service/src/main/java/io/mosip/registration/processor/workflowmanager/verticle/WorkflowActionJob.java b/registration-processor/workflow-engine/registration-processor-workflow-manager-service/src/main/java/io/mosip/registration/processor/workflowmanager/verticle/WorkflowActionJob.java index 55b77018366..6a49713b7a3 100644 --- a/registration-processor/workflow-engine/registration-processor-workflow-manager-service/src/main/java/io/mosip/registration/processor/workflowmanager/verticle/WorkflowActionJob.java +++ b/registration-processor/workflow-engine/registration-processor-workflow-manager-service/src/main/java/io/mosip/registration/processor/workflowmanager/verticle/WorkflowActionJob.java @@ -16,6 +16,7 @@ import io.mosip.registration.processor.core.abstractverticle.MosipEventBus; import io.mosip.registration.processor.core.abstractverticle.MosipRouter; import io.mosip.registration.processor.core.abstractverticle.MosipVerticleAPIManager; +import io.mosip.registration.processor.core.code.AuditLogConstant; import io.mosip.registration.processor.core.code.EventId; import io.mosip.registration.processor.core.code.EventName; import io.mosip.registration.processor.core.code.EventType; @@ -219,7 +220,7 @@ public MessageDTO process(MessageDTO object) { : description.getCode(); String moduleName = ModuleName.WORKFLOW_ACTION_JOB.toString(); auditLogRequestBuilder.createAuditRequestBuilder(description.getMessage(), eventId, eventName, eventType, - moduleId, moduleName, registrationId); + moduleId, moduleName, registrationId,AuditLogConstant.NO_ID); } return object; diff --git a/registration-processor/workflow-engine/registration-processor-workflow-manager-service/src/test/java/io/mosip/registration/processor/workflowmanager/verticle/WorkflowActionJobTest.java b/registration-processor/workflow-engine/registration-processor-workflow-manager-service/src/test/java/io/mosip/registration/processor/workflowmanager/verticle/WorkflowActionJobTest.java index 5f99567f9b9..7ea25762637 100644 --- a/registration-processor/workflow-engine/registration-processor-workflow-manager-service/src/test/java/io/mosip/registration/processor/workflowmanager/verticle/WorkflowActionJobTest.java +++ b/registration-processor/workflow-engine/registration-processor-workflow-manager-service/src/test/java/io/mosip/registration/processor/workflowmanager/verticle/WorkflowActionJobTest.java @@ -25,6 +25,7 @@ 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.AuditLogConstant; import io.mosip.registration.processor.core.code.EventId; import io.mosip.registration.processor.core.code.EventName; import io.mosip.registration.processor.core.code.EventType; @@ -110,8 +111,8 @@ public void setup() throws Exception { AuditResponseDto auditResponseDto = new AuditResponseDto(); ResponseWrapper responseWrapper = new ResponseWrapper<>(); responseWrapper.setResponse(auditResponseDto); - auditLogRequestBuilder.createAuditRequestBuilder("test case description", EventId.RPR_401.toString(), - EventName.ADD.toString(), EventType.BUSINESS.toString(), "1234testcase", ApiName.AUDIT); + Mockito.when(auditLogRequestBuilder.createAuditRequestBuilder(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(),Mockito.any(),Mockito.any(AuditLogConstant.class))) + .thenReturn(null); } @Test From 260a7ea3e972e433f4308628641cb65a399a6102 Mon Sep 17 00:00:00 2001 From: M1022006 Date: Wed, 11 Jan 2023 13:38:16 +0530 Subject: [PATCH 058/133] MOSIP-25736 code changes --- .../demodedupe/DemodedupeProcessor.java | 20 ++++++++++++++----- .../demodedupe/DemodedupeProcessorTest.java | 14 +++++++++++++ 2 files changed, 29 insertions(+), 5 deletions(-) diff --git a/registration-processor/core-processor/registration-processor-demo-dedupe-stage/src/main/java/io/mosip/registration/processor/stages/demodedupe/DemodedupeProcessor.java b/registration-processor/core-processor/registration-processor-demo-dedupe-stage/src/main/java/io/mosip/registration/processor/stages/demodedupe/DemodedupeProcessor.java index e4331c2a86a..dc7569e59a7 100644 --- a/registration-processor/core-processor/registration-processor-demo-dedupe-stage/src/main/java/io/mosip/registration/processor/stages/demodedupe/DemodedupeProcessor.java +++ b/registration-processor/core-processor/registration-processor-demo-dedupe-stage/src/main/java/io/mosip/registration/processor/stages/demodedupe/DemodedupeProcessor.java @@ -6,10 +6,6 @@ import java.util.List; import java.util.Set; -import io.mosip.kernel.core.util.StringUtils; -import io.mosip.kernel.core.util.exception.JsonProcessingException; -import io.mosip.registration.processor.core.exception.PacketManagerException; -import io.mosip.registration.processor.core.constant.ProviderStageName; import org.apache.commons.lang3.exception.ExceptionUtils; import org.json.simple.JSONObject; import org.springframework.beans.factory.annotation.Autowired; @@ -20,6 +16,8 @@ import io.mosip.kernel.core.fsadapter.exception.FSAdapterException; import io.mosip.kernel.core.logger.spi.Logger; +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.AbisStatusCode; @@ -34,8 +32,10 @@ import io.mosip.registration.processor.core.constant.AbisConstant; import io.mosip.registration.processor.core.constant.LoggerFileConstant; import io.mosip.registration.processor.core.constant.MappingJsonConstants; +import io.mosip.registration.processor.core.constant.ProviderStageName; import io.mosip.registration.processor.core.exception.ApisResourceAccessException; import io.mosip.registration.processor.core.exception.PacketDecryptionFailureException; +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; @@ -160,6 +160,7 @@ public MessageDTO process(MessageDTO object, String stageName) { boolean isDemoDedupeSkip = true; String moduleName = ModuleName.DEMO_DEDUPE.toString(); String moduleId = PlatformSuccessMessages.RPR_PKR_DEMO_DE_DUP.getCode(); + boolean isDuplicateRequestForSameTransactionId = false; InternalRegistrationStatusDto registrationStatusDto = registrationStatusService .getRegistrationStatus(registrationId, object.getReg_type(), object.getIteration(), object.getWorkflowInstanceId()); @@ -180,7 +181,9 @@ public MessageDTO process(MessageDTO object, String stageName) { insertDemodedupDetails(demographicData, regProcessorIdentityJson, jsonObject, registrationStatusDto, object, moduleId, moduleName); } - + if (abisHandlerUtil.getPacketStatus(registrationStatusDto).equalsIgnoreCase(AbisConstant.DUPLICATE_FOR_SAME_TRANSACTION_ID)) + isDuplicateRequestForSameTransactionId = true; + registrationStatusDto.setRegistrationStageName(stageName); if (isTransactionSuccessful) { object.setIsValid(Boolean.TRUE); @@ -236,6 +239,7 @@ public MessageDTO process(MessageDTO object, String stageName) { description.getMessage() + ExceptionUtils.getStackTrace(ex)); object.setInternalError(Boolean.TRUE); } finally { + if (!isDuplicateRequestForSameTransactionId) { registrationStatusDto .setLatestTransactionTypeCode(RegistrationTransactionTypeCode.DEMOGRAPHIC_VERIFICATION.toString()); moduleId = isTransactionSuccessful ? PlatformSuccessMessages.RPR_PKR_DEMO_DE_DUP.getCode() @@ -277,6 +281,12 @@ public MessageDTO process(MessageDTO object, String stageName) { auditLogRequestBuilder.createAuditRequestBuilder(description.getMessage(), eventId, eventName, eventType, moduleId, moduleName, registrationId); + } else { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + registrationId, "Duplicate request received for same latest transaction id. This will be ignored."); + object.setIsValid(false); + object.setInternalError(true); + } } 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 cdb2b4be990..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 @@ -369,6 +369,7 @@ public void testDemoDedupeUpdatePacketSuccess() throws Exception { 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()); @@ -447,6 +448,7 @@ public void testDemoDedupeResUpdatePacketSuccess() throws Exception { 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()); @@ -885,4 +887,16 @@ public void testDemoDedupeSuccess() throws Exception { } + @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 From bf00aa796fb6e358f7699ae4181ee3e4643280c8 Mon Sep 17 00:00:00 2001 From: Keshav Mishra Date: Fri, 20 Jan 2023 13:41:09 +0530 Subject: [PATCH 059/133] Revert "[MOSIP-24254] reverted pom version" (#1650) --- .github/workflows/push_trigger.yml | 2 +- pom.xml | 2 +- registration-processor/core-processor/pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../registration-processor-abis/pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 2 +- .../pom.xml | 4 +- .../pom.xml | 2 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- registration-processor/init/pom.xml | 2 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../mosip-stage-executor/pom.xml | 4 +- registration-processor/pom.xml | 50 +++++++++---------- registration-processor/post-processor/pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- registration-processor/pre-processor/pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../qc-users-manger/pom.xml | 2 +- .../pom.xml | 4 +- .../dependency-reduced-pom.xml | 6 +-- .../pom.xml | 6 +-- .../registration-processor-core/pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 6 +-- .../pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- registration-processor/stage-groups/pom.xml | 4 +- .../pom.xml | 8 +-- .../pom.xml | 12 ++--- .../pom.xml | 14 +++--- .../pom.xml | 10 ++-- .../pom.xml | 16 +++--- .../pom.xml | 12 ++--- .../pom.xml | 14 +++--- .../workflow-engine/pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- 55 files changed, 159 insertions(+), 159 deletions(-) diff --git a/.github/workflows/push_trigger.yml b/.github/workflows/push_trigger.yml index 193b1799401..296b982e759 100644 --- a/.github/workflows/push_trigger.yml +++ b/.github/workflows/push_trigger.yml @@ -370,7 +370,7 @@ jobs: - name: Publish the maven package run: | - mvn deploy -DaltDeploymentRepository=ossrh::default::${{ secrets.OSSRH_SNAPSHOT_URL }} -s $GITHUB_WORKSPACE/settings.xml -f pom.xml + mvn deploy -DaltDeploymentRepository=ossrh::default::${{ secrets.RELEASE_URL }} -s $GITHUB_WORKSPACE/settings.xml -f pom.xml env: GITHUB_TOKEN: ${{ secrets.RELEASE_TOKEN }} GPG_TTY: $(tty) diff --git a/pom.xml b/pom.xml index 965197ff54e..ae08308e5ca 100644 --- a/pom.xml +++ b/pom.xml @@ -4,7 +4,7 @@ 4.0.0 io.mosip registration - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 pom MOSIP Registration Parent POM diff --git a/registration-processor/core-processor/pom.xml b/registration-processor/core-processor/pom.xml index 106d77739de..351e147b9d6 100644 --- a/registration-processor/core-processor/pom.xml +++ b/registration-processor/core-processor/pom.xml @@ -5,9 +5,9 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 core-processor core-processor diff --git a/registration-processor/core-processor/registration-processor-abis-handler-stage/pom.xml b/registration-processor/core-processor/registration-processor-abis-handler-stage/pom.xml index b49fc181c4d..772656286b9 100644 --- a/registration-processor/core-processor/registration-processor-abis-handler-stage/pom.xml +++ b/registration-processor/core-processor/registration-processor-abis-handler-stage/pom.xml @@ -5,11 +5,11 @@ io.mosip.registrationprocessor core-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-abis-handler-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 jar UTF-8 diff --git a/registration-processor/core-processor/registration-processor-abis-middleware-stage/pom.xml b/registration-processor/core-processor/registration-processor-abis-middleware-stage/pom.xml index 8495dd388f4..96485b993a8 100644 --- a/registration-processor/core-processor/registration-processor-abis-middleware-stage/pom.xml +++ b/registration-processor/core-processor/registration-processor-abis-middleware-stage/pom.xml @@ -5,10 +5,10 @@ io.mosip.registrationprocessor core-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-abis-middleware-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 jar UTF-8 diff --git a/registration-processor/core-processor/registration-processor-abis/pom.xml b/registration-processor/core-processor/registration-processor-abis/pom.xml index 29a7bcb63ff..9d0d4370574 100644 --- a/registration-processor/core-processor/registration-processor-abis/pom.xml +++ b/registration-processor/core-processor/registration-processor-abis/pom.xml @@ -8,10 +8,10 @@ io.mosip.registrationprocessor core-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-abis - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-abis UTF-8 diff --git a/registration-processor/core-processor/registration-processor-bio-dedupe-stage/pom.xml b/registration-processor/core-processor/registration-processor-bio-dedupe-stage/pom.xml index 737ae711b55..0f16b444e8f 100644 --- a/registration-processor/core-processor/registration-processor-bio-dedupe-stage/pom.xml +++ b/registration-processor/core-processor/registration-processor-bio-dedupe-stage/pom.xml @@ -5,11 +5,11 @@ io.mosip.registrationprocessor core-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-bio-dedupe-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 jar UTF-8 diff --git a/registration-processor/core-processor/registration-processor-biometric-authentication-stage/pom.xml b/registration-processor/core-processor/registration-processor-biometric-authentication-stage/pom.xml index 871df8996a9..06092177c26 100644 --- a/registration-processor/core-processor/registration-processor-biometric-authentication-stage/pom.xml +++ b/registration-processor/core-processor/registration-processor-biometric-authentication-stage/pom.xml @@ -5,10 +5,10 @@ io.mosip.registrationprocessor core-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-biometric-authentication-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 jar UTF-8 diff --git a/registration-processor/core-processor/registration-processor-biometric-extraction-stage/pom.xml b/registration-processor/core-processor/registration-processor-biometric-extraction-stage/pom.xml index b7c2f9d2ed0..bceda4de3de 100644 --- a/registration-processor/core-processor/registration-processor-biometric-extraction-stage/pom.xml +++ b/registration-processor/core-processor/registration-processor-biometric-extraction-stage/pom.xml @@ -5,7 +5,7 @@ io.mosip.registrationprocessor core-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-biometric-extraction-stage jar diff --git a/registration-processor/core-processor/registration-processor-demo-dedupe-stage/pom.xml b/registration-processor/core-processor/registration-processor-demo-dedupe-stage/pom.xml index bf2643428fd..32c7a9cdbb6 100644 --- a/registration-processor/core-processor/registration-processor-demo-dedupe-stage/pom.xml +++ b/registration-processor/core-processor/registration-processor-demo-dedupe-stage/pom.xml @@ -5,10 +5,10 @@ io.mosip.registrationprocessor core-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-demo-dedupe-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 jar UTF-8 diff --git a/registration-processor/core-processor/registration-processor-finalization-stage/pom.xml b/registration-processor/core-processor/registration-processor-finalization-stage/pom.xml index 1a52f000158..d6ec3d102a0 100644 --- a/registration-processor/core-processor/registration-processor-finalization-stage/pom.xml +++ b/registration-processor/core-processor/registration-processor-finalization-stage/pom.xml @@ -5,7 +5,7 @@ io.mosip.registrationprocessor core-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-finalization-stage registration-processor-finalization-stage diff --git a/registration-processor/core-processor/registration-processor-manual-adjudication-stage/pom.xml b/registration-processor/core-processor/registration-processor-manual-adjudication-stage/pom.xml index 1db77ee63d4..fda716669f3 100644 --- a/registration-processor/core-processor/registration-processor-manual-adjudication-stage/pom.xml +++ b/registration-processor/core-processor/registration-processor-manual-adjudication-stage/pom.xml @@ -8,11 +8,11 @@ io.mosip.registrationprocessor core-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-manual-adjudication-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 UTF-8 diff --git a/registration-processor/core-processor/registration-processor-uin-generator-stage/pom.xml b/registration-processor/core-processor/registration-processor-uin-generator-stage/pom.xml index abb698a38ad..ea0d5a2eb73 100644 --- a/registration-processor/core-processor/registration-processor-uin-generator-stage/pom.xml +++ b/registration-processor/core-processor/registration-processor-uin-generator-stage/pom.xml @@ -4,10 +4,10 @@ io.mosip.registrationprocessor core-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-uin-generator-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 jar UTF-8 diff --git a/registration-processor/core-processor/registration-processor-verification-stage/pom.xml b/registration-processor/core-processor/registration-processor-verification-stage/pom.xml index c4206b67be5..5eacfaf200b 100644 --- a/registration-processor/core-processor/registration-processor-verification-stage/pom.xml +++ b/registration-processor/core-processor/registration-processor-verification-stage/pom.xml @@ -8,11 +8,11 @@ io.mosip.registrationprocessor core-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-verification-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 UTF-8 diff --git a/registration-processor/init/pom.xml b/registration-processor/init/pom.xml index 494e4fea9da..acb9a8eaf40 100644 --- a/registration-processor/init/pom.xml +++ b/registration-processor/init/pom.xml @@ -6,7 +6,7 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 init diff --git a/registration-processor/init/registration-processor-packet-receiver-stage/pom.xml b/registration-processor/init/registration-processor-packet-receiver-stage/pom.xml index 906a591c711..8c01e101a59 100644 --- a/registration-processor/init/registration-processor-packet-receiver-stage/pom.xml +++ b/registration-processor/init/registration-processor-packet-receiver-stage/pom.xml @@ -7,11 +7,11 @@ io.mosip.registrationprocessor init - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-packet-receiver-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 jar registration-processor-packet-receiver-stage diff --git a/registration-processor/init/registration-processor-registration-status-service/pom.xml b/registration-processor/init/registration-processor-registration-status-service/pom.xml index 01e8d688bfd..cee40b9c641 100644 --- a/registration-processor/init/registration-processor-registration-status-service/pom.xml +++ b/registration-processor/init/registration-processor-registration-status-service/pom.xml @@ -8,10 +8,10 @@ io.mosip.registrationprocessor init - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-registration-status-service - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-registration-status-service diff --git a/registration-processor/mosip-stage-executor/pom.xml b/registration-processor/mosip-stage-executor/pom.xml index ce7f722007d..78dd5a1c966 100644 --- a/registration-processor/mosip-stage-executor/pom.xml +++ b/registration-processor/mosip-stage-executor/pom.xml @@ -5,11 +5,11 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 mosip-stage-executor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 diff --git a/registration-processor/pom.xml b/registration-processor/pom.xml index 9cd555ff9d2..1cb99130a98 100644 --- a/registration-processor/pom.xml +++ b/registration-processor/pom.xml @@ -5,12 +5,12 @@ io.mosip registration - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 io.mosip.registrationprocessor registration-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 pom registration-processor @@ -108,32 +108,32 @@ 0.1.55 - 1.2.0.1-SNAPSHOT - 1.2.0.1-SNAPSHOT - 1.2.0.1-SNAPSHOT - 1.2.0.1-SNAPSHOT - 1.2.0.1-SNAPSHOT - 1.2.0.1-SNAPSHOT - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 + 1.2.0.1-B1 + 1.2.0.1-B1 + 1.2.0.1-B1 + 1.2.0.1-B1 + 1.2.0.1-B1 + 1.2.0.1-B1 - 1.2.0.1-SNAPSHOT - 1.2.0.1-SNAPSHOT - 1.2.0.1-SNAPSHOT - 1.2.0.1-SNAPSHOT - 1.2.0.1-SNAPSHOT - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 + 1.2.0.1-B1 + 1.2.0.1-B1 + 1.2.0.1-B1 + 1.2.0.1-B1 + 1.2.0.1-B1 1.2.0 - 1.2.0.1-SNAPSHOT - 1.2.0.1-SNAPSHOT - 1.2.0.1-SNAPSHOT - 1.2.0.1-SNAPSHOT - 1.2.0.1-SNAPSHOT - 1.2.0.1-SNAPSHOT - 1.2.0.1-SNAPSHOT - 1.2.0.1-SNAPSHOT - 1.2.0.1-SNAPSHOT - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 + 1.2.0.1-B1 + 1.2.0.1-B1 + 1.2.0.1-B1 + 1.2.0.1-B1 + 1.2.0.1-B1 + 1.2.0.1-B1 + 1.2.0.1-B1 + 1.2.0.1-B1 + 1.2.0.1-B1 **/dto/**, **/exception/*Exception.java, **/config/*Config.java, diff --git a/registration-processor/post-processor/pom.xml b/registration-processor/post-processor/pom.xml index f3d3bd158e6..ac3a2ba4971 100644 --- a/registration-processor/post-processor/pom.xml +++ b/registration-processor/post-processor/pom.xml @@ -6,9 +6,9 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 post-processor post-processor diff --git a/registration-processor/post-processor/registration-processor-message-sender-stage/pom.xml b/registration-processor/post-processor/registration-processor-message-sender-stage/pom.xml index 94b54a878aa..9078acad095 100644 --- a/registration-processor/post-processor/registration-processor-message-sender-stage/pom.xml +++ b/registration-processor/post-processor/registration-processor-message-sender-stage/pom.xml @@ -7,11 +7,11 @@ io.mosip.registrationprocessor post-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-message-sender-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 UTF-8 UTF-8 diff --git a/registration-processor/post-processor/registration-processor-printing-stage/pom.xml b/registration-processor/post-processor/registration-processor-printing-stage/pom.xml index 9ef76784ae8..0f16514303c 100644 --- a/registration-processor/post-processor/registration-processor-printing-stage/pom.xml +++ b/registration-processor/post-processor/registration-processor-printing-stage/pom.xml @@ -6,10 +6,10 @@ io.mosip.registrationprocessor post-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-printing-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 UTF-8 UTF-8 diff --git a/registration-processor/post-processor/registration-processor-registration-transaction-service/pom.xml b/registration-processor/post-processor/registration-processor-registration-transaction-service/pom.xml index 7722fe24934..9eeba25f5ac 100644 --- a/registration-processor/post-processor/registration-processor-registration-transaction-service/pom.xml +++ b/registration-processor/post-processor/registration-processor-registration-transaction-service/pom.xml @@ -5,10 +5,10 @@ io.mosip.registrationprocessor post-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-registration-transaction-service - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-registration-transaction-service UTF-8 diff --git a/registration-processor/pre-processor/pom.xml b/registration-processor/pre-processor/pom.xml index dbbd3483267..c9fcd668989 100644 --- a/registration-processor/pre-processor/pom.xml +++ b/registration-processor/pre-processor/pom.xml @@ -7,9 +7,9 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 pre-processor pre-processor diff --git a/registration-processor/pre-processor/registration-processor-cmd-validator-stage/pom.xml b/registration-processor/pre-processor/registration-processor-cmd-validator-stage/pom.xml index 6a5ecd53db8..5f80375a435 100644 --- a/registration-processor/pre-processor/registration-processor-cmd-validator-stage/pom.xml +++ b/registration-processor/pre-processor/registration-processor-cmd-validator-stage/pom.xml @@ -6,10 +6,10 @@ io.mosip.registrationprocessor pre-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-cmd-validator-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-cmd-validator-stage UTF-8 diff --git a/registration-processor/pre-processor/registration-processor-introducer-validator-stage/pom.xml b/registration-processor/pre-processor/registration-processor-introducer-validator-stage/pom.xml index 80f2a06dc20..3e312282a42 100644 --- a/registration-processor/pre-processor/registration-processor-introducer-validator-stage/pom.xml +++ b/registration-processor/pre-processor/registration-processor-introducer-validator-stage/pom.xml @@ -6,10 +6,10 @@ io.mosip.registrationprocessor pre-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-introducer-validator-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-introducer-validator-stage UTF-8 diff --git a/registration-processor/pre-processor/registration-processor-operator-validator-stage/pom.xml b/registration-processor/pre-processor/registration-processor-operator-validator-stage/pom.xml index f5c7d2ebf0d..bd76683991d 100644 --- a/registration-processor/pre-processor/registration-processor-operator-validator-stage/pom.xml +++ b/registration-processor/pre-processor/registration-processor-operator-validator-stage/pom.xml @@ -6,10 +6,10 @@ io.mosip.registrationprocessor pre-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-operator-validator-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-operator-validator-stage UTF-8 diff --git a/registration-processor/pre-processor/registration-processor-packet-classifier-stage/pom.xml b/registration-processor/pre-processor/registration-processor-packet-classifier-stage/pom.xml index a18de10078e..648118ceadb 100644 --- a/registration-processor/pre-processor/registration-processor-packet-classifier-stage/pom.xml +++ b/registration-processor/pre-processor/registration-processor-packet-classifier-stage/pom.xml @@ -7,10 +7,10 @@ io.mosip.registrationprocessor pre-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-packet-classifier-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 jar UTF-8 diff --git a/registration-processor/pre-processor/registration-processor-packet-uploader-stage/pom.xml b/registration-processor/pre-processor/registration-processor-packet-uploader-stage/pom.xml index cfe699815a0..58413e23803 100644 --- a/registration-processor/pre-processor/registration-processor-packet-uploader-stage/pom.xml +++ b/registration-processor/pre-processor/registration-processor-packet-uploader-stage/pom.xml @@ -9,9 +9,9 @@ io.mosip.registrationprocessor pre-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 UTF-8 diff --git a/registration-processor/pre-processor/registration-processor-packet-validator-stage/pom.xml b/registration-processor/pre-processor/registration-processor-packet-validator-stage/pom.xml index c62733d01d2..409c4bf220f 100644 --- a/registration-processor/pre-processor/registration-processor-packet-validator-stage/pom.xml +++ b/registration-processor/pre-processor/registration-processor-packet-validator-stage/pom.xml @@ -7,10 +7,10 @@ io.mosip.registrationprocessor pre-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-packet-validator-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 jar UTF-8 diff --git a/registration-processor/pre-processor/registration-processor-quality-classifier-stage/pom.xml b/registration-processor/pre-processor/registration-processor-quality-classifier-stage/pom.xml index 9f357aea6d6..833e75c92a3 100644 --- a/registration-processor/pre-processor/registration-processor-quality-classifier-stage/pom.xml +++ b/registration-processor/pre-processor/registration-processor-quality-classifier-stage/pom.xml @@ -5,11 +5,11 @@ io.mosip.registrationprocessor pre-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-quality-classifier-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 UTF-8 diff --git a/registration-processor/pre-processor/registration-processor-securezone-notification-stage/pom.xml b/registration-processor/pre-processor/registration-processor-securezone-notification-stage/pom.xml index adac7a92910..b3ab0e91704 100644 --- a/registration-processor/pre-processor/registration-processor-securezone-notification-stage/pom.xml +++ b/registration-processor/pre-processor/registration-processor-securezone-notification-stage/pom.xml @@ -5,10 +5,10 @@ pre-processor io.mosip.registrationprocessor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 4.0.0 - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-securezone-notification-stage diff --git a/registration-processor/pre-processor/registration-processor-supervisor-validator-stage/pom.xml b/registration-processor/pre-processor/registration-processor-supervisor-validator-stage/pom.xml index f1735ff282c..d4d05723920 100644 --- a/registration-processor/pre-processor/registration-processor-supervisor-validator-stage/pom.xml +++ b/registration-processor/pre-processor/registration-processor-supervisor-validator-stage/pom.xml @@ -6,10 +6,10 @@ io.mosip.registrationprocessor pre-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-supervisor-validator-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-supervisor-validator-stage UTF-8 diff --git a/registration-processor/qc-users-manger/pom.xml b/registration-processor/qc-users-manger/pom.xml index f1550c8fc4a..98ef5146ae5 100644 --- a/registration-processor/qc-users-manger/pom.xml +++ b/registration-processor/qc-users-manger/pom.xml @@ -8,7 +8,7 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 diff --git a/registration-processor/registration-processor-bio-dedupe-service-impl/pom.xml b/registration-processor/registration-processor-bio-dedupe-service-impl/pom.xml index b6d2f0eddd3..33f74594ab8 100644 --- a/registration-processor/registration-processor-bio-dedupe-service-impl/pom.xml +++ b/registration-processor/registration-processor-bio-dedupe-service-impl/pom.xml @@ -5,11 +5,11 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-bio-dedupe-service-impl - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-bio-dedupe-service-impl diff --git a/registration-processor/registration-processor-common-camel-bridge/dependency-reduced-pom.xml b/registration-processor/registration-processor-common-camel-bridge/dependency-reduced-pom.xml index 051ece7c025..6c645e5bfb2 100644 --- a/registration-processor/registration-processor-common-camel-bridge/dependency-reduced-pom.xml +++ b/registration-processor/registration-processor-common-camel-bridge/dependency-reduced-pom.xml @@ -3,11 +3,11 @@ registration-processor io.mosip.registrationprocessor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 4.0.0 registration-processor-common-camel-bridge - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 @@ -102,7 +102,7 @@ io.mosip.registration.processor.camel.bridge.MosipCamelBridge 1.0.5 - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 diff --git a/registration-processor/registration-processor-common-camel-bridge/pom.xml b/registration-processor/registration-processor-common-camel-bridge/pom.xml index 3e67f0bae81..4ec488235ab 100644 --- a/registration-processor/registration-processor-common-camel-bridge/pom.xml +++ b/registration-processor/registration-processor-common-camel-bridge/pom.xml @@ -6,16 +6,16 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-common-camel-bridge - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 jar io.mosip.registration.processor.camel.bridge.MosipCamelBridge 1.0.5 - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 diff --git a/registration-processor/registration-processor-core/pom.xml b/registration-processor/registration-processor-core/pom.xml index 41f0268f633..422e0df5f33 100644 --- a/registration-processor/registration-processor-core/pom.xml +++ b/registration-processor/registration-processor-core/pom.xml @@ -7,10 +7,10 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-core - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 org.mockito diff --git a/registration-processor/registration-processor-info-storage-service/pom.xml b/registration-processor/registration-processor-info-storage-service/pom.xml index 08a80dd04b5..81de5a580ad 100644 --- a/registration-processor/registration-processor-info-storage-service/pom.xml +++ b/registration-processor/registration-processor-info-storage-service/pom.xml @@ -7,10 +7,10 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-info-storage-service - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-info-storage-service UTF-8 diff --git a/registration-processor/registration-processor-message-sender-impl/pom.xml b/registration-processor/registration-processor-message-sender-impl/pom.xml index fa5a7b048dd..5132a6aa025 100644 --- a/registration-processor/registration-processor-message-sender-impl/pom.xml +++ b/registration-processor/registration-processor-message-sender-impl/pom.xml @@ -8,11 +8,11 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-message-sender-impl - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 UTF-8 diff --git a/registration-processor/registration-processor-notification-service/pom.xml b/registration-processor/registration-processor-notification-service/pom.xml index ed32e34884a..9e72de49c3f 100644 --- a/registration-processor/registration-processor-notification-service/pom.xml +++ b/registration-processor/registration-processor-notification-service/pom.xml @@ -8,15 +8,15 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-notification-service - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 UTF-8 UTF-8 - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 diff --git a/registration-processor/registration-processor-packet-manager/pom.xml b/registration-processor/registration-processor-packet-manager/pom.xml index c32bc40c734..dbef7053f11 100644 --- a/registration-processor/registration-processor-packet-manager/pom.xml +++ b/registration-processor/registration-processor-packet-manager/pom.xml @@ -7,12 +7,12 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-packet-manager registration-processor-packet-manager - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 UTF-8 diff --git a/registration-processor/registration-processor-registration-status-service-impl/pom.xml b/registration-processor/registration-processor-registration-status-service-impl/pom.xml index bdcbf23f5c3..cd6e25f01ba 100644 --- a/registration-processor/registration-processor-registration-status-service-impl/pom.xml +++ b/registration-processor/registration-processor-registration-status-service-impl/pom.xml @@ -8,10 +8,10 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-registration-status-service-impl - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 UTF-8 diff --git a/registration-processor/registration-processor-rest-client/pom.xml b/registration-processor/registration-processor-rest-client/pom.xml index abcae1d9870..bdd642bd8b4 100644 --- a/registration-processor/registration-processor-rest-client/pom.xml +++ b/registration-processor/registration-processor-rest-client/pom.xml @@ -9,12 +9,12 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-rest-client registration-processor-rest-client - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 UTF-8 diff --git a/registration-processor/stage-groups/pom.xml b/registration-processor/stage-groups/pom.xml index 8eb2b176739..f1dbd341adb 100644 --- a/registration-processor/stage-groups/pom.xml +++ b/registration-processor/stage-groups/pom.xml @@ -7,9 +7,9 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 stage-groups stage-groups diff --git a/registration-processor/stage-groups/registration-processor-stage-group-1/pom.xml b/registration-processor/stage-groups/registration-processor-stage-group-1/pom.xml index 2b85ca79676..ed78ae79825 100644 --- a/registration-processor/stage-groups/registration-processor-stage-group-1/pom.xml +++ b/registration-processor/stage-groups/registration-processor-stage-group-1/pom.xml @@ -5,11 +5,11 @@ io.mosip.registrationprocessor stage-groups - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-stage-group-1 - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 UTF-8 @@ -21,14 +21,14 @@ io.mosip.registrationprocessor mosip-stage-executor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 io.mosip.registrationprocessor registration-processor-packet-receiver-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 diff --git a/registration-processor/stage-groups/registration-processor-stage-group-2/pom.xml b/registration-processor/stage-groups/registration-processor-stage-group-2/pom.xml index 5a878a5566d..ada325f055d 100644 --- a/registration-processor/stage-groups/registration-processor-stage-group-2/pom.xml +++ b/registration-processor/stage-groups/registration-processor-stage-group-2/pom.xml @@ -5,11 +5,11 @@ io.mosip.registrationprocessor stage-groups - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-stage-group-2 - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 UTF-8 @@ -21,24 +21,24 @@ io.mosip.registrationprocessor mosip-stage-executor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 io.mosip.registrationprocessor registration-processor-quality-classifier-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 io.mosip.registrationprocessor registration-processor-securezone-notification-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 io.mosip.registrationprocessor registration-processor-message-sender-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 diff --git a/registration-processor/stage-groups/registration-processor-stage-group-3/pom.xml b/registration-processor/stage-groups/registration-processor-stage-group-3/pom.xml index 2adf6045d83..e1de3540c1d 100644 --- a/registration-processor/stage-groups/registration-processor-stage-group-3/pom.xml +++ b/registration-processor/stage-groups/registration-processor-stage-group-3/pom.xml @@ -5,11 +5,11 @@ io.mosip.registrationprocessor stage-groups - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-stage-group-3 - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 UTF-8 @@ -21,29 +21,29 @@ io.mosip.registrationprocessor mosip-stage-executor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 io.mosip.registrationprocessor registration-processor-abis-handler-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 io.mosip.registrationprocessor registration-processor-abis-middleware-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 io.mosip.registrationprocessor registration-processor-bio-dedupe-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 io.mosip.registrationprocessor registration-processor-manual-adjudication-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 diff --git a/registration-processor/stage-groups/registration-processor-stage-group-4/pom.xml b/registration-processor/stage-groups/registration-processor-stage-group-4/pom.xml index 3ffb388b565..85e97e9dee6 100644 --- a/registration-processor/stage-groups/registration-processor-stage-group-4/pom.xml +++ b/registration-processor/stage-groups/registration-processor-stage-group-4/pom.xml @@ -5,11 +5,11 @@ io.mosip.registrationprocessor stage-groups - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-stage-group-4 - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 UTF-8 @@ -21,19 +21,19 @@ io.mosip.registrationprocessor mosip-stage-executor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 io.mosip.registrationprocessor registration-processor-biometric-authentication-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 io.mosip.registrationprocessor registration-processor-demo-dedupe-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 diff --git a/registration-processor/stage-groups/registration-processor-stage-group-5/pom.xml b/registration-processor/stage-groups/registration-processor-stage-group-5/pom.xml index 201a885a1af..5de03453f5f 100644 --- a/registration-processor/stage-groups/registration-processor-stage-group-5/pom.xml +++ b/registration-processor/stage-groups/registration-processor-stage-group-5/pom.xml @@ -5,11 +5,11 @@ io.mosip.registrationprocessor stage-groups - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-stage-group-5 - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 UTF-8 @@ -21,34 +21,34 @@ io.mosip.registrationprocessor mosip-stage-executor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 io.mosip.registrationprocessor registration-processor-cmd-validator-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 io.mosip.registrationprocessor registration-processor-operator-validator-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 io.mosip.registrationprocessor registration-processor-supervisor-validator-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 io.mosip.registrationprocessor registration-processor-introducer-validator-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 io.mosip.registrationprocessor registration-processor-packet-validator-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 diff --git a/registration-processor/stage-groups/registration-processor-stage-group-6/pom.xml b/registration-processor/stage-groups/registration-processor-stage-group-6/pom.xml index 681015c8a46..f4ce7933f7a 100644 --- a/registration-processor/stage-groups/registration-processor-stage-group-6/pom.xml +++ b/registration-processor/stage-groups/registration-processor-stage-group-6/pom.xml @@ -5,11 +5,11 @@ io.mosip.registrationprocessor stage-groups - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-stage-group-6 - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 UTF-8 @@ -21,24 +21,24 @@ io.mosip.registrationprocessor mosip-stage-executor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 io.mosip.registrationprocessor registration-processor-packet-uploader-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 io.mosip.registrationprocessor registration-processor-packet-classifier-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 io.mosip.registrationprocessor registration-processor-verification-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 diff --git a/registration-processor/stage-groups/registration-processor-stage-group-7/pom.xml b/registration-processor/stage-groups/registration-processor-stage-group-7/pom.xml index 3c8ffc6f066..f22d032a05b 100644 --- a/registration-processor/stage-groups/registration-processor-stage-group-7/pom.xml +++ b/registration-processor/stage-groups/registration-processor-stage-group-7/pom.xml @@ -5,11 +5,11 @@ io.mosip.registrationprocessor stage-groups - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-stage-group-7 - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 UTF-8 @@ -21,29 +21,29 @@ io.mosip.registrationprocessor mosip-stage-executor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 io.mosip.registrationprocessor registration-processor-uin-generator-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 io.mosip.registrationprocessor registration-processor-biometric-extraction-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 io.mosip.registrationprocessor registration-processor-finalization-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 io.mosip.registrationprocessor registration-processor-printing-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 diff --git a/registration-processor/workflow-engine/pom.xml b/registration-processor/workflow-engine/pom.xml index b9485169347..7bb2d165aeb 100644 --- a/registration-processor/workflow-engine/pom.xml +++ b/registration-processor/workflow-engine/pom.xml @@ -5,9 +5,9 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 workflow-engine workflow-engine diff --git a/registration-processor/workflow-engine/registration-processor-reprocessor/pom.xml b/registration-processor/workflow-engine/registration-processor-reprocessor/pom.xml index 35b437cd194..fac36d647a2 100644 --- a/registration-processor/workflow-engine/registration-processor-reprocessor/pom.xml +++ b/registration-processor/workflow-engine/registration-processor-reprocessor/pom.xml @@ -7,10 +7,10 @@ io.mosip.registrationprocessor workflow-engine - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-reprocessor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-reprocessor UTF-8 diff --git a/registration-processor/workflow-engine/registration-processor-workflow-manager-service/pom.xml b/registration-processor/workflow-engine/registration-processor-workflow-manager-service/pom.xml index c69945fe557..c17473fbd1a 100644 --- a/registration-processor/workflow-engine/registration-processor-workflow-manager-service/pom.xml +++ b/registration-processor/workflow-engine/registration-processor-workflow-manager-service/pom.xml @@ -5,10 +5,10 @@ io.mosip.registrationprocessor workflow-engine - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-workflow-manager-service - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 registration-processor-workflow-manager-service UTF-8 From ee662d187e35a3ca030ea7379dbafb3061ba3d71 Mon Sep 17 00:00:00 2001 From: Sowmya Ujjappa Banakar <43202851+sowmya695@users.noreply.github.com> Date: Tue, 28 Mar 2023 11:58:11 +0530 Subject: [PATCH 060/133] Mosip 23945 release 1.2.0.1 (#1677) * MOSIP-23945 rest template fix * MOSIP-23945 Code changes --------- Co-authored-by: Sowmya Ujjappa Banakar --- .../packet/storage/utils/Utilities.java | 1644 +++++++++-------- .../impl/MessageNotificationServiceImpl.java | 19 +- 2 files changed, 836 insertions(+), 827 deletions(-) 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 a803d2730d7..72fd2d76e1c 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,822 +1,824 @@ -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.*; - -import io.mosip.kernel.core.util.exception.JsonProcessingException; -import io.mosip.registration.processor.core.exception.PacketManagerException; -import io.mosip.registration.processor.packet.manager.idreposervice.IdRepoService; -import io.mosip.registration.processor.packet.storage.dto.ConfigEnum; -import io.mosip.registration.processor.core.constant.ProviderStageName; -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.DateUtils; -import io.mosip.registration.processor.abis.queue.dto.AbisQueueDetails; -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.LoggerFileConstant; -import io.mosip.registration.processor.core.constant.MappingJsonConstants; -import io.mosip.registration.processor.core.exception.ApisResourceAccessException; -import io.mosip.registration.processor.core.exception.RegistrationProcessorCheckedException; -import io.mosip.registration.processor.core.exception.RegistrationProcessorUnCheckedException; -import io.mosip.registration.processor.core.exception.util.PlatformErrorMessages; -import io.mosip.registration.processor.core.idrepo.dto.IdRequestDto; -import io.mosip.registration.processor.core.idrepo.dto.IdResponseDTO; -import io.mosip.registration.processor.core.idrepo.dto.IdResponseDTO1; -import io.mosip.registration.processor.core.idrepo.dto.RequestDto; -import io.mosip.registration.processor.core.logger.RegProcessorLogger; -import io.mosip.registration.processor.core.packet.dto.Identity; -import io.mosip.registration.processor.core.packet.dto.vid.VidResponseDTO; -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.MosipQueueConnectionFactory; -import io.mosip.registration.processor.core.spi.restclient.RegistrationProcessorRestClientService; -import io.mosip.registration.processor.core.util.JsonUtil; -import io.mosip.registration.processor.packet.storage.dao.PacketInfoDao; -import io.mosip.registration.processor.packet.storage.dto.ApplicantInfoDto; -import io.mosip.registration.processor.packet.storage.exception.IdRepoAppException; -import io.mosip.registration.processor.packet.storage.exception.ParsingException; -import io.mosip.registration.processor.packet.storage.exception.QueueConnectionNotFound; -import io.mosip.registration.processor.packet.storage.exception.VidCreationException; -import io.mosip.registration.processor.status.dao.RegistrationStatusDao; -import io.mosip.registration.processor.status.dto.InternalRegistrationStatusDto; -import io.mosip.registration.processor.status.entity.RegistrationStatusEntity; -import lombok.Data; - -/** - * The Class Utilities. - * - * @author Girish Yarru - */ -@Component - -/** - * Instantiates a new utilities. - */ -@Data -public class Utilities { - /** The reg proc logger. */ - private static Logger regProcLogger = RegProcessorLogger.getLogger(Utilities.class); - private static final String SOURCE = "source"; - private static final String PROCESS = "process"; - private static final String PROVIDER = "provider"; - - private static Map readerConfiguration; - private static Map writerConfiguration; - - /** The Constant UIN. */ - private static final String UIN = "UIN"; - - /** The Constant FILE_SEPARATOR. */ - public static final String FILE_SEPARATOR = "\\"; - - /** The Constant RE_PROCESSING. */ - private static final String RE_PROCESSING = "re-processing"; - - /** The Constant HANDLER. */ - private static final String HANDLER = "handler"; - - /** The Constant NEW_PACKET. */ - private static final String NEW_PACKET = "New-packet"; - - @Value("${mosip.kernel.machineid.length}") - private int machineIdLength; - - @Value("${mosip.kernel.registrationcenterid.length}") - private int centerIdLength; - - @Autowired - private ObjectMapper objMapper; - - @Autowired - private IdRepoService idRepoService; - - - /** The rest client service. */ - @Autowired - private RegistrationProcessorRestClientService restClientService; - - /** The mosip connection factory. */ - @Autowired - private MosipQueueConnectionFactory mosipConnectionFactory; - - @Value("${provider.packetreader.mosip}") - private String provider; - - /** The config server file storage URL. */ - @Value("${config.server.file.storage.uri}") - private String configServerFileStorageURL; - - /** The get reg processor identity json. */ - @Value("${registration.processor.identityjson}") - private String getRegProcessorIdentityJson; - - /** The get reg processor demographic identity. */ - @Value("${registration.processor.demographic.identity}") - private String getRegProcessorDemographicIdentity; - - /** The get reg processor applicant type. */ - @Value("${registration.processor.applicant.type}") - private String getRegProcessorApplicantType; - - /** The dob format. */ - @Value("${registration.processor.applicant.dob.format}") - private String dobFormat; - - /** The elapse time. */ - @Value("${registration.processor.reprocess.elapse.time}") - private long elapseTime; - - /** The registration processor abis json. */ - @Value("${registration.processor.abis.json}") - private String registrationProcessorAbisJson; - - /** The id repo update. */ - @Value("${registration.processor.id.repo.update}") - private String idRepoUpdate; - - /** The vid version. */ - @Value("${registration.processor.id.repo.vidVersion}") - private String vidVersion; - - @Autowired - private PacketInfoDao packetInfoDao; - - @Autowired - private PriorityBasedPacketManagerService packetManagerService; - - /** The registration status dao. */ - @Autowired - private RegistrationStatusDao registrationStatusDao; - - /** The packet info manager. */ - @Autowired - private PacketInfoManager packetInfoManager; - - /** The Constant INBOUNDQUEUENAME. */ - private static final String INBOUNDQUEUENAME = "inboundQueueName"; - - /** The Constant OUTBOUNDQUEUENAME. */ - private static final String OUTBOUNDQUEUENAME = "outboundQueueName"; - - /** The Constant ABIS. */ - private static final String ABIS = "abis"; - - /** The Constant USERNAME. */ - private static final String USERNAME = "userName"; - - /** The Constant PASSWORD. */ - private static final String PASSWORD = "password"; - - /** The Constant BROKERURL. */ - private static final String BROKERURL = "brokerUrl"; - - /** The Constant TYPEOFQUEUE. */ - private static final String TYPEOFQUEUE = "typeOfQueue"; - - /** The Constant NAME. */ - private static final String NAME = "name"; - - /** The Constant NAME. */ - private static final String INBOUNDMESSAGETTL = "inboundMessageTTL"; - - /** The Constant FAIL_OVER. */ - private static final String FAIL_OVER = "failover:("; - - /** The Constant RANDOMIZE_FALSE. */ - private static final String RANDOMIZE_FALSE = ")?randomize=false"; - - private static final String VALUE = "value"; - - private JSONObject mappingJsonObject = null; - - public static void initialize(Map reader, Map writer) { - readerConfiguration = reader; - writerConfiguration = writer; - } - - /** - * Gets the json. - * - * @param configServerFileStorageURL - * the config server file storage URL - * @param uri - * the uri - * @return the json - */ - public static String getJson(String configServerFileStorageURL, String uri) { - RestTemplate restTemplate = new RestTemplate(); - return restTemplate.getForObject(configServerFileStorageURL + uri, String.class); - } - - /** - * get applicant age by registration id. Checks the id json if dob or age - * present, if yes returns age if both dob or age are not present then retrieves - * age from id repo - * - * @param id - * the registration id - * @return the applicant age - * @throws IOException - * Signals that an I/O exception has occurred. - * @throws IOException - * Signals that an I/O exception has occurred. - * @throws ApisResourceAccessException - * the packet decryption failure exception - * @throws RegistrationProcessorCheckedException - */ - public int getApplicantAge(String id, String process, ProviderStageName stageName) throws IOException, - ApisResourceAccessException, JsonProcessingException, PacketManagerException { - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), - id, "Utilities::getApplicantAge()::entry"); - - String applicantDob = packetManagerService.getFieldByMappingJsonKey(id, MappingJsonConstants.DOB, process, stageName); - String applicantAge = packetManagerService.getFieldByMappingJsonKey(id, MappingJsonConstants.AGE, process, stageName); - if (applicantDob != null) { - return calculateAge(applicantDob); - } else if (applicantAge != null) { - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), - id, "Utilities::getApplicantAge()::exit when applicantAge is not null"); - return Integer.valueOf(applicantAge); - } else { - String uin = getUIn(id, process, stageName); - JSONObject identityJSONOject = retrieveIdrepoJson(uin); - JSONObject regProcessorIdentityJson = getRegistrationProcessorMappingJson(MappingJsonConstants.IDENTITY); - String ageKey = JsonUtil.getJSONValue(JsonUtil.getJSONObject(regProcessorIdentityJson, MappingJsonConstants.AGE), VALUE); - String dobKey = JsonUtil.getJSONValue(JsonUtil.getJSONObject(regProcessorIdentityJson, MappingJsonConstants.DOB), VALUE); - String idRepoApplicantDob = JsonUtil.getJSONValue(identityJSONOject, dobKey); - if (idRepoApplicantDob != null) { - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), - id, "Utilities::getApplicantAge()::exit when ID REPO applicantDob is not null"); - return calculateAge(idRepoApplicantDob); - } - Integer idRepoApplicantAge = JsonUtil.getJSONValue(identityJSONOject, ageKey); - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), - id, "Utilities::getApplicantAge()::exit when ID REPO applicantAge is not null"); - return idRepoApplicantAge != null ? idRepoApplicantAge : -1; - - } - - } - - public String getDefaultSource(String process, ConfigEnum config) { - Map configMap = null; - if (config.equals(ConfigEnum.READER)) - configMap = readerConfiguration; - else if (config.equals(ConfigEnum.WRITER)) - configMap = writerConfiguration; - - if (configMap != null) { - for (Map.Entry entry : configMap.entrySet()) { - String[] values = entry.getValue().split(","); - String source = null; - for (String val : values) { - if (val.startsWith("process:") && val.contains(process)) - for (String sVal : values) { - if (sVal.startsWith("source:")) { - source = sVal.replace("source:", ""); - return source; - } - } - } - } - } - return null; - } - - public String getSource(String packetSegment, String process, String field) throws IOException { - String source = null; - JSONObject jsonObject = getRegistrationProcessorMappingJson(packetSegment); - Object obj = field == null ? jsonObject.get(PROVIDER) : getField(jsonObject, field); - if (obj != null && obj instanceof ArrayList) { - List providerList = (List) obj; - for (String value : providerList) { - String[] values = value.split(","); - for (String provider : values) { - if (provider != null) { - if (provider.startsWith(PROCESS) && provider.contains(process)) { - for (String val : values) { - if (val.startsWith(SOURCE)) { - return val.replace(SOURCE + ":", "").trim(); - } - } - } - } - } - } - } - - return source; - } - - private Object getField(JSONObject jsonObject, String field) { - LinkedHashMap lm = (LinkedHashMap) jsonObject.get(field); - return lm.get(PROVIDER); - } - - - public String getSourceFromIdField(String packetSegment, String process, String idField) throws IOException { - JSONObject jsonObject = getRegistrationProcessorMappingJson(packetSegment); - for (Object key : jsonObject.keySet()) { - LinkedHashMap hMap = (LinkedHashMap) jsonObject.get(key); - String value = (String) hMap.get(VALUE); - if (value != null && value.contains(idField)) { - return getSource(packetSegment, process, key.toString()); - } - } - return null; - } - - /** - * retrieving identity json ffrom id repo by UIN. - * - * @param uin - * the uin - * @return the JSON object - * @throws ApisResourceAccessException - * the apis resource access exception - * @throws IdRepoAppException - * the id repo app exception - * @throws IOException - * Signals that an I/O exception has occurred. - */ - public JSONObject retrieveIdrepoJson(String uin) throws ApisResourceAccessException, IdRepoAppException, IOException { - - if (uin != null) { - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.UIN.toString(), "", - "Utilities::retrieveIdrepoJson()::entry"); - List pathSegments = new ArrayList<>(); - pathSegments.add(uin); - IdResponseDTO1 idResponseDto; - - idResponseDto = (IdResponseDTO1) restClientService.getApi(ApiName.IDREPOGETIDBYUIN, pathSegments, "", "", - IdResponseDTO1.class); - if (idResponseDto == null) { - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.UIN.toString(), "", - "Utilities::retrieveIdrepoJson()::exit idResponseDto is null"); - return null; - } - if (!idResponseDto.getErrors().isEmpty()) { - List error = idResponseDto.getErrors(); - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.UIN.toString(), "", - "Utilities::retrieveIdrepoJson():: error with error message " + error.get(0).getMessage()); - throw new IdRepoAppException(error.get(0).getMessage()); - } - String response = objMapper.writeValueAsString(idResponseDto.getResponse().getIdentity()); - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.UIN.toString(), "", - "Utilities::retrieveIdrepoJson():: IDREPOGETIDBYUIN GET service call ended Successfully"); - try { - return (JSONObject) new JSONParser().parse(response); - } catch (org.json.simple.parser.ParseException e) { - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.UIN.toString(), "", - ExceptionUtils.getStackTrace(e)); - throw new IdRepoAppException("Error while parsing string to JSONObject",e); - } - - - } - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.UIN.toString(), "", - "Utilities::retrieveIdrepoJson()::exit UIN is null"); - return null; - } - - /** - * Check if uin is present in idrepo - * @param uin - * @return - * @throws ApisResourceAccessException - * @throws IOException - */ - public boolean uinPresentInIdRepo(String uin) throws ApisResourceAccessException, IOException { - return idRepoService.findUinFromIdrepo(uin, getGetRegProcessorDemographicIdentity()) != null; - } - - /** - * Check if uin is missing from Id - * @param errorCode - * @param id - * @param idType - * @return - */ - public boolean isUinMissingFromIdAuth(String errorCode, String id, String idType) { - if (errorCode.equalsIgnoreCase("IDA-MLC-018") && - idType != null && idType.equalsIgnoreCase("UIN")) { - try { - return uinPresentInIdRepo(id); - } catch (IOException | ApisResourceAccessException exception) { - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.UIN.toString(), "", - ExceptionUtils.getStackTrace(exception)); - // in case of exception return true so that the request is marked for reprocess - return true; - } - } - return false; - } - - /** - * Returns all the list of queue details(inbound/outbound address,name,url,pwd) - * from abisJson Also validates the abis json fileds(null or not). - * - * @return the abis queue details - * @throws RegistrationProcessorCheckedException - * the registration processor checked exception - */ - public List getAbisQueueDetails() throws RegistrationProcessorCheckedException { - List abisQueueDetailsList = new ArrayList<>(); - String registrationProcessorAbis = Utilities.getJson(configServerFileStorageURL, registrationProcessorAbisJson); - JSONObject regProcessorAbisJson; - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", - "Utilities::getAbisQueueDetails()::entry"); - - try { - regProcessorAbisJson = JsonUtil.objectMapperReadValue(registrationProcessorAbis, JSONObject.class); - - JSONArray regProcessorAbisArray = JsonUtil.getJSONArray(regProcessorAbisJson, ABIS); - - for (Object jsonObject : regProcessorAbisArray) { - AbisQueueDetails abisQueueDetails = new AbisQueueDetails(); - JSONObject json = new JSONObject((Map) jsonObject); - String userName = validateAbisQueueJsonAndReturnValue(json, USERNAME); - String password = validateAbisQueueJsonAndReturnValue(json, PASSWORD); - String brokerUrl = validateAbisQueueJsonAndReturnValue(json, BROKERURL); - String failOverBrokerUrl = FAIL_OVER + brokerUrl + "," + brokerUrl + RANDOMIZE_FALSE; - String typeOfQueue = validateAbisQueueJsonAndReturnValue(json, TYPEOFQUEUE); - String inboundQueueName = validateAbisQueueJsonAndReturnValue(json, INBOUNDQUEUENAME); - String outboundQueueName = validateAbisQueueJsonAndReturnValue(json, OUTBOUNDQUEUENAME); - String queueName = validateAbisQueueJsonAndReturnValue(json, NAME); - int inboundMessageTTL = validateAbisQueueJsonAndReturnIntValue(json, INBOUNDMESSAGETTL); - MosipQueue mosipQueue = mosipConnectionFactory.createConnection(typeOfQueue, userName, password, - failOverBrokerUrl); - if (mosipQueue == null) - throw new QueueConnectionNotFound( - PlatformErrorMessages.RPR_PIS_ABIS_QUEUE_CONNECTION_NULL.getMessage()); - - abisQueueDetails.setMosipQueue(mosipQueue); - abisQueueDetails.setInboundQueueName(inboundQueueName); - abisQueueDetails.setOutboundQueueName(outboundQueueName); - abisQueueDetails.setName(queueName); - abisQueueDetails.setInboundMessageTTL(inboundMessageTTL); - abisQueueDetailsList.add(abisQueueDetails); - - } - } catch (IOException e) { - throw new RegistrationProcessorCheckedException(PlatformErrorMessages.RPR_SYS_IO_EXCEPTION.getCode(), - PlatformErrorMessages.RPR_SYS_IO_EXCEPTION.getMessage(), e); - } - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", - "Utilities::getAbisQueueDetails()::exit"); - - return abisQueueDetailsList; - - } - - /** - * Gets registration processor mapping json from config and maps to - * RegistrationProcessorIdentity java class. - * - * @return the registration processor identity json - * @throws IOException - * Signals that an I/O exception has occurred. - */ - public JSONObject getRegistrationProcessorMappingJson(String packetSegment) throws IOException { - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", - "Utilities::getRegistrationProcessorMappingJson()::entry"); - - if (mappingJsonObject == null) { - String mappingJsonString = Utilities.getJson(configServerFileStorageURL, getRegProcessorIdentityJson); - mappingJsonObject = objMapper.readValue(mappingJsonString, JSONObject.class); - - } - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", - "Utilities::getRegistrationProcessorMappingJson()::exit"); - return JsonUtil.getJSONObject(mappingJsonObject, packetSegment); - - } - - public String getMappingJsonValue(String key, String packetSegment) throws IOException { - JSONObject jsonObject = getRegistrationProcessorMappingJson(packetSegment); - Object obj = jsonObject.get(key); - if (obj instanceof LinkedHashMap) { - LinkedHashMap hm = (LinkedHashMap) obj; - return hm.get("value") != null ? hm.get("value").toString() : null; - } - return jsonObject.get(key) != null ? jsonObject.get(key).toString() : null; - - } - - /** - * Get UIN from identity json (used only for update/res update/activate/de - * activate packets). - * - * @param id - * the registration id - * @return the u in - * @throws IOException - * Signals that an I/O exception has occurred. - * @throws IOException - * Signals that an I/O exception has occurred. - * @throws ApisResourceAccessException - * the apis resource access exception - * @throws RegistrationProcessorCheckedException - */ - public String getUIn(String id, String process, ProviderStageName stageName) throws IOException, ApisResourceAccessException, PacketManagerException, JsonProcessingException { - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - id, "Utilities::getUIn()::entry"); - String UIN = packetManagerService.getFieldByMappingJsonKey(id, MappingJsonConstants.UIN, process, stageName); - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - id, "Utilities::getUIn()::exit"); - - return UIN; - - } - - /** - * Gets the elapse status. - * - * @param registrationStatusDto - * the registration status dto - * @param transactionType - * the transaction type - * @return the elapse status - */ - public String getElapseStatus(InternalRegistrationStatusDto registrationStatusDto, String transactionType) { - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", - "Utilities::getElapseStatus()::entry"); - - if (registrationStatusDto.getLatestTransactionTypeCode().equalsIgnoreCase(transactionType)) { - LocalDateTime createdDateTime = registrationStatusDto.getCreateDateTime(); - LocalDateTime currentDateTime = LocalDateTime.now(); - Duration duration = Duration.between(createdDateTime, currentDateTime); - long secondsDiffernce = duration.getSeconds(); - if (secondsDiffernce > elapseTime) { - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", - "Utilities::getElapseStatus()::exit and value is: " + RE_PROCESSING); - - return RE_PROCESSING; - } else { - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", - "Utilities::getElapseStatus()::exit and value is: " + HANDLER); - - return HANDLER; - } - } - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", - "Utilities::getElapseStatus()::exit and value is: " + NEW_PACKET); - - return NEW_PACKET; - } - - /** - * Gets the latest transaction id. - * - * @param registrationId - * the registration id - * @return the latest transaction id - */ - public String getLatestTransactionId(String registrationId, String process, int iteration, String workflowInstanceId) { - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - registrationId, "Utilities::getLatestTransactionId()::entry"); - RegistrationStatusEntity entity = registrationStatusDao.find(registrationId, process, iteration, workflowInstanceId); - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - registrationId, "Utilities::getLatestTransactionId()::exit"); - return entity != null ? entity.getLatestRegistrationTransactionId() : null; - - } - - /** - * retrieve UIN from IDRepo by registration id. - * - * @param regId - * the reg id - * @return the JSON object - * @throws ApisResourceAccessException - * the apis resource access exception - * @throws IdRepoAppException - * the id repo app exception - * @throws IOException - * Signals that an I/O exception has occurred. - */ - public JSONObject retrieveUIN(String regId) throws ApisResourceAccessException, IdRepoAppException, IOException { - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - regId, "Utilities::retrieveUIN()::entry"); - - if (regId != null) { - List pathSegments = new ArrayList<>(); - pathSegments.add(regId); - IdResponseDTO1 idResponseDto; - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - regId, "Utilities::retrieveUIN():: RETRIEVEIDENTITYFROMRID GET service call Started"); - - idResponseDto = (IdResponseDTO1) restClientService.getApi(ApiName.RETRIEVEIDENTITYFROMRID, pathSegments, "", - "", IdResponseDTO1.class); - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.UIN.toString(), "", - "Utilities::retrieveUIN():: RETRIEVEIDENTITYFROMRID GET service call ended successfully"); - - if (!idResponseDto.getErrors().isEmpty()) { - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), - LoggerFileConstant.REGISTRATIONID.toString(), regId, - "Utilities::retrieveUIN():: error with error message " - + PlatformErrorMessages.RPR_PVM_INVALID_UIN.getMessage() + " " - + idResponseDto.getErrors().toString()); - throw new IdRepoAppException( - PlatformErrorMessages.RPR_PVM_INVALID_UIN.getMessage() + idResponseDto.getErrors().toString()); - } - String response = objMapper.writeValueAsString(idResponseDto.getResponse().getIdentity()); - try { - return (JSONObject) new JSONParser().parse(response); - } catch (org.json.simple.parser.ParseException e) { - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.UIN.toString(), "", - ExceptionUtils.getStackTrace(e)); - throw new IdRepoAppException("Error while parsing string to JSONObject",e); - } - - } - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), "", - "Utilities::retrieveUIN()::exit regId is null"); - - return null; - } - - /** - * Calculate age. - * - * @param applicantDob - * the applicant dob - * @return the int - */ - private int calculateAge(String applicantDob) { - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), "", - "Utilities::calculateAge():: entry"); - - DateFormat sdf = new SimpleDateFormat(dobFormat); - Date birthDate = null; - try { - birthDate = sdf.parse(applicantDob); - - } catch (ParseException e) { - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - "", "Utilities::calculateAge():: error with error message " - + PlatformErrorMessages.RPR_SYS_PARSING_DATE_EXCEPTION.getMessage()); - throw new ParsingException(PlatformErrorMessages.RPR_SYS_PARSING_DATE_EXCEPTION.getCode(), e); - } - LocalDate ld = new java.sql.Date(birthDate.getTime()).toLocalDate(); - Period p = Period.between(ld, LocalDate.now()); - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), "", - "Utilities::calculateAge():: exit"); - - return p.getYears(); - - } - - /** - * Validate abis queue json and return value. - * - * @param jsonObject - * the json object - * @param key - * the key - * @return the string - */ - private String validateAbisQueueJsonAndReturnValue(JSONObject jsonObject, String key) { - - String value = JsonUtil.getJSONValue(jsonObject, key); - if (value == null) { - - throw new RegistrationProcessorUnCheckedException( - PlatformErrorMessages.ABIS_QUEUE_JSON_VALIDATION_FAILED.getCode(), - PlatformErrorMessages.ABIS_QUEUE_JSON_VALIDATION_FAILED.getMessage() + "::" + key); - } - - return value; - } - - /** - * Validate abis queue json and return long value. - * - * @param jsonObject - * the json object - * @param key - * the key - * @return the long value - */ - private int validateAbisQueueJsonAndReturnIntValue(JSONObject jsonObject, String key) { - - Integer value = JsonUtil.getJSONValue(jsonObject, key); - if (value == null) { - - throw new RegistrationProcessorUnCheckedException( - PlatformErrorMessages.ABIS_QUEUE_JSON_VALIDATION_FAILED.getCode(), - PlatformErrorMessages.ABIS_QUEUE_JSON_VALIDATION_FAILED.getMessage() + "::" + key); - } - - return value.intValue(); - } - - /** - * Gets the uin by vid. - * - * @param vid - * the vid - * @return the uin by vid - * @throws ApisResourceAccessException - * the apis resource access exception - * @throws VidCreationException - * the vid creation exception - */ - @SuppressWarnings("unchecked") - public String getUinByVid(String vid) throws ApisResourceAccessException, VidCreationException { - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), "", - "Utilities::getUinByVid():: entry"); - List pathSegments = new ArrayList<>(); - pathSegments.add(vid); - String uin = null; - VidResponseDTO response; - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), "", - "Stage::methodname():: RETRIEVEIUINBYVID GET service call Started"); - - response = (VidResponseDTO) restClientService.getApi(ApiName.GETUINBYVID, pathSegments, "", "", - VidResponseDTO.class); - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.UIN.toString(), "", - "Utilities::getUinByVid():: RETRIEVEIUINBYVID GET service call ended successfully"); - - if (!response.getErrors().isEmpty()) { - throw new VidCreationException(PlatformErrorMessages.RPR_PGS_VID_EXCEPTION.getMessage(), - "VID creation exception"); - - } else { - uin = response.getResponse().getUin(); - } - return uin; - } - - /** - * Retrieve idrepo json status. - * - * @param uin - * the uin - * @return the string - * @throws ApisResourceAccessException - * the apis resource access exception - * @throws IdRepoAppException - * the id repo app exception - */ - public String retrieveIdrepoJsonStatus(String uin) throws ApisResourceAccessException, IdRepoAppException { - String response = null; - if (uin != null) { - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.UIN.toString(), "", - "Utilities::retrieveIdrepoJson()::entry"); - List pathSegments = new ArrayList<>(); - pathSegments.add(uin); - IdResponseDTO1 idResponseDto; - - idResponseDto = (IdResponseDTO1) restClientService.getApi(ApiName.IDREPOGETIDBYUIN, pathSegments, "", "", - IdResponseDTO1.class); - if (idResponseDto == null) { - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.UIN.toString(), "", - "Utilities::retrieveIdrepoJson()::exit idResponseDto is null"); - return null; - } - if (!idResponseDto.getErrors().isEmpty()) { - List error = idResponseDto.getErrors(); - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.UIN.toString(), "", - "Utilities::retrieveIdrepoJson():: error with error message " + error.get(0).getMessage()); - throw new IdRepoAppException(error.get(0).getMessage()); - } - - response = idResponseDto.getResponse().getStatus(); - - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.UIN.toString(), "", - "Utilities::retrieveIdrepoJson():: IDREPOGETIDBYUIN GET service call ended Successfully"); - } - - return response; - } - - public String getRefId(String id, String refId) { - if (StringUtils.isNotEmpty(refId)) - return refId; - - String centerId = id.substring(0, centerIdLength); - String machineId = id.substring(centerIdLength, centerIdLength + machineIdLength); - return centerId + "_" + machineId; - } - +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.*; + +import io.mosip.kernel.core.util.exception.JsonProcessingException; +import io.mosip.registration.processor.core.exception.PacketManagerException; +import io.mosip.registration.processor.packet.manager.idreposervice.IdRepoService; +import io.mosip.registration.processor.packet.storage.dto.ConfigEnum; +import io.mosip.registration.processor.core.constant.ProviderStageName; +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.DateUtils; +import io.mosip.registration.processor.abis.queue.dto.AbisQueueDetails; +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.LoggerFileConstant; +import io.mosip.registration.processor.core.constant.MappingJsonConstants; +import io.mosip.registration.processor.core.exception.ApisResourceAccessException; +import io.mosip.registration.processor.core.exception.RegistrationProcessorCheckedException; +import io.mosip.registration.processor.core.exception.RegistrationProcessorUnCheckedException; +import io.mosip.registration.processor.core.exception.util.PlatformErrorMessages; +import io.mosip.registration.processor.core.idrepo.dto.IdRequestDto; +import io.mosip.registration.processor.core.idrepo.dto.IdResponseDTO; +import io.mosip.registration.processor.core.idrepo.dto.IdResponseDTO1; +import io.mosip.registration.processor.core.idrepo.dto.RequestDto; +import io.mosip.registration.processor.core.logger.RegProcessorLogger; +import io.mosip.registration.processor.core.packet.dto.Identity; +import io.mosip.registration.processor.core.packet.dto.vid.VidResponseDTO; +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.MosipQueueConnectionFactory; +import io.mosip.registration.processor.core.spi.restclient.RegistrationProcessorRestClientService; +import io.mosip.registration.processor.core.util.JsonUtil; +import io.mosip.registration.processor.packet.storage.dao.PacketInfoDao; +import io.mosip.registration.processor.packet.storage.dto.ApplicantInfoDto; +import io.mosip.registration.processor.packet.storage.exception.IdRepoAppException; +import io.mosip.registration.processor.packet.storage.exception.ParsingException; +import io.mosip.registration.processor.packet.storage.exception.QueueConnectionNotFound; +import io.mosip.registration.processor.packet.storage.exception.VidCreationException; +import io.mosip.registration.processor.status.dao.RegistrationStatusDao; +import io.mosip.registration.processor.status.dto.InternalRegistrationStatusDto; +import io.mosip.registration.processor.status.entity.RegistrationStatusEntity; +import lombok.Data; + +/** + * The Class Utilities. + * + * @author Girish Yarru + */ +@Component + +/** + * Instantiates a new utilities. + */ +@Data +public class Utilities { + /** The reg proc logger. */ + private static Logger regProcLogger = RegProcessorLogger.getLogger(Utilities.class); + private static final String SOURCE = "source"; + private static final String PROCESS = "process"; + private static final String PROVIDER = "provider"; + + private static Map readerConfiguration; + private static Map writerConfiguration; + + /** The Constant UIN. */ + private static final String UIN = "UIN"; + + /** The Constant FILE_SEPARATOR. */ + public static final String FILE_SEPARATOR = "\\"; + + /** The Constant RE_PROCESSING. */ + private static final String RE_PROCESSING = "re-processing"; + + /** The Constant HANDLER. */ + private static final String HANDLER = "handler"; + + /** The Constant NEW_PACKET. */ + private static final String NEW_PACKET = "New-packet"; + + @Value("${mosip.kernel.machineid.length}") + private int machineIdLength; + + @Value("${mosip.kernel.registrationcenterid.length}") + private int centerIdLength; + + @Autowired + private ObjectMapper objMapper; + + @Autowired + private IdRepoService idRepoService; + + + /** The rest client service. */ + @Autowired + private RegistrationProcessorRestClientService restClientService; + + /** The mosip connection factory. */ + @Autowired + private MosipQueueConnectionFactory mosipConnectionFactory; + + @Value("${provider.packetreader.mosip}") + private String provider; + + /** The config server file storage URL. */ + @Value("${config.server.file.storage.uri}") + private String configServerFileStorageURL; + + /** The get reg processor identity json. */ + @Value("${registration.processor.identityjson}") + private String getRegProcessorIdentityJson; + + /** The get reg processor demographic identity. */ + @Value("${registration.processor.demographic.identity}") + private String getRegProcessorDemographicIdentity; + + /** The get reg processor applicant type. */ + @Value("${registration.processor.applicant.type}") + private String getRegProcessorApplicantType; + + /** The dob format. */ + @Value("${registration.processor.applicant.dob.format}") + private String dobFormat; + + /** The elapse time. */ + @Value("${registration.processor.reprocess.elapse.time}") + private long elapseTime; + + /** The registration processor abis json. */ + @Value("${registration.processor.abis.json}") + private String registrationProcessorAbisJson; + + /** The id repo update. */ + @Value("${registration.processor.id.repo.update}") + private String idRepoUpdate; + + /** The vid version. */ + @Value("${registration.processor.id.repo.vidVersion}") + private String vidVersion; + + @Autowired + private PacketInfoDao packetInfoDao; + + @Autowired + private PriorityBasedPacketManagerService packetManagerService; + + /** The registration status dao. */ + @Autowired + private RegistrationStatusDao registrationStatusDao; + + /** The packet info manager. */ + @Autowired + private PacketInfoManager packetInfoManager; + + /** The Constant INBOUNDQUEUENAME. */ + private static final String INBOUNDQUEUENAME = "inboundQueueName"; + + /** The Constant OUTBOUNDQUEUENAME. */ + private static final String OUTBOUNDQUEUENAME = "outboundQueueName"; + + /** The Constant ABIS. */ + private static final String ABIS = "abis"; + + /** The Constant USERNAME. */ + private static final String USERNAME = "userName"; + + /** The Constant PASSWORD. */ + private static final String PASSWORD = "password"; + + /** The Constant BROKERURL. */ + private static final String BROKERURL = "brokerUrl"; + + /** The Constant TYPEOFQUEUE. */ + private static final String TYPEOFQUEUE = "typeOfQueue"; + + /** The Constant NAME. */ + private static final String NAME = "name"; + + /** The Constant NAME. */ + private static final String INBOUNDMESSAGETTL = "inboundMessageTTL"; + + /** The Constant FAIL_OVER. */ + private static final String FAIL_OVER = "failover:("; + + /** The Constant RANDOMIZE_FALSE. */ + private static final String RANDOMIZE_FALSE = ")?randomize=false"; + + private static final String VALUE = "value"; + + private JSONObject mappingJsonObject = null; + + private JSONObject regProcessorAbisJson = null; + + public static void initialize(Map reader, Map writer) { + readerConfiguration = reader; + writerConfiguration = writer; + } + + /** + * Gets the json. + * + * @param configServerFileStorageURL + * the config server file storage URL + * @param uri + * the uri + * @return the json + */ + public static String getJson(String configServerFileStorageURL, String uri) { + RestTemplate restTemplate = new RestTemplate(); + return restTemplate.getForObject(configServerFileStorageURL + uri, String.class); + } + + /** + * get applicant age by registration id. Checks the id json if dob or age + * present, if yes returns age if both dob or age are not present then retrieves + * age from id repo + * + * @param id + * the registration id + * @return the applicant age + * @throws IOException + * Signals that an I/O exception has occurred. + * @throws IOException + * Signals that an I/O exception has occurred. + * @throws ApisResourceAccessException + * the packet decryption failure exception + * @throws RegistrationProcessorCheckedException + */ + public int getApplicantAge(String id, String process, ProviderStageName stageName) throws IOException, + ApisResourceAccessException, JsonProcessingException, PacketManagerException { + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), + id, "Utilities::getApplicantAge()::entry"); + + String applicantDob = packetManagerService.getFieldByMappingJsonKey(id, MappingJsonConstants.DOB, process, stageName); + String applicantAge = packetManagerService.getFieldByMappingJsonKey(id, MappingJsonConstants.AGE, process, stageName); + if (applicantDob != null) { + return calculateAge(applicantDob); + } else if (applicantAge != null) { + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), + id, "Utilities::getApplicantAge()::exit when applicantAge is not null"); + return Integer.valueOf(applicantAge); + } else { + String uin = getUIn(id, process, stageName); + JSONObject identityJSONOject = retrieveIdrepoJson(uin); + JSONObject regProcessorIdentityJson = getRegistrationProcessorMappingJson(MappingJsonConstants.IDENTITY); + String ageKey = JsonUtil.getJSONValue(JsonUtil.getJSONObject(regProcessorIdentityJson, MappingJsonConstants.AGE), VALUE); + String dobKey = JsonUtil.getJSONValue(JsonUtil.getJSONObject(regProcessorIdentityJson, MappingJsonConstants.DOB), VALUE); + String idRepoApplicantDob = JsonUtil.getJSONValue(identityJSONOject, dobKey); + if (idRepoApplicantDob != null) { + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), + id, "Utilities::getApplicantAge()::exit when ID REPO applicantDob is not null"); + return calculateAge(idRepoApplicantDob); + } + Integer idRepoApplicantAge = JsonUtil.getJSONValue(identityJSONOject, ageKey); + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), + id, "Utilities::getApplicantAge()::exit when ID REPO applicantAge is not null"); + return idRepoApplicantAge != null ? idRepoApplicantAge : -1; + + } + + } + + public String getDefaultSource(String process, ConfigEnum config) { + Map configMap = null; + if (config.equals(ConfigEnum.READER)) + configMap = readerConfiguration; + else if (config.equals(ConfigEnum.WRITER)) + configMap = writerConfiguration; + + if (configMap != null) { + for (Map.Entry entry : configMap.entrySet()) { + String[] values = entry.getValue().split(","); + String source = null; + for (String val : values) { + if (val.startsWith("process:") && val.contains(process)) + for (String sVal : values) { + if (sVal.startsWith("source:")) { + source = sVal.replace("source:", ""); + return source; + } + } + } + } + } + return null; + } + + public String getSource(String packetSegment, String process, String field) throws IOException { + String source = null; + JSONObject jsonObject = getRegistrationProcessorMappingJson(packetSegment); + Object obj = field == null ? jsonObject.get(PROVIDER) : getField(jsonObject, field); + if (obj != null && obj instanceof ArrayList) { + List providerList = (List) obj; + for (String value : providerList) { + String[] values = value.split(","); + for (String provider : values) { + if (provider != null) { + if (provider.startsWith(PROCESS) && provider.contains(process)) { + for (String val : values) { + if (val.startsWith(SOURCE)) { + return val.replace(SOURCE + ":", "").trim(); + } + } + } + } + } + } + } + + return source; + } + + private Object getField(JSONObject jsonObject, String field) { + LinkedHashMap lm = (LinkedHashMap) jsonObject.get(field); + return lm.get(PROVIDER); + } + + + public String getSourceFromIdField(String packetSegment, String process, String idField) throws IOException { + JSONObject jsonObject = getRegistrationProcessorMappingJson(packetSegment); + for (Object key : jsonObject.keySet()) { + LinkedHashMap hMap = (LinkedHashMap) jsonObject.get(key); + String value = (String) hMap.get(VALUE); + if (value != null && value.contains(idField)) { + return getSource(packetSegment, process, key.toString()); + } + } + return null; + } + + /** + * retrieving identity json ffrom id repo by UIN. + * + * @param uin + * the uin + * @return the JSON object + * @throws ApisResourceAccessException + * the apis resource access exception + * @throws IdRepoAppException + * the id repo app exception + * @throws IOException + * Signals that an I/O exception has occurred. + */ + public JSONObject retrieveIdrepoJson(String uin) throws ApisResourceAccessException, IdRepoAppException, IOException { + + if (uin != null) { + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.UIN.toString(), "", + "Utilities::retrieveIdrepoJson()::entry"); + List pathSegments = new ArrayList<>(); + pathSegments.add(uin); + IdResponseDTO1 idResponseDto; + + idResponseDto = (IdResponseDTO1) restClientService.getApi(ApiName.IDREPOGETIDBYUIN, pathSegments, "", "", + IdResponseDTO1.class); + if (idResponseDto == null) { + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.UIN.toString(), "", + "Utilities::retrieveIdrepoJson()::exit idResponseDto is null"); + return null; + } + if (!idResponseDto.getErrors().isEmpty()) { + List error = idResponseDto.getErrors(); + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.UIN.toString(), "", + "Utilities::retrieveIdrepoJson():: error with error message " + error.get(0).getMessage()); + throw new IdRepoAppException(error.get(0).getMessage()); + } + String response = objMapper.writeValueAsString(idResponseDto.getResponse().getIdentity()); + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.UIN.toString(), "", + "Utilities::retrieveIdrepoJson():: IDREPOGETIDBYUIN GET service call ended Successfully"); + try { + return (JSONObject) new JSONParser().parse(response); + } catch (org.json.simple.parser.ParseException e) { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.UIN.toString(), "", + ExceptionUtils.getStackTrace(e)); + throw new IdRepoAppException("Error while parsing string to JSONObject",e); + } + + + } + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.UIN.toString(), "", + "Utilities::retrieveIdrepoJson()::exit UIN is null"); + return null; + } + + /** + * Check if uin is present in idrepo + * @param uin + * @return + * @throws ApisResourceAccessException + * @throws IOException + */ + public boolean uinPresentInIdRepo(String uin) throws ApisResourceAccessException, IOException { + return idRepoService.findUinFromIdrepo(uin, getGetRegProcessorDemographicIdentity()) != null; + } + + /** + * Check if uin is missing from Id + * @param errorCode + * @param id + * @param idType + * @return + */ + public boolean isUinMissingFromIdAuth(String errorCode, String id, String idType) { + if (errorCode.equalsIgnoreCase("IDA-MLC-018") && + idType != null && idType.equalsIgnoreCase("UIN")) { + try { + return uinPresentInIdRepo(id); + } catch (IOException | ApisResourceAccessException exception) { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.UIN.toString(), "", + ExceptionUtils.getStackTrace(exception)); + // in case of exception return true so that the request is marked for reprocess + return true; + } + } + return false; + } + + /** + * Returns all the list of queue details(inbound/outbound address,name,url,pwd) + * from abisJson Also validates the abis json fileds(null or not). + * + * @return the abis queue details + * @throws RegistrationProcessorCheckedException + * the registration processor checked exception + */ + public List getAbisQueueDetails() throws RegistrationProcessorCheckedException { + List abisQueueDetailsList = new ArrayList<>(); + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", + "Utilities::getAbisQueueDetails()::entry"); + + try { + if(regProcessorAbisJson==null) { + String registrationProcessorAbis = Utilities.getJson(configServerFileStorageURL, registrationProcessorAbisJson); + regProcessorAbisJson = JsonUtil.objectMapperReadValue(registrationProcessorAbis, JSONObject.class); + } + JSONArray regProcessorAbisArray = JsonUtil.getJSONArray(regProcessorAbisJson, ABIS); + + for (Object jsonObject : regProcessorAbisArray) { + AbisQueueDetails abisQueueDetails = new AbisQueueDetails(); + JSONObject json = new JSONObject((Map) jsonObject); + String userName = validateAbisQueueJsonAndReturnValue(json, USERNAME); + String password = validateAbisQueueJsonAndReturnValue(json, PASSWORD); + String brokerUrl = validateAbisQueueJsonAndReturnValue(json, BROKERURL); + String failOverBrokerUrl = FAIL_OVER + brokerUrl + "," + brokerUrl + RANDOMIZE_FALSE; + String typeOfQueue = validateAbisQueueJsonAndReturnValue(json, TYPEOFQUEUE); + String inboundQueueName = validateAbisQueueJsonAndReturnValue(json, INBOUNDQUEUENAME); + String outboundQueueName = validateAbisQueueJsonAndReturnValue(json, OUTBOUNDQUEUENAME); + String queueName = validateAbisQueueJsonAndReturnValue(json, NAME); + int inboundMessageTTL = validateAbisQueueJsonAndReturnIntValue(json, INBOUNDMESSAGETTL); + MosipQueue mosipQueue = mosipConnectionFactory.createConnection(typeOfQueue, userName, password, + failOverBrokerUrl); + if (mosipQueue == null) + throw new QueueConnectionNotFound( + PlatformErrorMessages.RPR_PIS_ABIS_QUEUE_CONNECTION_NULL.getMessage()); + + abisQueueDetails.setMosipQueue(mosipQueue); + abisQueueDetails.setInboundQueueName(inboundQueueName); + abisQueueDetails.setOutboundQueueName(outboundQueueName); + abisQueueDetails.setName(queueName); + abisQueueDetails.setInboundMessageTTL(inboundMessageTTL); + abisQueueDetailsList.add(abisQueueDetails); + + } + } catch (IOException e) { + throw new RegistrationProcessorCheckedException(PlatformErrorMessages.RPR_SYS_IO_EXCEPTION.getCode(), + PlatformErrorMessages.RPR_SYS_IO_EXCEPTION.getMessage(), e); + } + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", + "Utilities::getAbisQueueDetails()::exit"); + + return abisQueueDetailsList; + + } + + /** + * Gets registration processor mapping json from config and maps to + * RegistrationProcessorIdentity java class. + * + * @return the registration processor identity json + * @throws IOException + * Signals that an I/O exception has occurred. + */ + public JSONObject getRegistrationProcessorMappingJson(String packetSegment) throws IOException { + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", + "Utilities::getRegistrationProcessorMappingJson()::entry"); + + if (mappingJsonObject == null) { + String mappingJsonString = Utilities.getJson(configServerFileStorageURL, getRegProcessorIdentityJson); + mappingJsonObject = objMapper.readValue(mappingJsonString, JSONObject.class); + + } + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", + "Utilities::getRegistrationProcessorMappingJson()::exit"); + return JsonUtil.getJSONObject(mappingJsonObject, packetSegment); + + } + + public String getMappingJsonValue(String key, String packetSegment) throws IOException { + JSONObject jsonObject = getRegistrationProcessorMappingJson(packetSegment); + Object obj = jsonObject.get(key); + if (obj instanceof LinkedHashMap) { + LinkedHashMap hm = (LinkedHashMap) obj; + return hm.get("value") != null ? hm.get("value").toString() : null; + } + return jsonObject.get(key) != null ? jsonObject.get(key).toString() : null; + + } + + /** + * Get UIN from identity json (used only for update/res update/activate/de + * activate packets). + * + * @param id + * the registration id + * @return the u in + * @throws IOException + * Signals that an I/O exception has occurred. + * @throws IOException + * Signals that an I/O exception has occurred. + * @throws ApisResourceAccessException + * the apis resource access exception + * @throws RegistrationProcessorCheckedException + */ + public String getUIn(String id, String process, ProviderStageName stageName) throws IOException, ApisResourceAccessException, PacketManagerException, JsonProcessingException { + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + id, "Utilities::getUIn()::entry"); + String UIN = packetManagerService.getFieldByMappingJsonKey(id, MappingJsonConstants.UIN, process, stageName); + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + id, "Utilities::getUIn()::exit"); + + return UIN; + + } + + /** + * Gets the elapse status. + * + * @param registrationStatusDto + * the registration status dto + * @param transactionType + * the transaction type + * @return the elapse status + */ + public String getElapseStatus(InternalRegistrationStatusDto registrationStatusDto, String transactionType) { + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", + "Utilities::getElapseStatus()::entry"); + + if (registrationStatusDto.getLatestTransactionTypeCode().equalsIgnoreCase(transactionType)) { + LocalDateTime createdDateTime = registrationStatusDto.getCreateDateTime(); + LocalDateTime currentDateTime = LocalDateTime.now(); + Duration duration = Duration.between(createdDateTime, currentDateTime); + long secondsDiffernce = duration.getSeconds(); + if (secondsDiffernce > elapseTime) { + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", + "Utilities::getElapseStatus()::exit and value is: " + RE_PROCESSING); + + return RE_PROCESSING; + } else { + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", + "Utilities::getElapseStatus()::exit and value is: " + HANDLER); + + return HANDLER; + } + } + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", + "Utilities::getElapseStatus()::exit and value is: " + NEW_PACKET); + + return NEW_PACKET; + } + + /** + * Gets the latest transaction id. + * + * @param registrationId + * the registration id + * @return the latest transaction id + */ + public String getLatestTransactionId(String registrationId, String process, int iteration, String workflowInstanceId) { + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + registrationId, "Utilities::getLatestTransactionId()::entry"); + RegistrationStatusEntity entity = registrationStatusDao.find(registrationId, process, iteration, workflowInstanceId); + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + registrationId, "Utilities::getLatestTransactionId()::exit"); + return entity != null ? entity.getLatestRegistrationTransactionId() : null; + + } + + /** + * retrieve UIN from IDRepo by registration id. + * + * @param regId + * the reg id + * @return the JSON object + * @throws ApisResourceAccessException + * the apis resource access exception + * @throws IdRepoAppException + * the id repo app exception + * @throws IOException + * Signals that an I/O exception has occurred. + */ + public JSONObject retrieveUIN(String regId) throws ApisResourceAccessException, IdRepoAppException, IOException { + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + regId, "Utilities::retrieveUIN()::entry"); + + if (regId != null) { + List pathSegments = new ArrayList<>(); + pathSegments.add(regId); + IdResponseDTO1 idResponseDto; + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + regId, "Utilities::retrieveUIN():: RETRIEVEIDENTITYFROMRID GET service call Started"); + + idResponseDto = (IdResponseDTO1) restClientService.getApi(ApiName.RETRIEVEIDENTITYFROMRID, pathSegments, "", + "", IdResponseDTO1.class); + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.UIN.toString(), "", + "Utilities::retrieveUIN():: RETRIEVEIDENTITYFROMRID GET service call ended successfully"); + + if (!idResponseDto.getErrors().isEmpty()) { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString(), regId, + "Utilities::retrieveUIN():: error with error message " + + PlatformErrorMessages.RPR_PVM_INVALID_UIN.getMessage() + " " + + idResponseDto.getErrors().toString()); + throw new IdRepoAppException( + PlatformErrorMessages.RPR_PVM_INVALID_UIN.getMessage() + idResponseDto.getErrors().toString()); + } + String response = objMapper.writeValueAsString(idResponseDto.getResponse().getIdentity()); + try { + return (JSONObject) new JSONParser().parse(response); + } catch (org.json.simple.parser.ParseException e) { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.UIN.toString(), "", + ExceptionUtils.getStackTrace(e)); + throw new IdRepoAppException("Error while parsing string to JSONObject",e); + } + + } + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), "", + "Utilities::retrieveUIN()::exit regId is null"); + + return null; + } + + /** + * Calculate age. + * + * @param applicantDob + * the applicant dob + * @return the int + */ + private int calculateAge(String applicantDob) { + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), "", + "Utilities::calculateAge():: entry"); + + DateFormat sdf = new SimpleDateFormat(dobFormat); + Date birthDate = null; + try { + birthDate = sdf.parse(applicantDob); + + } catch (ParseException e) { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + "", "Utilities::calculateAge():: error with error message " + + PlatformErrorMessages.RPR_SYS_PARSING_DATE_EXCEPTION.getMessage()); + throw new ParsingException(PlatformErrorMessages.RPR_SYS_PARSING_DATE_EXCEPTION.getCode(), e); + } + LocalDate ld = new java.sql.Date(birthDate.getTime()).toLocalDate(); + Period p = Period.between(ld, LocalDate.now()); + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), "", + "Utilities::calculateAge():: exit"); + + return p.getYears(); + + } + + /** + * Validate abis queue json and return value. + * + * @param jsonObject + * the json object + * @param key + * the key + * @return the string + */ + private String validateAbisQueueJsonAndReturnValue(JSONObject jsonObject, String key) { + + String value = JsonUtil.getJSONValue(jsonObject, key); + if (value == null) { + + throw new RegistrationProcessorUnCheckedException( + PlatformErrorMessages.ABIS_QUEUE_JSON_VALIDATION_FAILED.getCode(), + PlatformErrorMessages.ABIS_QUEUE_JSON_VALIDATION_FAILED.getMessage() + "::" + key); + } + + return value; + } + + /** + * Validate abis queue json and return long value. + * + * @param jsonObject + * the json object + * @param key + * the key + * @return the long value + */ + private int validateAbisQueueJsonAndReturnIntValue(JSONObject jsonObject, String key) { + + Integer value = JsonUtil.getJSONValue(jsonObject, key); + if (value == null) { + + throw new RegistrationProcessorUnCheckedException( + PlatformErrorMessages.ABIS_QUEUE_JSON_VALIDATION_FAILED.getCode(), + PlatformErrorMessages.ABIS_QUEUE_JSON_VALIDATION_FAILED.getMessage() + "::" + key); + } + + return value.intValue(); + } + + /** + * Gets the uin by vid. + * + * @param vid + * the vid + * @return the uin by vid + * @throws ApisResourceAccessException + * the apis resource access exception + * @throws VidCreationException + * the vid creation exception + */ + @SuppressWarnings("unchecked") + public String getUinByVid(String vid) throws ApisResourceAccessException, VidCreationException { + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), "", + "Utilities::getUinByVid():: entry"); + List pathSegments = new ArrayList<>(); + pathSegments.add(vid); + String uin = null; + VidResponseDTO response; + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), "", + "Stage::methodname():: RETRIEVEIUINBYVID GET service call Started"); + + response = (VidResponseDTO) restClientService.getApi(ApiName.GETUINBYVID, pathSegments, "", "", + VidResponseDTO.class); + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.UIN.toString(), "", + "Utilities::getUinByVid():: RETRIEVEIUINBYVID GET service call ended successfully"); + + if (!response.getErrors().isEmpty()) { + throw new VidCreationException(PlatformErrorMessages.RPR_PGS_VID_EXCEPTION.getMessage(), + "VID creation exception"); + + } else { + uin = response.getResponse().getUin(); + } + return uin; + } + + /** + * Retrieve idrepo json status. + * + * @param uin + * the uin + * @return the string + * @throws ApisResourceAccessException + * the apis resource access exception + * @throws IdRepoAppException + * the id repo app exception + */ + public String retrieveIdrepoJsonStatus(String uin) throws ApisResourceAccessException, IdRepoAppException { + String response = null; + if (uin != null) { + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.UIN.toString(), "", + "Utilities::retrieveIdrepoJson()::entry"); + List pathSegments = new ArrayList<>(); + pathSegments.add(uin); + IdResponseDTO1 idResponseDto; + + idResponseDto = (IdResponseDTO1) restClientService.getApi(ApiName.IDREPOGETIDBYUIN, pathSegments, "", "", + IdResponseDTO1.class); + if (idResponseDto == null) { + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.UIN.toString(), "", + "Utilities::retrieveIdrepoJson()::exit idResponseDto is null"); + return null; + } + if (!idResponseDto.getErrors().isEmpty()) { + List error = idResponseDto.getErrors(); + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.UIN.toString(), "", + "Utilities::retrieveIdrepoJson():: error with error message " + error.get(0).getMessage()); + throw new IdRepoAppException(error.get(0).getMessage()); + } + + response = idResponseDto.getResponse().getStatus(); + + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.UIN.toString(), "", + "Utilities::retrieveIdrepoJson():: IDREPOGETIDBYUIN GET service call ended Successfully"); + } + + return response; + } + + public String getRefId(String id, String refId) { + if (StringUtils.isNotEmpty(refId)) + return refId; + + String centerId = id.substring(0, centerIdLength); + String machineId = id.substring(centerIdLength, centerIdLength + machineIdLength); + return centerId + "_" + machineId; + } + } \ No newline at end of file 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 0e1f79aa780..e6ac5d78e70 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 @@ -161,6 +161,10 @@ public class MessageNotificationServiceImpl @Autowired private ObjectMapper mapper; + + private List mapperJsonKeys = null; + + private JSONObject mapperIdentity=null; /* * (non-Javadoc) @@ -535,13 +539,16 @@ private Map setAttributes(String idJsonString, Map mapperJsonKeys = new ArrayList<>(mapperIdentity.keySet()); + mapperJsonKeys = new ArrayList<>(mapperIdentity.keySet()); + } + + for (String key : mapperJsonKeys) { JSONObject jsonValue = JsonUtil.getJSONObject(mapperIdentity, key); if (jsonValue.get(VALUE) != null && !jsonValue.get(VALUE).toString().isBlank()) { From 48e1e04bd737b3398c30199a225b73804a778983 Mon Sep 17 00:00:00 2001 From: Sowmya Ujjappa Banakar Date: Tue, 28 Mar 2023 14:59:51 +0530 Subject: [PATCH 061/133] MOSIP-26444 code changes --- ...sMiddlewareAppConfigurationsValidator.java | 128 +- ...erificationAppConfigurationsValidator.java | 96 +- ...erificationAppConfigurationsValidator.java | 96 +- ...erificationAppConfigurationsValidator.java | 96 +- .../api/config/RegistrationStatusConfig.java | 6 +- .../MosipStageExecutorApplication.java | 167 +-- .../executor/util/StageClassesUtil.java | 7 +- .../transaction/api/config/SwaggerConfig.java | 132 +-- .../StageHealthCheckHandler.java | 1052 ++++++++--------- .../core/eventbus/KafkaMosipEventBus.java | 6 +- .../core/eventbus/VertxMosipEventBus.java | 7 +- .../core/logger/RegProcessorLogger.java | 27 +- .../processor/core/util/ServerUtil.java | 6 +- .../PacketInfoStorageExceptionHandler.java | 6 +- .../audit/builder/AuditLogRequestBuilder.java | 6 +- 15 files changed, 932 insertions(+), 906 deletions(-) diff --git a/registration-processor/core-processor/registration-processor-abis-middleware-stage/src/main/java/io/mosip/registartion/processor/abis/middleware/validators/AbisMiddlewareAppConfigurationsValidator.java b/registration-processor/core-processor/registration-processor-abis-middleware-stage/src/main/java/io/mosip/registartion/processor/abis/middleware/validators/AbisMiddlewareAppConfigurationsValidator.java index 50bd72ab943..ebc0e7a40cb 100644 --- a/registration-processor/core-processor/registration-processor-abis-middleware-stage/src/main/java/io/mosip/registartion/processor/abis/middleware/validators/AbisMiddlewareAppConfigurationsValidator.java +++ b/registration-processor/core-processor/registration-processor-abis-middleware-stage/src/main/java/io/mosip/registartion/processor/abis/middleware/validators/AbisMiddlewareAppConfigurationsValidator.java @@ -1,64 +1,64 @@ -package io.mosip.registartion.processor.abis.middleware.validators; - -import org.springframework.context.event.ContextRefreshedEvent; -import org.springframework.context.event.EventListener; -import org.springframework.stereotype.Component; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.slf4j.LoggerFactory; -import org.slf4j.Logger; -import java.util.List; - -import io.mosip.registration.processor.abis.queue.dto.AbisQueueDetails; -import io.mosip.registration.processor.core.exception.RegistrationProcessorCheckedException; -import io.mosip.registration.processor.packet.storage.utils.Utilities; - -/** - * All the configuration validations will be done in this class - */ -@Component -public class AbisMiddlewareAppConfigurationsValidator { - - private static final Logger logger = LoggerFactory.getLogger(AbisMiddlewareAppConfigurationsValidator.class); - - /** - * This configuration will be used by reprocessor stage to reprocess the events - */ - @Value("${registration.processor.reprocess.elapse.time}") - private long reprocessorElapseTime; - - - @Value("${registration.processor.bio.dedupe.reprocess.buffer.time}") - private long reprocessBufferTime; - - @Autowired - private Utilities utility; - - /** - * The below method will be called by spring once the context is initialized or refreshed - * @param event Context refreshed event - */ - @EventListener - public void validateConfigurations(ContextRefreshedEvent event) { - logger.info("ContextRefreshedEvent received"); - validateReprocessElapseTimeConfig(); - } - - private void validateReprocessElapseTimeConfig() { - try { - List abisQueueDetails = utility.getAbisQueueDetails(); - long allowedReprocessTime = reprocessBufferTime; - for(AbisQueueDetails abisQueueDetail : abisQueueDetails) { - //TTL is multiplied by 2 to compute both Insert and Identify request expiry time - allowedReprocessTime += (abisQueueDetail.getInboundMessageTTL() * 2); - } - if(reprocessorElapseTime <= allowedReprocessTime) { - logger.warn("registration.processor.reprocess.elapse.time config {} is invalid," + - " it should should be greater than all the queue expiry put together with an" + - " additional buffer {}", reprocessorElapseTime, allowedReprocessTime); - } - } catch (RegistrationProcessorCheckedException e) { - logger.error("Abis queue details invalid", e); - } - } -} +package io.mosip.registartion.processor.abis.middleware.validators; + +import org.springframework.context.event.ContextRefreshedEvent; +import org.springframework.context.event.EventListener; +import org.springframework.stereotype.Component; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import io.mosip.registration.processor.core.logger.RegProcessorLogger; +import io.mosip.kernel.core.logger.spi.Logger; +import java.util.List; + +import io.mosip.registration.processor.abis.queue.dto.AbisQueueDetails; +import io.mosip.registration.processor.core.exception.RegistrationProcessorCheckedException; +import io.mosip.registration.processor.packet.storage.utils.Utilities; + +/** + * All the configuration validations will be done in this class + */ +@Component +public class AbisMiddlewareAppConfigurationsValidator { + + private static final Logger logger = RegProcessorLogger.getLogger(AbisMiddlewareAppConfigurationsValidator.class); + + /** + * This configuration will be used by reprocessor stage to reprocess the events + */ + @Value("${registration.processor.reprocess.elapse.time}") + private long reprocessorElapseTime; + + + @Value("${registration.processor.bio.dedupe.reprocess.buffer.time}") + private long reprocessBufferTime; + + @Autowired + private Utilities utility; + + /** + * The below method will be called by spring once the context is initialized or refreshed + * @param event Context refreshed event + */ + @EventListener + public void validateConfigurations(ContextRefreshedEvent event) { + logger.info("ContextRefreshedEvent received"); + validateReprocessElapseTimeConfig(); + } + + private void validateReprocessElapseTimeConfig() { + try { + List abisQueueDetails = utility.getAbisQueueDetails(); + long allowedReprocessTime = reprocessBufferTime; + for(AbisQueueDetails abisQueueDetail : abisQueueDetails) { + //TTL is multiplied by 2 to compute both Insert and Identify request expiry time + allowedReprocessTime += (abisQueueDetail.getInboundMessageTTL() * 2); + } + if(reprocessorElapseTime <= allowedReprocessTime) { + logger.warn("registration.processor.reprocess.elapse.time config {} is invalid," + + " it should should be greater than all the queue expiry put together with an" + + " additional buffer {}", reprocessorElapseTime, allowedReprocessTime); + } + } catch (RegistrationProcessorCheckedException e) { + logger.error("Abis queue details invalid", e); + } + } +} diff --git a/registration-processor/core-processor/registration-processor-manual-adjudication-stage/src/main/java/io/mosip/registration/processor/adjudication/validators/ManualVerificationAppConfigurationsValidator.java b/registration-processor/core-processor/registration-processor-manual-adjudication-stage/src/main/java/io/mosip/registration/processor/adjudication/validators/ManualVerificationAppConfigurationsValidator.java index 8365fe11c1c..04049714a14 100644 --- a/registration-processor/core-processor/registration-processor-manual-adjudication-stage/src/main/java/io/mosip/registration/processor/adjudication/validators/ManualVerificationAppConfigurationsValidator.java +++ b/registration-processor/core-processor/registration-processor-manual-adjudication-stage/src/main/java/io/mosip/registration/processor/adjudication/validators/ManualVerificationAppConfigurationsValidator.java @@ -1,48 +1,48 @@ -package io.mosip.registration.processor.adjudication.validators; - -import org.springframework.context.event.ContextRefreshedEvent; -import org.springframework.context.event.EventListener; -import org.springframework.stereotype.Component; -import org.springframework.beans.factory.annotation.Value; -import org.slf4j.LoggerFactory; -import org.slf4j.Logger; - -/** - * All the configuration validations will be done in this class - */ -@Component -public class ManualVerificationAppConfigurationsValidator { - - private static final Logger logger = LoggerFactory.getLogger(ManualVerificationAppConfigurationsValidator.class); - - /** - * This configuration will be used by reprocessor stage to reprocess the events - */ - @Value("${registration.processor.reprocess.elapse.time}") - private long reprocessorElapseTime; - - @Value("${registration.processor.queue.manual.adjudication.request.messageTTL}") - private int mvRequestMessageTTL; - - @Value("${registration.processor.manual.adjudication.reprocess.buffer.time}") - private long reprocessBufferTime; - - /** - * The below method will be called by spring once the context is initialized or refreshed - * @param event Context refreshed event - */ - @EventListener - public void validateConfigurations(ContextRefreshedEvent event) { - logger.info("ContextRefreshedEvent received"); - validateReprocessElapseTimeConfig(); - } - - private void validateReprocessElapseTimeConfig() { - long allowedReprocessTime = mvRequestMessageTTL + reprocessBufferTime; - if(reprocessorElapseTime <= allowedReprocessTime) { - logger.warn("registration.processor.reprocess.elapse.time config {} is invalid," + - " it should should be greater than the queue expiry with an" + - " additional buffer {}", reprocessorElapseTime, allowedReprocessTime); - } - } -} +package io.mosip.registration.processor.adjudication.validators; + +import org.springframework.context.event.ContextRefreshedEvent; +import org.springframework.context.event.EventListener; +import org.springframework.stereotype.Component; +import org.springframework.beans.factory.annotation.Value; +import io.mosip.registration.processor.core.logger.RegProcessorLogger; +import io.mosip.kernel.core.logger.spi.Logger; + +/** + * All the configuration validations will be done in this class + */ +@Component +public class ManualVerificationAppConfigurationsValidator { + + private static final Logger logger = RegProcessorLogger.getLogger(ManualVerificationAppConfigurationsValidator.class); + + /** + * This configuration will be used by reprocessor stage to reprocess the events + */ + @Value("${registration.processor.reprocess.elapse.time}") + private long reprocessorElapseTime; + + @Value("${registration.processor.queue.manual.adjudication.request.messageTTL}") + private int mvRequestMessageTTL; + + @Value("${registration.processor.manual.adjudication.reprocess.buffer.time}") + private long reprocessBufferTime; + + /** + * The below method will be called by spring once the context is initialized or refreshed + * @param event Context refreshed event + */ + @EventListener + public void validateConfigurations(ContextRefreshedEvent event) { + logger.info("ContextRefreshedEvent received"); + validateReprocessElapseTimeConfig(); + } + + private void validateReprocessElapseTimeConfig() { + long allowedReprocessTime = mvRequestMessageTTL + reprocessBufferTime; + if(reprocessorElapseTime <= allowedReprocessTime) { + logger.warn("registration.processor.reprocess.elapse.time config {} is invalid," + + " it should should be greater than the queue expiry with an" + + " additional buffer {}", reprocessorElapseTime, allowedReprocessTime); + } + } +} diff --git a/registration-processor/core-processor/registration-processor-verification-stage/src/main/java/io/mosip/registration/processor/verification/validators/ManualVerificationAppConfigurationsValidator.java b/registration-processor/core-processor/registration-processor-verification-stage/src/main/java/io/mosip/registration/processor/verification/validators/ManualVerificationAppConfigurationsValidator.java index 5249dfaa5e3..d5961bea7d5 100644 --- a/registration-processor/core-processor/registration-processor-verification-stage/src/main/java/io/mosip/registration/processor/verification/validators/ManualVerificationAppConfigurationsValidator.java +++ b/registration-processor/core-processor/registration-processor-verification-stage/src/main/java/io/mosip/registration/processor/verification/validators/ManualVerificationAppConfigurationsValidator.java @@ -1,48 +1,48 @@ -package io.mosip.registration.processor.verification.validators; - -import org.springframework.context.event.ContextRefreshedEvent; -import org.springframework.context.event.EventListener; -import org.springframework.stereotype.Component; -import org.springframework.beans.factory.annotation.Value; -import org.slf4j.LoggerFactory; -import org.slf4j.Logger; - -/** - * All the configuration validations will be done in this class - */ -@Component -public class ManualVerificationAppConfigurationsValidator { - - private static final Logger logger = LoggerFactory.getLogger(ManualVerificationAppConfigurationsValidator.class); - - /** - * This configuration will be used by reprocessor stage to reprocess the events - */ - @Value("${registration.processor.reprocess.elapse.time}") - private long reprocessorElapseTime; - - @Value("${registration.processor.queue.verification.request.messageTTL}") - private int mvRequestMessageTTL; - - @Value("${registration.processor.verification.reprocess.buffer.time:900}") - private long reprocessBufferTime; - - /** - * The below method will be called by spring once the context is initialized or refreshed - * @param event Context refreshed event - */ - @EventListener - public void validateConfigurations(ContextRefreshedEvent event) { - logger.info("ContextRefreshedEvent received"); - validateReprocessElapseTimeConfig(); - } - - private void validateReprocessElapseTimeConfig() { - long allowedReprocessTime = mvRequestMessageTTL + reprocessBufferTime; - if(reprocessorElapseTime <= allowedReprocessTime) { - logger.warn("registration.processor.reprocess.elapse.time config {} is invalid," + - " it should should be greater than the queue expiry with an" + - " additional buffer {}", reprocessorElapseTime, allowedReprocessTime); - } - } -} +package io.mosip.registration.processor.verification.validators; + +import org.springframework.context.event.ContextRefreshedEvent; +import org.springframework.context.event.EventListener; +import org.springframework.stereotype.Component; +import org.springframework.beans.factory.annotation.Value; +import io.mosip.registration.processor.core.logger.RegProcessorLogger; +import io.mosip.kernel.core.logger.spi.Logger; + +/** + * All the configuration validations will be done in this class + */ +@Component +public class ManualVerificationAppConfigurationsValidator { + + private static final Logger logger = RegProcessorLogger.getLogger(ManualVerificationAppConfigurationsValidator.class); + + /** + * This configuration will be used by reprocessor stage to reprocess the events + */ + @Value("${registration.processor.reprocess.elapse.time}") + private long reprocessorElapseTime; + + @Value("${registration.processor.queue.verification.request.messageTTL}") + private int mvRequestMessageTTL; + + @Value("${registration.processor.verification.reprocess.buffer.time:900}") + private long reprocessBufferTime; + + /** + * The below method will be called by spring once the context is initialized or refreshed + * @param event Context refreshed event + */ + @EventListener + public void validateConfigurations(ContextRefreshedEvent event) { + logger.info("ContextRefreshedEvent received"); + validateReprocessElapseTimeConfig(); + } + + private void validateReprocessElapseTimeConfig() { + long allowedReprocessTime = mvRequestMessageTTL + reprocessBufferTime; + if(reprocessorElapseTime <= allowedReprocessTime) { + logger.warn("registration.processor.reprocess.elapse.time config {} is invalid," + + " it should should be greater than the queue expiry with an" + + " additional buffer {}", reprocessorElapseTime, allowedReprocessTime); + } + } +} diff --git a/registration-processor/core-processor/registration-processor-verification-stage/src/main/java/io/mosip/registration/processor/verification/validators/VerificationAppConfigurationsValidator.java b/registration-processor/core-processor/registration-processor-verification-stage/src/main/java/io/mosip/registration/processor/verification/validators/VerificationAppConfigurationsValidator.java index 5e267d73022..f21ca1e7fe7 100644 --- a/registration-processor/core-processor/registration-processor-verification-stage/src/main/java/io/mosip/registration/processor/verification/validators/VerificationAppConfigurationsValidator.java +++ b/registration-processor/core-processor/registration-processor-verification-stage/src/main/java/io/mosip/registration/processor/verification/validators/VerificationAppConfigurationsValidator.java @@ -1,48 +1,48 @@ -package io.mosip.registration.processor.verification.validators; - -import org.springframework.context.event.ContextRefreshedEvent; -import org.springframework.context.event.EventListener; -import org.springframework.stereotype.Component; -import org.springframework.beans.factory.annotation.Value; -import org.slf4j.LoggerFactory; -import org.slf4j.Logger; - -/** - * All the configuration validations will be done in this class - */ -@Component -public class VerificationAppConfigurationsValidator { - - private static final Logger logger = LoggerFactory.getLogger(VerificationAppConfigurationsValidator.class); - - /** - * This configuration will be used by reprocessor stage to reprocess the events - */ - @Value("${registration.processor.reprocess.elapse.time}") - private long reprocessorElapseTime; - - @Value("${registration.processor.queue.verification.request.messageTTL}") - private int mvRequestMessageTTL; - - @Value("${registration.processor.verification.reprocess.buffer.time:900}") - private long reprocessBufferTime; - - /** - * The below method will be called by spring once the context is initialized or refreshed - * @param event Context refreshed event - */ - @EventListener - public void validateConfigurations(ContextRefreshedEvent event) { - logger.info("ContextRefreshedEvent received"); - validateReprocessElapseTimeConfig(); - } - - private void validateReprocessElapseTimeConfig() { - long allowedReprocessTime = mvRequestMessageTTL + reprocessBufferTime; - if(reprocessorElapseTime <= allowedReprocessTime) { - logger.warn("registration.processor.reprocess.elapse.time config {} is invalid," + - " it should should be greater than the queue expiry with an" + - " additional buffer {}", reprocessorElapseTime, allowedReprocessTime); - } - } -} +package io.mosip.registration.processor.verification.validators; + +import org.springframework.context.event.ContextRefreshedEvent; +import org.springframework.context.event.EventListener; +import org.springframework.stereotype.Component; +import org.springframework.beans.factory.annotation.Value; +import io.mosip.registration.processor.core.logger.RegProcessorLogger; +import io.mosip.kernel.core.logger.spi.Logger; + +/** + * All the configuration validations will be done in this class + */ +@Component +public class VerificationAppConfigurationsValidator { + + private static final Logger logger = RegProcessorLogger.getLogger(VerificationAppConfigurationsValidator.class); + + /** + * This configuration will be used by reprocessor stage to reprocess the events + */ + @Value("${registration.processor.reprocess.elapse.time}") + private long reprocessorElapseTime; + + @Value("${registration.processor.queue.verification.request.messageTTL}") + private int mvRequestMessageTTL; + + @Value("${registration.processor.verification.reprocess.buffer.time:900}") + private long reprocessBufferTime; + + /** + * The below method will be called by spring once the context is initialized or refreshed + * @param event Context refreshed event + */ + @EventListener + public void validateConfigurations(ContextRefreshedEvent event) { + logger.info("ContextRefreshedEvent received"); + validateReprocessElapseTimeConfig(); + } + + private void validateReprocessElapseTimeConfig() { + long allowedReprocessTime = mvRequestMessageTTL + reprocessBufferTime; + if(reprocessorElapseTime <= allowedReprocessTime) { + logger.warn("registration.processor.reprocess.elapse.time config {} is invalid," + + " it should should be greater than the queue expiry with an" + + " additional buffer {}", reprocessorElapseTime, allowedReprocessTime); + } + } +} diff --git a/registration-processor/init/registration-processor-registration-status-service/src/main/java/io/mosip/registration/processor/status/api/config/RegistrationStatusConfig.java b/registration-processor/init/registration-processor-registration-status-service/src/main/java/io/mosip/registration/processor/status/api/config/RegistrationStatusConfig.java index ed91a8fc862..a25b4105aec 100644 --- a/registration-processor/init/registration-processor-registration-status-service/src/main/java/io/mosip/registration/processor/status/api/config/RegistrationStatusConfig.java +++ b/registration-processor/init/registration-processor-registration-status-service/src/main/java/io/mosip/registration/processor/status/api/config/RegistrationStatusConfig.java @@ -1,7 +1,7 @@ package io.mosip.registration.processor.status.api.config; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import io.mosip.registration.processor.core.logger.RegProcessorLogger; +import io.mosip.kernel.core.logger.spi.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -20,7 +20,7 @@ @Configuration public class RegistrationStatusConfig { - private static final Logger logger = LoggerFactory.getLogger(RegistrationStatusConfig.class); + private static final Logger logger = RegProcessorLogger.getLogger(RegistrationStatusConfig.class); @Autowired private OpenApiProperties openApiProperties; 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 f509f63d1b1..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 @@ -1,83 +1,84 @@ -package io.mosip.registration.processor.stages.executor; - -import java.util.List; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; -import org.springframework.core.env.MutablePropertySources; - -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; - -/** - * The Class MosipStageExecutorApplication. - */ -public class MosipStageExecutorApplication { - - /** The Constant regProcLogger. */ - private static final Logger regProcLogger = LoggerFactory.getLogger(MosipStageExecutorApplication.class); - - /** - * main method to launch external stage application. - * - * @param args the arguments - */ - public static void main(String[] args) { - regProcLogger.info("Starting mosip-stage-executor..."); - //This context is closed after deploying the stages - try (AnnotationConfigApplicationContext stageInfoApplicationContext = new AnnotationConfigApplicationContext( - new Class[] { StagesConfig.class });) { - StagesConfig stagesConfig = stageInfoApplicationContext.getBean(StagesConfig.class); - MutablePropertySources propertySources = stagesConfig.getCloudPropertySources(); - - List stageBeansBasePackages = StageClassesUtil.getStageBeansBasePackages(stagesConfig, propertySources); - - if(!stageBeansBasePackages.isEmpty()) { - - regProcLogger.info("Base packages for stage beans from configuration: {}", stageBeansBasePackages); - - List> stageClasses = StageClassesUtil.getStageBeanClasses(stageBeansBasePackages); - - regProcLogger.info("Stage classes identified: {}", stageClasses.stream().map(Class::getCanonicalName).collect(Collectors.joining(", "))); - - Class[] entrypointConfigClasses = Stream.concat(Stream.of(StagesConfig.class), stageClasses.stream()) - .toArray(size -> new Class[size]); - - //This context should not be closed and to be kept for consumption by the verticles - AnnotationConfigApplicationContext mainApplicationContext = new PropertySourcesCustomizingApplicationContext( - entrypointConfigClasses) { - @Override - public MutablePropertySources getPropertySources() { - return propertySources; - }; - }; - - if (!stageClasses.isEmpty()) { - ExecutorService executorService = Executors.newFixedThreadPool(stageClasses.size()); - stageClasses.forEach(stageClass -> executorService.execute(() -> { - try { - regProcLogger.info("Executing Stage: {}", stageClass.getCanonicalName()); - MosipVerticleAPIManager stageBean = StageClassesUtil.getStageBean(mainApplicationContext, stageClass); - stageBean.deployVerticle(); - } catch (Exception e) { - regProcLogger.error("Exception occured while loading verticles. Please make sure correct verticle name was passed from deployment script. \n {}", - ExceptionUtils.getStackTrace(e)); - } - })); - executorService.shutdown(); - } else { - regProcLogger.error("No stage class is found. Please make sure correct correct stage class base packages are specified in properties and stages are added to classpath/dependencies."); - } - } else { - regProcLogger.error("No base packages configured for stages."); - } - } - } -} +package io.mosip.registration.processor.stages.executor; + +import java.util.List; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import io.mosip.registration.processor.core.logger.RegProcessorLogger; +import io.mosip.kernel.core.logger.spi.Logger; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.core.env.MutablePropertySources; + +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; + +/** + * The Class MosipStageExecutorApplication. + */ +public class MosipStageExecutorApplication { + + /** The Constant regProcLogger. */ + private static final Logger regProcLogger = RegProcessorLogger.getLogger(MosipStageExecutorApplication.class); + + /** + * main method to launch external stage application. + * + * @param args the arguments + */ + public static void main(String[] args) { + regProcLogger.info("Starting mosip-stage-executor..."); + //This context is closed after deploying the stages + try (AnnotationConfigApplicationContext stageInfoApplicationContext = new AnnotationConfigApplicationContext( + new Class[] { StagesConfig.class });) { + StagesConfig stagesConfig = stageInfoApplicationContext.getBean(StagesConfig.class); + MutablePropertySources propertySources = stagesConfig.getCloudPropertySources(); + + List stageBeansBasePackages = StageClassesUtil.getStageBeansBasePackages(stagesConfig, propertySources); + + if(!stageBeansBasePackages.isEmpty()) { + + regProcLogger.info("Base packages for stage beans from configuration: {}", stageBeansBasePackages); + + List> stageClasses = StageClassesUtil.getStageBeanClasses(stageBeansBasePackages); + + regProcLogger.info("Stage classes identified: {}", stageClasses.stream().map(Class::getCanonicalName).collect(Collectors.joining(", "))); + + Class[] entrypointConfigClasses = Stream.concat(Stream.of(StagesConfig.class), stageClasses.stream()) + .toArray(size -> new Class[size]); + + //This context should not be closed and to be kept for consumption by the verticles + AnnotationConfigApplicationContext mainApplicationContext = new PropertySourcesCustomizingApplicationContext( + entrypointConfigClasses) { + @Override + public MutablePropertySources getPropertySources() { + return propertySources; + }; + }; + + if (!stageClasses.isEmpty()) { + ExecutorService executorService = Executors.newFixedThreadPool(stageClasses.size()); + stageClasses.forEach(stageClass -> executorService.execute(() -> { + try { + regProcLogger.info("Executing Stage: {}", stageClass.getCanonicalName()); + MosipVerticleAPIManager stageBean = StageClassesUtil.getStageBean(mainApplicationContext, stageClass); + stageBean.deployVerticle(); + } catch (Exception e) { + regProcLogger.error("Exception occured while loading verticles. Please make sure correct verticle name was passed from deployment script. \n {}", + ExceptionUtils.getStackTrace(e)); + } + })); + executorService.shutdown(); + } else { + regProcLogger.error("No stage class is found. Please make sure correct correct stage class base packages are specified in properties and stages are added to classpath/dependencies."); + } + } else { + regProcLogger.error("No base packages configured for stages."); + } + } + } +} 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 4c3f26f9dce..6e5beb7480f 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 @@ -8,8 +8,7 @@ import java.util.Set; import java.util.stream.Collectors; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; + import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.context.annotation.AnnotationConfigApplicationContext; @@ -21,6 +20,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; /** @@ -29,7 +30,7 @@ public class StageClassesUtil { /** The Constant regProcLogger. */ - private static final Logger regProcLogger = LoggerFactory.getLogger(StageClassesUtil.class); + private static final Logger regProcLogger = RegProcessorLogger.getLogger(StageClassesUtil.class); /** The Constant PROP_STAGE_GROUPS_STAGE_BEANS_BASE_PACKAGES_PREFIX. */ private static final String PROP_STAGE_GROUPS_STAGE_BEANS_BASE_PACKAGES_PREFIX = "mosip.regproc.mosip-stage-executor.stage-beans-base-packages."; diff --git a/registration-processor/post-processor/registration-processor-registration-transaction-service/src/main/java/io/mosip/registration/processor/transaction/api/config/SwaggerConfig.java b/registration-processor/post-processor/registration-processor-registration-transaction-service/src/main/java/io/mosip/registration/processor/transaction/api/config/SwaggerConfig.java index 62664c3672e..0eba028f189 100644 --- a/registration-processor/post-processor/registration-processor-registration-transaction-service/src/main/java/io/mosip/registration/processor/transaction/api/config/SwaggerConfig.java +++ b/registration-processor/post-processor/registration-processor-registration-transaction-service/src/main/java/io/mosip/registration/processor/transaction/api/config/SwaggerConfig.java @@ -1,66 +1,66 @@ -package io.mosip.registration.processor.transaction.api.config; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -import io.swagger.v3.oas.models.Components; -import io.swagger.v3.oas.models.OpenAPI; -import io.swagger.v3.oas.models.info.Info; -import io.swagger.v3.oas.models.info.License; -import io.swagger.v3.oas.models.servers.Server; - -/** - * Configuration class for swagger config - * - * @author Dharmesh Khandelwal - * @since 1.0.0 - * @author Govindaraj Velu - * @implSpec upgrade the Swagger2.0 to OpenAPI (Swagger3.0) - * - */ -@Configuration -public class SwaggerConfig { - - private static final Logger logger = LoggerFactory.getLogger(SwaggerConfig.class); - - @Autowired - private OpenApiProperties openApiProperties; - - @Bean - public OpenAPI openApi() { - String msg = "Swagger open api, "; - OpenAPI api = new OpenAPI() - .components(new Components()); - if (null != openApiProperties.getInfo()) { - api.info(new Info() - .title(openApiProperties.getInfo().getTitle()) - .version(openApiProperties.getInfo().getVersion()) - .description(openApiProperties.getInfo().getDescription())); - if (null != openApiProperties.getInfo().getLicense()) { - api.getInfo().license(new License() - .name(openApiProperties.getInfo().getLicense().getName()) - .url(openApiProperties.getInfo().getLicense().getUrl())); - logger.info(msg + "info license property is added"); - } else { - logger.error(msg + "info license property is empty"); - } - logger.info(msg + "info property is added"); - } else { - logger.error(msg + "info property is empty"); - } - - if (null != openApiProperties.getRegistrationProcessor().getServers()) { - openApiProperties.getRegistrationProcessor().getServers().forEach(server -> { - api.addServersItem(new Server().description(server.getDescription()).url(server.getUrl())); - }); - logger.info(msg + "server property is added"); - } else { - logger.error(msg + "server property is empty"); - } - return api; - } - -} +package io.mosip.registration.processor.transaction.api.config; + +import io.mosip.registration.processor.core.logger.RegProcessorLogger; +import io.mosip.kernel.core.logger.spi.Logger; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import io.swagger.v3.oas.models.Components; +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.info.Info; +import io.swagger.v3.oas.models.info.License; +import io.swagger.v3.oas.models.servers.Server; + +/** + * Configuration class for swagger config + * + * @author Dharmesh Khandelwal + * @since 1.0.0 + * @author Govindaraj Velu + * @implSpec upgrade the Swagger2.0 to OpenAPI (Swagger3.0) + * + */ +@Configuration +public class SwaggerConfig { + + private static final Logger logger = RegProcessorLogger.getLogger(SwaggerConfig.class); + + @Autowired + private OpenApiProperties openApiProperties; + + @Bean + public OpenAPI openApi() { + String msg = "Swagger open api, "; + OpenAPI api = new OpenAPI() + .components(new Components()); + if (null != openApiProperties.getInfo()) { + api.info(new Info() + .title(openApiProperties.getInfo().getTitle()) + .version(openApiProperties.getInfo().getVersion()) + .description(openApiProperties.getInfo().getDescription())); + if (null != openApiProperties.getInfo().getLicense()) { + api.getInfo().license(new License() + .name(openApiProperties.getInfo().getLicense().getName()) + .url(openApiProperties.getInfo().getLicense().getUrl())); + logger.info(msg + "info license property is added"); + } else { + logger.error(msg + "info license property is empty"); + } + logger.info(msg + "info property is added"); + } else { + logger.error(msg + "info property is empty"); + } + + if (null != openApiProperties.getRegistrationProcessor().getServers()) { + openApiProperties.getRegistrationProcessor().getServers().forEach(server -> { + api.addServersItem(new Server().description(server.getDescription()).url(server.getUrl())); + }); + logger.info(msg + "server property is added"); + } else { + logger.error(msg + "server property is empty"); + } + return api; + } + +} 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 9f02ca4822b..45a7064cb12 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 @@ -1,526 +1,526 @@ -package io.mosip.registration.processor.core.abstractverticle; - -import static io.vertx.ext.healthchecks.impl.StatusHelper.isUp; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; - -import javax.jms.*; - -import io.mosip.kernel.core.exception.ExceptionUtils; -import io.mosip.kernel.core.virusscanner.spi.VirusScanner; -import io.mosip.registration.processor.core.constant.LoggerFileConstant; -import io.mosip.registration.processor.core.queue.factory.MosipActiveMq; -import io.mosip.registration.processor.core.queue.factory.MosipQueue; -import io.mosip.registration.processor.core.queue.factory.QueueListener; -import io.mosip.registration.processor.core.queue.impl.TransportExceptionListener; -import io.mosip.registration.processor.core.spi.queue.MosipQueueConnectionFactory; -import io.mosip.registration.processor.core.spi.queue.MosipQueueManager; -import org.apache.activemq.ActiveMQConnection; -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.command.ActiveMQBytesMessage; -import org.apache.commons.io.FileUtils; -import org.apache.hadoop.conf.Configuration; -import org.apache.hadoop.fs.FileSystem; -import org.apache.hadoop.security.UserGroupInformation; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.core.env.Environment; -import org.springframework.core.io.DefaultResourceLoader; -import org.springframework.core.io.Resource; -import org.springframework.core.io.ResourceLoader; -import org.springframework.jdbc.support.JdbcUtils; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; - -import io.mosip.registration.processor.core.constant.HealthConstant; -import io.netty.handler.codec.http.HttpResponse; -import io.vertx.core.AsyncResult; -import io.vertx.core.Handler; -import io.vertx.core.Promise; -import io.vertx.core.Vertx; -import io.vertx.core.http.HttpHeaders; -import io.vertx.core.http.HttpMethod; -import io.vertx.core.http.HttpServerResponse; -import io.vertx.core.json.JsonArray; -import io.vertx.core.json.JsonObject; -import io.vertx.ext.auth.AuthProvider; -import io.vertx.ext.healthchecks.HealthCheckHandler; -import io.vertx.ext.healthchecks.HealthChecks; -import io.vertx.ext.healthchecks.Status; -import io.vertx.ext.healthchecks.impl.HealthChecksImpl; -import io.vertx.ext.web.RoutingContext; - -/** - * @author Mukul Puspam - * - */ -public class StageHealthCheckHandler implements HealthCheckHandler { - private HealthChecks healthChecks; - - MosipQueue mosipQueue = null; - boolean isConsumerStarted = false; - private final AuthProvider authProvider; - private ObjectMapper objectMapper; - private String driver; - private String url; - private String username; - private String password; - private String virusScannerHost; - private String nameNodeUrl; - private String kdcDomain; - private String keytabPath; - private String queueUsername; - private String queuePassword; - private String queueBrokerUrl; - private Boolean isAuthEnable; - private int virusScannerPort; - private File currentWorkingDirPath; - private VirusScanner virusScanner; - private FileSystem configuredFileSystem; - private Path hadoopLibPath; - private static final String HADOOP_HOME = "hadoop-lib"; - private static final String WIN_UTIL = "winutils.exe"; - private static final String CLASSPATH_PREFIX = "classpath:"; - private static final int THRESHOLD = 10485760; - javax.jms.Connection connection = null; - private Session session = null; - MessageConsumer messageConsumer; - MessageProducer messageProducer; - - private static final String DEFAULT_QUERY = "SELECT 1"; - - private StageHealthCheckHandler.JSONResultBuilder resultBuilder; - /** - * The field for Logger - */ - private static final Logger LOGGER = LoggerFactory.getLogger(StageHealthCheckHandler.class); - - private ResourceLoader resourceLoader = new DefaultResourceLoader(); - - /** - * @param vertx - * @param provider - * @param objectMapper - * @param environment - */ - public StageHealthCheckHandler(Vertx vertx, AuthProvider provider, ObjectMapper objectMapper, VirusScanner virusScanner, - Environment environment) { - this.healthChecks = new HealthChecksImpl(vertx); - this.authProvider = provider; - this.objectMapper = objectMapper; - this.driver = environment.getProperty(HealthConstant.DRIVER); - this.url = environment.getProperty(HealthConstant.URL); - this.username = environment.getProperty(HealthConstant.USER); - this.password = environment.getProperty(HealthConstant.PASSWORD); - this.queueUsername = environment.getProperty(HealthConstant.QUEUE_USERNAME); - this.queuePassword = environment.getProperty(HealthConstant.QUEUE_PASSWORD); - this.queueBrokerUrl = environment.getProperty(HealthConstant.QUEUE_BROKER_URL); - this.currentWorkingDirPath = new File(System.getProperty(HealthConstant.CURRENT_WORKING_DIRECTORY)); - this.resultBuilder = new StageHealthCheckHandler.JSONResultBuilder(); - this.virusScanner = virusScanner; - } - - @Override - public StageHealthCheckHandler register(String name, Handler> procedure) { - healthChecks.register(name, procedure); - return this; - } - - @Override - public StageHealthCheckHandler register(String name, long timeout, Handler> procedure) { - healthChecks.register(name, timeout, procedure); - return this; - } - - /** - * @param promise - */ - public void queueHealthChecker(Promise promise, MosipQueueManager mosipQueueManager, MosipQueueConnectionFactory mosipConnectionFactory) { - - try { - final String msg = "Ping"; - - if (mosipQueue == null) - mosipQueue = mosipConnectionFactory.createConnection("ACTIVEMQ", queueUsername, - queuePassword, queueBrokerUrl); - - mosipQueueManager.send(mosipQueue, msg.getBytes(), HealthConstant.QUEUE_ADDRESS); - - if (!isConsumerStarted) { - QueueListener listener = new QueueListener() { - @Override - public void setListener(Message message) { - try { - consumerListener(message, promise, msg); - } catch (Exception e) { - LOGGER.error(LoggerFileConstant.SESSIONID.toString(), - LoggerFileConstant.REGISTRATIONID.toString(), "Unable to check activemq health", ExceptionUtils.getStackTrace(e)); - } - } - }; - mosipQueueManager.consume(mosipQueue, HealthConstant.QUEUE_ADDRESS, listener); - isConsumerStarted = true; - } - } catch (Exception e) { - isConsumerStarted = false; - mosipQueue = null; - final JsonObject result = resultBuilder.create().add(HealthConstant.ERROR, e.getMessage()).build(); - promise.complete(Status.KO(result)); - } - } - public void consumerListener(Message message, Promise promise, String msg) { - String res = new String(((ActiveMQBytesMessage) message).getContent().data); - if (res == null || !msg.equalsIgnoreCase(res)) { - final JsonObject result = resultBuilder.create().add(HealthConstant.ERROR, "Could not read response from queue").build(); - promise.complete(Status.KO(result)); - } - final JsonObject result = resultBuilder.create().add(HealthConstant.RESPONSE, res).build(); - promise.complete(Status.OK(result)); - } - - /** - * @param configuration - * @return - * @throws Exception - */ - private void initSecurityConfiguration(Configuration configuration) throws Exception { - configuration.set("dfs.data.transfer.protection", "authentication"); - configuration.set("hadoop.security.authentication", "kerberos"); - InputStream krbStream = getClass().getClassLoader().getResourceAsStream("krb5.conf"); - File krbPath = FileUtils.getFile(hadoopLibPath.toString(), "krb5.conf"); - FileUtils.copyInputStreamToFile(krbStream, krbPath); - System.setProperty("java.security.krb5.conf", krbPath.toString()); - UserGroupInformation.setConfiguration(configuration); - } - - /** - * @param user - * @param keytabPath - * @throws Exception - */ - private void loginWithKeyTab(String user, String keytabPath) throws Exception { - File keyPath = null; - Resource resource = resourceLoader.getResource(keytabPath); - File dataPath = FileUtils.getFile(hadoopLibPath.toString(), "data"); - boolean created = dataPath.mkdir(); - if (resource.exists() && created) { - keyPath = FileUtils.getFile(dataPath.toString(), resource.getFilename()); - FileUtils.copyInputStreamToFile(resource.getInputStream(), keyPath); - } else { - throw new Exception("KEYTAB_FILE_NOT_FOUND_EXCEPTION: " + keytabPath); - } - try { - UserGroupInformation.loginUserFromKeytab(user, keyPath.toString()); - } catch (IOException e) { - throw new Exception("LOGIN_EXCEPTION", e); - } - } - - /** - * @param promise - */ - public void virusScanHealthChecker(Promise promise) { - try { - File file = new File("virus_scan_test.txt"); - String fileData = "virus scan test"; - Files.write(Paths.get("virus_scan_test.txt"), fileData.getBytes()); - boolean scanResult = this.virusScanner.scanFile(new FileInputStream(file)); - - final JsonObject result = resultBuilder.create().add(HealthConstant.RESPONSE, scanResult) - .build(); - promise.complete(Status.OK(result)); - - } catch (IOException e) { - final JsonObject result = resultBuilder.create().add(HealthConstant.ERROR, e.getMessage()).build(); - promise.complete(Status.KO(result)); - } - } - - /** - * Database health check handler - * - * @param promise {@link Promise} instance from handler - */ - public void databaseHealthChecker(Promise promise) { - - try { - Class.forName(driver); - } catch (ClassNotFoundException exception) { - final JsonObject result = resultBuilder.create().add(HealthConstant.ERROR, exception.getMessage()).build(); - promise.complete(Status.KO(result)); - } - try (Connection conn = DriverManager.getConnection(url, username, password)) { - try (final Statement statement = conn.createStatement()) { - - try (final ResultSet rs = statement.executeQuery(DEFAULT_QUERY)) { - - if (rs.next()) { - final JsonObject result = resultBuilder.create() - .add(HealthConstant.DATABASE, conn.getMetaData().getDatabaseProductName()) - .add(HealthConstant.HELLO, JdbcUtils.getResultSetValue(rs, 1)).build(); - promise.complete(Status.OK(result)); - - } - } - } - } catch (SQLException exception) { - final JsonObject result = resultBuilder.create().add(HealthConstant.ERROR, exception.getMessage()).build(); - promise.complete(Status.KO(result)); - } - } - - /** - * Disk-Space health check Handler - * - * @param promise {@link Promise} instance from handler - */ - public void dispSpaceHealthChecker(Promise promise) { - - final long diskFreeInBytes = this.currentWorkingDirPath.getUsableSpace(); - if (diskFreeInBytes >= THRESHOLD) { - final JsonObject result = resultBuilder.create() - .add(HealthConstant.TOTAL, this.currentWorkingDirPath.getTotalSpace()) - .add(HealthConstant.FREE, diskFreeInBytes).add(HealthConstant.THRESHOLD, THRESHOLD).build(); - promise.complete(Status.OK(result)); - } else { - final JsonObject result = resultBuilder.create().add(HealthConstant.ERROR, - String.format(HealthConstant.THRESHOLD_ERROR, diskFreeInBytes, THRESHOLD)).build(); - promise.complete(Status.KO(result)); - } - - } - - /** - * Send Verticle health check handler - * - * @param promise {@link Promise} instance from handler - * @param vertx {@link Vertx} instance - */ - public void senderHealthHandler(Promise promise, Vertx vertx, String address) { - try { - vertx.eventBus().send(address, HealthConstant.PING); - final JsonObject result = resultBuilder.create().add(HealthConstant.RESPONSE, HealthConstant.PING).build(); - promise.complete(Status.OK(result)); - } catch (Exception e) { - final JsonObject result = resultBuilder.create().add(HealthConstant.ERROR, e.getMessage()).build(); - promise.complete(Status.KO(result)); - } - } - - /** - * @param promise - * @param vertx - * @param address - */ - public void consumerHealthHandler(Promise promise, Vertx vertx, String address) { - try { - Boolean isRegistered = vertx.eventBus().consumer(address).isRegistered(); - final JsonObject result = resultBuilder.create().add(HealthConstant.RESPONSE, isRegistered).build(); - promise.complete(Status.OK(result)); - } catch (Exception e) { - final JsonObject result = resultBuilder.create().add(HealthConstant.ERROR, e.getMessage()).build(); - promise.complete(Status.KO(result)); - } - } - - @Override - public void handle(RoutingContext rc) { - String path = rc.request().path(); - String mount = rc.mountPoint(); - String route = rc.currentRoute().getPath(); - - String id; - - // We are under a sub-router. - // Remove the mount prefix from the path - if (mount != null && path.startsWith(mount)) { - path = path.substring(mount.length()); - } - - // The route has a path, remove this path from the path - if (route != null && path.startsWith(route)) { - id = path.substring(route.length()); - } else { - id = path; - } - - if (authProvider != null) { - // Copy all HTTP header in a json array and params - JsonObject authData = new JsonObject(); - rc.request().headers().forEach(entry -> authData.put(entry.getKey(), entry.getValue())); - rc.request().params().forEach(entry -> authData.put(entry.getKey(), entry.getValue())); - if (rc.request().method() == HttpMethod.POST && rc.request().getHeader(HttpHeaders.CONTENT_TYPE) != null - && rc.request().getHeader(HttpHeaders.CONTENT_TYPE).contains(HealthConstant.CONTENT_TYPE)) { - authData.mergeIn(rc.getBodyAsJson()); - } - authProvider.authenticate(authData, ar -> { - if (ar.failed()) { - rc.response().setStatusCode(403).end(); - } else { - healthChecks.invoke(id, this.healthSummaryHandler(rc)); - } - }); - } else { - healthChecks.invoke(id, this.healthSummaryHandler(rc)); - } - } - - /** - * Create health check summary - * - * @param rc {@link RoutingContext} instance - * @return {@link Handler} - */ - private Handler> healthSummaryHandler(RoutingContext rc) { - return json -> { - HttpServerResponse response = rc.response().putHeader(HttpHeaders.CONTENT_TYPE, - "application/json;charset=UTF-8"); - if (json.failed()) { - if (json.cause().getMessage().toLowerCase().contains("not found")) { - response.setStatusCode(404); - } else { - response.setStatusCode(400); - } - response.end("{\"message\": \"" + json.cause().getMessage() + "\"}"); - } else { - createResponse(json.result(), response); - } - }; - } - - /** - * Create a json response - * - * @param json summary json - * @param response {@link HttpResponse} - */ - private void createResponse(JsonObject json, HttpServerResponse response) { - int status = isUp(json) ? 200 : 503; - - if (status == 503 && hasErrors(json)) { - status = 500; - } - - json.put(HealthConstant.DETAILS, new JsonObject()); - - JsonArray checks = json.getJsonArray(HealthConstant.CHECKS); - - if (status == 200 && checks.isEmpty()) { - // Special case, no procedure installed. - response.setStatusCode(204).end(); - return; - } - if (checks != null && !checks.isEmpty()) { - createResponse(json, checks); - } - response.setStatusCode(status).end(encode(json)); - } - - /** - * Copy actual response to Spring actuator like response - * - * @param json Summary json - * @param checks Json array of all registered parameters with details - */ - private void createResponse(JsonObject json, JsonArray checks) { - for (int i = 0; i < checks.size(); i++) { - JsonObject jsonobject = checks.getJsonObject(i); - String id = jsonobject.getString(HealthConstant.ID); - BaseHealthCheckModel healthCheckModel = new BaseHealthCheckModel(); - healthCheckModel.setStatus(jsonobject.getString(HealthConstant.STATUS)); - JsonObject result = null; - try { - if (jsonobject.containsKey(HealthConstant.DATA)) { - healthCheckModel.setDetails(jsonobject.getJsonObject(HealthConstant.DATA).getMap()); - result = new JsonObject(objectMapper.writeValueAsString(healthCheckModel)); - - } else { - result = new JsonObject(objectMapper.writeValueAsString(healthCheckModel)); - result.remove("details"); - } - } catch (JsonProcessingException e) { - LOGGER.error(e.getMessage()); - } - - json.getJsonObject(HealthConstant.DETAILS).put(id, result); - - } - } - - @Override - public synchronized StageHealthCheckHandler unregister(String name) { - healthChecks.unregister(name); - return this; - } - - /** - * Check if error has occurred or not - * - * @param json Summary json - * @return True if has Error;else False - */ - private boolean hasErrors(JsonObject json) { - JsonObject data = json.getJsonObject(HealthConstant.DATA); - if (data != null && data.getBoolean("procedure-execution-failure", false)) { - return true; - } - - JsonArray checks = json.getJsonArray(HealthConstant.CHECKS); - if (checks != null) { - for (int i = 0; i < checks.size(); i++) { - JsonObject check = checks.getJsonObject(i); - if (hasErrors(check)) { - return true; - } - } - } - - return false; - } - - /** - * Encode the json object - * - * @param json Result json - * @return Encoded Json String - */ - private String encode(JsonObject json) { - final String outcome = json.getString(HealthConstant.OUTCOME); - json.remove(HealthConstant.OUTCOME); - json.put(HealthConstant.STATUS, outcome); - return json.encode(); - } - - static class JSONResultBuilder { - - private JsonObject jsonObject; - - public JSONResultBuilder create() { - jsonObject = new JsonObject(); - return this; - } - - public JSONResultBuilder add(String key, Object object) { - jsonObject.put(key, object); - return this; - } - - public JsonObject build() { - return jsonObject; - } - - } - -} +package io.mosip.registration.processor.core.abstractverticle; + +import static io.vertx.ext.healthchecks.impl.StatusHelper.isUp; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; + +import javax.jms.*; + +import io.mosip.kernel.core.exception.ExceptionUtils; +import io.mosip.kernel.core.virusscanner.spi.VirusScanner; +import io.mosip.registration.processor.core.constant.LoggerFileConstant; +import io.mosip.registration.processor.core.queue.factory.MosipActiveMq; +import io.mosip.registration.processor.core.queue.factory.MosipQueue; +import io.mosip.registration.processor.core.queue.factory.QueueListener; +import io.mosip.registration.processor.core.queue.impl.TransportExceptionListener; +import io.mosip.registration.processor.core.spi.queue.MosipQueueConnectionFactory; +import io.mosip.registration.processor.core.spi.queue.MosipQueueManager; +import org.apache.activemq.ActiveMQConnection; +import org.apache.activemq.ActiveMQConnectionFactory; +import org.apache.activemq.command.ActiveMQBytesMessage; +import org.apache.commons.io.FileUtils; +import org.apache.hadoop.conf.Configuration; +import org.apache.hadoop.fs.FileSystem; +import org.apache.hadoop.security.UserGroupInformation; +import io.mosip.registration.processor.core.logger.RegProcessorLogger; +import io.mosip.kernel.core.logger.spi.Logger; +import org.springframework.core.env.Environment; +import org.springframework.core.io.DefaultResourceLoader; +import org.springframework.core.io.Resource; +import org.springframework.core.io.ResourceLoader; +import org.springframework.jdbc.support.JdbcUtils; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +import io.mosip.registration.processor.core.constant.HealthConstant; +import io.netty.handler.codec.http.HttpResponse; +import io.vertx.core.AsyncResult; +import io.vertx.core.Handler; +import io.vertx.core.Promise; +import io.vertx.core.Vertx; +import io.vertx.core.http.HttpHeaders; +import io.vertx.core.http.HttpMethod; +import io.vertx.core.http.HttpServerResponse; +import io.vertx.core.json.JsonArray; +import io.vertx.core.json.JsonObject; +import io.vertx.ext.auth.AuthProvider; +import io.vertx.ext.healthchecks.HealthCheckHandler; +import io.vertx.ext.healthchecks.HealthChecks; +import io.vertx.ext.healthchecks.Status; +import io.vertx.ext.healthchecks.impl.HealthChecksImpl; +import io.vertx.ext.web.RoutingContext; + +/** + * @author Mukul Puspam + * + */ +public class StageHealthCheckHandler implements HealthCheckHandler { + private HealthChecks healthChecks; + + MosipQueue mosipQueue = null; + boolean isConsumerStarted = false; + private final AuthProvider authProvider; + private ObjectMapper objectMapper; + private String driver; + private String url; + private String username; + private String password; + private String virusScannerHost; + private String nameNodeUrl; + private String kdcDomain; + private String keytabPath; + private String queueUsername; + private String queuePassword; + private String queueBrokerUrl; + private Boolean isAuthEnable; + private int virusScannerPort; + private File currentWorkingDirPath; + private VirusScanner virusScanner; + private FileSystem configuredFileSystem; + private Path hadoopLibPath; + private static final String HADOOP_HOME = "hadoop-lib"; + private static final String WIN_UTIL = "winutils.exe"; + private static final String CLASSPATH_PREFIX = "classpath:"; + private static final int THRESHOLD = 10485760; + javax.jms.Connection connection = null; + private Session session = null; + MessageConsumer messageConsumer; + MessageProducer messageProducer; + + private static final String DEFAULT_QUERY = "SELECT 1"; + + private StageHealthCheckHandler.JSONResultBuilder resultBuilder; + /** + * The field for Logger + */ + private static final Logger LOGGER = RegProcessorLogger.getLogger(StageHealthCheckHandler.class); + + private ResourceLoader resourceLoader = new DefaultResourceLoader(); + + /** + * @param vertx + * @param provider + * @param objectMapper + * @param environment + */ + public StageHealthCheckHandler(Vertx vertx, AuthProvider provider, ObjectMapper objectMapper, VirusScanner virusScanner, + Environment environment) { + this.healthChecks = new HealthChecksImpl(vertx); + this.authProvider = provider; + this.objectMapper = objectMapper; + this.driver = environment.getProperty(HealthConstant.DRIVER); + this.url = environment.getProperty(HealthConstant.URL); + this.username = environment.getProperty(HealthConstant.USER); + this.password = environment.getProperty(HealthConstant.PASSWORD); + this.queueUsername = environment.getProperty(HealthConstant.QUEUE_USERNAME); + this.queuePassword = environment.getProperty(HealthConstant.QUEUE_PASSWORD); + this.queueBrokerUrl = environment.getProperty(HealthConstant.QUEUE_BROKER_URL); + this.currentWorkingDirPath = new File(System.getProperty(HealthConstant.CURRENT_WORKING_DIRECTORY)); + this.resultBuilder = new StageHealthCheckHandler.JSONResultBuilder(); + this.virusScanner = virusScanner; + } + + @Override + public StageHealthCheckHandler register(String name, Handler> procedure) { + healthChecks.register(name, procedure); + return this; + } + + @Override + public StageHealthCheckHandler register(String name, long timeout, Handler> procedure) { + healthChecks.register(name, timeout, procedure); + return this; + } + + /** + * @param promise + */ + public void queueHealthChecker(Promise promise, MosipQueueManager mosipQueueManager, MosipQueueConnectionFactory mosipConnectionFactory) { + + try { + final String msg = "Ping"; + + if (mosipQueue == null) + mosipQueue = mosipConnectionFactory.createConnection("ACTIVEMQ", queueUsername, + queuePassword, queueBrokerUrl); + + mosipQueueManager.send(mosipQueue, msg.getBytes(), HealthConstant.QUEUE_ADDRESS); + + if (!isConsumerStarted) { + QueueListener listener = new QueueListener() { + @Override + public void setListener(Message message) { + try { + consumerListener(message, promise, msg); + } catch (Exception e) { + LOGGER.error(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString(), "Unable to check activemq health", ExceptionUtils.getStackTrace(e)); + } + } + }; + mosipQueueManager.consume(mosipQueue, HealthConstant.QUEUE_ADDRESS, listener); + isConsumerStarted = true; + } + } catch (Exception e) { + isConsumerStarted = false; + mosipQueue = null; + final JsonObject result = resultBuilder.create().add(HealthConstant.ERROR, e.getMessage()).build(); + promise.complete(Status.KO(result)); + } + } + public void consumerListener(Message message, Promise promise, String msg) { + String res = new String(((ActiveMQBytesMessage) message).getContent().data); + if (res == null || !msg.equalsIgnoreCase(res)) { + final JsonObject result = resultBuilder.create().add(HealthConstant.ERROR, "Could not read response from queue").build(); + promise.complete(Status.KO(result)); + } + final JsonObject result = resultBuilder.create().add(HealthConstant.RESPONSE, res).build(); + promise.complete(Status.OK(result)); + } + + /** + * @param configuration + * @return + * @throws Exception + */ + private void initSecurityConfiguration(Configuration configuration) throws Exception { + configuration.set("dfs.data.transfer.protection", "authentication"); + configuration.set("hadoop.security.authentication", "kerberos"); + InputStream krbStream = getClass().getClassLoader().getResourceAsStream("krb5.conf"); + File krbPath = FileUtils.getFile(hadoopLibPath.toString(), "krb5.conf"); + FileUtils.copyInputStreamToFile(krbStream, krbPath); + System.setProperty("java.security.krb5.conf", krbPath.toString()); + UserGroupInformation.setConfiguration(configuration); + } + + /** + * @param user + * @param keytabPath + * @throws Exception + */ + private void loginWithKeyTab(String user, String keytabPath) throws Exception { + File keyPath = null; + Resource resource = resourceLoader.getResource(keytabPath); + File dataPath = FileUtils.getFile(hadoopLibPath.toString(), "data"); + boolean created = dataPath.mkdir(); + if (resource.exists() && created) { + keyPath = FileUtils.getFile(dataPath.toString(), resource.getFilename()); + FileUtils.copyInputStreamToFile(resource.getInputStream(), keyPath); + } else { + throw new Exception("KEYTAB_FILE_NOT_FOUND_EXCEPTION: " + keytabPath); + } + try { + UserGroupInformation.loginUserFromKeytab(user, keyPath.toString()); + } catch (IOException e) { + throw new Exception("LOGIN_EXCEPTION", e); + } + } + + /** + * @param promise + */ + public void virusScanHealthChecker(Promise promise) { + try { + File file = new File("virus_scan_test.txt"); + String fileData = "virus scan test"; + Files.write(Paths.get("virus_scan_test.txt"), fileData.getBytes()); + boolean scanResult = this.virusScanner.scanFile(new FileInputStream(file)); + + final JsonObject result = resultBuilder.create().add(HealthConstant.RESPONSE, scanResult) + .build(); + promise.complete(Status.OK(result)); + + } catch (IOException e) { + final JsonObject result = resultBuilder.create().add(HealthConstant.ERROR, e.getMessage()).build(); + promise.complete(Status.KO(result)); + } + } + + /** + * Database health check handler + * + * @param promise {@link Promise} instance from handler + */ + public void databaseHealthChecker(Promise promise) { + + try { + Class.forName(driver); + } catch (ClassNotFoundException exception) { + final JsonObject result = resultBuilder.create().add(HealthConstant.ERROR, exception.getMessage()).build(); + promise.complete(Status.KO(result)); + } + try (Connection conn = DriverManager.getConnection(url, username, password)) { + try (final Statement statement = conn.createStatement()) { + + try (final ResultSet rs = statement.executeQuery(DEFAULT_QUERY)) { + + if (rs.next()) { + final JsonObject result = resultBuilder.create() + .add(HealthConstant.DATABASE, conn.getMetaData().getDatabaseProductName()) + .add(HealthConstant.HELLO, JdbcUtils.getResultSetValue(rs, 1)).build(); + promise.complete(Status.OK(result)); + + } + } + } + } catch (SQLException exception) { + final JsonObject result = resultBuilder.create().add(HealthConstant.ERROR, exception.getMessage()).build(); + promise.complete(Status.KO(result)); + } + } + + /** + * Disk-Space health check Handler + * + * @param promise {@link Promise} instance from handler + */ + public void dispSpaceHealthChecker(Promise promise) { + + final long diskFreeInBytes = this.currentWorkingDirPath.getUsableSpace(); + if (diskFreeInBytes >= THRESHOLD) { + final JsonObject result = resultBuilder.create() + .add(HealthConstant.TOTAL, this.currentWorkingDirPath.getTotalSpace()) + .add(HealthConstant.FREE, diskFreeInBytes).add(HealthConstant.THRESHOLD, THRESHOLD).build(); + promise.complete(Status.OK(result)); + } else { + final JsonObject result = resultBuilder.create().add(HealthConstant.ERROR, + String.format(HealthConstant.THRESHOLD_ERROR, diskFreeInBytes, THRESHOLD)).build(); + promise.complete(Status.KO(result)); + } + + } + + /** + * Send Verticle health check handler + * + * @param promise {@link Promise} instance from handler + * @param vertx {@link Vertx} instance + */ + public void senderHealthHandler(Promise promise, Vertx vertx, String address) { + try { + vertx.eventBus().send(address, HealthConstant.PING); + final JsonObject result = resultBuilder.create().add(HealthConstant.RESPONSE, HealthConstant.PING).build(); + promise.complete(Status.OK(result)); + } catch (Exception e) { + final JsonObject result = resultBuilder.create().add(HealthConstant.ERROR, e.getMessage()).build(); + promise.complete(Status.KO(result)); + } + } + + /** + * @param promise + * @param vertx + * @param address + */ + public void consumerHealthHandler(Promise promise, Vertx vertx, String address) { + try { + Boolean isRegistered = vertx.eventBus().consumer(address).isRegistered(); + final JsonObject result = resultBuilder.create().add(HealthConstant.RESPONSE, isRegistered).build(); + promise.complete(Status.OK(result)); + } catch (Exception e) { + final JsonObject result = resultBuilder.create().add(HealthConstant.ERROR, e.getMessage()).build(); + promise.complete(Status.KO(result)); + } + } + + @Override + public void handle(RoutingContext rc) { + String path = rc.request().path(); + String mount = rc.mountPoint(); + String route = rc.currentRoute().getPath(); + + String id; + + // We are under a sub-router. + // Remove the mount prefix from the path + if (mount != null && path.startsWith(mount)) { + path = path.substring(mount.length()); + } + + // The route has a path, remove this path from the path + if (route != null && path.startsWith(route)) { + id = path.substring(route.length()); + } else { + id = path; + } + + if (authProvider != null) { + // Copy all HTTP header in a json array and params + JsonObject authData = new JsonObject(); + rc.request().headers().forEach(entry -> authData.put(entry.getKey(), entry.getValue())); + rc.request().params().forEach(entry -> authData.put(entry.getKey(), entry.getValue())); + if (rc.request().method() == HttpMethod.POST && rc.request().getHeader(HttpHeaders.CONTENT_TYPE) != null + && rc.request().getHeader(HttpHeaders.CONTENT_TYPE).contains(HealthConstant.CONTENT_TYPE)) { + authData.mergeIn(rc.getBodyAsJson()); + } + authProvider.authenticate(authData, ar -> { + if (ar.failed()) { + rc.response().setStatusCode(403).end(); + } else { + healthChecks.invoke(id, this.healthSummaryHandler(rc)); + } + }); + } else { + healthChecks.invoke(id, this.healthSummaryHandler(rc)); + } + } + + /** + * Create health check summary + * + * @param rc {@link RoutingContext} instance + * @return {@link Handler} + */ + private Handler> healthSummaryHandler(RoutingContext rc) { + return json -> { + HttpServerResponse response = rc.response().putHeader(HttpHeaders.CONTENT_TYPE, + "application/json;charset=UTF-8"); + if (json.failed()) { + if (json.cause().getMessage().toLowerCase().contains("not found")) { + response.setStatusCode(404); + } else { + response.setStatusCode(400); + } + response.end("{\"message\": \"" + json.cause().getMessage() + "\"}"); + } else { + createResponse(json.result(), response); + } + }; + } + + /** + * Create a json response + * + * @param json summary json + * @param response {@link HttpResponse} + */ + private void createResponse(JsonObject json, HttpServerResponse response) { + int status = isUp(json) ? 200 : 503; + + if (status == 503 && hasErrors(json)) { + status = 500; + } + + json.put(HealthConstant.DETAILS, new JsonObject()); + + JsonArray checks = json.getJsonArray(HealthConstant.CHECKS); + + if (status == 200 && checks.isEmpty()) { + // Special case, no procedure installed. + response.setStatusCode(204).end(); + return; + } + if (checks != null && !checks.isEmpty()) { + createResponse(json, checks); + } + response.setStatusCode(status).end(encode(json)); + } + + /** + * Copy actual response to Spring actuator like response + * + * @param json Summary json + * @param checks Json array of all registered parameters with details + */ + private void createResponse(JsonObject json, JsonArray checks) { + for (int i = 0; i < checks.size(); i++) { + JsonObject jsonobject = checks.getJsonObject(i); + String id = jsonobject.getString(HealthConstant.ID); + BaseHealthCheckModel healthCheckModel = new BaseHealthCheckModel(); + healthCheckModel.setStatus(jsonobject.getString(HealthConstant.STATUS)); + JsonObject result = null; + try { + if (jsonobject.containsKey(HealthConstant.DATA)) { + healthCheckModel.setDetails(jsonobject.getJsonObject(HealthConstant.DATA).getMap()); + result = new JsonObject(objectMapper.writeValueAsString(healthCheckModel)); + + } else { + result = new JsonObject(objectMapper.writeValueAsString(healthCheckModel)); + result.remove("details"); + } + } catch (JsonProcessingException e) { + LOGGER.error(e.getMessage()); + } + + json.getJsonObject(HealthConstant.DETAILS).put(id, result); + + } + } + + @Override + public synchronized StageHealthCheckHandler unregister(String name) { + healthChecks.unregister(name); + return this; + } + + /** + * Check if error has occurred or not + * + * @param json Summary json + * @return True if has Error;else False + */ + private boolean hasErrors(JsonObject json) { + JsonObject data = json.getJsonObject(HealthConstant.DATA); + if (data != null && data.getBoolean("procedure-execution-failure", false)) { + return true; + } + + JsonArray checks = json.getJsonArray(HealthConstant.CHECKS); + if (checks != null) { + for (int i = 0; i < checks.size(); i++) { + JsonObject check = checks.getJsonObject(i); + if (hasErrors(check)) { + return true; + } + } + } + + return false; + } + + /** + * Encode the json object + * + * @param json Result json + * @return Encoded Json String + */ + private String encode(JsonObject json) { + final String outcome = json.getString(HealthConstant.OUTCOME); + json.remove(HealthConstant.OUTCOME); + json.put(HealthConstant.STATUS, outcome); + return json.encode(); + } + + static class JSONResultBuilder { + + private JsonObject jsonObject; + + public JSONResultBuilder create() { + jsonObject = new JsonObject(); + return this; + } + + public JSONResultBuilder add(String key, Object object) { + jsonObject.put(key, object); + return this; + } + + public JsonObject build() { + return jsonObject; + } + + } + +} 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 d7c9c7ae2e6..98b13cde0b1 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 @@ -36,8 +36,8 @@ import io.vertx.kafka.client.consumer.impl.KafkaConsumerRecordsImpl; import io.vertx.kafka.client.producer.KafkaProducer; import io.vertx.kafka.client.producer.KafkaProducerRecord; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import io.mosip.registration.processor.core.logger.RegProcessorLogger; +import io.mosip.kernel.core.logger.spi.Logger; import org.slf4j.MDC; /** @@ -48,7 +48,7 @@ public class KafkaMosipEventBus implements MosipEventBus { /** The logger. */ - private Logger logger = LoggerFactory.getLogger(KafkaMosipEventBus.class); + private Logger logger = RegProcessorLogger.getLogger(KafkaMosipEventBus.class); /** The vertx instance that will be used by this event bus */ private Vertx vertx = null; 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 ca26589c856..b28f92ccdde 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 @@ -12,9 +12,8 @@ import io.vertx.core.Handler; import io.vertx.core.Vertx; import io.vertx.core.json.JsonObject; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - +import io.mosip.registration.processor.core.logger.RegProcessorLogger; +import io.mosip.kernel.core.logger.spi.Logger; /** @@ -25,7 +24,7 @@ public class VertxMosipEventBus implements MosipEventBus { /** The logger. */ - private Logger logger = LoggerFactory.getLogger(VertxMosipEventBus.class); + private Logger logger = RegProcessorLogger.getLogger(VertxMosipEventBus.class); /** The vertx instance that will be used by this event bus */ private Vertx vertx = null; 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 4b8b3abb90e..1624332391f 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,8 +1,15 @@ package io.mosip.registration.processor.core.logger; +import java.util.HashMap; +import java.util.Map; +import java.util.stream.Collectors; +import org.slf4j.LoggerFactory; + import io.mosip.kernel.core.logger.spi.Logger; import io.mosip.kernel.logger.logback.appender.RollingFileAppender; import io.mosip.kernel.logger.logback.factory.Logfactory; +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.LoggerContext; /** @@ -11,6 +18,10 @@ */ public final class RegProcessorLogger { + public static final String PROP_PREFIX = "logging.level."; + + public static Map loggingLevelMap=new HashMap(); + /** * Instantiates a new reg processor logger. */ @@ -24,6 +35,20 @@ private RegProcessorLogger() { * @return the logger */ public static Logger getLogger(Class clazz) { - return Logfactory.getSlf4jLogger(clazz); + if(loggingLevelMap.isEmpty()) { + loggingLevelMap = System.getProperties().entrySet().stream() + .filter(entry -> entry.getKey().toString().startsWith(PROP_PREFIX)) + .collect(Collectors.toMap(entry -> (String)entry.getKey(), entry -> (String)entry.getValue())); + } + Logger logger=Logfactory.getSlf4jLogger(clazz); + String loggerName = clazz.getName(); + if(loggingLevelMap.entrySet().stream().anyMatch( entry -> entry.getKey().equals(PROP_PREFIX+loggerName))) { + LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory(); + ch.qos.logback.classic.Logger slf4jlogger=loggerContext.getLogger(loggerName); + if(slf4jlogger!=null) { + slf4jlogger.setLevel(Level.valueOf(loggingLevelMap.get(PROP_PREFIX+loggerName))); + } + } + return logger; } } diff --git a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/util/ServerUtil.java b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/util/ServerUtil.java index a1a52f5c21c..feac469082b 100644 --- a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/util/ServerUtil.java +++ b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/util/ServerUtil.java @@ -3,8 +3,8 @@ import java.net.InetAddress; import java.net.UnknownHostException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import io.mosip.registration.processor.core.logger.RegProcessorLogger; +import io.mosip.kernel.core.logger.spi.Logger; /** * This class provides Server IP and Name. @@ -17,7 +17,7 @@ public class ServerUtil { private static ServerUtil serverInstance = null; /** The Constant LOGGER. */ - private static final Logger LOGGER = LoggerFactory.getLogger(ServerUtil.class); + private static final Logger LOGGER = RegProcessorLogger.getLogger(ServerUtil.class); /** The host not found. */ private String noHost = "HOST_NOT_FOUND"; diff --git a/registration-processor/registration-processor-info-storage-service/src/main/java/io/mosip/registration/processor/packet/storage/handler/PacketInfoStorageExceptionHandler.java b/registration-processor/registration-processor-info-storage-service/src/main/java/io/mosip/registration/processor/packet/storage/handler/PacketInfoStorageExceptionHandler.java index a6b5b09d9af..8c42e9bf8f9 100644 --- a/registration-processor/registration-processor-info-storage-service/src/main/java/io/mosip/registration/processor/packet/storage/handler/PacketInfoStorageExceptionHandler.java +++ b/registration-processor/registration-processor-info-storage-service/src/main/java/io/mosip/registration/processor/packet/storage/handler/PacketInfoStorageExceptionHandler.java @@ -1,7 +1,7 @@ package io.mosip.registration.processor.packet.storage.handler; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import io.mosip.registration.processor.core.logger.RegProcessorLogger; +import io.mosip.kernel.core.logger.spi.Logger; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; @@ -19,7 +19,7 @@ public class PacketInfoStorageExceptionHandler { /** The Constant log. */ - private static final Logger log = LoggerFactory.getLogger(PacketInfoStorageExceptionHandler.class); + private static final Logger log = RegProcessorLogger.getLogger(PacketInfoStorageExceptionHandler.class); /** * Duplicateentry. 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 ddc7796f584..9fdd16c0660 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 @@ -3,8 +3,8 @@ import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import io.mosip.registration.processor.core.logger.RegProcessorLogger; +import io.mosip.kernel.core.logger.spi.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; @@ -30,7 +30,7 @@ public class AuditLogRequestBuilder { /** The logger. */ - private final Logger regProcLogger = LoggerFactory.getLogger(AuditLogRequestBuilder.class); + private final Logger regProcLogger = RegProcessorLogger.getLogger(AuditLogRequestBuilder.class); /** The registration processor rest service. */ @Autowired From afefe96a69e2c3bf4c677447046b5ca54e6ddd3b Mon Sep 17 00:00:00 2001 From: Keshav Mishra Date: Mon, 8 May 2023 12:23:07 +0530 Subject: [PATCH 062/133] [MOSIP-23833] rstructered db upgrade scripts --- .../mosip_regprc/deploy.properties | 7 --- db_release_scripts/mosip_regprc/revoke.sh | 59 ------------------ .../mosip_regprc/sql/1.1.4_revoke.sql | 19 ------ .../mosip_regprc/sql/1.1.4_upgrade.sql | 21 ------- .../mosip_regprc/sql/1.1.5_revoke.sql | 16 ----- .../mosip_regprc/sql/1.1.5_upgrade.sql | 23 ------- db_release_scripts/mosip_regprc/upgrade.sh | 60 ------------------- .../README.MD | 0 .../ddl/regprc-additional_info_request.sql | 0 .../ddl/regprc-anonymous_profile.sql | 0 .../mosip_regprc/ddl/regprc-crypto_salt.sql | 0 .../ddl/regprc-reg_verification.sql | 0 .../dml/regprc-transaction_type.csv | 0 .../sql/1.1.5.5_to_1.2.0.1-B1_rollback.sql | 0 .../sql/1.1.5.5_to_1.2.0.1-B1_upgrade.sql | 0 .../mosip_regprc/upgrade.properties | 11 ++++ db_upgrade_scripts/mosip_regprc/upgrade.sh | 51 ++++++++++++++++ 17 files changed, 62 insertions(+), 205 deletions(-) delete mode 100644 db_release_scripts/mosip_regprc/deploy.properties delete mode 100644 db_release_scripts/mosip_regprc/revoke.sh delete mode 100644 db_release_scripts/mosip_regprc/sql/1.1.4_revoke.sql delete mode 100644 db_release_scripts/mosip_regprc/sql/1.1.4_upgrade.sql delete mode 100644 db_release_scripts/mosip_regprc/sql/1.1.5_revoke.sql delete mode 100644 db_release_scripts/mosip_regprc/sql/1.1.5_upgrade.sql delete mode 100644 db_release_scripts/mosip_regprc/upgrade.sh rename {db_release_scripts => db_upgrade_scripts}/README.MD (100%) rename {db_release_scripts => db_upgrade_scripts}/mosip_regprc/ddl/regprc-additional_info_request.sql (100%) rename {db_release_scripts => db_upgrade_scripts}/mosip_regprc/ddl/regprc-anonymous_profile.sql (100%) rename {db_release_scripts => db_upgrade_scripts}/mosip_regprc/ddl/regprc-crypto_salt.sql (100%) rename {db_release_scripts => db_upgrade_scripts}/mosip_regprc/ddl/regprc-reg_verification.sql (100%) rename {db_release_scripts => db_upgrade_scripts}/mosip_regprc/dml/regprc-transaction_type.csv (100%) rename db_release_scripts/mosip_regprc/sql/1.2.0.1_to_1.1.5.5_revoke.sql => db_upgrade_scripts/mosip_regprc/sql/1.1.5.5_to_1.2.0.1-B1_rollback.sql (100%) rename db_release_scripts/mosip_regprc/sql/1.1.5.5_to_1.2.0.1_upgrade.sql => db_upgrade_scripts/mosip_regprc/sql/1.1.5.5_to_1.2.0.1-B1_upgrade.sql (100%) create mode 100644 db_upgrade_scripts/mosip_regprc/upgrade.properties create mode 100644 db_upgrade_scripts/mosip_regprc/upgrade.sh diff --git a/db_release_scripts/mosip_regprc/deploy.properties b/db_release_scripts/mosip_regprc/deploy.properties deleted file mode 100644 index 72f9f4983d0..00000000000 --- a/db_release_scripts/mosip_regprc/deploy.properties +++ /dev/null @@ -1,7 +0,0 @@ -DB_SERVERIP= -DB_PORT= -SU_USER=postgres -DEFAULT_DB_NAME=postgres -MOSIP_DB_NAME=mosip_regprc -ALTER_SCRIPT_FILENAME=upgrade.sql -REVOKE_SCRIPT_FILENAME=revoke.sql diff --git a/db_release_scripts/mosip_regprc/revoke.sh b/db_release_scripts/mosip_regprc/revoke.sh deleted file mode 100644 index 12ae985490f..00000000000 --- a/db_release_scripts/mosip_regprc/revoke.sh +++ /dev/null @@ -1,59 +0,0 @@ -## Properties file -set -e -properties_file="$1" -revoke_version="$3" -current_version="$2" - echo "Properties File Name - $properties_file" - echo "DB revoke Version - $revoke_version" - echo "DB current version - $current_version" -if [ -f "$properties_file" ] -then - echo "Property file \"$properties_file\" found." - while IFS='=' read -r key value - do - key=$(echo $key | tr '.' '_') - eval ${key}=\${value} - done < "$properties_file" -else - echo "Property file not found, Pass property file name as argument." - exit 0 -fi - -if [ $# -ge 2 ] -then - echo "DB current version \"$current_version\" found." -else - echo "DB current version not found, Pass current version as argument." - exit 0 -fi -if [ $# -ge 3 ] -then - echo "DB revoke version \"$revoke_version\" found." -else - echo "DB revoke version not found, Pass revoke version as argument." - exit 0 -fi - -## 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" - -## Executing DB revoke scripts -echo "Alter scripts deployment on $MOSIP_DB_NAME database from $current_version to $revoke_version started...." -ALTER_SCRIPT_FILE="sql/${current_version}_to_${revoke_version}_${REVOKE_SCRIPT_FILENAME}" - -echo "revoke script considered for release deployment - $ALTER_SCRIPT_FILE" - -## Checking If Alter scripts are present -echo "Checking if script $ALTER_SCRIPT_FILE is present" -if [ -f "$ALTER_SCRIPT_FILE" ] -then - echo "SQL file "$ALTER_SCRIPT_FILE" found." -else - echo "SQL file not found, Since no SQL file present for \"$revoke_version\" hence exiting." - exit 0 -fi -echo Applying revoke changes - -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 $ALTER_SCRIPT_FILE diff --git a/db_release_scripts/mosip_regprc/sql/1.1.4_revoke.sql b/db_release_scripts/mosip_regprc/sql/1.1.4_revoke.sql deleted file mode 100644 index de1d86384f9..00000000000 --- a/db_release_scripts/mosip_regprc/sql/1.1.4_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.4_upgrade.sql b/db_release_scripts/mosip_regprc/sql/1.1.4_upgrade.sql deleted file mode 100644 index 6279fefa2aa..00000000000 --- a/db_release_scripts/mosip_regprc/sql/1.1.4_upgrade.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.5_revoke.sql b/db_release_scripts/mosip_regprc/sql/1.1.5_revoke.sql deleted file mode 100644 index 87b757f1f3c..00000000000 --- a/db_release_scripts/mosip_regprc/sql/1.1.5_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.1.5_upgrade.sql b/db_release_scripts/mosip_regprc/sql/1.1.5_upgrade.sql deleted file mode 100644 index 89fa3f3283e..00000000000 --- a/db_release_scripts/mosip_regprc/sql/1.1.5_upgrade.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/upgrade.sh b/db_release_scripts/mosip_regprc/upgrade.sh deleted file mode 100644 index 90df3b59ddd..00000000000 --- a/db_release_scripts/mosip_regprc/upgrade.sh +++ /dev/null @@ -1,60 +0,0 @@ -## Properties file -set -e -properties_file="$1" -upgrade_version="$3" -current_version="$2" - echo "Properties File Name - $properties_file" - echo "DB Upgrade Version - $upgrade_version" - echo "DB current version - $current_version" -if [ -f "$properties_file" ] -then - echo "Property file \"$properties_file\" found." - while IFS='=' read -r key value - do - key=$(echo $key | tr '.' '_') - eval ${key}=\${value} - done < "$properties_file" -else - echo "Property file not found, Pass property file name as argument." - exit 0 -fi - -if [ $# -ge 2 ] -then - echo "DB current version \"$current_version\" found." -else - echo "DB current version not found, Pass current version as argument." - exit 0 -fi -if [ $# -ge 3 ] -then - echo "DB upgrade version \"$upgrade_version\" found." -else - echo "DB upgrade version not found, Pass upgrade version as argument." - exit 0 -fi - - -## 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" - -## Executing DB Upgrade scripts -echo "Alter scripts deployment on $MOSIP_DB_NAME database from $current_version to $upgrade_version started...." -ALTER_SCRIPT_FILE="sql/${current_version}_to_${upgrade_version}_${ALTER_SCRIPT_FILENAME}" - -echo "Upgrade script considered for release deployment - $ALTER_SCRIPT_FILE" - -## Checking If Alter scripts are present -echo "Checking if script $ALTER_SCRIPT_FILE is present" -if [ -f "$ALTER_SCRIPT_FILE" ] -then - echo "SQL file "$ALTER_SCRIPT_FILE" found." -else - echo "SQL file not found, Since no SQL file present for \"$upgrade_version\" hence exiting." - exit 0 -fi -echo Applying upgrade changes - -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 $ALTER_SCRIPT_FILE 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_release_scripts/mosip_regprc/ddl/regprc-additional_info_request.sql b/db_upgrade_scripts/mosip_regprc/ddl/regprc-additional_info_request.sql similarity index 100% rename from db_release_scripts/mosip_regprc/ddl/regprc-additional_info_request.sql rename to db_upgrade_scripts/mosip_regprc/ddl/regprc-additional_info_request.sql diff --git a/db_release_scripts/mosip_regprc/ddl/regprc-anonymous_profile.sql b/db_upgrade_scripts/mosip_regprc/ddl/regprc-anonymous_profile.sql similarity index 100% rename from db_release_scripts/mosip_regprc/ddl/regprc-anonymous_profile.sql rename to db_upgrade_scripts/mosip_regprc/ddl/regprc-anonymous_profile.sql diff --git a/db_release_scripts/mosip_regprc/ddl/regprc-crypto_salt.sql b/db_upgrade_scripts/mosip_regprc/ddl/regprc-crypto_salt.sql similarity index 100% rename from db_release_scripts/mosip_regprc/ddl/regprc-crypto_salt.sql rename to db_upgrade_scripts/mosip_regprc/ddl/regprc-crypto_salt.sql diff --git a/db_release_scripts/mosip_regprc/ddl/regprc-reg_verification.sql b/db_upgrade_scripts/mosip_regprc/ddl/regprc-reg_verification.sql similarity index 100% rename from db_release_scripts/mosip_regprc/ddl/regprc-reg_verification.sql rename to db_upgrade_scripts/mosip_regprc/ddl/regprc-reg_verification.sql diff --git a/db_release_scripts/mosip_regprc/dml/regprc-transaction_type.csv b/db_upgrade_scripts/mosip_regprc/dml/regprc-transaction_type.csv similarity index 100% rename from db_release_scripts/mosip_regprc/dml/regprc-transaction_type.csv rename to db_upgrade_scripts/mosip_regprc/dml/regprc-transaction_type.csv diff --git a/db_release_scripts/mosip_regprc/sql/1.2.0.1_to_1.1.5.5_revoke.sql b/db_upgrade_scripts/mosip_regprc/sql/1.1.5.5_to_1.2.0.1-B1_rollback.sql similarity index 100% rename from db_release_scripts/mosip_regprc/sql/1.2.0.1_to_1.1.5.5_revoke.sql rename to db_upgrade_scripts/mosip_regprc/sql/1.1.5.5_to_1.2.0.1-B1_rollback.sql diff --git a/db_release_scripts/mosip_regprc/sql/1.1.5.5_to_1.2.0.1_upgrade.sql b/db_upgrade_scripts/mosip_regprc/sql/1.1.5.5_to_1.2.0.1-B1_upgrade.sql similarity index 100% rename from db_release_scripts/mosip_regprc/sql/1.1.5.5_to_1.2.0.1_upgrade.sql rename to db_upgrade_scripts/mosip_regprc/sql/1.1.5.5_to_1.2.0.1-B1_upgrade.sql diff --git a/db_upgrade_scripts/mosip_regprc/upgrade.properties b/db_upgrade_scripts/mosip_regprc/upgrade.properties new file mode 100644 index 00000000000..5a3dba3d491 --- /dev/null +++ b/db_upgrade_scripts/mosip_regprc/upgrade.properties @@ -0,0 +1,11 @@ +MOSIP_DB_NAME= +DB_SERVERIP= +DB_PORT= +SU_USER=postgres +SU_USER_PWD= +SYS_ADMIN_USER= +SYS_ADMIN_PWD= +DEFAULT_DB_NAME=postgres +DBUSER_PWD= +CURRENT_VERSION= +TARGET_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..1e0619e00c6 --- /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 From 18c4699e4babc00e2aa84985935ed0641c213546 Mon Sep 17 00:00:00 2001 From: Keshav Mishra Date: Mon, 8 May 2023 12:25:15 +0530 Subject: [PATCH 063/133] added action as param --- db_upgrade_scripts/mosip_regprc/upgrade.properties | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/db_upgrade_scripts/mosip_regprc/upgrade.properties b/db_upgrade_scripts/mosip_regprc/upgrade.properties index 5a3dba3d491..3bdec16410a 100644 --- a/db_upgrade_scripts/mosip_regprc/upgrade.properties +++ b/db_upgrade_scripts/mosip_regprc/upgrade.properties @@ -8,4 +8,5 @@ SYS_ADMIN_PWD= DEFAULT_DB_NAME=postgres DBUSER_PWD= CURRENT_VERSION= -TARGET_VERSION= \ No newline at end of file +TARGET_VERSION= +ACTION= \ No newline at end of file From 0c774051f93f8edad404cf36f781d1798be78e4a Mon Sep 17 00:00:00 2001 From: Sowmya Ujjappa Banakar Date: Wed, 10 May 2023 13:02:14 +0530 Subject: [PATCH 064/133] MOSIP-27069 code changes --- .../biodedupe/stage/BioDedupeProcessor.java | 1351 +++++++++-------- 1 file changed, 676 insertions(+), 675 deletions(-) diff --git a/registration-processor/core-processor/registration-processor-bio-dedupe-stage/src/main/java/io/mosip/registration/processor/biodedupe/stage/BioDedupeProcessor.java b/registration-processor/core-processor/registration-processor-bio-dedupe-stage/src/main/java/io/mosip/registration/processor/biodedupe/stage/BioDedupeProcessor.java index 5520f67349f..be0738c4a74 100644 --- a/registration-processor/core-processor/registration-processor-bio-dedupe-stage/src/main/java/io/mosip/registration/processor/biodedupe/stage/BioDedupeProcessor.java +++ b/registration-processor/core-processor/registration-processor-bio-dedupe-stage/src/main/java/io/mosip/registration/processor/biodedupe/stage/BioDedupeProcessor.java @@ -1,676 +1,677 @@ -package io.mosip.registration.processor.biodedupe.stage; - -import io.mosip.kernel.core.logger.spi.Logger; -import io.mosip.kernel.core.util.StringUtils; -import io.mosip.kernel.core.util.exception.JsonProcessingException; -import io.mosip.registration.processor.biodedupe.constants.BioDedupeConstants; -import io.mosip.registration.processor.biodedupe.service.CbeffValidateAndVerificatonService; -import io.mosip.registration.processor.biodedupe.stage.exception.CbeffNotFoundException; -import io.mosip.registration.processor.core.abstractverticle.MessageBusAddress; -import io.mosip.registration.processor.core.abstractverticle.MessageDTO; -import io.mosip.registration.processor.core.code.DedupeSourceName; -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.AbisConstant; -import io.mosip.registration.processor.core.constant.LoggerFileConstant; -import io.mosip.registration.processor.core.constant.MappingJsonConstants; -import io.mosip.registration.processor.core.constant.ProviderStageName; -import io.mosip.registration.processor.core.constant.RegistrationType; -import io.mosip.registration.processor.core.exception.ApisResourceAccessException; -import io.mosip.registration.processor.core.exception.PacketDecryptionFailureException; -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.Identity; -import io.mosip.registration.processor.core.packet.dto.demographicinfo.JsonValue; -import io.mosip.registration.processor.core.spi.biodedupe.BioDedupeService; -import io.mosip.registration.processor.core.spi.packetmanager.PacketInfoManager; -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.idreposervice.IdRepoService; -import io.mosip.registration.processor.packet.storage.dto.ApplicantInfoDto; -import io.mosip.registration.processor.packet.storage.exception.IdentityNotFoundException; -import io.mosip.registration.processor.packet.storage.utils.ABISHandlerUtil; -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.dto.SyncTypeDto; -import io.mosip.registration.processor.status.service.RegistrationStatusService; -import org.apache.commons.lang3.exception.ExceptionUtils; -import org.json.simple.JSONArray; -import org.json.simple.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 java.io.IOException; -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - -/** - * The Class BioDedupeProcessor. - * - * @author Nagalakshmi - * @author Sowmya - * @author Horteppa - */ - -@Service -@Transactional -public class BioDedupeProcessor { - - /** The utilities. */ - @Autowired - Utilities utilities; - - @Autowired - private IdRepoService idRepoService; - - @Value("#{'${registration.processor.sub-processes}'.split(',')}") - private List subProcesses; - - @Autowired - private CbeffValidateAndVerificatonService cbeffValidateAndVerificatonService; - - @Autowired - private PriorityBasedPacketManagerService priorityBasedPacketManagerService; - - /** The packet info manager. */ - @Autowired - private PacketInfoManager packetInfoManager; - - /** The registration status service. */ - @Autowired - private RegistrationStatusService registrationStatusService; - - /** The core audit request builder. */ - @Autowired - private AuditLogRequestBuilder auditLogRequestBuilder; - - /** The registration exception mapper util. */ - @Autowired - RegistrationExceptionMapperUtil registrationExceptionMapperUtil; - - /** The abis handler util. */ - @Autowired - private ABISHandlerUtil abisHandlerUtil; - - @Autowired - private BioDedupeService biodedupeServiceImpl; - - /** The config server file storage URL. */ - @Value("${config.server.file.storage.uri}") - private String configServerFileStorageURL; - - /** The get reg processor identity json. */ - @Value("${registration.processor.identityjson}") - private String getRegProcessorIdentityJson; - - /** The age limit. */ - @Value("${mosip.kernel.applicant.type.age.limit}") - private String ageLimit; - - @Value("${registration.processor.missing.biometric.verification.enabled:true}") - private boolean missingBiometricVerificationEnabled; - - /** The reg proc logger. */ - private static Logger regProcLogger = RegProcessorLogger.getLogger(BioDedupeProcessor.class); - - - - @Value("${registration.processor.infant.dedupe}") - private String infantDedupe; - - public static final String GLOBAL_CONFIG_TRUE_VALUE = "Y"; - - - - - /** - * Process. - * - * @param object - * the object - * @param stageName - * the stage name - * @return the message DTO - */ - public MessageDTO process(MessageDTO object, String stageName) { - TrimExceptionMessage trimExceptionMessage = new TrimExceptionMessage(); - String registrationId = object.getRid(); - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - registrationId, "BioDedupeProcessor::process::entry"); - LogDescription description = new LogDescription(); - object.setMessageBusAddress(MessageBusAddress.BIO_DEDUPE_BUS_IN); - object.setInternalError(Boolean.FALSE); - object.setIsValid(Boolean.FALSE); - - boolean isTransactionSuccessful = false; - - boolean isDuplicateRequestForSameTransactionId = false; - - InternalRegistrationStatusDto registrationStatusDto = new InternalRegistrationStatusDto(); - try { - registrationStatusDto = registrationStatusService.getRegistrationStatus( - registrationId, object.getReg_type(), object.getIteration(), object.getWorkflowInstanceId()); - String registrationType = registrationStatusDto.getRegistrationType(); - if (registrationType.equalsIgnoreCase(SyncTypeDto.NEW.toString()) - || (subProcesses != null && subProcesses.contains(registrationType))) { - String packetStatus = abisHandlerUtil.getPacketStatus(registrationStatusDto); - if (packetStatus.equalsIgnoreCase(AbisConstant.PRE_ABIS_IDENTIFICATION)) { - newPacketPreAbisIdentification(registrationStatusDto, object); - } else if (packetStatus.equalsIgnoreCase(AbisConstant.POST_ABIS_IDENTIFICATION)) { - postAbisIdentification(registrationStatusDto, object, registrationType); - - } - - } else if (registrationType.equalsIgnoreCase(SyncTypeDto.UPDATE.toString()) - || registrationType.equalsIgnoreCase(SyncTypeDto.RES_UPDATE.toString())) { - String packetStatus = abisHandlerUtil.getPacketStatus(registrationStatusDto); - if (packetStatus.equalsIgnoreCase(AbisConstant.PRE_ABIS_IDENTIFICATION)) { - updatePacketPreAbisIdentification(registrationStatusDto, object); - } else if (packetStatus.equalsIgnoreCase(AbisConstant.POST_ABIS_IDENTIFICATION)) { - postAbisIdentification(registrationStatusDto, object, registrationType); - } - - } else if (registrationType.equalsIgnoreCase(SyncTypeDto.LOST.toString()) - && isValidCbeff(object)) { - String packetStatus = abisHandlerUtil.getPacketStatus(registrationStatusDto); - - if (packetStatus.equalsIgnoreCase(AbisConstant.PRE_ABIS_IDENTIFICATION)) { - lostPacketPreAbisIdentification(registrationStatusDto, object); - } else if (packetStatus.equalsIgnoreCase(AbisConstant.POST_ABIS_IDENTIFICATION)) { - Set matchedRegIds = abisHandlerUtil - .getUniqueRegIds(registrationStatusDto.getRegistrationId(), - registrationType, object.getIteration(), object.getWorkflowInstanceId(), ProviderStageName.BIO_DEDUPE); - lostPacketPostAbisIdentification(registrationStatusDto, object, matchedRegIds); - } - - } - - if (abisHandlerUtil.getPacketStatus(registrationStatusDto).equalsIgnoreCase(AbisConstant.DUPLICATE_FOR_SAME_TRANSACTION_ID)) - isDuplicateRequestForSameTransactionId = true; - - registrationStatusDto.setRegistrationStageName(stageName); - isTransactionSuccessful = true; - - } catch (DataAccessException e) { - registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.name()); - registrationStatusDto.setStatusComment(trimExceptionMessage - .trimExceptionMessage(StatusUtil.DB_NOT_ACCESSIBLE.getMessage() + e.getMessage())); - registrationStatusDto.setSubStatusCode(StatusUtil.DB_NOT_ACCESSIBLE.getCode()); - registrationStatusDto.setLatestTransactionStatusCode( - registrationExceptionMapperUtil.getStatusCode(RegistrationExceptionTypeCode.DATA_ACCESS_EXCEPTION)); - description.setCode(PlatformErrorMessages.PACKET_BIO_DEDUPE_FAILED.getCode()); - description.setMessage(PlatformErrorMessages.PACKET_BIO_DEDUPE_FAILED.getMessage()); - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), - description.getCode() + " -- " + LoggerFileConstant.REGISTRATIONID.toString(), registrationId, - description.getMessage() + "\n" + ExceptionUtils.getStackTrace(e)); - object.setInternalError(Boolean.TRUE); - } catch (ApisResourceAccessException e) { - registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.name()); - registrationStatusDto.setStatusComment( - trimExceptionMessage.trimExceptionMessage(StatusUtil.API_RESOUCE_ACCESS_FAILED + e.getMessage())); - registrationStatusDto.setSubStatusCode(StatusUtil.API_RESOUCE_ACCESS_FAILED.getCode()); - registrationStatusDto.setLatestTransactionStatusCode(registrationExceptionMapperUtil - .getStatusCode(RegistrationExceptionTypeCode.APIS_RESOURCE_ACCESS_EXCEPTION)); - description.setCode(PlatformErrorMessages.RPR_BIO_API_RESOUCE_ACCESS_FAILED.getCode()); - description.setMessage(PlatformErrorMessages.RPR_BIO_API_RESOUCE_ACCESS_FAILED.getMessage()); - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), - description.getCode() + " -- " + LoggerFileConstant.REGISTRATIONID.toString(), registrationId, - description + "\n" + ExceptionUtils.getStackTrace(e)); - object.setInternalError(Boolean.TRUE); - } catch (CbeffNotFoundException ex) { - registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.name()); - registrationStatusDto.setStatusComment(StatusUtil.CBEF_NOT_FOUND.getMessage()); - registrationStatusDto.setSubStatusCode(StatusUtil.CBEF_NOT_FOUND.getCode()); - registrationStatusDto.setLatestTransactionStatusCode(registrationExceptionMapperUtil - .getStatusCode(RegistrationExceptionTypeCode.CBEFF_NOT_PRESENT_EXCEPTION)); - description.setCode(PlatformErrorMessages.PACKET_BIO_DEDUPE_FAILED.getCode()); - description.setMessage(PlatformErrorMessages.PACKET_BIO_DEDUPE_FAILED.getMessage()); - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), - description.getCode() + " -- " + LoggerFileConstant.REGISTRATIONID.toString(), registrationId, - description.getMessage() + "\n" + ExceptionUtils.getStackTrace(ex)); - object.setInternalError(Boolean.TRUE); - } catch (IdentityNotFoundException | IOException ex) { - registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.name()); - registrationStatusDto.setStatusComment(trimExceptionMessage - .trimExceptionMessage(StatusUtil.SYSTEM_EXCEPTION_OCCURED.getMessage() + ex.getMessage())); - registrationStatusDto.setSubStatusCode(StatusUtil.SYSTEM_EXCEPTION_OCCURED.getCode()); - registrationStatusDto.setLatestTransactionStatusCode( - registrationExceptionMapperUtil.getStatusCode(RegistrationExceptionTypeCode.IOEXCEPTION)); - description.setCode(PlatformErrorMessages.PACKET_BIO_DEDUPE_FAILED.getCode()); - description.setMessage(PlatformErrorMessages.PACKET_BIO_DEDUPE_FAILED.getMessage()); - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), - description.getCode() + " -- " + LoggerFileConstant.REGISTRATIONID.toString(), registrationId, - description.getMessage() + "\n" + ExceptionUtils.getStackTrace(ex)); - object.setInternalError(Boolean.TRUE); - } catch (Exception ex) { - registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.name()); - registrationStatusDto.setStatusComment(trimExceptionMessage - .trimExceptionMessage(StatusUtil.UNKNOWN_EXCEPTION_OCCURED.getMessage() + ex.getMessage())); - registrationStatusDto.setSubStatusCode(StatusUtil.UNKNOWN_EXCEPTION_OCCURED.getCode()); - registrationStatusDto.setLatestTransactionStatusCode( - registrationExceptionMapperUtil.getStatusCode(RegistrationExceptionTypeCode.EXCEPTION)); - description.setCode(PlatformErrorMessages.PACKET_BIO_DEDUPE_FAILED.getCode()); - description.setMessage(PlatformErrorMessages.PACKET_BIO_DEDUPE_FAILED.getMessage()); - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), - description.getCode() + " -- " + LoggerFileConstant.REGISTRATIONID.toString(), registrationId, - description.getMessage() + "\n" + ExceptionUtils.getStackTrace(ex)); - object.setInternalError(Boolean.TRUE); - } finally { - if (!isDuplicateRequestForSameTransactionId) { - if (object.getInternalError()) { - updateErrorFlags(registrationStatusDto, object); - } - registrationStatusDto - .setLatestTransactionTypeCode(RegistrationTransactionTypeCode.BIOGRAPHIC_VERIFICATION.toString()); - String moduleId = isTransactionSuccessful ? PlatformSuccessMessages.RPR_BIO_DEDUPE_SUCCESS.getCode() - : description.getCode(); - String moduleName = ModuleName.BIO_DEDUPE.name(); - registrationStatusService.updateRegistrationStatus(registrationStatusDto, moduleId, moduleName); - - regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - registrationId, "BioDedupeProcessor::" + registrationStatusDto.getLatestTransactionStatusCode()); - - String eventId = isTransactionSuccessful ? EventId.RPR_402.toString() : EventId.RPR_405.toString(); - String eventName = isTransactionSuccessful ? EventName.UPDATE.toString() : EventName.EXCEPTION.toString(); - String eventType = isTransactionSuccessful ? EventType.BUSINESS.toString() : EventType.SYSTEM.toString(); - - auditLogRequestBuilder.createAuditRequestBuilder(description.getMessage(), eventId, eventName, eventType, - moduleId, moduleName, registrationId); - } else { - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - registrationId, "Duplicate request received for same latest transaction id. This will be ignored."); - object.setIsValid(false); - object.setInternalError(true); - } - } - return object; - } - - /** - * New packet pre abis identification. - * - * @param registrationStatusDto the registration status dto - * @param object the object - * @throws ApisResourceAccessException the apis resource access - * exception - * @throws IOException Signals that an I/O exception - * has occurred. - * @throws io.mosip.kernel.core.exception.IOException - * @throws PacketDecryptionFailureException - * @throws RegistrationProcessorCheckedException RegistrationProcessorCheckedException - */ - private void newPacketPreAbisIdentification(InternalRegistrationStatusDto registrationStatusDto, MessageDTO object) - throws ApisResourceAccessException, IOException, JsonProcessingException, PacketManagerException { - if (isValidCbeff(object)) { - object.setIsValid(Boolean.TRUE); - registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); - registrationStatusDto.setStatusComment(StatusUtil.BIO_DEDUPE_INPROGRESS.getMessage()); - registrationStatusDto.setSubStatusCode(StatusUtil.BIO_DEDUPE_INPROGRESS.getCode()); - registrationStatusDto - .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.IN_PROGRESS.toString()); - object.setMessageBusAddress(MessageBusAddress.ABIS_HANDLER_BUS_IN); - regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - registrationStatusDto.getRegistrationId(), BioDedupeConstants.CBEFF_PRESENT_IN_PACKET); - } else { - if (object.getMessageBusAddress() == MessageBusAddress.VERIFICATION_BUS_IN) { - object.setIsValid(Boolean.TRUE); - registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); - registrationStatusDto.setStatusComment(StatusUtil.BIO_DEDUPE_INPROGRESS.getMessage()); - registrationStatusDto.setSubStatusCode(StatusUtil.BIO_DEDUPE_INPROGRESS.getCode()); - registrationStatusDto - .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.IN_PROGRESS.toString()); - registrationStatusDto.setStatusComment(BioDedupeConstants.CBEFF_NOT_PRESENT_IN_PACKET); - regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - registrationStatusDto.getRegistrationId(), BioDedupeConstants.CBEFF_NOT_PRESENT_IN_PACKET); - } else { - registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.name()); - registrationStatusDto.setStatusComment(StatusUtil.BIO_DEDUPE_SUCCESS.getMessage()); - registrationStatusDto.setSubStatusCode(StatusUtil.BIO_DEDUPE_SUCCESS.getCode()); - registrationStatusDto.setLatestTransactionStatusCode(RegistrationTransactionStatusCode.SUCCESS.toString()); - object.setIsValid(Boolean.TRUE); - regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - registrationStatusDto.getRegistrationId(), BioDedupeConstants.CBEFF_ABSENT_IN_PACKET); - } - } - } - - /** - * Update packet pre abis identification. - * - * @param registrationStatusDto the registration status dto - * @param object the object - * @throws IOException Signals that an I/O exception - * has occurred. - * @throws io.mosip.kernel.core.exception.IOException - * @throws ApisResourceAccessException - * @throws PacketManagerException PacketManagerException - * @throws RegistrationProcessorCheckedException - */ - private void updatePacketPreAbisIdentification(InternalRegistrationStatusDto registrationStatusDto, - MessageDTO object) throws IOException, ApisResourceAccessException, PacketManagerException, JsonProcessingException { - - String bioField = priorityBasedPacketManagerService.getFieldByMappingJsonKey(registrationStatusDto.getRegistrationId(), - MappingJsonConstants.INDIVIDUAL_BIOMETRICS, registrationStatusDto.getRegistrationType(), ProviderStageName.BIO_DEDUPE); - - if (StringUtils.isNotEmpty(bioField) && isValidCbeff(object)) { - object.setIsValid(Boolean.TRUE); - registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); - registrationStatusDto.setStatusComment(StatusUtil.BIO_DEDUPE_INPROGRESS.getMessage()); - registrationStatusDto.setSubStatusCode(StatusUtil.BIO_DEDUPE_INPROGRESS.getCode()); - registrationStatusDto - .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.IN_PROGRESS.toString()); - object.setMessageBusAddress(MessageBusAddress.ABIS_HANDLER_BUS_IN); - - regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - registrationStatusDto.getRegistrationId(), BioDedupeConstants.UPDATE_PACKET_BIOMETRIC_NOT_NULL); - } else { - registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.name()); - registrationStatusDto.setStatusComment(StatusUtil.BIO_DEDUPE_SUCCESS.getMessage()); - registrationStatusDto.setSubStatusCode(StatusUtil.BIO_DEDUPE_SUCCESS.getCode()); - registrationStatusDto.setLatestTransactionStatusCode(RegistrationTransactionStatusCode.SUCCESS.toString()); - object.setIsValid(Boolean.TRUE); - - regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - registrationStatusDto.getRegistrationId(), BioDedupeConstants.UPDATE_PACKET_BIOMETRIC_NULL); - } - } - - /** - * Post abis identification. - * - * @param registrationStatusDto the registration status dto - * @param object the object - * @param registrationType the registration type - * @throws ApisResourceAccessException the apis resource access - * exception - * @throws IOException Signals that an I/O exception - * has occurred. - * @throws io.mosip.kernel.core.exception.IOException - * @throws PacketDecryptionFailureException - * @throws RegistrationProcessorCheckedException RegistrationProcessorCheckedException - */ - private void postAbisIdentification(InternalRegistrationStatusDto registrationStatusDto, MessageDTO object, - String registrationType) throws ApisResourceAccessException, IOException, - io.mosip.kernel.core.exception.IOException, JsonProcessingException, PacketManagerException { - String moduleId = ""; - String moduleName = ModuleName.BIO_DEDUPE.toString(); - Set matchedRegIds = abisHandlerUtil.getUniqueRegIds(registrationStatusDto.getRegistrationId(), - registrationType, registrationStatusDto.getIteration(), registrationStatusDto.getWorkflowInstanceId(), ProviderStageName.BIO_DEDUPE); - ArrayList matchedRegIdsList = new ArrayList(matchedRegIds); - // TODO : temporary fix. Need to analyze more. - if (matchedRegIds != null && !matchedRegIds.isEmpty() - && matchedRegIds.contains(registrationStatusDto.getRegistrationId())) { - matchedRegIds.remove(registrationStatusDto.getRegistrationId()); - matchedRegIdsList.remove(registrationStatusDto.getRegistrationId()); - } - if (matchedRegIds == null || matchedRegIds.isEmpty()) { - registrationStatusDto.setLatestTransactionStatusCode(RegistrationTransactionStatusCode.SUCCESS.toString()); - object.setIsValid(Boolean.TRUE); - registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.name()); - registrationStatusDto.setStatusComment(StatusUtil.BIO_DEDUPE_SUCCESS.getMessage()); - registrationStatusDto.setSubStatusCode(StatusUtil.BIO_DEDUPE_SUCCESS.getCode()); - regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - registrationStatusDto.getRegistrationId(), BioDedupeConstants.ABIS_RESPONSE_NULL); - - } else { - registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.name()); - registrationStatusDto.setStatusComment(StatusUtil.BIO_DEDUPE_POTENTIAL_MATCH.getMessage()); - registrationStatusDto.setSubStatusCode(StatusUtil.BIO_DEDUPE_POTENTIAL_MATCH.getCode()); - registrationStatusDto.setLatestTransactionStatusCode(RegistrationTransactionStatusCode.FAILED.toString()); - moduleId = PlatformSuccessMessages.RPR_BIO_METRIC_POTENTIAL_MATCH.getCode(); - packetInfoManager.saveManualAdjudicationData(matchedRegIds, object, - DedupeSourceName.BIO, moduleId, moduleName,null,null); - //send message to manual adjudication - object.setInternalError(Boolean.FALSE); - object.setRid(registrationStatusDto.getRegistrationId()); - object.setIsValid(Boolean.TRUE); - object.setReg_type(registrationType); - object.setMessageBusAddress(MessageBusAddress.MANUAL_ADJUDICATION_BUS_IN); - - regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - registrationStatusDto.getRegistrationId(), BioDedupeConstants.ABIS_RESPONSE_NOT_NULL); - - } - } - - /** - * Checks if is valid cbeff. - * - * @param messageDTO the messageDTO - * @return the boolean - * @throws ApisResourceAccessException the apis resource access - * exception - * @throws IOException Signals that an I/O exception - * has occurred. - * @throws io.mosip.kernel.core.exception.IOException - * @throws PacketDecryptionFailureException - * @throws RegistrationProcessorCheckedException RegistrationProcessorCheckedException - */ - private Boolean isValidCbeff(MessageDTO messageDTO) throws ApisResourceAccessException, - IOException, JsonProcessingException, PacketManagerException { - String id = messageDTO.getRid(); - String process = messageDTO.getReg_type(); - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - id, "BioDedupeProcessor::isValidCbeff()::get BIODEDUPE service call started"); - boolean isInfant = infantCheck(id, process); - try { - if (isInfant) - if (infantDedupe.equalsIgnoreCase(GLOBAL_CONFIG_TRUE_VALUE)) - cbeffValidateAndVerificatonService.validateBiometrics(id, process); - else - return false; - else - cbeffValidateAndVerificatonService.validateBiometrics(id, process); - } catch (CbeffNotFoundException e) { - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), - LoggerFileConstant.REGISTRATIONID.toString(), id, ExceptionUtils.getStackTrace(e)); - messageDTO.setMessageBusAddress(MessageBusAddress.VERIFICATION_BUS_IN); - return false; - } - return true; - - } - - private boolean infantCheck(String registrationId, String registrationType) throws ApisResourceAccessException, JsonProcessingException, PacketManagerException, IOException { - boolean isInfant = false; - if (RegistrationType.NEW.name().equalsIgnoreCase(registrationType)) { - int age = utilities.getApplicantAge(registrationId, registrationType, ProviderStageName.BIO_DEDUPE); - int ageThreshold = Integer.parseInt(ageLimit); - isInfant = age < ageThreshold; - } else { - isInfant = false; - } - return isInfant; - } - - private void lostPacketPreAbisIdentification(InternalRegistrationStatusDto registrationStatusDto, - MessageDTO object) { - - object.setIsValid(Boolean.TRUE); - registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); - registrationStatusDto.setStatusComment(StatusUtil.BIO_DEDUPE_INPROGRESS.getMessage()); - registrationStatusDto.setSubStatusCode(StatusUtil.BIO_DEDUPE_INPROGRESS.getCode()); - registrationStatusDto.setLatestTransactionStatusCode(RegistrationTransactionStatusCode.IN_PROGRESS.toString()); - object.setMessageBusAddress(MessageBusAddress.ABIS_HANDLER_BUS_IN); - - regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - registrationStatusDto.getRegistrationId(), BioDedupeConstants.LOST_PRE_ABIS_IDENTITIFICATION); - - } - - private void lostPacketPostAbisIdentification(InternalRegistrationStatusDto registrationStatusDto, - MessageDTO object, Set matchedRegIds) throws IOException, ApisResourceAccessException, JsonProcessingException, PacketManagerException { - String moduleId = ""; - String moduleName = ModuleName.BIO_DEDUPE.toString(); - String registrationId = registrationStatusDto.getRegistrationId(); - if (matchedRegIds.isEmpty()) { - registrationStatusDto.setLatestTransactionStatusCode(RegistrationTransactionStatusCode.FAILED.toString()); - object.setIsValid(Boolean.FALSE); - registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.name()); - registrationStatusDto.setStatusComment(StatusUtil.LOST_PACKET_BIOMETRICS_NOT_FOUND.getMessage()); - registrationStatusDto.setSubStatusCode(StatusUtil.LOST_PACKET_BIOMETRICS_NOT_FOUND.getCode()); - regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - registrationStatusDto.getRegistrationId(), - BioDedupeConstants.NO_MATCH_FOUND_FOR_LOST + registrationId); - - } else if (matchedRegIds.size() == 1) { - - registrationStatusDto.setLatestTransactionStatusCode(RegistrationTransactionStatusCode.SUCCESS.toString()); - object.setIsValid(Boolean.TRUE); - registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.name()); - registrationStatusDto.setStatusComment(StatusUtil.LOST_PACKET_UNIQUE_MATCH_FOUND.getMessage()); - registrationStatusDto.setSubStatusCode(StatusUtil.LOST_PACKET_UNIQUE_MATCH_FOUND.getCode()); - moduleId = PlatformSuccessMessages.RPR_BIO_LOST_PACKET_UNIQUE_MATCH_FOUND.getCode(); - packetInfoManager.saveRegLostUinDet(registrationId, - object.getWorkflowInstanceId(), matchedRegIds.iterator().next(), moduleId, moduleName); - regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - registrationStatusDto.getRegistrationId(), - BioDedupeConstants.FOUND_UIN_IN_BIO_CHECK + registrationId); - - } else { - - List demoMatchedIds = new ArrayList<>(); - int matchCount = 0; - - for (String matchedRegId : matchedRegIds) { - JSONObject matchedDemographicIdentity = idRepoService.getIdJsonFromIDRepo(matchedRegId, - utilities.getGetRegProcessorDemographicIdentity()); - matchCount = addMactchedRefId(registrationStatusDto.getRegistrationId(), - registrationStatusDto.getRegistrationType(), matchedDemographicIdentity, matchCount, demoMatchedIds, matchedRegId); - if (matchCount > 1) - break; - } - - if (matchCount == 1) { - - registrationStatusDto - .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.SUCCESS.toString()); - object.setIsValid(Boolean.TRUE); - registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.name()); - registrationStatusDto.setStatusComment(StatusUtil.LOST_PACKET_UNIQUE_MATCH_FOUND.getMessage()); - registrationStatusDto.setSubStatusCode(StatusUtil.LOST_PACKET_UNIQUE_MATCH_FOUND.getCode()); - moduleId = PlatformSuccessMessages.RPR_BIO_LOST_PACKET_UNIQUE_MATCH_FOUND.getCode(); - packetInfoManager.saveRegLostUinDet(registrationId, - object.getWorkflowInstanceId(), demoMatchedIds.get(0), moduleId, moduleName); - regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), - LoggerFileConstant.REGISTRATIONID.toString(), registrationStatusDto.getRegistrationId(), - BioDedupeConstants.FOUND_UIN_IN_DEMO_CHECK + registrationId); - } else { - - registrationStatusDto.setStatusComment(StatusUtil.LOST_PACKET_MULTIPLE_MATCH_FOUND.getMessage()); - registrationStatusDto.setSubStatusCode(StatusUtil.LOST_PACKET_MULTIPLE_MATCH_FOUND.getCode()); - registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.name()); - registrationStatusDto - .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.FAILED.toString()); - - regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), - LoggerFileConstant.REGISTRATIONID.toString(), registrationStatusDto.getRegistrationId(), - BioDedupeConstants.MULTIPLE_RID_FOUND); - moduleId = PlatformErrorMessages.RPR_BIO_LOST_PACKET_MULTIPLE_MATCH_FOUND.getCode(); - packetInfoManager.saveManualAdjudicationData(matchedRegIds, - object, DedupeSourceName.BIO, moduleId, moduleName,null,null); - } - } - } - - private int addMactchedRefId(String id, String process, JSONObject matchedDemographicIdentity, int matchCount, List demoMatchedIds, - String matchedRegId) throws IOException, ApisResourceAccessException, PacketManagerException, JsonProcessingException { - if (matchedDemographicIdentity != null) { - Map matchedAttribute = getIdJson(matchedDemographicIdentity); - if (!matchedAttribute.isEmpty()) { - if (compareDemoDedupe(id, process, matchedAttribute)) { - matchCount++; - demoMatchedIds.add(matchedRegId); - } - - } - } - return matchCount; - } - - private boolean compareDemoDedupe(String id, String process, Map matchedAttribute) throws ApisResourceAccessException, IOException, PacketManagerException, JsonProcessingException { - boolean isMatch = false; - - for (String key : matchedAttribute.keySet()) { - String value = priorityBasedPacketManagerService.getField(id, key, process, ProviderStageName.BIO_DEDUPE); - if (value != null && value.equalsIgnoreCase(matchedAttribute.get(key))) { - isMatch = true; - } else { - isMatch = false; - return isMatch; - } - - } - return isMatch; - } - - private Map getIdJson(JSONObject demographicJsonIdentity) throws IOException { - Map attribute = new LinkedHashMap<>(); - - - JSONObject mapperIdentity = new JSONObject(); - mapperIdentity.putAll(utilities.getRegistrationProcessorMappingJson(MappingJsonConstants.IDENTITY)); - mapperIdentity.putAll(utilities.getRegistrationProcessorMappingJson(MappingJsonConstants.DOCUMENT)); - - - List mapperJsonKeys = new ArrayList<>(mapperIdentity.keySet()); - - for (String key : mapperJsonKeys) { - JSONObject jsonValue = JsonUtil.getJSONObject(mapperIdentity, key); - Object jsonObject = JsonUtil.getJSONValue(demographicJsonIdentity, - (String) jsonValue.get(BioDedupeConstants.VALUE)); - if (jsonObject instanceof ArrayList) { - JSONArray node = JsonUtil.getJSONArray(demographicJsonIdentity, - (String) jsonValue.get(BioDedupeConstants.VALUE)); - JsonValue[] jsonValues = JsonUtil.mapJsonNodeToJavaObject(JsonValue.class, node); - if (jsonValues != null) - for (int count = 0; count < jsonValues.length; count++) { - String lang = jsonValues[count].getLanguage(); - attribute.put(key + "_" + lang, jsonValues[count].getValue()); - } - - } else if (jsonObject instanceof LinkedHashMap) { - JSONObject json = JsonUtil.getJSONObject(demographicJsonIdentity, - (String) jsonValue.get(BioDedupeConstants.VALUE)); - if (json != null) - attribute.put(key, json.get(BioDedupeConstants.VALUE).toString()); - } else { - if (jsonObject != null) - attribute.put(key, jsonObject.toString()); - } - } - - return attribute; - } - - private void updateErrorFlags(InternalRegistrationStatusDto registrationStatusDto, MessageDTO object) { - object.setInternalError(true); - if (registrationStatusDto.getLatestTransactionStatusCode() - .equalsIgnoreCase(RegistrationTransactionStatusCode.REPROCESS.toString())) { - object.setIsValid(true); - } else { - object.setIsValid(false); - } - } +package io.mosip.registration.processor.biodedupe.stage; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.apache.commons.lang3.exception.ExceptionUtils; +import org.json.simple.JSONArray; +import org.json.simple.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 io.mosip.kernel.core.logger.spi.Logger; +import io.mosip.kernel.core.util.StringUtils; +import io.mosip.kernel.core.util.exception.JsonProcessingException; +import io.mosip.registration.processor.biodedupe.constants.BioDedupeConstants; +import io.mosip.registration.processor.biodedupe.service.CbeffValidateAndVerificatonService; +import io.mosip.registration.processor.biodedupe.stage.exception.CbeffNotFoundException; +import io.mosip.registration.processor.core.abstractverticle.MessageBusAddress; +import io.mosip.registration.processor.core.abstractverticle.MessageDTO; +import io.mosip.registration.processor.core.code.DedupeSourceName; +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.AbisConstant; +import io.mosip.registration.processor.core.constant.LoggerFileConstant; +import io.mosip.registration.processor.core.constant.MappingJsonConstants; +import io.mosip.registration.processor.core.constant.ProviderStageName; +import io.mosip.registration.processor.core.constant.RegistrationType; +import io.mosip.registration.processor.core.exception.ApisResourceAccessException; +import io.mosip.registration.processor.core.exception.PacketDecryptionFailureException; +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.Identity; +import io.mosip.registration.processor.core.packet.dto.demographicinfo.JsonValue; +import io.mosip.registration.processor.core.spi.biodedupe.BioDedupeService; +import io.mosip.registration.processor.core.spi.packetmanager.PacketInfoManager; +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.idreposervice.IdRepoService; +import io.mosip.registration.processor.packet.storage.dto.ApplicantInfoDto; +import io.mosip.registration.processor.packet.storage.exception.IdentityNotFoundException; +import io.mosip.registration.processor.packet.storage.utils.ABISHandlerUtil; +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.dto.SyncTypeDto; +import io.mosip.registration.processor.status.service.RegistrationStatusService; + +/** + * The Class BioDedupeProcessor. + * + * @author Nagalakshmi + * @author Sowmya + * @author Horteppa + */ + +@Service +@Transactional +public class BioDedupeProcessor { + + /** The utilities. */ + @Autowired + Utilities utilities; + + @Autowired + private IdRepoService idRepoService; + + @Value("#{'${registration.processor.sub-processes}'.split(',')}") + private List subProcesses; + + @Autowired + private CbeffValidateAndVerificatonService cbeffValidateAndVerificatonService; + + @Autowired + private PriorityBasedPacketManagerService priorityBasedPacketManagerService; + + /** The packet info manager. */ + @Autowired + private PacketInfoManager packetInfoManager; + + /** The registration status service. */ + @Autowired + private RegistrationStatusService registrationStatusService; + + /** The core audit request builder. */ + @Autowired + private AuditLogRequestBuilder auditLogRequestBuilder; + + /** The registration exception mapper util. */ + @Autowired + RegistrationExceptionMapperUtil registrationExceptionMapperUtil; + + /** The abis handler util. */ + @Autowired + private ABISHandlerUtil abisHandlerUtil; + + @Autowired + private BioDedupeService biodedupeServiceImpl; + + /** The config server file storage URL. */ + @Value("${config.server.file.storage.uri}") + private String configServerFileStorageURL; + + /** The get reg processor identity json. */ + @Value("${registration.processor.identityjson}") + private String getRegProcessorIdentityJson; + + /** The age limit. */ + @Value("${mosip.kernel.applicant.type.age.limit}") + private String ageLimit; + + @Value("${registration.processor.missing.biometric.verification.enabled:true}") + private boolean missingBiometricVerificationEnabled; + + /** The reg proc logger. */ + private static Logger regProcLogger = RegProcessorLogger.getLogger(BioDedupeProcessor.class); + + + + @Value("${registration.processor.infant.dedupe}") + private String infantDedupe; + + public static final String GLOBAL_CONFIG_TRUE_VALUE = "Y"; + + + + + /** + * Process. + * + * @param object + * the object + * @param stageName + * the stage name + * @return the message DTO + */ + public MessageDTO process(MessageDTO object, String stageName) { + TrimExceptionMessage trimExceptionMessage = new TrimExceptionMessage(); + String registrationId = object.getRid(); + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + registrationId, "BioDedupeProcessor::process::entry"); + LogDescription description = new LogDescription(); + object.setMessageBusAddress(MessageBusAddress.BIO_DEDUPE_BUS_IN); + object.setInternalError(Boolean.FALSE); + object.setIsValid(Boolean.FALSE); + + boolean isTransactionSuccessful = false; + + boolean isDuplicateRequestForSameTransactionId = false; + + InternalRegistrationStatusDto registrationStatusDto = new InternalRegistrationStatusDto(); + try { + registrationStatusDto = registrationStatusService.getRegistrationStatus( + registrationId, object.getReg_type(), object.getIteration(), object.getWorkflowInstanceId()); + String registrationType = registrationStatusDto.getRegistrationType(); + if (registrationType.equalsIgnoreCase(SyncTypeDto.NEW.toString()) + || (subProcesses != null && subProcesses.contains(registrationType))) { + String packetStatus = abisHandlerUtil.getPacketStatus(registrationStatusDto); + if (packetStatus.equalsIgnoreCase(AbisConstant.PRE_ABIS_IDENTIFICATION)) { + newPacketPreAbisIdentification(registrationStatusDto, object); + } else if (packetStatus.equalsIgnoreCase(AbisConstant.POST_ABIS_IDENTIFICATION)) { + postAbisIdentification(registrationStatusDto, object, registrationType); + + } + + } else if (registrationType.equalsIgnoreCase(SyncTypeDto.UPDATE.toString()) + || registrationType.equalsIgnoreCase(SyncTypeDto.RES_UPDATE.toString())) { + String packetStatus = abisHandlerUtil.getPacketStatus(registrationStatusDto); + if (packetStatus.equalsIgnoreCase(AbisConstant.PRE_ABIS_IDENTIFICATION)) { + updatePacketPreAbisIdentification(registrationStatusDto, object); + } else if (packetStatus.equalsIgnoreCase(AbisConstant.POST_ABIS_IDENTIFICATION)) { + postAbisIdentification(registrationStatusDto, object, registrationType); + } + + } else if (registrationType.equalsIgnoreCase(SyncTypeDto.LOST.toString()) + && isValidCbeff(object)) { + String packetStatus = abisHandlerUtil.getPacketStatus(registrationStatusDto); + + if (packetStatus.equalsIgnoreCase(AbisConstant.PRE_ABIS_IDENTIFICATION)) { + lostPacketPreAbisIdentification(registrationStatusDto, object); + } else if (packetStatus.equalsIgnoreCase(AbisConstant.POST_ABIS_IDENTIFICATION)) { + Set matchedRegIds = abisHandlerUtil + .getUniqueRegIds(registrationStatusDto.getRegistrationId(), + registrationType, object.getIteration(), object.getWorkflowInstanceId(), ProviderStageName.BIO_DEDUPE); + lostPacketPostAbisIdentification(registrationStatusDto, object, matchedRegIds); + } + + } + + if (abisHandlerUtil.getPacketStatus(registrationStatusDto).equalsIgnoreCase(AbisConstant.DUPLICATE_FOR_SAME_TRANSACTION_ID)) + isDuplicateRequestForSameTransactionId = true; + + registrationStatusDto.setRegistrationStageName(stageName); + isTransactionSuccessful = true; + + } catch (DataAccessException e) { + registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.name()); + registrationStatusDto.setStatusComment(trimExceptionMessage + .trimExceptionMessage(StatusUtil.DB_NOT_ACCESSIBLE.getMessage() + e.getMessage())); + registrationStatusDto.setSubStatusCode(StatusUtil.DB_NOT_ACCESSIBLE.getCode()); + registrationStatusDto.setLatestTransactionStatusCode( + registrationExceptionMapperUtil.getStatusCode(RegistrationExceptionTypeCode.DATA_ACCESS_EXCEPTION)); + description.setCode(PlatformErrorMessages.PACKET_BIO_DEDUPE_FAILED.getCode()); + description.setMessage(PlatformErrorMessages.PACKET_BIO_DEDUPE_FAILED.getMessage()); + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), + description.getCode() + " -- " + LoggerFileConstant.REGISTRATIONID.toString(), registrationId, + description.getMessage() + "\n" + ExceptionUtils.getStackTrace(e)); + object.setInternalError(Boolean.TRUE); + } catch (ApisResourceAccessException e) { + registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.name()); + registrationStatusDto.setStatusComment( + trimExceptionMessage.trimExceptionMessage(StatusUtil.API_RESOUCE_ACCESS_FAILED + e.getMessage())); + registrationStatusDto.setSubStatusCode(StatusUtil.API_RESOUCE_ACCESS_FAILED.getCode()); + registrationStatusDto.setLatestTransactionStatusCode(registrationExceptionMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.APIS_RESOURCE_ACCESS_EXCEPTION)); + description.setCode(PlatformErrorMessages.RPR_BIO_API_RESOUCE_ACCESS_FAILED.getCode()); + description.setMessage(PlatformErrorMessages.RPR_BIO_API_RESOUCE_ACCESS_FAILED.getMessage()); + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), + description.getCode() + " -- " + LoggerFileConstant.REGISTRATIONID.toString(), registrationId, + description + "\n" + ExceptionUtils.getStackTrace(e)); + object.setInternalError(Boolean.TRUE); + } catch (CbeffNotFoundException ex) { + registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.name()); + registrationStatusDto.setStatusComment(StatusUtil.CBEF_NOT_FOUND.getMessage()); + registrationStatusDto.setSubStatusCode(StatusUtil.CBEF_NOT_FOUND.getCode()); + registrationStatusDto.setLatestTransactionStatusCode(registrationExceptionMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.CBEFF_NOT_PRESENT_EXCEPTION)); + description.setCode(PlatformErrorMessages.PACKET_BIO_DEDUPE_FAILED.getCode()); + description.setMessage(PlatformErrorMessages.PACKET_BIO_DEDUPE_FAILED.getMessage()); + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), + description.getCode() + " -- " + LoggerFileConstant.REGISTRATIONID.toString(), registrationId, + description.getMessage() + "\n" + ExceptionUtils.getStackTrace(ex)); + object.setInternalError(Boolean.TRUE); + } catch (IdentityNotFoundException | IOException ex) { + registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.name()); + registrationStatusDto.setStatusComment(trimExceptionMessage + .trimExceptionMessage(StatusUtil.SYSTEM_EXCEPTION_OCCURED.getMessage() + ex.getMessage())); + registrationStatusDto.setSubStatusCode(StatusUtil.SYSTEM_EXCEPTION_OCCURED.getCode()); + registrationStatusDto.setLatestTransactionStatusCode( + registrationExceptionMapperUtil.getStatusCode(RegistrationExceptionTypeCode.IOEXCEPTION)); + description.setCode(PlatformErrorMessages.PACKET_BIO_DEDUPE_FAILED.getCode()); + description.setMessage(PlatformErrorMessages.PACKET_BIO_DEDUPE_FAILED.getMessage()); + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), + description.getCode() + " -- " + LoggerFileConstant.REGISTRATIONID.toString(), registrationId, + description.getMessage() + "\n" + ExceptionUtils.getStackTrace(ex)); + object.setInternalError(Boolean.TRUE); + } catch (Exception ex) { + registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.name()); + registrationStatusDto.setStatusComment(trimExceptionMessage + .trimExceptionMessage(StatusUtil.UNKNOWN_EXCEPTION_OCCURED.getMessage() + ex.getMessage())); + registrationStatusDto.setSubStatusCode(StatusUtil.UNKNOWN_EXCEPTION_OCCURED.getCode()); + registrationStatusDto.setLatestTransactionStatusCode( + registrationExceptionMapperUtil.getStatusCode(RegistrationExceptionTypeCode.EXCEPTION)); + description.setCode(PlatformErrorMessages.PACKET_BIO_DEDUPE_FAILED.getCode()); + description.setMessage(PlatformErrorMessages.PACKET_BIO_DEDUPE_FAILED.getMessage()); + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), + description.getCode() + " -- " + LoggerFileConstant.REGISTRATIONID.toString(), registrationId, + description.getMessage() + "\n" + ExceptionUtils.getStackTrace(ex)); + object.setInternalError(Boolean.TRUE); + } finally { + if (!isDuplicateRequestForSameTransactionId) { + if (object.getInternalError()) { + updateErrorFlags(registrationStatusDto, object); + } + registrationStatusDto + .setLatestTransactionTypeCode(RegistrationTransactionTypeCode.BIOGRAPHIC_VERIFICATION.toString()); + String moduleId = isTransactionSuccessful ? PlatformSuccessMessages.RPR_BIO_DEDUPE_SUCCESS.getCode() + : description.getCode(); + String moduleName = ModuleName.BIO_DEDUPE.name(); + registrationStatusService.updateRegistrationStatus(registrationStatusDto, moduleId, moduleName); + + regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + registrationId, "BioDedupeProcessor::" + registrationStatusDto.getLatestTransactionStatusCode()); + + String eventId = isTransactionSuccessful ? EventId.RPR_402.toString() : EventId.RPR_405.toString(); + String eventName = isTransactionSuccessful ? EventName.UPDATE.toString() : EventName.EXCEPTION.toString(); + String eventType = isTransactionSuccessful ? EventType.BUSINESS.toString() : EventType.SYSTEM.toString(); + + auditLogRequestBuilder.createAuditRequestBuilder(description.getMessage(), eventId, eventName, eventType, + moduleId, moduleName, registrationId); + } else { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + registrationId, "Duplicate request received for same latest transaction id. This will be ignored."); + object.setIsValid(false); + object.setInternalError(true); + } + } + return object; + } + + /** + * New packet pre abis identification. + * + * @param registrationStatusDto the registration status dto + * @param object the object + * @throws ApisResourceAccessException the apis resource access + * exception + * @throws IOException Signals that an I/O exception + * has occurred. + * @throws io.mosip.kernel.core.exception.IOException + * @throws PacketDecryptionFailureException + * @throws RegistrationProcessorCheckedException RegistrationProcessorCheckedException + */ + private void newPacketPreAbisIdentification(InternalRegistrationStatusDto registrationStatusDto, MessageDTO object) + throws ApisResourceAccessException, IOException, JsonProcessingException, PacketManagerException { + if (isValidCbeff(object)) { + object.setIsValid(Boolean.TRUE); + registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); + registrationStatusDto.setStatusComment(StatusUtil.BIO_DEDUPE_INPROGRESS.getMessage()); + registrationStatusDto.setSubStatusCode(StatusUtil.BIO_DEDUPE_INPROGRESS.getCode()); + registrationStatusDto + .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.IN_PROGRESS.toString()); + object.setMessageBusAddress(MessageBusAddress.ABIS_HANDLER_BUS_IN); + regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + registrationStatusDto.getRegistrationId(), BioDedupeConstants.CBEFF_PRESENT_IN_PACKET); + } else { + if (object.getMessageBusAddress() == MessageBusAddress.VERIFICATION_BUS_IN) { + object.setIsValid(Boolean.TRUE); + registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); + registrationStatusDto.setStatusComment(StatusUtil.BIO_DEDUPE_INPROGRESS.getMessage()); + registrationStatusDto.setSubStatusCode(StatusUtil.BIO_DEDUPE_INPROGRESS.getCode()); + registrationStatusDto + .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.IN_PROGRESS.toString()); + registrationStatusDto.setStatusComment(BioDedupeConstants.CBEFF_NOT_PRESENT_IN_PACKET); + regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + registrationStatusDto.getRegistrationId(), BioDedupeConstants.CBEFF_NOT_PRESENT_IN_PACKET); + } else { + registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.name()); + registrationStatusDto.setStatusComment(StatusUtil.BIO_DEDUPE_SUCCESS.getMessage()); + registrationStatusDto.setSubStatusCode(StatusUtil.BIO_DEDUPE_SUCCESS.getCode()); + registrationStatusDto.setLatestTransactionStatusCode(RegistrationTransactionStatusCode.SUCCESS.toString()); + object.setIsValid(Boolean.TRUE); + regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + registrationStatusDto.getRegistrationId(), BioDedupeConstants.CBEFF_ABSENT_IN_PACKET); + } + } + } + + /** + * Update packet pre abis identification. + * + * @param registrationStatusDto the registration status dto + * @param object the object + * @throws IOException Signals that an I/O exception + * has occurred. + * @throws io.mosip.kernel.core.exception.IOException + * @throws ApisResourceAccessException + * @throws PacketManagerException PacketManagerException + * @throws RegistrationProcessorCheckedException + */ + private void updatePacketPreAbisIdentification(InternalRegistrationStatusDto registrationStatusDto, + MessageDTO object) throws IOException, ApisResourceAccessException, PacketManagerException, JsonProcessingException { + + String bioField = priorityBasedPacketManagerService.getFieldByMappingJsonKey(registrationStatusDto.getRegistrationId(), + MappingJsonConstants.INDIVIDUAL_BIOMETRICS, registrationStatusDto.getRegistrationType(), ProviderStageName.BIO_DEDUPE); + + if (StringUtils.isNotEmpty(bioField) && isValidCbeff(object)) { + object.setIsValid(Boolean.TRUE); + registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); + registrationStatusDto.setStatusComment(StatusUtil.BIO_DEDUPE_INPROGRESS.getMessage()); + registrationStatusDto.setSubStatusCode(StatusUtil.BIO_DEDUPE_INPROGRESS.getCode()); + registrationStatusDto + .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.IN_PROGRESS.toString()); + object.setMessageBusAddress(MessageBusAddress.ABIS_HANDLER_BUS_IN); + + regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + registrationStatusDto.getRegistrationId(), BioDedupeConstants.UPDATE_PACKET_BIOMETRIC_NOT_NULL); + } else { + registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.name()); + registrationStatusDto.setStatusComment(StatusUtil.BIO_DEDUPE_SUCCESS.getMessage()); + registrationStatusDto.setSubStatusCode(StatusUtil.BIO_DEDUPE_SUCCESS.getCode()); + registrationStatusDto.setLatestTransactionStatusCode(RegistrationTransactionStatusCode.SUCCESS.toString()); + object.setIsValid(Boolean.TRUE); + + regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + registrationStatusDto.getRegistrationId(), BioDedupeConstants.UPDATE_PACKET_BIOMETRIC_NULL); + } + } + + /** + * Post abis identification. + * + * @param registrationStatusDto the registration status dto + * @param object the object + * @param registrationType the registration type + * @throws ApisResourceAccessException the apis resource access + * exception + * @throws IOException Signals that an I/O exception + * has occurred. + * @throws io.mosip.kernel.core.exception.IOException + * @throws PacketDecryptionFailureException + * @throws RegistrationProcessorCheckedException RegistrationProcessorCheckedException + */ + private void postAbisIdentification(InternalRegistrationStatusDto registrationStatusDto, MessageDTO object, + String registrationType) throws ApisResourceAccessException, IOException, + io.mosip.kernel.core.exception.IOException, JsonProcessingException, PacketManagerException { + String moduleId = ""; + String moduleName = ModuleName.BIO_DEDUPE.toString(); + Set matchedRegIds = abisHandlerUtil.getUniqueRegIds(registrationStatusDto.getRegistrationId(), + registrationType, registrationStatusDto.getIteration(), registrationStatusDto.getWorkflowInstanceId(), ProviderStageName.BIO_DEDUPE); + ArrayList matchedRegIdsList = new ArrayList(matchedRegIds); + // TODO : temporary fix. Need to analyze more. + if (matchedRegIds != null && !matchedRegIds.isEmpty() + && matchedRegIds.contains(registrationStatusDto.getRegistrationId())) { + matchedRegIds.remove(registrationStatusDto.getRegistrationId()); + matchedRegIdsList.remove(registrationStatusDto.getRegistrationId()); + } + if (matchedRegIds == null || matchedRegIds.isEmpty()) { + registrationStatusDto.setLatestTransactionStatusCode(RegistrationTransactionStatusCode.SUCCESS.toString()); + object.setIsValid(Boolean.TRUE); + registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.name()); + registrationStatusDto.setStatusComment(StatusUtil.BIO_DEDUPE_SUCCESS.getMessage()); + registrationStatusDto.setSubStatusCode(StatusUtil.BIO_DEDUPE_SUCCESS.getCode()); + regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + registrationStatusDto.getRegistrationId(), BioDedupeConstants.ABIS_RESPONSE_NULL); + + } else { + registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.name()); + registrationStatusDto.setStatusComment(StatusUtil.BIO_DEDUPE_POTENTIAL_MATCH.getMessage()); + registrationStatusDto.setSubStatusCode(StatusUtil.BIO_DEDUPE_POTENTIAL_MATCH.getCode()); + registrationStatusDto.setLatestTransactionStatusCode(RegistrationTransactionStatusCode.FAILED.toString()); + moduleId = PlatformSuccessMessages.RPR_BIO_METRIC_POTENTIAL_MATCH.getCode(); + packetInfoManager.saveManualAdjudicationData(matchedRegIds, object, + DedupeSourceName.BIO, moduleId, moduleName,null,null); + //send message to manual adjudication + object.setInternalError(Boolean.FALSE); + object.setRid(registrationStatusDto.getRegistrationId()); + object.setIsValid(Boolean.TRUE); + object.setReg_type(registrationType); + object.setMessageBusAddress(MessageBusAddress.MANUAL_ADJUDICATION_BUS_IN); + + regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + registrationStatusDto.getRegistrationId(), BioDedupeConstants.ABIS_RESPONSE_NOT_NULL); + + } + } + + /** + * Checks if is valid cbeff. + * + * @param messageDTO the messageDTO + * @return the boolean + * @throws ApisResourceAccessException the apis resource access + * exception + * @throws IOException Signals that an I/O exception + * has occurred. + * @throws io.mosip.kernel.core.exception.IOException + * @throws PacketDecryptionFailureException + * @throws RegistrationProcessorCheckedException RegistrationProcessorCheckedException + */ + private Boolean isValidCbeff(MessageDTO messageDTO) throws ApisResourceAccessException, + IOException, JsonProcessingException, PacketManagerException { + String id = messageDTO.getRid(); + String process = messageDTO.getReg_type(); + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + id, "BioDedupeProcessor::isValidCbeff()::get BIODEDUPE service call started"); + boolean isInfant = infantCheck(id, process); + try { + if (isInfant) + if (infantDedupe.equalsIgnoreCase(GLOBAL_CONFIG_TRUE_VALUE)) + cbeffValidateAndVerificatonService.validateBiometrics(id, process); + else + return false; + else + cbeffValidateAndVerificatonService.validateBiometrics(id, process); + } catch (CbeffNotFoundException e) { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString(), id, ExceptionUtils.getStackTrace(e)); + messageDTO.setMessageBusAddress(MessageBusAddress.VERIFICATION_BUS_IN); + return false; + } + return true; + + } + + private boolean infantCheck(String registrationId, String registrationType) throws ApisResourceAccessException, JsonProcessingException, PacketManagerException, IOException { + boolean isInfant = false; + if (RegistrationType.NEW.name().equalsIgnoreCase(registrationType)) { + int age = utilities.getApplicantAge(registrationId, registrationType, ProviderStageName.BIO_DEDUPE); + int ageThreshold = Integer.parseInt(ageLimit); + isInfant = age < ageThreshold; + } else { + isInfant = false; + } + return isInfant; + } + + private void lostPacketPreAbisIdentification(InternalRegistrationStatusDto registrationStatusDto, + MessageDTO object) { + + object.setIsValid(Boolean.TRUE); + registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); + registrationStatusDto.setStatusComment(StatusUtil.BIO_DEDUPE_INPROGRESS.getMessage()); + registrationStatusDto.setSubStatusCode(StatusUtil.BIO_DEDUPE_INPROGRESS.getCode()); + registrationStatusDto.setLatestTransactionStatusCode(RegistrationTransactionStatusCode.IN_PROGRESS.toString()); + object.setMessageBusAddress(MessageBusAddress.ABIS_HANDLER_BUS_IN); + + regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + registrationStatusDto.getRegistrationId(), BioDedupeConstants.LOST_PRE_ABIS_IDENTITIFICATION); + + } + + private void lostPacketPostAbisIdentification(InternalRegistrationStatusDto registrationStatusDto, + MessageDTO object, Set matchedRegIds) throws IOException, ApisResourceAccessException, JsonProcessingException, PacketManagerException { + String moduleId = ""; + String moduleName = ModuleName.BIO_DEDUPE.toString(); + String registrationId = registrationStatusDto.getRegistrationId(); + if (matchedRegIds.isEmpty()) { + registrationStatusDto.setLatestTransactionStatusCode(RegistrationTransactionStatusCode.FAILED.toString()); + object.setIsValid(Boolean.FALSE); + registrationStatusDto.setStatusCode(RegistrationStatusCode.REJECTED.name()); + registrationStatusDto.setStatusComment(StatusUtil.LOST_PACKET_BIOMETRICS_NOT_FOUND.getMessage()); + registrationStatusDto.setSubStatusCode(StatusUtil.LOST_PACKET_BIOMETRICS_NOT_FOUND.getCode()); + regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + registrationStatusDto.getRegistrationId(), + BioDedupeConstants.NO_MATCH_FOUND_FOR_LOST + registrationId); + + } else if (matchedRegIds.size() == 1) { + + registrationStatusDto.setLatestTransactionStatusCode(RegistrationTransactionStatusCode.SUCCESS.toString()); + object.setIsValid(Boolean.TRUE); + registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.name()); + registrationStatusDto.setStatusComment(StatusUtil.LOST_PACKET_UNIQUE_MATCH_FOUND.getMessage()); + registrationStatusDto.setSubStatusCode(StatusUtil.LOST_PACKET_UNIQUE_MATCH_FOUND.getCode()); + moduleId = PlatformSuccessMessages.RPR_BIO_LOST_PACKET_UNIQUE_MATCH_FOUND.getCode(); + packetInfoManager.saveRegLostUinDet(registrationId, + object.getWorkflowInstanceId(), matchedRegIds.iterator().next(), moduleId, moduleName); + regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + registrationStatusDto.getRegistrationId(), + BioDedupeConstants.FOUND_UIN_IN_BIO_CHECK + registrationId); + + } else { + + List demoMatchedIds = new ArrayList<>(); + int matchCount = 0; + + for (String matchedRegId : matchedRegIds) { + JSONObject matchedDemographicIdentity = idRepoService.getIdJsonFromIDRepo(matchedRegId, + utilities.getGetRegProcessorDemographicIdentity()); + matchCount = addMactchedRefId(registrationStatusDto.getRegistrationId(), + registrationStatusDto.getRegistrationType(), matchedDemographicIdentity, matchCount, demoMatchedIds, matchedRegId); + if (matchCount > 1) + break; + } + + if (matchCount == 1) { + + registrationStatusDto + .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.SUCCESS.toString()); + object.setIsValid(Boolean.TRUE); + registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.name()); + registrationStatusDto.setStatusComment(StatusUtil.LOST_PACKET_UNIQUE_MATCH_FOUND.getMessage()); + registrationStatusDto.setSubStatusCode(StatusUtil.LOST_PACKET_UNIQUE_MATCH_FOUND.getCode()); + moduleId = PlatformSuccessMessages.RPR_BIO_LOST_PACKET_UNIQUE_MATCH_FOUND.getCode(); + packetInfoManager.saveRegLostUinDet(registrationId, + object.getWorkflowInstanceId(), demoMatchedIds.get(0), moduleId, moduleName); + regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString(), registrationStatusDto.getRegistrationId(), + BioDedupeConstants.FOUND_UIN_IN_DEMO_CHECK + registrationId); + } else { + + registrationStatusDto.setStatusComment(StatusUtil.LOST_PACKET_MULTIPLE_MATCH_FOUND.getMessage()); + registrationStatusDto.setSubStatusCode(StatusUtil.LOST_PACKET_MULTIPLE_MATCH_FOUND.getCode()); + registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.name()); + registrationStatusDto + .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.FAILED.toString()); + + regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString(), registrationStatusDto.getRegistrationId(), + BioDedupeConstants.MULTIPLE_RID_FOUND); + moduleId = PlatformErrorMessages.RPR_BIO_LOST_PACKET_MULTIPLE_MATCH_FOUND.getCode(); + packetInfoManager.saveManualAdjudicationData(matchedRegIds, + object, DedupeSourceName.BIO, moduleId, moduleName,null,null); + } + } + } + + private int addMactchedRefId(String id, String process, JSONObject matchedDemographicIdentity, int matchCount, List demoMatchedIds, + String matchedRegId) throws IOException, ApisResourceAccessException, PacketManagerException, JsonProcessingException { + if (matchedDemographicIdentity != null) { + Map matchedAttribute = getIdJson(matchedDemographicIdentity); + if (!matchedAttribute.isEmpty()) { + if (compareDemoDedupe(id, process, matchedAttribute)) { + matchCount++; + demoMatchedIds.add(matchedRegId); + } + + } + } + return matchCount; + } + + private boolean compareDemoDedupe(String id, String process, Map matchedAttribute) throws ApisResourceAccessException, IOException, PacketManagerException, JsonProcessingException { + boolean isMatch = false; + + for (String key : matchedAttribute.keySet()) { + String value = priorityBasedPacketManagerService.getField(id, key, process, ProviderStageName.BIO_DEDUPE); + if (value != null && value.equalsIgnoreCase(matchedAttribute.get(key))) { + isMatch = true; + } else { + isMatch = false; + return isMatch; + } + + } + return isMatch; + } + + private Map getIdJson(JSONObject demographicJsonIdentity) throws IOException { + Map attribute = new LinkedHashMap<>(); + + + JSONObject mapperIdentity = new JSONObject(); + mapperIdentity.putAll(utilities.getRegistrationProcessorMappingJson(MappingJsonConstants.IDENTITY)); + mapperIdentity.putAll(utilities.getRegistrationProcessorMappingJson(MappingJsonConstants.DOCUMENT)); + + + List mapperJsonKeys = new ArrayList<>(mapperIdentity.keySet()); + + for (String key : mapperJsonKeys) { + JSONObject jsonValue = JsonUtil.getJSONObject(mapperIdentity, key); + Object jsonObject = JsonUtil.getJSONValue(demographicJsonIdentity, + (String) jsonValue.get(BioDedupeConstants.VALUE)); + if (jsonObject instanceof ArrayList) { + JSONArray node = JsonUtil.getJSONArray(demographicJsonIdentity, + (String) jsonValue.get(BioDedupeConstants.VALUE)); + JsonValue[] jsonValues = JsonUtil.mapJsonNodeToJavaObject(JsonValue.class, node); + if (jsonValues != null) + for (int count = 0; count < jsonValues.length; count++) { + String lang = jsonValues[count].getLanguage(); + attribute.put(key + "_" + lang, jsonValues[count].getValue()); + } + + } else if (jsonObject instanceof LinkedHashMap) { + JSONObject json = JsonUtil.getJSONObject(demographicJsonIdentity, + (String) jsonValue.get(BioDedupeConstants.VALUE)); + if (json != null) + attribute.put(key, json.get(BioDedupeConstants.VALUE).toString()); + } else { + if (jsonObject != null) + attribute.put(key, jsonObject.toString()); + } + } + + return attribute; + } + + private void updateErrorFlags(InternalRegistrationStatusDto registrationStatusDto, MessageDTO object) { + object.setInternalError(true); + if (registrationStatusDto.getLatestTransactionStatusCode() + .equalsIgnoreCase(RegistrationTransactionStatusCode.REPROCESS.toString())) { + object.setIsValid(true); + } else { + object.setIsValid(false); + } + } } \ No newline at end of file From 22bf70d589e5bd8b49f26d1af91ed0b4027ffc82 Mon Sep 17 00:00:00 2001 From: Sowmya Ujjappa Banakar Date: Wed, 10 May 2023 13:08:30 +0530 Subject: [PATCH 065/133] MOSIP-27067 code changes --- .../impl/ManualAdjudicationServiceImpl.java | 2129 +++++++++-------- 1 file changed, 1078 insertions(+), 1051 deletions(-) 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 6e576774774..c20271107ed 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 @@ -1,1051 +1,1078 @@ -package io.mosip.registration.processor.adjudication.service.impl; - -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.adjudication.constants.ManualAdjudicationConstants; -import io.mosip.registration.processor.adjudication.dto.DataShareRequestDto; -import io.mosip.registration.processor.adjudication.dto.ManualVerificationStatus; -import io.mosip.registration.processor.adjudication.exception.*; -import io.mosip.registration.processor.adjudication.request.dto.*; -import io.mosip.registration.processor.adjudication.response.dto.Candidate; -import io.mosip.registration.processor.adjudication.response.dto.ManualAdjudicationResponseDTO; -import io.mosip.registration.processor.adjudication.service.ManualAdjudicationService; -import io.mosip.registration.processor.adjudication.stage.ManualAdjudicationStage; -import io.mosip.registration.processor.adjudication.util.ManualVerificationUpdateUtility; -import io.mosip.registration.processor.core.abstractverticle.MessageBusAddress; -import io.mosip.registration.processor.core.abstractverticle.MessageDTO; -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.constant.*; -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.idrepo.dto.Documents; -import io.mosip.registration.processor.core.idrepo.dto.ResponseDTO; -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.manager.idreposervice.IdRepoService; -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.ManualVerificationEntity; -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 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 java.io.IOException; -import java.net.MalformedURLException; -import java.util.*; -import java.util.Map.Entry; -import java.util.stream.Collectors; - -import static io.mosip.registration.processor.adjudication.constants.ManualAdjudicationConstants.DATETIME_PATTERN; - -/** - * The Class ManualAdjudicationServiceImpl. - */ -@Component -@Transactional -public class ManualAdjudicationServiceImpl implements ManualAdjudicationService { - - /** The logger. */ - private static Logger regProcLogger = RegProcessorLogger.getLogger(ManualAdjudicationServiceImpl.class); - private LinkedHashMap policies = null; - private static final String MANUAL_ADJUDICATION = "manualadjudication"; - - /** 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"; - private static final String ID_REPO = "idrepo"; - private static final String PACKET = "packet"; - private static final String PROCESSED = "PROCESSED"; - @Autowired - private Environment env; - - /** The address. */ - @Value("${registration.processor.queue.manual.adjudication.request:mosip-to-adjudication}") - private String mvRequestAddress; - - /**Manual adjudication queue message expiry in seconds, if given 0 then message will never expire*/ - @Value("${registration.processor.queue.manual.adjudication.request.messageTTL}") - private int mvRequestMessageTTL; - - @Value("${registration.processor.manual.adjudication.policy.id:mpolicy-default-adjudication}") - private String policyId; - - @Value("${registration.processor.manual.adjudication.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; - - @Value("${mosip.regproc.manual.adjudication.use.lts.format:true}") - private boolean uselatestManualAdjudicationRequestFormat; - - @Autowired - private RegistrationProcessorRestClientService registrationProcessorRestClientService; - - @Autowired - private CbeffUtil cbeffutil; - - @Autowired - private Utilities utility; - - @Autowired - private IdRepoService idRepoService; - - @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 ManualAdjudicationStage manualAdjudicationStage; - - @Autowired - private RegistrationProcessorRestClientService restClientService; - - @Autowired - private PacketInfoManager packetInfoManager; - - @Autowired - private ObjectMapper mapper; - - @Autowired - RegistrationExceptionMapperUtil registrationExceptionMapperUtil; - - @Autowired - private ManualVerificationUpdateUtility manualVerificationUpdateUtility; - - /** The Constant PROTOCOL. */ - public static final String PROTOCOL = "https"; - - /* - * (non-Javadoc) - * - * @see io.mosip.registration.processor.manual.adjudication.service. - * ManualAdjudicationService#updatePacketStatus(io.mosip.registration.processor. - * manual.adjudication.dto.ManualVerificationDTO) - */ - @Override - public boolean updatePacketStatus(ManualAdjudicationResponseDTO 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(), "ManualVerificationServiceImpl::updatePacketStatus()::entry"); - - ManualVerificationEntity entity = validateRequestIdAndReturnRid(manualVerificationDTO.getRequestId()); - String regId = entity!=null?entity.getRegId():null; - - InternalRegistrationStatusDto registrationStatusDto = null; - - MessageDTO messageDTO = new MessageDTO(); - - - try { - registrationStatusDto = registrationStatusService - .getRegistrationStatus((entity!=null?entity.getRegId():null), null, null, (entity!=null?(entity.getId()!=null?entity.getId().getWorkflowInstanceId():null):null)); - registrationStatusDto.setLatestTransactionTypeCode(RegistrationTransactionTypeCode.MANUAL_ADJUDICATION.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(regId, manualVerificationDTO, entities)) { - registrationStatusDto.setStatusComment(StatusUtil.RPR_MANUAL_VERIFICATION_RESEND.getMessage()); - registrationStatusDto.setSubStatusCode(StatusUtil.RPR_MANUAL_VERIFICATION_RESEND.getCode()); - registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); - registrationStatusDto - .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.REPROCESS.toString()); - description.setMessage(PlatformSuccessMessages.RPR_MANUAL_VERIFICATION_RESEND.getMessage()); - description.setCode(PlatformSuccessMessages.RPR_MANUAL_VERIFICATION_RESEND.getCode()); - messageDTO.setInternalError(true); - messageDTO.setIsValid(isTransactionSuccessful); - manualAdjudicationStage.sendMessage(messageDTO); - } else { - // call success flow and process the response received from manual verification system - isTransactionSuccessful = successFlow( - entity, manualVerificationDTO, entities, 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 (IOException e) { - messageDTO.setInternalError(true); - registrationStatusDto.setLatestTransactionStatusCode(registrationExceptionMapperUtil - .getStatusCode(RegistrationExceptionTypeCode.IOEXCEPTION)); - registrationStatusDto.setStatusComment(trimExceptionMessage - .trimExceptionMessage(StatusUtil.IO_EXCEPTION.getMessage() + e.getMessage())); - registrationStatusDto.setSubStatusCode(StatusUtil.IO_EXCEPTION.getCode()); - - description.setMessage(PlatformErrorMessages.RPR_SYS_IO_EXCEPTION.getMessage()); - description.setCode(PlatformErrorMessages.RPR_SYS_IO_EXCEPTION.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 { - if(messageDTO.getInternalError()) { - updateErrorFlags(registrationStatusDto, messageDTO); - } - /** Module-Id can be Both Success/Error code */ - String moduleId = isTransactionSuccessful - ? PlatformSuccessMessages.RPR_MANUAL_VERIFICATION_APPROVED.getCode() - : description.getCode(); - String moduleName = ModuleName.MANUAL_ADJUDICATION.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, "ManualVerificationServiceImpl::updatePacketStatus()::exit"); - return isTransactionSuccessful; - - } - - /** - * 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 ManualVerificationEntity validateRequestIdAndReturnRid(String reqId) { - List entities = basePacketRepository.getRegistrationIdbyRequestId(reqId); - - if (CollectionUtils.isEmpty(entities) || new HashSet<>(entities.stream().map(ManualVerificationEntity::getRegId).collect(Collectors.toList())).size() != 1) { - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - entities != null ? entities.stream().map(ManualVerificationEntity::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()); - } - - ManualVerificationEntity entity = entities.iterator().next(); - - if (entity != null && StringUtils.isEmpty(entity.getRegId())) { - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - entity.getRegId(), "ManualVerificationServiceImpl::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.getAllAssignedRecord( - regId, ManualVerificationStatus.INQUEUE.name()); - - if (CollectionUtils.isEmpty(entities)) { - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - regId, "ManualVerificationServiceImpl::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; - } - - /* - * Get matched ref id for given RID and form request ,push to queue - */ - private void pushRequestToQueue(MessageDTO messageDTO, MosipQueue queue) throws Exception { - String refId = messageDTO.getRid(); - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - refId, "ManualVerificationServiceImpl::pushRequestToQueue()::entry"); - List mves = getMatchingEntitiesforRefId(refId); - if (mves == null || mves.isEmpty()) - throw new MatchedRefNotExistsException( - PlatformErrorMessages.RPR_MVS_NO_MATCHEDRID_FOUND_FOR_GIVEN_RID.getCode(), - PlatformErrorMessages.RPR_MVS_NO_MATCHEDRID_FOUND_FOR_GIVEN_RID.getMessage()); - - ManualAdjudicationRequestDTO mar=null; - if(uselatestManualAdjudicationRequestFormat) { - mar = prepareManualAdjudicationRequestLatest(messageDTO, mves); - }else { - mar = prepareManualAdjudicationRequest(messageDTO, mves); - } - String requestId = UUID.randomUUID().toString(); - mar.setRequestId(requestId); - regProcLogger.info("Request : " + JsonUtils.javaObjectToJsonString(mar)); - manualVerificationUpdateUtility.updateManualVerificationEntityRID(mves, requestId); - if (messageFormat.equalsIgnoreCase(TEXT_MESSAGE)) - mosipQueueManager.send(queue, JsonUtils.javaObjectToJsonString(mar), mvRequestAddress, mvRequestMessageTTL); - else - mosipQueueManager.send(queue, JsonUtils.javaObjectToJsonString(mar).getBytes(), mvRequestAddress, mvRequestMessageTTL); - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - refId, "ManualVerificationServiceImpl::pushRequestToQueue()::entry"); - } - - private String getDataShareUrl(String id, String process) throws Exception { - DataShareRequestDto requestDto = new DataShareRequestDto(); - - LinkedHashMap policy = getPolicy(); - - Map policyMap = getPolicyMap(policy); - - // set demographic - Map demographicMap = getDemographicMap(policyMap); - requestDto.setIdentity(packetManagerService.getFields(id, demographicMap.values().stream().collect(Collectors.toList()), process, ProviderStageName.MANUAL_ADJUDICATION)); - - // set documents - requestDto=setDocuments(policyMap, requestDto, id, process, null); - - // set audits - for(Entry entry: policyMap.entrySet()) { - if (entry.getValue().contains(AUDITS)) - requestDto.setAudits(JsonUtils.javaObjectToJsonString(packetManagerService.getAudits(id, process, ProviderStageName.MANUAL_ADJUDICATION))); - - // set metainfo - if (entry.getValue().contains(META_INFO)) - requestDto.setMetaInfo(JsonUtils.javaObjectToJsonString(packetManagerService.getMetaInfo(id, process, ProviderStageName.MANUAL_ADJUDICATION))); - - - // set biometrics - JSONObject regProcessorIdentityJson = utility.getRegistrationProcessorMappingJson(MappingJsonConstants.IDENTITY); - String individualBiometricsLabel = JsonUtil.getJSONValue( - JsonUtil.getJSONObject(regProcessorIdentityJson, MappingJsonConstants.INDIVIDUAL_BIOMETRICS), - MappingJsonConstants.VALUE); - - if (entry.getValue().contains(individualBiometricsLabel)) { - List modalities = getModalities(policy); - BiometricRecord biometricRecord = packetManagerService.getBiometrics( - id, individualBiometricsLabel, modalities, process, ProviderStageName.MANUAL_ADJUDICATION); - byte[] content = cbeffutil.createXML(biometricRecord.getSegments()); - requestDto.setBiometrics(content != null ? CryptoUtil.encodeToURLSafeBase64(content) : null); - } - } - - return CreateDataShareUrl(requestDto, policy); - } - - private String getDataShareUrlfromIdRepo(String id) throws DataShareException, ApisResourceAccessException, JsonProcessingException, IOException, PacketManagerException { - - DataShareRequestDto requestDto = new DataShareRequestDto(); - LinkedHashMap policy = getPolicy(); - Map policyMap = getPolicyMap(policy); - Map demographicMap = getDemographicMap(policyMap); - - ResponseDTO responseDTO=idRepoService.getIdResponseFromIDRepo(id); - - String identityResponse = mapper.writeValueAsString(responseDTO.getIdentity()); - Map identity=new HashMap<>(); - - for(Entry entry:demographicMap.entrySet()) { - JSONObject identityJson = JsonUtil.objectMapperReadValue(identityResponse, JSONObject.class); - identity.put(entry.getValue(),mapper.writeValueAsString(JsonUtil.getJSONValue(identityJson, entry.getValue()))); - } - requestDto.setIdentity(identity); - List documents=responseDTO.getDocuments(); - requestDto=setDocuments(policyMap, requestDto, null, null, documents); - - JSONObject regProcessorIdentityJson = utility.getRegistrationProcessorMappingJson(MappingJsonConstants.IDENTITY); - String individualBiometricsLabel = JsonUtil.getJSONValue( - JsonUtil.getJSONObject(regProcessorIdentityJson, MappingJsonConstants.INDIVIDUAL_BIOMETRICS), - MappingJsonConstants.VALUE); - for(Documents docs:documents) { - for(Entry entry: policyMap.entrySet()) { - if(entry.getValue().contains(individualBiometricsLabel) && docs.getCategory().equalsIgnoreCase(individualBiometricsLabel)){ - requestDto.setBiometrics(docs.getValue() != null ? docs.getValue() : null); - } - if(entry.getValue().contains(AUDITS) && docs.getCategory().equalsIgnoreCase(AUDITS)){ - requestDto.setAudits(docs.getValue() != null ? docs.getValue() : null); - } - if(entry.getValue().contains(META_INFO) && docs.getCategory().equalsIgnoreCase(META_INFO)){ - requestDto.setMetaInfo(docs.getValue() != null ? docs.getValue() : null); - } - } - } - - return CreateDataShareUrl(requestDto, policy); - - } - - @SuppressWarnings("rawtypes") - private String CreateDataShareUrl(DataShareRequestDto requestDto, LinkedHashMap policy) throws JsonProcessingException, MalformedURLException, ApisResourceAccessException, DataShareException { - String req = JsonUtils.javaObjectToJsonString(requestDto); - - MultiValueMap map = new LinkedMultiValueMap<>(); - map.add("name", MANUAL_ADJUDICATION); - map.add("filename", MANUAL_ADJUDICATION); - - ByteArrayResource contentsAsResource = new ByteArrayResource(req.getBytes()) { - @Override - public String getFilename() { - return MANUAL_ADJUDICATION; - } - }; - 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 response1 = (LinkedHashMap) registrationProcessorRestClientService.postApi(url, MediaType.MULTIPART_FORM_DATA, pathSegments, null, null, map, LinkedHashMap.class); - if (response1 == null || (response1.get(ERRORS) != null)) - throw new DataShareException(response1 == null ? "Datashare response is null" : response1.get(ERRORS).toString()); - - LinkedHashMap datashare = (LinkedHashMap) response1.get(DATASHARE); - return datashare.get(URL) != null ? datashare.get(URL).toString() : null; - } - - private Map getPolicyMap(LinkedHashMap policies) throws DataShareException, IOException, ApisResourceAccessException { - Map policyMap = new HashMap<>(); - List attributes = (List) policies.get(ManualAdjudicationConstants.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 Map getDemographicMap(Map policyMap){ - 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())); - return demographicMap; - } - private DataShareRequestDto setDocuments(Map policyMap,DataShareRequestDto requestDto, String id, String process, List documents) throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException{ - 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; - for(Entry entry: policyMap.entrySet()) { - 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(), 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; - } - - 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().isEmpty())) { - 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(ManualAdjudicationConstants.POLICIES); - } - return policies; - - } - - - public List getModalities(LinkedHashMap policy) throws IOException{ - Map> typeAndSubTypeMap = new HashMap<>(); - List attributes = (List) policy.get(ManualAdjudicationConstants.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; - - } - - /* - * get matched ref id for a given registration id - */ - private List getMatchingEntitiesforRefId(String rid) { - regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), rid, - "ManualVerificationServiceImpl::getMatchingEntitiesforRefId()::entry"); - - List matchedEntities = basePacketRepository.getMatchedIds(rid, ManualVerificationStatus.PENDING.name()); - - regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), rid, - "ManualVerificationServiceImpl::getMatchingEntitiesforRefId()::entry"); - - return matchedEntities; - } - - /* - * Form manual adjudication request - */ - private ManualAdjudicationRequestDTO prepareManualAdjudicationRequest(MessageDTO messageDTO, List mve) throws Exception { - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), "", - "ManualVerificationServiceImpl::formAdjudicationRequest()::entry"); - - ManualAdjudicationRequestDTO req = new ManualAdjudicationRequestDTO(); - req.setId(ManualAdjudicationConstants.MANUAL_ADJUDICATION_ID); - req.setVersion(ManualAdjudicationConstants.VERSION); - req.setRequestId(mve.get(0).getRequestId()); - req.setRequesttime(DateUtils.getUTCCurrentDateTimeString(env.getProperty(DATETIME_PATTERN))); - req.setReferenceId(mve.get(0).getRegId()); - InternalRegistrationStatusDto registrationStatusDto = null; - registrationStatusDto = registrationStatusService.getRegistrationStatus( - mve.get(0).getRegId(), messageDTO.getReg_type(), messageDTO.getIteration(), mve.get(0).getId().getWorkflowInstanceId()); - try { - req.setReferenceURL( - getDataShareUrl(mve.get(0).getRegId(), registrationStatusDto.getRegistrationType())); - - } catch (PacketManagerException | ApisResourceAccessException ex) { - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - ex.getErrorCode(), ex.getErrorText()); - throw ex; - } - - List referenceIds = new ArrayList<>(); - mve.forEach(e -> { - ReferenceIds r = new ReferenceIds(); - InternalRegistrationStatusDto registrationStatusDto1 = null; - registrationStatusDto1 = registrationStatusService.getRegistrationStatus( - e.getId().getMatchedRefId(),messageDTO.getReg_type(), messageDTO.getIteration(),null); - - try { - r.setReferenceId(e.getId().getMatchedRefId()); - r.setReferenceURL(getDataShareUrl(e.getId().getMatchedRefId(),registrationStatusDto1.getRegistrationType())); - referenceIds.add(r); - } catch (PacketManagerException | ApisResourceAccessException ex) { - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), - LoggerFileConstant.REGISTRATIONID.toString(), ex.getErrorCode(), ex.getErrorText()); - r.setReferenceURL(null); - referenceIds.add(r); - } catch (Exception exp) { - regProcLogger.error(ExceptionUtils.getStackTrace(exp)); - } - - }); - Gallery g = new Gallery(); - g.setReferenceIds(referenceIds); - req.setGallery(g); - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), "", - "ManualVerificationServiceImpl::formAdjudicationRequest()::entry"); - - return req; - } - - /* - * Form manual adjudication request - */ - private ManualAdjudicationRequestDTO prepareManualAdjudicationRequestLatest(MessageDTO messageDTO, List mve) throws Exception { - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), "", - "ManualVerificationServiceImpl::formAdjudicationRequest()::entry"); - - ManualAdjudicationRequestDTO req = new ManualAdjudicationRequestDTO(); - req.setId(ManualAdjudicationConstants.MANUAL_ADJUDICATION_ID); - req.setVersion(ManualAdjudicationConstants.VERSION); - req.setRequestId(mve.get(0).getRequestId()); - req.setRequesttime(DateUtils.getUTCCurrentDateTimeString(env.getProperty(DATETIME_PATTERN))); - req.setReferenceId(mve.get(0).getRegId()); - InternalRegistrationStatusDto registrationStatusDto = null; - registrationStatusDto = registrationStatusService.getRegistrationStatus( - mve.get(0).getRegId(), messageDTO.getReg_type(), messageDTO.getIteration(), mve.get(0).getId().getWorkflowInstanceId()); - try { - req.setReferenceURL( - JsonUtil.objectMapperObjectToJson(addReferenceURLs(mve.get(0).getRegId(), registrationStatusDto))); - - } catch (PacketManagerException | ApisResourceAccessException ex) { - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - ex.getErrorCode(), ex.getErrorText()); - throw ex; - } - - List referenceIds = new ArrayList<>(); - mve.forEach(e -> { - ReferenceIds r = new ReferenceIds(); - InternalRegistrationStatusDto registrationStatusDto1 = null; - registrationStatusDto1 = registrationStatusService.getRegistrationStatus( - e.getId().getMatchedRefId(),messageDTO.getReg_type(), messageDTO.getIteration(), null); - - try { - r.setReferenceId(e.getId().getMatchedRefId()); - r.setReferenceURL(JsonUtil.objectMapperObjectToJson(addReferenceURLs(e.getId().getMatchedRefId(),registrationStatusDto1))); - referenceIds.add(r); - } catch (PacketManagerException | ApisResourceAccessException ex) { - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), - LoggerFileConstant.REGISTRATIONID.toString(), ex.getErrorCode(), ex.getErrorText()); - r.setReferenceURL(null); - referenceIds.add(r); - } catch (Exception exp) { - regProcLogger.error(ExceptionUtils.getStackTrace(exp)); - } - - }); - Gallery g = new Gallery(); - g.setReferenceIds(referenceIds); - req.setGallery(g); - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), "", - "ManualVerificationServiceImpl::formAdjudicationRequest()::entry"); - - return req; - } - - private List addReferenceURLs(String id,InternalRegistrationStatusDto registrationStatusDto) throws Exception { - List referenceURLs=new ArrayList<>(); - if( registrationStatusDto.getStatusCode().equalsIgnoreCase(RegistrationStatusCode.PROCESSED.name())) { - ReferenceURL referenceURL=new ReferenceURL(); - referenceURL.setSource(ID_REPO); - referenceURL.setStatus(registrationStatusDto.getStatusCode()); - referenceURL.setURL(getDataShareUrlfromIdRepo(id)); - referenceURLs.add(referenceURL); - } - else{ - ReferenceURL referenceURL=new ReferenceURL(); - referenceURL.setSource(PACKET); - referenceURL.setStatus(registrationStatusDto.getStatusCode()); - referenceURL.setURL( - getDataShareUrl(id,registrationStatusDto.getRegistrationType())); - referenceURLs.add(referenceURL); - if(registrationStatusDto.getRegistrationType().equalsIgnoreCase(RegistrationType.UPDATE.name()) - || registrationStatusDto.getRegistrationType().equalsIgnoreCase(RegistrationType.RES_UPDATE.name())) { - String uinField = utility.getUIn(id, registrationStatusDto.getRegistrationType(), ProviderStageName.MANUAL_ADJUDICATION); - ReferenceURL referenceURL1=new ReferenceURL(); - referenceURL1.setSource(ID_REPO); - referenceURL1.setStatus(PROCESSED); - referenceURL1.setURL( - getDataShareUrlfromIdRepo(uinField)); - referenceURLs.add(referenceURL1); - } - } - return referenceURLs; - } - - /* - * 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 object, MosipQueue queue) { - InternalRegistrationStatusDto registrationStatusDto=new InternalRegistrationStatusDto(); - TrimExceptionMessage trimExceptionMessage = new TrimExceptionMessage(); - LogDescription description = new LogDescription(); - String moduleName = ModuleName.MANUAL_ADJUDICATION.toString(); - String moduleId = PlatformSuccessMessages.RPR_MANUAL_VERIFICATION_SENT.getCode(); - String registrationId = object.getRid(); - boolean isTransactionSuccessful = false; - try { - object.setInternalError(false); - object.setIsValid(false); - object.setMessageBusAddress(MessageBusAddress.MANUAL_ADJUDICATION_BUS_IN); - - if (null == object.getRid() || object.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()); - } - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - object.getRid(), "ManualVerificationServiceImpl::process()::entry"); - - registrationStatusDto = registrationStatusService - .getRegistrationStatus(object.getRid(), object.getReg_type(), object.getIteration(), object.getWorkflowInstanceId()); - - pushRequestToQueue(object, queue); - isTransactionSuccessful=true; - registrationStatusDto.setStatusComment(StatusUtil.RPR_MANUAL_VERIFICATION_SENT_TO_QUEUE.getMessage()); - registrationStatusDto.setSubStatusCode(StatusUtil.RPR_MANUAL_VERIFICATION_SENT_TO_QUEUE.getCode()); - registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); - registrationStatusDto - .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.SUCCESS.toString()); - - } catch (DataShareException de) { - registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.name()); - registrationStatusDto.setStatusComment(trimExceptionMessage - .trimExceptionMessage(StatusUtil.MANUAL_ADJUDICATION_FAILED.getMessage() + de.getMessage())); - registrationStatusDto.setSubStatusCode(StatusUtil.MANUAL_ADJUDICATION_FAILED.getCode()); - registrationStatusDto.setLatestTransactionStatusCode( - registrationExceptionMapperUtil.getStatusCode(RegistrationExceptionTypeCode.MANUAL_VERIFICATION_FAILED)); - description.setCode(PlatformErrorMessages.MANUAL_VERIFICATION_FAILED.getCode()); - description.setMessage(PlatformErrorMessages.MANUAL_VERIFICATION_FAILED.getMessage()); - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), description.getCode(), object.getRid(), - description.getMessage() + ExceptionUtils.getStackTrace(de)); - object.setInternalError(true); - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - de.getErrorCode(), de.getErrorText()); - - } catch (InvalidRidException exp) { - registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.name()); - registrationStatusDto.setStatusComment(trimExceptionMessage - .trimExceptionMessage(StatusUtil.MANUAL_ADJUDICATION_RID_SHOULD_NOT_EMPTY_OR_NULL.getMessage() + exp.getMessage())); - registrationStatusDto.setSubStatusCode(StatusUtil.MANUAL_ADJUDICATION_RID_SHOULD_NOT_EMPTY_OR_NULL.getCode()); - registrationStatusDto.setLatestTransactionStatusCode( - registrationExceptionMapperUtil.getStatusCode(RegistrationExceptionTypeCode.MANUAL_VERIFICATION_FAILED)); - description.setCode(PlatformErrorMessages.RPR_MVS_NO_RID_SHOULD_NOT_EMPTY_OR_NULL.getCode()); - description.setMessage(PlatformErrorMessages.RPR_MVS_NO_RID_SHOULD_NOT_EMPTY_OR_NULL.getMessage()); - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), description.getCode(), null, - description.getMessage() + ExceptionUtils.getStackTrace(exp)); - object.setInternalError(true); - - } catch (Exception e) { - registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.name()); - registrationStatusDto.setStatusComment(trimExceptionMessage - .trimExceptionMessage(StatusUtil.UNKNOWN_EXCEPTION_OCCURED.getMessage() + e.getMessage())); - registrationStatusDto.setSubStatusCode(StatusUtil.UNKNOWN_EXCEPTION_OCCURED.getCode()); - registrationStatusDto.setLatestTransactionStatusCode( - registrationExceptionMapperUtil.getStatusCode(RegistrationExceptionTypeCode.MANUAL_VERIFICATION_FAILED)); - description.setCode(PlatformErrorMessages.MANUAL_VERIFICATION_FAILED.getCode()); - description.setMessage(PlatformErrorMessages.MANUAL_VERIFICATION_FAILED.getMessage()); - object.setInternalError(true); - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), description.getCode(), object.getRid(), - description.getMessage() + ExceptionUtils.getStackTrace(e)); - }finally { - registrationStatusDto - .setLatestTransactionTypeCode(RegistrationTransactionTypeCode.MANUAL_ADJUDICATION.toString()); - registrationStatusService.updateRegistrationStatus(registrationStatusDto, moduleId, moduleName); - if (object.getInternalError()) { - updateErrorFlags(registrationStatusDto, object); - } - if (object.getIsValid() && !object.getInternalError()) - regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), - LoggerFileConstant.REGISTRATIONID.toString(), registrationId, "ManualVerificationServiceImpl::process()::success"); - else - regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), - LoggerFileConstant.REGISTRATIONID.toString(), registrationId, "ManualVerificationServiceImpl::process()::failure"); - - String eventId = isTransactionSuccessful ? EventId.RPR_402.toString() : EventId.RPR_405.toString(); - String eventName = isTransactionSuccessful ? EventName.UPDATE.toString() : EventName.EXCEPTION.toString(); - String eventType = isTransactionSuccessful ? EventType.BUSINESS.toString() : EventType.SYSTEM.toString(); - - auditLogRequestBuilder.createAuditRequestBuilder(description.getMessage(), eventId, eventName, eventType, - moduleId, moduleName, registrationId); - - } - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - object.getRid(), "ManualVerificationServiceImpl::process()::exit"); - - return object; - } - - /** - * Process response for success flow. - * - * @param entity - * @param manualVerificationDTO - * @param entities - * @param registrationStatusDto - * @param messageDTO - * @param description - * @return boolean - * @throws com.fasterxml.jackson.core.JsonProcessingException - */ - private boolean successFlow(ManualVerificationEntity entity, ManualAdjudicationResponseDTO manualVerificationDTO, - List entities, - InternalRegistrationStatusDto registrationStatusDto, MessageDTO messageDTO, - LogDescription description) throws com.fasterxml.jackson.core.JsonProcessingException { - - boolean isTransactionSuccessful = false; - String statusCode = manualVerificationDTO.getReturnValue() == 1 && - CollectionUtils.isEmpty(manualVerificationDTO.getCandidateList().getCandidates()) ? - ManualVerificationStatus.APPROVED.name() : ManualVerificationStatus.REJECTED.name(); - - for (int i = 0; i < entities.size(); i++) { - byte[] responsetext = mapper.writeValueAsBytes(manualVerificationDTO); - - ManualVerificationEntity manualVerificationEntity=entities.get(i); - manualVerificationEntity.setStatusCode(statusCode); - manualVerificationEntity.setReponseText(responsetext); - manualVerificationEntity.setStatusComment(statusCode.equalsIgnoreCase(ManualVerificationStatus.APPROVED.name()) ? - StatusUtil.MANUAL_VERIFIER_APPROVED_PACKET.getMessage() : - StatusUtil.MANUAL_VERIFIER_REJECTED_PACKET.getMessage()); - entities.set(i, manualVerificationEntity); - } - isTransactionSuccessful = true; - registrationStatusDto - .setLatestTransactionTypeCode(RegistrationTransactionTypeCode.MANUAL_ADJUDICATION.toString()); - registrationStatusDto.setRegistrationStageName(registrationStatusDto.getRegistrationStageName()); - - if (statusCode != null && statusCode.equalsIgnoreCase(ManualVerificationStatus.APPROVED.name())) { - if (registrationStatusDto.getRegistrationType().equalsIgnoreCase(RegistrationType.LOST.toString())) { - for(ManualVerificationEntity detail: entities) { - packetInfoManager.saveRegLostUinDet(entity.getRegId(), - entity.getId().getWorkflowInstanceId(), detail.getId().getMatchedRefId(), - PlatformSuccessMessages.RPR_MANUAL_VERIFICATION_APPROVED.getCode(), - ModuleName.MANUAL_ADJUDICATION.toString()); - } - } - messageDTO.setIsValid(isTransactionSuccessful); - manualAdjudicationStage.sendMessage(messageDTO); - registrationStatusDto.setStatusComment(StatusUtil.MANUAL_VERIFIER_APPROVED_PACKET.getMessage()); - registrationStatusDto.setSubStatusCode(StatusUtil.MANUAL_VERIFIER_APPROVED_PACKET.getCode()); - registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); - registrationStatusDto - .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.SUCCESS.toString()); - - description.setMessage(PlatformSuccessMessages.RPR_MANUAL_VERIFICATION_APPROVED.getMessage()); - description.setCode(PlatformSuccessMessages.RPR_MANUAL_VERIFICATION_APPROVED.getCode()); - - } else if (statusCode != null && statusCode.equalsIgnoreCase(ManualVerificationStatus.REJECTED.name())) { - registrationStatusDto.setStatusCode(RegistrationStatusCode.REJECTED.toString()); - registrationStatusDto.setStatusComment(StatusUtil.MANUAL_VERIFIER_REJECTED_PACKET.getMessage()); - registrationStatusDto.setSubStatusCode(StatusUtil.MANUAL_VERIFIER_REJECTED_PACKET.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); - manualAdjudicationStage.sendMessage(messageDTO); - } else { - registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); - registrationStatusDto.setStatusComment(StatusUtil.RPR_MANUAL_VERIFICATION_RESEND.getMessage()); - registrationStatusDto.setSubStatusCode(StatusUtil.RPR_MANUAL_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); - manualAdjudicationStage.sendMessage(messageDTO); - } - List maVerificationEntity = new ArrayList<>(); - for(ManualVerificationEntity manualVerificationEntity: entities) { - maVerificationEntity.add(basePacketRepository.update(manualVerificationEntity)); - } - - 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); - } - } - - /** - * Validate the response received from manual verification system. - * - * @param regId - * @param manualVerificationDTO - * @param entities - * @return boolean - * @throws JsonProcessingException - */ - private boolean isResponseValidationSuccess(String regId, ManualAdjudicationResponseDTO manualVerificationDTO, List entities) throws JsonProcessingException { - boolean isValidationSuccess = true; - // if candidate count is a positive number - if (manualVerificationDTO.getReturnValue() == 1 - && manualVerificationDTO.getCandidateList() != null - && manualVerificationDTO.getCandidateList().getCount() > 0) { - - // get the reference ids from response candidates. - List refIdsFromResponse = !CollectionUtils.isEmpty(manualVerificationDTO.getCandidateList().getCandidates()) ? - manualVerificationDTO.getCandidateList().getCandidates().stream().map(Candidate::getReferenceId).collect(Collectors.toList()) - : Collections.emptyList(); - - // get the reference ids from manual verification table entities. - List refIdsFromEntities = entities.stream().map(e -> e.getId().getMatchedRefId()).collect(Collectors.toList()); - - if (!CollectionUtils.isEmpty(refIdsFromResponse) && !manualVerificationDTO.getCandidateList().getCount().equals(refIdsFromResponse.size())) { - String errorMessage = "Validation error - Candidate count does not match reference ids count."; - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - regId, errorMessage); - auditLogRequestBuilder.createAuditRequestBuilder( - errorMessage + " Response received : " - +JsonUtils.javaObjectToJsonString(manualVerificationDTO), EventId.RPR_405.toString(), - EventName.EXCEPTION.name(), EventType.BUSINESS.name(), - PlatformSuccessMessages.RPR_MANUAL_VERIFICATION_RESEND.getCode(), ModuleName.MANUAL_ADJUDICATION.toString(), regId); - isValidationSuccess = false; - - } else if (!CollectionUtils.isEmpty(refIdsFromResponse) && !refIdsFromEntities.containsAll(refIdsFromResponse)) { - String errorMessage = "Validation error - Received ReferenceIds does not match reference ids in manual verification table."; - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - regId, errorMessage); - auditLogRequestBuilder.createAuditRequestBuilder( - errorMessage + " Response received : " - +JsonUtils.javaObjectToJsonString(manualVerificationDTO), EventId.RPR_405.toString(), - EventName.EXCEPTION.name(), EventType.BUSINESS.name(), - PlatformSuccessMessages.RPR_MANUAL_VERIFICATION_RESEND.getCode(), ModuleName.MANUAL_ADJUDICATION.toString(), regId); - isValidationSuccess = false; - } - } - return isValidationSuccess; - } - - /** - * This method would validate response and on failure it will mark the response for reprocessing. - * - * @param regId - * @param manualVerificationDTO - * @param entities - * @return boolean - * @throws JsonProcessingException - */ - public boolean isResendFlow(String regId, ManualAdjudicationResponseDTO manualVerificationDTO, List entities) throws JsonProcessingException { - boolean isResendFlow = false; - if(manualVerificationDTO.getReturnValue() == 2 || !isResponseValidationSuccess(regId, manualVerificationDTO, entities)) { - regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - regId, "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 - entities.forEach(e -> { - e.setStatusCode(ManualVerificationStatus.PENDING.name()); - basePacketRepository.update(e); - }); - isResendFlow = true; - } - return isResendFlow; - } - - -} +package io.mosip.registration.processor.adjudication.service.impl; + +import static io.mosip.registration.processor.adjudication.constants.ManualAdjudicationConstants.DATETIME_PATTERN; + +import java.io.IOException; +import java.net.MalformedURLException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +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.adjudication.constants.ManualAdjudicationConstants; +import io.mosip.registration.processor.adjudication.dto.DataShareRequestDto; +import io.mosip.registration.processor.adjudication.dto.ManualVerificationStatus; +import io.mosip.registration.processor.adjudication.exception.DataShareException; +import io.mosip.registration.processor.adjudication.exception.InvalidFileNameException; +import io.mosip.registration.processor.adjudication.exception.InvalidRidException; +import io.mosip.registration.processor.adjudication.exception.MatchedRefNotExistsException; +import io.mosip.registration.processor.adjudication.exception.NoRecordAssignedException; +import io.mosip.registration.processor.adjudication.request.dto.Filter; +import io.mosip.registration.processor.adjudication.request.dto.Gallery; +import io.mosip.registration.processor.adjudication.request.dto.ManualAdjudicationRequestDTO; +import io.mosip.registration.processor.adjudication.request.dto.ReferenceIds; +import io.mosip.registration.processor.adjudication.request.dto.ReferenceURL; +import io.mosip.registration.processor.adjudication.request.dto.ShareableAttributes; +import io.mosip.registration.processor.adjudication.request.dto.Source; +import io.mosip.registration.processor.adjudication.response.dto.Candidate; +import io.mosip.registration.processor.adjudication.response.dto.ManualAdjudicationResponseDTO; +import io.mosip.registration.processor.adjudication.service.ManualAdjudicationService; +import io.mosip.registration.processor.adjudication.stage.ManualAdjudicationStage; +import io.mosip.registration.processor.adjudication.util.ManualVerificationUpdateUtility; +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.constant.RegistrationType; +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.idrepo.dto.Documents; +import io.mosip.registration.processor.core.idrepo.dto.ResponseDTO; +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.manager.idreposervice.IdRepoService; +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.ManualVerificationEntity; +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; + +/** + * The Class ManualAdjudicationServiceImpl. + */ +@Component +@Transactional +public class ManualAdjudicationServiceImpl implements ManualAdjudicationService { + + /** The logger. */ + private static Logger regProcLogger = RegProcessorLogger.getLogger(ManualAdjudicationServiceImpl.class); + private LinkedHashMap policies = null; + private static final String MANUAL_ADJUDICATION = "manualadjudication"; + + /** 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"; + private static final String ID_REPO = "idrepo"; + private static final String PACKET = "packet"; + private static final String PROCESSED = "PROCESSED"; + @Autowired + private Environment env; + + /** The address. */ + @Value("${registration.processor.queue.manual.adjudication.request:mosip-to-adjudication}") + private String mvRequestAddress; + + /**Manual adjudication queue message expiry in seconds, if given 0 then message will never expire*/ + @Value("${registration.processor.queue.manual.adjudication.request.messageTTL}") + private int mvRequestMessageTTL; + + @Value("${registration.processor.manual.adjudication.policy.id:mpolicy-default-adjudication}") + private String policyId; + + @Value("${registration.processor.manual.adjudication.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; + + @Value("${mosip.regproc.manual.adjudication.use.lts.format:true}") + private boolean uselatestManualAdjudicationRequestFormat; + + @Autowired + private RegistrationProcessorRestClientService registrationProcessorRestClientService; + + @Autowired + private CbeffUtil cbeffutil; + + @Autowired + private Utilities utility; + + @Autowired + private IdRepoService idRepoService; + + @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 ManualAdjudicationStage manualAdjudicationStage; + + @Autowired + private RegistrationProcessorRestClientService restClientService; + + @Autowired + private PacketInfoManager packetInfoManager; + + @Autowired + private ObjectMapper mapper; + + @Autowired + RegistrationExceptionMapperUtil registrationExceptionMapperUtil; + + @Autowired + private ManualVerificationUpdateUtility manualVerificationUpdateUtility; + + /** The Constant PROTOCOL. */ + public static final String PROTOCOL = "https"; + + /* + * (non-Javadoc) + * + * @see io.mosip.registration.processor.manual.adjudication.service. + * ManualAdjudicationService#updatePacketStatus(io.mosip.registration.processor. + * manual.adjudication.dto.ManualVerificationDTO) + */ + @Override + public boolean updatePacketStatus(ManualAdjudicationResponseDTO 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(), "ManualVerificationServiceImpl::updatePacketStatus()::entry"); + + ManualVerificationEntity entity = validateRequestIdAndReturnRid(manualVerificationDTO.getRequestId()); + String regId = entity!=null?entity.getRegId():null; + + InternalRegistrationStatusDto registrationStatusDto = null; + + MessageDTO messageDTO = new MessageDTO(); + + + try { + registrationStatusDto = registrationStatusService + .getRegistrationStatus((entity!=null?entity.getRegId():null), null, null, (entity!=null?(entity.getId()!=null?entity.getId().getWorkflowInstanceId():null):null)); + registrationStatusDto.setLatestTransactionTypeCode(RegistrationTransactionTypeCode.MANUAL_ADJUDICATION.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(regId, manualVerificationDTO, entities)) { + registrationStatusDto.setStatusComment(StatusUtil.RPR_MANUAL_VERIFICATION_RESEND.getMessage()); + registrationStatusDto.setSubStatusCode(StatusUtil.RPR_MANUAL_VERIFICATION_RESEND.getCode()); + registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); + registrationStatusDto + .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.REPROCESS.toString()); + description.setMessage(PlatformSuccessMessages.RPR_MANUAL_VERIFICATION_RESEND.getMessage()); + description.setCode(PlatformSuccessMessages.RPR_MANUAL_VERIFICATION_RESEND.getCode()); + messageDTO.setInternalError(true); + messageDTO.setIsValid(isTransactionSuccessful); + manualAdjudicationStage.sendMessage(messageDTO); + } else { + // call success flow and process the response received from manual verification system + isTransactionSuccessful = successFlow( + entity, manualVerificationDTO, entities, 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 (IOException e) { + messageDTO.setInternalError(true); + registrationStatusDto.setLatestTransactionStatusCode(registrationExceptionMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.IOEXCEPTION)); + registrationStatusDto.setStatusComment(trimExceptionMessage + .trimExceptionMessage(StatusUtil.IO_EXCEPTION.getMessage() + e.getMessage())); + registrationStatusDto.setSubStatusCode(StatusUtil.IO_EXCEPTION.getCode()); + + description.setMessage(PlatformErrorMessages.RPR_SYS_IO_EXCEPTION.getMessage()); + description.setCode(PlatformErrorMessages.RPR_SYS_IO_EXCEPTION.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 { + if(messageDTO.getInternalError()) { + updateErrorFlags(registrationStatusDto, messageDTO); + } + /** Module-Id can be Both Success/Error code */ + String moduleId = isTransactionSuccessful + ? PlatformSuccessMessages.RPR_MANUAL_VERIFICATION_APPROVED.getCode() + : description.getCode(); + String moduleName = ModuleName.MANUAL_ADJUDICATION.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, "ManualVerificationServiceImpl::updatePacketStatus()::exit"); + return isTransactionSuccessful; + + } + + /** + * 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 ManualVerificationEntity validateRequestIdAndReturnRid(String reqId) { + List entities = basePacketRepository.getRegistrationIdbyRequestId(reqId); + + if (CollectionUtils.isEmpty(entities) || new HashSet<>(entities.stream().map(ManualVerificationEntity::getRegId).collect(Collectors.toList())).size() != 1) { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + entities != null ? entities.stream().map(ManualVerificationEntity::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()); + } + + ManualVerificationEntity entity = entities.iterator().next(); + + if (entity != null && StringUtils.isEmpty(entity.getRegId())) { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + entity.getRegId(), "ManualVerificationServiceImpl::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.getAllAssignedRecord( + regId, ManualVerificationStatus.INQUEUE.name()); + + if (CollectionUtils.isEmpty(entities)) { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + regId, "ManualVerificationServiceImpl::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; + } + + /* + * Get matched ref id for given RID and form request ,push to queue + */ + private void pushRequestToQueue(MessageDTO messageDTO, MosipQueue queue) throws Exception { + String refId = messageDTO.getRid(); + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + refId, "ManualVerificationServiceImpl::pushRequestToQueue()::entry"); + List mves = getMatchingEntitiesforRefId(refId); + if (mves == null || mves.isEmpty()) + throw new MatchedRefNotExistsException( + PlatformErrorMessages.RPR_MVS_NO_MATCHEDRID_FOUND_FOR_GIVEN_RID.getCode(), + PlatformErrorMessages.RPR_MVS_NO_MATCHEDRID_FOUND_FOR_GIVEN_RID.getMessage()); + + ManualAdjudicationRequestDTO mar=null; + if(uselatestManualAdjudicationRequestFormat) { + mar = prepareManualAdjudicationRequestLatest(messageDTO, mves); + }else { + mar = prepareManualAdjudicationRequest(messageDTO, mves); + } + String requestId = UUID.randomUUID().toString(); + mar.setRequestId(requestId); + regProcLogger.info("Request : " + JsonUtils.javaObjectToJsonString(mar)); + manualVerificationUpdateUtility.updateManualVerificationEntityRID(mves, requestId); + if (messageFormat.equalsIgnoreCase(TEXT_MESSAGE)) + mosipQueueManager.send(queue, JsonUtils.javaObjectToJsonString(mar), mvRequestAddress, mvRequestMessageTTL); + else + mosipQueueManager.send(queue, JsonUtils.javaObjectToJsonString(mar).getBytes(), mvRequestAddress, mvRequestMessageTTL); + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + refId, "ManualVerificationServiceImpl::pushRequestToQueue()::entry"); + } + + private String getDataShareUrl(String id, String process) throws Exception { + DataShareRequestDto requestDto = new DataShareRequestDto(); + + LinkedHashMap policy = getPolicy(); + + Map policyMap = getPolicyMap(policy); + + // set demographic + Map demographicMap = getDemographicMap(policyMap); + requestDto.setIdentity(packetManagerService.getFields(id, demographicMap.values().stream().collect(Collectors.toList()), process, ProviderStageName.MANUAL_ADJUDICATION)); + + // set documents + requestDto=setDocuments(policyMap, requestDto, id, process, null); + + // set audits + for(Entry entry: policyMap.entrySet()) { + if (entry.getValue().contains(AUDITS)) + requestDto.setAudits(JsonUtils.javaObjectToJsonString(packetManagerService.getAudits(id, process, ProviderStageName.MANUAL_ADJUDICATION))); + + // set metainfo + if (entry.getValue().contains(META_INFO)) + requestDto.setMetaInfo(JsonUtils.javaObjectToJsonString(packetManagerService.getMetaInfo(id, process, ProviderStageName.MANUAL_ADJUDICATION))); + + + // set biometrics + JSONObject regProcessorIdentityJson = utility.getRegistrationProcessorMappingJson(MappingJsonConstants.IDENTITY); + String individualBiometricsLabel = JsonUtil.getJSONValue( + JsonUtil.getJSONObject(regProcessorIdentityJson, MappingJsonConstants.INDIVIDUAL_BIOMETRICS), + MappingJsonConstants.VALUE); + + if (entry.getValue().contains(individualBiometricsLabel)) { + List modalities = getModalities(policy); + BiometricRecord biometricRecord = packetManagerService.getBiometrics( + id, individualBiometricsLabel, modalities, process, ProviderStageName.MANUAL_ADJUDICATION); + byte[] content = cbeffutil.createXML(biometricRecord.getSegments()); + requestDto.setBiometrics(content != null ? CryptoUtil.encodeToURLSafeBase64(content) : null); + } + } + + return CreateDataShareUrl(requestDto, policy); + } + + private String getDataShareUrlfromIdRepo(String id) throws DataShareException, ApisResourceAccessException, JsonProcessingException, IOException, PacketManagerException { + + DataShareRequestDto requestDto = new DataShareRequestDto(); + LinkedHashMap policy = getPolicy(); + Map policyMap = getPolicyMap(policy); + Map demographicMap = getDemographicMap(policyMap); + + ResponseDTO responseDTO=idRepoService.getIdResponseFromIDRepo(id); + + String identityResponse = mapper.writeValueAsString(responseDTO.getIdentity()); + Map identity=new HashMap<>(); + + for(Entry entry:demographicMap.entrySet()) { + JSONObject identityJson = JsonUtil.objectMapperReadValue(identityResponse, JSONObject.class); + identity.put(entry.getValue(),mapper.writeValueAsString(JsonUtil.getJSONValue(identityJson, entry.getValue()))); + } + requestDto.setIdentity(identity); + List documents=responseDTO.getDocuments(); + requestDto=setDocuments(policyMap, requestDto, null, null, documents); + + JSONObject regProcessorIdentityJson = utility.getRegistrationProcessorMappingJson(MappingJsonConstants.IDENTITY); + String individualBiometricsLabel = JsonUtil.getJSONValue( + JsonUtil.getJSONObject(regProcessorIdentityJson, MappingJsonConstants.INDIVIDUAL_BIOMETRICS), + MappingJsonConstants.VALUE); + for(Documents docs:documents) { + for(Entry entry: policyMap.entrySet()) { + if(entry.getValue().contains(individualBiometricsLabel) && docs.getCategory().equalsIgnoreCase(individualBiometricsLabel)){ + requestDto.setBiometrics(docs.getValue() != null ? docs.getValue() : null); + } + if(entry.getValue().contains(AUDITS) && docs.getCategory().equalsIgnoreCase(AUDITS)){ + requestDto.setAudits(docs.getValue() != null ? docs.getValue() : null); + } + if(entry.getValue().contains(META_INFO) && docs.getCategory().equalsIgnoreCase(META_INFO)){ + requestDto.setMetaInfo(docs.getValue() != null ? docs.getValue() : null); + } + } + } + + return CreateDataShareUrl(requestDto, policy); + + } + + @SuppressWarnings("rawtypes") + private String CreateDataShareUrl(DataShareRequestDto requestDto, LinkedHashMap policy) throws JsonProcessingException, MalformedURLException, ApisResourceAccessException, DataShareException { + String req = JsonUtils.javaObjectToJsonString(requestDto); + + MultiValueMap map = new LinkedMultiValueMap<>(); + map.add("name", MANUAL_ADJUDICATION); + map.add("filename", MANUAL_ADJUDICATION); + + ByteArrayResource contentsAsResource = new ByteArrayResource(req.getBytes()) { + @Override + public String getFilename() { + return MANUAL_ADJUDICATION; + } + }; + 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 response1 = (LinkedHashMap) registrationProcessorRestClientService.postApi(url, MediaType.MULTIPART_FORM_DATA, pathSegments, null, null, map, LinkedHashMap.class); + if (response1 == null || (response1.get(ERRORS) != null)) + throw new DataShareException(response1 == null ? "Datashare response is null" : response1.get(ERRORS).toString()); + + LinkedHashMap datashare = (LinkedHashMap) response1.get(DATASHARE); + return datashare.get(URL) != null ? datashare.get(URL).toString() : null; + } + + private Map getPolicyMap(LinkedHashMap policies) throws DataShareException, IOException, ApisResourceAccessException { + Map policyMap = new HashMap<>(); + List attributes = (List) policies.get(ManualAdjudicationConstants.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 Map getDemographicMap(Map policyMap){ + 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())); + return demographicMap; + } + private DataShareRequestDto setDocuments(Map policyMap,DataShareRequestDto requestDto, String id, String process, List documents) throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException{ + 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; + for(Entry entry: policyMap.entrySet()) { + 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(), 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; + } + + 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().isEmpty())) { + 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(ManualAdjudicationConstants.POLICIES); + } + return policies; + + } + + + public List getModalities(LinkedHashMap policy) throws IOException{ + Map> typeAndSubTypeMap = new HashMap<>(); + List attributes = (List) policy.get(ManualAdjudicationConstants.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; + + } + + /* + * get matched ref id for a given registration id + */ + private List getMatchingEntitiesforRefId(String rid) { + regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), rid, + "ManualVerificationServiceImpl::getMatchingEntitiesforRefId()::entry"); + + List matchedEntities = basePacketRepository.getMatchedIds(rid, ManualVerificationStatus.PENDING.name()); + + regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), rid, + "ManualVerificationServiceImpl::getMatchingEntitiesforRefId()::entry"); + + return matchedEntities; + } + + /* + * Form manual adjudication request + */ + private ManualAdjudicationRequestDTO prepareManualAdjudicationRequest(MessageDTO messageDTO, List mve) throws Exception { + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), "", + "ManualVerificationServiceImpl::formAdjudicationRequest()::entry"); + + ManualAdjudicationRequestDTO req = new ManualAdjudicationRequestDTO(); + req.setId(ManualAdjudicationConstants.MANUAL_ADJUDICATION_ID); + req.setVersion(ManualAdjudicationConstants.VERSION); + req.setRequestId(mve.get(0).getRequestId()); + req.setRequesttime(DateUtils.getUTCCurrentDateTimeString(env.getProperty(DATETIME_PATTERN))); + req.setReferenceId(mve.get(0).getRegId()); + InternalRegistrationStatusDto registrationStatusDto = null; + registrationStatusDto = registrationStatusService.getRegistrationStatus( + mve.get(0).getRegId(), messageDTO.getReg_type(), messageDTO.getIteration(), mve.get(0).getId().getWorkflowInstanceId()); + try { + req.setReferenceURL( + getDataShareUrl(mve.get(0).getRegId(), registrationStatusDto.getRegistrationType())); + + } catch (PacketManagerException | ApisResourceAccessException ex) { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + ex.getErrorCode(), ex.getErrorText()); + throw ex; + } + + List referenceIds = new ArrayList<>(); + mve.forEach(e -> { + ReferenceIds r = new ReferenceIds(); + InternalRegistrationStatusDto registrationStatusDto1 = null; + registrationStatusDto1 = registrationStatusService.getRegistrationStatus( + e.getId().getMatchedRefId(),messageDTO.getReg_type(), messageDTO.getIteration(),null); + + try { + r.setReferenceId(e.getId().getMatchedRefId()); + r.setReferenceURL(getDataShareUrl(e.getId().getMatchedRefId(),registrationStatusDto1.getRegistrationType())); + referenceIds.add(r); + } catch (PacketManagerException | ApisResourceAccessException ex) { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString(), ex.getErrorCode(), ex.getErrorText()); + r.setReferenceURL(null); + referenceIds.add(r); + } catch (Exception exp) { + regProcLogger.error(ExceptionUtils.getStackTrace(exp)); + } + + }); + Gallery g = new Gallery(); + g.setReferenceIds(referenceIds); + req.setGallery(g); + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), "", + "ManualVerificationServiceImpl::formAdjudicationRequest()::entry"); + + return req; + } + + /* + * Form manual adjudication request + */ + private ManualAdjudicationRequestDTO prepareManualAdjudicationRequestLatest(MessageDTO messageDTO, List mve) throws Exception { + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), "", + "ManualVerificationServiceImpl::formAdjudicationRequest()::entry"); + + ManualAdjudicationRequestDTO req = new ManualAdjudicationRequestDTO(); + req.setId(ManualAdjudicationConstants.MANUAL_ADJUDICATION_ID); + req.setVersion(ManualAdjudicationConstants.VERSION); + req.setRequestId(mve.get(0).getRequestId()); + req.setRequesttime(DateUtils.getUTCCurrentDateTimeString(env.getProperty(DATETIME_PATTERN))); + req.setReferenceId(mve.get(0).getRegId()); + InternalRegistrationStatusDto registrationStatusDto = null; + registrationStatusDto = registrationStatusService.getRegistrationStatus( + mve.get(0).getRegId(), messageDTO.getReg_type(), messageDTO.getIteration(), mve.get(0).getId().getWorkflowInstanceId()); + try { + req.setReferenceURL( + JsonUtil.objectMapperObjectToJson(addReferenceURLs(mve.get(0).getRegId(), registrationStatusDto))); + + } catch (PacketManagerException | ApisResourceAccessException ex) { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + ex.getErrorCode(), ex.getErrorText()); + throw ex; + } + + List referenceIds = new ArrayList<>(); + mve.forEach(e -> { + ReferenceIds r = new ReferenceIds(); + InternalRegistrationStatusDto registrationStatusDto1 = null; + registrationStatusDto1 = registrationStatusService.getRegistrationStatus( + e.getId().getMatchedRefId(),messageDTO.getReg_type(), messageDTO.getIteration(), null); + + try { + r.setReferenceId(e.getId().getMatchedRefId()); + r.setReferenceURL(JsonUtil.objectMapperObjectToJson(addReferenceURLs(e.getId().getMatchedRefId(),registrationStatusDto1))); + referenceIds.add(r); + } catch (PacketManagerException | ApisResourceAccessException ex) { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString(), ex.getErrorCode(), ex.getErrorText()); + r.setReferenceURL(null); + referenceIds.add(r); + } catch (Exception exp) { + regProcLogger.error(ExceptionUtils.getStackTrace(exp)); + } + + }); + Gallery g = new Gallery(); + g.setReferenceIds(referenceIds); + req.setGallery(g); + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), "", + "ManualVerificationServiceImpl::formAdjudicationRequest()::entry"); + + return req; + } + + private List addReferenceURLs(String id,InternalRegistrationStatusDto registrationStatusDto) throws Exception { + List referenceURLs=new ArrayList<>(); + if( registrationStatusDto.getStatusCode().equalsIgnoreCase(RegistrationStatusCode.PROCESSED.name())) { + ReferenceURL referenceURL=new ReferenceURL(); + referenceURL.setSource(ID_REPO); + referenceURL.setStatus(registrationStatusDto.getStatusCode()); + referenceURL.setURL(getDataShareUrlfromIdRepo(id)); + referenceURLs.add(referenceURL); + } + else{ + ReferenceURL referenceURL=new ReferenceURL(); + referenceURL.setSource(PACKET); + referenceURL.setStatus(registrationStatusDto.getStatusCode()); + referenceURL.setURL( + getDataShareUrl(id,registrationStatusDto.getRegistrationType())); + referenceURLs.add(referenceURL); + if(registrationStatusDto.getRegistrationType().equalsIgnoreCase(RegistrationType.UPDATE.name()) + || registrationStatusDto.getRegistrationType().equalsIgnoreCase(RegistrationType.RES_UPDATE.name())) { + String uinField = utility.getUIn(id, registrationStatusDto.getRegistrationType(), ProviderStageName.MANUAL_ADJUDICATION); + ReferenceURL referenceURL1=new ReferenceURL(); + referenceURL1.setSource(ID_REPO); + referenceURL1.setStatus(PROCESSED); + referenceURL1.setURL( + getDataShareUrlfromIdRepo(uinField)); + referenceURLs.add(referenceURL1); + } + } + return referenceURLs; + } + + /* + * 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 object, MosipQueue queue) { + InternalRegistrationStatusDto registrationStatusDto=new InternalRegistrationStatusDto(); + TrimExceptionMessage trimExceptionMessage = new TrimExceptionMessage(); + LogDescription description = new LogDescription(); + String moduleName = ModuleName.MANUAL_ADJUDICATION.toString(); + String moduleId = PlatformSuccessMessages.RPR_MANUAL_VERIFICATION_SENT.getCode(); + String registrationId = object.getRid(); + boolean isTransactionSuccessful = false; + try { + object.setInternalError(false); + object.setIsValid(false); + object.setMessageBusAddress(MessageBusAddress.MANUAL_ADJUDICATION_BUS_IN); + + if (null == object.getRid() || object.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()); + } + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + object.getRid(), "ManualVerificationServiceImpl::process()::entry"); + + registrationStatusDto = registrationStatusService + .getRegistrationStatus(object.getRid(), object.getReg_type(), object.getIteration(), object.getWorkflowInstanceId()); + + pushRequestToQueue(object, queue); + isTransactionSuccessful=true; + registrationStatusDto.setStatusComment(StatusUtil.RPR_MANUAL_VERIFICATION_SENT_TO_QUEUE.getMessage()); + registrationStatusDto.setSubStatusCode(StatusUtil.RPR_MANUAL_VERIFICATION_SENT_TO_QUEUE.getCode()); + registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); + registrationStatusDto + .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.IN_PROGRESS.toString()); + + } catch (DataShareException de) { + registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.name()); + registrationStatusDto.setStatusComment(trimExceptionMessage + .trimExceptionMessage(StatusUtil.MANUAL_ADJUDICATION_FAILED.getMessage() + de.getMessage())); + registrationStatusDto.setSubStatusCode(StatusUtil.MANUAL_ADJUDICATION_FAILED.getCode()); + registrationStatusDto.setLatestTransactionStatusCode( + registrationExceptionMapperUtil.getStatusCode(RegistrationExceptionTypeCode.MANUAL_VERIFICATION_FAILED)); + description.setCode(PlatformErrorMessages.MANUAL_VERIFICATION_FAILED.getCode()); + description.setMessage(PlatformErrorMessages.MANUAL_VERIFICATION_FAILED.getMessage()); + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), description.getCode(), object.getRid(), + description.getMessage() + ExceptionUtils.getStackTrace(de)); + object.setInternalError(true); + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + de.getErrorCode(), de.getErrorText()); + + } catch (InvalidRidException exp) { + registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.name()); + registrationStatusDto.setStatusComment(trimExceptionMessage + .trimExceptionMessage(StatusUtil.MANUAL_ADJUDICATION_RID_SHOULD_NOT_EMPTY_OR_NULL.getMessage() + exp.getMessage())); + registrationStatusDto.setSubStatusCode(StatusUtil.MANUAL_ADJUDICATION_RID_SHOULD_NOT_EMPTY_OR_NULL.getCode()); + registrationStatusDto.setLatestTransactionStatusCode( + registrationExceptionMapperUtil.getStatusCode(RegistrationExceptionTypeCode.MANUAL_VERIFICATION_FAILED)); + description.setCode(PlatformErrorMessages.RPR_MVS_NO_RID_SHOULD_NOT_EMPTY_OR_NULL.getCode()); + description.setMessage(PlatformErrorMessages.RPR_MVS_NO_RID_SHOULD_NOT_EMPTY_OR_NULL.getMessage()); + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), description.getCode(), null, + description.getMessage() + ExceptionUtils.getStackTrace(exp)); + object.setInternalError(true); + + } catch (Exception e) { + registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.name()); + registrationStatusDto.setStatusComment(trimExceptionMessage + .trimExceptionMessage(StatusUtil.UNKNOWN_EXCEPTION_OCCURED.getMessage() + e.getMessage())); + registrationStatusDto.setSubStatusCode(StatusUtil.UNKNOWN_EXCEPTION_OCCURED.getCode()); + registrationStatusDto.setLatestTransactionStatusCode( + registrationExceptionMapperUtil.getStatusCode(RegistrationExceptionTypeCode.MANUAL_VERIFICATION_FAILED)); + description.setCode(PlatformErrorMessages.MANUAL_VERIFICATION_FAILED.getCode()); + description.setMessage(PlatformErrorMessages.MANUAL_VERIFICATION_FAILED.getMessage()); + object.setInternalError(true); + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), description.getCode(), object.getRid(), + description.getMessage() + ExceptionUtils.getStackTrace(e)); + }finally { + registrationStatusDto + .setLatestTransactionTypeCode(RegistrationTransactionTypeCode.MANUAL_ADJUDICATION.toString()); + registrationStatusService.updateRegistrationStatus(registrationStatusDto, moduleId, moduleName); + if (object.getInternalError()) { + updateErrorFlags(registrationStatusDto, object); + } + if (object.getIsValid() && !object.getInternalError()) + regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString(), registrationId, "ManualVerificationServiceImpl::process()::success"); + else + regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString(), registrationId, "ManualVerificationServiceImpl::process()::failure"); + + String eventId = isTransactionSuccessful ? EventId.RPR_402.toString() : EventId.RPR_405.toString(); + String eventName = isTransactionSuccessful ? EventName.UPDATE.toString() : EventName.EXCEPTION.toString(); + String eventType = isTransactionSuccessful ? EventType.BUSINESS.toString() : EventType.SYSTEM.toString(); + + auditLogRequestBuilder.createAuditRequestBuilder(description.getMessage(), eventId, eventName, eventType, + moduleId, moduleName, registrationId); + + } + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + object.getRid(), "ManualVerificationServiceImpl::process()::exit"); + + return object; + } + + /** + * Process response for success flow. + * + * @param entity + * @param manualVerificationDTO + * @param entities + * @param registrationStatusDto + * @param messageDTO + * @param description + * @return boolean + * @throws com.fasterxml.jackson.core.JsonProcessingException + */ + private boolean successFlow(ManualVerificationEntity entity, ManualAdjudicationResponseDTO manualVerificationDTO, + List entities, + InternalRegistrationStatusDto registrationStatusDto, MessageDTO messageDTO, + LogDescription description) throws com.fasterxml.jackson.core.JsonProcessingException { + + boolean isTransactionSuccessful = false; + String statusCode = manualVerificationDTO.getReturnValue() == 1 && + CollectionUtils.isEmpty(manualVerificationDTO.getCandidateList().getCandidates()) ? + ManualVerificationStatus.APPROVED.name() : ManualVerificationStatus.REJECTED.name(); + + for (int i = 0; i < entities.size(); i++) { + byte[] responsetext = mapper.writeValueAsBytes(manualVerificationDTO); + + ManualVerificationEntity manualVerificationEntity=entities.get(i); + manualVerificationEntity.setStatusCode(statusCode); + manualVerificationEntity.setReponseText(responsetext); + manualVerificationEntity.setStatusComment(statusCode.equalsIgnoreCase(ManualVerificationStatus.APPROVED.name()) ? + StatusUtil.MANUAL_VERIFIER_APPROVED_PACKET.getMessage() : + StatusUtil.MANUAL_VERIFIER_REJECTED_PACKET.getMessage()); + entities.set(i, manualVerificationEntity); + } + isTransactionSuccessful = true; + registrationStatusDto + .setLatestTransactionTypeCode(RegistrationTransactionTypeCode.MANUAL_ADJUDICATION.toString()); + registrationStatusDto.setRegistrationStageName(registrationStatusDto.getRegistrationStageName()); + + if (statusCode != null && statusCode.equalsIgnoreCase(ManualVerificationStatus.APPROVED.name())) { + if (registrationStatusDto.getRegistrationType().equalsIgnoreCase(RegistrationType.LOST.toString())) { + for(ManualVerificationEntity detail: entities) { + packetInfoManager.saveRegLostUinDet(entity.getRegId(), + entity.getId().getWorkflowInstanceId(), detail.getId().getMatchedRefId(), + PlatformSuccessMessages.RPR_MANUAL_VERIFICATION_APPROVED.getCode(), + ModuleName.MANUAL_ADJUDICATION.toString()); + } + } + messageDTO.setIsValid(isTransactionSuccessful); + manualAdjudicationStage.sendMessage(messageDTO); + registrationStatusDto.setStatusComment(StatusUtil.MANUAL_VERIFIER_APPROVED_PACKET.getMessage()); + registrationStatusDto.setSubStatusCode(StatusUtil.MANUAL_VERIFIER_APPROVED_PACKET.getCode()); + registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); + registrationStatusDto + .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.SUCCESS.toString()); + + description.setMessage(PlatformSuccessMessages.RPR_MANUAL_VERIFICATION_APPROVED.getMessage()); + description.setCode(PlatformSuccessMessages.RPR_MANUAL_VERIFICATION_APPROVED.getCode()); + + } else if (statusCode != null && statusCode.equalsIgnoreCase(ManualVerificationStatus.REJECTED.name())) { + registrationStatusDto.setStatusCode(RegistrationStatusCode.REJECTED.toString()); + registrationStatusDto.setStatusComment(StatusUtil.MANUAL_VERIFIER_REJECTED_PACKET.getMessage()); + registrationStatusDto.setSubStatusCode(StatusUtil.MANUAL_VERIFIER_REJECTED_PACKET.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); + manualAdjudicationStage.sendMessage(messageDTO); + } else { + registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); + registrationStatusDto.setStatusComment(StatusUtil.RPR_MANUAL_VERIFICATION_RESEND.getMessage()); + registrationStatusDto.setSubStatusCode(StatusUtil.RPR_MANUAL_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); + manualAdjudicationStage.sendMessage(messageDTO); + } + List maVerificationEntity = new ArrayList<>(); + for(ManualVerificationEntity manualVerificationEntity: entities) { + maVerificationEntity.add(basePacketRepository.update(manualVerificationEntity)); + } + + 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); + } + } + + /** + * Validate the response received from manual verification system. + * + * @param regId + * @param manualVerificationDTO + * @param entities + * @return boolean + * @throws JsonProcessingException + */ + private boolean isResponseValidationSuccess(String regId, ManualAdjudicationResponseDTO manualVerificationDTO, List entities) throws JsonProcessingException { + boolean isValidationSuccess = true; + // if candidate count is a positive number + if (manualVerificationDTO.getReturnValue() == 1 + && manualVerificationDTO.getCandidateList() != null + && manualVerificationDTO.getCandidateList().getCount() > 0) { + + // get the reference ids from response candidates. + List refIdsFromResponse = !CollectionUtils.isEmpty(manualVerificationDTO.getCandidateList().getCandidates()) ? + manualVerificationDTO.getCandidateList().getCandidates().stream().map(Candidate::getReferenceId).collect(Collectors.toList()) + : Collections.emptyList(); + + // get the reference ids from manual verification table entities. + List refIdsFromEntities = entities.stream().map(e -> e.getId().getMatchedRefId()).collect(Collectors.toList()); + + if (!CollectionUtils.isEmpty(refIdsFromResponse) && !manualVerificationDTO.getCandidateList().getCount().equals(refIdsFromResponse.size())) { + String errorMessage = "Validation error - Candidate count does not match reference ids count."; + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + regId, errorMessage); + auditLogRequestBuilder.createAuditRequestBuilder( + errorMessage + " Response received : " + +JsonUtils.javaObjectToJsonString(manualVerificationDTO), EventId.RPR_405.toString(), + EventName.EXCEPTION.name(), EventType.BUSINESS.name(), + PlatformSuccessMessages.RPR_MANUAL_VERIFICATION_RESEND.getCode(), ModuleName.MANUAL_ADJUDICATION.toString(), regId); + isValidationSuccess = false; + + } else if (!CollectionUtils.isEmpty(refIdsFromResponse) && !refIdsFromEntities.containsAll(refIdsFromResponse)) { + String errorMessage = "Validation error - Received ReferenceIds does not match reference ids in manual verification table."; + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + regId, errorMessage); + auditLogRequestBuilder.createAuditRequestBuilder( + errorMessage + " Response received : " + +JsonUtils.javaObjectToJsonString(manualVerificationDTO), EventId.RPR_405.toString(), + EventName.EXCEPTION.name(), EventType.BUSINESS.name(), + PlatformSuccessMessages.RPR_MANUAL_VERIFICATION_RESEND.getCode(), ModuleName.MANUAL_ADJUDICATION.toString(), regId); + isValidationSuccess = false; + } + } + return isValidationSuccess; + } + + /** + * This method would validate response and on failure it will mark the response for reprocessing. + * + * @param regId + * @param manualVerificationDTO + * @param entities + * @return boolean + * @throws JsonProcessingException + */ + public boolean isResendFlow(String regId, ManualAdjudicationResponseDTO manualVerificationDTO, List entities) throws JsonProcessingException { + boolean isResendFlow = false; + if(manualVerificationDTO.getReturnValue() == 2 || !isResponseValidationSuccess(regId, manualVerificationDTO, entities)) { + regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + regId, "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 + entities.forEach(e -> { + e.setStatusCode(ManualVerificationStatus.PENDING.name()); + basePacketRepository.update(e); + }); + isResendFlow = true; + } + return isResendFlow; + } + + +} From 5419619c4ffd9b5ceb532753727ab95dd8499a0c Mon Sep 17 00:00:00 2001 From: Sowmya Ujjappa Banakar Date: Wed, 10 May 2023 16:18:28 +0530 Subject: [PATCH 066/133] MOSIP-23715 code changes --- .../stage/test/AbisHandlerStageTest.java | 2040 +++---- .../stage/AbisMiddleWareStageTest.java | 1380 ++--- .../biodedupe/stage/BioDedupeStageTest.java | 13 + .../BiometricAuthenticationStageTest.java | 1233 ++--- .../test/BiometricExtractionStageTest.java | 13 + .../demodedupe/DemoDedupeStageTest.java | 13 + .../stage/tests/FinalizationStageTest.java | 13 + .../uigenerator/UinGeneratorStageTest.java | 4667 +++++++++-------- .../stage/test/MessageSenderStageTest.java | 1853 +++---- .../print/stage/test/PrintingStageTest.java | 869 +-- .../cmdvalidator/CMDValidatorStageTest.java | 245 +- .../app/IntroducerValidatorStageTest.java | 245 +- .../app/OperatorValidatorStageTest.java | 245 +- .../PacketClassifierStageTest.java | 15 +- .../stage/test/PacketUploaderStageTest.java | 287 +- .../validator/PacketValidatorStageTest.java | 13 + .../test/QualityClassifierStageTest.java | 1159 ++-- .../app/SupervisorValidatorStageTest.java | 245 +- .../core/abstractverticle/HealthCheckDTO.java | 12 + .../core/abstractverticle/MosipEventBus.java | 2 + .../MosipVerticleAPIManager.java | 424 +- .../MosipVerticleManager.java | 761 ++- .../StageHealthCheckHandler.java | 72 +- .../core/eventbus/KafkaMosipEventBus.java | 42 +- .../core/eventbus/VertxMosipEventBus.java | 28 +- .../core/eventbus/KafkaMosipEventBusTest.java | 1339 ++--- .../verticle/ReprocessingSchedulerTest.java | 595 ++- .../verticle/ReprocessorVerticleTest.java | 509 +- .../verticle/WorkflowActionApiTest.java | 13 + .../WorkflowActionJobSchedularTest.java | 582 +- .../verticle/WorkflowActionJobTest.java | 17 +- .../WorkflowInternalActionVerticleTest.java | 1417 ++--- 32 files changed, 10411 insertions(+), 9950 deletions(-) create mode 100644 registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/abstractverticle/HealthCheckDTO.java diff --git a/registration-processor/core-processor/registration-processor-abis-handler-stage/src/test/java/io/mosip/registration/processor/abis/handler/stage/test/AbisHandlerStageTest.java b/registration-processor/core-processor/registration-processor-abis-handler-stage/src/test/java/io/mosip/registration/processor/abis/handler/stage/test/AbisHandlerStageTest.java index edcffd7501d..ef6cbf134de 100644 --- a/registration-processor/core-processor/registration-processor-abis-handler-stage/src/test/java/io/mosip/registration/processor/abis/handler/stage/test/AbisHandlerStageTest.java +++ b/registration-processor/core-processor/registration-processor-abis-handler-stage/src/test/java/io/mosip/registration/processor/abis/handler/stage/test/AbisHandlerStageTest.java @@ -1,1013 +1,1029 @@ -package io.mosip.registration.processor.abis.handler.stage.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.Type; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; - -import org.assertj.core.util.Lists; -import org.junit.Before; -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.beans.factory.annotation.Autowired; -import org.springframework.core.env.Environment; -import org.springframework.http.MediaType; -import org.springframework.test.util.ReflectionTestUtils; - -import com.fasterxml.jackson.databind.ObjectMapper; -import com.google.common.reflect.TypeToken; -import com.google.gson.Gson; - -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.JsonUtils; -import io.mosip.kernel.core.util.exception.JsonProcessingException; -import io.mosip.registration.processor.abis.handler.dto.DataShare; -import io.mosip.registration.processor.abis.handler.dto.DataShareResponseDto; -import io.mosip.registration.processor.core.packet.dto.datashare.Filter; -import io.mosip.registration.processor.core.packet.dto.datashare.ShareableAttributes; -import io.mosip.registration.processor.core.packet.dto.datashare.Source; -import io.mosip.registration.processor.abis.handler.stage.AbisHandlerStage; -import io.mosip.registration.processor.abis.queue.dto.AbisQueueDetails; -import io.mosip.registration.processor.core.abstractverticle.EventDTO; -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.common.rest.dto.ErrorDTO; -import io.mosip.registration.processor.core.constant.PolicyConstant; -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.Identity; -import io.mosip.registration.processor.core.packet.dto.abis.AbisApplicationDto; -import io.mosip.registration.processor.core.packet.dto.abis.AbisIdentifyRequestDto; -import io.mosip.registration.processor.core.packet.dto.abis.AbisInsertRequestDto; -import io.mosip.registration.processor.core.packet.dto.abis.AbisRequestDto; -import io.mosip.registration.processor.core.packet.dto.abis.RegBioRefDto; -import io.mosip.registration.processor.core.packet.dto.abis.RegDemoDedupeListDto; -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.packet.storage.dto.ApplicantInfoDto; -import io.mosip.registration.processor.packet.storage.utils.PacketManagerService; -import io.mosip.registration.processor.packet.storage.utils.PriorityBasedPacketManagerService; -import io.mosip.registration.processor.packet.storage.utils.Utilities; -import io.mosip.registration.processor.rest.client.audit.builder.AuditLogRequestBuilder; -import io.mosip.registration.processor.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; - -@RunWith(PowerMockRunner.class) -@PrepareForTest({ JsonUtils.class }) -@PowerMockIgnore({ "com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "javax.management.*", "javax.net.ssl.*" }) -public class AbisHandlerStageTest { - - @Mock - private AuditLogRequestBuilder auditLogRequestBuilder; - - @Mock - private RegistrationStatusService registrationStatusService; - - @Mock - private PacketInfoManager packetInfoManager; - - private InternalRegistrationStatusDto registrationStatusDto = new InternalRegistrationStatusDto(); - - @Mock - private Utilities utility; - - @Spy - private ObjectMapper mapper = new ObjectMapper(); - - @Mock - private PriorityBasedPacketManagerService packetManagerService; - - @Mock - private PacketManagerService packetService; - - @Mock - private LogDescription description; - - List abisApplicationDtos = new ArrayList<>(); - - List bioRefDtos = new ArrayList<>(); - - List regDemoDedupeListDtoList = new ArrayList<>(); - - List abisRequestDtoList = new ArrayList<>(); - - Map tags = new HashMap(); - - @Mock - private Environment env; - - @Mock - private RegistrationProcessorRestClientService registrationProcessorRestClientService; - - @Mock - private CbeffUtil cbeffutil; - - @InjectMocks - private AbisHandlerStage abisHandlerStage = new AbisHandlerStage() { - @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 consumeAndSend(MosipEventBus mosipEventBus, MessageBusAddress fromAddress, - MessageBusAddress toAddress, long messageExpiryTimeLimit) { - } - - @Override - public Integer getPort() { - return 8080; - }; - }; - - @Before - public void setUp() throws Exception { - ReflectionTestUtils.setField(abisHandlerStage, "maxResults", "30"); - ReflectionTestUtils.setField(abisHandlerStage, "targetFPIR", "30"); - ReflectionTestUtils.setField(abisHandlerStage, "workerPoolSize", 10); - ReflectionTestUtils.setField(abisHandlerStage, "messageExpiryTimeLimit", Long.valueOf(0)); - ReflectionTestUtils.setField(abisHandlerStage, "clusterManagerUrl", "/dummyPath"); - ReflectionTestUtils.setField(abisHandlerStage, "httpProtocol", "http"); - ReflectionTestUtils.setField(abisHandlerStage, "internalDomainName", "localhost"); - Mockito.when(env.getProperty("mosip.registration.processor.datetime.pattern")) - .thenReturn("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); - - Map> biometricModalitySegmentsMap = new HashMap(); - Map> biometricModalitySegmentsMapInfant = new HashMap(); - biometricModalitySegmentsMapInfant.put("Face", getFaceList()); - biometricModalitySegmentsMap.put("Finger", getFingerList()); - biometricModalitySegmentsMap.put("Iris", getIrisList()); - biometricModalitySegmentsMap.put("Face", getFaceList()); - ReflectionTestUtils.setField(abisHandlerStage, "biometricModalitySegmentsMapInfant", biometricModalitySegmentsMapInfant); - ReflectionTestUtils.setField(abisHandlerStage, "biometricModalitySegmentsMapMinor", biometricModalitySegmentsMap); - ReflectionTestUtils.setField(abisHandlerStage, "biometricModalitySegmentsMapAdult", biometricModalitySegmentsMap); - ReflectionTestUtils.setField(abisHandlerStage, "exceptionSegmentsMap", getExceptionModalityMap()); - - Mockito.when(env.getProperty("DATASHARECREATEURL")).thenReturn("/v1/datashare/create"); - AbisApplicationDto dto = new AbisApplicationDto(); - dto.setCode("ABIS1"); - abisApplicationDtos.add(dto); - - Mockito.doNothing().when(description).setMessage(any()); - Mockito.when(description.getMessage()).thenReturn("description"); - - - Mockito.when(packetManagerService.getBiometrics(any(), any(), any(), any(), any())).thenReturn(getBiometricRecord(Arrays.asList("Left Thumb" ,"Right Thumb" , "Left MiddleFinger" , - "Left RingFinger" ,"Left LittleFinger" ,"Left IndexFinger" ,"Right MiddleFinger" , - "Right RingFinger" ,"Right LittleFinger" ,"Right IndexFinger" , - "Left" ,"Right","Face"),false)); - mockDataSharePolicy(Lists.newArrayList(BiometricType.FINGER,BiometricType.IRIS,BiometricType.FACE)); - - List list = new LinkedList<>(); - setMetaInfoMap(list); - - //Mockito.doNothing().when(registrationStatusDto).setLatestTransactionStatusCode(any()); - Mockito.doNothing().when(registrationStatusService).updateRegistrationStatus(any(), any(), any()); - - Mockito.when(packetInfoManager.getAbisRequestsByBioRefId(any())).thenReturn(abisRequestDtoList); - - AbisQueueDetails abisQueueDetails = new AbisQueueDetails(); - abisQueueDetails.setName("ABIS1"); - List abisQueueDetailsList = new ArrayList<>(); - abisQueueDetailsList.add(abisQueueDetails); - Mockito.when(utility.getAbisQueueDetails()).thenReturn(abisQueueDetailsList); - - AuditResponseDto auditResponseDto = new AuditResponseDto(); - ResponseWrapper responseWrapper = new ResponseWrapper<>(); - responseWrapper.setResponse(auditResponseDto); - Mockito.when(auditLogRequestBuilder.createAuditRequestBuilder(any(), any(), any(), any(), any(), any(), any())) - .thenReturn(responseWrapper); - - DataShareResponseDto dataShareResponseDto = new DataShareResponseDto(); - DataShare dataShare = new DataShare(); - dataShare.setUrl("http://localhost"); - dataShareResponseDto.setDataShare(dataShare); - - mockDataSharePolicy(Lists.newArrayList(BiometricType.FACE, BiometricType.FINGER)); - - Mockito.when(registrationProcessorRestClientService.postApi(anyString(), any(MediaType.class), any(), any(), - any(), any(), any())).thenReturn(dataShareResponseDto); - - Mockito.when(cbeffutil.createXML(any())).thenReturn(new byte[2048]); - } - - private Map getExceptionModalityMap() { - Map exceptionMap = new HashMap(); - exceptionMap.put("Left Thumb" , "leftThumb"); - exceptionMap.put("Right Thumb" , "rightThumb"); - exceptionMap.put("Left MiddleFinger" , "leftMiddle"); - exceptionMap.put("Left RingFinger" , "leftRing"); - exceptionMap.put("Left LittleFinger" , "leftLittle"); - exceptionMap.put("Left IndexFinger" , "leftIndex"); - exceptionMap.put("Right MiddleFinger" , "rightMiddle"); - exceptionMap.put("Right RingFinger" , "rightRing"); - exceptionMap.put("Right LittleFinger" , "rightLittle"); - exceptionMap.put("Right IndexFinger" , "rightIndex"); - exceptionMap.put("Left" , "leftEye"); - exceptionMap.put("Right" , "rightEye"); - exceptionMap.put("Face" , "face"); - - return exceptionMap; - } - - private List getFaceList() { - return Arrays.asList("Face"); - } - - private List getIrisList() { - return Arrays.asList("Left", "Right"); - - } - - private List getFingerList() { - return Arrays.asList("Left Thumb", "Left LittleFinger", "Left IndexFinger", "Left MiddleFinger", - "Left RingFinger", "Right Thumb", "Right LittleFinger", - "Right IndexFinger", "Right MiddleFinger", - "Right RingFinger"); - } - - private void mockDataSharePolicy(List sherableBiometricList) throws ApisResourceAccessException { - when(registrationProcessorRestClientService.getApi(any(), any(), anyString(), anyString(), any())) - .thenReturn(getMockDataSharePolicy(sherableBiometricList)); - } - - private ResponseWrapper> getMockDataSharePolicy( - List sherableBiometricList) { - - ObjectMapper mapper = new ObjectMapper(); - - List attr = new LinkedList<>(); - if (sherableBiometricList != null && !sherableBiometricList.isEmpty()) { - - ShareableAttributes shareableAttributes = new ShareableAttributes(); - List sourceList = new ArrayList<>(); - - for (BiometricType bioType : sherableBiometricList) { - Filter filter = new Filter(); - filter.setType(bioType.value()); - Source src = new Source(); - src.setFilter(Lists.newArrayList(filter)); - sourceList.add(src); - } - - shareableAttributes.setSource(sourceList); - attr = Lists.newArrayList(shareableAttributes); - } - - ResponseWrapper> policy = new ResponseWrapper<>(); - LinkedHashMap policies = new LinkedHashMap<>(); - LinkedHashMap sharableAttributes = new LinkedHashMap<>(); - sharableAttributes.put(PolicyConstant.SHAREABLE_ATTRIBUTES, attr); - policies.put(PolicyConstant.POLICIES, sharableAttributes); - policy.setResponse(policies); - - return policy; - } - - @Test - public void testDeployVerticle() { - abisHandlerStage.deployVerticle(); - } - - @Test - public void testDemoToAbisHandlerTOMiddlewareSuccess() throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { - registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); - registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); - Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); - Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); - Mockito.when(packetInfoManager.getAllAbisDetails()).thenReturn(abisApplicationDtos); - - mockDataSharePolicy(Lists.newArrayList(BiometricType.IRIS, BiometricType.FINGER, BiometricType.FACE)); - Mockito.when(packetInfoManager.getBioRefIdByRegId(any())).thenReturn(bioRefDtos); - tags.put("AGE_GROUP", "ADULT"); - Mockito.when(packetService.getAllTags(any())).thenReturn(tags); - - Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); - Mockito.doNothing().when(packetInfoManager).saveAbisRequest(any(), any(), any()); - - RegDemoDedupeListDto regDemoDedupeListDto = new RegDemoDedupeListDto(); - regDemoDedupeListDto.setMatchedRegId("10003100030001520190422074511"); - regDemoDedupeListDtoList.add(regDemoDedupeListDto); - Mockito.when(packetInfoManager.getDemoListByTransactionId(any())).thenReturn(regDemoDedupeListDtoList); - - MessageDTO dto = new MessageDTO(); - dto.setRid("10003100030001520190422074511"); - MessageDTO result = abisHandlerStage.process(dto); - - assertTrue(result.getMessageBusAddress().getAddress().equalsIgnoreCase("abis-middle-ware-bus-in")); - } - - @Test - public void testBioToAbisHandlerToMiddlewareSuccess() throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { - registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); - registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); - Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); - Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); - Mockito.when(packetInfoManager.getAllAbisDetails()).thenReturn(abisApplicationDtos); - - mockDataSharePolicy(Lists.newArrayList(BiometricType.IRIS, BiometricType.FINGER, BiometricType.FACE)); - RegBioRefDto regBioRefDto = new RegBioRefDto(); - regBioRefDto.setBioRefId("1234567890"); - bioRefDtos.add(regBioRefDto); - Mockito.when(packetInfoManager.getBioRefIdByRegId(any())).thenReturn(bioRefDtos); - tags.put("AGE_GROUP", "ADULT"); - Mockito.when(packetService.getAllTags(any())).thenReturn(tags); - - Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); - Mockito.doNothing().when(packetInfoManager).saveAbisRequest(any(), any(), any()); - - RegDemoDedupeListDto regDemoDedupeListDto = new RegDemoDedupeListDto(); - regDemoDedupeListDto.setMatchedRegId("10003100030001520190422074511"); - regDemoDedupeListDtoList.add(regDemoDedupeListDto); - Mockito.when(packetInfoManager.getDemoListByTransactionId(any())).thenReturn(regDemoDedupeListDtoList); - - MessageDTO dto = new MessageDTO(); - dto.setRid("10003100030001520190422074511"); - MessageDTO result = abisHandlerStage.process(dto); - - assertTrue(result.getMessageBusAddress().getAddress().equalsIgnoreCase("abis-middle-ware-bus-in")); - } - - @Test - public void testMiddlewareToAbisHandlerToDemoSuccess() { - registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); - registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); - Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); - Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.TRUE); - - MessageDTO dto = new MessageDTO(); - dto.setRid("10003100030001520190422074511"); - MessageDTO result = abisHandlerStage.process(dto); - - assertTrue(result.getMessageBusAddress().getAddress().equalsIgnoreCase("demo-dedupe-bus-in")); - } - - @Test - public void testMiddlewareToAbisHandlerToBioSuccess() { - registrationStatusDto.setLatestTransactionTypeCode("BIOGRAPHIC_VERIFICATION"); - registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); - Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); - Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.TRUE); - - MessageDTO dto = new MessageDTO(); - dto.setRid("10003100030001520190422074511"); - MessageDTO result = abisHandlerStage.process(dto); - - assertTrue(result.getMessageBusAddress().getAddress().equalsIgnoreCase("bio-dedupe-bus-in")); - } - - @Test - public void testDemoDedupeDataNotFound() { - registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); - registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); - Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); - Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); - Mockito.when(packetInfoManager.getAllAbisDetails()).thenReturn(abisApplicationDtos); - - Mockito.when(packetInfoManager.getBioRefIdByRegId(any())).thenReturn(bioRefDtos); - - Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); - Mockito.doNothing().when(packetInfoManager).saveAbisRequest(any(), any(), any()); - - Mockito.when(packetInfoManager.getDemoListByTransactionId(any())).thenReturn(regDemoDedupeListDtoList); - - MessageDTO dto = new MessageDTO(); - dto.setRid("10003100030001520190422074511"); - MessageDTO result = abisHandlerStage.process(dto); - - assertTrue(result.getInternalError()); - assertTrue(result.getIsValid()); - } - - @Test - public void testReprocessInsert() throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { - registrationStatusDto.setLatestTransactionTypeCode("BIOGRAPHIC_VERIFICATION"); - registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); - Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); - Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); - List appCodeList = new ArrayList<>(); - appCodeList.add("ABIS1"); - Mockito.when(packetInfoManager.getAbisProcessedRequestsAppCodeByBioRefId(any(), any(), any())) - .thenReturn(appCodeList); - - Mockito.when(packetInfoManager.getAllAbisDetails()).thenReturn(abisApplicationDtos); - - RegBioRefDto bioRefDto = new RegBioRefDto(); - bioRefDtos.add(bioRefDto); - Mockito.when(packetInfoManager.getBioRefIdByRegId(any())).thenReturn(bioRefDtos); - - Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); - - AbisRequestDto abisRequestDto = new AbisRequestDto(); - abisRequestDto.setAbisAppCode("ABIS1"); - abisRequestDto.setStatusCode("IN-PROGRESS"); - abisRequestDtoList.add(abisRequestDto); - Mockito.when(packetInfoManager.getAbisRequestsByBioRefId(any())).thenReturn(abisRequestDtoList); - tags.put("AGE_GROUP", "ADULT"); - Mockito.when(packetService.getAllTags(any())).thenReturn(tags); - - Mockito.doNothing().when(packetInfoManager).saveAbisRequest(any(), any(), any()); - - Mockito.when(packetInfoManager.getDemoListByTransactionId(any())).thenReturn(regDemoDedupeListDtoList); - - MessageDTO dto = new MessageDTO(); - dto.setRid("10003100030001520190422074511"); - MessageDTO result = abisHandlerStage.process(dto); - - assertTrue(result.getMessageBusAddress().getAddress().equalsIgnoreCase("abis-middle-ware-bus-in")); - } - - @Test - public void testAbisDetailsNotFound() throws RegistrationProcessorCheckedException { - registrationStatusDto.setLatestTransactionTypeCode("BIOGRAPHIC_VERIFICATION"); - registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); - Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); - Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); - - List abisQueueDetails = new ArrayList<>(); - Mockito.when(utility.getAbisQueueDetails()).thenReturn(abisQueueDetails); - - MessageDTO dto = new MessageDTO(); - dto.setRid("10003100030001520190422074511"); - MessageDTO result = abisHandlerStage.process(dto); - - assertTrue(result.getInternalError()); - } - - @Test - public void testPotentialMatchNotFound() throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { - registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); - registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); - Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); - Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); - - mockDataSharePolicy(Lists.newArrayList(BiometricType.IRIS, BiometricType.FINGER, BiometricType.FACE)); - tags.put("AGE_GROUP", "ADULT"); - Mockito.when(packetService.getAllTags(any())).thenReturn(tags); - - Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); - Mockito.doNothing().when(packetInfoManager).saveAbisRequest(any(), any(), any()); - - Mockito.when(packetInfoManager.getDemoListByTransactionId(any())).thenReturn(Arrays.asList()); - - MessageDTO dto = new MessageDTO(); - dto.setRid("10003100030001520190422074511"); - MessageDTO result = abisHandlerStage.process(dto); - - assertTrue(result.getInternalError()); - } - - @Test - public void testIdentifyRequestJsonProcessingException() throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { - registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); - registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); - Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); - Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); - - mockDataSharePolicy(Lists.newArrayList(BiometricType.IRIS, BiometricType.FINGER, BiometricType.FACE)); - Mockito.when(packetInfoManager.getBioRefIdByRegId(any())).thenReturn(bioRefDtos); - tags.put("AGE_GROUP", "ADULT"); - Mockito.when(packetService.getAllTags(any())).thenReturn(tags); - - Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); - Mockito.doNothing().when(packetInfoManager).saveAbisRequest(any(), any(), any()); - - RegDemoDedupeListDto regDemoDedupeListDto = new RegDemoDedupeListDto(); - regDemoDedupeListDto.setMatchedRegId("10003100030001520190422074511"); - regDemoDedupeListDtoList.add(regDemoDedupeListDto); - Mockito.when(packetInfoManager.getDemoListByTransactionId(any())).thenReturn(regDemoDedupeListDtoList); - - PowerMockito.mockStatic(JsonUtils.class); - PowerMockito.when(JsonUtils.javaObjectToJsonString(any())).thenReturn("value").thenThrow(JsonProcessingException.class); - MessageDTO dto = new MessageDTO(); - dto.setRid("10003100030001520190422074511"); - MessageDTO result = abisHandlerStage.process(dto); - - assertTrue(result.getInternalError()); - } - - @Test - public void testInsertRequestJsonProcessingException() throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { - registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); - registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); - Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); - Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); - - mockDataSharePolicy(Lists.newArrayList(BiometricType.IRIS, BiometricType.FINGER, BiometricType.FACE)); - tags.put("AGE_GROUP", "MINOR"); - Mockito.when(packetService.getAllTags(any())).thenReturn(tags); - - Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); - - PowerMockito.mockStatic(JsonUtils.class); - PowerMockito.when(JsonUtils.javaObjectToJsonString(any())).thenThrow(JsonProcessingException.class); - MessageDTO dto = new MessageDTO(); - dto.setRid("10003100030001520190422074511"); - MessageDTO result = abisHandlerStage.process(dto); - - assertTrue(result.getInternalError()); - } - - @Test - public void testDataShareResponseNullException() throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { - registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); - registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); - Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); - Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); - - mockDataSharePolicy(Lists.newArrayList(BiometricType.IRIS, BiometricType.FINGER, BiometricType.FACE)); - tags.put("AGE_GROUP", "MINOR"); - Mockito.when(packetService.getAllTags(any())).thenReturn(tags); - - Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); - - DataShareResponseDto dataShareResponseDto = new DataShareResponseDto(); - ErrorDTO error = new ErrorDTO("ERR-001", "exception occured"); - dataShareResponseDto.setDataShare(null); - dataShareResponseDto.setErrors(Arrays.asList(error)); - Mockito.when(registrationProcessorRestClientService.postApi(anyString(), any(MediaType.class), any(), any(), - any(), any(), any())).thenReturn(dataShareResponseDto); - MessageDTO dto = new MessageDTO(); - dto.setRid("10003100030001520190422074511"); - MessageDTO result = abisHandlerStage.process(dto); - - assertTrue(result.getInternalError()); - } - - @Test - public void testCreateTypeSubtypeMappingResponseNullException() - throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { - registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); - registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); - Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())) - .thenReturn(registrationStatusDto); - Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); - ErrorDTO error = new ErrorDTO("ERR-001", "exception occured"); - ResponseWrapper> policyResponse = new ResponseWrapper<>(); - - policyResponse.setErrors(Arrays.asList(error)); - - Mockito.when(registrationProcessorRestClientService.getApi(any(), any(), anyString(), - anyString(), any())).thenReturn(policyResponse); - Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); - - MessageDTO dto = new MessageDTO(); - dto.setRid("10003100030001520190422074511"); - MessageDTO result = abisHandlerStage.process(dto); - - assertTrue(result.getInternalError()); - } - - @Test - public void testvalidateBiometricRecordModalitiesEmptyException() - throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { - registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); - registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); - Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())) - .thenReturn(registrationStatusDto); - Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); - - mockDataSharePolicy(Lists.newArrayList(BiometricType.IRIS, BiometricType.FINGER, BiometricType.FACE)); - tags.put("AGE_GROUP", "MINOR"); - Mockito.when(packetService.getAllTags(any())).thenReturn(tags); - - Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); - - ResponseWrapper> policyResponse = new ResponseWrapper<>(); - LinkedHashMap response = new LinkedHashMap(); - LinkedHashMap attributes = new LinkedHashMap(); - ShareableAttributes shareableAttributes = new ShareableAttributes(); - shareableAttributes.setSource(Arrays.asList()); - attributes.put(PolicyConstant.SHAREABLE_ATTRIBUTES, Arrays.asList(shareableAttributes)); - response.put(PolicyConstant.POLICIES, attributes); - policyResponse.setResponse(response); - - Mockito.when(registrationProcessorRestClientService.getApi(any(), any(), anyString(), anyString(), any())) - .thenReturn(policyResponse); - - MessageDTO dto = new MessageDTO(); - dto.setRid("10003100030001520190422074511"); - MessageDTO result = abisHandlerStage.process(dto); - - assertTrue(result.getInternalError()); - } - - @Test - public void testvalidateBiometricRecordSegmentEmptyException() - throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { - registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); - registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); - Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())) - .thenReturn(registrationStatusDto); - Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); - - mockDataSharePolicy(Lists.newArrayList(BiometricType.IRIS, BiometricType.FINGER, BiometricType.FACE)); - tags.put("AGE_GROUP", "ADULT"); - Mockito.when(packetService.getAllTags(any())).thenReturn(tags); - BiometricRecord biometricRecord = new BiometricRecord(); - biometricRecord.setSegments(null); - Mockito.when(packetManagerService.getBiometrics(any(), any(), any(), any(), any())).thenReturn(biometricRecord); - Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); - - MessageDTO dto = new MessageDTO(); - dto.setRid("10003100030001520190422074511"); - MessageDTO result = abisHandlerStage.process(dto); - - assertTrue(result.getInternalError()); - } - - @Test - public void testvalidateBiometricRecordOthersMapNullException() - throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { - registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); - registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); - Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())) - .thenReturn(registrationStatusDto); - Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); - - mockDataSharePolicy(Lists.newArrayList(BiometricType.IRIS, BiometricType.FINGER, BiometricType.FACE)); - tags.put("AGE_GROUP", "ADULT"); - Mockito.when(packetService.getAllTags(any())).thenReturn(tags); - BiometricRecord biometricRecord = new BiometricRecord(); - BIR bir = new BIR.BIRBuilder().build(); - BDBInfo bdbInfo = new BDBInfo.BDBInfoBuilder().build(); - bdbInfo.setSubtype(Arrays.asList("Left")); - bdbInfo.setType(Arrays.asList(BiometricType.IRIS)); - bir.setOthers(null); - bir.setBdbInfo(bdbInfo); - biometricRecord.setSegments(Arrays.asList(bir)); - Mockito.when(packetManagerService.getBiometrics(any(), any(), any(), any(), any())).thenReturn(biometricRecord); - Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); - - MessageDTO dto = new MessageDTO(); - dto.setRid("10003100030001520190422074511"); - MessageDTO result = abisHandlerStage.process(dto); - - assertTrue(result.getInternalError()); - } - - @Test - public void testCreateRequestException() throws JsonProcessingException { - registrationStatusDto.setLatestTransactionTypeCode("BIOGRAPHIC_VERIFICATION"); - registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); - Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); - Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); - - Mockito.when(packetInfoManager.getAllAbisDetails()).thenReturn(abisApplicationDtos); - - RegBioRefDto bioRefDto = new RegBioRefDto(); - bioRefDtos.add(bioRefDto); - Mockito.when(packetInfoManager.getBioRefIdByRegId(any())).thenReturn(bioRefDtos); - - Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); - - AbisRequestDto abisRequestDto = new AbisRequestDto(); - abisRequestDto.setAbisAppCode("ABIS1"); - abisRequestDto.setStatusCode("IN-PROGRESS"); - abisRequestDtoList.add(abisRequestDto); - Mockito.when(packetInfoManager.getAbisRequestsByBioRefId(any())).thenReturn(abisRequestDtoList); - - Mockito.doNothing().when(packetInfoManager).saveAbisRequest(any(), any(), any()); - - Mockito.when(packetInfoManager.getDemoListByTransactionId(any())).thenReturn(regDemoDedupeListDtoList); - - PowerMockito.mockStatic(JsonUtils.class); - PowerMockito.when(JsonUtils.javaObjectToJsonString(any(AbisInsertRequestDto.class))) - .thenThrow(JsonProcessingException.class); - - MessageDTO dto = new MessageDTO(); - dto.setRid("10003100030001520190422074511"); - MessageDTO result = abisHandlerStage.process(dto); - - assertTrue(result.getInternalError()); - assertTrue(result.getIsValid()); - } - - @Test - public void testIdentifyRequestException() throws JsonProcessingException { - registrationStatusDto.setLatestTransactionTypeCode("BIOGRAPHIC_VERIFICATION"); - registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); - Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); - Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); - - Mockito.when(packetInfoManager.getAllAbisDetails()).thenReturn(abisApplicationDtos); - - RegBioRefDto bioRefDto = new RegBioRefDto(); - bioRefDtos.add(bioRefDto); - Mockito.when(packetInfoManager.getBioRefIdByRegId(any())).thenReturn(bioRefDtos); - - Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); - - AbisRequestDto abisRequestDto = new AbisRequestDto(); - abisRequestDto.setAbisAppCode("ABIS1"); - abisRequestDto.setStatusCode("IN-PROGRESS"); - abisRequestDtoList.add(abisRequestDto); - Mockito.when(packetInfoManager.getAbisRequestsByBioRefId(any())).thenReturn(abisRequestDtoList); - - Mockito.doNothing().when(packetInfoManager).saveAbisRequest(any(), any(), any()); - - Mockito.when(packetInfoManager.getDemoListByTransactionId(any())).thenReturn(regDemoDedupeListDtoList); - - PowerMockito.mockStatic(JsonUtils.class); - PowerMockito.when(JsonUtils.javaObjectToJsonString(any(AbisInsertRequestDto.class))) - .thenReturn("AbisInsertRequestDto"); - PowerMockito.when(JsonUtils.javaObjectToJsonString(ArgumentMatchers.any(AbisIdentifyRequestDto.class))) - .thenThrow(JsonProcessingException.class); - - MessageDTO dto = new MessageDTO(); - dto.setRid("10003100030001520190422074511"); - MessageDTO result = abisHandlerStage.process(dto); - - assertTrue(result.getInternalError()); - assertTrue(result.getIsValid()); - } - - - @Test - public void bioRecordDataNotFound() - throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { - - defaultMockToProcess(); - - Mockito.when(packetManagerService.getBiometrics(any(), any(), any(), any(), any())).thenReturn(null); - mockDataSharePolicy(Lists.newArrayList(BiometricType.IRIS, BiometricType.FINGER, BiometricType.FACE)); - - setMetaInfoMap(new LinkedList<>(getExceptionModalityMap().values())); - MessageDTO dto = new MessageDTO(); - dto.setRid("10003100030001520190422074511"); - MessageDTO result = abisHandlerStage.process(dto); - - assertTrue(result.getIsValid()); - assertTrue(result.getInternalError()); - } - - @Test - public void biometricsNotFoundWithSegmentConfig() - throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { - - defaultMockToProcess(); - - Mockito.when(packetManagerService.getBiometrics(any(), any(), any(), any(), any())).thenReturn(getBiometricRecord(Arrays.asList("Left Thumb" ,"Right Thumb","Face"),false)); - - - setMetaInfoMap(Arrays.asList("leftEye")); - MessageDTO dto = new MessageDTO(); - dto.setRid("10003100030001520190422074511"); - MessageDTO result = abisHandlerStage.process(dto); - - assertTrue(result.getIsValid()); - assertTrue(result.getInternalError()); - } - - @Test - public void biometricsTypeNotFoundConfig() - throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { - - defaultMockToProcess(); - - Map> biometricModalitySegmentsMap = new HashMap(); - biometricModalitySegmentsMap.put("Finger", getFingerList()); - biometricModalitySegmentsMap.put("Iris", getIrisList()); - ReflectionTestUtils.setField(abisHandlerStage, "biometricModalitySegmentsMapAdult", biometricModalitySegmentsMap); - ReflectionTestUtils.setField(abisHandlerStage, "exceptionSegmentsMap", getExceptionModalityMap()); - - MessageDTO dto = new MessageDTO(); - dto.setRid("10003100030001520190422074511"); - MessageDTO result = abisHandlerStage.process(dto); - - assertTrue(result.getIsValid()); - assertTrue(result.getInternalError()); - } - - @Test - public void testBiometricSegmentNotConfiguredInfant() throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { - registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); - registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); - Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); - Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); - Mockito.when(packetInfoManager.getAllAbisDetails()).thenReturn(abisApplicationDtos); - - Mockito.when(packetInfoManager.getBioRefIdByRegId(any())).thenReturn(bioRefDtos); - tags.put("AGE_GROUP", "INFANT"); - Mockito.when(packetService.getAllTags(any())).thenReturn(tags); - - Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); - Mockito.doNothing().when(packetInfoManager).saveAbisRequest(any(), any(), any()); - - RegDemoDedupeListDto regDemoDedupeListDto = new RegDemoDedupeListDto(); - regDemoDedupeListDto.setMatchedRegId("10003100030001520190422074511"); - regDemoDedupeListDtoList.add(regDemoDedupeListDto); - Mockito.when(packetInfoManager.getDemoListByTransactionId(any())).thenReturn(regDemoDedupeListDtoList); - - MessageDTO dto = new MessageDTO(); - dto.setRid("10003100030001520190422074511"); - MessageDTO result = abisHandlerStage.process(dto); - - assertTrue(result.getIsValid()); - assertFalse(result.getInternalError()); - } - - - - @Test - public void emptyBdbFound() - throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { - - defaultMockToProcess(); - - boolean isBdbEmpty = true; - Mockito.when(packetManagerService.getBiometrics(any(), any(), any(), any(), any())).thenReturn(getBiometricRecord(Arrays.asList("Left RingFinger"), isBdbEmpty )); - mockDataSharePolicy(Lists.newArrayList(BiometricType.FINGER)); - - List list = new ArrayList(getExceptionModalityMap().values()); - list.remove("leftRing"); - setMetaInfoMap(list); - - MessageDTO dto = new MessageDTO(); - dto.setRid("10003100030001520190422074511"); - MessageDTO result = abisHandlerStage.process(dto); - - assertTrue(result.getIsValid()); - assertTrue(result.getInternalError()); - } - - @Test - public void noBdbInAnyBiometric() - throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { - - defaultMockToProcess(); - - Mockito.when(packetManagerService.getBiometrics(any(), any(), any(), any(), any())).thenReturn(getBiometricRecord(Arrays.asList("Left Thumb" ,"Right Thumb" , "Left MiddleFinger" , - "Left RingFinger" ,"Left LittleFinger" ,"Left IndexFinger" ,"Right MiddleFinger" , - "Right RingFinger" ,"Right LittleFinger" ,"Right IndexFinger" , - "Left" ,"Right","Face"),true)); - - MessageDTO dto = new MessageDTO(); - dto.setRid("10003100030001520190422074511"); - MessageDTO result = abisHandlerStage.process(dto); - - assertTrue(result.getIsValid()); - assertTrue(result.getInternalError()); - } - - private void defaultMockToProcess() { - registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); - registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); - Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); - Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); - Mockito.when(packetInfoManager.getAllAbisDetails()).thenReturn(abisApplicationDtos); - - RegBioRefDto regBioRefDto = new RegBioRefDto(); - regBioRefDto.setBioRefId("1234567890"); - bioRefDtos.add(regBioRefDto); - Mockito.when(packetInfoManager.getBioRefIdByRegId(any())).thenReturn(bioRefDtos); - - Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); - Mockito.doNothing().when(packetInfoManager).saveAbisRequest(any(), any(), any()); - - RegDemoDedupeListDto regDemoDedupeListDto = new RegDemoDedupeListDto(); - regDemoDedupeListDto.setMatchedRegId("10003100030001520190422074511"); - regDemoDedupeListDtoList.add(regDemoDedupeListDto); - Mockito.when(packetInfoManager.getDemoListByTransactionId(any())).thenReturn(regDemoDedupeListDtoList); - - } - - private void setMetaInfoMap(List exceptionAttributes) throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException{ - - Map metaInfoMap = new HashMap<>(); - - Map> exceptionBiometrcisMap = new HashMap<>(); - - Map applicantExceptionBiometrcisMap = new HashMap(); - - if(exceptionAttributes!=null) { - for(String exceptionAttribute : exceptionAttributes) { - - Map detailMap = new HashMap(); - detailMap.put("missingBiometric", exceptionAttribute); - detailMap.put("reason", "Temporary"); - detailMap.put("individualType", "applicant"); - - applicantExceptionBiometrcisMap.put(exceptionAttribute, detailMap); - - } - } - - - exceptionBiometrcisMap.put("applicant", applicantExceptionBiometrcisMap); - Gson gson = new Gson(); - Type gsonType = new TypeToken(){}.getType(); - - String gsonString = gson.toJson(exceptionBiometrcisMap,gsonType); - - metaInfoMap.put("exceptionBiometrics", gsonString); - Mockito.when(packetManagerService.getMetaInfo(any(), any(), any())).thenReturn(metaInfoMap); - } - - private BiometricRecord getBiometricRecord(List bioAttributes, boolean isBdbEmpty) { - BiometricRecord biometricRecord = new BiometricRecord(); - - byte[] bdb = isBdbEmpty ? null : new byte[2048]; - for(String bioAttribute : bioAttributes) { - BIR birType1 = new BIR.BIRBuilder().build(); - 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 = bioAttribute.equalsIgnoreCase("face") ? BiometricType.FACE : - bioAttribute.equalsIgnoreCase("left") || bioAttribute.equalsIgnoreCase("right") ? BiometricType.IRIS : BiometricType.FINGER ; - List singleTypeList1 = new ArrayList<>(); - singleTypeList1.add(singleType1); - bdbInfoType1.setType(singleTypeList1); - - - - String[] bioAttributeArray = bioAttribute.split(" "); - - List subtype = new ArrayList<>(); - for(String attribute : bioAttributeArray) { - subtype.add(attribute); - } - bdbInfoType1.setSubtype(subtype); - - birType1.setBdbInfo(bdbInfoType1); - birType1.setBdb(bdb); - - if(bdb==null) { - Map others = new HashMap<>(); - others.put("EXCEPTION", true); - HashMap entry = new HashMap<>(); - entry.put("EXCEPTION", "true"); - birType1.setOthers(entry); - - } - - biometricRecord.getSegments().add(birType1); - } - - return biometricRecord; - } - +package io.mosip.registration.processor.abis.handler.stage.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.Type; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +import org.assertj.core.util.Lists; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentMatchers; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.Spy; +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.MediaType; +import org.springframework.test.util.ReflectionTestUtils; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.common.reflect.TypeToken; +import com.google.gson.Gson; + +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.JsonUtils; +import io.mosip.kernel.core.util.exception.JsonProcessingException; +import io.mosip.registration.processor.abis.handler.dto.DataShare; +import io.mosip.registration.processor.abis.handler.dto.DataShareResponseDto; +import io.mosip.registration.processor.abis.handler.stage.AbisHandlerStage; +import io.mosip.registration.processor.abis.queue.dto.AbisQueueDetails; +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.common.rest.dto.ErrorDTO; +import io.mosip.registration.processor.core.constant.PolicyConstant; +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.Identity; +import io.mosip.registration.processor.core.packet.dto.abis.AbisApplicationDto; +import io.mosip.registration.processor.core.packet.dto.abis.AbisIdentifyRequestDto; +import io.mosip.registration.processor.core.packet.dto.abis.AbisInsertRequestDto; +import io.mosip.registration.processor.core.packet.dto.abis.AbisRequestDto; +import io.mosip.registration.processor.core.packet.dto.abis.RegBioRefDto; +import io.mosip.registration.processor.core.packet.dto.abis.RegDemoDedupeListDto; +import io.mosip.registration.processor.core.packet.dto.datashare.Filter; +import io.mosip.registration.processor.core.packet.dto.datashare.ShareableAttributes; +import io.mosip.registration.processor.core.packet.dto.datashare.Source; +import io.mosip.registration.processor.core.spi.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.packet.storage.dto.ApplicantInfoDto; +import io.mosip.registration.processor.packet.storage.utils.PacketManagerService; +import io.mosip.registration.processor.packet.storage.utils.PriorityBasedPacketManagerService; +import io.mosip.registration.processor.packet.storage.utils.Utilities; +import io.mosip.registration.processor.rest.client.audit.builder.AuditLogRequestBuilder; +import io.mosip.registration.processor.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; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({ JsonUtils.class }) +@PowerMockIgnore({ "com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "javax.management.*", "javax.net.ssl.*" }) +public class AbisHandlerStageTest { + + @Mock + private AuditLogRequestBuilder auditLogRequestBuilder; + + @Mock + private RegistrationStatusService registrationStatusService; + + @Mock + private PacketInfoManager packetInfoManager; + + private InternalRegistrationStatusDto registrationStatusDto = new InternalRegistrationStatusDto(); + + @Mock + private Utilities utility; + + @Spy + private ObjectMapper mapper = new ObjectMapper(); + + @Mock + private PriorityBasedPacketManagerService packetManagerService; + + @Mock + private PacketManagerService packetService; + + @Mock + private LogDescription description; + + List abisApplicationDtos = new ArrayList<>(); + + List bioRefDtos = new ArrayList<>(); + + List regDemoDedupeListDtoList = new ArrayList<>(); + + List abisRequestDtoList = new ArrayList<>(); + + Map tags = new HashMap(); + + @Mock + private Environment env; + + @Mock + private RegistrationProcessorRestClientService registrationProcessorRestClientService; + + @Mock + private CbeffUtil cbeffutil; + + @InjectMocks + private AbisHandlerStage abisHandlerStage = new AbisHandlerStage() { + @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 consumeAndSend(MosipEventBus mosipEventBus, MessageBusAddress fromAddress, + MessageBusAddress toAddress, long messageExpiryTimeLimit) { + } + + @Override + public Integer getPort() { + return 8080; + }; + }; + + @Before + public void setUp() throws Exception { + ReflectionTestUtils.setField(abisHandlerStage, "maxResults", "30"); + ReflectionTestUtils.setField(abisHandlerStage, "targetFPIR", "30"); + ReflectionTestUtils.setField(abisHandlerStage, "workerPoolSize", 10); + ReflectionTestUtils.setField(abisHandlerStage, "messageExpiryTimeLimit", Long.valueOf(0)); + ReflectionTestUtils.setField(abisHandlerStage, "clusterManagerUrl", "/dummyPath"); + ReflectionTestUtils.setField(abisHandlerStage, "httpProtocol", "http"); + ReflectionTestUtils.setField(abisHandlerStage, "internalDomainName", "localhost"); + Mockito.when(env.getProperty("mosip.registration.processor.datetime.pattern")) + .thenReturn("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); + + Map> biometricModalitySegmentsMap = new HashMap(); + Map> biometricModalitySegmentsMapInfant = new HashMap(); + biometricModalitySegmentsMapInfant.put("Face", getFaceList()); + biometricModalitySegmentsMap.put("Finger", getFingerList()); + biometricModalitySegmentsMap.put("Iris", getIrisList()); + biometricModalitySegmentsMap.put("Face", getFaceList()); + ReflectionTestUtils.setField(abisHandlerStage, "biometricModalitySegmentsMapInfant", biometricModalitySegmentsMapInfant); + ReflectionTestUtils.setField(abisHandlerStage, "biometricModalitySegmentsMapMinor", biometricModalitySegmentsMap); + ReflectionTestUtils.setField(abisHandlerStage, "biometricModalitySegmentsMapAdult", biometricModalitySegmentsMap); + ReflectionTestUtils.setField(abisHandlerStage, "exceptionSegmentsMap", getExceptionModalityMap()); + + Mockito.when(env.getProperty("DATASHARECREATEURL")).thenReturn("/v1/datashare/create"); + AbisApplicationDto dto = new AbisApplicationDto(); + dto.setCode("ABIS1"); + abisApplicationDtos.add(dto); + + Mockito.doNothing().when(description).setMessage(any()); + Mockito.when(description.getMessage()).thenReturn("description"); + + + Mockito.when(packetManagerService.getBiometrics(any(), any(), any(), any(), any())).thenReturn(getBiometricRecord(Arrays.asList("Left Thumb" ,"Right Thumb" , "Left MiddleFinger" , + "Left RingFinger" ,"Left LittleFinger" ,"Left IndexFinger" ,"Right MiddleFinger" , + "Right RingFinger" ,"Right LittleFinger" ,"Right IndexFinger" , + "Left" ,"Right","Face"),false)); + mockDataSharePolicy(Lists.newArrayList(BiometricType.FINGER,BiometricType.IRIS,BiometricType.FACE)); + + List list = new LinkedList<>(); + setMetaInfoMap(list); + + //Mockito.doNothing().when(registrationStatusDto).setLatestTransactionStatusCode(any()); + Mockito.doNothing().when(registrationStatusService).updateRegistrationStatus(any(), any(), any()); + + Mockito.when(packetInfoManager.getAbisRequestsByBioRefId(any())).thenReturn(abisRequestDtoList); + + AbisQueueDetails abisQueueDetails = new AbisQueueDetails(); + abisQueueDetails.setName("ABIS1"); + List abisQueueDetailsList = new ArrayList<>(); + abisQueueDetailsList.add(abisQueueDetails); + Mockito.when(utility.getAbisQueueDetails()).thenReturn(abisQueueDetailsList); + + AuditResponseDto auditResponseDto = new AuditResponseDto(); + ResponseWrapper responseWrapper = new ResponseWrapper<>(); + responseWrapper.setResponse(auditResponseDto); + Mockito.when(auditLogRequestBuilder.createAuditRequestBuilder(any(), any(), any(), any(), any(), any(), any())) + .thenReturn(responseWrapper); + + DataShareResponseDto dataShareResponseDto = new DataShareResponseDto(); + DataShare dataShare = new DataShare(); + dataShare.setUrl("http://localhost"); + dataShareResponseDto.setDataShare(dataShare); + + mockDataSharePolicy(Lists.newArrayList(BiometricType.FACE, BiometricType.FINGER)); + + Mockito.when(registrationProcessorRestClientService.postApi(anyString(), any(MediaType.class), any(), any(), + any(), any(), any())).thenReturn(dataShareResponseDto); + + Mockito.when(cbeffutil.createXML(any())).thenReturn(new byte[2048]); + } + + private Map getExceptionModalityMap() { + Map exceptionMap = new HashMap(); + exceptionMap.put("Left Thumb" , "leftThumb"); + exceptionMap.put("Right Thumb" , "rightThumb"); + exceptionMap.put("Left MiddleFinger" , "leftMiddle"); + exceptionMap.put("Left RingFinger" , "leftRing"); + exceptionMap.put("Left LittleFinger" , "leftLittle"); + exceptionMap.put("Left IndexFinger" , "leftIndex"); + exceptionMap.put("Right MiddleFinger" , "rightMiddle"); + exceptionMap.put("Right RingFinger" , "rightRing"); + exceptionMap.put("Right LittleFinger" , "rightLittle"); + exceptionMap.put("Right IndexFinger" , "rightIndex"); + exceptionMap.put("Left" , "leftEye"); + exceptionMap.put("Right" , "rightEye"); + exceptionMap.put("Face" , "face"); + + return exceptionMap; + } + + private List getFaceList() { + return Arrays.asList("Face"); + } + + private List getIrisList() { + return Arrays.asList("Left", "Right"); + + } + + private List getFingerList() { + return Arrays.asList("Left Thumb", "Left LittleFinger", "Left IndexFinger", "Left MiddleFinger", + "Left RingFinger", "Right Thumb", "Right LittleFinger", + "Right IndexFinger", "Right MiddleFinger", + "Right RingFinger"); + } + + private void mockDataSharePolicy(List sherableBiometricList) throws ApisResourceAccessException { + when(registrationProcessorRestClientService.getApi(any(), any(), anyString(), anyString(), any())) + .thenReturn(getMockDataSharePolicy(sherableBiometricList)); + } + + private ResponseWrapper> getMockDataSharePolicy( + List sherableBiometricList) { + + ObjectMapper mapper = new ObjectMapper(); + + List attr = new LinkedList<>(); + if (sherableBiometricList != null && !sherableBiometricList.isEmpty()) { + + ShareableAttributes shareableAttributes = new ShareableAttributes(); + List sourceList = new ArrayList<>(); + + for (BiometricType bioType : sherableBiometricList) { + Filter filter = new Filter(); + filter.setType(bioType.value()); + Source src = new Source(); + src.setFilter(Lists.newArrayList(filter)); + sourceList.add(src); + } + + shareableAttributes.setSource(sourceList); + attr = Lists.newArrayList(shareableAttributes); + } + + ResponseWrapper> policy = new ResponseWrapper<>(); + LinkedHashMap policies = new LinkedHashMap<>(); + LinkedHashMap sharableAttributes = new LinkedHashMap<>(); + sharableAttributes.put(PolicyConstant.SHAREABLE_ATTRIBUTES, attr); + policies.put(PolicyConstant.POLICIES, sharableAttributes); + policy.setResponse(policies); + + return policy; + } + + @Test + public void testDeployVerticle() { + abisHandlerStage.deployVerticle(); + } + + @Test + public void testDemoToAbisHandlerTOMiddlewareSuccess() throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { + registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); + registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); + Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); + Mockito.when(packetInfoManager.getAllAbisDetails()).thenReturn(abisApplicationDtos); + + mockDataSharePolicy(Lists.newArrayList(BiometricType.IRIS, BiometricType.FINGER, BiometricType.FACE)); + Mockito.when(packetInfoManager.getBioRefIdByRegId(any())).thenReturn(bioRefDtos); + tags.put("AGE_GROUP", "ADULT"); + Mockito.when(packetService.getAllTags(any())).thenReturn(tags); + + Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); + Mockito.doNothing().when(packetInfoManager).saveAbisRequest(any(), any(), any()); + + RegDemoDedupeListDto regDemoDedupeListDto = new RegDemoDedupeListDto(); + regDemoDedupeListDto.setMatchedRegId("10003100030001520190422074511"); + regDemoDedupeListDtoList.add(regDemoDedupeListDto); + Mockito.when(packetInfoManager.getDemoListByTransactionId(any())).thenReturn(regDemoDedupeListDtoList); + + MessageDTO dto = new MessageDTO(); + dto.setRid("10003100030001520190422074511"); + MessageDTO result = abisHandlerStage.process(dto); + + assertTrue(result.getMessageBusAddress().getAddress().equalsIgnoreCase("abis-middle-ware-bus-in")); + } + + @Test + public void testBioToAbisHandlerToMiddlewareSuccess() throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { + registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); + registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); + Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); + Mockito.when(packetInfoManager.getAllAbisDetails()).thenReturn(abisApplicationDtos); + + mockDataSharePolicy(Lists.newArrayList(BiometricType.IRIS, BiometricType.FINGER, BiometricType.FACE)); + RegBioRefDto regBioRefDto = new RegBioRefDto(); + regBioRefDto.setBioRefId("1234567890"); + bioRefDtos.add(regBioRefDto); + Mockito.when(packetInfoManager.getBioRefIdByRegId(any())).thenReturn(bioRefDtos); + tags.put("AGE_GROUP", "ADULT"); + Mockito.when(packetService.getAllTags(any())).thenReturn(tags); + + Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); + Mockito.doNothing().when(packetInfoManager).saveAbisRequest(any(), any(), any()); + + RegDemoDedupeListDto regDemoDedupeListDto = new RegDemoDedupeListDto(); + regDemoDedupeListDto.setMatchedRegId("10003100030001520190422074511"); + regDemoDedupeListDtoList.add(regDemoDedupeListDto); + Mockito.when(packetInfoManager.getDemoListByTransactionId(any())).thenReturn(regDemoDedupeListDtoList); + + MessageDTO dto = new MessageDTO(); + dto.setRid("10003100030001520190422074511"); + MessageDTO result = abisHandlerStage.process(dto); + + assertTrue(result.getMessageBusAddress().getAddress().equalsIgnoreCase("abis-middle-ware-bus-in")); + } + + @Test + public void testMiddlewareToAbisHandlerToDemoSuccess() { + registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); + registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); + Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.TRUE); + + MessageDTO dto = new MessageDTO(); + dto.setRid("10003100030001520190422074511"); + MessageDTO result = abisHandlerStage.process(dto); + + assertTrue(result.getMessageBusAddress().getAddress().equalsIgnoreCase("demo-dedupe-bus-in")); + } + + @Test + public void testMiddlewareToAbisHandlerToBioSuccess() { + registrationStatusDto.setLatestTransactionTypeCode("BIOGRAPHIC_VERIFICATION"); + registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); + Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.TRUE); + + MessageDTO dto = new MessageDTO(); + dto.setRid("10003100030001520190422074511"); + MessageDTO result = abisHandlerStage.process(dto); + + assertTrue(result.getMessageBusAddress().getAddress().equalsIgnoreCase("bio-dedupe-bus-in")); + } + + @Test + public void testDemoDedupeDataNotFound() { + registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); + registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); + Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); + Mockito.when(packetInfoManager.getAllAbisDetails()).thenReturn(abisApplicationDtos); + + Mockito.when(packetInfoManager.getBioRefIdByRegId(any())).thenReturn(bioRefDtos); + + Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); + Mockito.doNothing().when(packetInfoManager).saveAbisRequest(any(), any(), any()); + + Mockito.when(packetInfoManager.getDemoListByTransactionId(any())).thenReturn(regDemoDedupeListDtoList); + + MessageDTO dto = new MessageDTO(); + dto.setRid("10003100030001520190422074511"); + MessageDTO result = abisHandlerStage.process(dto); + + assertTrue(result.getInternalError()); + assertTrue(result.getIsValid()); + } + + @Test + public void testReprocessInsert() throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { + registrationStatusDto.setLatestTransactionTypeCode("BIOGRAPHIC_VERIFICATION"); + registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); + Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); + List appCodeList = new ArrayList<>(); + appCodeList.add("ABIS1"); + Mockito.when(packetInfoManager.getAbisProcessedRequestsAppCodeByBioRefId(any(), any(), any())) + .thenReturn(appCodeList); + + Mockito.when(packetInfoManager.getAllAbisDetails()).thenReturn(abisApplicationDtos); + + RegBioRefDto bioRefDto = new RegBioRefDto(); + bioRefDtos.add(bioRefDto); + Mockito.when(packetInfoManager.getBioRefIdByRegId(any())).thenReturn(bioRefDtos); + + Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); + + AbisRequestDto abisRequestDto = new AbisRequestDto(); + abisRequestDto.setAbisAppCode("ABIS1"); + abisRequestDto.setStatusCode("IN-PROGRESS"); + abisRequestDtoList.add(abisRequestDto); + Mockito.when(packetInfoManager.getAbisRequestsByBioRefId(any())).thenReturn(abisRequestDtoList); + tags.put("AGE_GROUP", "ADULT"); + Mockito.when(packetService.getAllTags(any())).thenReturn(tags); + + Mockito.doNothing().when(packetInfoManager).saveAbisRequest(any(), any(), any()); + + Mockito.when(packetInfoManager.getDemoListByTransactionId(any())).thenReturn(regDemoDedupeListDtoList); + + MessageDTO dto = new MessageDTO(); + dto.setRid("10003100030001520190422074511"); + MessageDTO result = abisHandlerStage.process(dto); + + assertTrue(result.getMessageBusAddress().getAddress().equalsIgnoreCase("abis-middle-ware-bus-in")); + } + + @Test + public void testAbisDetailsNotFound() throws RegistrationProcessorCheckedException { + registrationStatusDto.setLatestTransactionTypeCode("BIOGRAPHIC_VERIFICATION"); + registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); + Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); + + List abisQueueDetails = new ArrayList<>(); + Mockito.when(utility.getAbisQueueDetails()).thenReturn(abisQueueDetails); + + MessageDTO dto = new MessageDTO(); + dto.setRid("10003100030001520190422074511"); + MessageDTO result = abisHandlerStage.process(dto); + + assertTrue(result.getInternalError()); + } + + @Test + public void testPotentialMatchNotFound() throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { + registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); + registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); + Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); + + mockDataSharePolicy(Lists.newArrayList(BiometricType.IRIS, BiometricType.FINGER, BiometricType.FACE)); + tags.put("AGE_GROUP", "ADULT"); + Mockito.when(packetService.getAllTags(any())).thenReturn(tags); + + Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); + Mockito.doNothing().when(packetInfoManager).saveAbisRequest(any(), any(), any()); + + Mockito.when(packetInfoManager.getDemoListByTransactionId(any())).thenReturn(Arrays.asList()); + + MessageDTO dto = new MessageDTO(); + dto.setRid("10003100030001520190422074511"); + MessageDTO result = abisHandlerStage.process(dto); + + assertTrue(result.getInternalError()); + } + + @Test + public void testIdentifyRequestJsonProcessingException() throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { + registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); + registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); + Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); + + mockDataSharePolicy(Lists.newArrayList(BiometricType.IRIS, BiometricType.FINGER, BiometricType.FACE)); + Mockito.when(packetInfoManager.getBioRefIdByRegId(any())).thenReturn(bioRefDtos); + tags.put("AGE_GROUP", "ADULT"); + Mockito.when(packetService.getAllTags(any())).thenReturn(tags); + + Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); + Mockito.doNothing().when(packetInfoManager).saveAbisRequest(any(), any(), any()); + + RegDemoDedupeListDto regDemoDedupeListDto = new RegDemoDedupeListDto(); + regDemoDedupeListDto.setMatchedRegId("10003100030001520190422074511"); + regDemoDedupeListDtoList.add(regDemoDedupeListDto); + Mockito.when(packetInfoManager.getDemoListByTransactionId(any())).thenReturn(regDemoDedupeListDtoList); + + PowerMockito.mockStatic(JsonUtils.class); + PowerMockito.when(JsonUtils.javaObjectToJsonString(any())).thenReturn("value").thenThrow(JsonProcessingException.class); + MessageDTO dto = new MessageDTO(); + dto.setRid("10003100030001520190422074511"); + MessageDTO result = abisHandlerStage.process(dto); + + assertTrue(result.getInternalError()); + } + + @Test + public void testInsertRequestJsonProcessingException() throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { + registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); + registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); + Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); + + mockDataSharePolicy(Lists.newArrayList(BiometricType.IRIS, BiometricType.FINGER, BiometricType.FACE)); + tags.put("AGE_GROUP", "MINOR"); + Mockito.when(packetService.getAllTags(any())).thenReturn(tags); + + Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); + + PowerMockito.mockStatic(JsonUtils.class); + PowerMockito.when(JsonUtils.javaObjectToJsonString(any())).thenThrow(JsonProcessingException.class); + MessageDTO dto = new MessageDTO(); + dto.setRid("10003100030001520190422074511"); + MessageDTO result = abisHandlerStage.process(dto); + + assertTrue(result.getInternalError()); + } + + @Test + public void testDataShareResponseNullException() throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { + registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); + registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); + Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); + + mockDataSharePolicy(Lists.newArrayList(BiometricType.IRIS, BiometricType.FINGER, BiometricType.FACE)); + tags.put("AGE_GROUP", "MINOR"); + Mockito.when(packetService.getAllTags(any())).thenReturn(tags); + + Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); + + DataShareResponseDto dataShareResponseDto = new DataShareResponseDto(); + ErrorDTO error = new ErrorDTO("ERR-001", "exception occured"); + dataShareResponseDto.setDataShare(null); + dataShareResponseDto.setErrors(Arrays.asList(error)); + Mockito.when(registrationProcessorRestClientService.postApi(anyString(), any(MediaType.class), any(), any(), + any(), any(), any())).thenReturn(dataShareResponseDto); + MessageDTO dto = new MessageDTO(); + dto.setRid("10003100030001520190422074511"); + MessageDTO result = abisHandlerStage.process(dto); + + assertTrue(result.getInternalError()); + } + + @Test + public void testCreateTypeSubtypeMappingResponseNullException() + throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { + registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); + registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())) + .thenReturn(registrationStatusDto); + Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); + ErrorDTO error = new ErrorDTO("ERR-001", "exception occured"); + ResponseWrapper> policyResponse = new ResponseWrapper<>(); + + policyResponse.setErrors(Arrays.asList(error)); + + Mockito.when(registrationProcessorRestClientService.getApi(any(), any(), anyString(), + anyString(), any())).thenReturn(policyResponse); + Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); + + MessageDTO dto = new MessageDTO(); + dto.setRid("10003100030001520190422074511"); + MessageDTO result = abisHandlerStage.process(dto); + + assertTrue(result.getInternalError()); + } + + @Test + public void testvalidateBiometricRecordModalitiesEmptyException() + throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { + registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); + registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())) + .thenReturn(registrationStatusDto); + Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); + + mockDataSharePolicy(Lists.newArrayList(BiometricType.IRIS, BiometricType.FINGER, BiometricType.FACE)); + tags.put("AGE_GROUP", "MINOR"); + Mockito.when(packetService.getAllTags(any())).thenReturn(tags); + + Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); + + ResponseWrapper> policyResponse = new ResponseWrapper<>(); + LinkedHashMap response = new LinkedHashMap(); + LinkedHashMap attributes = new LinkedHashMap(); + ShareableAttributes shareableAttributes = new ShareableAttributes(); + shareableAttributes.setSource(Arrays.asList()); + attributes.put(PolicyConstant.SHAREABLE_ATTRIBUTES, Arrays.asList(shareableAttributes)); + response.put(PolicyConstant.POLICIES, attributes); + policyResponse.setResponse(response); + + Mockito.when(registrationProcessorRestClientService.getApi(any(), any(), anyString(), anyString(), any())) + .thenReturn(policyResponse); + + MessageDTO dto = new MessageDTO(); + dto.setRid("10003100030001520190422074511"); + MessageDTO result = abisHandlerStage.process(dto); + + assertTrue(result.getInternalError()); + } + + @Test + public void testvalidateBiometricRecordSegmentEmptyException() + throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { + registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); + registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())) + .thenReturn(registrationStatusDto); + Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); + + mockDataSharePolicy(Lists.newArrayList(BiometricType.IRIS, BiometricType.FINGER, BiometricType.FACE)); + tags.put("AGE_GROUP", "ADULT"); + Mockito.when(packetService.getAllTags(any())).thenReturn(tags); + BiometricRecord biometricRecord = new BiometricRecord(); + biometricRecord.setSegments(null); + Mockito.when(packetManagerService.getBiometrics(any(), any(), any(), any(), any())).thenReturn(biometricRecord); + Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); + + MessageDTO dto = new MessageDTO(); + dto.setRid("10003100030001520190422074511"); + MessageDTO result = abisHandlerStage.process(dto); + + assertTrue(result.getInternalError()); + } + + @Test + public void testvalidateBiometricRecordOthersMapNullException() + throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { + registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); + registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())) + .thenReturn(registrationStatusDto); + Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); + + mockDataSharePolicy(Lists.newArrayList(BiometricType.IRIS, BiometricType.FINGER, BiometricType.FACE)); + tags.put("AGE_GROUP", "ADULT"); + Mockito.when(packetService.getAllTags(any())).thenReturn(tags); + BiometricRecord biometricRecord = new BiometricRecord(); + BIR bir = new BIR.BIRBuilder().build(); + BDBInfo bdbInfo = new BDBInfo.BDBInfoBuilder().build(); + bdbInfo.setSubtype(Arrays.asList("Left")); + bdbInfo.setType(Arrays.asList(BiometricType.IRIS)); + bir.setOthers(null); + bir.setBdbInfo(bdbInfo); + biometricRecord.setSegments(Arrays.asList(bir)); + Mockito.when(packetManagerService.getBiometrics(any(), any(), any(), any(), any())).thenReturn(biometricRecord); + Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); + + MessageDTO dto = new MessageDTO(); + dto.setRid("10003100030001520190422074511"); + MessageDTO result = abisHandlerStage.process(dto); + + assertTrue(result.getInternalError()); + } + + @Test + public void testCreateRequestException() throws JsonProcessingException { + registrationStatusDto.setLatestTransactionTypeCode("BIOGRAPHIC_VERIFICATION"); + registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); + Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); + + Mockito.when(packetInfoManager.getAllAbisDetails()).thenReturn(abisApplicationDtos); + + RegBioRefDto bioRefDto = new RegBioRefDto(); + bioRefDtos.add(bioRefDto); + Mockito.when(packetInfoManager.getBioRefIdByRegId(any())).thenReturn(bioRefDtos); + + Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); + + AbisRequestDto abisRequestDto = new AbisRequestDto(); + abisRequestDto.setAbisAppCode("ABIS1"); + abisRequestDto.setStatusCode("IN-PROGRESS"); + abisRequestDtoList.add(abisRequestDto); + Mockito.when(packetInfoManager.getAbisRequestsByBioRefId(any())).thenReturn(abisRequestDtoList); + + Mockito.doNothing().when(packetInfoManager).saveAbisRequest(any(), any(), any()); + + Mockito.when(packetInfoManager.getDemoListByTransactionId(any())).thenReturn(regDemoDedupeListDtoList); + + PowerMockito.mockStatic(JsonUtils.class); + PowerMockito.when(JsonUtils.javaObjectToJsonString(any(AbisInsertRequestDto.class))) + .thenThrow(JsonProcessingException.class); + + MessageDTO dto = new MessageDTO(); + dto.setRid("10003100030001520190422074511"); + MessageDTO result = abisHandlerStage.process(dto); + + assertTrue(result.getInternalError()); + assertTrue(result.getIsValid()); + } + + @Test + public void testIdentifyRequestException() throws JsonProcessingException { + registrationStatusDto.setLatestTransactionTypeCode("BIOGRAPHIC_VERIFICATION"); + registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); + Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); + + Mockito.when(packetInfoManager.getAllAbisDetails()).thenReturn(abisApplicationDtos); + + RegBioRefDto bioRefDto = new RegBioRefDto(); + bioRefDtos.add(bioRefDto); + Mockito.when(packetInfoManager.getBioRefIdByRegId(any())).thenReturn(bioRefDtos); + + Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); + + AbisRequestDto abisRequestDto = new AbisRequestDto(); + abisRequestDto.setAbisAppCode("ABIS1"); + abisRequestDto.setStatusCode("IN-PROGRESS"); + abisRequestDtoList.add(abisRequestDto); + Mockito.when(packetInfoManager.getAbisRequestsByBioRefId(any())).thenReturn(abisRequestDtoList); + + Mockito.doNothing().when(packetInfoManager).saveAbisRequest(any(), any(), any()); + + Mockito.when(packetInfoManager.getDemoListByTransactionId(any())).thenReturn(regDemoDedupeListDtoList); + + PowerMockito.mockStatic(JsonUtils.class); + PowerMockito.when(JsonUtils.javaObjectToJsonString(any(AbisInsertRequestDto.class))) + .thenReturn("AbisInsertRequestDto"); + PowerMockito.when(JsonUtils.javaObjectToJsonString(ArgumentMatchers.any(AbisIdentifyRequestDto.class))) + .thenThrow(JsonProcessingException.class); + + MessageDTO dto = new MessageDTO(); + dto.setRid("10003100030001520190422074511"); + MessageDTO result = abisHandlerStage.process(dto); + + assertTrue(result.getInternalError()); + assertTrue(result.getIsValid()); + } + + + @Test + public void bioRecordDataNotFound() + throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { + + defaultMockToProcess(); + + Mockito.when(packetManagerService.getBiometrics(any(), any(), any(), any(), any())).thenReturn(null); + mockDataSharePolicy(Lists.newArrayList(BiometricType.IRIS, BiometricType.FINGER, BiometricType.FACE)); + + setMetaInfoMap(new LinkedList<>(getExceptionModalityMap().values())); + MessageDTO dto = new MessageDTO(); + dto.setRid("10003100030001520190422074511"); + MessageDTO result = abisHandlerStage.process(dto); + + assertTrue(result.getIsValid()); + assertTrue(result.getInternalError()); + } + + @Test + public void biometricsNotFoundWithSegmentConfig() + throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { + + defaultMockToProcess(); + + Mockito.when(packetManagerService.getBiometrics(any(), any(), any(), any(), any())).thenReturn(getBiometricRecord(Arrays.asList("Left Thumb" ,"Right Thumb","Face"),false)); + + + setMetaInfoMap(Arrays.asList("leftEye")); + MessageDTO dto = new MessageDTO(); + dto.setRid("10003100030001520190422074511"); + MessageDTO result = abisHandlerStage.process(dto); + + assertTrue(result.getIsValid()); + assertTrue(result.getInternalError()); + } + + @Test + public void biometricsTypeNotFoundConfig() + throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { + + defaultMockToProcess(); + + Map> biometricModalitySegmentsMap = new HashMap(); + biometricModalitySegmentsMap.put("Finger", getFingerList()); + biometricModalitySegmentsMap.put("Iris", getIrisList()); + ReflectionTestUtils.setField(abisHandlerStage, "biometricModalitySegmentsMapAdult", biometricModalitySegmentsMap); + ReflectionTestUtils.setField(abisHandlerStage, "exceptionSegmentsMap", getExceptionModalityMap()); + + MessageDTO dto = new MessageDTO(); + dto.setRid("10003100030001520190422074511"); + MessageDTO result = abisHandlerStage.process(dto); + + assertTrue(result.getIsValid()); + assertTrue(result.getInternalError()); + } + + @Test + public void testBiometricSegmentNotConfiguredInfant() throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { + registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); + registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); + Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); + Mockito.when(packetInfoManager.getAllAbisDetails()).thenReturn(abisApplicationDtos); + + Mockito.when(packetInfoManager.getBioRefIdByRegId(any())).thenReturn(bioRefDtos); + tags.put("AGE_GROUP", "INFANT"); + Mockito.when(packetService.getAllTags(any())).thenReturn(tags); + + Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); + Mockito.doNothing().when(packetInfoManager).saveAbisRequest(any(), any(), any()); + + RegDemoDedupeListDto regDemoDedupeListDto = new RegDemoDedupeListDto(); + regDemoDedupeListDto.setMatchedRegId("10003100030001520190422074511"); + regDemoDedupeListDtoList.add(regDemoDedupeListDto); + Mockito.when(packetInfoManager.getDemoListByTransactionId(any())).thenReturn(regDemoDedupeListDtoList); + + MessageDTO dto = new MessageDTO(); + dto.setRid("10003100030001520190422074511"); + MessageDTO result = abisHandlerStage.process(dto); + + assertTrue(result.getIsValid()); + assertFalse(result.getInternalError()); + } + + + + @Test + public void emptyBdbFound() + throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { + + defaultMockToProcess(); + + boolean isBdbEmpty = true; + Mockito.when(packetManagerService.getBiometrics(any(), any(), any(), any(), any())).thenReturn(getBiometricRecord(Arrays.asList("Left RingFinger"), isBdbEmpty )); + mockDataSharePolicy(Lists.newArrayList(BiometricType.FINGER)); + + List list = new ArrayList(getExceptionModalityMap().values()); + list.remove("leftRing"); + setMetaInfoMap(list); + + MessageDTO dto = new MessageDTO(); + dto.setRid("10003100030001520190422074511"); + MessageDTO result = abisHandlerStage.process(dto); + + assertTrue(result.getIsValid()); + assertTrue(result.getInternalError()); + } + + @Test + public void noBdbInAnyBiometric() + throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { + + defaultMockToProcess(); + + Mockito.when(packetManagerService.getBiometrics(any(), any(), any(), any(), any())).thenReturn(getBiometricRecord(Arrays.asList("Left Thumb" ,"Right Thumb" , "Left MiddleFinger" , + "Left RingFinger" ,"Left LittleFinger" ,"Left IndexFinger" ,"Right MiddleFinger" , + "Right RingFinger" ,"Right LittleFinger" ,"Right IndexFinger" , + "Left" ,"Right","Face"),true)); + + MessageDTO dto = new MessageDTO(); + dto.setRid("10003100030001520190422074511"); + MessageDTO result = abisHandlerStage.process(dto); + + assertTrue(result.getIsValid()); + assertTrue(result.getInternalError()); + } + + private void defaultMockToProcess() { + registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); + registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); + Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); + Mockito.when(packetInfoManager.getAllAbisDetails()).thenReturn(abisApplicationDtos); + + RegBioRefDto regBioRefDto = new RegBioRefDto(); + regBioRefDto.setBioRefId("1234567890"); + bioRefDtos.add(regBioRefDto); + Mockito.when(packetInfoManager.getBioRefIdByRegId(any())).thenReturn(bioRefDtos); + + Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); + Mockito.doNothing().when(packetInfoManager).saveAbisRequest(any(), any(), any()); + + RegDemoDedupeListDto regDemoDedupeListDto = new RegDemoDedupeListDto(); + regDemoDedupeListDto.setMatchedRegId("10003100030001520190422074511"); + regDemoDedupeListDtoList.add(regDemoDedupeListDto); + Mockito.when(packetInfoManager.getDemoListByTransactionId(any())).thenReturn(regDemoDedupeListDtoList); + + } + + private void setMetaInfoMap(List exceptionAttributes) throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException{ + + Map metaInfoMap = new HashMap<>(); + + Map> exceptionBiometrcisMap = new HashMap<>(); + + Map applicantExceptionBiometrcisMap = new HashMap(); + + if(exceptionAttributes!=null) { + for(String exceptionAttribute : exceptionAttributes) { + + Map detailMap = new HashMap(); + detailMap.put("missingBiometric", exceptionAttribute); + detailMap.put("reason", "Temporary"); + detailMap.put("individualType", "applicant"); + + applicantExceptionBiometrcisMap.put(exceptionAttribute, detailMap); + + } + } + + + exceptionBiometrcisMap.put("applicant", applicantExceptionBiometrcisMap); + Gson gson = new Gson(); + Type gsonType = new TypeToken(){}.getType(); + + String gsonString = gson.toJson(exceptionBiometrcisMap,gsonType); + + metaInfoMap.put("exceptionBiometrics", gsonString); + Mockito.when(packetManagerService.getMetaInfo(any(), any(), any())).thenReturn(metaInfoMap); + } + + private BiometricRecord getBiometricRecord(List bioAttributes, boolean isBdbEmpty) { + BiometricRecord biometricRecord = new BiometricRecord(); + + byte[] bdb = isBdbEmpty ? null : new byte[2048]; + for(String bioAttribute : bioAttributes) { + BIR birType1 = new BIR.BIRBuilder().build(); + 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 = bioAttribute.equalsIgnoreCase("face") ? BiometricType.FACE : + bioAttribute.equalsIgnoreCase("left") || bioAttribute.equalsIgnoreCase("right") ? BiometricType.IRIS : BiometricType.FINGER ; + List singleTypeList1 = new ArrayList<>(); + singleTypeList1.add(singleType1); + bdbInfoType1.setType(singleTypeList1); + + + + String[] bioAttributeArray = bioAttribute.split(" "); + + List subtype = new ArrayList<>(); + for(String attribute : bioAttributeArray) { + subtype.add(attribute); + } + bdbInfoType1.setSubtype(subtype); + + birType1.setBdbInfo(bdbInfoType1); + birType1.setBdb(bdb); + + if(bdb==null) { + Map others = new HashMap<>(); + others.put("EXCEPTION", true); + HashMap entry = new HashMap<>(); + entry.put("EXCEPTION", "true"); + birType1.setOthers(entry); + + } + + biometricRecord.getSegments().add(birType1); + } + + return biometricRecord; + } + } \ No newline at end of file diff --git a/registration-processor/core-processor/registration-processor-abis-middleware-stage/src/test/java/io/mosip/registartion/processor/abis/middleware/stage/AbisMiddleWareStageTest.java b/registration-processor/core-processor/registration-processor-abis-middleware-stage/src/test/java/io/mosip/registartion/processor/abis/middleware/stage/AbisMiddleWareStageTest.java index 3e6d1861d26..00db3cbdbd2 100644 --- a/registration-processor/core-processor/registration-processor-abis-middleware-stage/src/test/java/io/mosip/registartion/processor/abis/middleware/stage/AbisMiddleWareStageTest.java +++ b/registration-processor/core-processor/registration-processor-abis-middleware-stage/src/test/java/io/mosip/registartion/processor/abis/middleware/stage/AbisMiddleWareStageTest.java @@ -1,684 +1,698 @@ -package io.mosip.registartion.processor.abis.middleware.stage; - -import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.*; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import io.mosip.registration.processor.core.util.PropertiesUtil; -import org.apache.activemq.command.ActiveMQBytesMessage; -import org.apache.activemq.util.ByteSequence; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.ArgumentMatchers; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; -import org.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.test.util.ReflectionTestUtils; - -import io.mosip.registration.processor.abis.queue.dto.AbisQueueDetails; -import io.mosip.registration.processor.core.abstractverticle.EventDTO; -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.exception.RegistrationProcessorCheckedException; -import io.mosip.registration.processor.core.exception.RegistrationProcessorUnCheckedException; -import io.mosip.registration.processor.core.packet.dto.Identity; -import io.mosip.registration.processor.core.packet.dto.abis.AbisIdentifyResponseDto; -import io.mosip.registration.processor.core.packet.dto.abis.AbisRequestDto; -import io.mosip.registration.processor.core.packet.dto.abis.CandidateListDto; -import io.mosip.registration.processor.core.packet.dto.abis.CandidatesDto; -import io.mosip.registration.processor.core.packet.dto.abis.RegBioRefDto; -import io.mosip.registration.processor.core.queue.factory.MosipQueue; -import io.mosip.registration.processor.core.queue.impl.exception.ConnectionUnavailableException; -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.queue.MosipQueueManager; -import io.mosip.registration.processor.core.util.JsonUtil; -import io.mosip.registration.processor.packet.storage.dao.PacketInfoDao; -import io.mosip.registration.processor.packet.storage.dto.ApplicantInfoDto; -import io.mosip.registration.processor.packet.storage.entity.AbisRequestEntity; -import io.mosip.registration.processor.packet.storage.entity.AbisResponseDetEntity; -import io.mosip.registration.processor.packet.storage.entity.AbisResponseEntity; -import io.mosip.registration.processor.packet.storage.repository.BasePacketRepository; -import io.mosip.registration.processor.packet.storage.utils.Utilities; -import io.mosip.registration.processor.rest.client.audit.builder.AuditLogRequestBuilder; -import io.mosip.registration.processor.status.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; -import io.vertx.core.AsyncResult; -import io.vertx.core.Handler; -import io.vertx.core.Vertx; -import io.vertx.ext.web.Router; - -@RunWith(PowerMockRunner.class) -@PrepareForTest({ JsonUtil.class }) -@PowerMockIgnore({"com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*","javax.management.*", "javax.net.ssl.*" }) -public class AbisMiddleWareStageTest { - - @Mock - private MosipQueueManager mosipQueueManager; - - @Mock - private PacketInfoManager packetInfoManager; - - @Mock - private BasePacketRepository abisRequestRepositary; - - @Mock - private BasePacketRepository abisResponseRepositary; - - @Mock - private BasePacketRepository abisResponseDetailRepositary; - - @Mock - private Utilities utility; - - @Mock - private RegistrationStatusDao registrationStatusDao; - - @Mock - private RegistrationStatusService registrationStatusService; - - @Mock - private AuditLogRequestBuilder auditLogRequestBuilder; - - @Mock - private PacketInfoDao packetInfoDao; - - private RegistrationStatusEntity regStatusEntity; - private List abisRefList; - private List abisInsertIdentifyList; - private List mosipQueueList; - private int messageTTL = 0; - - @InjectMocks - AbisMiddleWareStage stage = new AbisMiddleWareStage() { - - @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 consumeAndSend(MosipEventBus mosipEventBus, MessageBusAddress fromAddress, - MessageBusAddress toAddress, long messageExpiryTimeLimit) { - } - - @Override - public void consume(MosipEventBus mosipEventBus, MessageBusAddress fromAddress, - long messageExpiryTimeLimit) { - - } - - @Override - public Router postUrl(Vertx vertx, MessageBusAddress consumeAddress, MessageBusAddress sendAddress) { - return null; - } - - @Override - public Integer getPort() { - return 8080; - }; - - }; - - @Mock - private PropertiesUtil propertiesUtil; - - @Before - public void setUp() throws RegistrationProcessorCheckedException { - MockitoAnnotations.openMocks(this); - ReflectionTestUtils.setField(stage, "messageFormat", "byte"); - ReflectionTestUtils.setField(stage, "workerPoolSize", 10); - ReflectionTestUtils.setField(stage, "messageExpiryTimeLimit", Long.valueOf(0)); - ReflectionTestUtils.setField(stage, "clusterManagerUrl", "/dummyPath"); - InternalRegistrationStatusDto internalRegStatusDto = new InternalRegistrationStatusDto(); - internalRegStatusDto.setRegistrationId(""); - internalRegStatusDto.setLatestTransactionStatusCode("Demodedupe"); - Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())) - .thenReturn(internalRegStatusDto); - - regStatusEntity = new RegistrationStatusEntity(); - regStatusEntity.setLatestRegistrationTransactionId("1234"); - Mockito.when(registrationStatusDao.find(Mockito.anyString(), Mockito.anyString(), Mockito.anyInt(), Mockito.anyString())).thenReturn(regStatusEntity); - - abisRefList = new ArrayList<>(); - abisRefList.add("88"); - Mockito.when(packetInfoManager.getReferenceIdByWorkflowInstanceId(Mockito.anyString())).thenReturn(abisRefList); - - abisInsertIdentifyList = new ArrayList<>(); - AbisRequestDto insertAbisReq = new AbisRequestDto(); - insertAbisReq.setRefRegtrnId("10001100010027120190430071052"); - insertAbisReq.setAbisAppCode("Abis1"); - insertAbisReq.setBioRefId("d1070375-0960-4e90-b12c-72ab6186444d"); - insertAbisReq.setRequestType("INSERT"); - insertAbisReq.setId("f4b1f6fd-466c-462f-aa8b-c218596542ec"); - insertAbisReq.setStatusCode("IN_PROGRESS"); - insertAbisReq.setReqText("mosip".getBytes()); - - AbisRequestDto insertAlreadyProcessed = new AbisRequestDto(); - insertAlreadyProcessed.setRefRegtrnId("de7c4893-bf6f-46b4-a4d5-5cd458d5c7e2"); - insertAlreadyProcessed.setAbisAppCode("Abis2"); - insertAlreadyProcessed.setBioRefId("d1070375-0960-4e90-b12c-72ab6186444d"); - insertAlreadyProcessed.setRequestType("INSERT"); - insertAlreadyProcessed.setId("f4b1f6fd-466c-462f-aa8b-c218596542ed"); - insertAlreadyProcessed.setStatusCode("ALREADY_PROCESSED"); - insertAlreadyProcessed.setReqText("mosip".getBytes()); - - AbisRequestDto identifyAbisReq = new AbisRequestDto(); - identifyAbisReq.setRefRegtrnId("de7c4893-bf6f-46b4-a4d5-5cd458d5c7e2"); - identifyAbisReq.setAbisAppCode("Abis1"); - identifyAbisReq.setBioRefId("d1070375-0960-4e90-b12c-72ab6186444d"); - identifyAbisReq.setRequestType("IDENTIFY"); - insertAbisReq.setId("f4b1f6fd-466c-462f-aa8b-c218596542ee"); - insertAbisReq.setReqText("mosip".getBytes()); - - AbisRequestDto identifyAbisReq1 = new AbisRequestDto(); - identifyAbisReq1.setRefRegtrnId("de7c4893-bf6f-46b4-a4d5-5cd458d5c7e2"); - identifyAbisReq1.setAbisAppCode("Abis2"); - identifyAbisReq1.setBioRefId("d1070375-0960-4e90-b12c-72ab6186444d"); - identifyAbisReq1.setRequestType("IDENTIFY"); - identifyAbisReq1.setId("f4b1f6fd-466c-462f-aa8b-c218596542ef"); - identifyAbisReq1.setReqText("mosip".getBytes()); - - abisInsertIdentifyList.add(insertAbisReq); - abisInsertIdentifyList.add(identifyAbisReq); - abisInsertIdentifyList.add(identifyAbisReq1); - abisInsertIdentifyList.add(insertAlreadyProcessed); - - mosipQueueList = new ArrayList<>(); - MosipQueue queue1 = new MosipQueue() { - @Override - public String getQueueName() { - // TODO Auto-generated method stub - return "Abis1"; - } - - @Override - public void createConnection(String username, String password, String brokerUrl) { - // TODO Auto-generated method stub - - } - }; - - MosipQueue queue2 = new MosipQueue() { - @Override - public String getQueueName() { - // TODO Auto-generated method stub - return "Abis2"; - } - - @Override - public void createConnection(String username, String password, String brokerUrl) { - // TODO Auto-generated method stub - - } - }; - mosipQueueList.add(queue1); - mosipQueueList.add(queue2); - - List abisInboundAddresses = new ArrayList<>(); - abisInboundAddresses.add("abis1-inbound-address"); - - List abisOutboundAddresses = new ArrayList<>(); - abisOutboundAddresses.add("abis1-outboundaddress"); - List> abisInboundOutBounAddressList = new ArrayList<>(); - abisInboundOutBounAddressList.add(abisInboundAddresses); - abisInboundOutBounAddressList.add(abisOutboundAddresses); - - AbisQueueDetails abisQueue = new AbisQueueDetails(); - abisQueue.setMosipQueue(queue1); - abisQueue.setInboundQueueName("abis1-inbound-Queue"); - abisQueue.setOutboundQueueName("abis1-outbound-Queue"); - abisQueue.setName("Abis1"); - - AbisQueueDetails abisQueue1 = new AbisQueueDetails(); - abisQueue1.setMosipQueue(queue2); - abisQueue1.setInboundQueueName("abis2-inbound-Queue"); - abisQueue1.setOutboundQueueName("abis2-outbound-Queue"); - abisQueue1.setName("Abis2"); - List abisQueueList = new ArrayList<>(); - abisQueueList.add(abisQueue); - abisQueueList.add(abisQueue1); - - Mockito.when(utility.getAbisQueueDetails()).thenReturn(abisQueueList); - Mockito.when(packetInfoManager.getBatchIdByRequestId(ArgumentMatchers.any())) - .thenReturn("69098823-eba8-4aa9-bb64-9e0d36bd64a9"); - List bioRefId = new ArrayList<>(); - bioRefId.add("d1070375-0960-4e90-b12c-72ab6186444d"); - Mockito.when(packetInfoManager.getReferenceIdByBatchId(Mockito.anyString())).thenReturn(bioRefId); - List regBioRefist = new ArrayList(); - RegBioRefDto bioRefDto = new RegBioRefDto(); - bioRefDto.setBioRefId("d1070375-0960-4e90-b12c-72ab6186444d"); - bioRefDto.setRegId("10001100010027120190430071052"); - regBioRefist.add(bioRefDto); - Mockito.when(packetInfoManager.getRegBioRefDataByBioRefIds(Mockito.any())).thenReturn(regBioRefist); - List transIdList = new ArrayList<>(); - transIdList.add("1234"); - Mockito.when(packetInfoManager.getAbisTransactionIdByRequestId(Mockito.anyString())).thenReturn(transIdList); - // - // packetInfoManager.getIdentifyReqListByTransactionId( - // transactionIdList.get(0), AbisStatusCode.IDENTIFY.toString()) - List abisIdentifyRequestDtoList = new ArrayList<>(); - AbisRequestDto abisIdentifyRequestDto = new AbisRequestDto(); - abisIdentifyRequestDto.setAbisAppCode("Abis1"); - abisIdentifyRequestDto.setBioRefId("d1070375-0960-4e90-b12c-72ab6186444d"); - abisIdentifyRequestDto.setId("98509c18-ff22-46b7-a8c7-b4dec1d00c85"); - abisIdentifyRequestDto.setReqText("mosip".getBytes()); - abisIdentifyRequestDto.setReqBatchId("d87e6e28-4234-4433-b45d-0313c2aeca01"); - abisIdentifyRequestDtoList.add(abisIdentifyRequestDto); - Mockito.when(packetInfoManager.getIdentifyReqListByTransactionId(Mockito.any(), Mockito.any())) - .thenReturn(abisIdentifyRequestDtoList); - - // Mockito.when(utility.getInboundOutBoundAddressList()).thenReturn(abisInboundOutBounAddressList); - messageTTL = 30 * 60; - - Mockito.when(propertiesUtil.getProperty(any(), any(Class.class), anyBoolean())).thenReturn(true); - } - - @Test - public void processTest() throws RegistrationProcessorCheckedException { - - Mockito.when(packetInfoManager.getInsertOrIdentifyRequest(Mockito.anyString(), Mockito.anyString())) - .thenReturn(abisInsertIdentifyList); - - Mockito.when(mosipQueueManager.send(Mockito.any(), Mockito.anyString(), Mockito.any())).thenReturn(true); - MessageDTO dto = new MessageDTO(); - dto.setRid("10003100030001520190422074511"); - dto.setWorkflowInstanceId("workflowInstanceId"); - dto.setReg_type("NEW"); - - stage.deployVerticle(); - stage.process(dto); - assertTrue(dto.getIsValid()); - - // test for insert request list is empty - List abisInsertIdentifyList = new ArrayList<>(); - AbisRequestDto identifyAbisReq = new AbisRequestDto(); - identifyAbisReq.setRefRegtrnId("d87e6e28-4234-4433-b45d-0313c2aeca01"); - identifyAbisReq.setAbisAppCode("Abis1"); - identifyAbisReq.setBioRefId("d1070375-0960-4e90-b12c-72ab6186444d"); - identifyAbisReq.setRequestType("IDENTIFY"); - identifyAbisReq.setReqText("mosip".getBytes()); - abisInsertIdentifyList.add(identifyAbisReq); - Mockito.when(packetInfoManager.getInsertOrIdentifyRequest(Mockito.anyString(), Mockito.anyString())) - .thenReturn(abisInsertIdentifyList); - stage.process(dto); - assertTrue(dto.getIsValid()); - } - - @Test - public void testProcessForMessageFormatText() throws RegistrationProcessorCheckedException { - - ReflectionTestUtils.setField(stage, "messageFormat", "text"); - Mockito.when(packetInfoManager.getInsertOrIdentifyRequest(Mockito.anyString(), Mockito.anyString())) - .thenReturn(abisInsertIdentifyList); - - Mockito.when(mosipQueueManager.send(Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyInt())) - .thenThrow(ConnectionUnavailableException.class); - MessageDTO dto = new MessageDTO(); - dto.setRid("10003100030001520190422074511"); - dto.setWorkflowInstanceId("workflowInstanceId"); - dto.setReg_type("NEW"); - - stage.deployVerticle(); - stage.process(dto); - assertTrue(dto.getIsValid()); - assertTrue(dto.getInternalError()); - } - - @Test - public void testInsertIdentitySuccessText() throws RegistrationProcessorCheckedException { - // test for insert identity success - ReflectionTestUtils.setField(stage, "messageFormat", "text"); - Mockito.when(packetInfoManager.getInsertOrIdentifyRequest(Mockito.anyString(), Mockito.anyString())) - .thenReturn(abisInsertIdentifyList); - - Mockito.when(mosipQueueManager.send(Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyInt())) - .thenReturn(true); - MessageDTO dto = new MessageDTO(); - dto.setRid("10003100030001520190422074511"); - dto.setWorkflowInstanceId("workflowInstanceId"); - dto.setReg_type("NEW"); - - stage.deployVerticle(); - stage.process(dto); - assertTrue(dto.getIsValid()); - } - - @Test - public void testVariousScenarious() throws RegistrationProcessorCheckedException { - // Mockito.when(utility.getMosipQueuesForAbis()).thenReturn(mosipQueueList); - Mockito.when(packetInfoManager.getInsertOrIdentifyRequest(Mockito.anyString(), Mockito.anyString())) - .thenReturn(abisInsertIdentifyList); - Mockito.when(mosipQueueManager.send(Mockito.any(), Mockito.anyString(), Mockito.any())).thenReturn(true); - MessageDTO dto = new MessageDTO(); - dto.setRid("10003100030001520190422074511"); - Mockito.when(packetInfoManager.getReferenceIdByWorkflowInstanceId(Mockito.anyString())).thenReturn(null); - stage.deployVerticle(); - stage.process(dto); - assertTrue(dto.getIsValid()); - assertTrue(dto.getInternalError()); - - // test for null transactionId - Mockito.when(registrationStatusDao.find(Mockito.anyString(),Mockito.anyString(),Mockito.anyInt(), Mockito.anyString())).thenReturn(null); - Mockito.when(packetInfoManager.getReferenceIdByWorkflowInstanceId(Mockito.anyString())).thenReturn(abisRefList); - stage.process(dto); - assertTrue(dto.getIsValid()); - assertTrue(dto.getInternalError()); - - // test for empty insertidentify request List - Mockito.when(registrationStatusDao.find(Mockito.anyString(), Mockito.anyString(), Mockito.anyInt(), Mockito.anyString())).thenReturn(regStatusEntity); - Mockito.when(packetInfoManager.getInsertOrIdentifyRequest(Mockito.anyString(), Mockito.anyString())) - .thenReturn(new ArrayList()); - Mockito.when(packetInfoManager.getReferenceIdByWorkflowInstanceId(Mockito.anyString())).thenReturn(abisRefList); - stage.process(dto); - assertTrue(dto.getIsValid()); - assertTrue(dto.getInternalError()); - - // test for send to queue failed - Mockito.when(registrationStatusDao.find(Mockito.anyString(), Mockito.anyString(), Mockito.anyInt(), Mockito.anyString())).thenReturn(regStatusEntity); - Mockito.when(packetInfoManager.getInsertOrIdentifyRequest(Mockito.anyString(), Mockito.anyString())) - .thenReturn(abisInsertIdentifyList); - Mockito.when(packetInfoManager.getReferenceIdByWorkflowInstanceId(Mockito.anyString())).thenReturn(abisRefList); - Mockito.when(mosipQueueManager.send(Mockito.any(), Mockito.anyString(), Mockito.any())).thenReturn(false); - stage.process(dto); - - // test for exception while sending to queue - Mockito.when(registrationStatusDao.find(Mockito.anyString(), Mockito.anyString(), Mockito.anyInt(), Mockito.anyString())).thenReturn(regStatusEntity); - Mockito.when(packetInfoManager.getInsertOrIdentifyRequest(Mockito.anyString(), Mockito.anyString())) - .thenReturn(abisInsertIdentifyList); - Mockito.when(packetInfoManager.getReferenceIdByWorkflowInstanceId(Mockito.anyString())).thenReturn(abisRefList); - Mockito.when(mosipQueueManager.send(Mockito.any(), Mockito.anyString(), Mockito.any())) - .thenThrow(new NullPointerException()); - stage.process(dto); - assertTrue(dto.getIsValid()); - - } - - // test for unknown exception occured - @Test - public void testException() { -// Mockito.when(packetInfoManager.getInsertOrIdentifyRequest(Mockito.anyString(), Mockito.anyString())) -// .thenReturn(abisInsertIdentifyList); -// Mockito.when(packetInfoManager.getReferenceIdByRid(Mockito.anyString())).thenReturn(abisRefList); -// Mockito.when(mosipQueueManager.send(Mockito.any(), Mockito.any(), Mockito.any())).thenReturn(true); -// Mockito.when(registrationStatusDao.findById(Mockito.anyString())).thenThrow(new TablenotAccessibleException()); - MessageDTO dto = new MessageDTO(); - dto.setRid("10003100030001520190422074511"); - stage.process(dto); - assertTrue(dto.getIsValid()); - assertTrue(dto.getInternalError()); - } - - - - @Test - public void testConsumerListener() throws RegistrationProcessorCheckedException { - - String failedInsertResponse = "{\"id\":\"mosip.abis.insert\",\"requestId\":\"5b64e806-8d5f-4ba1-b641-0b55cf40c0e1\",\"responsetime\":" - + null + ",\"returnValue\":2,\"failureReason\":7}\r\n" - + ""; - ActiveMQBytesMessage amq = new ActiveMQBytesMessage(); - ByteSequence byteSeq = new ByteSequence(); - byteSeq.setData(failedInsertResponse.getBytes()); - amq.setContent(byteSeq); - Vertx vertx = Mockito.mock(Vertx.class); - //MosipEventBus evenBus = new MosipEventBusFactory().getEventBus(vertx, "vertx", "mosip.regproc.abis.middleware."); - MosipEventBus evenBus = Mockito.mock(MosipEventBus.class); - MosipQueue queue = Mockito.mock(MosipQueue.class); - AbisRequestDto abisCommonRequestDto = new AbisRequestDto(); - abisCommonRequestDto.setRequestType("INSERT"); - abisCommonRequestDto.setStatusCode("SENT"); - Mockito.when(packetInfoManager.getAbisRequestByRequestId(Mockito.any())).thenReturn(abisCommonRequestDto); - stage.consumerListener(amq, "abis1_inboundAddress", queue, evenBus, messageTTL); - - String sucessfulResponse = "{\"id\":\"mosip.abis.insert\",\"requestId\":\"5b64e806-8d5f-4ba1-b641-0b55cf40c0e1\",\"responsetime\":" - + null + ",\"returnValue\":1,\"failureReason\":null}\r\n" - + ""; - byteSeq.setData(sucessfulResponse.getBytes()); - amq.setContent(byteSeq); - AbisRequestDto abisCommonRequestDto1 = new AbisRequestDto(); - abisCommonRequestDto1.setRequestType("INSERT"); - abisCommonRequestDto1.setAbisAppCode("Abis1"); - abisCommonRequestDto1.setStatusCode("SENT"); - Mockito.when(packetInfoManager.getAbisRequestByRequestId(Mockito.any())).thenReturn(abisCommonRequestDto1); - stage.consumerListener(amq, "abis1_inboundAddress", queue, evenBus, messageTTL); - // test for multiple response for same request id - abisCommonRequestDto1.setStatusCode("PROCESSED"); - stage.consumerListener(amq, "abis1_inboundAddress", queue, evenBus, messageTTL); - } - - - @Test - public void testConsumerListenerForIdentifyReq() throws RegistrationProcessorCheckedException, IOException { - - String failedInsertResponse = "{\"id\":\"mosip.id.identify\",\"requestId\":\"01234567-89AB-CDEF-0123-456789ABCDEF\",\"responsetime\":\"2020-03-29T07:01:24.692Z\",\"returnValue\":\"2\",\"failureReason\":\"7\"}"; - ActiveMQBytesMessage amq = new ActiveMQBytesMessage(); - ByteSequence byteSeq = new ByteSequence(); - byteSeq.setData(failedInsertResponse.getBytes()); - amq.setContent(byteSeq); - Vertx vertx = Mockito.mock(Vertx.class); - //MosipEventBus evenBus = new MosipEventBusFactory().getEventBus(vertx, "vertx", "mosip.regproc.abis.middleware."); - MosipEventBus evenBus = Mockito.mock(MosipEventBus.class); - MosipQueue queue = Mockito.mock(MosipQueue.class); - AbisRequestDto abisCommonRequestDto = new AbisRequestDto(); - abisCommonRequestDto.setRequestType("IDENTIFY"); - abisCommonRequestDto.setStatusCode("SENT"); - Mockito.when(packetInfoManager.getAbisRequestByRequestId(Mockito.any())).thenReturn(abisCommonRequestDto); - stage.consumerListener(amq, "abis1_inboundAddress", queue, evenBus, messageTTL); - - // Exception - PowerMockito.mockStatic(JsonUtil.class); - PowerMockito.when( - JsonUtil.readValueWithUnknownProperties(Mockito.anyString(), Mockito.eq(AbisIdentifyResponseDto.class))) - .thenThrow(NullPointerException.class); - stage.consumerListener(amq, "abis1_inboundAddress", queue, evenBus, messageTTL); - } - - @Test(expected = RegistrationProcessorCheckedException.class) - public void testConsumerListenerForIdentifyReqIOException() throws RegistrationProcessorCheckedException, IOException { - - // test for IO Exception - String failedInsertResponse = "{\"id\":\"mosip.id.identify\",\"requestId\":\"01234567-89AB-CDEF-0123-456789ABCDEF\",\"responsetime\":\"2020-03-29T07:01:24.692Z\",\"returnValue\":\"2\",\"failureReason\":\"7\"}"; - ActiveMQBytesMessage amq = new ActiveMQBytesMessage(); - ByteSequence byteSeq = new ByteSequence(); - byteSeq.setData(failedInsertResponse.getBytes()); - amq.setContent(byteSeq); - MosipEventBus evenBus = Mockito.mock(MosipEventBus.class); - MosipQueue queue = Mockito.mock(MosipQueue.class); - - AbisRequestDto abisCommonRequestDto = new AbisRequestDto(); - abisCommonRequestDto.setRequestType("IDENTIFY"); - abisCommonRequestDto.setStatusCode("SENT"); - Mockito.when(packetInfoManager.getAbisRequestByRequestId(Mockito.any())).thenReturn(abisCommonRequestDto); - PowerMockito.mockStatic(JsonUtil.class); - PowerMockito.when( - JsonUtil.readValueWithUnknownProperties(Mockito.anyString(), Mockito.eq(AbisIdentifyResponseDto.class))) - .thenThrow(IOException.class); - stage.consumerListener(amq, "abis1_inboundAddress", queue, evenBus, messageTTL); - } - - - @Test - public void batchIdNull() throws RegistrationProcessorCheckedException { - String sucessfulResponse = "{\"id\":\"mosip.abis.insert\",\"requestId\":\"5b64e806-8d5f-4ba1-b641-0b55cf40c0e1\",\"responsetime\":" - + null + ",\"returnValue\":1,\"failureReason\":null}\r\n" - + ""; - ActiveMQBytesMessage amq1 = new ActiveMQBytesMessage(); - ByteSequence byteSeq1 = new ByteSequence(); - byteSeq1.setData(sucessfulResponse.getBytes()); - amq1.setContent(byteSeq1); - Vertx vertx1 = Mockito.mock(Vertx.class); - //MosipEventBus evenBus = new MosipEventBusFactory().getEventBus(vertx, "vertx", "mosip.regproc.abis.middleware."); - MosipEventBus eventBus = Mockito.mock(MosipEventBus.class); - MosipQueue queue1 = Mockito.mock(MosipQueue.class); - AbisRequestDto abisCommonRequestDto1 = new AbisRequestDto(); - abisCommonRequestDto1.setRequestType("INSERT"); - abisCommonRequestDto1.setAbisAppCode("Abis1"); - //Mockito.when(packetInfoManager.getAbisRequestByRequestId(Mockito.any())).thenReturn(abisCommonRequestDto1); - Mockito.when(packetInfoManager.getBatchIdByRequestId(Mockito.anyString())).thenReturn(null); - stage.consumerListener(amq1, "abis1_inboundAddress", queue1, eventBus, messageTTL); - - } - - // - @Test - public void testIdentifyConsumerListener() throws RegistrationProcessorCheckedException, NoSuchFieldException, - SecurityException, IllegalArgumentException, IllegalAccessException { - Mockito.when(packetInfoManager.getBatchStatusbyBatchId(Mockito.anyString())).thenReturn(null); - - // test for identify succes response - no duplicates - String identifySucessfulResponse = "{\"id\":\"mosip.abis.identify\",\"requestId\":\"8a3effd4-5fba-44e0-8cbb-3083ba098209\",\"responsetime\":" - + null + ",\"returnValue\":1,\"failureReason\":null,\"candidateList\":null}"; - ActiveMQBytesMessage amq1 = new ActiveMQBytesMessage(); - ByteSequence byteSeq1 = new ByteSequence(); - byteSeq1.setData(identifySucessfulResponse.getBytes()); - amq1.setContent(byteSeq1); - Vertx vertx1 = Mockito.mock(Vertx.class); - //MosipEventBus evenBus = new MosipEventBusFactory().getEventBus(vertx, "vertx", "mosip.regproc.abis.middleware."); - MosipEventBus evenBus1 = Mockito.mock(MosipEventBus.class); - MosipQueue queue1 = Mockito.mock(MosipQueue.class); - AbisRequestDto abisCommonRequestDto1 = new AbisRequestDto(); - abisCommonRequestDto1.setRequestType("IDENTIFY"); - abisCommonRequestDto1.setStatusCode("SENT"); - Mockito.when(packetInfoManager.getAbisRequestByRequestId(Mockito.any())).thenReturn(abisCommonRequestDto1); - stage.consumerListener(amq1, "abis1_inboundAddress", queue1, evenBus1, messageTTL); - // test for multiple response for same request id - abisCommonRequestDto1.setStatusCode("PROCESSED"); - stage.consumerListener(amq1, "abis1_inboundAddress", queue1, evenBus1, messageTTL); - // test for identify failed response - String identifyFailedResponse = "{\"id\":\"mosip.abis.identify\",\"requestId\":\"8a3effd4-5fba-44e0-8cbb-3083ba098209\",\"responsetime\":" - + null + ",\"returnValue\":2,\"failureReason\":3,\"candidateList\":null}"; - byteSeq1.setData(identifyFailedResponse.getBytes()); - amq1.setContent(byteSeq1); - abisCommonRequestDto1.setStatusCode("SENT"); - stage.consumerListener(amq1, "abis1_inboundAddress", queue1, evenBus1, messageTTL); - - // test for identify response - with duplicates - List bioRefId = new ArrayList<>(); - bioRefId.add("d1070375-0960-4e90-b12c-72ab6186764c"); - Mockito.when(packetInfoManager.getReferenceIdByBatchId(Mockito.anyString())).thenReturn(bioRefId); - Mockito.when(packetInfoDao.getRegIdByBioRefId(ArgumentMatchers.any())).thenReturn("Test123"); - String duplicateIdentifySuccessResponse = "{\"id\":\"mosip.abis.identify\",\"requestId\":\"f4b1f6fd-466c-462f-aa8b-c218596542ec\",\"responsetime\":" - + null - + ",\"returnValue\":1,\"failureReason\":null,\"candidateList\":{\"count\":\"1\",\"candidates\":[{\"referenceId\":\"d1070375-0960-4e90-b12c-72ab6186444d\",\"analytics\":null,\"modalities\":null}]}}"; - byteSeq1.setData(duplicateIdentifySuccessResponse.getBytes()); - amq1.setContent(byteSeq1); - abisCommonRequestDto1.setStatusCode("SENT"); - stage.consumerListener(amq1, "abis1_inboundAddress", queue1, evenBus1, messageTTL); - - } - - @Test(expected = RegistrationProcessorUnCheckedException.class) - public void testDeployVerticle() throws RegistrationProcessorCheckedException { - Mockito.when(utility.getAbisQueueDetails()).thenThrow(RegistrationProcessorCheckedException.class); - stage.deployVerticle(); - } - - @Test - public void testConsumerListenerForIdentifyRequest() throws RegistrationProcessorCheckedException, IOException { - String failedInsertResponse = "{\"id\":\"mosip.id.identify\",\"requestId\":\"01234567-89AB-CDEF-0123-456789ABCDEF\",\"responsetime\":\"2020-03-29T07:01:24.692Z\",\"returnValue\":\"2\",\"failureReason\":\"7\"}"; - ActiveMQBytesMessage amq = new ActiveMQBytesMessage(); - ByteSequence byteSeq = new ByteSequence(); - byteSeq.setData(failedInsertResponse.getBytes()); - amq.setContent(byteSeq); - Vertx vertx = Mockito.mock(Vertx.class); - //MosipEventBus evenBus = new MosipEventBusFactory().getEventBus(vertx, "vertx", "mosip.regproc.abis.middleware."); - MosipEventBus evenBus = Mockito.mock(MosipEventBus.class); - MosipQueue queue = Mockito.mock(MosipQueue.class); - AbisRequestDto abisCommonRequestDto = new AbisRequestDto(); - abisCommonRequestDto.setRequestType("IDENTIFY"); - abisCommonRequestDto.setStatusCode("SENT"); - Mockito.when(packetInfoManager.getAbisRequestByRequestId(Mockito.any())).thenReturn(abisCommonRequestDto); - - AbisIdentifyResponseDto abisIdentifyResponseDto = new AbisIdentifyResponseDto(); - abisIdentifyResponseDto.setReturnValue("1"); - abisIdentifyResponseDto.setFailureReason("Test"); - abisIdentifyResponseDto.setRequestId("Test1"); - CandidateListDto candidateList = new CandidateListDto(); - CandidatesDto candidate = new CandidatesDto(); - candidate.setReferenceId("e1070375-0960-4e90-b12c-72ab6186444d"); - CandidatesDto[] candidates = new CandidatesDto[1]; - candidates[0] = candidate; - candidateList.setCandidates(candidates); - abisIdentifyResponseDto.setCandidateList(candidateList); - String response = new String(((ActiveMQBytesMessage) amq).getContent().data); - PowerMockito.mockStatic(JsonUtil.class); - PowerMockito.when(JsonUtil.objectMapperReadValue(response, AbisIdentifyResponseDto.class)).thenReturn(abisIdentifyResponseDto); - PowerMockito.when(JsonUtil.readValueWithUnknownProperties(failedInsertResponse, - AbisIdentifyResponseDto.class)).thenReturn(abisIdentifyResponseDto); - Mockito.when(packetInfoDao.getRegIdByBioRefId(ArgumentMatchers.any())).thenReturn("Test123"); - - stage.consumerListener(amq, "abis1_inboundAddress", queue, evenBus, messageTTL); - } - - @Test(expected = RegistrationProcessorCheckedException.class) - public void testConsumerListenerForIdentifyReqException() throws RegistrationProcessorCheckedException, IOException { - String failedInsertResponse = "{\"id\":\"mosip.id.identify\",\"requestId\":\"01234567-89AB-CDEF-0123-456789ABCDEF\",\"responsetime\":\"2020-03-29T07:01:24.692Z\",\"returnValue\":\"2\",\"failureReason\":\"7\"}"; - ActiveMQBytesMessage amq = new ActiveMQBytesMessage(); - ByteSequence byteSeq = new ByteSequence(); - byteSeq.setData(failedInsertResponse.getBytes()); - amq.setContent(byteSeq); - Vertx vertx = Mockito.mock(Vertx.class); - //MosipEventBus evenBus = new MosipEventBusFactory().getEventBus(vertx, "vertx", "mosip.regproc.abis.middleware."); - MosipEventBus evenBus = Mockito.mock(MosipEventBus.class); - MosipQueue queue = Mockito.mock(MosipQueue.class); - AbisRequestDto abisCommonRequestDto = new AbisRequestDto(); - abisCommonRequestDto.setRequestType("IDENTIFY"); - abisCommonRequestDto.setStatusCode("SENT"); - Mockito.when(packetInfoManager.getAbisRequestByRequestId(Mockito.any())).thenReturn(abisCommonRequestDto); - - AbisIdentifyResponseDto abisIdentifyResponseDto = new AbisIdentifyResponseDto(); - abisIdentifyResponseDto.setReturnValue("1"); - abisIdentifyResponseDto.setFailureReason("Test"); - abisIdentifyResponseDto.setRequestId("Test1"); - CandidateListDto candidateList = new CandidateListDto(); - CandidatesDto candidate = new CandidatesDto(); - candidate.setReferenceId("e1070375-0960-4e90-b12c-72ab6186444d"); - CandidatesDto[] candidates = new CandidatesDto[1]; - candidates[0] = candidate; - candidateList.setCandidates(candidates); - abisIdentifyResponseDto.setCandidateList(candidateList); - String response = new String(((ActiveMQBytesMessage) amq).getContent().data); - PowerMockito.mockStatic(JsonUtil.class); - PowerMockito.when(JsonUtil.readValueWithUnknownProperties(response, AbisIdentifyResponseDto.class)).thenThrow(IOException.class); - stage.consumerListener(amq, "abis1_inboundAddress", queue, evenBus, messageTTL); - } +package io.mosip.registartion.processor.abis.middleware.stage; + +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyBoolean; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import org.apache.activemq.command.ActiveMQBytesMessage; +import org.apache.activemq.util.ByteSequence; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentMatchers; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.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.test.util.ReflectionTestUtils; + +import io.mosip.registration.processor.abis.queue.dto.AbisQueueDetails; +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.exception.RegistrationProcessorCheckedException; +import io.mosip.registration.processor.core.exception.RegistrationProcessorUnCheckedException; +import io.mosip.registration.processor.core.packet.dto.Identity; +import io.mosip.registration.processor.core.packet.dto.abis.AbisIdentifyResponseDto; +import io.mosip.registration.processor.core.packet.dto.abis.AbisRequestDto; +import io.mosip.registration.processor.core.packet.dto.abis.CandidateListDto; +import io.mosip.registration.processor.core.packet.dto.abis.CandidatesDto; +import io.mosip.registration.processor.core.packet.dto.abis.RegBioRefDto; +import io.mosip.registration.processor.core.queue.factory.MosipQueue; +import io.mosip.registration.processor.core.queue.impl.exception.ConnectionUnavailableException; +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.queue.MosipQueueManager; +import io.mosip.registration.processor.core.util.JsonUtil; +import io.mosip.registration.processor.core.util.PropertiesUtil; +import io.mosip.registration.processor.packet.storage.dao.PacketInfoDao; +import io.mosip.registration.processor.packet.storage.dto.ApplicantInfoDto; +import io.mosip.registration.processor.packet.storage.entity.AbisRequestEntity; +import io.mosip.registration.processor.packet.storage.entity.AbisResponseDetEntity; +import io.mosip.registration.processor.packet.storage.entity.AbisResponseEntity; +import io.mosip.registration.processor.packet.storage.repository.BasePacketRepository; +import io.mosip.registration.processor.packet.storage.utils.Utilities; +import io.mosip.registration.processor.rest.client.audit.builder.AuditLogRequestBuilder; +import io.mosip.registration.processor.status.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; +import io.vertx.core.AsyncResult; +import io.vertx.core.Handler; +import io.vertx.core.Vertx; +import io.vertx.ext.web.Router; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({ JsonUtil.class }) +@PowerMockIgnore({"com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*","javax.management.*", "javax.net.ssl.*" }) +public class AbisMiddleWareStageTest { + + @Mock + private MosipQueueManager mosipQueueManager; + + @Mock + private PacketInfoManager packetInfoManager; + + @Mock + private BasePacketRepository abisRequestRepositary; + + @Mock + private BasePacketRepository abisResponseRepositary; + + @Mock + private BasePacketRepository abisResponseDetailRepositary; + + @Mock + private Utilities utility; + + @Mock + private RegistrationStatusDao registrationStatusDao; + + @Mock + private RegistrationStatusService registrationStatusService; + + @Mock + private AuditLogRequestBuilder auditLogRequestBuilder; + + @Mock + private PacketInfoDao packetInfoDao; + + private RegistrationStatusEntity regStatusEntity; + private List abisRefList; + private List abisInsertIdentifyList; + private List mosipQueueList; + private int messageTTL = 0; + + @InjectMocks + AbisMiddleWareStage stage = new AbisMiddleWareStage() { + + @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 consumeAndSend(MosipEventBus mosipEventBus, MessageBusAddress fromAddress, + MessageBusAddress toAddress, long messageExpiryTimeLimit) { + } + + @Override + public void consume(MosipEventBus mosipEventBus, MessageBusAddress fromAddress, + long messageExpiryTimeLimit) { + + } + + @Override + public Router postUrl(Vertx vertx, MessageBusAddress consumeAddress, MessageBusAddress sendAddress) { + return null; + } + + @Override + public Integer getPort() { + return 8080; + }; + + }; + + @Mock + private PropertiesUtil propertiesUtil; + + @Before + public void setUp() throws RegistrationProcessorCheckedException { + MockitoAnnotations.openMocks(this); + ReflectionTestUtils.setField(stage, "messageFormat", "byte"); + ReflectionTestUtils.setField(stage, "workerPoolSize", 10); + ReflectionTestUtils.setField(stage, "messageExpiryTimeLimit", Long.valueOf(0)); + ReflectionTestUtils.setField(stage, "clusterManagerUrl", "/dummyPath"); + InternalRegistrationStatusDto internalRegStatusDto = new InternalRegistrationStatusDto(); + internalRegStatusDto.setRegistrationId(""); + internalRegStatusDto.setLatestTransactionStatusCode("Demodedupe"); + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())) + .thenReturn(internalRegStatusDto); + + regStatusEntity = new RegistrationStatusEntity(); + regStatusEntity.setLatestRegistrationTransactionId("1234"); + Mockito.when(registrationStatusDao.find(Mockito.anyString(), Mockito.anyString(), Mockito.anyInt(), Mockito.anyString())).thenReturn(regStatusEntity); + + abisRefList = new ArrayList<>(); + abisRefList.add("88"); + Mockito.when(packetInfoManager.getReferenceIdByWorkflowInstanceId(Mockito.anyString())).thenReturn(abisRefList); + + abisInsertIdentifyList = new ArrayList<>(); + AbisRequestDto insertAbisReq = new AbisRequestDto(); + insertAbisReq.setRefRegtrnId("10001100010027120190430071052"); + insertAbisReq.setAbisAppCode("Abis1"); + insertAbisReq.setBioRefId("d1070375-0960-4e90-b12c-72ab6186444d"); + insertAbisReq.setRequestType("INSERT"); + insertAbisReq.setId("f4b1f6fd-466c-462f-aa8b-c218596542ec"); + insertAbisReq.setStatusCode("IN_PROGRESS"); + insertAbisReq.setReqText("mosip".getBytes()); + + AbisRequestDto insertAlreadyProcessed = new AbisRequestDto(); + insertAlreadyProcessed.setRefRegtrnId("de7c4893-bf6f-46b4-a4d5-5cd458d5c7e2"); + insertAlreadyProcessed.setAbisAppCode("Abis2"); + insertAlreadyProcessed.setBioRefId("d1070375-0960-4e90-b12c-72ab6186444d"); + insertAlreadyProcessed.setRequestType("INSERT"); + insertAlreadyProcessed.setId("f4b1f6fd-466c-462f-aa8b-c218596542ed"); + insertAlreadyProcessed.setStatusCode("ALREADY_PROCESSED"); + insertAlreadyProcessed.setReqText("mosip".getBytes()); + + AbisRequestDto identifyAbisReq = new AbisRequestDto(); + identifyAbisReq.setRefRegtrnId("de7c4893-bf6f-46b4-a4d5-5cd458d5c7e2"); + identifyAbisReq.setAbisAppCode("Abis1"); + identifyAbisReq.setBioRefId("d1070375-0960-4e90-b12c-72ab6186444d"); + identifyAbisReq.setRequestType("IDENTIFY"); + insertAbisReq.setId("f4b1f6fd-466c-462f-aa8b-c218596542ee"); + insertAbisReq.setReqText("mosip".getBytes()); + + AbisRequestDto identifyAbisReq1 = new AbisRequestDto(); + identifyAbisReq1.setRefRegtrnId("de7c4893-bf6f-46b4-a4d5-5cd458d5c7e2"); + identifyAbisReq1.setAbisAppCode("Abis2"); + identifyAbisReq1.setBioRefId("d1070375-0960-4e90-b12c-72ab6186444d"); + identifyAbisReq1.setRequestType("IDENTIFY"); + identifyAbisReq1.setId("f4b1f6fd-466c-462f-aa8b-c218596542ef"); + identifyAbisReq1.setReqText("mosip".getBytes()); + + abisInsertIdentifyList.add(insertAbisReq); + abisInsertIdentifyList.add(identifyAbisReq); + abisInsertIdentifyList.add(identifyAbisReq1); + abisInsertIdentifyList.add(insertAlreadyProcessed); + + mosipQueueList = new ArrayList<>(); + MosipQueue queue1 = new MosipQueue() { + @Override + public String getQueueName() { + // TODO Auto-generated method stub + return "Abis1"; + } + + @Override + public void createConnection(String username, String password, String brokerUrl) { + // TODO Auto-generated method stub + + } + }; + + MosipQueue queue2 = new MosipQueue() { + @Override + public String getQueueName() { + // TODO Auto-generated method stub + return "Abis2"; + } + + @Override + public void createConnection(String username, String password, String brokerUrl) { + // TODO Auto-generated method stub + + } + }; + mosipQueueList.add(queue1); + mosipQueueList.add(queue2); + + List abisInboundAddresses = new ArrayList<>(); + abisInboundAddresses.add("abis1-inbound-address"); + + List abisOutboundAddresses = new ArrayList<>(); + abisOutboundAddresses.add("abis1-outboundaddress"); + List> abisInboundOutBounAddressList = new ArrayList<>(); + abisInboundOutBounAddressList.add(abisInboundAddresses); + abisInboundOutBounAddressList.add(abisOutboundAddresses); + + AbisQueueDetails abisQueue = new AbisQueueDetails(); + abisQueue.setMosipQueue(queue1); + abisQueue.setInboundQueueName("abis1-inbound-Queue"); + abisQueue.setOutboundQueueName("abis1-outbound-Queue"); + abisQueue.setName("Abis1"); + + AbisQueueDetails abisQueue1 = new AbisQueueDetails(); + abisQueue1.setMosipQueue(queue2); + abisQueue1.setInboundQueueName("abis2-inbound-Queue"); + abisQueue1.setOutboundQueueName("abis2-outbound-Queue"); + abisQueue1.setName("Abis2"); + List abisQueueList = new ArrayList<>(); + abisQueueList.add(abisQueue); + abisQueueList.add(abisQueue1); + + Mockito.when(utility.getAbisQueueDetails()).thenReturn(abisQueueList); + Mockito.when(packetInfoManager.getBatchIdByRequestId(ArgumentMatchers.any())) + .thenReturn("69098823-eba8-4aa9-bb64-9e0d36bd64a9"); + List bioRefId = new ArrayList<>(); + bioRefId.add("d1070375-0960-4e90-b12c-72ab6186444d"); + Mockito.when(packetInfoManager.getReferenceIdByBatchId(Mockito.anyString())).thenReturn(bioRefId); + List regBioRefist = new ArrayList(); + RegBioRefDto bioRefDto = new RegBioRefDto(); + bioRefDto.setBioRefId("d1070375-0960-4e90-b12c-72ab6186444d"); + bioRefDto.setRegId("10001100010027120190430071052"); + regBioRefist.add(bioRefDto); + Mockito.when(packetInfoManager.getRegBioRefDataByBioRefIds(Mockito.any())).thenReturn(regBioRefist); + List transIdList = new ArrayList<>(); + transIdList.add("1234"); + Mockito.when(packetInfoManager.getAbisTransactionIdByRequestId(Mockito.anyString())).thenReturn(transIdList); + // + // packetInfoManager.getIdentifyReqListByTransactionId( + // transactionIdList.get(0), AbisStatusCode.IDENTIFY.toString()) + List abisIdentifyRequestDtoList = new ArrayList<>(); + AbisRequestDto abisIdentifyRequestDto = new AbisRequestDto(); + abisIdentifyRequestDto.setAbisAppCode("Abis1"); + abisIdentifyRequestDto.setBioRefId("d1070375-0960-4e90-b12c-72ab6186444d"); + abisIdentifyRequestDto.setId("98509c18-ff22-46b7-a8c7-b4dec1d00c85"); + abisIdentifyRequestDto.setReqText("mosip".getBytes()); + abisIdentifyRequestDto.setReqBatchId("d87e6e28-4234-4433-b45d-0313c2aeca01"); + abisIdentifyRequestDtoList.add(abisIdentifyRequestDto); + Mockito.when(packetInfoManager.getIdentifyReqListByTransactionId(Mockito.any(), Mockito.any())) + .thenReturn(abisIdentifyRequestDtoList); + + // Mockito.when(utility.getInboundOutBoundAddressList()).thenReturn(abisInboundOutBounAddressList); + messageTTL = 30 * 60; + + Mockito.when(propertiesUtil.getProperty(any(), any(Class.class), anyBoolean())).thenReturn(true); + } + + @Test + public void processTest() throws RegistrationProcessorCheckedException { + + Mockito.when(packetInfoManager.getInsertOrIdentifyRequest(Mockito.anyString(), Mockito.anyString())) + .thenReturn(abisInsertIdentifyList); + + Mockito.when(mosipQueueManager.send(Mockito.any(), Mockito.anyString(), Mockito.any())).thenReturn(true); + MessageDTO dto = new MessageDTO(); + dto.setRid("10003100030001520190422074511"); + dto.setWorkflowInstanceId("workflowInstanceId"); + dto.setReg_type("NEW"); + + stage.deployVerticle(); + stage.process(dto); + assertTrue(dto.getIsValid()); + + // test for insert request list is empty + List abisInsertIdentifyList = new ArrayList<>(); + AbisRequestDto identifyAbisReq = new AbisRequestDto(); + identifyAbisReq.setRefRegtrnId("d87e6e28-4234-4433-b45d-0313c2aeca01"); + identifyAbisReq.setAbisAppCode("Abis1"); + identifyAbisReq.setBioRefId("d1070375-0960-4e90-b12c-72ab6186444d"); + identifyAbisReq.setRequestType("IDENTIFY"); + identifyAbisReq.setReqText("mosip".getBytes()); + abisInsertIdentifyList.add(identifyAbisReq); + Mockito.when(packetInfoManager.getInsertOrIdentifyRequest(Mockito.anyString(), Mockito.anyString())) + .thenReturn(abisInsertIdentifyList); + stage.process(dto); + assertTrue(dto.getIsValid()); + } + + @Test + public void testProcessForMessageFormatText() throws RegistrationProcessorCheckedException { + + ReflectionTestUtils.setField(stage, "messageFormat", "text"); + Mockito.when(packetInfoManager.getInsertOrIdentifyRequest(Mockito.anyString(), Mockito.anyString())) + .thenReturn(abisInsertIdentifyList); + + Mockito.when(mosipQueueManager.send(Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyInt())) + .thenThrow(ConnectionUnavailableException.class); + MessageDTO dto = new MessageDTO(); + dto.setRid("10003100030001520190422074511"); + dto.setWorkflowInstanceId("workflowInstanceId"); + dto.setReg_type("NEW"); + + stage.deployVerticle(); + stage.process(dto); + assertTrue(dto.getIsValid()); + assertTrue(dto.getInternalError()); + } + + @Test + public void testInsertIdentitySuccessText() throws RegistrationProcessorCheckedException { + // test for insert identity success + ReflectionTestUtils.setField(stage, "messageFormat", "text"); + Mockito.when(packetInfoManager.getInsertOrIdentifyRequest(Mockito.anyString(), Mockito.anyString())) + .thenReturn(abisInsertIdentifyList); + + Mockito.when(mosipQueueManager.send(Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyInt())) + .thenReturn(true); + MessageDTO dto = new MessageDTO(); + dto.setRid("10003100030001520190422074511"); + dto.setWorkflowInstanceId("workflowInstanceId"); + dto.setReg_type("NEW"); + + stage.deployVerticle(); + stage.process(dto); + assertTrue(dto.getIsValid()); + } + + @Test + public void testVariousScenarious() throws RegistrationProcessorCheckedException { + // Mockito.when(utility.getMosipQueuesForAbis()).thenReturn(mosipQueueList); + Mockito.when(packetInfoManager.getInsertOrIdentifyRequest(Mockito.anyString(), Mockito.anyString())) + .thenReturn(abisInsertIdentifyList); + Mockito.when(mosipQueueManager.send(Mockito.any(), Mockito.anyString(), Mockito.any())).thenReturn(true); + MessageDTO dto = new MessageDTO(); + dto.setRid("10003100030001520190422074511"); + Mockito.when(packetInfoManager.getReferenceIdByWorkflowInstanceId(Mockito.anyString())).thenReturn(null); + stage.deployVerticle(); + stage.process(dto); + assertTrue(dto.getIsValid()); + assertTrue(dto.getInternalError()); + + // test for null transactionId + Mockito.when(registrationStatusDao.find(Mockito.anyString(),Mockito.anyString(),Mockito.anyInt(), Mockito.anyString())).thenReturn(null); + Mockito.when(packetInfoManager.getReferenceIdByWorkflowInstanceId(Mockito.anyString())).thenReturn(abisRefList); + stage.process(dto); + assertTrue(dto.getIsValid()); + assertTrue(dto.getInternalError()); + + // test for empty insertidentify request List + Mockito.when(registrationStatusDao.find(Mockito.anyString(), Mockito.anyString(), Mockito.anyInt(), Mockito.anyString())).thenReturn(regStatusEntity); + Mockito.when(packetInfoManager.getInsertOrIdentifyRequest(Mockito.anyString(), Mockito.anyString())) + .thenReturn(new ArrayList()); + Mockito.when(packetInfoManager.getReferenceIdByWorkflowInstanceId(Mockito.anyString())).thenReturn(abisRefList); + stage.process(dto); + assertTrue(dto.getIsValid()); + assertTrue(dto.getInternalError()); + + // test for send to queue failed + Mockito.when(registrationStatusDao.find(Mockito.anyString(), Mockito.anyString(), Mockito.anyInt(), Mockito.anyString())).thenReturn(regStatusEntity); + Mockito.when(packetInfoManager.getInsertOrIdentifyRequest(Mockito.anyString(), Mockito.anyString())) + .thenReturn(abisInsertIdentifyList); + Mockito.when(packetInfoManager.getReferenceIdByWorkflowInstanceId(Mockito.anyString())).thenReturn(abisRefList); + Mockito.when(mosipQueueManager.send(Mockito.any(), Mockito.anyString(), Mockito.any())).thenReturn(false); + stage.process(dto); + + // test for exception while sending to queue + Mockito.when(registrationStatusDao.find(Mockito.anyString(), Mockito.anyString(), Mockito.anyInt(), Mockito.anyString())).thenReturn(regStatusEntity); + Mockito.when(packetInfoManager.getInsertOrIdentifyRequest(Mockito.anyString(), Mockito.anyString())) + .thenReturn(abisInsertIdentifyList); + Mockito.when(packetInfoManager.getReferenceIdByWorkflowInstanceId(Mockito.anyString())).thenReturn(abisRefList); + Mockito.when(mosipQueueManager.send(Mockito.any(), Mockito.anyString(), Mockito.any())) + .thenThrow(new NullPointerException()); + stage.process(dto); + assertTrue(dto.getIsValid()); + + } + + // test for unknown exception occured + @Test + public void testException() { +// Mockito.when(packetInfoManager.getInsertOrIdentifyRequest(Mockito.anyString(), Mockito.anyString())) +// .thenReturn(abisInsertIdentifyList); +// Mockito.when(packetInfoManager.getReferenceIdByRid(Mockito.anyString())).thenReturn(abisRefList); +// Mockito.when(mosipQueueManager.send(Mockito.any(), Mockito.any(), Mockito.any())).thenReturn(true); +// Mockito.when(registrationStatusDao.findById(Mockito.anyString())).thenThrow(new TablenotAccessibleException()); + MessageDTO dto = new MessageDTO(); + dto.setRid("10003100030001520190422074511"); + stage.process(dto); + assertTrue(dto.getIsValid()); + assertTrue(dto.getInternalError()); + } + + + + @Test + public void testConsumerListener() throws RegistrationProcessorCheckedException { + + String failedInsertResponse = "{\"id\":\"mosip.abis.insert\",\"requestId\":\"5b64e806-8d5f-4ba1-b641-0b55cf40c0e1\",\"responsetime\":" + + null + ",\"returnValue\":2,\"failureReason\":7}\r\n" + + ""; + ActiveMQBytesMessage amq = new ActiveMQBytesMessage(); + ByteSequence byteSeq = new ByteSequence(); + byteSeq.setData(failedInsertResponse.getBytes()); + amq.setContent(byteSeq); + Vertx vertx = Mockito.mock(Vertx.class); + //MosipEventBus evenBus = new MosipEventBusFactory().getEventBus(vertx, "vertx", "mosip.regproc.abis.middleware."); + MosipEventBus evenBus = Mockito.mock(MosipEventBus.class); + MosipQueue queue = Mockito.mock(MosipQueue.class); + AbisRequestDto abisCommonRequestDto = new AbisRequestDto(); + abisCommonRequestDto.setRequestType("INSERT"); + abisCommonRequestDto.setStatusCode("SENT"); + Mockito.when(packetInfoManager.getAbisRequestByRequestId(Mockito.any())).thenReturn(abisCommonRequestDto); + stage.consumerListener(amq, "abis1_inboundAddress", queue, evenBus, messageTTL); + + String sucessfulResponse = "{\"id\":\"mosip.abis.insert\",\"requestId\":\"5b64e806-8d5f-4ba1-b641-0b55cf40c0e1\",\"responsetime\":" + + null + ",\"returnValue\":1,\"failureReason\":null}\r\n" + + ""; + byteSeq.setData(sucessfulResponse.getBytes()); + amq.setContent(byteSeq); + AbisRequestDto abisCommonRequestDto1 = new AbisRequestDto(); + abisCommonRequestDto1.setRequestType("INSERT"); + abisCommonRequestDto1.setAbisAppCode("Abis1"); + abisCommonRequestDto1.setStatusCode("SENT"); + Mockito.when(packetInfoManager.getAbisRequestByRequestId(Mockito.any())).thenReturn(abisCommonRequestDto1); + stage.consumerListener(amq, "abis1_inboundAddress", queue, evenBus, messageTTL); + // test for multiple response for same request id + abisCommonRequestDto1.setStatusCode("PROCESSED"); + stage.consumerListener(amq, "abis1_inboundAddress", queue, evenBus, messageTTL); + } + + + @Test + public void testConsumerListenerForIdentifyReq() throws RegistrationProcessorCheckedException, IOException { + + String failedInsertResponse = "{\"id\":\"mosip.id.identify\",\"requestId\":\"01234567-89AB-CDEF-0123-456789ABCDEF\",\"responsetime\":\"2020-03-29T07:01:24.692Z\",\"returnValue\":\"2\",\"failureReason\":\"7\"}"; + ActiveMQBytesMessage amq = new ActiveMQBytesMessage(); + ByteSequence byteSeq = new ByteSequence(); + byteSeq.setData(failedInsertResponse.getBytes()); + amq.setContent(byteSeq); + Vertx vertx = Mockito.mock(Vertx.class); + //MosipEventBus evenBus = new MosipEventBusFactory().getEventBus(vertx, "vertx", "mosip.regproc.abis.middleware."); + MosipEventBus evenBus = Mockito.mock(MosipEventBus.class); + MosipQueue queue = Mockito.mock(MosipQueue.class); + AbisRequestDto abisCommonRequestDto = new AbisRequestDto(); + abisCommonRequestDto.setRequestType("IDENTIFY"); + abisCommonRequestDto.setStatusCode("SENT"); + Mockito.when(packetInfoManager.getAbisRequestByRequestId(Mockito.any())).thenReturn(abisCommonRequestDto); + stage.consumerListener(amq, "abis1_inboundAddress", queue, evenBus, messageTTL); + + // Exception + PowerMockito.mockStatic(JsonUtil.class); + PowerMockito.when( + JsonUtil.readValueWithUnknownProperties(Mockito.anyString(), Mockito.eq(AbisIdentifyResponseDto.class))) + .thenThrow(NullPointerException.class); + stage.consumerListener(amq, "abis1_inboundAddress", queue, evenBus, messageTTL); + } + + @Test(expected = RegistrationProcessorCheckedException.class) + public void testConsumerListenerForIdentifyReqIOException() throws RegistrationProcessorCheckedException, IOException { + + // test for IO Exception + String failedInsertResponse = "{\"id\":\"mosip.id.identify\",\"requestId\":\"01234567-89AB-CDEF-0123-456789ABCDEF\",\"responsetime\":\"2020-03-29T07:01:24.692Z\",\"returnValue\":\"2\",\"failureReason\":\"7\"}"; + ActiveMQBytesMessage amq = new ActiveMQBytesMessage(); + ByteSequence byteSeq = new ByteSequence(); + byteSeq.setData(failedInsertResponse.getBytes()); + amq.setContent(byteSeq); + MosipEventBus evenBus = Mockito.mock(MosipEventBus.class); + MosipQueue queue = Mockito.mock(MosipQueue.class); + + AbisRequestDto abisCommonRequestDto = new AbisRequestDto(); + abisCommonRequestDto.setRequestType("IDENTIFY"); + abisCommonRequestDto.setStatusCode("SENT"); + Mockito.when(packetInfoManager.getAbisRequestByRequestId(Mockito.any())).thenReturn(abisCommonRequestDto); + PowerMockito.mockStatic(JsonUtil.class); + PowerMockito.when( + JsonUtil.readValueWithUnknownProperties(Mockito.anyString(), Mockito.eq(AbisIdentifyResponseDto.class))) + .thenThrow(IOException.class); + stage.consumerListener(amq, "abis1_inboundAddress", queue, evenBus, messageTTL); + } + + + @Test + public void batchIdNull() throws RegistrationProcessorCheckedException { + String sucessfulResponse = "{\"id\":\"mosip.abis.insert\",\"requestId\":\"5b64e806-8d5f-4ba1-b641-0b55cf40c0e1\",\"responsetime\":" + + null + ",\"returnValue\":1,\"failureReason\":null}\r\n" + + ""; + ActiveMQBytesMessage amq1 = new ActiveMQBytesMessage(); + ByteSequence byteSeq1 = new ByteSequence(); + byteSeq1.setData(sucessfulResponse.getBytes()); + amq1.setContent(byteSeq1); + Vertx vertx1 = Mockito.mock(Vertx.class); + //MosipEventBus evenBus = new MosipEventBusFactory().getEventBus(vertx, "vertx", "mosip.regproc.abis.middleware."); + MosipEventBus eventBus = Mockito.mock(MosipEventBus.class); + MosipQueue queue1 = Mockito.mock(MosipQueue.class); + AbisRequestDto abisCommonRequestDto1 = new AbisRequestDto(); + abisCommonRequestDto1.setRequestType("INSERT"); + abisCommonRequestDto1.setAbisAppCode("Abis1"); + //Mockito.when(packetInfoManager.getAbisRequestByRequestId(Mockito.any())).thenReturn(abisCommonRequestDto1); + Mockito.when(packetInfoManager.getBatchIdByRequestId(Mockito.anyString())).thenReturn(null); + stage.consumerListener(amq1, "abis1_inboundAddress", queue1, eventBus, messageTTL); + + } + + // + @Test + public void testIdentifyConsumerListener() throws RegistrationProcessorCheckedException, NoSuchFieldException, + SecurityException, IllegalArgumentException, IllegalAccessException { + Mockito.when(packetInfoManager.getBatchStatusbyBatchId(Mockito.anyString())).thenReturn(null); + + // test for identify succes response - no duplicates + String identifySucessfulResponse = "{\"id\":\"mosip.abis.identify\",\"requestId\":\"8a3effd4-5fba-44e0-8cbb-3083ba098209\",\"responsetime\":" + + null + ",\"returnValue\":1,\"failureReason\":null,\"candidateList\":null}"; + ActiveMQBytesMessage amq1 = new ActiveMQBytesMessage(); + ByteSequence byteSeq1 = new ByteSequence(); + byteSeq1.setData(identifySucessfulResponse.getBytes()); + amq1.setContent(byteSeq1); + Vertx vertx1 = Mockito.mock(Vertx.class); + //MosipEventBus evenBus = new MosipEventBusFactory().getEventBus(vertx, "vertx", "mosip.regproc.abis.middleware."); + MosipEventBus evenBus1 = Mockito.mock(MosipEventBus.class); + MosipQueue queue1 = Mockito.mock(MosipQueue.class); + AbisRequestDto abisCommonRequestDto1 = new AbisRequestDto(); + abisCommonRequestDto1.setRequestType("IDENTIFY"); + abisCommonRequestDto1.setStatusCode("SENT"); + Mockito.when(packetInfoManager.getAbisRequestByRequestId(Mockito.any())).thenReturn(abisCommonRequestDto1); + stage.consumerListener(amq1, "abis1_inboundAddress", queue1, evenBus1, messageTTL); + // test for multiple response for same request id + abisCommonRequestDto1.setStatusCode("PROCESSED"); + stage.consumerListener(amq1, "abis1_inboundAddress", queue1, evenBus1, messageTTL); + // test for identify failed response + String identifyFailedResponse = "{\"id\":\"mosip.abis.identify\",\"requestId\":\"8a3effd4-5fba-44e0-8cbb-3083ba098209\",\"responsetime\":" + + null + ",\"returnValue\":2,\"failureReason\":3,\"candidateList\":null}"; + byteSeq1.setData(identifyFailedResponse.getBytes()); + amq1.setContent(byteSeq1); + abisCommonRequestDto1.setStatusCode("SENT"); + stage.consumerListener(amq1, "abis1_inboundAddress", queue1, evenBus1, messageTTL); + + // test for identify response - with duplicates + List bioRefId = new ArrayList<>(); + bioRefId.add("d1070375-0960-4e90-b12c-72ab6186764c"); + Mockito.when(packetInfoManager.getReferenceIdByBatchId(Mockito.anyString())).thenReturn(bioRefId); + Mockito.when(packetInfoDao.getRegIdByBioRefId(ArgumentMatchers.any())).thenReturn("Test123"); + String duplicateIdentifySuccessResponse = "{\"id\":\"mosip.abis.identify\",\"requestId\":\"f4b1f6fd-466c-462f-aa8b-c218596542ec\",\"responsetime\":" + + null + + ",\"returnValue\":1,\"failureReason\":null,\"candidateList\":{\"count\":\"1\",\"candidates\":[{\"referenceId\":\"d1070375-0960-4e90-b12c-72ab6186444d\",\"analytics\":null,\"modalities\":null}]}}"; + byteSeq1.setData(duplicateIdentifySuccessResponse.getBytes()); + amq1.setContent(byteSeq1); + abisCommonRequestDto1.setStatusCode("SENT"); + stage.consumerListener(amq1, "abis1_inboundAddress", queue1, evenBus1, messageTTL); + + } + + @Test(expected = RegistrationProcessorUnCheckedException.class) + public void testDeployVerticle() throws RegistrationProcessorCheckedException { + Mockito.when(utility.getAbisQueueDetails()).thenThrow(RegistrationProcessorCheckedException.class); + stage.deployVerticle(); + } + + @Test + public void testConsumerListenerForIdentifyRequest() throws RegistrationProcessorCheckedException, IOException { + String failedInsertResponse = "{\"id\":\"mosip.id.identify\",\"requestId\":\"01234567-89AB-CDEF-0123-456789ABCDEF\",\"responsetime\":\"2020-03-29T07:01:24.692Z\",\"returnValue\":\"2\",\"failureReason\":\"7\"}"; + ActiveMQBytesMessage amq = new ActiveMQBytesMessage(); + ByteSequence byteSeq = new ByteSequence(); + byteSeq.setData(failedInsertResponse.getBytes()); + amq.setContent(byteSeq); + Vertx vertx = Mockito.mock(Vertx.class); + //MosipEventBus evenBus = new MosipEventBusFactory().getEventBus(vertx, "vertx", "mosip.regproc.abis.middleware."); + MosipEventBus evenBus = Mockito.mock(MosipEventBus.class); + MosipQueue queue = Mockito.mock(MosipQueue.class); + AbisRequestDto abisCommonRequestDto = new AbisRequestDto(); + abisCommonRequestDto.setRequestType("IDENTIFY"); + abisCommonRequestDto.setStatusCode("SENT"); + Mockito.when(packetInfoManager.getAbisRequestByRequestId(Mockito.any())).thenReturn(abisCommonRequestDto); + + AbisIdentifyResponseDto abisIdentifyResponseDto = new AbisIdentifyResponseDto(); + abisIdentifyResponseDto.setReturnValue("1"); + abisIdentifyResponseDto.setFailureReason("Test"); + abisIdentifyResponseDto.setRequestId("Test1"); + CandidateListDto candidateList = new CandidateListDto(); + CandidatesDto candidate = new CandidatesDto(); + candidate.setReferenceId("e1070375-0960-4e90-b12c-72ab6186444d"); + CandidatesDto[] candidates = new CandidatesDto[1]; + candidates[0] = candidate; + candidateList.setCandidates(candidates); + abisIdentifyResponseDto.setCandidateList(candidateList); + String response = new String(((ActiveMQBytesMessage) amq).getContent().data); + PowerMockito.mockStatic(JsonUtil.class); + PowerMockito.when(JsonUtil.objectMapperReadValue(response, AbisIdentifyResponseDto.class)).thenReturn(abisIdentifyResponseDto); + PowerMockito.when(JsonUtil.readValueWithUnknownProperties(failedInsertResponse, + AbisIdentifyResponseDto.class)).thenReturn(abisIdentifyResponseDto); + Mockito.when(packetInfoDao.getRegIdByBioRefId(ArgumentMatchers.any())).thenReturn("Test123"); + + stage.consumerListener(amq, "abis1_inboundAddress", queue, evenBus, messageTTL); + } + + @Test(expected = RegistrationProcessorCheckedException.class) + public void testConsumerListenerForIdentifyReqException() throws RegistrationProcessorCheckedException, IOException { + String failedInsertResponse = "{\"id\":\"mosip.id.identify\",\"requestId\":\"01234567-89AB-CDEF-0123-456789ABCDEF\",\"responsetime\":\"2020-03-29T07:01:24.692Z\",\"returnValue\":\"2\",\"failureReason\":\"7\"}"; + ActiveMQBytesMessage amq = new ActiveMQBytesMessage(); + ByteSequence byteSeq = new ByteSequence(); + byteSeq.setData(failedInsertResponse.getBytes()); + amq.setContent(byteSeq); + Vertx vertx = Mockito.mock(Vertx.class); + //MosipEventBus evenBus = new MosipEventBusFactory().getEventBus(vertx, "vertx", "mosip.regproc.abis.middleware."); + MosipEventBus evenBus = Mockito.mock(MosipEventBus.class); + MosipQueue queue = Mockito.mock(MosipQueue.class); + AbisRequestDto abisCommonRequestDto = new AbisRequestDto(); + abisCommonRequestDto.setRequestType("IDENTIFY"); + abisCommonRequestDto.setStatusCode("SENT"); + Mockito.when(packetInfoManager.getAbisRequestByRequestId(Mockito.any())).thenReturn(abisCommonRequestDto); + + AbisIdentifyResponseDto abisIdentifyResponseDto = new AbisIdentifyResponseDto(); + abisIdentifyResponseDto.setReturnValue("1"); + abisIdentifyResponseDto.setFailureReason("Test"); + abisIdentifyResponseDto.setRequestId("Test1"); + CandidateListDto candidateList = new CandidateListDto(); + CandidatesDto candidate = new CandidatesDto(); + candidate.setReferenceId("e1070375-0960-4e90-b12c-72ab6186444d"); + CandidatesDto[] candidates = new CandidatesDto[1]; + candidates[0] = candidate; + candidateList.setCandidates(candidates); + abisIdentifyResponseDto.setCandidateList(candidateList); + String response = new String(((ActiveMQBytesMessage) amq).getContent().data); + PowerMockito.mockStatic(JsonUtil.class); + PowerMockito.when(JsonUtil.readValueWithUnknownProperties(response, AbisIdentifyResponseDto.class)).thenThrow(IOException.class); + stage.consumerListener(amq, "abis1_inboundAddress", queue, evenBus, messageTTL); + } } \ No newline at end of file diff --git a/registration-processor/core-processor/registration-processor-bio-dedupe-stage/src/test/java/io/mosip/registration/processor/biodedupe/stage/BioDedupeStageTest.java b/registration-processor/core-processor/registration-processor-bio-dedupe-stage/src/test/java/io/mosip/registration/processor/biodedupe/stage/BioDedupeStageTest.java index b5246ffb29d..0ceca9c9c86 100644 --- a/registration-processor/core-processor/registration-processor-bio-dedupe-stage/src/test/java/io/mosip/registration/processor/biodedupe/stage/BioDedupeStageTest.java +++ b/registration-processor/core-processor/registration-processor-bio-dedupe-stage/src/test/java/io/mosip/registration/processor/biodedupe/stage/BioDedupeStageTest.java @@ -17,6 +17,7 @@ import brave.Tracing; 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; @@ -77,6 +78,18 @@ public void consumeAndSend(MessageBusAddress fromAddress, MessageBusAddress toAd 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 + + } }; } 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 8e472ab317a..1eb5d98bb47 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 @@ -1,610 +1,623 @@ -package io.mosip.registration.processor.biometric.authentication.stage; - -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.io.InputStream; -import java.security.NoSuchAlgorithmException; -import java.security.cert.CertificateException; -import java.security.spec.InvalidKeySpecException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; - -import org.apache.commons.io.IOUtils; -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.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 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.core.util.HMACUtils2; -import io.mosip.kernel.core.util.exception.JsonProcessingException; -import io.mosip.registration.processor.core.abstractverticle.EventDTO; -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.auth.dto.AuthResponseDTO; -import io.mosip.registration.processor.core.auth.dto.ErrorDTO; -import io.mosip.registration.processor.core.auth.dto.ResponseDTO; -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.exception.ApisResourceAccessException; -import io.mosip.registration.processor.core.exception.BioTypeException; -import io.mosip.registration.processor.core.exception.PacketManagerException; -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.Identity; -import io.mosip.registration.processor.core.packet.dto.masterdata.StatusResponseDto; -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.IdentityIteratorUtil; -import io.mosip.registration.processor.core.util.RegistrationExceptionMapperUtil; -import io.mosip.registration.processor.packet.storage.dto.ApplicantInfoDto; -import io.mosip.registration.processor.packet.storage.utils.AuthUtil; -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.status.dto.InternalRegistrationStatusDto; -import io.mosip.registration.processor.status.dto.RegistrationStatusDto; -import io.mosip.registration.processor.status.dto.SyncRegistrationDto; -import io.mosip.registration.processor.status.dto.SyncResponseDto; -import io.mosip.registration.processor.status.entity.SyncRegistrationEntity; -import io.mosip.registration.processor.status.repositary.SyncRegistrationRepository; -import io.mosip.registration.processor.status.service.RegistrationStatusService; -import io.mosip.registration.processor.status.service.SyncRegistrationService; -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 BiometricAuthenticationStageTest { - - /** The input stream. */ - @Mock - private InputStream inputStream; - - - - /** The registration status service. */ - @Mock - RegistrationStatusService registrationStatusService; - - /** The packet info manager. */ - @Mock - private PacketInfoManager packetInfoManager; - - @Mock - private AuthUtil authUtil; - - @Mock - InternalRegistrationStatusDto registrationStatusDto; - - @Mock - private RegistrationProcessorRestClientService restClientService; - - @Mock - private IdentityIteratorUtil identityIteratorUtil; - - /** The dto. */ - MessageDTO dto = new MessageDTO(); - - @Mock - private PriorityBasedPacketManagerService packetManagerService; - - @Mock - private SyncRegistrationService syncRegistrationservice; - - /** The BiometricAuthenticationStage stage. */ - @InjectMocks - private BiometricAuthenticationStage biometricAuthenticationStage = new BiometricAuthenticationStage() { - @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 consumeAndSend(MosipEventBus mosipEventBus, MessageBusAddress fromAddress, - MessageBusAddress toAddress, long messageExpiryTimeLimit) { - } - - @Override - public Integer getPort() { - return 8080; - } - }; - - /** The audit log request builder. */ - @Mock - private AuditLogRequestBuilder auditLogRequestBuilder; - - @Mock - private Environment env; - - - - - /** The dto. */ - InternalRegistrationStatusDto statusDto; - /** The list. */ - List list; - - /** The list appender. */ - private ListAppender listAppender; - - @Mock - private RegistrationProcessorRestClientService registrationProcessorRestService; - - @Mock - private Utilities utility; - - @Mock - ObjectMapper mapIdentityJsonStringToObject; - - @Mock - private SyncRegistrationRepository registrationRepositary; - - StatusResponseDto statusResponseDto; - - @Mock - LogDescription description; - - @Mock - RegistrationExceptionMapperUtil registrationStatusMapperUtil; - - private SyncRegistrationEntity regentity = Mockito.mock(SyncRegistrationEntity.class); - - /** - * Sets the up. - * - * @throws Exception - * the exception - */ - @Before - public void setUp() throws Exception { - ReflectionTestUtils.setField(biometricAuthenticationStage, "workerPoolSize", 10); - ReflectionTestUtils.setField(biometricAuthenticationStage, "messageExpiryTimeLimit", Long.valueOf(0)); - ReflectionTestUtils.setField(biometricAuthenticationStage, "clusterManagerUrl", "/dummyPath"); - ReflectionTestUtils.setField(biometricAuthenticationStage, "ageLimit", "5"); - - - when(utility.getGetRegProcessorDemographicIdentity()).thenReturn("identity"); - - - list = new ArrayList(); - - listAppender = new ListAppender<>(); - - dto.setRid("2018701130000410092018110735"); - dto.setReg_type("UPDATE"); - - MockitoAnnotations.initMocks(this); - - - ResponseWrapper responseWrapper = new ResponseWrapper<>(); - Mockito.doReturn(responseWrapper).when(auditLogRequestBuilder).createAuditRequestBuilder( - "test case description", EventId.RPR_405.toString(), EventName.UPDATE.toString(), - EventType.BUSINESS.toString(), "1234testcase", ApiName.AUDIT); - - - - InternalRegistrationStatusDto registrationStatusDto = new InternalRegistrationStatusDto(); - registrationStatusDto = new InternalRegistrationStatusDto(); - registrationStatusDto.setRegistrationId("2018701130000410092018110735"); - registrationStatusDto.setStatusCode(""); - registrationStatusDto.setRegistrationType("UPDATE"); - listAppender.start(); - list.add(registrationStatusDto); - when(registrationStatusService.getByStatus(anyString())).thenReturn(list); - when(registrationStatusService.getRegistrationStatus(anyString(), any(), any(), any())).thenReturn(registrationStatusDto); - Mockito.doNothing().when(registrationStatusService).updateRegistrationStatus(any(), any(), any()); - - when(identityIteratorUtil.getFieldValue(any(), any())).thenReturn("UPDATE"); - - - Mockito.doNothing().when(description).setMessage(any()); - when(registrationStatusMapperUtil.getStatusCode(any())).thenReturn(""); - - - statusResponseDto = new StatusResponseDto(); - statusResponseDto.setStatus("VALID"); - when(registrationProcessorRestService.getApi(any(), any(), anyString(), any(), any())) - .thenReturn(statusResponseDto); - - JSONObject jsonObject = Mockito.mock(JSONObject.class); - when(utility.getUIn(anyString(), anyString(), any())).thenReturn("12345678"); - when(utility.retrieveIdrepoJson(any())).thenReturn(jsonObject); - FieldValue fieldValue = new FieldValue(); - FieldValue fieldValue1 = new FieldValue(); - fieldValue1.setLabel("authenticationBiometricFileName"); - fieldValue1.setValue("biometricTestFileName"); - fieldValue.setLabel("registrationType"); - fieldValue.setValue("update"); - List metadata = new ArrayList<>(); - metadata.add(fieldValue); - metadata.add(fieldValue1); - - - when(utility.getDefaultSource(any(), any())).thenReturn("reg-client"); - when(utility.getApplicantAge(anyString(),anyString(), any())).thenReturn(21); - - regentity.setRegistrationType("update"); - when(syncRegistrationservice.findByWorkflowInstanceId(any())).thenReturn(regentity); - - AuthResponseDTO authResponseDTO = new AuthResponseDTO(); - ResponseDTO responseDTO = new ResponseDTO(); - responseDTO.setAuthStatus(true); - authResponseDTO.setResponse(responseDTO); - when(authUtil.authByIdAuthentication(any(), any(), any())).thenReturn(authResponseDTO); - - 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); - - when(packetManagerService.getBiometricsByMappingJsonKey(any(), any(), any(), any())).thenReturn(biometricRecord); - - - } - - @Test - public void biometricAuthenticationSuccessTest() throws ApisResourceAccessException, IOException, PacketManagerException, JsonProcessingException { - when(regentity.getRegistrationType()).thenReturn("UPDATE"); - 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); - - when(packetManagerService.getBiometricsByMappingJsonKey(any(), - any(), any(),any())).thenReturn(biometricRecord); - - MessageDTO messageDto = biometricAuthenticationStage.process(dto); - assertTrue(messageDto.getIsValid()); - assertFalse(messageDto.getInternalError()); - } - - @Test - public void biometricAuthenticationBiometricNullTest() throws ApisResourceAccessException, IOException, PacketManagerException, JsonProcessingException { - when(regentity.getRegistrationType()).thenReturn("UPDATE"); - - String individualBiometrics="{\"format\" : \"cbeff\",\"version\" : 1.0,\"value\" : \"individualBiometrics_bio_CBEFF\"}"; - when(packetManagerService.getFieldByMappingJsonKey(any(), - any(), any(),any())).thenReturn(individualBiometrics); - - when(packetManagerService.getBiometricsByMappingJsonKey(any(), - any(), any(),any())).thenReturn(null); - - MessageDTO messageDto = biometricAuthenticationStage.process(dto); - assertFalse(messageDto.getIsValid()); - assertFalse(messageDto.getInternalError()); - } - - @Test - public void individualBiometricAuthenticationBiometricNullTest() throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { - when(regentity.getRegistrationType()).thenReturn("UPDATE"); - - when(packetManagerService.getBiometricsByMappingJsonKey(any(), - any(), any(),any())).thenReturn(null); - - MessageDTO messageDto = biometricAuthenticationStage.process(dto); - assertFalse(messageDto.getIsValid()); - assertFalse(messageDto.getInternalError()); - } - - @Test - public void biometricAuthenticationIndividualBiometricsValueNullTest() throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { - when(regentity.getRegistrationType()).thenReturn("UPDATE"); - - String individualBiometrics="{\"format\" : \"cbeff\",\"version\" : 1.0,\"value\" : null}"; - when(packetManagerService.getFieldByMappingJsonKey(any(), - any(), any(),any())).thenReturn(individualBiometrics); - - MessageDTO messageDto = biometricAuthenticationStage.process(dto); - assertTrue(messageDto.getIsValid()); - assertFalse(messageDto.getInternalError()); - } - - @Test - public void IDAuthFailureTest() throws IOException, ApisResourceAccessException, InvalidKeySpecException, NoSuchAlgorithmException, BioTypeException, CertificateException { - AuthResponseDTO authResponseDTO = new AuthResponseDTO(); - ResponseDTO responseDTO = new ResponseDTO(); - responseDTO.setAuthStatus(false); - authResponseDTO.setResponse(responseDTO); - when(authUtil.authByIdAuthentication(any(), any(), any())).thenReturn(authResponseDTO); - Mockito.when(registrationStatusMapperUtil - .getStatusCode(RegistrationExceptionTypeCode.AUTH_SYSTEM_EXCEPTION)).thenReturn("REPROCESS"); - - MessageDTO messageDto = biometricAuthenticationStage.process(dto); - assertFalse(messageDto.getIsValid()); - assertTrue(messageDto.getInternalError()); - } - - @Test - public void childPacketTest() throws ApisResourceAccessException, JsonProcessingException, io.mosip.kernel.core.exception.IOException, PacketManagerException, IOException { - when(regentity.getRegistrationType()).thenReturn("UPDATE"); - when(utility.getApplicantAge(anyString(),anyString(), any())).thenReturn(2); - MessageDTO messageDto = biometricAuthenticationStage.process(dto); - assertTrue(messageDto.getIsValid()); - } - - @Test - public void inputStreamNullIndividualAuthTest() throws ApisResourceAccessException, InvalidKeySpecException, NoSuchAlgorithmException, BioTypeException, IOException { - - HashMap hashMap = new HashMap(); - hashMap.put("value", "testFile"); - - MessageDTO messageDto = biometricAuthenticationStage.process(dto); - - assertFalse(messageDto.getIsValid()); - assertTrue(messageDto.getInternalError()); - } - - @Test - public void testIOException() throws ApisResourceAccessException, IOException, PacketManagerException, io.mosip.kernel.core.exception.IOException, JsonProcessingException { - - when(utility.getApplicantAge(any(),anyString(), any())).thenThrow(new IOException("IOException")); - Mockito.when(registrationStatusMapperUtil - .getStatusCode(RegistrationExceptionTypeCode.IOEXCEPTION)).thenReturn("ERROR"); - MessageDTO messageDto = biometricAuthenticationStage.process(dto); - assertTrue(messageDto.getInternalError()); - assertFalse(messageDto.getIsValid()); - } - - @Test - public void testApisResourceAccessException() throws ApisResourceAccessException, IOException, PacketManagerException, io.mosip.kernel.core.exception.IOException, JsonProcessingException { - - when(utility.getApplicantAge(anyString(),anyString(), any())) - .thenThrow(new ApisResourceAccessException("ApisResourceAccessException")); - Mockito.when(registrationStatusMapperUtil - .getStatusCode(RegistrationExceptionTypeCode.APIS_RESOURCE_ACCESS_EXCEPTION)).thenReturn("REPROCESS"); - MessageDTO messageDto = biometricAuthenticationStage.process(dto); - assertTrue(messageDto.getInternalError()); - assertTrue(messageDto.getIsValid()); - } - - @Test - public void testException() throws ApisResourceAccessException, IOException, PacketManagerException, io.mosip.kernel.core.exception.IOException, JsonProcessingException { - - when(utility.getApplicantAge(anyString(),anyString(), any())) - .thenThrow( - new ApisResourceAccessException( - "test message")); - Mockito.when(registrationStatusMapperUtil - .getStatusCode(RegistrationExceptionTypeCode.APIS_RESOURCE_ACCESS_EXCEPTION)).thenReturn("REPROCESS"); - MessageDTO messageDto = biometricAuthenticationStage.process(dto); - assertTrue(messageDto.getInternalError()); - assertTrue(messageDto.getIsValid()); - } - - @Test - public void resupdatePacketTest() throws ApisResourceAccessException, IOException, PacketManagerException, JsonProcessingException { - when(regentity.getRegistrationType()).thenReturn("res_update"); - 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); - when(packetManagerService.getBiometricsByMappingJsonKey(any(), any(), any(),any())).thenReturn(biometricRecord); - - MessageDTO messageDto = biometricAuthenticationStage.process(dto); - - assertTrue(messageDto.getIsValid()); - assertFalse(messageDto.getInternalError()); - } - - @Test - public void testNewPacket() throws IOException, - ApisResourceAccessException, InvalidKeySpecException, NoSuchAlgorithmException, BioTypeException, CertificateException { - - AuthResponseDTO authResponseDTO = new AuthResponseDTO(); - ResponseDTO responseDTO = new ResponseDTO(); - responseDTO.setAuthStatus(false); - authResponseDTO.setResponse(responseDTO); - when(regentity.getRegistrationType()).thenReturn("new"); - when(authUtil.authByIdAuthentication(any(), any(), any())).thenReturn(authResponseDTO); - MessageDTO messageDto = biometricAuthenticationStage.process(dto); - - assertTrue(messageDto.getIsValid()); - assertFalse(messageDto.getInternalError()); - } - - @Test - public void deployVerticle() { - - biometricAuthenticationStage.deployVerticle(); - } - @Test - public void testAuthSystemException() throws ApisResourceAccessException, IOException, InvalidKeySpecException, - NoSuchAlgorithmException, BioTypeException, JsonProcessingException, PacketManagerException, CertificateException { - 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); - - when(packetManagerService.getBiometricsByMappingJsonKey(any(), - any(), any(),any())).thenReturn(biometricRecord); - AuthResponseDTO authResponseDTO = new AuthResponseDTO(); - ErrorDTO error=new ErrorDTO(); - error.setErrorCode("IDA-MLC-007"); - error.setErrorMessage("system error from ida"); - - List errors=new ArrayList(); - errors.add(error); - authResponseDTO.setErrors(errors); - when(authUtil.authByIdAuthentication(any(), any(), any())).thenReturn(authResponseDTO); - Mockito.when(registrationStatusMapperUtil - .getStatusCode(RegistrationExceptionTypeCode.AUTH_SYSTEM_EXCEPTION)).thenReturn("REPROCESS"); - when(regentity.getRegistrationType()).thenReturn("UPDATE"); - MessageDTO messageDto = biometricAuthenticationStage.process(dto); - assertTrue(messageDto.getInternalError()); - assertTrue(messageDto.getIsValid()); - } - @Test - public void testAuthFailed() throws ApisResourceAccessException, IOException, InvalidKeySpecException, - NoSuchAlgorithmException, BioTypeException, CertificateException { - AuthResponseDTO authResponseDTO = new AuthResponseDTO(); - ErrorDTO error=new ErrorDTO(); - error.setErrorCode("IDA-MLC-008"); - error.setErrorMessage("biometric didnt match"); - - List errors=new ArrayList(); - errors.add(error); - authResponseDTO.setErrors(errors); - when(authUtil.authByIdAuthentication(any(), any(), any())).thenReturn(authResponseDTO); - /*File idJson = new File(classLoader.getResource("ID2.json").getFile()); - InputStream ip = new FileInputStream(idJson); - *//*String idJsonString = IOUtils.toString(ip, "UTF-8"); - Mockito.when(utility.getDemographicIdentityJSONObject(Mockito.anyString(), Mockito.anyString())) - .thenReturn(JsonUtil.getJSONObject(JsonUtil.objectMapperReadValue(idJsonString, JSONObject.class), - MappingJsonConstants.IDENTITY));*/ - when(regentity.getRegistrationType()).thenReturn("UPDATE"); - MessageDTO messageDto = biometricAuthenticationStage.process(dto); - assertFalse(messageDto.getIsValid()); - assertFalse(messageDto.getInternalError()); - } - - @Test - public void testJsonProcessingException() throws ApisResourceAccessException, IOException, PacketManagerException, io.mosip.kernel.core.exception.IOException, JsonProcessingException { - - when(utility.getApplicantAge(any(),anyString(), any())).thenThrow(new JsonProcessingException("IOException")); - Mockito.when(registrationStatusMapperUtil - .getStatusCode(RegistrationExceptionTypeCode.JSON_PROCESSING_EXCEPTION)).thenReturn("ERROR"); - MessageDTO messageDto = biometricAuthenticationStage.process(dto); - assertTrue(messageDto.getInternalError()); - assertFalse(messageDto.getIsValid()); - } - - @Test - public void testPacketManagerException() throws ApisResourceAccessException, IOException, PacketManagerException, io.mosip.kernel.core.exception.IOException, JsonProcessingException { - - when(utility.getApplicantAge(any(),anyString(), any())).thenThrow(new PacketManagerException("errorcode","IOException")); - Mockito.when(registrationStatusMapperUtil - .getStatusCode(RegistrationExceptionTypeCode.PACKET_MANAGER_EXCEPTION)).thenReturn("REPROCESS"); - MessageDTO messageDto = biometricAuthenticationStage.process(dto); - assertTrue(messageDto.getInternalError()); - assertTrue(messageDto.getIsValid()); - } -} +package io.mosip.registration.processor.biometric.authentication.stage; + +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.io.InputStream; +import java.security.NoSuchAlgorithmException; +import java.security.cert.CertificateException; +import java.security.spec.InvalidKeySpecException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; + +import org.apache.commons.io.IOUtils; +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.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 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.core.util.HMACUtils2; +import io.mosip.kernel.core.util.exception.JsonProcessingException; +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.auth.dto.AuthResponseDTO; +import io.mosip.registration.processor.core.auth.dto.ErrorDTO; +import io.mosip.registration.processor.core.auth.dto.ResponseDTO; +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.exception.ApisResourceAccessException; +import io.mosip.registration.processor.core.exception.BioTypeException; +import io.mosip.registration.processor.core.exception.PacketManagerException; +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.Identity; +import io.mosip.registration.processor.core.packet.dto.masterdata.StatusResponseDto; +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.IdentityIteratorUtil; +import io.mosip.registration.processor.core.util.RegistrationExceptionMapperUtil; +import io.mosip.registration.processor.packet.storage.dto.ApplicantInfoDto; +import io.mosip.registration.processor.packet.storage.utils.AuthUtil; +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.status.dto.InternalRegistrationStatusDto; +import io.mosip.registration.processor.status.dto.RegistrationStatusDto; +import io.mosip.registration.processor.status.dto.SyncRegistrationDto; +import io.mosip.registration.processor.status.dto.SyncResponseDto; +import io.mosip.registration.processor.status.entity.SyncRegistrationEntity; +import io.mosip.registration.processor.status.repositary.SyncRegistrationRepository; +import io.mosip.registration.processor.status.service.RegistrationStatusService; +import io.mosip.registration.processor.status.service.SyncRegistrationService; +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 BiometricAuthenticationStageTest { + + /** The input stream. */ + @Mock + private InputStream inputStream; + + + + /** The registration status service. */ + @Mock + RegistrationStatusService registrationStatusService; + + /** The packet info manager. */ + @Mock + private PacketInfoManager packetInfoManager; + + @Mock + private AuthUtil authUtil; + + @Mock + InternalRegistrationStatusDto registrationStatusDto; + + @Mock + private RegistrationProcessorRestClientService restClientService; + + @Mock + private IdentityIteratorUtil identityIteratorUtil; + + /** The dto. */ + MessageDTO dto = new MessageDTO(); + + @Mock + private PriorityBasedPacketManagerService packetManagerService; + + @Mock + private SyncRegistrationService syncRegistrationservice; + + /** The BiometricAuthenticationStage stage. */ + @InjectMocks + private BiometricAuthenticationStage biometricAuthenticationStage = new BiometricAuthenticationStage() { + @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 consumeAndSend(MosipEventBus mosipEventBus, MessageBusAddress fromAddress, + MessageBusAddress toAddress, long messageExpiryTimeLimit) { + } + + @Override + public Integer getPort() { + return 8080; + } + }; + + /** The audit log request builder. */ + @Mock + private AuditLogRequestBuilder auditLogRequestBuilder; + + @Mock + private Environment env; + + + + + /** The dto. */ + InternalRegistrationStatusDto statusDto; + /** The list. */ + List list; + + /** The list appender. */ + private ListAppender listAppender; + + @Mock + private RegistrationProcessorRestClientService registrationProcessorRestService; + + @Mock + private Utilities utility; + + @Mock + ObjectMapper mapIdentityJsonStringToObject; + + @Mock + private SyncRegistrationRepository registrationRepositary; + + StatusResponseDto statusResponseDto; + + @Mock + LogDescription description; + + @Mock + RegistrationExceptionMapperUtil registrationStatusMapperUtil; + + private SyncRegistrationEntity regentity = Mockito.mock(SyncRegistrationEntity.class); + + /** + * Sets the up. + * + * @throws Exception + * the exception + */ + @Before + public void setUp() throws Exception { + ReflectionTestUtils.setField(biometricAuthenticationStage, "workerPoolSize", 10); + ReflectionTestUtils.setField(biometricAuthenticationStage, "messageExpiryTimeLimit", Long.valueOf(0)); + ReflectionTestUtils.setField(biometricAuthenticationStage, "clusterManagerUrl", "/dummyPath"); + ReflectionTestUtils.setField(biometricAuthenticationStage, "ageLimit", "5"); + + + when(utility.getGetRegProcessorDemographicIdentity()).thenReturn("identity"); + + + list = new ArrayList(); + + listAppender = new ListAppender<>(); + + dto.setRid("2018701130000410092018110735"); + dto.setReg_type("UPDATE"); + + MockitoAnnotations.initMocks(this); + + + ResponseWrapper responseWrapper = new ResponseWrapper<>(); + Mockito.doReturn(responseWrapper).when(auditLogRequestBuilder).createAuditRequestBuilder( + "test case description", EventId.RPR_405.toString(), EventName.UPDATE.toString(), + EventType.BUSINESS.toString(), "1234testcase", ApiName.AUDIT); + + + + InternalRegistrationStatusDto registrationStatusDto = new InternalRegistrationStatusDto(); + registrationStatusDto = new InternalRegistrationStatusDto(); + registrationStatusDto.setRegistrationId("2018701130000410092018110735"); + registrationStatusDto.setStatusCode(""); + registrationStatusDto.setRegistrationType("UPDATE"); + listAppender.start(); + list.add(registrationStatusDto); + when(registrationStatusService.getByStatus(anyString())).thenReturn(list); + when(registrationStatusService.getRegistrationStatus(anyString(), any(), any(), any())).thenReturn(registrationStatusDto); + Mockito.doNothing().when(registrationStatusService).updateRegistrationStatus(any(), any(), any()); + + when(identityIteratorUtil.getFieldValue(any(), any())).thenReturn("UPDATE"); + + + Mockito.doNothing().when(description).setMessage(any()); + when(registrationStatusMapperUtil.getStatusCode(any())).thenReturn(""); + + + statusResponseDto = new StatusResponseDto(); + statusResponseDto.setStatus("VALID"); + when(registrationProcessorRestService.getApi(any(), any(), anyString(), any(), any())) + .thenReturn(statusResponseDto); + + JSONObject jsonObject = Mockito.mock(JSONObject.class); + when(utility.getUIn(anyString(), anyString(), any())).thenReturn("12345678"); + when(utility.retrieveIdrepoJson(any())).thenReturn(jsonObject); + FieldValue fieldValue = new FieldValue(); + FieldValue fieldValue1 = new FieldValue(); + fieldValue1.setLabel("authenticationBiometricFileName"); + fieldValue1.setValue("biometricTestFileName"); + fieldValue.setLabel("registrationType"); + fieldValue.setValue("update"); + List metadata = new ArrayList<>(); + metadata.add(fieldValue); + metadata.add(fieldValue1); + + + when(utility.getDefaultSource(any(), any())).thenReturn("reg-client"); + when(utility.getApplicantAge(anyString(),anyString(), any())).thenReturn(21); + + regentity.setRegistrationType("update"); + when(syncRegistrationservice.findByWorkflowInstanceId(any())).thenReturn(regentity); + + AuthResponseDTO authResponseDTO = new AuthResponseDTO(); + ResponseDTO responseDTO = new ResponseDTO(); + responseDTO.setAuthStatus(true); + authResponseDTO.setResponse(responseDTO); + when(authUtil.authByIdAuthentication(any(), any(), any())).thenReturn(authResponseDTO); + + 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); + + when(packetManagerService.getBiometricsByMappingJsonKey(any(), any(), any(), any())).thenReturn(biometricRecord); + + + } + + @Test + public void biometricAuthenticationSuccessTest() throws ApisResourceAccessException, IOException, PacketManagerException, JsonProcessingException { + when(regentity.getRegistrationType()).thenReturn("UPDATE"); + 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); + + when(packetManagerService.getBiometricsByMappingJsonKey(any(), + any(), any(),any())).thenReturn(biometricRecord); + + MessageDTO messageDto = biometricAuthenticationStage.process(dto); + assertTrue(messageDto.getIsValid()); + assertFalse(messageDto.getInternalError()); + } + + @Test + public void biometricAuthenticationBiometricNullTest() throws ApisResourceAccessException, IOException, PacketManagerException, JsonProcessingException { + when(regentity.getRegistrationType()).thenReturn("UPDATE"); + + String individualBiometrics="{\"format\" : \"cbeff\",\"version\" : 1.0,\"value\" : \"individualBiometrics_bio_CBEFF\"}"; + when(packetManagerService.getFieldByMappingJsonKey(any(), + any(), any(),any())).thenReturn(individualBiometrics); + + when(packetManagerService.getBiometricsByMappingJsonKey(any(), + any(), any(),any())).thenReturn(null); + + MessageDTO messageDto = biometricAuthenticationStage.process(dto); + assertFalse(messageDto.getIsValid()); + assertFalse(messageDto.getInternalError()); + } + + @Test + public void individualBiometricAuthenticationBiometricNullTest() throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { + when(regentity.getRegistrationType()).thenReturn("UPDATE"); + + when(packetManagerService.getBiometricsByMappingJsonKey(any(), + any(), any(),any())).thenReturn(null); + + MessageDTO messageDto = biometricAuthenticationStage.process(dto); + assertFalse(messageDto.getIsValid()); + assertFalse(messageDto.getInternalError()); + } + + @Test + public void biometricAuthenticationIndividualBiometricsValueNullTest() throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { + when(regentity.getRegistrationType()).thenReturn("UPDATE"); + + String individualBiometrics="{\"format\" : \"cbeff\",\"version\" : 1.0,\"value\" : null}"; + when(packetManagerService.getFieldByMappingJsonKey(any(), + any(), any(),any())).thenReturn(individualBiometrics); + + MessageDTO messageDto = biometricAuthenticationStage.process(dto); + assertTrue(messageDto.getIsValid()); + assertFalse(messageDto.getInternalError()); + } + + @Test + public void IDAuthFailureTest() throws IOException, ApisResourceAccessException, InvalidKeySpecException, NoSuchAlgorithmException, BioTypeException, CertificateException { + AuthResponseDTO authResponseDTO = new AuthResponseDTO(); + ResponseDTO responseDTO = new ResponseDTO(); + responseDTO.setAuthStatus(false); + authResponseDTO.setResponse(responseDTO); + when(authUtil.authByIdAuthentication(any(), any(), any())).thenReturn(authResponseDTO); + Mockito.when(registrationStatusMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.AUTH_SYSTEM_EXCEPTION)).thenReturn("REPROCESS"); + + MessageDTO messageDto = biometricAuthenticationStage.process(dto); + assertFalse(messageDto.getIsValid()); + assertTrue(messageDto.getInternalError()); + } + + @Test + public void childPacketTest() throws ApisResourceAccessException, JsonProcessingException, io.mosip.kernel.core.exception.IOException, PacketManagerException, IOException { + when(regentity.getRegistrationType()).thenReturn("UPDATE"); + when(utility.getApplicantAge(anyString(),anyString(), any())).thenReturn(2); + MessageDTO messageDto = biometricAuthenticationStage.process(dto); + assertTrue(messageDto.getIsValid()); + } + + @Test + public void inputStreamNullIndividualAuthTest() throws ApisResourceAccessException, InvalidKeySpecException, NoSuchAlgorithmException, BioTypeException, IOException { + + HashMap hashMap = new HashMap(); + hashMap.put("value", "testFile"); + + MessageDTO messageDto = biometricAuthenticationStage.process(dto); + + assertFalse(messageDto.getIsValid()); + assertTrue(messageDto.getInternalError()); + } + + @Test + public void testIOException() throws ApisResourceAccessException, IOException, PacketManagerException, io.mosip.kernel.core.exception.IOException, JsonProcessingException { + + when(utility.getApplicantAge(any(),anyString(), any())).thenThrow(new IOException("IOException")); + Mockito.when(registrationStatusMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.IOEXCEPTION)).thenReturn("ERROR"); + MessageDTO messageDto = biometricAuthenticationStage.process(dto); + assertTrue(messageDto.getInternalError()); + assertFalse(messageDto.getIsValid()); + } + + @Test + public void testApisResourceAccessException() throws ApisResourceAccessException, IOException, PacketManagerException, io.mosip.kernel.core.exception.IOException, JsonProcessingException { + + when(utility.getApplicantAge(anyString(),anyString(), any())) + .thenThrow(new ApisResourceAccessException("ApisResourceAccessException")); + Mockito.when(registrationStatusMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.APIS_RESOURCE_ACCESS_EXCEPTION)).thenReturn("REPROCESS"); + MessageDTO messageDto = biometricAuthenticationStage.process(dto); + assertTrue(messageDto.getInternalError()); + assertTrue(messageDto.getIsValid()); + } + + @Test + public void testException() throws ApisResourceAccessException, IOException, PacketManagerException, io.mosip.kernel.core.exception.IOException, JsonProcessingException { + + when(utility.getApplicantAge(anyString(),anyString(), any())) + .thenThrow( + new ApisResourceAccessException( + "test message")); + Mockito.when(registrationStatusMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.APIS_RESOURCE_ACCESS_EXCEPTION)).thenReturn("REPROCESS"); + MessageDTO messageDto = biometricAuthenticationStage.process(dto); + assertTrue(messageDto.getInternalError()); + assertTrue(messageDto.getIsValid()); + } + + @Test + public void resupdatePacketTest() throws ApisResourceAccessException, IOException, PacketManagerException, JsonProcessingException { + when(regentity.getRegistrationType()).thenReturn("res_update"); + 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); + when(packetManagerService.getBiometricsByMappingJsonKey(any(), any(), any(),any())).thenReturn(biometricRecord); + + MessageDTO messageDto = biometricAuthenticationStage.process(dto); + + assertTrue(messageDto.getIsValid()); + assertFalse(messageDto.getInternalError()); + } + + @Test + public void testNewPacket() throws IOException, + ApisResourceAccessException, InvalidKeySpecException, NoSuchAlgorithmException, BioTypeException, CertificateException { + + AuthResponseDTO authResponseDTO = new AuthResponseDTO(); + ResponseDTO responseDTO = new ResponseDTO(); + responseDTO.setAuthStatus(false); + authResponseDTO.setResponse(responseDTO); + when(regentity.getRegistrationType()).thenReturn("new"); + when(authUtil.authByIdAuthentication(any(), any(), any())).thenReturn(authResponseDTO); + MessageDTO messageDto = biometricAuthenticationStage.process(dto); + + assertTrue(messageDto.getIsValid()); + assertFalse(messageDto.getInternalError()); + } + + @Test + public void deployVerticle() { + + biometricAuthenticationStage.deployVerticle(); + } + @Test + public void testAuthSystemException() throws ApisResourceAccessException, IOException, InvalidKeySpecException, + NoSuchAlgorithmException, BioTypeException, JsonProcessingException, PacketManagerException, CertificateException { + 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); + + when(packetManagerService.getBiometricsByMappingJsonKey(any(), + any(), any(),any())).thenReturn(biometricRecord); + AuthResponseDTO authResponseDTO = new AuthResponseDTO(); + ErrorDTO error=new ErrorDTO(); + error.setErrorCode("IDA-MLC-007"); + error.setErrorMessage("system error from ida"); + + List errors=new ArrayList(); + errors.add(error); + authResponseDTO.setErrors(errors); + when(authUtil.authByIdAuthentication(any(), any(), any())).thenReturn(authResponseDTO); + Mockito.when(registrationStatusMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.AUTH_SYSTEM_EXCEPTION)).thenReturn("REPROCESS"); + when(regentity.getRegistrationType()).thenReturn("UPDATE"); + MessageDTO messageDto = biometricAuthenticationStage.process(dto); + assertTrue(messageDto.getInternalError()); + assertTrue(messageDto.getIsValid()); + } + @Test + public void testAuthFailed() throws ApisResourceAccessException, IOException, InvalidKeySpecException, + NoSuchAlgorithmException, BioTypeException, CertificateException { + AuthResponseDTO authResponseDTO = new AuthResponseDTO(); + ErrorDTO error=new ErrorDTO(); + error.setErrorCode("IDA-MLC-008"); + error.setErrorMessage("biometric didnt match"); + + List errors=new ArrayList(); + errors.add(error); + authResponseDTO.setErrors(errors); + when(authUtil.authByIdAuthentication(any(), any(), any())).thenReturn(authResponseDTO); + /*File idJson = new File(classLoader.getResource("ID2.json").getFile()); + InputStream ip = new FileInputStream(idJson); + *//*String idJsonString = IOUtils.toString(ip, "UTF-8"); + Mockito.when(utility.getDemographicIdentityJSONObject(Mockito.anyString(), Mockito.anyString())) + .thenReturn(JsonUtil.getJSONObject(JsonUtil.objectMapperReadValue(idJsonString, JSONObject.class), + MappingJsonConstants.IDENTITY));*/ + when(regentity.getRegistrationType()).thenReturn("UPDATE"); + MessageDTO messageDto = biometricAuthenticationStage.process(dto); + assertFalse(messageDto.getIsValid()); + assertFalse(messageDto.getInternalError()); + } + + @Test + public void testJsonProcessingException() throws ApisResourceAccessException, IOException, PacketManagerException, io.mosip.kernel.core.exception.IOException, JsonProcessingException { + + when(utility.getApplicantAge(any(),anyString(), any())).thenThrow(new JsonProcessingException("IOException")); + Mockito.when(registrationStatusMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.JSON_PROCESSING_EXCEPTION)).thenReturn("ERROR"); + MessageDTO messageDto = biometricAuthenticationStage.process(dto); + assertTrue(messageDto.getInternalError()); + assertFalse(messageDto.getIsValid()); + } + + @Test + public void testPacketManagerException() throws ApisResourceAccessException, IOException, PacketManagerException, io.mosip.kernel.core.exception.IOException, JsonProcessingException { + + when(utility.getApplicantAge(any(),anyString(), any())).thenThrow(new PacketManagerException("errorcode","IOException")); + Mockito.when(registrationStatusMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.PACKET_MANAGER_EXCEPTION)).thenReturn("REPROCESS"); + MessageDTO messageDto = biometricAuthenticationStage.process(dto); + assertTrue(messageDto.getInternalError()); + assertTrue(messageDto.getIsValid()); + } +} 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 3606a1d0cd1..c0d91296e82 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 @@ -26,6 +26,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; 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; @@ -125,6 +126,18 @@ public void consumeAndSend(MessageBusAddress fromAddress, MessageBusAddress toAd 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 + + } }; } diff --git a/registration-processor/core-processor/registration-processor-demo-dedupe-stage/src/test/java/io/mosip/registrationprocessor/stages/demodedupe/DemoDedupeStageTest.java b/registration-processor/core-processor/registration-processor-demo-dedupe-stage/src/test/java/io/mosip/registrationprocessor/stages/demodedupe/DemoDedupeStageTest.java index 8b8e18fbce0..1d4f2cc5360 100644 --- a/registration-processor/core-processor/registration-processor-demo-dedupe-stage/src/test/java/io/mosip/registrationprocessor/stages/demodedupe/DemoDedupeStageTest.java +++ b/registration-processor/core-processor/registration-processor-demo-dedupe-stage/src/test/java/io/mosip/registrationprocessor/stages/demodedupe/DemoDedupeStageTest.java @@ -13,6 +13,7 @@ import org.springframework.test.util.ReflectionTestUtils; 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; @@ -69,6 +70,18 @@ public void consumeAndSend(MessageBusAddress fromAddress, MessageBusAddress toAd 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 + + } }; } diff --git a/registration-processor/core-processor/registration-processor-finalization-stage/src/test/java/io/mosip/registration/processor/stages/finalization/stage/tests/FinalizationStageTest.java b/registration-processor/core-processor/registration-processor-finalization-stage/src/test/java/io/mosip/registration/processor/stages/finalization/stage/tests/FinalizationStageTest.java index 43b608c8810..0d964bccb57 100644 --- a/registration-processor/core-processor/registration-processor-finalization-stage/src/test/java/io/mosip/registration/processor/stages/finalization/stage/tests/FinalizationStageTest.java +++ b/registration-processor/core-processor/registration-processor-finalization-stage/src/test/java/io/mosip/registration/processor/stages/finalization/stage/tests/FinalizationStageTest.java @@ -20,6 +20,7 @@ import org.springframework.test.util.ReflectionTestUtils; 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; @@ -106,6 +107,18 @@ public void consumeAndSend(MessageBusAddress fromAddress, MessageBusAddress toAd 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 + + } }; } 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 52c7df763dc..89e48e9bb0b 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,2326 +1,2343 @@ -package io.mosip.registration.processor.stages.uigenerator; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyDouble; -import static org.mockito.ArgumentMatchers.anyList; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.when; - -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.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -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 com.google.gson.Gson; - -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.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.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, Gson.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 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"); - - 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 { - - 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 { - 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 { - 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 { - 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 { - - 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 { - - 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 { - - 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 { - 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 { - 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 updateTestSuccess() throws ApisResourceAccessException, IOException, JsonProcessingException, PacketManagerException, JSONException, IdrepoDraftException { - 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 { - 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 { - 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 { - 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 { - 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 { - 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 { - 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()); - } - +package io.mosip.registration.processor.stages.uigenerator; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyDouble; +import static org.mockito.ArgumentMatchers.anyList; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.when; + +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.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +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.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.mockito.Spy; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.core.classloader.annotations.PrepareForTest; +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 com.google.gson.Gson; + +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.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, Gson.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) { + // TODO Auto-generated method stub + + } + + @Override + public void senderHealthCheck(Handler eventHandler, String address) { + // TODO Auto-generated method stub + + } + }; + } + + @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"); + + 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 { + + 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 { + 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 { + 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 { + 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 { + + 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 { + + 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 { + + 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 { + 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 { + 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 updateTestSuccess() throws ApisResourceAccessException, IOException, JsonProcessingException, PacketManagerException, JSONException, IdrepoDraftException { + 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 { + 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 { + 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 { + 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 { + 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 { + 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 { + 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()); + } + } \ No newline at end of file diff --git a/registration-processor/post-processor/registration-processor-message-sender-stage/src/test/java/io/mosip/registration/processor/message/sender/stage/test/MessageSenderStageTest.java b/registration-processor/post-processor/registration-processor-message-sender-stage/src/test/java/io/mosip/registration/processor/message/sender/stage/test/MessageSenderStageTest.java index d80f6d57f81..e359b073402 100644 --- a/registration-processor/post-processor/registration-processor-message-sender-stage/src/test/java/io/mosip/registration/processor/message/sender/stage/test/MessageSenderStageTest.java +++ b/registration-processor/post-processor/registration-processor-message-sender-stage/src/test/java/io/mosip/registration/processor/message/sender/stage/test/MessageSenderStageTest.java @@ -1,920 +1,933 @@ -package io.mosip.registration.processor.message.sender.stage.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 java.io.InputStream; -import java.util.ArrayList; -import java.util.List; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.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 org.springframework.web.multipart.MultipartFile; - -import com.fasterxml.jackson.databind.ObjectMapper; - -import io.mosip.kernel.core.fsadapter.exception.FSAdapterException; -import io.mosip.registration.processor.core.abstractverticle.EventDTO; -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.RegistrationTransactionStatusCode; -import io.mosip.registration.processor.core.code.RegistrationTransactionTypeCode; -import io.mosip.registration.processor.core.exception.ApisResourceAccessException; -import io.mosip.registration.processor.core.http.ResponseWrapper; -import io.mosip.registration.processor.core.logger.LogDescription; -import io.mosip.registration.processor.core.notification.template.generator.dto.ResponseDto; -import io.mosip.registration.processor.core.notification.template.generator.dto.SmsResponseDto; -import io.mosip.registration.processor.core.notification.template.generator.dto.TemplateDto; -import io.mosip.registration.processor.core.notification.template.generator.dto.TemplateResponseDto; -import io.mosip.registration.processor.core.packet.dto.FieldValue; -import io.mosip.registration.processor.core.packet.dto.Identity; -import io.mosip.registration.processor.core.packet.dto.PacketMetaInfo; -import io.mosip.registration.processor.core.spi.eventbus.EventHandler; -import io.mosip.registration.processor.core.spi.message.sender.MessageNotificationService; -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.message.sender.dto.MessageSenderDto; -import io.mosip.registration.processor.message.sender.exception.EmailIdNotFoundException; -import io.mosip.registration.processor.message.sender.exception.PhoneNumberNotFoundException; -import io.mosip.registration.processor.message.sender.stage.MessageSenderStage; -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.dto.SyncRegistrationDto; -import io.mosip.registration.processor.status.dto.SyncResponseDto; -import io.mosip.registration.processor.status.dto.TransactionDto; -import io.mosip.registration.processor.status.entity.SyncRegistrationEntity; -import io.mosip.registration.processor.status.service.RegistrationStatusService; -import io.mosip.registration.processor.status.service.SyncRegistrationService; -import io.mosip.registration.processor.status.service.TransactionService; -import io.vertx.core.AsyncResult; -import io.vertx.core.Handler; -import io.vertx.core.Vertx; - -@RunWith(PowerMockRunner.class) -@PrepareForTest({ Utilities.class, JsonUtil.class }) -@PowerMockIgnore({ "com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*","javax.management.*", "javax.net.ssl.*" }) -public class MessageSenderStageTest { - - @Mock - private MessageNotificationService service; - - @Mock - private ObjectMapper mapper; - - @Mock - private RegistrationProcessorRestClientService restClientService; - - @Mock - private RegistrationStatusService registrationStatusService; - - @Mock - private TransactionService transcationStatusService; - - @Mock - private InternalRegistrationStatusDto registrationStatusDto; - - @Mock - private SyncRegistrationService syncRegistrationservice; - - - @Mock - private AuditLogRequestBuilder auditLogRequestBuilder; - - - /** The packet meta info. */ - private PacketMetaInfo packetMetaInfo = new PacketMetaInfo(); - - /** The identity. */ - Identity identity = new Identity(); - - /** The input stream. */ - @Mock - private InputStream inputStream; - - @Mock - private RegistrationExceptionMapperUtil registrationExceptionMapperUtil; - - @Mock - private LogDescription description; - - @Mock - private RegistrationExceptionMapperUtil registrationStatusMapperUtil; - - @Mock - Environment env; - - MessageSenderDto messageSenderDto = Mockito.mock(MessageSenderDto.class); - - private SmsResponseDto smsResponseDto = Mockito.mock(SmsResponseDto.class); - - private ResponseDto responseDto = Mockito.mock(ResponseDto.class); - - private SyncRegistrationEntity regentity = Mockito.mock(SyncRegistrationEntity.class); - - @InjectMocks - private MessageSenderStage stage = new MessageSenderStage() { - @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 consumeAndSend(MosipEventBus mosipEventBus, MessageBusAddress fromAddress, - MessageBusAddress toAddress, long messageExpiryTimeLimit) { - } - }; - - @Before - public void setup() throws Exception { - ReflectionTestUtils.setField(stage, "workerPoolSize", 10); - ReflectionTestUtils.setField(stage, "messageExpiryTimeLimit", Long.valueOf(0)); - ReflectionTestUtils.setField(stage, "clusterManagerUrl", "/dummyPath"); - ReflectionTestUtils.setField(stage, "notificationTypes", "SMS|EMAIL"); - ReflectionTestUtils.setField(stage, "notificationEmails", "abc@gmail.com"); - - Mockito.doNothing().when(registrationStatusDto).setStatusCode(any()); - Mockito.doNothing().when(registrationStatusDto).setStatusComment(any()); - Mockito.when(registrationStatusDto.getRegistrationType()).thenReturn("NEW"); - Mockito.doNothing().when(registrationStatusService).updateRegistrationStatus(any(), any(), any()); - Mockito.when(transcationStatusService.addRegistrationTransaction(any())).thenReturn(null); - Mockito.doNothing().when(registrationStatusDto).setLatestTransactionTypeCode(any()); - Mockito.doNothing().when(registrationStatusDto).setRegistrationStageName(any()); - Mockito.doNothing().when(registrationStatusDto).setLatestTransactionStatusCode(any()); - Mockito.doNothing().when(description).setMessage(any()); - - Mockito.doNothing().when(messageSenderDto).setEmailTemplateCode(any()); - Mockito.doNothing().when(messageSenderDto).setSmsTemplateCode(any()); - Mockito.doNothing().when(messageSenderDto).setIdType(any()); - Mockito.doNothing().when(messageSenderDto).setSubjectCode(any()); - Mockito.doNothing().when(messageSenderDto).setTemplateAvailable(any(Boolean.class)); - - Mockito.when(service.sendSmsNotification(any(), any(), any(), any(), any(), any())).thenReturn(smsResponseDto); - Mockito.when(service.sendEmailNotification(any(), any(), any(), any(), any(), any(), any(), any(), any())) - .thenReturn(responseDto); - - Mockito.when(registrationStatusMapperUtil.getStatusCode(any())).thenReturn("ERROR"); - Mockito.when(registrationExceptionMapperUtil.getStatusCode(any())).thenReturn("ERROR"); - - - FieldValue registrationType = new FieldValue(); - registrationType.setLabel("registrationType"); - registrationType.setValue("New"); - List fieldValueList = new ArrayList<>(); - fieldValueList.add(registrationType); - identity.setMetaData(fieldValueList); - packetMetaInfo.setIdentity(identity); - - PowerMockito.mockStatic(JsonUtil.class); - - regentity.setRegistrationType("NEW"); - Mockito.when(syncRegistrationservice.findByWorkflowInstanceId(any())).thenReturn(regentity); - } - - @Test - public void testDeployVerticle() { - stage.deployVerticle(); - } - - @SuppressWarnings("unchecked") - @Test - public void testMessageSentUINGenerated() throws Exception { - ResponseWrapper responseWrapper = new ResponseWrapper<>(); - TemplateResponseDto templateResponseDto = new TemplateResponseDto(); - - TemplateDto templateDto = new TemplateDto(); - TemplateDto templateDto1 = new TemplateDto(); - Mockito.when(env.getProperty(any())).thenReturn("RPR_UIN_GEN_SMS").thenReturn("RPR_UIN_GEN_EMAIL") - .thenReturn("RPR_UIN_GEN_EMAIL_SUB"); - templateDto.setTemplateTypeCode("RPR_UIN_GEN_SMS"); - List list = new ArrayList(); - list.add(templateDto); - templateDto1.setTemplateTypeCode("RPR_UIN_GEN_EMAIL"); - list.add(templateDto1); - templateResponseDto.setTemplates(list); - String s = templateResponseDto.toString(); - responseWrapper.setResponse(templateResponseDto); - responseWrapper.setErrors(null); - Mockito.when(restClientService.getApi(any(), any(), anyString(), any(), any())).thenReturn(responseWrapper); - Mockito.when(mapper.writeValueAsString(any())).thenReturn(s); - Mockito.when(mapper.readValue(anyString(), any(Class.class))).thenReturn(templateResponseDto); - Mockito.when(registrationStatusService.getRegistrationStatus(any(),any(),any(), any())).thenReturn(registrationStatusDto); - Mockito.when(registrationStatusDto.getStatusCode()).thenReturn(RegistrationStatusCode.PROCESSED.name()); - Mockito.when(registrationStatusDto.getLatestTransactionTypeCode()) - .thenReturn(RegistrationTransactionTypeCode.UIN_GENERATOR.name()); - Mockito.when(registrationStatusDto.getLatestTransactionStatusCode()) - .thenReturn(RegistrationTransactionStatusCode.PROCESSED.name()); - Mockito.doReturn("success").when(smsResponseDto).getStatus(); - Mockito.doReturn("success").when(responseDto).getStatus(); - - MessageDTO dto = new MessageDTO(); - dto.setRid("85425022110000120190117110505"); - MessageDTO result = stage.process(dto); - assertTrue(result.getIsValid()); - } - - @SuppressWarnings("unchecked") - @Test - public void testMessageSentUINUpdate() throws Exception { - ResponseWrapper responseWrapper = new ResponseWrapper<>(); - TemplateResponseDto templateResponseDto = new TemplateResponseDto(); - - TemplateDto templateDto = new TemplateDto(); - TemplateDto templateDto1 = new TemplateDto(); - Mockito.when(env.getProperty(any())).thenReturn("RPR_UIN_UPD_SMS").thenReturn("RPR_UIN_UPD_EMAIL") - .thenReturn("RPR_UIN_UPD_EMAIL_SUB"); - templateDto.setTemplateTypeCode("RPR_UIN_UPD_SMS"); - List list = new ArrayList(); - list.add(templateDto); - templateDto1.setTemplateTypeCode("RPR_UIN_UPD_EMAIL"); - list.add(templateDto1); - templateResponseDto.setTemplates(list); - String s = templateResponseDto.toString(); - responseWrapper.setResponse(templateResponseDto); - responseWrapper.setErrors(null); - Mockito.when(restClientService.getApi(any(), any(), anyString(), any(), any())).thenReturn(responseWrapper); - Mockito.when(mapper.writeValueAsString(any())).thenReturn(s); - Mockito.when(mapper.readValue(anyString(), any(Class.class))).thenReturn(templateResponseDto); - - Mockito.when(registrationStatusService.getRegistrationStatus(any(),any(),any(), any())).thenReturn(registrationStatusDto); - - Mockito.when(registrationStatusDto.getStatusCode()).thenReturn(RegistrationStatusCode.PROCESSED.name()); - Mockito.when(registrationStatusDto.getLatestTransactionTypeCode()) - .thenReturn(RegistrationTransactionTypeCode.UIN_GENERATOR.name()); - Mockito.when(registrationStatusDto.getLatestTransactionStatusCode()) - .thenReturn(RegistrationTransactionStatusCode.PROCESSED.name()); - - Mockito.when(smsResponseDto.getStatus()).thenReturn("success"); - Mockito.when(responseDto.getStatus()).thenReturn("success"); - Mockito.when(registrationStatusDto.getRegistrationType()).thenReturn("UPDATE"); - Mockito.when(regentity.getRegistrationType()).thenReturn("UPDATE"); - MessageDTO dto = new MessageDTO(); - dto.setRid("85425022110000120190117110505"); - MessageDTO result = stage.process(dto); - assertTrue(result.getIsValid()); - } - - @SuppressWarnings("unchecked") - @Test - public void testMessageSentUINUpdatewithActivatedUIN() throws Exception { - ResponseWrapper responseWrapper = new ResponseWrapper<>(); - TemplateResponseDto templateResponseDto = new TemplateResponseDto(); - - TemplateDto templateDto = new TemplateDto(); - TemplateDto templateDto1 = new TemplateDto(); - Mockito.when(env.getProperty(any())).thenReturn("RPR_UIN_REAC_SMS").thenReturn("RPR_UIN_REAC_EMAIL") - .thenReturn("RPR_UIN_REAC_EMAIL_SUB"); - templateDto.setTemplateTypeCode("RPR_UIN_REAC_SMS"); - List list = new ArrayList(); - list.add(templateDto); - templateDto1.setTemplateTypeCode("RPR_UIN_REAC_EMAIL"); - list.add(templateDto1); - templateResponseDto.setTemplates(list); - String s = templateResponseDto.toString(); - responseWrapper.setResponse(templateResponseDto); - responseWrapper.setErrors(null); - Mockito.when(restClientService.getApi(any(), any(), anyString(), any(), any())).thenReturn(responseWrapper); - Mockito.when(mapper.writeValueAsString(any())).thenReturn(s); - Mockito.when(mapper.readValue(anyString(), any(Class.class))).thenReturn(templateResponseDto); - Mockito.when(registrationStatusService.getRegistrationStatus(any(),any(),any(), any())).thenReturn(registrationStatusDto); - Mockito.when(registrationStatusDto.getRegistrationType()).thenReturn("ACTIVATED"); - Mockito.when(regentity.getRegistrationType()).thenReturn("ACTIVATED"); - Mockito.when(registrationStatusDto.getStatusCode()).thenReturn(RegistrationStatusCode.PROCESSED.name()); - Mockito.when(registrationStatusDto.getLatestTransactionTypeCode()) - .thenReturn(RegistrationTransactionTypeCode.UIN_GENERATOR.name()); - Mockito.when(registrationStatusDto.getLatestTransactionStatusCode()) - .thenReturn(RegistrationTransactionStatusCode.PROCESSED.name()); - Mockito.when(smsResponseDto.getStatus()).thenReturn("success"); - Mockito.when(responseDto.getStatus()).thenReturn("success"); - - FieldValue registrationType = new FieldValue(); - registrationType.setLabel("registrationType"); - registrationType.setValue("ACTIVATED"); - List fieldValueList = new ArrayList<>(); - fieldValueList.add(registrationType); - identity.setMetaData(fieldValueList); - packetMetaInfo.setIdentity(identity); - - PowerMockito.mockStatic(JsonUtil.class); - PowerMockito.when(JsonUtil.class, "inputStreamtoJavaObject", inputStream, PacketMetaInfo.class) - .thenReturn(packetMetaInfo); - - MessageDTO dto = new MessageDTO(); - dto.setRid("85425022110000120190117110505"); - MessageDTO result = stage.process(dto); - assertTrue(result.getIsValid()); - } - - @SuppressWarnings("unchecked") - @Test - public void testMessageSentUINUpdatewithDeactivatedUIN() throws Exception { - ResponseWrapper responseWrapper = new ResponseWrapper<>(); - TemplateResponseDto templateResponseDto = new TemplateResponseDto(); - - TemplateDto templateDto = new TemplateDto(); - TemplateDto templateDto1 = new TemplateDto(); - Mockito.when(env.getProperty(any())).thenReturn("RPR_UIN_DEAC_SMS").thenReturn("RPR_UIN_DEAC_EMAIL") - .thenReturn("RPR_UIN_DEAC_EMAIL_SUB"); - templateDto.setTemplateTypeCode("RPR_UIN_DEAC_SMS"); - List list = new ArrayList(); - list.add(templateDto); - templateDto1.setTemplateTypeCode("RPR_UIN_DEAC_EMAIL"); - list.add(templateDto1); - templateResponseDto.setTemplates(list); - String s = templateResponseDto.toString(); - responseWrapper.setResponse(templateResponseDto); - responseWrapper.setErrors(null); - Mockito.when(restClientService.getApi(any(), any(), anyString(), any(), any())).thenReturn(responseWrapper); - Mockito.when(mapper.writeValueAsString(any())).thenReturn(s); - Mockito.when(mapper.readValue(anyString(), any(Class.class))).thenReturn(templateResponseDto); - - Mockito.when(registrationStatusService.getRegistrationStatus(any(),any(),any(), any())).thenReturn(registrationStatusDto); - // Mockito.when(registrationStatusDto.getStatusCode()).thenReturn(RegistrationStatusCode.PACKET_UIN_UPDATION_SUCCESS.name()); - Mockito.when(registrationStatusDto.getRegistrationType()).thenReturn("DEACTIVATED"); - Mockito.when(regentity.getRegistrationType()).thenReturn("DEACTIVATED"); - Mockito.when(registrationStatusDto.getStatusCode()).thenReturn(RegistrationStatusCode.PROCESSED.name()); - Mockito.when(registrationStatusDto.getLatestTransactionTypeCode()) - .thenReturn(RegistrationTransactionTypeCode.UIN_GENERATOR.name()); - Mockito.when(registrationStatusDto.getLatestTransactionStatusCode()) - .thenReturn(RegistrationTransactionStatusCode.PROCESSED.name()); - Mockito.when(smsResponseDto.getStatus()).thenReturn("success"); - Mockito.when(responseDto.getStatus()).thenReturn("success"); - - FieldValue registrationType = new FieldValue(); - registrationType.setLabel("registrationType"); - registrationType.setValue("DEACTIVATED"); - List fieldValueList = new ArrayList<>(); - fieldValueList.add(registrationType); - identity.setMetaData(fieldValueList); - packetMetaInfo.setIdentity(identity); - - PowerMockito.mockStatic(JsonUtil.class); - PowerMockito.when(JsonUtil.class, "inputStreamtoJavaObject", inputStream, PacketMetaInfo.class) - .thenReturn(packetMetaInfo); - - MessageDTO dto = new MessageDTO(); - dto.setRid("85425022110000120190117110505"); - MessageDTO result = stage.process(dto); - assertTrue(result.getIsValid()); - } - - @SuppressWarnings("unchecked") - @Test - public void testMessageSentDuplicateUIN() throws Exception { - ResponseWrapper responseWrapper = new ResponseWrapper<>(); - TemplateResponseDto templateResponseDto = new TemplateResponseDto(); - - TemplateDto templateDto = new TemplateDto(); - TemplateDto templateDto1 = new TemplateDto(); - Mockito.when(env.getProperty(any())).thenReturn("RPR_DUP_UIN_SMS").thenReturn("RPR_DUP_UIN_EMAIL") - .thenReturn("RPR_DUP_UIN_EMAIL_SUB"); - templateDto.setTemplateTypeCode("RPR_DUP_UIN_SMS"); - List list = new ArrayList(); - list.add(templateDto); - templateDto1.setTemplateTypeCode("RPR_DUP_UIN_EMAIL"); - list.add(templateDto1); - templateResponseDto.setTemplates(list); - String s = templateResponseDto.toString(); - responseWrapper.setResponse(templateResponseDto); - responseWrapper.setErrors(null); - Mockito.when(restClientService.getApi(any(), any(), anyString(), any(), any())).thenReturn(responseWrapper); - Mockito.when(mapper.writeValueAsString(any())).thenReturn(s); - Mockito.when(mapper.readValue(anyString(), any(Class.class))).thenReturn(templateResponseDto); - - Mockito.when(registrationStatusService.getRegistrationStatus(any(),any(),any(), any())).thenReturn(registrationStatusDto); - Mockito.when(registrationStatusDto.getLatestTransactionTypeCode()) - .thenReturn(RegistrationTransactionTypeCode.MANUAL_ADJUDICATION.name()); - Mockito.when(registrationStatusDto.getLatestTransactionStatusCode()) - .thenReturn(RegistrationTransactionStatusCode.FAILED.name()); - Mockito.when(registrationStatusDto.getStatusCode()).thenReturn(RegistrationStatusCode.REJECTED.name()); - Mockito.when(smsResponseDto.getStatus()).thenReturn("success"); - Mockito.when(responseDto.getStatus()).thenReturn("success"); - - MessageDTO dto = new MessageDTO(); - dto.setRid("85425022110000120190117110505"); - MessageDTO result = stage.process(dto); - assertFalse(result.getIsValid()); - } - - @SuppressWarnings("unchecked") - @Test - public void testMessageSentTechnicalIssue() throws Exception { - ResponseWrapper responseWrapper = new ResponseWrapper<>(); - TemplateResponseDto templateResponseDto = new TemplateResponseDto(); - TemplateDto templateDto = new TemplateDto(); - TemplateDto templateDto1 = new TemplateDto(); - Mockito.when(env.getProperty(any())).thenReturn("RPR_TEC_ISSUE_SMS").thenReturn("RPR_TEC_ISSUE_EMAIL") - .thenReturn("RPR_TEC_ISSUE_EMAIL_SUB"); - templateDto.setTemplateTypeCode("RPR_TEC_ISSUE_SMS"); - List list = new ArrayList(); - list.add(templateDto); - templateDto1.setTemplateTypeCode("RPR_TEC_ISSUE_EMAIL"); - list.add(templateDto1); - templateResponseDto.setTemplates(list); - String s = templateResponseDto.toString(); - responseWrapper.setResponse(templateResponseDto); - responseWrapper.setErrors(null); - Mockito.when(restClientService.getApi(any(), any(), anyString(), any(), any())).thenReturn(responseWrapper); - Mockito.when(mapper.writeValueAsString(any())).thenReturn(s); - Mockito.when(mapper.readValue(anyString(), any(Class.class))).thenReturn(templateResponseDto); - - Mockito.when(registrationStatusService.getRegistrationStatus(any(),any(),any(), any())).thenReturn(registrationStatusDto); - Mockito.when(registrationStatusDto.getLatestTransactionTypeCode()) - .thenReturn(RegistrationTransactionTypeCode.CMD_VALIDATION.name()); - Mockito.when(registrationStatusDto.getLatestTransactionStatusCode()) - .thenReturn(RegistrationTransactionStatusCode.FAILED.name()); - Mockito.when(registrationStatusDto.getStatusCode()).thenReturn(RegistrationStatusCode.FAILED.name()); - Mockito.when(smsResponseDto.getStatus()).thenReturn("success"); - Mockito.when(responseDto.getStatus()).thenReturn("success"); - - MessageDTO dto = new MessageDTO(); - dto.setRid("85425022110000120190117110505"); - MessageDTO result = stage.process(dto); - assertTrue(result.getIsValid()); - } - - @Test - public void testConfigNotFoundException() throws Exception { - ReflectionTestUtils.setField(stage, "notificationTypes", ""); - Mockito.when(registrationStatusService.getRegistrationStatus(any(),any(),any(), any())).thenReturn(registrationStatusDto); - Mockito.when(registrationStatusDto.getStatusCode()).thenReturn(RegistrationStatusCode.PROCESSED.name()); - Mockito.when(registrationStatusDto.getLatestTransactionTypeCode()) - .thenReturn(RegistrationTransactionTypeCode.UIN_GENERATOR.name()); - Mockito.when(registrationStatusDto.getLatestTransactionStatusCode()) - .thenReturn(RegistrationTransactionStatusCode.PROCESSED.name()); - - MessageDTO dto = new MessageDTO(); - dto.setRid("85425022110000120190117110505"); - MessageDTO result = stage.process(dto); - assertTrue(result.getInternalError()); - } - - @Test - public void testTemplateNotFound() throws ApisResourceAccessException { - ReflectionTestUtils.setField(stage, "notificationTypes", "OTP"); - - Mockito.when(registrationStatusService.getRegistrationStatus(any(),any(),any(), any())).thenReturn(registrationStatusDto); - Mockito.when(registrationStatusDto.getStatusCode()).thenReturn(RegistrationStatusCode.PROCESSED.name()); - Mockito.when(registrationStatusDto.getLatestTransactionTypeCode()) - .thenReturn(RegistrationTransactionTypeCode.UIN_GENERATOR.name()); - Mockito.when(registrationStatusDto.getLatestTransactionStatusCode()) - .thenReturn(RegistrationTransactionStatusCode.PROCESSED.name()); - - MessageDTO dto = new MessageDTO(); - dto.setRid("85425022110000120190117110505"); - MessageDTO result = stage.process(dto); - assertTrue(result.getInternalError()); - } - - @Test - public void testException() throws ApisResourceAccessException { - Mockito.when(registrationStatusService.getRegistrationStatus(any(),any(),any(), any())).thenReturn(registrationStatusDto); - Mockito.when(registrationStatusDto.getLatestTransactionTypeCode()) - .thenReturn(RegistrationTransactionTypeCode.BIOGRAPHIC_VERIFICATION.name()); - Mockito.when(registrationStatusDto.getLatestTransactionStatusCode()) - .thenReturn(RegistrationTransactionStatusCode.FAILED.name()); - - MessageDTO dto = new MessageDTO(); - dto.setRid("85425022110000120190117110505"); - MessageDTO result = stage.process(dto); - assertTrue(result.getInternalError()); - } - - @Test - public void testFsadapterException() throws ApisResourceAccessException { - FSAdapterException e = new FSAdapterException(null, null); - TemplateResponseDto templateResponseDto = new TemplateResponseDto(); - - TemplateDto templateDto = new TemplateDto(); - TemplateDto templateDto1 = new TemplateDto(); - - templateDto.setTemplateTypeCode("RPR_TEC_ISSUE_SMS"); - List list = new ArrayList(); - list.add(templateDto); - templateDto1.setTemplateTypeCode("RPR_TEC_ISSUE_EMAIL"); - list.add(templateDto1); - templateResponseDto.setTemplates(list); - Mockito.when(restClientService.getApi(any(), any(), anyString(), any(), any())).thenThrow(e); - Mockito.when(registrationStatusDto.getRegistrationType()).thenReturn("ACTIVATED"); - Mockito.when(regentity.getRegistrationType()).thenReturn("ACTIVATED"); - Mockito.when(registrationStatusDto.getStatusCode()) - .thenReturn(RegistrationTransactionStatusCode.PROCESSED.name()); - Mockito.when(registrationStatusService.getRegistrationStatus(any(),any(),any(), any())).thenReturn(registrationStatusDto); - Mockito.when(registrationStatusDto.getLatestTransactionTypeCode()) - .thenReturn(RegistrationTransactionTypeCode.CMD_VALIDATION.name()); - Mockito.when(registrationStatusDto.getLatestTransactionStatusCode()) - .thenReturn(RegistrationTransactionStatusCode.FAILED.name()); - - MessageDTO dto = new MessageDTO(); - dto.setRid("85425022110000120190117110505"); - MessageDTO result = stage.process(dto); - assertTrue(result.getInternalError()); - } - - @SuppressWarnings("unchecked") - @Test - public void testMessageSentFailedLostUin() throws Exception { - ResponseWrapper responseWrapper = new ResponseWrapper<>(); - TemplateResponseDto templateResponseDto = new TemplateResponseDto(); - - TemplateDto templateDto = new TemplateDto(); - TemplateDto templateDto1 = new TemplateDto(); - Mockito.when(env.getProperty(any())).thenReturn("RPR_LOST_UIN_SMS").thenReturn("RPR_LOST_UIN_EMAIL") - .thenReturn("RPR_UIN_GEN_EMAIL_SUB"); - templateDto.setTemplateTypeCode("RPR_LOST_UIN_SMS"); - List list = new ArrayList(); - list.add(templateDto); - templateDto1.setTemplateTypeCode("RPR_LOST_UIN_EMAIL"); - list.add(templateDto1); - templateResponseDto.setTemplates(list); - String s = templateResponseDto.toString(); - responseWrapper.setResponse(templateResponseDto); - responseWrapper.setErrors(null); - Mockito.when(restClientService.getApi(any(), any(), anyString(), any(), any())).thenReturn(responseWrapper); - Mockito.when(mapper.writeValueAsString(any())).thenReturn(s); - Mockito.when(mapper.readValue(anyString(), any(Class.class))).thenReturn(templateResponseDto); - Mockito.when(registrationStatusService.getRegistrationStatus(any(),any(),any(), any())).thenReturn(registrationStatusDto); - Mockito.when(registrationStatusDto.getStatusCode()).thenReturn(RegistrationStatusCode.PROCESSED.name()); - Mockito.when(registrationStatusDto.getLatestTransactionTypeCode()) - .thenReturn(RegistrationTransactionTypeCode.UIN_GENERATOR.name()); - Mockito.when(registrationStatusDto.getRegistrationType()).thenReturn("LOST"); - Mockito.when(regentity.getRegistrationType()).thenReturn("LOST"); - Mockito.when(registrationStatusDto.getLatestTransactionStatusCode()) - .thenReturn(RegistrationTransactionStatusCode.PROCESSED.name()); - Mockito.doReturn("failed").when(smsResponseDto).getStatus(); - Mockito.doReturn("failed").when(responseDto).getStatus(); - - MessageDTO dto = new MessageDTO(); - dto.setRid("85425022110000120190117110505"); - MessageDTO result = stage.process(dto); - assertFalse(result.getIsValid()); - } - - @SuppressWarnings("unchecked") - @Test - public void testMessageUpdateApiException() throws Exception { - ResponseWrapper responseWrapper = new ResponseWrapper<>(); - TemplateResponseDto templateResponseDto = new TemplateResponseDto(); - - TemplateDto templateDto = new TemplateDto(); - TemplateDto templateDto1 = new TemplateDto(); - Mockito.when(env.getProperty(any())).thenReturn("RPR_LOST_UIN_SMS").thenReturn("RPR_LOST_UIN_EMAIL") - .thenReturn("RPR_UIN_GEN_EMAIL_SUB"); - templateDto.setTemplateTypeCode("RPR_LOST_UIN_SMS"); - List list = new ArrayList(); - list.add(templateDto); - templateDto1.setTemplateTypeCode("RPR_LOST_UIN_EMAIL"); - list.add(templateDto1); - templateResponseDto.setTemplates(list); - String s = templateResponseDto.toString(); - responseWrapper.setResponse(templateResponseDto); - responseWrapper.setErrors(null); - Mockito.when(restClientService.getApi(any(), any(), anyString(), any(), any())).thenReturn(responseWrapper); - Mockito.when(mapper.writeValueAsString(any())).thenReturn(s); - Mockito.when(mapper.readValue(anyString(), any(Class.class))).thenReturn(templateResponseDto); - Mockito.when(registrationStatusService.getRegistrationStatus(any(),any(),any(), any())).thenReturn(registrationStatusDto); - Mockito.when(registrationStatusDto.getStatusCode()).thenReturn(RegistrationStatusCode.PROCESSED.name()); - Mockito.when(registrationStatusDto.getLatestTransactionTypeCode()) - .thenReturn(RegistrationTransactionTypeCode.UIN_GENERATOR.name()); - Mockito.when(registrationStatusDto.getRegistrationType()).thenReturn("LOST"); - Mockito.when(regentity.getRegistrationType()).thenReturn("LOST"); - Mockito.when(registrationStatusDto.getLatestTransactionStatusCode()) - .thenReturn(RegistrationTransactionStatusCode.PROCESSED.name()); - ApisResourceAccessException e = new ApisResourceAccessException(); - Mockito.doThrow(e).when(service).sendSmsNotification(any(), any(), any(), any(), any(), any()); - Mockito.doThrow(e).when(service).sendEmailNotification(any(), any(), any(), any(), any(), any(), any(), any(), any()); - - MessageDTO dto = new MessageDTO(); - dto.setRid("85425022110000120190117110505"); - MessageDTO result = stage.process(dto); - assertFalse(result.getIsValid()); - } - - @Test - public void testNotificationTyeNoneSuccess() throws Exception { - ReflectionTestUtils.setField(stage, "notificationTypes", "NONE"); - - ResponseWrapper responseWrapper = new ResponseWrapper<>(); - TemplateResponseDto templateResponseDto = new TemplateResponseDto(); - - TemplateDto templateDto = new TemplateDto(); - TemplateDto templateDto1 = new TemplateDto(); - Mockito.when(env.getProperty(any())).thenReturn("RPR_UIN_REAC_SMS").thenReturn("RPR_UIN_REAC_EMAIL") - .thenReturn("RPR_UIN_REAC_EMAIL_SUB"); - templateDto.setTemplateTypeCode("RPR_UIN_REAC_SMS"); - List list = new ArrayList(); - list.add(templateDto); - templateDto1.setTemplateTypeCode("RPR_UIN_REAC_EMAIL"); - list.add(templateDto1); - templateResponseDto.setTemplates(list); - String s = templateResponseDto.toString(); - responseWrapper.setResponse(templateResponseDto); - responseWrapper.setErrors(null); - Mockito.when(restClientService.getApi(any(), any(), anyString(), any(), any())).thenReturn(responseWrapper); - Mockito.when(mapper.writeValueAsString(any())).thenReturn(s); - Mockito.when(mapper.readValue(anyString(), any(Class.class))).thenReturn(templateResponseDto); - Mockito.when(registrationStatusService.getRegistrationStatus(any(),any(),any(), any())).thenReturn(registrationStatusDto); - Mockito.when(registrationStatusDto.getRegistrationType()).thenReturn("UPDATE"); - Mockito.when(regentity.getRegistrationType()).thenReturn("LOST"); - Mockito.when(registrationStatusDto.getStatusCode()).thenReturn(RegistrationStatusCode.PROCESSED.name()); - Mockito.when(registrationStatusDto.getLatestTransactionTypeCode()) - .thenReturn(RegistrationTransactionTypeCode.UIN_GENERATOR.name()); - Mockito.when(registrationStatusDto.getLatestTransactionStatusCode()) - .thenReturn(RegistrationTransactionStatusCode.PROCESSED.name()); - Mockito.when(smsResponseDto.getStatus()).thenReturn("success"); - Mockito.when(responseDto.getStatus()).thenReturn("success"); - - FieldValue registrationType = new FieldValue(); - registrationType.setLabel("registrationType"); - registrationType.setValue("ACTIVATED"); - List fieldValueList = new ArrayList<>(); - fieldValueList.add(registrationType); - identity.setMetaData(fieldValueList); - packetMetaInfo.setIdentity(identity); - - PowerMockito.mockStatic(JsonUtil.class); - PowerMockito.when(JsonUtil.class, "inputStreamtoJavaObject", inputStream, PacketMetaInfo.class) - .thenReturn(packetMetaInfo); - - MessageDTO dto = new MessageDTO(); - dto.setRid("85425022110000120190117110505"); - MessageDTO result = stage.process(dto); - assertTrue(result.getIsValid()); - } - - @Test - public void testNotificationSentFailureForAllNotificationType() throws Exception { - ReflectionTestUtils.setField(stage, "notificationTypes", "SMS|EMAIL"); - - ResponseWrapper responseWrapper = new ResponseWrapper<>(); - TemplateResponseDto templateResponseDto = new TemplateResponseDto(); - - TemplateDto templateDto = new TemplateDto(); - TemplateDto templateDto1 = new TemplateDto(); - Mockito.when(env.getProperty(any())).thenReturn("RPR_UIN_REAC_SMS").thenReturn("RPR_UIN_REAC_EMAIL") - .thenReturn("RPR_UIN_REAC_EMAIL_SUB"); - templateDto.setTemplateTypeCode("RPR_UIN_REAC_SMS"); - List list = new ArrayList(); - list.add(templateDto); - templateDto1.setTemplateTypeCode("RPR_UIN_REAC_EMAIL"); - list.add(templateDto1); - templateResponseDto.setTemplates(list); - String s = templateResponseDto.toString(); - responseWrapper.setResponse(templateResponseDto); - responseWrapper.setErrors(null); - Mockito.when(restClientService.getApi(any(), any(), anyString(), any(), any())).thenReturn(responseWrapper); - Mockito.when(mapper.writeValueAsString(any())).thenReturn(s); - Mockito.when(mapper.readValue(anyString(), any(Class.class))).thenReturn(templateResponseDto); - Mockito.when(registrationStatusService.getRegistrationStatus(any(),any(),any(), any())).thenReturn(registrationStatusDto); - Mockito.when(registrationStatusDto.getRegistrationType()).thenReturn("UPDATE"); - Mockito.when(regentity.getRegistrationType()).thenReturn("LOST"); - Mockito.when(registrationStatusDto.getStatusCode()).thenReturn(RegistrationStatusCode.PROCESSED.name()); - Mockito.when(registrationStatusDto.getLatestTransactionTypeCode()) - .thenReturn(RegistrationTransactionTypeCode.UIN_GENERATOR.name()); - Mockito.when(registrationStatusDto.getLatestTransactionStatusCode()) - .thenReturn(RegistrationTransactionStatusCode.PROCESSED.name()); - Mockito.when(smsResponseDto.getStatus()).thenReturn("failed"); - Mockito.when(responseDto.getStatus()).thenReturn("failed"); - - FieldValue registrationType = new FieldValue(); - registrationType.setLabel("registrationType"); - registrationType.setValue("ACTIVATED"); - List fieldValueList = new ArrayList<>(); - fieldValueList.add(registrationType); - identity.setMetaData(fieldValueList); - packetMetaInfo.setIdentity(identity); - - PowerMockito.mockStatic(JsonUtil.class); - PowerMockito.when(JsonUtil.class, "inputStreamtoJavaObject", inputStream, PacketMetaInfo.class) - .thenReturn(packetMetaInfo); - - MessageDTO dto = new MessageDTO(); - dto.setRid("85425022110000120190117110505"); - MessageDTO result = stage.process(dto); - assertFalse(result.getIsValid()); - - } - - @Test - public void testNotificationSentFailureForOneNotificationType() throws Exception { - ReflectionTestUtils.setField(stage, "notificationTypes", "SMS|EMAIL"); - - ResponseWrapper responseWrapper = new ResponseWrapper<>(); - TemplateResponseDto templateResponseDto = new TemplateResponseDto(); - - TemplateDto templateDto = new TemplateDto(); - TemplateDto templateDto1 = new TemplateDto(); - Mockito.when(env.getProperty(any())).thenReturn("RPR_UIN_REAC_SMS").thenReturn("RPR_UIN_REAC_EMAIL") - .thenReturn("RPR_UIN_REAC_EMAIL_SUB"); - templateDto.setTemplateTypeCode("RPR_UIN_REAC_SMS"); - List list = new ArrayList(); - list.add(templateDto); - templateDto1.setTemplateTypeCode("RPR_UIN_REAC_EMAIL"); - list.add(templateDto1); - templateResponseDto.setTemplates(list); - String s = templateResponseDto.toString(); - responseWrapper.setResponse(templateResponseDto); - responseWrapper.setErrors(null); - Mockito.when(restClientService.getApi(any(), any(), anyString(), any(), any())).thenReturn(responseWrapper); - Mockito.when(mapper.writeValueAsString(any())).thenReturn(s); - Mockito.when(mapper.readValue(anyString(), any(Class.class))).thenReturn(templateResponseDto); - Mockito.when(registrationStatusService.getRegistrationStatus(any(),any(),any(), any())).thenReturn(registrationStatusDto); - Mockito.when(registrationStatusDto.getRegistrationType()).thenReturn("UPDATE"); - Mockito.when(regentity.getRegistrationType()).thenReturn("UPDATE"); - Mockito.when(registrationStatusDto.getStatusCode()).thenReturn(RegistrationStatusCode.PROCESSED.name()); - Mockito.when(registrationStatusDto.getLatestTransactionTypeCode()) - .thenReturn(RegistrationTransactionTypeCode.UIN_GENERATOR.name()); - Mockito.when(registrationStatusDto.getLatestTransactionStatusCode()) - .thenReturn(RegistrationTransactionStatusCode.PROCESSED.name()); - Mockito.when(smsResponseDto.getStatus()).thenReturn("failed"); - Mockito.when(responseDto.getStatus()).thenReturn("success"); - - FieldValue registrationType = new FieldValue(); - registrationType.setLabel("registrationType"); - registrationType.setValue("ACTIVATED"); - List fieldValueList = new ArrayList<>(); - fieldValueList.add(registrationType); - identity.setMetaData(fieldValueList); - packetMetaInfo.setIdentity(identity); - - PowerMockito.mockStatic(JsonUtil.class); - PowerMockito.when(JsonUtil.class, "inputStreamtoJavaObject", inputStream, PacketMetaInfo.class) - .thenReturn(packetMetaInfo); - - MessageDTO dto = new MessageDTO(); - dto.setRid("85425022110000120190117110505"); - MessageDTO result = stage.process(dto); - assertFalse(result.getIsValid()); - - } - - - @Test - public void testNotificationSentSuccessForOneNotificationType() throws Exception { - ReflectionTestUtils.setField(stage, "notificationTypes", "SMS"); - - ResponseWrapper responseWrapper = new ResponseWrapper<>(); - TemplateResponseDto templateResponseDto = new TemplateResponseDto(); - - TemplateDto templateDto = new TemplateDto(); - TemplateDto templateDto1 = new TemplateDto(); - Mockito.when(env.getProperty(any())).thenReturn("RPR_UIN_REAC_SMS").thenReturn("RPR_UIN_REAC_EMAIL") - .thenReturn("RPR_UIN_REAC_EMAIL_SUB"); - templateDto.setTemplateTypeCode("RPR_UIN_REAC_SMS"); - List list = new ArrayList(); - list.add(templateDto); - templateDto1.setTemplateTypeCode("RPR_UIN_REAC_EMAIL"); - list.add(templateDto1); - templateResponseDto.setTemplates(list); - String s = templateResponseDto.toString(); - responseWrapper.setResponse(templateResponseDto); - responseWrapper.setErrors(null); - Mockito.when(restClientService.getApi(any(), any(), anyString(), any(), any())).thenReturn(responseWrapper); - Mockito.when(mapper.writeValueAsString(any())).thenReturn(s); - Mockito.when(mapper.readValue(anyString(), any(Class.class))).thenReturn(templateResponseDto); - Mockito.when(registrationStatusService.getRegistrationStatus(any(),any(),any(), any())).thenReturn(registrationStatusDto); - Mockito.when(registrationStatusDto.getRegistrationType()).thenReturn("ACTIVATED"); - Mockito.when(regentity.getRegistrationType()).thenReturn("ACTIVATED"); - Mockito.when(registrationStatusDto.getStatusCode()).thenReturn(RegistrationStatusCode.PROCESSED.name()); - Mockito.when(registrationStatusDto.getLatestTransactionTypeCode()) - .thenReturn(RegistrationTransactionTypeCode.UIN_GENERATOR.name()); - Mockito.when(registrationStatusDto.getLatestTransactionStatusCode()) - .thenReturn(RegistrationTransactionStatusCode.PROCESSED.name()); - Mockito.when(smsResponseDto.getStatus()).thenReturn("success"); - - FieldValue registrationType = new FieldValue(); - registrationType.setLabel("registrationType"); - registrationType.setValue("ACTIVATED"); - List fieldValueList = new ArrayList<>(); - fieldValueList.add(registrationType); - identity.setMetaData(fieldValueList); - packetMetaInfo.setIdentity(identity); - - PowerMockito.mockStatic(JsonUtil.class); - PowerMockito.when(JsonUtil.class, "inputStreamtoJavaObject", inputStream, PacketMetaInfo.class) - .thenReturn(packetMetaInfo); - - MessageDTO dto = new MessageDTO(); - dto.setRid("85425022110000120190117110505"); - MessageDTO result = stage.process(dto); - assertTrue(result.getIsValid()); - } - @SuppressWarnings("unchecked") - @Test - public void testMessageUpdateEmailIdNotFoundException() throws Exception { - ResponseWrapper responseWrapper = new ResponseWrapper<>(); - TemplateResponseDto templateResponseDto = new TemplateResponseDto(); - - TemplateDto templateDto = new TemplateDto(); - TemplateDto templateDto1 = new TemplateDto(); - Mockito.when(env.getProperty(any())).thenReturn("RPR_LOST_UIN_SMS").thenReturn("RPR_LOST_UIN_EMAIL") - .thenReturn("RPR_UIN_GEN_EMAIL_SUB"); - templateDto.setTemplateTypeCode("RPR_LOST_UIN_SMS"); - List list = new ArrayList(); - list.add(templateDto); - templateDto1.setTemplateTypeCode("RPR_LOST_UIN_EMAIL"); - list.add(templateDto1); - templateResponseDto.setTemplates(list); - String s = templateResponseDto.toString(); - responseWrapper.setResponse(templateResponseDto); - responseWrapper.setErrors(null); - Mockito.when(restClientService.getApi(any(), any(), anyString(), any(), any())).thenReturn(responseWrapper); - Mockito.when(mapper.writeValueAsString(any())).thenReturn(s); - Mockito.when(mapper.readValue(anyString(), any(Class.class))).thenReturn(templateResponseDto); - Mockito.when(registrationStatusService.getRegistrationStatus(any(),any(),any(), any())).thenReturn(registrationStatusDto); - Mockito.when(registrationStatusDto.getStatusCode()).thenReturn(RegistrationStatusCode.PROCESSED.name()); - Mockito.when(registrationStatusDto.getLatestTransactionTypeCode()) - .thenReturn(RegistrationTransactionTypeCode.UIN_GENERATOR.name()); - Mockito.when(registrationStatusDto.getRegistrationType()).thenReturn("LOST"); - Mockito.when(regentity.getRegistrationType()).thenReturn("LOST"); - Mockito.when(registrationStatusDto.getLatestTransactionStatusCode()) - .thenReturn(RegistrationTransactionStatusCode.PROCESSED.name()); - EmailIdNotFoundException e = new EmailIdNotFoundException(); - Mockito.doReturn("success").when(smsResponseDto).getStatus(); - Mockito.doReturn("success").when(responseDto).getStatus(); - Mockito.doThrow(e).when(service).sendEmailNotification(any(), any(), any(), any(), any(), any(), any(), any(), any()); - - MessageDTO dto = new MessageDTO(); - dto.setRid("85425022110000120190117110505"); - MessageDTO result = stage.process(dto); - assertFalse(result.getIsValid()); - } - @SuppressWarnings("unchecked") - @Test - public void testMessageUpdatePhoneNumberNotFoundException() throws Exception { - ResponseWrapper responseWrapper = new ResponseWrapper<>(); - TemplateResponseDto templateResponseDto = new TemplateResponseDto(); - - TemplateDto templateDto = new TemplateDto(); - TemplateDto templateDto1 = new TemplateDto(); - Mockito.when(env.getProperty(any())).thenReturn("RPR_LOST_UIN_SMS").thenReturn("RPR_LOST_UIN_EMAIL") - .thenReturn("RPR_UIN_GEN_EMAIL_SUB"); - templateDto.setTemplateTypeCode("RPR_LOST_UIN_SMS"); - List list = new ArrayList(); - list.add(templateDto); - templateDto1.setTemplateTypeCode("RPR_LOST_UIN_EMAIL"); - list.add(templateDto1); - templateResponseDto.setTemplates(list); - String s = templateResponseDto.toString(); - responseWrapper.setResponse(templateResponseDto); - responseWrapper.setErrors(null); - Mockito.when(restClientService.getApi(any(), any(), anyString(), any(), any())).thenReturn(responseWrapper); - Mockito.when(mapper.writeValueAsString(any())).thenReturn(s); - Mockito.when(mapper.readValue(anyString(), any(Class.class))).thenReturn(templateResponseDto); - Mockito.when(registrationStatusService.getRegistrationStatus(any(),any(),any(), any())).thenReturn(registrationStatusDto); - Mockito.when(registrationStatusDto.getStatusCode()).thenReturn(RegistrationStatusCode.PROCESSED.name()); - Mockito.when(registrationStatusDto.getLatestTransactionTypeCode()) - .thenReturn(RegistrationTransactionTypeCode.UIN_GENERATOR.name()); - Mockito.when(registrationStatusDto.getRegistrationType()).thenReturn("LOST"); - Mockito.when(registrationStatusDto.getLatestTransactionStatusCode()) - .thenReturn(RegistrationTransactionStatusCode.PROCESSED.name()); - PhoneNumberNotFoundException e = new PhoneNumberNotFoundException(); - Mockito.doThrow(e).when(service).sendSmsNotification(any(), any(), any(), any(), any(), any()); - - MessageDTO dto = new MessageDTO(); - dto.setRid("85425022110000120190117110505"); - MessageDTO result = stage.process(dto); - assertFalse(result.getIsValid()); - } -} +package io.mosip.registration.processor.message.sender.stage.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 java.io.InputStream; +import java.util.ArrayList; +import java.util.List; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.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 org.springframework.web.multipart.MultipartFile; + +import com.fasterxml.jackson.databind.ObjectMapper; + +import io.mosip.kernel.core.fsadapter.exception.FSAdapterException; +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.RegistrationTransactionStatusCode; +import io.mosip.registration.processor.core.code.RegistrationTransactionTypeCode; +import io.mosip.registration.processor.core.exception.ApisResourceAccessException; +import io.mosip.registration.processor.core.http.ResponseWrapper; +import io.mosip.registration.processor.core.logger.LogDescription; +import io.mosip.registration.processor.core.notification.template.generator.dto.ResponseDto; +import io.mosip.registration.processor.core.notification.template.generator.dto.SmsResponseDto; +import io.mosip.registration.processor.core.notification.template.generator.dto.TemplateDto; +import io.mosip.registration.processor.core.notification.template.generator.dto.TemplateResponseDto; +import io.mosip.registration.processor.core.packet.dto.FieldValue; +import io.mosip.registration.processor.core.packet.dto.Identity; +import io.mosip.registration.processor.core.packet.dto.PacketMetaInfo; +import io.mosip.registration.processor.core.spi.eventbus.EventHandler; +import io.mosip.registration.processor.core.spi.message.sender.MessageNotificationService; +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.message.sender.dto.MessageSenderDto; +import io.mosip.registration.processor.message.sender.exception.EmailIdNotFoundException; +import io.mosip.registration.processor.message.sender.exception.PhoneNumberNotFoundException; +import io.mosip.registration.processor.message.sender.stage.MessageSenderStage; +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.dto.SyncRegistrationDto; +import io.mosip.registration.processor.status.dto.SyncResponseDto; +import io.mosip.registration.processor.status.dto.TransactionDto; +import io.mosip.registration.processor.status.entity.SyncRegistrationEntity; +import io.mosip.registration.processor.status.service.RegistrationStatusService; +import io.mosip.registration.processor.status.service.SyncRegistrationService; +import io.mosip.registration.processor.status.service.TransactionService; +import io.vertx.core.AsyncResult; +import io.vertx.core.Handler; +import io.vertx.core.Vertx; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({ Utilities.class, JsonUtil.class }) +@PowerMockIgnore({ "com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*","javax.management.*", "javax.net.ssl.*" }) +public class MessageSenderStageTest { + + @Mock + private MessageNotificationService service; + + @Mock + private ObjectMapper mapper; + + @Mock + private RegistrationProcessorRestClientService restClientService; + + @Mock + private RegistrationStatusService registrationStatusService; + + @Mock + private TransactionService transcationStatusService; + + @Mock + private InternalRegistrationStatusDto registrationStatusDto; + + @Mock + private SyncRegistrationService syncRegistrationservice; + + + @Mock + private AuditLogRequestBuilder auditLogRequestBuilder; + + + /** The packet meta info. */ + private PacketMetaInfo packetMetaInfo = new PacketMetaInfo(); + + /** The identity. */ + Identity identity = new Identity(); + + /** The input stream. */ + @Mock + private InputStream inputStream; + + @Mock + private RegistrationExceptionMapperUtil registrationExceptionMapperUtil; + + @Mock + private LogDescription description; + + @Mock + private RegistrationExceptionMapperUtil registrationStatusMapperUtil; + + @Mock + Environment env; + + MessageSenderDto messageSenderDto = Mockito.mock(MessageSenderDto.class); + + private SmsResponseDto smsResponseDto = Mockito.mock(SmsResponseDto.class); + + private ResponseDto responseDto = Mockito.mock(ResponseDto.class); + + private SyncRegistrationEntity regentity = Mockito.mock(SyncRegistrationEntity.class); + + @InjectMocks + private MessageSenderStage stage = new MessageSenderStage() { + @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 consumeAndSend(MosipEventBus mosipEventBus, MessageBusAddress fromAddress, + MessageBusAddress toAddress, long messageExpiryTimeLimit) { + } + }; + + @Before + public void setup() throws Exception { + ReflectionTestUtils.setField(stage, "workerPoolSize", 10); + ReflectionTestUtils.setField(stage, "messageExpiryTimeLimit", Long.valueOf(0)); + ReflectionTestUtils.setField(stage, "clusterManagerUrl", "/dummyPath"); + ReflectionTestUtils.setField(stage, "notificationTypes", "SMS|EMAIL"); + ReflectionTestUtils.setField(stage, "notificationEmails", "abc@gmail.com"); + + Mockito.doNothing().when(registrationStatusDto).setStatusCode(any()); + Mockito.doNothing().when(registrationStatusDto).setStatusComment(any()); + Mockito.when(registrationStatusDto.getRegistrationType()).thenReturn("NEW"); + Mockito.doNothing().when(registrationStatusService).updateRegistrationStatus(any(), any(), any()); + Mockito.when(transcationStatusService.addRegistrationTransaction(any())).thenReturn(null); + Mockito.doNothing().when(registrationStatusDto).setLatestTransactionTypeCode(any()); + Mockito.doNothing().when(registrationStatusDto).setRegistrationStageName(any()); + Mockito.doNothing().when(registrationStatusDto).setLatestTransactionStatusCode(any()); + Mockito.doNothing().when(description).setMessage(any()); + + Mockito.doNothing().when(messageSenderDto).setEmailTemplateCode(any()); + Mockito.doNothing().when(messageSenderDto).setSmsTemplateCode(any()); + Mockito.doNothing().when(messageSenderDto).setIdType(any()); + Mockito.doNothing().when(messageSenderDto).setSubjectCode(any()); + Mockito.doNothing().when(messageSenderDto).setTemplateAvailable(any(Boolean.class)); + + Mockito.when(service.sendSmsNotification(any(), any(), any(), any(), any(), any())).thenReturn(smsResponseDto); + Mockito.when(service.sendEmailNotification(any(), any(), any(), any(), any(), any(), any(), any(), any())) + .thenReturn(responseDto); + + Mockito.when(registrationStatusMapperUtil.getStatusCode(any())).thenReturn("ERROR"); + Mockito.when(registrationExceptionMapperUtil.getStatusCode(any())).thenReturn("ERROR"); + + + FieldValue registrationType = new FieldValue(); + registrationType.setLabel("registrationType"); + registrationType.setValue("New"); + List fieldValueList = new ArrayList<>(); + fieldValueList.add(registrationType); + identity.setMetaData(fieldValueList); + packetMetaInfo.setIdentity(identity); + + PowerMockito.mockStatic(JsonUtil.class); + + regentity.setRegistrationType("NEW"); + Mockito.when(syncRegistrationservice.findByWorkflowInstanceId(any())).thenReturn(regentity); + } + + @Test + public void testDeployVerticle() { + stage.deployVerticle(); + } + + @SuppressWarnings("unchecked") + @Test + public void testMessageSentUINGenerated() throws Exception { + ResponseWrapper responseWrapper = new ResponseWrapper<>(); + TemplateResponseDto templateResponseDto = new TemplateResponseDto(); + + TemplateDto templateDto = new TemplateDto(); + TemplateDto templateDto1 = new TemplateDto(); + Mockito.when(env.getProperty(any())).thenReturn("RPR_UIN_GEN_SMS").thenReturn("RPR_UIN_GEN_EMAIL") + .thenReturn("RPR_UIN_GEN_EMAIL_SUB"); + templateDto.setTemplateTypeCode("RPR_UIN_GEN_SMS"); + List list = new ArrayList(); + list.add(templateDto); + templateDto1.setTemplateTypeCode("RPR_UIN_GEN_EMAIL"); + list.add(templateDto1); + templateResponseDto.setTemplates(list); + String s = templateResponseDto.toString(); + responseWrapper.setResponse(templateResponseDto); + responseWrapper.setErrors(null); + Mockito.when(restClientService.getApi(any(), any(), anyString(), any(), any())).thenReturn(responseWrapper); + Mockito.when(mapper.writeValueAsString(any())).thenReturn(s); + Mockito.when(mapper.readValue(anyString(), any(Class.class))).thenReturn(templateResponseDto); + Mockito.when(registrationStatusService.getRegistrationStatus(any(),any(),any(), any())).thenReturn(registrationStatusDto); + Mockito.when(registrationStatusDto.getStatusCode()).thenReturn(RegistrationStatusCode.PROCESSED.name()); + Mockito.when(registrationStatusDto.getLatestTransactionTypeCode()) + .thenReturn(RegistrationTransactionTypeCode.UIN_GENERATOR.name()); + Mockito.when(registrationStatusDto.getLatestTransactionStatusCode()) + .thenReturn(RegistrationTransactionStatusCode.PROCESSED.name()); + Mockito.doReturn("success").when(smsResponseDto).getStatus(); + Mockito.doReturn("success").when(responseDto).getStatus(); + + MessageDTO dto = new MessageDTO(); + dto.setRid("85425022110000120190117110505"); + MessageDTO result = stage.process(dto); + assertTrue(result.getIsValid()); + } + + @SuppressWarnings("unchecked") + @Test + public void testMessageSentUINUpdate() throws Exception { + ResponseWrapper responseWrapper = new ResponseWrapper<>(); + TemplateResponseDto templateResponseDto = new TemplateResponseDto(); + + TemplateDto templateDto = new TemplateDto(); + TemplateDto templateDto1 = new TemplateDto(); + Mockito.when(env.getProperty(any())).thenReturn("RPR_UIN_UPD_SMS").thenReturn("RPR_UIN_UPD_EMAIL") + .thenReturn("RPR_UIN_UPD_EMAIL_SUB"); + templateDto.setTemplateTypeCode("RPR_UIN_UPD_SMS"); + List list = new ArrayList(); + list.add(templateDto); + templateDto1.setTemplateTypeCode("RPR_UIN_UPD_EMAIL"); + list.add(templateDto1); + templateResponseDto.setTemplates(list); + String s = templateResponseDto.toString(); + responseWrapper.setResponse(templateResponseDto); + responseWrapper.setErrors(null); + Mockito.when(restClientService.getApi(any(), any(), anyString(), any(), any())).thenReturn(responseWrapper); + Mockito.when(mapper.writeValueAsString(any())).thenReturn(s); + Mockito.when(mapper.readValue(anyString(), any(Class.class))).thenReturn(templateResponseDto); + + Mockito.when(registrationStatusService.getRegistrationStatus(any(),any(),any(), any())).thenReturn(registrationStatusDto); + + Mockito.when(registrationStatusDto.getStatusCode()).thenReturn(RegistrationStatusCode.PROCESSED.name()); + Mockito.when(registrationStatusDto.getLatestTransactionTypeCode()) + .thenReturn(RegistrationTransactionTypeCode.UIN_GENERATOR.name()); + Mockito.when(registrationStatusDto.getLatestTransactionStatusCode()) + .thenReturn(RegistrationTransactionStatusCode.PROCESSED.name()); + + Mockito.when(smsResponseDto.getStatus()).thenReturn("success"); + Mockito.when(responseDto.getStatus()).thenReturn("success"); + Mockito.when(registrationStatusDto.getRegistrationType()).thenReturn("UPDATE"); + Mockito.when(regentity.getRegistrationType()).thenReturn("UPDATE"); + MessageDTO dto = new MessageDTO(); + dto.setRid("85425022110000120190117110505"); + MessageDTO result = stage.process(dto); + assertTrue(result.getIsValid()); + } + + @SuppressWarnings("unchecked") + @Test + public void testMessageSentUINUpdatewithActivatedUIN() throws Exception { + ResponseWrapper responseWrapper = new ResponseWrapper<>(); + TemplateResponseDto templateResponseDto = new TemplateResponseDto(); + + TemplateDto templateDto = new TemplateDto(); + TemplateDto templateDto1 = new TemplateDto(); + Mockito.when(env.getProperty(any())).thenReturn("RPR_UIN_REAC_SMS").thenReturn("RPR_UIN_REAC_EMAIL") + .thenReturn("RPR_UIN_REAC_EMAIL_SUB"); + templateDto.setTemplateTypeCode("RPR_UIN_REAC_SMS"); + List list = new ArrayList(); + list.add(templateDto); + templateDto1.setTemplateTypeCode("RPR_UIN_REAC_EMAIL"); + list.add(templateDto1); + templateResponseDto.setTemplates(list); + String s = templateResponseDto.toString(); + responseWrapper.setResponse(templateResponseDto); + responseWrapper.setErrors(null); + Mockito.when(restClientService.getApi(any(), any(), anyString(), any(), any())).thenReturn(responseWrapper); + Mockito.when(mapper.writeValueAsString(any())).thenReturn(s); + Mockito.when(mapper.readValue(anyString(), any(Class.class))).thenReturn(templateResponseDto); + Mockito.when(registrationStatusService.getRegistrationStatus(any(),any(),any(), any())).thenReturn(registrationStatusDto); + Mockito.when(registrationStatusDto.getRegistrationType()).thenReturn("ACTIVATED"); + Mockito.when(regentity.getRegistrationType()).thenReturn("ACTIVATED"); + Mockito.when(registrationStatusDto.getStatusCode()).thenReturn(RegistrationStatusCode.PROCESSED.name()); + Mockito.when(registrationStatusDto.getLatestTransactionTypeCode()) + .thenReturn(RegistrationTransactionTypeCode.UIN_GENERATOR.name()); + Mockito.when(registrationStatusDto.getLatestTransactionStatusCode()) + .thenReturn(RegistrationTransactionStatusCode.PROCESSED.name()); + Mockito.when(smsResponseDto.getStatus()).thenReturn("success"); + Mockito.when(responseDto.getStatus()).thenReturn("success"); + + FieldValue registrationType = new FieldValue(); + registrationType.setLabel("registrationType"); + registrationType.setValue("ACTIVATED"); + List fieldValueList = new ArrayList<>(); + fieldValueList.add(registrationType); + identity.setMetaData(fieldValueList); + packetMetaInfo.setIdentity(identity); + + PowerMockito.mockStatic(JsonUtil.class); + PowerMockito.when(JsonUtil.class, "inputStreamtoJavaObject", inputStream, PacketMetaInfo.class) + .thenReturn(packetMetaInfo); + + MessageDTO dto = new MessageDTO(); + dto.setRid("85425022110000120190117110505"); + MessageDTO result = stage.process(dto); + assertTrue(result.getIsValid()); + } + + @SuppressWarnings("unchecked") + @Test + public void testMessageSentUINUpdatewithDeactivatedUIN() throws Exception { + ResponseWrapper responseWrapper = new ResponseWrapper<>(); + TemplateResponseDto templateResponseDto = new TemplateResponseDto(); + + TemplateDto templateDto = new TemplateDto(); + TemplateDto templateDto1 = new TemplateDto(); + Mockito.when(env.getProperty(any())).thenReturn("RPR_UIN_DEAC_SMS").thenReturn("RPR_UIN_DEAC_EMAIL") + .thenReturn("RPR_UIN_DEAC_EMAIL_SUB"); + templateDto.setTemplateTypeCode("RPR_UIN_DEAC_SMS"); + List list = new ArrayList(); + list.add(templateDto); + templateDto1.setTemplateTypeCode("RPR_UIN_DEAC_EMAIL"); + list.add(templateDto1); + templateResponseDto.setTemplates(list); + String s = templateResponseDto.toString(); + responseWrapper.setResponse(templateResponseDto); + responseWrapper.setErrors(null); + Mockito.when(restClientService.getApi(any(), any(), anyString(), any(), any())).thenReturn(responseWrapper); + Mockito.when(mapper.writeValueAsString(any())).thenReturn(s); + Mockito.when(mapper.readValue(anyString(), any(Class.class))).thenReturn(templateResponseDto); + + Mockito.when(registrationStatusService.getRegistrationStatus(any(),any(),any(), any())).thenReturn(registrationStatusDto); + // Mockito.when(registrationStatusDto.getStatusCode()).thenReturn(RegistrationStatusCode.PACKET_UIN_UPDATION_SUCCESS.name()); + Mockito.when(registrationStatusDto.getRegistrationType()).thenReturn("DEACTIVATED"); + Mockito.when(regentity.getRegistrationType()).thenReturn("DEACTIVATED"); + Mockito.when(registrationStatusDto.getStatusCode()).thenReturn(RegistrationStatusCode.PROCESSED.name()); + Mockito.when(registrationStatusDto.getLatestTransactionTypeCode()) + .thenReturn(RegistrationTransactionTypeCode.UIN_GENERATOR.name()); + Mockito.when(registrationStatusDto.getLatestTransactionStatusCode()) + .thenReturn(RegistrationTransactionStatusCode.PROCESSED.name()); + Mockito.when(smsResponseDto.getStatus()).thenReturn("success"); + Mockito.when(responseDto.getStatus()).thenReturn("success"); + + FieldValue registrationType = new FieldValue(); + registrationType.setLabel("registrationType"); + registrationType.setValue("DEACTIVATED"); + List fieldValueList = new ArrayList<>(); + fieldValueList.add(registrationType); + identity.setMetaData(fieldValueList); + packetMetaInfo.setIdentity(identity); + + PowerMockito.mockStatic(JsonUtil.class); + PowerMockito.when(JsonUtil.class, "inputStreamtoJavaObject", inputStream, PacketMetaInfo.class) + .thenReturn(packetMetaInfo); + + MessageDTO dto = new MessageDTO(); + dto.setRid("85425022110000120190117110505"); + MessageDTO result = stage.process(dto); + assertTrue(result.getIsValid()); + } + + @SuppressWarnings("unchecked") + @Test + public void testMessageSentDuplicateUIN() throws Exception { + ResponseWrapper responseWrapper = new ResponseWrapper<>(); + TemplateResponseDto templateResponseDto = new TemplateResponseDto(); + + TemplateDto templateDto = new TemplateDto(); + TemplateDto templateDto1 = new TemplateDto(); + Mockito.when(env.getProperty(any())).thenReturn("RPR_DUP_UIN_SMS").thenReturn("RPR_DUP_UIN_EMAIL") + .thenReturn("RPR_DUP_UIN_EMAIL_SUB"); + templateDto.setTemplateTypeCode("RPR_DUP_UIN_SMS"); + List list = new ArrayList(); + list.add(templateDto); + templateDto1.setTemplateTypeCode("RPR_DUP_UIN_EMAIL"); + list.add(templateDto1); + templateResponseDto.setTemplates(list); + String s = templateResponseDto.toString(); + responseWrapper.setResponse(templateResponseDto); + responseWrapper.setErrors(null); + Mockito.when(restClientService.getApi(any(), any(), anyString(), any(), any())).thenReturn(responseWrapper); + Mockito.when(mapper.writeValueAsString(any())).thenReturn(s); + Mockito.when(mapper.readValue(anyString(), any(Class.class))).thenReturn(templateResponseDto); + + Mockito.when(registrationStatusService.getRegistrationStatus(any(),any(),any(), any())).thenReturn(registrationStatusDto); + Mockito.when(registrationStatusDto.getLatestTransactionTypeCode()) + .thenReturn(RegistrationTransactionTypeCode.MANUAL_ADJUDICATION.name()); + Mockito.when(registrationStatusDto.getLatestTransactionStatusCode()) + .thenReturn(RegistrationTransactionStatusCode.FAILED.name()); + Mockito.when(registrationStatusDto.getStatusCode()).thenReturn(RegistrationStatusCode.REJECTED.name()); + Mockito.when(smsResponseDto.getStatus()).thenReturn("success"); + Mockito.when(responseDto.getStatus()).thenReturn("success"); + + MessageDTO dto = new MessageDTO(); + dto.setRid("85425022110000120190117110505"); + MessageDTO result = stage.process(dto); + assertFalse(result.getIsValid()); + } + + @SuppressWarnings("unchecked") + @Test + public void testMessageSentTechnicalIssue() throws Exception { + ResponseWrapper responseWrapper = new ResponseWrapper<>(); + TemplateResponseDto templateResponseDto = new TemplateResponseDto(); + TemplateDto templateDto = new TemplateDto(); + TemplateDto templateDto1 = new TemplateDto(); + Mockito.when(env.getProperty(any())).thenReturn("RPR_TEC_ISSUE_SMS").thenReturn("RPR_TEC_ISSUE_EMAIL") + .thenReturn("RPR_TEC_ISSUE_EMAIL_SUB"); + templateDto.setTemplateTypeCode("RPR_TEC_ISSUE_SMS"); + List list = new ArrayList(); + list.add(templateDto); + templateDto1.setTemplateTypeCode("RPR_TEC_ISSUE_EMAIL"); + list.add(templateDto1); + templateResponseDto.setTemplates(list); + String s = templateResponseDto.toString(); + responseWrapper.setResponse(templateResponseDto); + responseWrapper.setErrors(null); + Mockito.when(restClientService.getApi(any(), any(), anyString(), any(), any())).thenReturn(responseWrapper); + Mockito.when(mapper.writeValueAsString(any())).thenReturn(s); + Mockito.when(mapper.readValue(anyString(), any(Class.class))).thenReturn(templateResponseDto); + + Mockito.when(registrationStatusService.getRegistrationStatus(any(),any(),any(), any())).thenReturn(registrationStatusDto); + Mockito.when(registrationStatusDto.getLatestTransactionTypeCode()) + .thenReturn(RegistrationTransactionTypeCode.CMD_VALIDATION.name()); + Mockito.when(registrationStatusDto.getLatestTransactionStatusCode()) + .thenReturn(RegistrationTransactionStatusCode.FAILED.name()); + Mockito.when(registrationStatusDto.getStatusCode()).thenReturn(RegistrationStatusCode.FAILED.name()); + Mockito.when(smsResponseDto.getStatus()).thenReturn("success"); + Mockito.when(responseDto.getStatus()).thenReturn("success"); + + MessageDTO dto = new MessageDTO(); + dto.setRid("85425022110000120190117110505"); + MessageDTO result = stage.process(dto); + assertTrue(result.getIsValid()); + } + + @Test + public void testConfigNotFoundException() throws Exception { + ReflectionTestUtils.setField(stage, "notificationTypes", ""); + Mockito.when(registrationStatusService.getRegistrationStatus(any(),any(),any(), any())).thenReturn(registrationStatusDto); + Mockito.when(registrationStatusDto.getStatusCode()).thenReturn(RegistrationStatusCode.PROCESSED.name()); + Mockito.when(registrationStatusDto.getLatestTransactionTypeCode()) + .thenReturn(RegistrationTransactionTypeCode.UIN_GENERATOR.name()); + Mockito.when(registrationStatusDto.getLatestTransactionStatusCode()) + .thenReturn(RegistrationTransactionStatusCode.PROCESSED.name()); + + MessageDTO dto = new MessageDTO(); + dto.setRid("85425022110000120190117110505"); + MessageDTO result = stage.process(dto); + assertTrue(result.getInternalError()); + } + + @Test + public void testTemplateNotFound() throws ApisResourceAccessException { + ReflectionTestUtils.setField(stage, "notificationTypes", "OTP"); + + Mockito.when(registrationStatusService.getRegistrationStatus(any(),any(),any(), any())).thenReturn(registrationStatusDto); + Mockito.when(registrationStatusDto.getStatusCode()).thenReturn(RegistrationStatusCode.PROCESSED.name()); + Mockito.when(registrationStatusDto.getLatestTransactionTypeCode()) + .thenReturn(RegistrationTransactionTypeCode.UIN_GENERATOR.name()); + Mockito.when(registrationStatusDto.getLatestTransactionStatusCode()) + .thenReturn(RegistrationTransactionStatusCode.PROCESSED.name()); + + MessageDTO dto = new MessageDTO(); + dto.setRid("85425022110000120190117110505"); + MessageDTO result = stage.process(dto); + assertTrue(result.getInternalError()); + } + + @Test + public void testException() throws ApisResourceAccessException { + Mockito.when(registrationStatusService.getRegistrationStatus(any(),any(),any(), any())).thenReturn(registrationStatusDto); + Mockito.when(registrationStatusDto.getLatestTransactionTypeCode()) + .thenReturn(RegistrationTransactionTypeCode.BIOGRAPHIC_VERIFICATION.name()); + Mockito.when(registrationStatusDto.getLatestTransactionStatusCode()) + .thenReturn(RegistrationTransactionStatusCode.FAILED.name()); + + MessageDTO dto = new MessageDTO(); + dto.setRid("85425022110000120190117110505"); + MessageDTO result = stage.process(dto); + assertTrue(result.getInternalError()); + } + + @Test + public void testFsadapterException() throws ApisResourceAccessException { + FSAdapterException e = new FSAdapterException(null, null); + TemplateResponseDto templateResponseDto = new TemplateResponseDto(); + + TemplateDto templateDto = new TemplateDto(); + TemplateDto templateDto1 = new TemplateDto(); + + templateDto.setTemplateTypeCode("RPR_TEC_ISSUE_SMS"); + List list = new ArrayList(); + list.add(templateDto); + templateDto1.setTemplateTypeCode("RPR_TEC_ISSUE_EMAIL"); + list.add(templateDto1); + templateResponseDto.setTemplates(list); + Mockito.when(restClientService.getApi(any(), any(), anyString(), any(), any())).thenThrow(e); + Mockito.when(registrationStatusDto.getRegistrationType()).thenReturn("ACTIVATED"); + Mockito.when(regentity.getRegistrationType()).thenReturn("ACTIVATED"); + Mockito.when(registrationStatusDto.getStatusCode()) + .thenReturn(RegistrationTransactionStatusCode.PROCESSED.name()); + Mockito.when(registrationStatusService.getRegistrationStatus(any(),any(),any(), any())).thenReturn(registrationStatusDto); + Mockito.when(registrationStatusDto.getLatestTransactionTypeCode()) + .thenReturn(RegistrationTransactionTypeCode.CMD_VALIDATION.name()); + Mockito.when(registrationStatusDto.getLatestTransactionStatusCode()) + .thenReturn(RegistrationTransactionStatusCode.FAILED.name()); + + MessageDTO dto = new MessageDTO(); + dto.setRid("85425022110000120190117110505"); + MessageDTO result = stage.process(dto); + assertTrue(result.getInternalError()); + } + + @SuppressWarnings("unchecked") + @Test + public void testMessageSentFailedLostUin() throws Exception { + ResponseWrapper responseWrapper = new ResponseWrapper<>(); + TemplateResponseDto templateResponseDto = new TemplateResponseDto(); + + TemplateDto templateDto = new TemplateDto(); + TemplateDto templateDto1 = new TemplateDto(); + Mockito.when(env.getProperty(any())).thenReturn("RPR_LOST_UIN_SMS").thenReturn("RPR_LOST_UIN_EMAIL") + .thenReturn("RPR_UIN_GEN_EMAIL_SUB"); + templateDto.setTemplateTypeCode("RPR_LOST_UIN_SMS"); + List list = new ArrayList(); + list.add(templateDto); + templateDto1.setTemplateTypeCode("RPR_LOST_UIN_EMAIL"); + list.add(templateDto1); + templateResponseDto.setTemplates(list); + String s = templateResponseDto.toString(); + responseWrapper.setResponse(templateResponseDto); + responseWrapper.setErrors(null); + Mockito.when(restClientService.getApi(any(), any(), anyString(), any(), any())).thenReturn(responseWrapper); + Mockito.when(mapper.writeValueAsString(any())).thenReturn(s); + Mockito.when(mapper.readValue(anyString(), any(Class.class))).thenReturn(templateResponseDto); + Mockito.when(registrationStatusService.getRegistrationStatus(any(),any(),any(), any())).thenReturn(registrationStatusDto); + Mockito.when(registrationStatusDto.getStatusCode()).thenReturn(RegistrationStatusCode.PROCESSED.name()); + Mockito.when(registrationStatusDto.getLatestTransactionTypeCode()) + .thenReturn(RegistrationTransactionTypeCode.UIN_GENERATOR.name()); + Mockito.when(registrationStatusDto.getRegistrationType()).thenReturn("LOST"); + Mockito.when(regentity.getRegistrationType()).thenReturn("LOST"); + Mockito.when(registrationStatusDto.getLatestTransactionStatusCode()) + .thenReturn(RegistrationTransactionStatusCode.PROCESSED.name()); + Mockito.doReturn("failed").when(smsResponseDto).getStatus(); + Mockito.doReturn("failed").when(responseDto).getStatus(); + + MessageDTO dto = new MessageDTO(); + dto.setRid("85425022110000120190117110505"); + MessageDTO result = stage.process(dto); + assertFalse(result.getIsValid()); + } + + @SuppressWarnings("unchecked") + @Test + public void testMessageUpdateApiException() throws Exception { + ResponseWrapper responseWrapper = new ResponseWrapper<>(); + TemplateResponseDto templateResponseDto = new TemplateResponseDto(); + + TemplateDto templateDto = new TemplateDto(); + TemplateDto templateDto1 = new TemplateDto(); + Mockito.when(env.getProperty(any())).thenReturn("RPR_LOST_UIN_SMS").thenReturn("RPR_LOST_UIN_EMAIL") + .thenReturn("RPR_UIN_GEN_EMAIL_SUB"); + templateDto.setTemplateTypeCode("RPR_LOST_UIN_SMS"); + List list = new ArrayList(); + list.add(templateDto); + templateDto1.setTemplateTypeCode("RPR_LOST_UIN_EMAIL"); + list.add(templateDto1); + templateResponseDto.setTemplates(list); + String s = templateResponseDto.toString(); + responseWrapper.setResponse(templateResponseDto); + responseWrapper.setErrors(null); + Mockito.when(restClientService.getApi(any(), any(), anyString(), any(), any())).thenReturn(responseWrapper); + Mockito.when(mapper.writeValueAsString(any())).thenReturn(s); + Mockito.when(mapper.readValue(anyString(), any(Class.class))).thenReturn(templateResponseDto); + Mockito.when(registrationStatusService.getRegistrationStatus(any(),any(),any(), any())).thenReturn(registrationStatusDto); + Mockito.when(registrationStatusDto.getStatusCode()).thenReturn(RegistrationStatusCode.PROCESSED.name()); + Mockito.when(registrationStatusDto.getLatestTransactionTypeCode()) + .thenReturn(RegistrationTransactionTypeCode.UIN_GENERATOR.name()); + Mockito.when(registrationStatusDto.getRegistrationType()).thenReturn("LOST"); + Mockito.when(regentity.getRegistrationType()).thenReturn("LOST"); + Mockito.when(registrationStatusDto.getLatestTransactionStatusCode()) + .thenReturn(RegistrationTransactionStatusCode.PROCESSED.name()); + ApisResourceAccessException e = new ApisResourceAccessException(); + Mockito.doThrow(e).when(service).sendSmsNotification(any(), any(), any(), any(), any(), any()); + Mockito.doThrow(e).when(service).sendEmailNotification(any(), any(), any(), any(), any(), any(), any(), any(), any()); + + MessageDTO dto = new MessageDTO(); + dto.setRid("85425022110000120190117110505"); + MessageDTO result = stage.process(dto); + assertFalse(result.getIsValid()); + } + + @Test + public void testNotificationTyeNoneSuccess() throws Exception { + ReflectionTestUtils.setField(stage, "notificationTypes", "NONE"); + + ResponseWrapper responseWrapper = new ResponseWrapper<>(); + TemplateResponseDto templateResponseDto = new TemplateResponseDto(); + + TemplateDto templateDto = new TemplateDto(); + TemplateDto templateDto1 = new TemplateDto(); + Mockito.when(env.getProperty(any())).thenReturn("RPR_UIN_REAC_SMS").thenReturn("RPR_UIN_REAC_EMAIL") + .thenReturn("RPR_UIN_REAC_EMAIL_SUB"); + templateDto.setTemplateTypeCode("RPR_UIN_REAC_SMS"); + List list = new ArrayList(); + list.add(templateDto); + templateDto1.setTemplateTypeCode("RPR_UIN_REAC_EMAIL"); + list.add(templateDto1); + templateResponseDto.setTemplates(list); + String s = templateResponseDto.toString(); + responseWrapper.setResponse(templateResponseDto); + responseWrapper.setErrors(null); + Mockito.when(restClientService.getApi(any(), any(), anyString(), any(), any())).thenReturn(responseWrapper); + Mockito.when(mapper.writeValueAsString(any())).thenReturn(s); + Mockito.when(mapper.readValue(anyString(), any(Class.class))).thenReturn(templateResponseDto); + Mockito.when(registrationStatusService.getRegistrationStatus(any(),any(),any(), any())).thenReturn(registrationStatusDto); + Mockito.when(registrationStatusDto.getRegistrationType()).thenReturn("UPDATE"); + Mockito.when(regentity.getRegistrationType()).thenReturn("LOST"); + Mockito.when(registrationStatusDto.getStatusCode()).thenReturn(RegistrationStatusCode.PROCESSED.name()); + Mockito.when(registrationStatusDto.getLatestTransactionTypeCode()) + .thenReturn(RegistrationTransactionTypeCode.UIN_GENERATOR.name()); + Mockito.when(registrationStatusDto.getLatestTransactionStatusCode()) + .thenReturn(RegistrationTransactionStatusCode.PROCESSED.name()); + Mockito.when(smsResponseDto.getStatus()).thenReturn("success"); + Mockito.when(responseDto.getStatus()).thenReturn("success"); + + FieldValue registrationType = new FieldValue(); + registrationType.setLabel("registrationType"); + registrationType.setValue("ACTIVATED"); + List fieldValueList = new ArrayList<>(); + fieldValueList.add(registrationType); + identity.setMetaData(fieldValueList); + packetMetaInfo.setIdentity(identity); + + PowerMockito.mockStatic(JsonUtil.class); + PowerMockito.when(JsonUtil.class, "inputStreamtoJavaObject", inputStream, PacketMetaInfo.class) + .thenReturn(packetMetaInfo); + + MessageDTO dto = new MessageDTO(); + dto.setRid("85425022110000120190117110505"); + MessageDTO result = stage.process(dto); + assertTrue(result.getIsValid()); + } + + @Test + public void testNotificationSentFailureForAllNotificationType() throws Exception { + ReflectionTestUtils.setField(stage, "notificationTypes", "SMS|EMAIL"); + + ResponseWrapper responseWrapper = new ResponseWrapper<>(); + TemplateResponseDto templateResponseDto = new TemplateResponseDto(); + + TemplateDto templateDto = new TemplateDto(); + TemplateDto templateDto1 = new TemplateDto(); + Mockito.when(env.getProperty(any())).thenReturn("RPR_UIN_REAC_SMS").thenReturn("RPR_UIN_REAC_EMAIL") + .thenReturn("RPR_UIN_REAC_EMAIL_SUB"); + templateDto.setTemplateTypeCode("RPR_UIN_REAC_SMS"); + List list = new ArrayList(); + list.add(templateDto); + templateDto1.setTemplateTypeCode("RPR_UIN_REAC_EMAIL"); + list.add(templateDto1); + templateResponseDto.setTemplates(list); + String s = templateResponseDto.toString(); + responseWrapper.setResponse(templateResponseDto); + responseWrapper.setErrors(null); + Mockito.when(restClientService.getApi(any(), any(), anyString(), any(), any())).thenReturn(responseWrapper); + Mockito.when(mapper.writeValueAsString(any())).thenReturn(s); + Mockito.when(mapper.readValue(anyString(), any(Class.class))).thenReturn(templateResponseDto); + Mockito.when(registrationStatusService.getRegistrationStatus(any(),any(),any(), any())).thenReturn(registrationStatusDto); + Mockito.when(registrationStatusDto.getRegistrationType()).thenReturn("UPDATE"); + Mockito.when(regentity.getRegistrationType()).thenReturn("LOST"); + Mockito.when(registrationStatusDto.getStatusCode()).thenReturn(RegistrationStatusCode.PROCESSED.name()); + Mockito.when(registrationStatusDto.getLatestTransactionTypeCode()) + .thenReturn(RegistrationTransactionTypeCode.UIN_GENERATOR.name()); + Mockito.when(registrationStatusDto.getLatestTransactionStatusCode()) + .thenReturn(RegistrationTransactionStatusCode.PROCESSED.name()); + Mockito.when(smsResponseDto.getStatus()).thenReturn("failed"); + Mockito.when(responseDto.getStatus()).thenReturn("failed"); + + FieldValue registrationType = new FieldValue(); + registrationType.setLabel("registrationType"); + registrationType.setValue("ACTIVATED"); + List fieldValueList = new ArrayList<>(); + fieldValueList.add(registrationType); + identity.setMetaData(fieldValueList); + packetMetaInfo.setIdentity(identity); + + PowerMockito.mockStatic(JsonUtil.class); + PowerMockito.when(JsonUtil.class, "inputStreamtoJavaObject", inputStream, PacketMetaInfo.class) + .thenReturn(packetMetaInfo); + + MessageDTO dto = new MessageDTO(); + dto.setRid("85425022110000120190117110505"); + MessageDTO result = stage.process(dto); + assertFalse(result.getIsValid()); + + } + + @Test + public void testNotificationSentFailureForOneNotificationType() throws Exception { + ReflectionTestUtils.setField(stage, "notificationTypes", "SMS|EMAIL"); + + ResponseWrapper responseWrapper = new ResponseWrapper<>(); + TemplateResponseDto templateResponseDto = new TemplateResponseDto(); + + TemplateDto templateDto = new TemplateDto(); + TemplateDto templateDto1 = new TemplateDto(); + Mockito.when(env.getProperty(any())).thenReturn("RPR_UIN_REAC_SMS").thenReturn("RPR_UIN_REAC_EMAIL") + .thenReturn("RPR_UIN_REAC_EMAIL_SUB"); + templateDto.setTemplateTypeCode("RPR_UIN_REAC_SMS"); + List list = new ArrayList(); + list.add(templateDto); + templateDto1.setTemplateTypeCode("RPR_UIN_REAC_EMAIL"); + list.add(templateDto1); + templateResponseDto.setTemplates(list); + String s = templateResponseDto.toString(); + responseWrapper.setResponse(templateResponseDto); + responseWrapper.setErrors(null); + Mockito.when(restClientService.getApi(any(), any(), anyString(), any(), any())).thenReturn(responseWrapper); + Mockito.when(mapper.writeValueAsString(any())).thenReturn(s); + Mockito.when(mapper.readValue(anyString(), any(Class.class))).thenReturn(templateResponseDto); + Mockito.when(registrationStatusService.getRegistrationStatus(any(),any(),any(), any())).thenReturn(registrationStatusDto); + Mockito.when(registrationStatusDto.getRegistrationType()).thenReturn("UPDATE"); + Mockito.when(regentity.getRegistrationType()).thenReturn("UPDATE"); + Mockito.when(registrationStatusDto.getStatusCode()).thenReturn(RegistrationStatusCode.PROCESSED.name()); + Mockito.when(registrationStatusDto.getLatestTransactionTypeCode()) + .thenReturn(RegistrationTransactionTypeCode.UIN_GENERATOR.name()); + Mockito.when(registrationStatusDto.getLatestTransactionStatusCode()) + .thenReturn(RegistrationTransactionStatusCode.PROCESSED.name()); + Mockito.when(smsResponseDto.getStatus()).thenReturn("failed"); + Mockito.when(responseDto.getStatus()).thenReturn("success"); + + FieldValue registrationType = new FieldValue(); + registrationType.setLabel("registrationType"); + registrationType.setValue("ACTIVATED"); + List fieldValueList = new ArrayList<>(); + fieldValueList.add(registrationType); + identity.setMetaData(fieldValueList); + packetMetaInfo.setIdentity(identity); + + PowerMockito.mockStatic(JsonUtil.class); + PowerMockito.when(JsonUtil.class, "inputStreamtoJavaObject", inputStream, PacketMetaInfo.class) + .thenReturn(packetMetaInfo); + + MessageDTO dto = new MessageDTO(); + dto.setRid("85425022110000120190117110505"); + MessageDTO result = stage.process(dto); + assertFalse(result.getIsValid()); + + } + + + @Test + public void testNotificationSentSuccessForOneNotificationType() throws Exception { + ReflectionTestUtils.setField(stage, "notificationTypes", "SMS"); + + ResponseWrapper responseWrapper = new ResponseWrapper<>(); + TemplateResponseDto templateResponseDto = new TemplateResponseDto(); + + TemplateDto templateDto = new TemplateDto(); + TemplateDto templateDto1 = new TemplateDto(); + Mockito.when(env.getProperty(any())).thenReturn("RPR_UIN_REAC_SMS").thenReturn("RPR_UIN_REAC_EMAIL") + .thenReturn("RPR_UIN_REAC_EMAIL_SUB"); + templateDto.setTemplateTypeCode("RPR_UIN_REAC_SMS"); + List list = new ArrayList(); + list.add(templateDto); + templateDto1.setTemplateTypeCode("RPR_UIN_REAC_EMAIL"); + list.add(templateDto1); + templateResponseDto.setTemplates(list); + String s = templateResponseDto.toString(); + responseWrapper.setResponse(templateResponseDto); + responseWrapper.setErrors(null); + Mockito.when(restClientService.getApi(any(), any(), anyString(), any(), any())).thenReturn(responseWrapper); + Mockito.when(mapper.writeValueAsString(any())).thenReturn(s); + Mockito.when(mapper.readValue(anyString(), any(Class.class))).thenReturn(templateResponseDto); + Mockito.when(registrationStatusService.getRegistrationStatus(any(),any(),any(), any())).thenReturn(registrationStatusDto); + Mockito.when(registrationStatusDto.getRegistrationType()).thenReturn("ACTIVATED"); + Mockito.when(regentity.getRegistrationType()).thenReturn("ACTIVATED"); + Mockito.when(registrationStatusDto.getStatusCode()).thenReturn(RegistrationStatusCode.PROCESSED.name()); + Mockito.when(registrationStatusDto.getLatestTransactionTypeCode()) + .thenReturn(RegistrationTransactionTypeCode.UIN_GENERATOR.name()); + Mockito.when(registrationStatusDto.getLatestTransactionStatusCode()) + .thenReturn(RegistrationTransactionStatusCode.PROCESSED.name()); + Mockito.when(smsResponseDto.getStatus()).thenReturn("success"); + + FieldValue registrationType = new FieldValue(); + registrationType.setLabel("registrationType"); + registrationType.setValue("ACTIVATED"); + List fieldValueList = new ArrayList<>(); + fieldValueList.add(registrationType); + identity.setMetaData(fieldValueList); + packetMetaInfo.setIdentity(identity); + + PowerMockito.mockStatic(JsonUtil.class); + PowerMockito.when(JsonUtil.class, "inputStreamtoJavaObject", inputStream, PacketMetaInfo.class) + .thenReturn(packetMetaInfo); + + MessageDTO dto = new MessageDTO(); + dto.setRid("85425022110000120190117110505"); + MessageDTO result = stage.process(dto); + assertTrue(result.getIsValid()); + } + @SuppressWarnings("unchecked") + @Test + public void testMessageUpdateEmailIdNotFoundException() throws Exception { + ResponseWrapper responseWrapper = new ResponseWrapper<>(); + TemplateResponseDto templateResponseDto = new TemplateResponseDto(); + + TemplateDto templateDto = new TemplateDto(); + TemplateDto templateDto1 = new TemplateDto(); + Mockito.when(env.getProperty(any())).thenReturn("RPR_LOST_UIN_SMS").thenReturn("RPR_LOST_UIN_EMAIL") + .thenReturn("RPR_UIN_GEN_EMAIL_SUB"); + templateDto.setTemplateTypeCode("RPR_LOST_UIN_SMS"); + List list = new ArrayList(); + list.add(templateDto); + templateDto1.setTemplateTypeCode("RPR_LOST_UIN_EMAIL"); + list.add(templateDto1); + templateResponseDto.setTemplates(list); + String s = templateResponseDto.toString(); + responseWrapper.setResponse(templateResponseDto); + responseWrapper.setErrors(null); + Mockito.when(restClientService.getApi(any(), any(), anyString(), any(), any())).thenReturn(responseWrapper); + Mockito.when(mapper.writeValueAsString(any())).thenReturn(s); + Mockito.when(mapper.readValue(anyString(), any(Class.class))).thenReturn(templateResponseDto); + Mockito.when(registrationStatusService.getRegistrationStatus(any(),any(),any(), any())).thenReturn(registrationStatusDto); + Mockito.when(registrationStatusDto.getStatusCode()).thenReturn(RegistrationStatusCode.PROCESSED.name()); + Mockito.when(registrationStatusDto.getLatestTransactionTypeCode()) + .thenReturn(RegistrationTransactionTypeCode.UIN_GENERATOR.name()); + Mockito.when(registrationStatusDto.getRegistrationType()).thenReturn("LOST"); + Mockito.when(regentity.getRegistrationType()).thenReturn("LOST"); + Mockito.when(registrationStatusDto.getLatestTransactionStatusCode()) + .thenReturn(RegistrationTransactionStatusCode.PROCESSED.name()); + EmailIdNotFoundException e = new EmailIdNotFoundException(); + Mockito.doReturn("success").when(smsResponseDto).getStatus(); + Mockito.doReturn("success").when(responseDto).getStatus(); + Mockito.doThrow(e).when(service).sendEmailNotification(any(), any(), any(), any(), any(), any(), any(), any(), any()); + + MessageDTO dto = new MessageDTO(); + dto.setRid("85425022110000120190117110505"); + MessageDTO result = stage.process(dto); + assertFalse(result.getIsValid()); + } + @SuppressWarnings("unchecked") + @Test + public void testMessageUpdatePhoneNumberNotFoundException() throws Exception { + ResponseWrapper responseWrapper = new ResponseWrapper<>(); + TemplateResponseDto templateResponseDto = new TemplateResponseDto(); + + TemplateDto templateDto = new TemplateDto(); + TemplateDto templateDto1 = new TemplateDto(); + Mockito.when(env.getProperty(any())).thenReturn("RPR_LOST_UIN_SMS").thenReturn("RPR_LOST_UIN_EMAIL") + .thenReturn("RPR_UIN_GEN_EMAIL_SUB"); + templateDto.setTemplateTypeCode("RPR_LOST_UIN_SMS"); + List list = new ArrayList(); + list.add(templateDto); + templateDto1.setTemplateTypeCode("RPR_LOST_UIN_EMAIL"); + list.add(templateDto1); + templateResponseDto.setTemplates(list); + String s = templateResponseDto.toString(); + responseWrapper.setResponse(templateResponseDto); + responseWrapper.setErrors(null); + Mockito.when(restClientService.getApi(any(), any(), anyString(), any(), any())).thenReturn(responseWrapper); + Mockito.when(mapper.writeValueAsString(any())).thenReturn(s); + Mockito.when(mapper.readValue(anyString(), any(Class.class))).thenReturn(templateResponseDto); + Mockito.when(registrationStatusService.getRegistrationStatus(any(),any(),any(), any())).thenReturn(registrationStatusDto); + Mockito.when(registrationStatusDto.getStatusCode()).thenReturn(RegistrationStatusCode.PROCESSED.name()); + Mockito.when(registrationStatusDto.getLatestTransactionTypeCode()) + .thenReturn(RegistrationTransactionTypeCode.UIN_GENERATOR.name()); + Mockito.when(registrationStatusDto.getRegistrationType()).thenReturn("LOST"); + Mockito.when(registrationStatusDto.getLatestTransactionStatusCode()) + .thenReturn(RegistrationTransactionStatusCode.PROCESSED.name()); + PhoneNumberNotFoundException e = new PhoneNumberNotFoundException(); + Mockito.doThrow(e).when(service).sendSmsNotification(any(), any(), any(), any(), any(), any()); + + MessageDTO dto = new MessageDTO(); + dto.setRid("85425022110000120190117110505"); + MessageDTO result = stage.process(dto); + assertFalse(result.getIsValid()); + } +} diff --git a/registration-processor/post-processor/registration-processor-printing-stage/src/test/java/io/mosip/registrationprocessor/print/stage/test/PrintingStageTest.java b/registration-processor/post-processor/registration-processor-printing-stage/src/test/java/io/mosip/registrationprocessor/print/stage/test/PrintingStageTest.java index 3b2e248a6bb..d2834b019e0 100644 --- a/registration-processor/post-processor/registration-processor-printing-stage/src/test/java/io/mosip/registrationprocessor/print/stage/test/PrintingStageTest.java +++ b/registration-processor/post-processor/registration-processor-printing-stage/src/test/java/io/mosip/registrationprocessor/print/stage/test/PrintingStageTest.java @@ -1,429 +1,442 @@ -package io.mosip.registrationprocessor.print.stage.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.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.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.print.stage.PrintingStage; -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 PrintingStageTest { - - @Mock - private AuditLogRequestBuilder auditLogRequestBuilder; - - @Mock - MosipRouter router; - - @Mock - protected PropertiesUtil propertiesUtil; - - @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 PrintingStage stage = new PrintingStage() { - @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 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.printing.server.port")).thenReturn("8099"); - - ReflectionTestUtils.setField(stage, "workerPoolSize", 10); - ReflectionTestUtils.setField(stage, "messageExpiryTimeLimit", Long.valueOf(0)); - ReflectionTestUtils.setField(stage, "clusterManagerUrl", "/dummyPath"); - ReflectionTestUtils.setField(stage, "busOutHaltAddresses", Arrays.asList()); - System.setProperty("server.port", "8099"); - - //ReflectionTestUtils.setField(stage, "port", "8080"); - ReflectionTestUtils.setField(stage, "encrypt", false); - 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.retrieveUIN(any())).thenReturn(jsonObject); - - - - } - - @Test - public void testAll() throws Exception { - testDeployVerticle(); - testStart(); - testPrintStageSuccess(); - testPrintStageFailure(); - } - - 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); - - 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(), any(), any(), any(), any(), any(MediaType.class))) - .thenReturn(responseWrapper); - - MessageDTO result = stage.process(dto); - assertFalse(result.getIsValid()); - assertFalse(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.retrieveUIN(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.print.stage.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.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.print.stage.PrintingStage; +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 PrintingStageTest { + + @Mock + private AuditLogRequestBuilder auditLogRequestBuilder; + + @Mock + MosipRouter router; + + @Mock + protected PropertiesUtil propertiesUtil; + + @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 PrintingStage stage = new PrintingStage() { + @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.printing.server.port")).thenReturn("8099"); + + ReflectionTestUtils.setField(stage, "workerPoolSize", 10); + ReflectionTestUtils.setField(stage, "messageExpiryTimeLimit", Long.valueOf(0)); + ReflectionTestUtils.setField(stage, "clusterManagerUrl", "/dummyPath"); + ReflectionTestUtils.setField(stage, "busOutHaltAddresses", Arrays.asList()); + System.setProperty("server.port", "8099"); + + //ReflectionTestUtils.setField(stage, "port", "8080"); + ReflectionTestUtils.setField(stage, "encrypt", false); + 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.retrieveUIN(any())).thenReturn(jsonObject); + + + + } + + @Test + public void testAll() throws Exception { + testDeployVerticle(); + testStart(); + testPrintStageSuccess(); + testPrintStageFailure(); + } + + 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); + + 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(), any(), any(), any(), any(), any(MediaType.class))) + .thenReturn(responseWrapper); + + MessageDTO result = stage.process(dto); + assertFalse(result.getIsValid()); + assertFalse(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.retrieveUIN(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-cmd-validator-stage/src/test/java/io/mosip/registration/processor/cmdvalidator/CMDValidatorStageTest.java b/registration-processor/pre-processor/registration-processor-cmd-validator-stage/src/test/java/io/mosip/registration/processor/cmdvalidator/CMDValidatorStageTest.java index 95702e1c0aa..deb338826c0 100644 --- a/registration-processor/pre-processor/registration-processor-cmd-validator-stage/src/test/java/io/mosip/registration/processor/cmdvalidator/CMDValidatorStageTest.java +++ b/registration-processor/pre-processor/registration-processor-cmd-validator-stage/src/test/java/io/mosip/registration/processor/cmdvalidator/CMDValidatorStageTest.java @@ -1,116 +1,129 @@ -package io.mosip.registration.processor.cmdvalidator; - -import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.any; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; -import org.springframework.test.util.ReflectionTestUtils; - -import io.mosip.registration.processor.core.abstractverticle.EventDTO; -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.spi.eventbus.EventHandler; -import io.mosip.registration.processor.stages.app.CMDValidationProcessor; -import io.mosip.registration.processor.stages.app.CMDValidatorStage; -import io.vertx.core.AsyncResult; -import io.vertx.core.Handler; -import io.vertx.core.Vertx; -import io.vertx.ext.web.Router; - -@RunWith(MockitoJUnitRunner.class) -public class CMDValidatorStageTest { - - MessageDTO dto = new MessageDTO(); - - @Mock - private CMDValidationProcessor cmdValidationProcessor; - - @Mock - private MosipRouter router; - @Mock - MosipEventBus mosipEventBus; - - @InjectMocks - private CMDValidatorStage cmdValidatorStage = new CMDValidatorStage() { - @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 Integer getPort() { - return 8080; - }; - - @Override - public void consumeAndSend(MosipEventBus eventbus, MessageBusAddress addressbus1, - MessageBusAddress addressbus2, long messageExpiryTimeLimit) { - } - - @Override - public Router postUrl(Vertx vertx, MessageBusAddress consumeAddress, MessageBusAddress sendAddress) { - return null; - - } - @Override - public void createServer(Router router, int port) { - - } - }; - - @Test - public void testStart() - { - Mockito.doNothing().when(router).setRoute(any()); - cmdValidatorStage.start(); - } - - @Test - public void testDeployVerticle() { - - ReflectionTestUtils.setField(cmdValidatorStage, "workerPoolSize", 10); - ReflectionTestUtils.setField(cmdValidatorStage, "clusterManagerUrl", "/dummyPath"); - ReflectionTestUtils.setField(cmdValidatorStage, "messageExpiryTimeLimit", Long.valueOf(0)); - cmdValidatorStage.deployVerticle(); - } - - @Test - public void testProcess() { - MessageDTO result = new MessageDTO(); - result.setIsValid(true); - Mockito.when(cmdValidationProcessor.process(any(), any())).thenReturn(result); - dto = cmdValidatorStage.process(dto); - assertTrue(dto.getIsValid()); - - } - -} +package io.mosip.registration.processor.cmdvalidator; + +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; +import org.springframework.test.util.ReflectionTestUtils; + +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.spi.eventbus.EventHandler; +import io.mosip.registration.processor.stages.app.CMDValidationProcessor; +import io.mosip.registration.processor.stages.app.CMDValidatorStage; +import io.vertx.core.AsyncResult; +import io.vertx.core.Handler; +import io.vertx.core.Vertx; +import io.vertx.ext.web.Router; + +@RunWith(MockitoJUnitRunner.class) +public class CMDValidatorStageTest { + + MessageDTO dto = new MessageDTO(); + + @Mock + private CMDValidationProcessor cmdValidationProcessor; + + @Mock + private MosipRouter router; + @Mock + MosipEventBus mosipEventBus; + + @InjectMocks + private CMDValidatorStage cmdValidatorStage = new CMDValidatorStage() { + @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 Integer getPort() { + return 8080; + }; + + @Override + public void consumeAndSend(MosipEventBus eventbus, MessageBusAddress addressbus1, + MessageBusAddress addressbus2, long messageExpiryTimeLimit) { + } + + @Override + public Router postUrl(Vertx vertx, MessageBusAddress consumeAddress, MessageBusAddress sendAddress) { + return null; + + } + @Override + public void createServer(Router router, int port) { + + } + }; + + @Test + public void testStart() + { + Mockito.doNothing().when(router).setRoute(any()); + cmdValidatorStage.start(); + } + + @Test + public void testDeployVerticle() { + + ReflectionTestUtils.setField(cmdValidatorStage, "workerPoolSize", 10); + ReflectionTestUtils.setField(cmdValidatorStage, "clusterManagerUrl", "/dummyPath"); + ReflectionTestUtils.setField(cmdValidatorStage, "messageExpiryTimeLimit", Long.valueOf(0)); + cmdValidatorStage.deployVerticle(); + } + + @Test + public void testProcess() { + MessageDTO result = new MessageDTO(); + result.setIsValid(true); + Mockito.when(cmdValidationProcessor.process(any(), any())).thenReturn(result); + dto = cmdValidatorStage.process(dto); + assertTrue(dto.getIsValid()); + + } + +} diff --git a/registration-processor/pre-processor/registration-processor-introducer-validator-stage/src/test/java/io/mosip/registration/processor/app/IntroducerValidatorStageTest.java b/registration-processor/pre-processor/registration-processor-introducer-validator-stage/src/test/java/io/mosip/registration/processor/app/IntroducerValidatorStageTest.java index 92bd39faa34..9093e611834 100644 --- a/registration-processor/pre-processor/registration-processor-introducer-validator-stage/src/test/java/io/mosip/registration/processor/app/IntroducerValidatorStageTest.java +++ b/registration-processor/pre-processor/registration-processor-introducer-validator-stage/src/test/java/io/mosip/registration/processor/app/IntroducerValidatorStageTest.java @@ -1,116 +1,129 @@ -package io.mosip.registration.processor.app; - -import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.any; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; -import org.springframework.test.util.ReflectionTestUtils; - -import io.mosip.registration.processor.core.abstractverticle.EventDTO; -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.spi.eventbus.EventHandler; -import io.mosip.registration.processor.stages.introducervalidator.IntroducerValidationProcessor; -import io.mosip.registration.processor.stages.introducervalidator.IntroducerValidatorStage; -import io.vertx.core.AsyncResult; -import io.vertx.core.Handler; -import io.vertx.core.Vertx; -import io.vertx.ext.web.Router; - -@RunWith(MockitoJUnitRunner.class) -public class IntroducerValidatorStageTest { - - MessageDTO dto = new MessageDTO(); - - @Mock - private IntroducerValidationProcessor introducerValidationProcessor; - - @Mock - private MosipRouter router; - @Mock - MosipEventBus mosipEventBus; - - @InjectMocks - private IntroducerValidatorStage introducerValidatorStage = new IntroducerValidatorStage() { - @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 Integer getPort() { - return 8080; - }; - - @Override - public void consumeAndSend(MosipEventBus eventbus, MessageBusAddress addressbus1, MessageBusAddress addressbus2, - long messageExpiryTimeLimit) { - } - - @Override - public Router postUrl(Vertx vertx, MessageBusAddress consumeAddress, MessageBusAddress sendAddress) { - return null; - - } - - @Override - public void createServer(Router router, int port) { - - } - }; - - @Test - public void testStart() { - Mockito.doNothing().when(router).setRoute(any()); - introducerValidatorStage.start(); - } - - @Test - public void testDeployVerticle() { - - ReflectionTestUtils.setField(introducerValidatorStage, "workerPoolSize", 10); - ReflectionTestUtils.setField(introducerValidatorStage, "clusterManagerUrl", "/dummyPath"); - ReflectionTestUtils.setField(introducerValidatorStage, "messageExpiryTimeLimit", Long.valueOf(0)); - introducerValidatorStage.deployVerticle(); - } - - @Test - public void testProcess() { - MessageDTO result = new MessageDTO(); - result.setIsValid(true); - Mockito.when(introducerValidationProcessor.process(any(), any())).thenReturn(result); - dto = introducerValidatorStage.process(dto); - assertTrue(dto.getIsValid()); - - } - -} +package io.mosip.registration.processor.app; + +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; +import org.springframework.test.util.ReflectionTestUtils; + +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.spi.eventbus.EventHandler; +import io.mosip.registration.processor.stages.introducervalidator.IntroducerValidationProcessor; +import io.mosip.registration.processor.stages.introducervalidator.IntroducerValidatorStage; +import io.vertx.core.AsyncResult; +import io.vertx.core.Handler; +import io.vertx.core.Vertx; +import io.vertx.ext.web.Router; + +@RunWith(MockitoJUnitRunner.class) +public class IntroducerValidatorStageTest { + + MessageDTO dto = new MessageDTO(); + + @Mock + private IntroducerValidationProcessor introducerValidationProcessor; + + @Mock + private MosipRouter router; + @Mock + MosipEventBus mosipEventBus; + + @InjectMocks + private IntroducerValidatorStage introducerValidatorStage = new IntroducerValidatorStage() { + @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 Integer getPort() { + return 8080; + }; + + @Override + public void consumeAndSend(MosipEventBus eventbus, MessageBusAddress addressbus1, MessageBusAddress addressbus2, + long messageExpiryTimeLimit) { + } + + @Override + public Router postUrl(Vertx vertx, MessageBusAddress consumeAddress, MessageBusAddress sendAddress) { + return null; + + } + + @Override + public void createServer(Router router, int port) { + + } + }; + + @Test + public void testStart() { + Mockito.doNothing().when(router).setRoute(any()); + introducerValidatorStage.start(); + } + + @Test + public void testDeployVerticle() { + + ReflectionTestUtils.setField(introducerValidatorStage, "workerPoolSize", 10); + ReflectionTestUtils.setField(introducerValidatorStage, "clusterManagerUrl", "/dummyPath"); + ReflectionTestUtils.setField(introducerValidatorStage, "messageExpiryTimeLimit", Long.valueOf(0)); + introducerValidatorStage.deployVerticle(); + } + + @Test + public void testProcess() { + MessageDTO result = new MessageDTO(); + result.setIsValid(true); + Mockito.when(introducerValidationProcessor.process(any(), any())).thenReturn(result); + dto = introducerValidatorStage.process(dto); + assertTrue(dto.getIsValid()); + + } + +} diff --git a/registration-processor/pre-processor/registration-processor-operator-validator-stage/src/test/java/io/mosip/registration/processor/app/OperatorValidatorStageTest.java b/registration-processor/pre-processor/registration-processor-operator-validator-stage/src/test/java/io/mosip/registration/processor/app/OperatorValidatorStageTest.java index e3e479d372c..98fd953eb11 100644 --- a/registration-processor/pre-processor/registration-processor-operator-validator-stage/src/test/java/io/mosip/registration/processor/app/OperatorValidatorStageTest.java +++ b/registration-processor/pre-processor/registration-processor-operator-validator-stage/src/test/java/io/mosip/registration/processor/app/OperatorValidatorStageTest.java @@ -1,116 +1,129 @@ -package io.mosip.registration.processor.app; - -import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.any; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; -import org.springframework.test.util.ReflectionTestUtils; - -import io.mosip.registration.processor.core.abstractverticle.EventDTO; -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.spi.eventbus.EventHandler; -import io.mosip.registration.processor.stages.operatorvalidator.OperatorValidationProcessor; -import io.mosip.registration.processor.stages.operatorvalidator.OperatorValidatorStage; -import io.vertx.core.AsyncResult; -import io.vertx.core.Handler; -import io.vertx.core.Vertx; -import io.vertx.ext.web.Router; - -@RunWith(MockitoJUnitRunner.class) -public class OperatorValidatorStageTest { - - MessageDTO dto = new MessageDTO(); - - @Mock - private OperatorValidationProcessor operatorValidationProcessor; - - @Mock - private MosipRouter router; - @Mock - MosipEventBus mosipEventBus; - - @InjectMocks - private OperatorValidatorStage operatorValidatorStage = new OperatorValidatorStage() { - @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 Integer getPort() { - return 8080; - }; - - @Override - public void consumeAndSend(MosipEventBus eventbus, MessageBusAddress addressbus1, MessageBusAddress addressbus2, - long messageExpiryTimeLimit) { - } - - @Override - public Router postUrl(Vertx vertx, MessageBusAddress consumeAddress, MessageBusAddress sendAddress) { - return null; - - } - - @Override - public void createServer(Router router, int port) { - - } - }; - - @Test - public void testStart() { - Mockito.doNothing().when(router).setRoute(any()); - operatorValidatorStage.start(); - } - - @Test - public void testDeployVerticle() { - - ReflectionTestUtils.setField(operatorValidatorStage, "workerPoolSize", 10); - ReflectionTestUtils.setField(operatorValidatorStage, "clusterManagerUrl", "/dummyPath"); - ReflectionTestUtils.setField(operatorValidatorStage, "messageExpiryTimeLimit", Long.valueOf(0)); - operatorValidatorStage.deployVerticle(); - } - - @Test - public void testProcess() { - MessageDTO result = new MessageDTO(); - result.setIsValid(true); - Mockito.when(operatorValidationProcessor.process(any(), any())).thenReturn(result); - dto = operatorValidatorStage.process(dto); - assertTrue(dto.getIsValid()); - - } - -} +package io.mosip.registration.processor.app; + +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; +import org.springframework.test.util.ReflectionTestUtils; + +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.spi.eventbus.EventHandler; +import io.mosip.registration.processor.stages.operatorvalidator.OperatorValidationProcessor; +import io.mosip.registration.processor.stages.operatorvalidator.OperatorValidatorStage; +import io.vertx.core.AsyncResult; +import io.vertx.core.Handler; +import io.vertx.core.Vertx; +import io.vertx.ext.web.Router; + +@RunWith(MockitoJUnitRunner.class) +public class OperatorValidatorStageTest { + + MessageDTO dto = new MessageDTO(); + + @Mock + private OperatorValidationProcessor operatorValidationProcessor; + + @Mock + private MosipRouter router; + @Mock + MosipEventBus mosipEventBus; + + @InjectMocks + private OperatorValidatorStage operatorValidatorStage = new OperatorValidatorStage() { + @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 Integer getPort() { + return 8080; + }; + + @Override + public void consumeAndSend(MosipEventBus eventbus, MessageBusAddress addressbus1, MessageBusAddress addressbus2, + long messageExpiryTimeLimit) { + } + + @Override + public Router postUrl(Vertx vertx, MessageBusAddress consumeAddress, MessageBusAddress sendAddress) { + return null; + + } + + @Override + public void createServer(Router router, int port) { + + } + }; + + @Test + public void testStart() { + Mockito.doNothing().when(router).setRoute(any()); + operatorValidatorStage.start(); + } + + @Test + public void testDeployVerticle() { + + ReflectionTestUtils.setField(operatorValidatorStage, "workerPoolSize", 10); + ReflectionTestUtils.setField(operatorValidatorStage, "clusterManagerUrl", "/dummyPath"); + ReflectionTestUtils.setField(operatorValidatorStage, "messageExpiryTimeLimit", Long.valueOf(0)); + operatorValidatorStage.deployVerticle(); + } + + @Test + public void testProcess() { + MessageDTO result = new MessageDTO(); + result.setIsValid(true); + Mockito.when(operatorValidationProcessor.process(any(), any())).thenReturn(result); + dto = operatorValidatorStage.process(dto); + assertTrue(dto.getIsValid()); + + } + +} diff --git a/registration-processor/pre-processor/registration-processor-packet-classifier-stage/src/test/java/io/mosip/registration/processor/stages/packetclassifier/PacketClassifierStageTest.java b/registration-processor/pre-processor/registration-processor-packet-classifier-stage/src/test/java/io/mosip/registration/processor/stages/packetclassifier/PacketClassifierStageTest.java index ee0b3cb43cf..bad17fbb155 100644 --- a/registration-processor/pre-processor/registration-processor-packet-classifier-stage/src/test/java/io/mosip/registration/processor/stages/packetclassifier/PacketClassifierStageTest.java +++ b/registration-processor/pre-processor/registration-processor-packet-classifier-stage/src/test/java/io/mosip/registration/processor/stages/packetclassifier/PacketClassifierStageTest.java @@ -1,7 +1,7 @@ package io.mosip.registration.processor.stages.packetclassifier; import static org.junit.Assert.assertTrue; -import static org.mockito.Matchers.any; +import static org.mockito.ArgumentMatchers.any; import org.junit.Test; import org.junit.runner.RunWith; @@ -12,6 +12,7 @@ import org.springframework.test.util.ReflectionTestUtils; 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; @@ -61,6 +62,18 @@ public void consumeAndSend(MessageBusAddress fromAddress, MessageBusAddress toAd @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 + + } }; } diff --git a/registration-processor/pre-processor/registration-processor-packet-uploader-stage/src/test/java/io/mosip/registration/processor/packet/uploader/stage/test/PacketUploaderStageTest.java b/registration-processor/pre-processor/registration-processor-packet-uploader-stage/src/test/java/io/mosip/registration/processor/packet/uploader/stage/test/PacketUploaderStageTest.java index 9ca51c0f827..e21de2a459f 100644 --- a/registration-processor/pre-processor/registration-processor-packet-uploader-stage/src/test/java/io/mosip/registration/processor/packet/uploader/stage/test/PacketUploaderStageTest.java +++ b/registration-processor/pre-processor/registration-processor-packet-uploader-stage/src/test/java/io/mosip/registration/processor/packet/uploader/stage/test/PacketUploaderStageTest.java @@ -1,154 +1,133 @@ -package io.mosip.registration.processor.packet.uploader.stage.test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anyString; -import static org.mockito.Mockito.when; - -import java.io.IOException; -import java.io.InputStream; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.apache.http.HttpResponse; -import org.apache.http.client.ClientProtocolException; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.entity.StringEntity; -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.impl.client.HttpClients; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.springframework.test.context.TestPropertySource; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.util.ReflectionTestUtils; - -import io.mosip.registration.processor.core.abstractverticle.EventDTO; -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.spi.eventbus.EventHandler; -import io.mosip.registration.processor.packet.uploader.service.PacketUploaderService; -import io.mosip.registration.processor.packet.uploader.stage.PacketUploaderStage; -import io.vertx.core.AsyncResult; -import io.vertx.core.Handler; -import io.vertx.core.MultiMap; -import io.vertx.core.Vertx; -import io.vertx.core.buffer.Buffer; -import io.vertx.core.http.HttpMethod; -import io.vertx.core.http.HttpServerRequest; -import io.vertx.core.http.HttpServerResponse; -import io.vertx.core.json.JsonArray; -import io.vertx.core.json.JsonObject; -import io.vertx.ext.auth.User; -import io.vertx.ext.web.Cookie; -import io.vertx.ext.web.FileUpload; -import io.vertx.ext.web.Locale; -import io.vertx.ext.web.ParsedHeaderValues; -import io.vertx.ext.web.Route; -import io.vertx.ext.web.Router; -import io.vertx.ext.web.RoutingContext; -import io.vertx.ext.web.Session; -/** - * The Class PacketUploaderJobTest. - * @author Rishabh Keshari - */ -@RunWith(SpringRunner.class) -public class PacketUploaderStageTest { - MessageDTO dto = new MessageDTO(); - @Mock - private PacketUploaderService packetUploaderService; - - @Mock - private MosipRouter router; - @Mock - MosipEventBus mosipEventBus; - @InjectMocks - private PacketUploaderStage packetValidatorStage = new PacketUploaderStage() { - @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 consumeAndSend(MosipEventBus eventbus, MessageBusAddress addressbus1, - MessageBusAddress addressbus2, long messageExpiryTimeLimit) { - } - - @Override - public Router postUrl(Vertx vertx, MessageBusAddress consumeAddress, MessageBusAddress sendAddress) { - return null; - - } - @Override - public void createServer(Router router, int port) { - - } - - @Override - public Integer getPort() { - return 8080; - }; - }; - @Test - public void testStart() - { - Mockito.doNothing().when(router).setRoute(any()); - packetValidatorStage.start(); - } - - /** - * Test deploy verticle. - */ - @Test - public void testDeployVerticle() { - - ReflectionTestUtils.setField(packetValidatorStage, "workerPoolSize", 10); - ReflectionTestUtils.setField(packetValidatorStage, "clusterManagerUrl", "/dummyPath"); - ReflectionTestUtils.setField(packetValidatorStage, "messageExpiryTimeLimit", Long.valueOf(0)); - packetValidatorStage.deployVerticle(); - } - - @Test - public void testProcess() { - MessageDTO result = new MessageDTO(); - result.setIsValid(true); - Mockito.when(packetUploaderService.validateAndUploadPacket(any(), any())).thenReturn(result); - dto = packetValidatorStage.process(dto); - assertTrue(dto.getIsValid()); - - } -} +package io.mosip.registration.processor.packet.uploader.stage.test; + +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.util.ReflectionTestUtils; + +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.spi.eventbus.EventHandler; +import io.mosip.registration.processor.packet.uploader.service.PacketUploaderService; +import io.mosip.registration.processor.packet.uploader.stage.PacketUploaderStage; +import io.vertx.core.AsyncResult; +import io.vertx.core.Handler; +import io.vertx.core.Vertx; +import io.vertx.ext.web.Router; +/** + * The Class PacketUploaderJobTest. + * @author Rishabh Keshari + */ +@RunWith(SpringRunner.class) +public class PacketUploaderStageTest { + MessageDTO dto = new MessageDTO(); + @Mock + private PacketUploaderService packetUploaderService; + + @Mock + private MosipRouter router; + @Mock + MosipEventBus mosipEventBus; + @InjectMocks + private PacketUploaderStage packetValidatorStage = new PacketUploaderStage() { + @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 consumeAndSend(MosipEventBus eventbus, MessageBusAddress addressbus1, + MessageBusAddress addressbus2, long messageExpiryTimeLimit) { + } + + @Override + public Router postUrl(Vertx vertx, MessageBusAddress consumeAddress, MessageBusAddress sendAddress) { + return null; + + } + @Override + public void createServer(Router router, int port) { + + } + + @Override + public Integer getPort() { + return 8080; + }; + }; + @Test + public void testStart() + { + Mockito.doNothing().when(router).setRoute(any()); + packetValidatorStage.start(); + } + + /** + * Test deploy verticle. + */ + @Test + public void testDeployVerticle() { + + ReflectionTestUtils.setField(packetValidatorStage, "workerPoolSize", 10); + ReflectionTestUtils.setField(packetValidatorStage, "clusterManagerUrl", "/dummyPath"); + ReflectionTestUtils.setField(packetValidatorStage, "messageExpiryTimeLimit", Long.valueOf(0)); + packetValidatorStage.deployVerticle(); + } + + @Test + public void testProcess() { + MessageDTO result = new MessageDTO(); + result.setIsValid(true); + Mockito.when(packetUploaderService.validateAndUploadPacket(any(), any())).thenReturn(result); + dto = packetValidatorStage.process(dto); + assertTrue(dto.getIsValid()); + + } +} diff --git a/registration-processor/pre-processor/registration-processor-packet-validator-stage/src/test/java/io/mosip/registration/processor/stages/packet/validator/PacketValidatorStageTest.java b/registration-processor/pre-processor/registration-processor-packet-validator-stage/src/test/java/io/mosip/registration/processor/stages/packet/validator/PacketValidatorStageTest.java index cfcbe79c206..9fe399f9120 100644 --- a/registration-processor/pre-processor/registration-processor-packet-validator-stage/src/test/java/io/mosip/registration/processor/stages/packet/validator/PacketValidatorStageTest.java +++ b/registration-processor/pre-processor/registration-processor-packet-validator-stage/src/test/java/io/mosip/registration/processor/stages/packet/validator/PacketValidatorStageTest.java @@ -12,6 +12,7 @@ import org.springframework.test.util.ReflectionTestUtils; 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; @@ -62,6 +63,18 @@ public void consumeAndSend(MessageBusAddress fromAddress, MessageBusAddress toAd 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 + + } }; } 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 1ffe4f276fb..7c3dbc180e6 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 @@ -1,573 +1,586 @@ -package io.mosip.registration.processor.quality.qualifier.stage.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.atLeastOnce; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.apache.commons.io.IOUtils; -import org.json.simple.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.ArgumentCaptor; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.modules.junit4.PowerMockRunner; -import org.powermock.reflect.Whitebox; -import org.springframework.test.util.ReflectionTestUtils; - -import io.mosip.kernel.biometrics.constant.BiometricFunction; -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.biosdk.provider.factory.BioAPIFactory; -import io.mosip.kernel.core.bioapi.exception.BiometricException; -import io.mosip.kernel.core.util.exception.JsonProcessingException; -import io.mosip.registration.processor.core.abstractverticle.EventDTO; -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.RegistrationExceptionTypeCode; -import io.mosip.registration.processor.core.exception.ApisResourceAccessException; -import io.mosip.registration.processor.core.exception.PacketManagerException; -import io.mosip.registration.processor.core.spi.eventbus.EventHandler; -import io.mosip.registration.processor.core.util.JsonUtil; -import io.mosip.registration.processor.core.util.RegistrationExceptionMapperUtil; -import io.mosip.registration.processor.packet.storage.utils.PacketManagerService; -import io.mosip.registration.processor.packet.storage.utils.PriorityBasedPacketManagerService; -import io.mosip.registration.processor.packet.storage.utils.Utilities; -import io.mosip.registration.processor.quality.classifier.stage.QualityClassifierStage; -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.vertx.core.AsyncResult; -import io.vertx.core.Handler; -import io.vertx.core.Vertx; -import io.mosip.kernel.biosdk.provider.spi.iBioProviderApi; - -@RunWith(PowerMockRunner.class) -@PowerMockIgnore({ "javax.management.*", "javax.net.ssl.*", "com.sun.org.apache.xerces.*", "javax.xml.*", - "org.xml.*", }) -public class QualityClassifierStageTest { - - @Mock - private AuditLogRequestBuilder auditLogRequestBuilder; - - @Mock - private RegistrationExceptionMapperUtil registrationStatusMapperUtil; - - @Mock - private RegistrationStatusService registrationStatusService; - - private InternalRegistrationStatusDto registrationStatusDto; - - @Mock - private Utilities utility; - - @Mock - private PriorityBasedPacketManagerService basedPacketManagerService; - - /** The cbeff util. */ - @Mock - private CbeffUtil cbeffUtil; - - @Mock - private BioAPIFactory bioApiFactory; - @Mock - private iBioProviderApi faceIBioProviderApi; - @Mock - private iBioProviderApi fingerIBioProviderApi; - @Mock - private iBioProviderApi irisIBioProviderApi; - - @Mock - private PacketManagerService packetManagerService; - - private String qualityPrefixTag = "Biometric_Quality-"; - - private String AVERAGE = "Average"; - - private String POOR = "Poor"; - - private String GOOD = "Good"; - -// - JSONObject mappingJSONObject; - - @InjectMocks - private QualityClassifierStage qualityClassifierStage = new QualityClassifierStage() { - @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 Integer getPort() { - return 8080; - }; - - @Override - public void consumeAndSend(MosipEventBus mosipEventBus, MessageBusAddress fromAddress, - MessageBusAddress toAddress, long messageExpiryTimeLimit) { - } - }; - - @Before - public void setUp() throws Exception { - ReflectionTestUtils.setField(qualityClassifierStage, "workerPoolSize", 10); - ReflectionTestUtils.setField(qualityClassifierStage, "clusterManagerUrl", "/dummyPath"); - ReflectionTestUtils.setField(qualityClassifierStage, "messageExpiryTimeLimit", Long.valueOf(0)); -// ReflectionTestUtils.setField(qualityClassifierStage, "irisThreshold", 70); -// ReflectionTestUtils.setField(qualityClassifierStage, "leftFingerThreshold", 80); -// ReflectionTestUtils.setField(qualityClassifierStage, "rightFingerThreshold", 80); -// ReflectionTestUtils.setField(qualityClassifierStage, "thumbFingerThreshold", 80); -// ReflectionTestUtils.setField(qualityClassifierStage, "faceThreshold", 25); - ReflectionTestUtils.setField(qualityClassifierStage, "qualityTagPrefix", qualityPrefixTag); - - Map qualityClassificationRangeMap = new HashMap(); - qualityClassificationRangeMap.put(POOR, "0-29"); - qualityClassificationRangeMap.put(AVERAGE, "30-69"); - qualityClassificationRangeMap.put(GOOD, "70-100"); - - ReflectionTestUtils.setField(qualityClassifierStage, "qualityClassificationRangeMap", - qualityClassificationRangeMap); - - Map parsedMap = new HashMap(); - parsedMap.put(POOR, new int[] { 0, 29 }); - parsedMap.put(AVERAGE, new int[] { 30, 69 }); - parsedMap.put(GOOD, new int[] { 70, 100 }); - - ReflectionTestUtils.setField(qualityClassifierStage, "parsedQualityRangeMap", parsedMap); - ReflectionTestUtils.setField(qualityClassifierStage, "modalities", Arrays.asList("Iris", "Finger", "Face")); - - registrationStatusDto = new InternalRegistrationStatusDto(); - registrationStatusDto.setRegistrationId("123456789"); - Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); - Mockito.doNothing().when(registrationStatusService).updateRegistrationStatus(any(), any(), any()); - String idJsonString = "{\n" + " \"identity\" : {\n" + " \"fullName\" : [ {\n" - + " \"language\" : \"eng\",\n" + " \"value\" : \"Ragavendran V\"\n" + " }, {\n" - + " \"language\" : \"ara\",\n" + " \"value\" : \"قشلشرثىيقشى ر\"\n" + " } ],\n" - + " \"individualBiometrics\" : {\n" + " \"format\" : \"cbeff\",\n" - + " \"version\" : 1.0,\n" + " \"value\" : \"applicant_bio_CBEFF\"\n" + " }\n" + " }\n" - + "}"; - InputStream idJsonStream = IOUtils.toInputStream(idJsonString, "UTF-8"); - - Mockito.when(utility.getGetRegProcessorDemographicIdentity()).thenReturn("identity"); - - ClassLoader classLoader = getClass().getClassLoader(); - File cbeff1 = new File(classLoader.getResource("CBEFF1.xml").getFile()); - InputStream cbeff1Stream = new FileInputStream(cbeff1); - - List birTypeList = new ArrayList<>(); - BIR birType1 = new BIR.BIRBuilder().build(); - io.mosip.kernel.biometrics.entities.BDBInfo bdbInfoType1 = new io.mosip.kernel.biometrics.entities.BDBInfo.BDBInfoBuilder() - .build(); - io.mosip.kernel.biometrics.entities.RegistryIDType registryIDType = new io.mosip.kernel.biometrics.entities.RegistryIDType(); - registryIDType.setOrganization("Mosip"); - registryIDType.setType("257"); - io.mosip.kernel.biometrics.constant.QualityType quality = new io.mosip.kernel.biometrics.constant.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); - - BIR birType2 = new BIR.BIRBuilder().build(); - io.mosip.kernel.biometrics.entities.BDBInfo bdbInfoType2 = new io.mosip.kernel.biometrics.entities.BDBInfo.BDBInfoBuilder() - .build(); - bdbInfoType2.setQuality(quality); - BiometricType singleType2 = BiometricType.FINGER; - List singleTypeList2 = new ArrayList<>(); - singleTypeList2.add(singleType2); - List subtype2 = new ArrayList<>(Arrays.asList("Right", "RingFinger")); - bdbInfoType2.setSubtype(subtype2); - bdbInfoType2.setType(singleTypeList2); - birType2.setBdbInfo(bdbInfoType2); - birTypeList.add(birType2); - - BIR birType3 = new BIR.BIRBuilder().build(); - io.mosip.kernel.biometrics.entities.BDBInfo bdbInfoType3 = new io.mosip.kernel.biometrics.entities.BDBInfo.BDBInfoBuilder() - .build(); - bdbInfoType3.setQuality(quality); - BiometricType singleType3 = BiometricType.IRIS; - List singleTypeList3 = new ArrayList<>(); - singleTypeList3.add(singleType3); - List subtype3 = new ArrayList<>(Arrays.asList("Right")); - bdbInfoType3.setSubtype(subtype3); - bdbInfoType3.setType(singleTypeList3); - birType3.setBdbInfo(bdbInfoType3); - birTypeList.add(birType3); - - BIR birType4 = new BIR.BIRBuilder().build(); - io.mosip.kernel.biometrics.entities.BDBInfo bdbInfoType4 = new io.mosip.kernel.biometrics.entities.BDBInfo.BDBInfoBuilder() - .build(); - bdbInfoType4.setQuality(quality); - BiometricType singleType4 = BiometricType.FACE; - List singleTypeList4 = new ArrayList<>(); - singleTypeList4.add(singleType4); - List subtype4 = new ArrayList<>(); - bdbInfoType4.setSubtype(subtype4); - bdbInfoType4.setType(singleTypeList4); - birType4.setBdbInfo(bdbInfoType4); - birTypeList.add(birType4); - - BiometricRecord biometricRecord = new BiometricRecord(); - biometricRecord.setSegments(birTypeList); - when(basedPacketManagerService.getBiometricsByMappingJsonKey(any(), any(), any(), any())) - .thenReturn(biometricRecord); - when(basedPacketManagerService.getFieldByMappingJsonKey(any(), any(), any(), any())) - .thenReturn("individualBiometrics"); -// Mockito.doNothing().when(packetManagerService).addOrUpdateTags(any(), any()); - - File file = new File(classLoader.getResource("RegistrationProcessorIdentity.json").getFile()); - InputStream inputStream = new FileInputStream(file); - String mappingJson = IOUtils.toString(inputStream); - mappingJSONObject = JsonUtil.objectMapperReadValue(mappingJson, JSONObject.class); - Mockito.when(utility.getRegistrationProcessorMappingJson(anyString())) - .thenReturn(JsonUtil.getJSONObject(mappingJSONObject, "identity")); - Mockito.when(bioApiFactory.getBioProvider(any(), any())).thenReturn(faceIBioProviderApi); - Mockito.when(bioApiFactory.getBioProvider(BiometricType.FACE, BiometricFunction.QUALITY_CHECK)) - .thenReturn(faceIBioProviderApi); - Mockito.when(bioApiFactory.getBioProvider(BiometricType.FINGER, BiometricFunction.QUALITY_CHECK)) - .thenReturn(fingerIBioProviderApi); - Mockito.when(bioApiFactory.getBioProvider(BiometricType.IRIS, BiometricFunction.QUALITY_CHECK)) - .thenReturn(irisIBioProviderApi); - float[] scores = new float[1]; - scores[0] = 100; - Mockito.when(faceIBioProviderApi.getSegmentQuality(any(), any())).thenReturn(scores); - - } - - @Test - public void testDeployVerticle() { - qualityClassifierStage.deployVerticle(); - } - - @Test - public void testQualityClassifierMixTags() throws Exception { - - Whitebox.invokeMethod(qualityClassifierStage, "generateParsedQualityRangeMap"); - when(basedPacketManagerService.getBiometricsByMappingJsonKey(any(), any(), any(), any())) - .thenReturn(getMockBiometricRecord()); - - mockScores(40, 20, 98); - - MessageDTO dto = new MessageDTO(); - dto.setRid("1234567890"); - MessageDTO result = qualityClassifierStage.process(dto); - - assertTrue(result.getIsValid()); - - ArgumentCaptor> argument = ArgumentCaptor.forClass(Map.class); - - verify(packetManagerService, atLeastOnce()).addOrUpdateTags(any(), argument.capture()); - - assertQualityTags(argument.getAllValues().get(0), AVERAGE, POOR, GOOD); - - } - - @Test - public void testQualityClassifierAllGoodTags() throws ApisResourceAccessException, IOException, - PacketManagerException, JsonProcessingException, BiometricException { - - when(basedPacketManagerService.getBiometricsByMappingJsonKey(any(), any(), any(), any())) - .thenReturn(getMockBiometricRecord()); - - mockScores(90, 94, 98); - - MessageDTO dto = new MessageDTO(); - dto.setRid("1234567890"); - MessageDTO result = qualityClassifierStage.process(dto); - - assertTrue(result.getIsValid()); - - ArgumentCaptor> argument = ArgumentCaptor.forClass(Map.class); - - verify(packetManagerService, atLeastOnce()).addOrUpdateTags(any(), argument.capture()); - - assertQualityTags(argument.getAllValues().get(0), GOOD, GOOD, GOOD); - - } - - private void assertQualityTags(Map qualityTags, String irisClassification, - String fingerClassification, String faceClassification) { - - assertTrue(qualityTags.get(qualityPrefixTag + BiometricType.FACE.value()).equalsIgnoreCase(faceClassification)); - assertTrue(qualityTags.get(qualityPrefixTag + BiometricType.FINGER.value()) - .equalsIgnoreCase(fingerClassification)); - assertTrue(qualityTags.get(qualityPrefixTag + BiometricType.IRIS.value()).equalsIgnoreCase(irisClassification)); - } - - private void mockScores(float irisScore, float fingerScore, float faceScore) { - float[] faceScores = new float[1]; - faceScores[0] = faceScore; - Mockito.when(faceIBioProviderApi.getSegmentQuality(any(), any())).thenReturn(faceScores); - - float[] irisScores = new float[1]; - irisScores[0] = irisScore; - Mockito.when(irisIBioProviderApi.getSegmentQuality(any(), any())).thenReturn(irisScores); - - float[] fingerScores = new float[1]; - fingerScores[0] = fingerScore; - Mockito.when(fingerIBioProviderApi.getSegmentQuality(any(), any())).thenReturn(fingerScores); - } - - private BiometricRecord getMockBiometricRecord() { - List birTypeList = new ArrayList<>(); - BIR birType1 = new BIR.BIRBuilder().build(); - io.mosip.kernel.biometrics.entities.BDBInfo bdbInfoType1 = new io.mosip.kernel.biometrics.entities.BDBInfo.BDBInfoBuilder() - .build(); - 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); - - BIR birType2 = new BIR.BIRBuilder().build(); - io.mosip.kernel.biometrics.entities.BDBInfo bdbInfoType2 = new io.mosip.kernel.biometrics.entities.BDBInfo.BDBInfoBuilder() - .build(); - bdbInfoType2.setQuality(quality); - BiometricType singleType2 = BiometricType.FINGER; - List singleTypeList2 = new ArrayList<>(); - singleTypeList2.add(singleType2); - List subtype2 = new ArrayList<>(Arrays.asList("Right", "RingFinger")); - bdbInfoType2.setSubtype(subtype2); - bdbInfoType2.setType(singleTypeList2); - birType2.setBdbInfo(bdbInfoType2); - birTypeList.add(birType2); - - BIR birType3 = new BIR.BIRBuilder().build(); - BDBInfo bdbInfoType3 = new BDBInfo.BDBInfoBuilder().build(); - bdbInfoType3.setQuality(quality); - BiometricType singleType3 = BiometricType.IRIS; - List singleTypeList3 = new ArrayList<>(); - singleTypeList3.add(singleType3); - List subtype3 = new ArrayList<>(Arrays.asList("Right")); - bdbInfoType3.setSubtype(subtype3); - bdbInfoType3.setType(singleTypeList3); - birType3.setBdbInfo(bdbInfoType3); - birTypeList.add(birType3); - - BIR birType4 = new BIR.BIRBuilder().build(); - BDBInfo bdbInfoType4 = new BDBInfo.BDBInfoBuilder().build(); - bdbInfoType4.setQuality(quality); - BiometricType singleType4 = BiometricType.FACE; - List singleTypeList4 = new ArrayList<>(); - singleTypeList4.add(singleType4); - List subtype4 = new ArrayList<>(); - bdbInfoType4.setSubtype(subtype4); - bdbInfoType4.setType(singleTypeList4); - birType4.setBdbInfo(bdbInfoType4); - birTypeList.add(birType4); - - BiometricRecord biometricRecord = new BiometricRecord(); - biometricRecord.setSegments(birTypeList); - return biometricRecord; - } - - @Test - public void testException() throws Exception { - when(basedPacketManagerService.getBiometricsByMappingJsonKey(any(), any(), any(), any())) - .thenThrow(new PacketManagerException("code", "message")); - Mockito.when(registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.PACKET_MANAGER_EXCEPTION)) - .thenReturn("REPROCESS"); - MessageDTO dto = new MessageDTO(); - dto.setRid("1234567890"); - MessageDTO messageDTO = qualityClassifierStage.process(dto); - assertTrue(messageDTO.getIsValid()); - assertTrue(messageDTO.getInternalError()); - } - - @Test - public void testCbeffNotFound() - throws IOException, PacketManagerException, JsonProcessingException, ApisResourceAccessException { - when(basedPacketManagerService.getBiometricsByMappingJsonKey(any(), any(), any(), any())) - .thenThrow(new IOException("message")); - Mockito.when(registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.IOEXCEPTION)) - .thenReturn("ERROR"); - MessageDTO dto = new MessageDTO(); - dto.setRid("1234567890"); - MessageDTO messageDTO = qualityClassifierStage.process(dto); - assertFalse(messageDTO.getIsValid()); - assertTrue(messageDTO.getInternalError()); - } - - @Test - public void testApiNotAccessibleTest() - throws ApisResourceAccessException, IOException, PacketManagerException, JsonProcessingException { - when(basedPacketManagerService.getBiometricsByMappingJsonKey(any(), any(), any(), any())) - .thenThrow(new ApisResourceAccessException("message")); - Mockito.when(registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.APIS_RESOURCE_ACCESS_EXCEPTION)) - .thenReturn("REPROCESS"); - MessageDTO dto = new MessageDTO(); - dto.setRid("1234567890"); - MessageDTO messageDTO = qualityClassifierStage.process(dto); - assertTrue(messageDTO.getIsValid()); - assertTrue(messageDTO.getInternalError()); - } - - - @Test - public void testFileNameMissing() - throws IOException, ApisResourceAccessException, PacketManagerException, JsonProcessingException { - when(basedPacketManagerService.getBiometricsByMappingJsonKey(any(), any(), any(), any())).thenReturn(null) - .thenReturn(null); - when(registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.BIOMETRIC_EXCEPTION)) - .thenReturn("REPROCESS"); - MessageDTO dto = new MessageDTO(); - dto.setRid("1234567890"); - MessageDTO result = qualityClassifierStage.process(dto); - - assertTrue(result.getIsValid()); - assertTrue(result.getInternalError()); - } - - @Test - public void testBiometricException() throws BiometricException { - Mockito.when(bioApiFactory.getBioProvider(any(), any())) - .thenThrow(new BiometricException("", "error from provider")); - Mockito.when(registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.BIOMETRIC_EXCEPTION)) - .thenReturn("REPROCESS"); - MessageDTO dto = new MessageDTO(); - dto.setRid("1234567890"); - MessageDTO result = qualityClassifierStage.process(dto); - - assertTrue(result.getIsValid()); - assertTrue(result.getInternalError()); - } - - @Test - public void testQualityCheckfailureException() throws BiometricException { - Mockito.when(bioApiFactory.getBioProvider(any(), any())).thenReturn(null); - when(registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.EXCEPTION)) - .thenReturn("ERROR"); - MessageDTO dto = new MessageDTO(); - dto.setRid("1234567890"); - MessageDTO result = qualityClassifierStage.process(dto); - - assertFalse(result.getIsValid()); - assertTrue(result.getInternalError()); - } - - @Test - public void testFileMissing() - throws ApisResourceAccessException, IOException, PacketManagerException, JsonProcessingException { - Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); - when(basedPacketManagerService.getBiometricsByMappingJsonKey(anyString(), any(), any(), any())) - .thenReturn(null); - when(registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.BIOMETRIC_EXCEPTION)) - .thenReturn("REPROCESS"); - MessageDTO dto = new MessageDTO(); - dto.setRid("1234567890"); - MessageDTO result = qualityClassifierStage.process(dto); - - assertTrue(result.getIsValid()); - assertTrue(result.getInternalError()); - } - - @Test - public void testBioetricFileNotPresentInIdObject() - throws ApisResourceAccessException, IOException, PacketManagerException, JsonProcessingException { - - when(basedPacketManagerService.getFieldByMappingJsonKey(any(), any(), any(), any())).thenReturn(null); - - MessageDTO dto = new MessageDTO(); - dto.setRid("1234567890"); - MessageDTO result = qualityClassifierStage.process(dto); - - assertFalse(result.getInternalError()); - assertTrue(result.getIsValid()); - } - - @Test - public void testNoBiometricInPacket() - throws ApisResourceAccessException, IOException, PacketManagerException, JsonProcessingException { - - when(basedPacketManagerService.getBiometricsByMappingJsonKey(any(), any(), any(), any())).thenReturn(null); - when(registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.BIOMETRIC_EXCEPTION)) - .thenReturn("REPROCESS"); - MessageDTO dto = new MessageDTO(); - dto.setRid("1234567890"); - MessageDTO result = qualityClassifierStage.process(dto); - assertTrue(result.getInternalError()); - assertTrue(result.getIsValid()); - } - - @Test - public void testJsonProcessingException() - throws ApisResourceAccessException, IOException, PacketManagerException, JsonProcessingException { - when(basedPacketManagerService.getBiometricsByMappingJsonKey(any(), any(), any(), any())) - .thenThrow(new JsonProcessingException("Json exception")); - Mockito.when(registrationStatusService.getRegistrationStatus(anyString(), any(), any(), any())).thenReturn(registrationStatusDto); - when(registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.JSON_PROCESSING_EXCEPTION)) - .thenReturn("ERROR"); - MessageDTO dto = new MessageDTO(); - dto.setRid("1234567890"); - MessageDTO result = qualityClassifierStage.process(dto); - assertFalse(result.getIsValid()); - assertTrue(result.getInternalError()); - } - -} +package io.mosip.registration.processor.quality.qualifier.stage.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.atLeastOnce; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.commons.io.IOUtils; +import org.json.simple.JSONObject; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.modules.junit4.PowerMockRunner; +import org.powermock.reflect.Whitebox; +import org.springframework.test.util.ReflectionTestUtils; + +import io.mosip.kernel.biometrics.constant.BiometricFunction; +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.biosdk.provider.factory.BioAPIFactory; +import io.mosip.kernel.biosdk.provider.spi.iBioProviderApi; +import io.mosip.kernel.core.bioapi.exception.BiometricException; +import io.mosip.kernel.core.util.exception.JsonProcessingException; +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.RegistrationExceptionTypeCode; +import io.mosip.registration.processor.core.exception.ApisResourceAccessException; +import io.mosip.registration.processor.core.exception.PacketManagerException; +import io.mosip.registration.processor.core.spi.eventbus.EventHandler; +import io.mosip.registration.processor.core.util.JsonUtil; +import io.mosip.registration.processor.core.util.RegistrationExceptionMapperUtil; +import io.mosip.registration.processor.packet.storage.utils.PacketManagerService; +import io.mosip.registration.processor.packet.storage.utils.PriorityBasedPacketManagerService; +import io.mosip.registration.processor.packet.storage.utils.Utilities; +import io.mosip.registration.processor.quality.classifier.stage.QualityClassifierStage; +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.vertx.core.AsyncResult; +import io.vertx.core.Handler; +import io.vertx.core.Vertx; + +@RunWith(PowerMockRunner.class) +@PowerMockIgnore({ "javax.management.*", "javax.net.ssl.*", "com.sun.org.apache.xerces.*", "javax.xml.*", + "org.xml.*", }) +public class QualityClassifierStageTest { + + @Mock + private AuditLogRequestBuilder auditLogRequestBuilder; + + @Mock + private RegistrationExceptionMapperUtil registrationStatusMapperUtil; + + @Mock + private RegistrationStatusService registrationStatusService; + + private InternalRegistrationStatusDto registrationStatusDto; + + @Mock + private Utilities utility; + + @Mock + private PriorityBasedPacketManagerService basedPacketManagerService; + + /** The cbeff util. */ + @Mock + private CbeffUtil cbeffUtil; + + @Mock + private BioAPIFactory bioApiFactory; + @Mock + private iBioProviderApi faceIBioProviderApi; + @Mock + private iBioProviderApi fingerIBioProviderApi; + @Mock + private iBioProviderApi irisIBioProviderApi; + + @Mock + private PacketManagerService packetManagerService; + + private String qualityPrefixTag = "Biometric_Quality-"; + + private String AVERAGE = "Average"; + + private String POOR = "Poor"; + + private String GOOD = "Good"; + +// + JSONObject mappingJSONObject; + + @InjectMocks + private QualityClassifierStage qualityClassifierStage = new QualityClassifierStage() { + @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 Integer getPort() { + return 8080; + }; + + @Override + public void consumeAndSend(MosipEventBus mosipEventBus, MessageBusAddress fromAddress, + MessageBusAddress toAddress, long messageExpiryTimeLimit) { + } + }; + + @Before + public void setUp() throws Exception { + ReflectionTestUtils.setField(qualityClassifierStage, "workerPoolSize", 10); + ReflectionTestUtils.setField(qualityClassifierStage, "clusterManagerUrl", "/dummyPath"); + ReflectionTestUtils.setField(qualityClassifierStage, "messageExpiryTimeLimit", Long.valueOf(0)); +// ReflectionTestUtils.setField(qualityClassifierStage, "irisThreshold", 70); +// ReflectionTestUtils.setField(qualityClassifierStage, "leftFingerThreshold", 80); +// ReflectionTestUtils.setField(qualityClassifierStage, "rightFingerThreshold", 80); +// ReflectionTestUtils.setField(qualityClassifierStage, "thumbFingerThreshold", 80); +// ReflectionTestUtils.setField(qualityClassifierStage, "faceThreshold", 25); + ReflectionTestUtils.setField(qualityClassifierStage, "qualityTagPrefix", qualityPrefixTag); + + Map qualityClassificationRangeMap = new HashMap(); + qualityClassificationRangeMap.put(POOR, "0-29"); + qualityClassificationRangeMap.put(AVERAGE, "30-69"); + qualityClassificationRangeMap.put(GOOD, "70-100"); + + ReflectionTestUtils.setField(qualityClassifierStage, "qualityClassificationRangeMap", + qualityClassificationRangeMap); + + Map parsedMap = new HashMap(); + parsedMap.put(POOR, new int[] { 0, 29 }); + parsedMap.put(AVERAGE, new int[] { 30, 69 }); + parsedMap.put(GOOD, new int[] { 70, 100 }); + + ReflectionTestUtils.setField(qualityClassifierStage, "parsedQualityRangeMap", parsedMap); + ReflectionTestUtils.setField(qualityClassifierStage, "modalities", Arrays.asList("Iris", "Finger", "Face")); + + registrationStatusDto = new InternalRegistrationStatusDto(); + registrationStatusDto.setRegistrationId("123456789"); + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); + Mockito.doNothing().when(registrationStatusService).updateRegistrationStatus(any(), any(), any()); + String idJsonString = "{\n" + " \"identity\" : {\n" + " \"fullName\" : [ {\n" + + " \"language\" : \"eng\",\n" + " \"value\" : \"Ragavendran V\"\n" + " }, {\n" + + " \"language\" : \"ara\",\n" + " \"value\" : \"قشلشرثىيقشى ر\"\n" + " } ],\n" + + " \"individualBiometrics\" : {\n" + " \"format\" : \"cbeff\",\n" + + " \"version\" : 1.0,\n" + " \"value\" : \"applicant_bio_CBEFF\"\n" + " }\n" + " }\n" + + "}"; + InputStream idJsonStream = IOUtils.toInputStream(idJsonString, "UTF-8"); + + Mockito.when(utility.getGetRegProcessorDemographicIdentity()).thenReturn("identity"); + + ClassLoader classLoader = getClass().getClassLoader(); + File cbeff1 = new File(classLoader.getResource("CBEFF1.xml").getFile()); + InputStream cbeff1Stream = new FileInputStream(cbeff1); + + List birTypeList = new ArrayList<>(); + BIR birType1 = new BIR.BIRBuilder().build(); + io.mosip.kernel.biometrics.entities.BDBInfo bdbInfoType1 = new io.mosip.kernel.biometrics.entities.BDBInfo.BDBInfoBuilder() + .build(); + io.mosip.kernel.biometrics.entities.RegistryIDType registryIDType = new io.mosip.kernel.biometrics.entities.RegistryIDType(); + registryIDType.setOrganization("Mosip"); + registryIDType.setType("257"); + io.mosip.kernel.biometrics.constant.QualityType quality = new io.mosip.kernel.biometrics.constant.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); + + BIR birType2 = new BIR.BIRBuilder().build(); + io.mosip.kernel.biometrics.entities.BDBInfo bdbInfoType2 = new io.mosip.kernel.biometrics.entities.BDBInfo.BDBInfoBuilder() + .build(); + bdbInfoType2.setQuality(quality); + BiometricType singleType2 = BiometricType.FINGER; + List singleTypeList2 = new ArrayList<>(); + singleTypeList2.add(singleType2); + List subtype2 = new ArrayList<>(Arrays.asList("Right", "RingFinger")); + bdbInfoType2.setSubtype(subtype2); + bdbInfoType2.setType(singleTypeList2); + birType2.setBdbInfo(bdbInfoType2); + birTypeList.add(birType2); + + BIR birType3 = new BIR.BIRBuilder().build(); + io.mosip.kernel.biometrics.entities.BDBInfo bdbInfoType3 = new io.mosip.kernel.biometrics.entities.BDBInfo.BDBInfoBuilder() + .build(); + bdbInfoType3.setQuality(quality); + BiometricType singleType3 = BiometricType.IRIS; + List singleTypeList3 = new ArrayList<>(); + singleTypeList3.add(singleType3); + List subtype3 = new ArrayList<>(Arrays.asList("Right")); + bdbInfoType3.setSubtype(subtype3); + bdbInfoType3.setType(singleTypeList3); + birType3.setBdbInfo(bdbInfoType3); + birTypeList.add(birType3); + + BIR birType4 = new BIR.BIRBuilder().build(); + io.mosip.kernel.biometrics.entities.BDBInfo bdbInfoType4 = new io.mosip.kernel.biometrics.entities.BDBInfo.BDBInfoBuilder() + .build(); + bdbInfoType4.setQuality(quality); + BiometricType singleType4 = BiometricType.FACE; + List singleTypeList4 = new ArrayList<>(); + singleTypeList4.add(singleType4); + List subtype4 = new ArrayList<>(); + bdbInfoType4.setSubtype(subtype4); + bdbInfoType4.setType(singleTypeList4); + birType4.setBdbInfo(bdbInfoType4); + birTypeList.add(birType4); + + BiometricRecord biometricRecord = new BiometricRecord(); + biometricRecord.setSegments(birTypeList); + when(basedPacketManagerService.getBiometricsByMappingJsonKey(any(), any(), any(), any())) + .thenReturn(biometricRecord); + when(basedPacketManagerService.getFieldByMappingJsonKey(any(), any(), any(), any())) + .thenReturn("individualBiometrics"); +// Mockito.doNothing().when(packetManagerService).addOrUpdateTags(any(), any()); + + File file = new File(classLoader.getResource("RegistrationProcessorIdentity.json").getFile()); + InputStream inputStream = new FileInputStream(file); + String mappingJson = IOUtils.toString(inputStream); + mappingJSONObject = JsonUtil.objectMapperReadValue(mappingJson, JSONObject.class); + Mockito.when(utility.getRegistrationProcessorMappingJson(anyString())) + .thenReturn(JsonUtil.getJSONObject(mappingJSONObject, "identity")); + Mockito.when(bioApiFactory.getBioProvider(any(), any())).thenReturn(faceIBioProviderApi); + Mockito.when(bioApiFactory.getBioProvider(BiometricType.FACE, BiometricFunction.QUALITY_CHECK)) + .thenReturn(faceIBioProviderApi); + Mockito.when(bioApiFactory.getBioProvider(BiometricType.FINGER, BiometricFunction.QUALITY_CHECK)) + .thenReturn(fingerIBioProviderApi); + Mockito.when(bioApiFactory.getBioProvider(BiometricType.IRIS, BiometricFunction.QUALITY_CHECK)) + .thenReturn(irisIBioProviderApi); + float[] scores = new float[1]; + scores[0] = 100; + Mockito.when(faceIBioProviderApi.getSegmentQuality(any(), any())).thenReturn(scores); + + } + + @Test + public void testDeployVerticle() { + qualityClassifierStage.deployVerticle(); + } + + @Test + public void testQualityClassifierMixTags() throws Exception { + + Whitebox.invokeMethod(qualityClassifierStage, "generateParsedQualityRangeMap"); + when(basedPacketManagerService.getBiometricsByMappingJsonKey(any(), any(), any(), any())) + .thenReturn(getMockBiometricRecord()); + + mockScores(40, 20, 98); + + MessageDTO dto = new MessageDTO(); + dto.setRid("1234567890"); + MessageDTO result = qualityClassifierStage.process(dto); + + assertTrue(result.getIsValid()); + + ArgumentCaptor> argument = ArgumentCaptor.forClass(Map.class); + + verify(packetManagerService, atLeastOnce()).addOrUpdateTags(any(), argument.capture()); + + assertQualityTags(argument.getAllValues().get(0), AVERAGE, POOR, GOOD); + + } + + @Test + public void testQualityClassifierAllGoodTags() throws ApisResourceAccessException, IOException, + PacketManagerException, JsonProcessingException, BiometricException { + + when(basedPacketManagerService.getBiometricsByMappingJsonKey(any(), any(), any(), any())) + .thenReturn(getMockBiometricRecord()); + + mockScores(90, 94, 98); + + MessageDTO dto = new MessageDTO(); + dto.setRid("1234567890"); + MessageDTO result = qualityClassifierStage.process(dto); + + assertTrue(result.getIsValid()); + + ArgumentCaptor> argument = ArgumentCaptor.forClass(Map.class); + + verify(packetManagerService, atLeastOnce()).addOrUpdateTags(any(), argument.capture()); + + assertQualityTags(argument.getAllValues().get(0), GOOD, GOOD, GOOD); + + } + + private void assertQualityTags(Map qualityTags, String irisClassification, + String fingerClassification, String faceClassification) { + + assertTrue(qualityTags.get(qualityPrefixTag + BiometricType.FACE.value()).equalsIgnoreCase(faceClassification)); + assertTrue(qualityTags.get(qualityPrefixTag + BiometricType.FINGER.value()) + .equalsIgnoreCase(fingerClassification)); + assertTrue(qualityTags.get(qualityPrefixTag + BiometricType.IRIS.value()).equalsIgnoreCase(irisClassification)); + } + + private void mockScores(float irisScore, float fingerScore, float faceScore) { + float[] faceScores = new float[1]; + faceScores[0] = faceScore; + Mockito.when(faceIBioProviderApi.getSegmentQuality(any(), any())).thenReturn(faceScores); + + float[] irisScores = new float[1]; + irisScores[0] = irisScore; + Mockito.when(irisIBioProviderApi.getSegmentQuality(any(), any())).thenReturn(irisScores); + + float[] fingerScores = new float[1]; + fingerScores[0] = fingerScore; + Mockito.when(fingerIBioProviderApi.getSegmentQuality(any(), any())).thenReturn(fingerScores); + } + + private BiometricRecord getMockBiometricRecord() { + List birTypeList = new ArrayList<>(); + BIR birType1 = new BIR.BIRBuilder().build(); + io.mosip.kernel.biometrics.entities.BDBInfo bdbInfoType1 = new io.mosip.kernel.biometrics.entities.BDBInfo.BDBInfoBuilder() + .build(); + 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); + + BIR birType2 = new BIR.BIRBuilder().build(); + io.mosip.kernel.biometrics.entities.BDBInfo bdbInfoType2 = new io.mosip.kernel.biometrics.entities.BDBInfo.BDBInfoBuilder() + .build(); + bdbInfoType2.setQuality(quality); + BiometricType singleType2 = BiometricType.FINGER; + List singleTypeList2 = new ArrayList<>(); + singleTypeList2.add(singleType2); + List subtype2 = new ArrayList<>(Arrays.asList("Right", "RingFinger")); + bdbInfoType2.setSubtype(subtype2); + bdbInfoType2.setType(singleTypeList2); + birType2.setBdbInfo(bdbInfoType2); + birTypeList.add(birType2); + + BIR birType3 = new BIR.BIRBuilder().build(); + BDBInfo bdbInfoType3 = new BDBInfo.BDBInfoBuilder().build(); + bdbInfoType3.setQuality(quality); + BiometricType singleType3 = BiometricType.IRIS; + List singleTypeList3 = new ArrayList<>(); + singleTypeList3.add(singleType3); + List subtype3 = new ArrayList<>(Arrays.asList("Right")); + bdbInfoType3.setSubtype(subtype3); + bdbInfoType3.setType(singleTypeList3); + birType3.setBdbInfo(bdbInfoType3); + birTypeList.add(birType3); + + BIR birType4 = new BIR.BIRBuilder().build(); + BDBInfo bdbInfoType4 = new BDBInfo.BDBInfoBuilder().build(); + bdbInfoType4.setQuality(quality); + BiometricType singleType4 = BiometricType.FACE; + List singleTypeList4 = new ArrayList<>(); + singleTypeList4.add(singleType4); + List subtype4 = new ArrayList<>(); + bdbInfoType4.setSubtype(subtype4); + bdbInfoType4.setType(singleTypeList4); + birType4.setBdbInfo(bdbInfoType4); + birTypeList.add(birType4); + + BiometricRecord biometricRecord = new BiometricRecord(); + biometricRecord.setSegments(birTypeList); + return biometricRecord; + } + + @Test + public void testException() throws Exception { + when(basedPacketManagerService.getBiometricsByMappingJsonKey(any(), any(), any(), any())) + .thenThrow(new PacketManagerException("code", "message")); + Mockito.when(registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.PACKET_MANAGER_EXCEPTION)) + .thenReturn("REPROCESS"); + MessageDTO dto = new MessageDTO(); + dto.setRid("1234567890"); + MessageDTO messageDTO = qualityClassifierStage.process(dto); + assertTrue(messageDTO.getIsValid()); + assertTrue(messageDTO.getInternalError()); + } + + @Test + public void testCbeffNotFound() + throws IOException, PacketManagerException, JsonProcessingException, ApisResourceAccessException { + when(basedPacketManagerService.getBiometricsByMappingJsonKey(any(), any(), any(), any())) + .thenThrow(new IOException("message")); + Mockito.when(registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.IOEXCEPTION)) + .thenReturn("ERROR"); + MessageDTO dto = new MessageDTO(); + dto.setRid("1234567890"); + MessageDTO messageDTO = qualityClassifierStage.process(dto); + assertFalse(messageDTO.getIsValid()); + assertTrue(messageDTO.getInternalError()); + } + + @Test + public void testApiNotAccessibleTest() + throws ApisResourceAccessException, IOException, PacketManagerException, JsonProcessingException { + when(basedPacketManagerService.getBiometricsByMappingJsonKey(any(), any(), any(), any())) + .thenThrow(new ApisResourceAccessException("message")); + Mockito.when(registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.APIS_RESOURCE_ACCESS_EXCEPTION)) + .thenReturn("REPROCESS"); + MessageDTO dto = new MessageDTO(); + dto.setRid("1234567890"); + MessageDTO messageDTO = qualityClassifierStage.process(dto); + assertTrue(messageDTO.getIsValid()); + assertTrue(messageDTO.getInternalError()); + } + + + @Test + public void testFileNameMissing() + throws IOException, ApisResourceAccessException, PacketManagerException, JsonProcessingException { + when(basedPacketManagerService.getBiometricsByMappingJsonKey(any(), any(), any(), any())).thenReturn(null) + .thenReturn(null); + when(registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.BIOMETRIC_EXCEPTION)) + .thenReturn("REPROCESS"); + MessageDTO dto = new MessageDTO(); + dto.setRid("1234567890"); + MessageDTO result = qualityClassifierStage.process(dto); + + assertTrue(result.getIsValid()); + assertTrue(result.getInternalError()); + } + + @Test + public void testBiometricException() throws BiometricException { + Mockito.when(bioApiFactory.getBioProvider(any(), any())) + .thenThrow(new BiometricException("", "error from provider")); + Mockito.when(registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.BIOMETRIC_EXCEPTION)) + .thenReturn("REPROCESS"); + MessageDTO dto = new MessageDTO(); + dto.setRid("1234567890"); + MessageDTO result = qualityClassifierStage.process(dto); + + assertTrue(result.getIsValid()); + assertTrue(result.getInternalError()); + } + + @Test + public void testQualityCheckfailureException() throws BiometricException { + Mockito.when(bioApiFactory.getBioProvider(any(), any())).thenReturn(null); + when(registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.EXCEPTION)) + .thenReturn("ERROR"); + MessageDTO dto = new MessageDTO(); + dto.setRid("1234567890"); + MessageDTO result = qualityClassifierStage.process(dto); + + assertFalse(result.getIsValid()); + assertTrue(result.getInternalError()); + } + + @Test + public void testFileMissing() + throws ApisResourceAccessException, IOException, PacketManagerException, JsonProcessingException { + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); + when(basedPacketManagerService.getBiometricsByMappingJsonKey(anyString(), any(), any(), any())) + .thenReturn(null); + when(registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.BIOMETRIC_EXCEPTION)) + .thenReturn("REPROCESS"); + MessageDTO dto = new MessageDTO(); + dto.setRid("1234567890"); + MessageDTO result = qualityClassifierStage.process(dto); + + assertTrue(result.getIsValid()); + assertTrue(result.getInternalError()); + } + + @Test + public void testBioetricFileNotPresentInIdObject() + throws ApisResourceAccessException, IOException, PacketManagerException, JsonProcessingException { + + when(basedPacketManagerService.getFieldByMappingJsonKey(any(), any(), any(), any())).thenReturn(null); + + MessageDTO dto = new MessageDTO(); + dto.setRid("1234567890"); + MessageDTO result = qualityClassifierStage.process(dto); + + assertFalse(result.getInternalError()); + assertTrue(result.getIsValid()); + } + + @Test + public void testNoBiometricInPacket() + throws ApisResourceAccessException, IOException, PacketManagerException, JsonProcessingException { + + when(basedPacketManagerService.getBiometricsByMappingJsonKey(any(), any(), any(), any())).thenReturn(null); + when(registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.BIOMETRIC_EXCEPTION)) + .thenReturn("REPROCESS"); + MessageDTO dto = new MessageDTO(); + dto.setRid("1234567890"); + MessageDTO result = qualityClassifierStage.process(dto); + assertTrue(result.getInternalError()); + assertTrue(result.getIsValid()); + } + + @Test + public void testJsonProcessingException() + throws ApisResourceAccessException, IOException, PacketManagerException, JsonProcessingException { + when(basedPacketManagerService.getBiometricsByMappingJsonKey(any(), any(), any(), any())) + .thenThrow(new JsonProcessingException("Json exception")); + Mockito.when(registrationStatusService.getRegistrationStatus(anyString(), any(), any(), any())).thenReturn(registrationStatusDto); + when(registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.JSON_PROCESSING_EXCEPTION)) + .thenReturn("ERROR"); + MessageDTO dto = new MessageDTO(); + dto.setRid("1234567890"); + MessageDTO result = qualityClassifierStage.process(dto); + assertFalse(result.getIsValid()); + assertTrue(result.getInternalError()); + } + +} diff --git a/registration-processor/pre-processor/registration-processor-supervisor-validator-stage/src/test/java/io/mosip/registration/processor/app/SupervisorValidatorStageTest.java b/registration-processor/pre-processor/registration-processor-supervisor-validator-stage/src/test/java/io/mosip/registration/processor/app/SupervisorValidatorStageTest.java index d009265a5b6..45b59148b98 100644 --- a/registration-processor/pre-processor/registration-processor-supervisor-validator-stage/src/test/java/io/mosip/registration/processor/app/SupervisorValidatorStageTest.java +++ b/registration-processor/pre-processor/registration-processor-supervisor-validator-stage/src/test/java/io/mosip/registration/processor/app/SupervisorValidatorStageTest.java @@ -1,116 +1,129 @@ -package io.mosip.registration.processor.app; - -import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.any; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; -import org.springframework.test.util.ReflectionTestUtils; - -import io.mosip.registration.processor.core.abstractverticle.EventDTO; -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.spi.eventbus.EventHandler; -import io.mosip.registration.processor.stages.supervisorvalidator.SupervisorValidationProcessor; -import io.mosip.registration.processor.stages.supervisorvalidator.SupervisorValidatorStage; -import io.vertx.core.AsyncResult; -import io.vertx.core.Handler; -import io.vertx.core.Vertx; -import io.vertx.ext.web.Router; - -@RunWith(MockitoJUnitRunner.class) -public class SupervisorValidatorStageTest { - - MessageDTO dto = new MessageDTO(); - - @Mock - private SupervisorValidationProcessor supervisorValidationProcessor; - - @Mock - private MosipRouter router; - @Mock - MosipEventBus mosipEventBus; - - @InjectMocks - private SupervisorValidatorStage supervisorValidatorStage = new SupervisorValidatorStage() { - @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 Integer getPort() { - return 8080; - }; - - @Override - public void consumeAndSend(MosipEventBus eventbus, MessageBusAddress addressbus1, MessageBusAddress addressbus2, - long messageExpiryTimeLimit) { - } - - @Override - public Router postUrl(Vertx vertx, MessageBusAddress consumeAddress, MessageBusAddress sendAddress) { - return null; - - } - - @Override - public void createServer(Router router, int port) { - - } - }; - - @Test - public void testStart() { - Mockito.doNothing().when(router).setRoute(any()); - supervisorValidatorStage.start(); - } - - @Test - public void testDeployVerticle() { - - ReflectionTestUtils.setField(supervisorValidatorStage, "workerPoolSize", 10); - ReflectionTestUtils.setField(supervisorValidatorStage, "clusterManagerUrl", "/dummyPath"); - ReflectionTestUtils.setField(supervisorValidatorStage, "messageExpiryTimeLimit", Long.valueOf(0)); - supervisorValidatorStage.deployVerticle(); - } - - @Test - public void testProcess() { - MessageDTO result = new MessageDTO(); - result.setIsValid(true); - Mockito.when(supervisorValidationProcessor.process(any(), any())).thenReturn(result); - dto = supervisorValidatorStage.process(dto); - assertTrue(dto.getIsValid()); - - } - -} +package io.mosip.registration.processor.app; + +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; +import org.springframework.test.util.ReflectionTestUtils; + +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.spi.eventbus.EventHandler; +import io.mosip.registration.processor.stages.supervisorvalidator.SupervisorValidationProcessor; +import io.mosip.registration.processor.stages.supervisorvalidator.SupervisorValidatorStage; +import io.vertx.core.AsyncResult; +import io.vertx.core.Handler; +import io.vertx.core.Vertx; +import io.vertx.ext.web.Router; + +@RunWith(MockitoJUnitRunner.class) +public class SupervisorValidatorStageTest { + + MessageDTO dto = new MessageDTO(); + + @Mock + private SupervisorValidationProcessor supervisorValidationProcessor; + + @Mock + private MosipRouter router; + @Mock + MosipEventBus mosipEventBus; + + @InjectMocks + private SupervisorValidatorStage supervisorValidatorStage = new SupervisorValidatorStage() { + @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 Integer getPort() { + return 8080; + }; + + @Override + public void consumeAndSend(MosipEventBus eventbus, MessageBusAddress addressbus1, MessageBusAddress addressbus2, + long messageExpiryTimeLimit) { + } + + @Override + public Router postUrl(Vertx vertx, MessageBusAddress consumeAddress, MessageBusAddress sendAddress) { + return null; + + } + + @Override + public void createServer(Router router, int port) { + + } + }; + + @Test + public void testStart() { + Mockito.doNothing().when(router).setRoute(any()); + supervisorValidatorStage.start(); + } + + @Test + public void testDeployVerticle() { + + ReflectionTestUtils.setField(supervisorValidatorStage, "workerPoolSize", 10); + ReflectionTestUtils.setField(supervisorValidatorStage, "clusterManagerUrl", "/dummyPath"); + ReflectionTestUtils.setField(supervisorValidatorStage, "messageExpiryTimeLimit", Long.valueOf(0)); + supervisorValidatorStage.deployVerticle(); + } + + @Test + public void testProcess() { + MessageDTO result = new MessageDTO(); + result.setIsValid(true); + Mockito.when(supervisorValidationProcessor.process(any(), any())).thenReturn(result); + dto = supervisorValidatorStage.process(dto); + assertTrue(dto.getIsValid()); + + } + +} diff --git a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/abstractverticle/HealthCheckDTO.java b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/abstractverticle/HealthCheckDTO.java new file mode 100644 index 00000000000..f16ea21aa06 --- /dev/null +++ b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/abstractverticle/HealthCheckDTO.java @@ -0,0 +1,12 @@ +package io.mosip.registration.processor.core.abstractverticle; + +import lombok.Data; + +@Data +public class HealthCheckDTO { + + boolean eventBusConnected; + + String failureReason; + +} \ No newline at end of file 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 193d64c0a61..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,5 +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 senderHealthCheck(Handler eventHandler, String address); } 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 658271c303e..14df2847cb4 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 @@ -1,212 +1,214 @@ -package io.mosip.registration.processor.core.abstractverticle; - -import io.mosip.kernel.core.virusscanner.spi.VirusScanner; -import io.mosip.registration.processor.core.queue.factory.MosipQueue; -import io.mosip.registration.processor.core.spi.queue.MosipQueueConnectionFactory; -import io.mosip.registration.processor.core.spi.queue.MosipQueueManager; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.core.env.Environment; -import org.springframework.util.ClassUtils; - -import com.fasterxml.jackson.databind.ObjectMapper; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; - -import brave.Tracing; -import io.mosip.registration.processor.core.constant.HealthConstant; -import io.mosip.registration.processor.core.tracing.VertxWebTracingLocal; -import io.mosip.registration.processor.core.util.DigitalSignatureUtility; -import io.vertx.core.Handler; -import io.vertx.core.Vertx; -import io.vertx.core.http.HttpServerResponse; -import io.vertx.core.json.Json; -import io.vertx.ext.web.Router; -import io.vertx.ext.web.RoutingContext; -import io.vertx.ext.web.handler.BodyHandler; -import io.vertx.micrometer.PrometheusScrapingHandler; - -/** - * @author Mukul Puspam - * - */ -public abstract class MosipVerticleAPIManager extends MosipVerticleManager { - - @Value("${registration.processor.signature.isEnabled}") - Boolean isEnabled; - - @Autowired - DigitalSignatureUtility digitalSignatureUtility; - - @Autowired - ObjectMapper objectMapper; - - @Autowired - private MosipQueueConnectionFactory mosipConnectionFactory; - - @Autowired - private Tracing tracing; - - @Autowired - private Environment environment; - - @Autowired(required = false) - private VirusScanner virusScanner; - - /** The mosip queue manager. */ - @Autowired - private MosipQueueManager mosipQueueManager; - - private static final String PROMETHEUS_ENDPOINT = "/actuator/prometheus"; - - /** - * This method creates a body handler for the routes - * - * @param vertx - * @return - */ - public Router postUrl(Vertx vertx, MessageBusAddress consumeAddress, MessageBusAddress sendAddress) { - Router router = Router.router(vertx); - - VertxWebTracingLocal vertxWebTracing = VertxWebTracingLocal.create(tracing); - Handler routingContextHandler = vertxWebTracing.routingContextHandler(); - router.route() - .order(-1) //applies before routes - .handler(routingContextHandler) - .failureHandler(routingContextHandler); - - router.route().handler(BodyHandler.create()); - String servletPath = getServletPath(); - router.get(servletPath + PROMETHEUS_ENDPOINT).handler(PrometheusScrapingHandler.create()); - if (consumeAddress == null && sendAddress == null) - configureHealthCheckEndpoint(vertx, router, servletPath, null, - null); - else if (consumeAddress == null) - configureHealthCheckEndpoint(vertx, router, servletPath, null, - sendAddress.getAddress()); - else if (sendAddress == null) - configureHealthCheckEndpoint(vertx, router, servletPath, - consumeAddress.getAddress(), null); - else - configureHealthCheckEndpoint(vertx, router, servletPath, - consumeAddress.getAddress(), sendAddress.getAddress()); - return router; - } - - public void configureHealthCheckEndpoint(Vertx vertx, Router router, final String servletPath, - String consumeAddress, String sendAddress) { - StageHealthCheckHandler healthCheckHandler = new StageHealthCheckHandler(vertx, null, objectMapper, - virusScanner, environment); - router.get(servletPath + HealthConstant.HEALTH_ENDPOINT).handler(healthCheckHandler); - if (servletPath.contains("packetreceiver") || servletPath.contains("uploader")) { - healthCheckHandler.register("virusscanner", healthCheckHandler::virusScanHealthChecker); - healthCheckHandler.register( - servletPath.substring(servletPath.lastIndexOf("/") + 1, servletPath.length()) + "Verticle", - future -> healthCheckHandler.senderHealthHandler(future, vertx, sendAddress)); - } - if (checkServletPathContainsCoreProcessor(servletPath)) { - healthCheckHandler.register( - servletPath.substring(servletPath.lastIndexOf("/") + 1, servletPath.length()) + "Send", future -> { - healthCheckHandler.senderHealthHandler(future, vertx, sendAddress); - }); - healthCheckHandler.register( - servletPath.substring(servletPath.lastIndexOf("/") + 1, servletPath.length()) + "Consume", - future -> { - healthCheckHandler.consumerHealthHandler(future, vertx, consumeAddress); - }); - } - if (servletPath.contains("external") || servletPath.contains("bioauth")) { - healthCheckHandler.register( - servletPath.substring(servletPath.lastIndexOf("/") + 1, servletPath.length()) + "Send", future -> { - healthCheckHandler.senderHealthHandler(future, vertx, sendAddress); - }); - healthCheckHandler.register( - servletPath.substring(servletPath.lastIndexOf("/") + 1, servletPath.length()) + "Consume", - future -> { - healthCheckHandler.senderHealthHandler(future, vertx, consumeAddress); - }); - } - if (servletPath.contains("manual")) { - healthCheckHandler.register( - servletPath.substring(servletPath.lastIndexOf("/") + 1, servletPath.length()) + "Verticle", - future -> healthCheckHandler.senderHealthHandler(future, vertx, sendAddress)); - } - if (servletPath.contains("abismiddleware")) { - healthCheckHandler.register("queuecheck", future -> healthCheckHandler.queueHealthChecker(future, mosipQueueManager, mosipConnectionFactory)); - healthCheckHandler.register( - servletPath.substring(servletPath.lastIndexOf("/") + 1, servletPath.length()) + "Verticle", - future -> healthCheckHandler.consumerHealthHandler(future, vertx, consumeAddress)); - } - if (servletPath.contains("sender")) { - healthCheckHandler.register( - servletPath.substring(servletPath.lastIndexOf("/") + 1, servletPath.length()) + "Verticle", - future -> healthCheckHandler.consumerHealthHandler(future, vertx, consumeAddress)); - } - - healthCheckHandler.register("diskSpace", healthCheckHandler::dispSpaceHealthChecker); - healthCheckHandler.register("db", healthCheckHandler::databaseHealthChecker); - } - - private boolean checkServletPathContainsCoreProcessor(String servletPath) { - return servletPath.contains("packetvalidator") || servletPath.contains("osi") || servletPath.contains("demo") - || servletPath.contains("bio") || servletPath.contains("uin") || servletPath.contains("quality") - || servletPath.contains("abishandler") || servletPath.contains("securezone"); - } - - /** - * This method creates server for vertx web application - * - * @param router - * @param port - */ - public void createServer(Router router, int port) { - vertx.createHttpServer().requestHandler(router::accept).listen(port); - } - - /** - * This method returns a response to the routing context - * - * @param ctx - * @param object - */ - public void setResponse(RoutingContext ctx, Object object) { - ctx.response().putHeader("content-type", "text/plain").putHeader("Access-Control-Allow-Origin", "*") - .putHeader("Access-Control-Allow-Methods", "GET, POST").setStatusCode(200) - .end(Json.encodePrettily(object)); - }; - - /** - * This method returns a response to the routing context - * - * @param ctx - * @param object - * @param contentType - */ - public void setResponseWithDigitalSignature(RoutingContext ctx, Object object, String contentType) { - HttpServerResponse response = ctx.response(); - Gson gson=new GsonBuilder().serializeNulls().create(); - if (isEnabled) - response.putHeader("Response-Signature", - digitalSignatureUtility.getDigitalSignature(gson.toJson(object))); - response.putHeader("content-type", contentType).putHeader("Access-Control-Allow-Origin", "*") - .putHeader("Access-Control-Allow-Methods", "GET, POST").setStatusCode(200) - .end(gson.toJson(object)); - } - - // Added this method to cast all the stages to this class and invoke the deployVerticle method - // to start the stage by configuration, since we don't want to test all the stages now, not marking this as - // an abstract method, but later this need to be marked as abstract - public void deployVerticle() { - - } - - - /** - * Gets the stage name. - * - * @return the stage name - */ - protected String getStageName() { - return ClassUtils.getUserClass(this.getClass()).getSimpleName(); - } +package io.mosip.registration.processor.core.abstractverticle; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.core.env.Environment; +import org.springframework.util.ClassUtils; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +import brave.Tracing; +import io.mosip.kernel.core.virusscanner.spi.VirusScanner; +import io.mosip.registration.processor.core.constant.HealthConstant; +import io.mosip.registration.processor.core.queue.factory.MosipQueue; +import io.mosip.registration.processor.core.spi.queue.MosipQueueConnectionFactory; +import io.mosip.registration.processor.core.spi.queue.MosipQueueManager; +import io.mosip.registration.processor.core.tracing.VertxWebTracingLocal; +import io.mosip.registration.processor.core.util.DigitalSignatureUtility; +import io.vertx.core.Handler; +import io.vertx.core.Vertx; +import io.vertx.core.http.HttpServerResponse; +import io.vertx.core.json.Json; +import io.vertx.ext.web.Router; +import io.vertx.ext.web.RoutingContext; +import io.vertx.ext.web.handler.BodyHandler; +import io.vertx.micrometer.PrometheusScrapingHandler; + +/** + * @author Mukul Puspam + * + */ +public abstract class MosipVerticleAPIManager extends MosipVerticleManager { + + @Value("${registration.processor.signature.isEnabled}") + Boolean isEnabled; + + @Autowired + DigitalSignatureUtility digitalSignatureUtility; + + @Autowired + ObjectMapper objectMapper; + + @Autowired + private MosipQueueConnectionFactory mosipConnectionFactory; + + @Autowired + private Tracing tracing; + + @Autowired + private Environment environment; + + @Autowired(required = false) + private VirusScanner virusScanner; + + /** The mosip queue manager. */ + @Autowired + private MosipQueueManager mosipQueueManager; + + private static final String PROMETHEUS_ENDPOINT = "/actuator/prometheus"; + + /** + * This method creates a body handler for the routes + * + * @param vertx + * @return + */ + public Router postUrl(Vertx vertx, MessageBusAddress consumeAddress, MessageBusAddress sendAddress) { + Router router = Router.router(vertx); + + VertxWebTracingLocal vertxWebTracing = VertxWebTracingLocal.create(tracing); + Handler routingContextHandler = vertxWebTracing.routingContextHandler(); + router.route() + .order(-1) //applies before routes + .handler(routingContextHandler) + .failureHandler(routingContextHandler); + + router.route().handler(BodyHandler.create()); + String servletPath = getServletPath(); + router.get(servletPath + PROMETHEUS_ENDPOINT).handler(PrometheusScrapingHandler.create()); + if (consumeAddress == null && sendAddress == null) + configureHealthCheckEndpoint(vertx, router, servletPath, null, + null); + else if (consumeAddress == null) + configureHealthCheckEndpoint(vertx, router, servletPath, null, + sendAddress.getAddress()); + else if (sendAddress == null) + configureHealthCheckEndpoint(vertx, router, servletPath, + consumeAddress.getAddress(), null); + else + configureHealthCheckEndpoint(vertx, router, servletPath, + consumeAddress.getAddress(), sendAddress.getAddress()); + return router; + } + + public void configureHealthCheckEndpoint(Vertx vertx, Router router, final String servletPath, + String consumeAddress, String sendAddress) { + StageHealthCheckHandler healthCheckHandler = new StageHealthCheckHandler(vertx, null, objectMapper, + virusScanner, environment); + router.get(servletPath + HealthConstant.HEALTH_ENDPOINT).handler(healthCheckHandler); + if (servletPath.contains("packetreceiver") || servletPath.contains("uploader")) { + healthCheckHandler.register("virusscanner", healthCheckHandler::virusScanHealthChecker); + healthCheckHandler.register( + servletPath.substring(servletPath.lastIndexOf("/") + 1, servletPath.length()) + "Verticle", + future -> healthCheckHandler.senderHealthHandler(future, vertx, super.mosipEventBus, sendAddress)); + } + if (checkServletPathContainsCoreProcessor(servletPath)) { + healthCheckHandler.register( + servletPath.substring(servletPath.lastIndexOf("/") + 1, servletPath.length()) + "Send", future -> { + healthCheckHandler.senderHealthHandler(future, vertx, super.mosipEventBus, sendAddress); + }); + healthCheckHandler.register( + servletPath.substring(servletPath.lastIndexOf("/") + 1, servletPath.length()) + "Consume", + future -> { + healthCheckHandler.consumerHealthHandler(future, vertx, super.mosipEventBus, consumeAddress); + }); + } + if (servletPath.contains("external") || servletPath.contains("bioauth")) { + healthCheckHandler.register( + servletPath.substring(servletPath.lastIndexOf("/") + 1, servletPath.length()) + "Send", future -> { + healthCheckHandler.senderHealthHandler(future, vertx, super.mosipEventBus, sendAddress); + }); + healthCheckHandler.register( + servletPath.substring(servletPath.lastIndexOf("/") + 1, servletPath.length()) + "Consume", + future -> { + healthCheckHandler.senderHealthHandler(future, vertx, super.mosipEventBus, consumeAddress); + }); + } + if (servletPath.contains("manual")) { + healthCheckHandler.register( + servletPath.substring(servletPath.lastIndexOf("/") + 1, servletPath.length()) + "Verticle", + future -> healthCheckHandler.senderHealthHandler(future, vertx, super.mosipEventBus, sendAddress)); + } + if (servletPath.contains("abismiddleware")) { + healthCheckHandler.register("queuecheck", future -> healthCheckHandler.queueHealthChecker(future, mosipQueueManager, mosipConnectionFactory)); + healthCheckHandler.register( + servletPath.substring(servletPath.lastIndexOf("/") + 1, servletPath.length()) + "Verticle", + future -> healthCheckHandler.consumerHealthHandler(future, vertx, super.mosipEventBus, + consumeAddress)); + } + if (servletPath.contains("sender")) { + healthCheckHandler.register( + servletPath.substring(servletPath.lastIndexOf("/") + 1, servletPath.length()) + "Verticle", + future -> healthCheckHandler.consumerHealthHandler(future, vertx, super.mosipEventBus, + consumeAddress)); + } + + healthCheckHandler.register("diskSpace", healthCheckHandler::dispSpaceHealthChecker); + healthCheckHandler.register("db", healthCheckHandler::databaseHealthChecker); + } + + private boolean checkServletPathContainsCoreProcessor(String servletPath) { + return servletPath.contains("packetvalidator") || servletPath.contains("osi") || servletPath.contains("demo") + || servletPath.contains("bio") || servletPath.contains("uin") || servletPath.contains("quality") + || servletPath.contains("abishandler") || servletPath.contains("securezone"); + } + + /** + * This method creates server for vertx web application + * + * @param router + * @param port + */ + public void createServer(Router router, int port) { + vertx.createHttpServer().requestHandler(router::accept).listen(port); + } + + /** + * This method returns a response to the routing context + * + * @param ctx + * @param object + */ + public void setResponse(RoutingContext ctx, Object object) { + ctx.response().putHeader("content-type", "text/plain").putHeader("Access-Control-Allow-Origin", "*") + .putHeader("Access-Control-Allow-Methods", "GET, POST").setStatusCode(200) + .end(Json.encodePrettily(object)); + }; + + /** + * This method returns a response to the routing context + * + * @param ctx + * @param object + * @param contentType + */ + public void setResponseWithDigitalSignature(RoutingContext ctx, Object object, String contentType) { + HttpServerResponse response = ctx.response(); + Gson gson=new GsonBuilder().serializeNulls().create(); + if (isEnabled) + response.putHeader("Response-Signature", + digitalSignatureUtility.getDigitalSignature(gson.toJson(object))); + response.putHeader("content-type", contentType).putHeader("Access-Control-Allow-Origin", "*") + .putHeader("Access-Control-Allow-Methods", "GET, POST").setStatusCode(200) + .end(gson.toJson(object)); + } + + // Added this method to cast all the stages to this class and invoke the deployVerticle method + // to start the stage by configuration, since we don't want to test all the stages now, not marking this as + // an abstract method, but later this need to be marked as abstract + public void deployVerticle() { + + } + + + /** + * Gets the stage name. + * + * @return the stage name + */ + protected String getStageName() { + return ClassUtils.getUserClass(this.getClass()).getSimpleName(); + } } \ No newline at end of file diff --git a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/abstractverticle/MosipVerticleManager.java b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/abstractverticle/MosipVerticleManager.java index c5e5c651479..6f61a739a4a 100644 --- a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/abstractverticle/MosipVerticleManager.java +++ b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/abstractverticle/MosipVerticleManager.java @@ -1,382 +1,379 @@ -package io.mosip.registration.processor.core.abstractverticle; - -import java.io.IOException; -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.time.LocalDateTime; -import java.time.temporal.ChronoUnit; -import java.util.HashMap; -import java.util.Map; -import java.util.List; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutionException; - -import io.mosip.registration.processor.core.constant.LoggerFileConstant; -import io.mosip.registration.processor.core.packet.dto.packetmanager.TagRequestDto; -import io.mosip.registration.processor.core.packet.dto.packetmanager.TagResponseDto; -import org.apache.commons.lang3.exception.ExceptionUtils; -import org.slf4j.MDC; -import org.apache.commons.lang3.exception.ExceptionUtils; -import io.vertx.core.http.HttpServerOptions; -import io.vertx.micrometer.MicrometerMetricsOptions; -import io.vertx.micrometer.VertxPrometheusOptions; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; - -import com.fasterxml.jackson.databind.ObjectMapper; -import com.hazelcast.config.Config; -import com.hazelcast.config.UrlXmlConfig; - -import io.mosip.kernel.core.logger.spi.Logger; -import io.mosip.kernel.core.util.DateUtils; -import io.mosip.kernel.core.util.JsonUtils; -import io.mosip.kernel.core.util.exception.JsonProcessingException; -import io.mosip.registration.processor.core.code.ApiName; -import io.mosip.registration.processor.core.constant.HealthConstant; -import io.mosip.registration.processor.core.eventbus.MosipEventBusFactory; -import io.mosip.registration.processor.core.exception.ApisResourceAccessException; -import io.mosip.registration.processor.core.exception.DeploymentFailureException; -import io.mosip.registration.processor.core.exception.MessageExpiredException; -import io.mosip.registration.processor.core.exception.PacketManagerException; -import io.mosip.registration.processor.core.exception.UnsupportedEventBusTypeException; -import io.mosip.registration.processor.core.exception.util.PlatformErrorMessages; -import io.mosip.registration.processor.core.http.RequestWrapper; -import io.mosip.registration.processor.core.http.ResponseWrapper; -import io.mosip.registration.processor.core.logger.RegProcessorLogger; -import io.mosip.registration.processor.core.packet.dto.packetmanager.InfoRequestDto; -import io.mosip.registration.processor.core.packet.dto.packetmanager.InfoResponseDto; -import io.mosip.registration.processor.core.spi.eventbus.EventBusManager; -import io.mosip.registration.processor.core.spi.restclient.RegistrationProcessorRestClientService; -import io.mosip.registration.processor.core.util.PropertiesUtil; -import io.vertx.core.AbstractVerticle; -import io.vertx.core.DeploymentOptions; -import io.vertx.core.Verticle; -import io.vertx.core.Vertx; -import io.vertx.core.VertxOptions; -import io.vertx.core.eventbus.EventBusOptions; -import io.vertx.core.json.JsonObject; -import io.vertx.core.spi.cluster.ClusterManager; -import io.vertx.spi.cluster.hazelcast.HazelcastClusterManager; - -/** - * This abstract class is Vert.x implementation for MOSIP. - * - * This class provides functionalities to be used by MOSIP verticles. - * - * @author Pranav Kumar - * @author Mukul Puspam - * @since 0.0.1 - * - */ -public abstract class MosipVerticleManager extends AbstractVerticle - implements EventBusManager { - - private static final String EMPTY_STRING = ""; - - /** The logger. */ - private Logger logger = RegProcessorLogger.getLogger(MosipVerticleManager.class); - - private static final String ID = "mosip.commmons.packetmanager"; - private static final String VERSION = "v1"; - - private static final boolean DEFAULT_MESSAGE_TAG_LOADING_DISABLE_VALUE = false; - - @Autowired - private RegistrationProcessorRestClientService restApi; - - @Autowired - private ObjectMapper objectMapper; - - private static final String PROMETHEUS_ENDPOINT = "/actuator/prometheus"; - - @Value("${mosip.regproc.eventbus.type:vertx}") - private String eventBusType; - - @Autowired - protected PropertiesUtil propertiesUtil; - - /* - * Comma separated out bus message addresses for which message will not be sent out from any stage - */ - @Value("#{T(java.util.Arrays).asList('${mosip.regproc.stage-common.bus-out-halt-addresses:}')}") - protected List busOutHaltAddresses; - - @Autowired - private MosipEventBusFactory mosipEventBusFactory; - - /* - * (non-Javadoc) - * - * @see - * io.mosip.registration.processor.core.spi.eventbus.EventBusManager#getEventBus - * (java.lang.Class, java.lang.String) - */ - @Override - public MosipEventBus getEventBus(Object verticleName, String clusterManagerUrl) { - return getEventBus(verticleName, clusterManagerUrl, 1); - } - - /* - * (non-Javadoc) - * - * @see - * io.mosip.registration.processor.core.spi.eventbus.EventBusManager#getEventBus - * (java.lang.Class) - */ - @Override - public MosipEventBus getEventBus(Object verticleName, String clusterManagerUrl, int instanceNumber) { - CompletableFuture eventBus = new CompletableFuture<>(); - MosipEventBus mosipEventBus = null; - Config config; - try { - config = new UrlXmlConfig(clusterManagerUrl); - } catch (IOException e1) { - throw new DeploymentFailureException(PlatformErrorMessages.RPR_CMB_MALFORMED_URL_EXCEPTION.getMessage()); - } - ClusterManager clusterManager = new HazelcastClusterManager(config); - String address = null; - try { - address = InetAddress.getLocalHost().getHostAddress(); - } catch (UnknownHostException e1) { - throw new DeploymentFailureException(PlatformErrorMessages.RPR_CMB_MALFORMED_URL_EXCEPTION.getMessage()); - } - - MicrometerMetricsOptions micrometerMetricsOptions = new MicrometerMetricsOptions() - .setPrometheusOptions(new VertxPrometheusOptions() - .setEnabled(true)) - .setEnabled(true); - - VertxOptions options = new VertxOptions().setClustered(true).setClusterManager(clusterManager) - .setHAEnabled(false).setWorkerPoolSize(instanceNumber) - .setEventBusOptions(new EventBusOptions().setPort(getEventBusPort()).setHost(address)) - .setMetricsOptions(micrometerMetricsOptions); - Vertx.clusteredVertx(options, result -> { - if (result.succeeded()) { - result.result().deployVerticle((Verticle) verticleName, - new DeploymentOptions().setHa(false).setWorker(true).setWorkerPoolSize(instanceNumber)); - eventBus.complete(result.result()); - logger.debug(verticleName + " deployed successfully"); - } else { - throw new DeploymentFailureException(PlatformErrorMessages.RPR_CMB_DEPLOYMENT_FAILURE.getMessage()); - } - }); - - try { - Vertx vert = eventBus.get(); - mosipEventBus = mosipEventBusFactory.getEventBus(vert, getEventBusType(), getPropertyPrefix()); - } catch (InterruptedException | ExecutionException | UnsupportedEventBusTypeException e) { - Thread.currentThread().interrupt(); - throw new DeploymentFailureException(PlatformErrorMessages.RPR_CMB_DEPLOYMENT_FAILURE.getMessage(), e); - } - return mosipEventBus; - } - - /* - * (non-Javadoc) - * - * @see io.mosip.registration.processor.core.spi.eventbus.EventBusManager# - * consumeAndSend(java.lang.Object, java.lang.Object, java.lang.Object) - */ - @Override - public void consumeAndSend(MosipEventBus mosipEventBus, MessageBusAddress fromAddress, - MessageBusAddress toAddress, long messageExpiryTimeLimit) { - if(busOutHaltAddresses.contains(toAddress.getAddress())) { - consume(mosipEventBus, fromAddress, messageExpiryTimeLimit); - return; - } - mosipEventBus.consumeAndSend(fromAddress, toAddress, (msg, handler) -> { - logger.debug("consumeAndSend received from {} {}",fromAddress.toString(), msg.getBody()); - Map mdc = MDC.getCopyOfContextMap(); - vertx.executeBlocking(future -> { - MessageDTO messageDTO =new MessageDTO(); - try { - MDC.setContextMap(mdc); - JsonObject jsonObject = (JsonObject) msg.getBody(); - messageDTO = objectMapper.readValue(objectMapper.writeValueAsString(jsonObject.getMap()), MessageDTO.class); - if(isMessageExpired(messageDTO, messageExpiryTimeLimit)) { - future.fail(new MessageExpiredException("rid: " + messageDTO.getRid() + - " lastHopTimestamp " + messageDTO.getLastHopTimestamp())); - return; - } - - MessageDTO result = process(messageDTO); - addTagsToMessageDTO(result); - result.setLastHopTimestamp(DateUtils.formatToISOString(DateUtils.getUTCCurrentDateTime())); - future.complete(result); - } catch (Exception e) { - logger.error("{} -- {} {} {}", - PlatformErrorMessages.RPR_SYS_STAGE_PROCESSING_FAILED.getCode(), - PlatformErrorMessages.RPR_SYS_STAGE_PROCESSING_FAILED.getMessage(), - e.getMessage(), ExceptionUtils.getStackTrace(e)); - messageDTO.setIsValid(false); - messageDTO.setInternalError(true); - addTagsToMessageDTO(messageDTO); - messageDTO.setLastHopTimestamp(DateUtils.formatToISOString(DateUtils.getUTCCurrentDateTime())); - future.complete(messageDTO); - } - - }, false, handler); - MDC.clear(); - }); - } - - /** - * Send. - * - * @param mosipEventBus - * The Eventbus instance for communication - * @param toAddress - * The address on which message is to be sent - * @param message - * The message that needs to be sent - */ - public void send(MosipEventBus mosipEventBus, MessageBusAddress toAddress, MessageDTO message) { - if(busOutHaltAddresses.contains(toAddress.getAddress())) - return; - addTagsToMessageDTO(message); - message.setLastHopTimestamp(DateUtils.formatToISOString(DateUtils.getUTCCurrentDateTime())); - mosipEventBus.send(toAddress, message); - } - - /** - * Consume. - * - * @param mosipEventBus - * The Eventbus instance for communication - * @param fromAddress - * The address from which message needs to be consumed - * @param messageExpiryTimeLimit - * The time limit in seconds, after which message should considered as expired - */ - public void consume(MosipEventBus mosipEventBus, MessageBusAddress fromAddress, - long messageExpiryTimeLimit) { - mosipEventBus.consume(fromAddress, (msg, handler) -> { - logger.debug("Received from {} {}",fromAddress.toString(), msg.getBody()); - Map mdc = MDC.getCopyOfContextMap(); - vertx.executeBlocking(future -> { - MessageDTO messageDTO=new MessageDTO(); - try { - MDC.setContextMap(mdc); - JsonObject jsonObject = (JsonObject) msg.getBody(); - messageDTO = objectMapper.readValue(objectMapper.writeValueAsString(jsonObject.getMap()), MessageDTO.class); - if(isMessageExpired(messageDTO, messageExpiryTimeLimit)) { - future.fail(new MessageExpiredException("rid: " + messageDTO.getRid() + - " lastHopTimestamp " + messageDTO.getLastHopTimestamp())); - return; - } - - MessageDTO result = process(messageDTO); - future.complete(result); - } catch (Exception e) { - logger.error("{} -- {} {} {}", - PlatformErrorMessages.RPR_SYS_STAGE_PROCESSING_FAILED.getCode(), - PlatformErrorMessages.RPR_SYS_STAGE_PROCESSING_FAILED.getMessage(), - e.getMessage(), ExceptionUtils.getStackTrace(e)); - messageDTO.setIsValid(false); - messageDTO.setInternalError(true); - future.complete(messageDTO); - } - }, false, handler); - MDC.clear(); - }); - } - - public Integer getEventBusPort() { - return getIntegerPropertyForSuffix("eventbus.port"); - } - - public Integer getPort() { - return getIntegerPropertyForSuffix("server.port"); - } - - protected Integer getIntegerPropertyForSuffix(String propSuffix) { - return propertiesUtil.getIntegerProperty(getPropertyPrefix(), propSuffix); - } - - protected Boolean getBooleanPropertyForSuffix(String propSuffix, Boolean defaultValue) { - return propertiesUtil.getProperty(getPropertyPrefix() + propSuffix, Boolean.class, defaultValue); - } - - protected String getPropertyForSuffix(String propSuffix) { - return propertiesUtil.getProperty(getPropertyPrefix(), propSuffix); - } - - protected String getServletPath() { - return getPropertyForSuffix(HealthConstant.SERVLET_PATH); - } - - public String getEventBusType() { - return this.eventBusType; - } - - public Boolean isTagLoadingDisabled() { - return getBooleanPropertyForSuffix("message.tag.loading.disable", DEFAULT_MESSAGE_TAG_LOADING_DISABLE_VALUE); - } - - //TODO Temporarely added for passing the existing unit test case, later to be removed and unit test case to be changed based on SpringRunner - protected void setMosipEventBusFactory(MosipEventBusFactory mosipEventBusFactory) { - this.mosipEventBusFactory = mosipEventBusFactory; - } - - private void addTagsToMessageDTO(MessageDTO messageDTO) { - if(isTagLoadingDisabled()) { - messageDTO.setTags(new HashMap<>()); - return; - } - try { - messageDTO.setTags(getTagsFromPacket(messageDTO.getRid())); - } catch (ApisResourceAccessException | PacketManagerException | - JsonProcessingException | IOException e) { - logger.error(PlatformErrorMessages.RPR_SYS_PACKET_TAGS_COPYING_FAILED.getCode() + - " -- " + PlatformErrorMessages.RPR_SYS_PACKET_TAGS_COPYING_FAILED.getMessage() + - e.getMessage() + ExceptionUtils.getStackTrace(e)); - messageDTO.setInternalError(true); - messageDTO.setTags(new HashMap<>()); - } - } - - private Map getTagsFromPacket(String id) throws ApisResourceAccessException, - PacketManagerException, JsonProcessingException, IOException { - TagRequestDto tagRequestDto = new TagRequestDto(id, null); - RequestWrapper request = new RequestWrapper<>(); - request.setId(ID); - request.setVersion(VERSION); - request.setRequesttime(DateUtils.getUTCCurrentDateTime()); - request.setRequest(tagRequestDto); - ResponseWrapper response = (ResponseWrapper) restApi - .postApi(ApiName.PACKETMANAGER_GET_TAGS, "", "", - request, ResponseWrapper.class); - - if (response.getErrors() != null && response.getErrors().size() > 0) { - logger.error("Registration Id : {} response: {}", id, JsonUtils.javaObjectToJsonString(response)); - throw new PacketManagerException(response.getErrors().get(0).getErrorCode(), - response.getErrors().get(0).getMessage()); - } - - TagResponseDto tagResponseDto = null; - if (response.getResponse() != null) - tagResponseDto = objectMapper.readValue(JsonUtils.javaObjectToJsonString(response.getResponse()), TagResponseDto.class); - - return tagResponseDto != null ? tagResponseDto.getTags() : null; - } - - private boolean isMessageExpired(MessageDTO messageDTO, long messageExpiryTimeLimit) { - if(messageExpiryTimeLimit <= 0) - return false; - try { - LocalDateTime lastHopDateTime = DateUtils.parseUTCToLocalDateTime(messageDTO.getLastHopTimestamp()); - LocalDateTime nowDateTime = LocalDateTime.now(); - if(ChronoUnit.SECONDS.between(lastHopDateTime, nowDateTime) <= messageExpiryTimeLimit) - return false; - return true; - } catch(Exception e) { - logger.error("{} {} {} {}", PlatformErrorMessages.RPR_SYS_PARSING_DATE_EXCEPTION.getCode(), - PlatformErrorMessages.RPR_SYS_PARSING_DATE_EXCEPTION.getMessage(), e.getMessage(), - ExceptionUtils.getStackTrace(e)); - return true; - } - } - - protected abstract String getPropertyPrefix(); - -} +package io.mosip.registration.processor.core.abstractverticle; + +import java.io.IOException; +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.time.LocalDateTime; +import java.time.temporal.ChronoUnit; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; + +import org.apache.commons.lang3.exception.ExceptionUtils; +import org.slf4j.MDC; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.hazelcast.config.Config; +import com.hazelcast.config.UrlXmlConfig; + +import io.mosip.kernel.core.logger.spi.Logger; +import io.mosip.kernel.core.util.DateUtils; +import io.mosip.kernel.core.util.JsonUtils; +import io.mosip.kernel.core.util.exception.JsonProcessingException; +import io.mosip.registration.processor.core.code.ApiName; +import io.mosip.registration.processor.core.constant.HealthConstant; +import io.mosip.registration.processor.core.eventbus.MosipEventBusFactory; +import io.mosip.registration.processor.core.exception.ApisResourceAccessException; +import io.mosip.registration.processor.core.exception.DeploymentFailureException; +import io.mosip.registration.processor.core.exception.MessageExpiredException; +import io.mosip.registration.processor.core.exception.PacketManagerException; +import io.mosip.registration.processor.core.exception.UnsupportedEventBusTypeException; +import io.mosip.registration.processor.core.exception.util.PlatformErrorMessages; +import io.mosip.registration.processor.core.http.RequestWrapper; +import io.mosip.registration.processor.core.http.ResponseWrapper; +import io.mosip.registration.processor.core.logger.RegProcessorLogger; +import io.mosip.registration.processor.core.packet.dto.packetmanager.TagRequestDto; +import io.mosip.registration.processor.core.packet.dto.packetmanager.TagResponseDto; +import io.mosip.registration.processor.core.spi.eventbus.EventBusManager; +import io.mosip.registration.processor.core.spi.restclient.RegistrationProcessorRestClientService; +import io.mosip.registration.processor.core.util.PropertiesUtil; +import io.vertx.core.AbstractVerticle; +import io.vertx.core.DeploymentOptions; +import io.vertx.core.Verticle; +import io.vertx.core.Vertx; +import io.vertx.core.VertxOptions; +import io.vertx.core.eventbus.EventBusOptions; +import io.vertx.core.json.JsonObject; +import io.vertx.core.spi.cluster.ClusterManager; +import io.vertx.micrometer.MicrometerMetricsOptions; +import io.vertx.micrometer.VertxPrometheusOptions; +import io.vertx.spi.cluster.hazelcast.HazelcastClusterManager; + +/** + * This abstract class is Vert.x implementation for MOSIP. + * + * This class provides functionalities to be used by MOSIP verticles. + * + * @author Pranav Kumar + * @author Mukul Puspam + * @since 0.0.1 + * + */ +public abstract class MosipVerticleManager extends AbstractVerticle + implements EventBusManager { + + private static final String EMPTY_STRING = ""; + + /** The logger. */ + private Logger logger = RegProcessorLogger.getLogger(MosipVerticleManager.class); + + private static final String ID = "mosip.commmons.packetmanager"; + private static final String VERSION = "v1"; + + private static final boolean DEFAULT_MESSAGE_TAG_LOADING_DISABLE_VALUE = false; + + @Autowired + private RegistrationProcessorRestClientService restApi; + + @Autowired + private ObjectMapper objectMapper; + + private static final String PROMETHEUS_ENDPOINT = "/actuator/prometheus"; + + @Value("${mosip.regproc.eventbus.type:vertx}") + private String eventBusType; + + @Autowired + protected PropertiesUtil propertiesUtil; + + /* + * Comma separated out bus message addresses for which message will not be sent out from any stage + */ + @Value("#{T(java.util.Arrays).asList('${mosip.regproc.stage-common.bus-out-halt-addresses:}')}") + protected List busOutHaltAddresses; + + @Autowired + private MosipEventBusFactory mosipEventBusFactory; + + protected MosipEventBus mosipEventBus; + + /* + * (non-Javadoc) + * + * @see + * io.mosip.registration.processor.core.spi.eventbus.EventBusManager#getEventBus + * (java.lang.Class, java.lang.String) + */ + @Override + public MosipEventBus getEventBus(Object verticleName, String clusterManagerUrl) { + return getEventBus(verticleName, clusterManagerUrl, 1); + } + + /* + * (non-Javadoc) + * + * @see + * io.mosip.registration.processor.core.spi.eventbus.EventBusManager#getEventBus + * (java.lang.Class) + */ + @Override + public MosipEventBus getEventBus(Object verticleName, String clusterManagerUrl, int instanceNumber) { + CompletableFuture eventBus = new CompletableFuture<>(); + mosipEventBus = null; + Config config; + try { + config = new UrlXmlConfig(clusterManagerUrl); + } catch (IOException e1) { + throw new DeploymentFailureException(PlatformErrorMessages.RPR_CMB_MALFORMED_URL_EXCEPTION.getMessage()); + } + ClusterManager clusterManager = new HazelcastClusterManager(config); + String address = null; + try { + address = InetAddress.getLocalHost().getHostAddress(); + } catch (UnknownHostException e1) { + throw new DeploymentFailureException(PlatformErrorMessages.RPR_CMB_MALFORMED_URL_EXCEPTION.getMessage()); + } + + MicrometerMetricsOptions micrometerMetricsOptions = new MicrometerMetricsOptions() + .setPrometheusOptions(new VertxPrometheusOptions() + .setEnabled(true)) + .setEnabled(true); + + VertxOptions options = new VertxOptions().setClustered(true).setClusterManager(clusterManager) + .setHAEnabled(false).setWorkerPoolSize(instanceNumber) + .setEventBusOptions(new EventBusOptions().setPort(getEventBusPort()).setHost(address)) + .setMetricsOptions(micrometerMetricsOptions); + Vertx.clusteredVertx(options, result -> { + if (result.succeeded()) { + result.result().deployVerticle((Verticle) verticleName, + new DeploymentOptions().setHa(false).setWorker(true).setWorkerPoolSize(instanceNumber)); + eventBus.complete(result.result()); + logger.debug(verticleName + " deployed successfully"); + } else { + throw new DeploymentFailureException(PlatformErrorMessages.RPR_CMB_DEPLOYMENT_FAILURE.getMessage()); + } + }); + + try { + Vertx vert = eventBus.get(); + mosipEventBus = mosipEventBusFactory.getEventBus(vert, getEventBusType(), getPropertyPrefix()); + } catch (InterruptedException | ExecutionException | UnsupportedEventBusTypeException e) { + Thread.currentThread().interrupt(); + throw new DeploymentFailureException(PlatformErrorMessages.RPR_CMB_DEPLOYMENT_FAILURE.getMessage(), e); + } + return mosipEventBus; + } + + /* + * (non-Javadoc) + * + * @see io.mosip.registration.processor.core.spi.eventbus.EventBusManager# + * consumeAndSend(java.lang.Object, java.lang.Object, java.lang.Object) + */ + @Override + public void consumeAndSend(MosipEventBus mosipEventBus, MessageBusAddress fromAddress, + MessageBusAddress toAddress, long messageExpiryTimeLimit) { + if(busOutHaltAddresses.contains(toAddress.getAddress())) { + consume(mosipEventBus, fromAddress, messageExpiryTimeLimit); + return; + } + mosipEventBus.consumeAndSend(fromAddress, toAddress, (msg, handler) -> { + logger.debug("consumeAndSend received from {} {}",fromAddress.toString(), msg.getBody()); + Map mdc = MDC.getCopyOfContextMap(); + vertx.executeBlocking(future -> { + MessageDTO messageDTO =new MessageDTO(); + try { + MDC.setContextMap(mdc); + JsonObject jsonObject = (JsonObject) msg.getBody(); + messageDTO = objectMapper.readValue(objectMapper.writeValueAsString(jsonObject.getMap()), MessageDTO.class); + if(isMessageExpired(messageDTO, messageExpiryTimeLimit)) { + future.fail(new MessageExpiredException("rid: " + messageDTO.getRid() + + " lastHopTimestamp " + messageDTO.getLastHopTimestamp())); + return; + } + + MessageDTO result = process(messageDTO); + addTagsToMessageDTO(result); + result.setLastHopTimestamp(DateUtils.formatToISOString(DateUtils.getUTCCurrentDateTime())); + future.complete(result); + } catch (Exception e) { + logger.error("{} -- {} {} {}", + PlatformErrorMessages.RPR_SYS_STAGE_PROCESSING_FAILED.getCode(), + PlatformErrorMessages.RPR_SYS_STAGE_PROCESSING_FAILED.getMessage(), + e.getMessage(), ExceptionUtils.getStackTrace(e)); + messageDTO.setIsValid(false); + messageDTO.setInternalError(true); + addTagsToMessageDTO(messageDTO); + messageDTO.setLastHopTimestamp(DateUtils.formatToISOString(DateUtils.getUTCCurrentDateTime())); + future.complete(messageDTO); + } + + }, false, handler); + MDC.clear(); + }); + } + + /** + * Send. + * + * @param mosipEventBus + * The Eventbus instance for communication + * @param toAddress + * The address on which message is to be sent + * @param message + * The message that needs to be sent + */ + public void send(MosipEventBus mosipEventBus, MessageBusAddress toAddress, MessageDTO message) { + if(busOutHaltAddresses.contains(toAddress.getAddress())) + return; + addTagsToMessageDTO(message); + message.setLastHopTimestamp(DateUtils.formatToISOString(DateUtils.getUTCCurrentDateTime())); + mosipEventBus.send(toAddress, message); + } + + /** + * Consume. + * + * @param mosipEventBus + * The Eventbus instance for communication + * @param fromAddress + * The address from which message needs to be consumed + * @param messageExpiryTimeLimit + * The time limit in seconds, after which message should considered as expired + */ + public void consume(MosipEventBus mosipEventBus, MessageBusAddress fromAddress, + long messageExpiryTimeLimit) { + mosipEventBus.consume(fromAddress, (msg, handler) -> { + logger.debug("Received from {} {}",fromAddress.toString(), msg.getBody()); + Map mdc = MDC.getCopyOfContextMap(); + vertx.executeBlocking(future -> { + MessageDTO messageDTO=new MessageDTO(); + try { + MDC.setContextMap(mdc); + JsonObject jsonObject = (JsonObject) msg.getBody(); + messageDTO = objectMapper.readValue(objectMapper.writeValueAsString(jsonObject.getMap()), MessageDTO.class); + if(isMessageExpired(messageDTO, messageExpiryTimeLimit)) { + future.fail(new MessageExpiredException("rid: " + messageDTO.getRid() + + " lastHopTimestamp " + messageDTO.getLastHopTimestamp())); + return; + } + + MessageDTO result = process(messageDTO); + future.complete(result); + } catch (Exception e) { + logger.error("{} -- {} {} {}", + PlatformErrorMessages.RPR_SYS_STAGE_PROCESSING_FAILED.getCode(), + PlatformErrorMessages.RPR_SYS_STAGE_PROCESSING_FAILED.getMessage(), + e.getMessage(), ExceptionUtils.getStackTrace(e)); + messageDTO.setIsValid(false); + messageDTO.setInternalError(true); + future.complete(messageDTO); + } + }, false, handler); + MDC.clear(); + }); + } + + public Integer getEventBusPort() { + return getIntegerPropertyForSuffix("eventbus.port"); + } + + public Integer getPort() { + return getIntegerPropertyForSuffix("server.port"); + } + + protected Integer getIntegerPropertyForSuffix(String propSuffix) { + return propertiesUtil.getIntegerProperty(getPropertyPrefix(), propSuffix); + } + + protected Boolean getBooleanPropertyForSuffix(String propSuffix, Boolean defaultValue) { + return propertiesUtil.getProperty(getPropertyPrefix() + propSuffix, Boolean.class, defaultValue); + } + + protected String getPropertyForSuffix(String propSuffix) { + return propertiesUtil.getProperty(getPropertyPrefix(), propSuffix); + } + + protected String getServletPath() { + return getPropertyForSuffix(HealthConstant.SERVLET_PATH); + } + + public String getEventBusType() { + return this.eventBusType; + } + + public Boolean isTagLoadingDisabled() { + return getBooleanPropertyForSuffix("message.tag.loading.disable", DEFAULT_MESSAGE_TAG_LOADING_DISABLE_VALUE); + } + + //TODO Temporarely added for passing the existing unit test case, later to be removed and unit test case to be changed based on SpringRunner + protected void setMosipEventBusFactory(MosipEventBusFactory mosipEventBusFactory) { + this.mosipEventBusFactory = mosipEventBusFactory; + } + + private void addTagsToMessageDTO(MessageDTO messageDTO) { + if(isTagLoadingDisabled()) { + messageDTO.setTags(new HashMap<>()); + return; + } + try { + messageDTO.setTags(getTagsFromPacket(messageDTO.getRid())); + } catch (ApisResourceAccessException | PacketManagerException | + JsonProcessingException | IOException e) { + logger.error(PlatformErrorMessages.RPR_SYS_PACKET_TAGS_COPYING_FAILED.getCode() + + " -- " + PlatformErrorMessages.RPR_SYS_PACKET_TAGS_COPYING_FAILED.getMessage() + + e.getMessage() + ExceptionUtils.getStackTrace(e)); + messageDTO.setInternalError(true); + messageDTO.setTags(new HashMap<>()); + } + } + + private Map getTagsFromPacket(String id) throws ApisResourceAccessException, + PacketManagerException, JsonProcessingException, IOException { + TagRequestDto tagRequestDto = new TagRequestDto(id, null); + RequestWrapper request = new RequestWrapper<>(); + request.setId(ID); + request.setVersion(VERSION); + request.setRequesttime(DateUtils.getUTCCurrentDateTime()); + request.setRequest(tagRequestDto); + ResponseWrapper response = (ResponseWrapper) restApi + .postApi(ApiName.PACKETMANAGER_GET_TAGS, "", "", + request, ResponseWrapper.class); + + if (response.getErrors() != null && response.getErrors().size() > 0) { + logger.error("Registration Id : {} response: {}", id, JsonUtils.javaObjectToJsonString(response)); + throw new PacketManagerException(response.getErrors().get(0).getErrorCode(), + response.getErrors().get(0).getMessage()); + } + + TagResponseDto tagResponseDto = null; + if (response.getResponse() != null) + tagResponseDto = objectMapper.readValue(JsonUtils.javaObjectToJsonString(response.getResponse()), TagResponseDto.class); + + return tagResponseDto != null ? tagResponseDto.getTags() : null; + } + + private boolean isMessageExpired(MessageDTO messageDTO, long messageExpiryTimeLimit) { + if(messageExpiryTimeLimit <= 0) + return false; + try { + LocalDateTime lastHopDateTime = DateUtils.parseUTCToLocalDateTime(messageDTO.getLastHopTimestamp()); + LocalDateTime nowDateTime = LocalDateTime.now(); + if(ChronoUnit.SECONDS.between(lastHopDateTime, nowDateTime) <= messageExpiryTimeLimit) + return false; + return true; + } catch(Exception e) { + logger.error("{} {} {} {}", PlatformErrorMessages.RPR_SYS_PARSING_DATE_EXCEPTION.getCode(), + PlatformErrorMessages.RPR_SYS_PARSING_DATE_EXCEPTION.getMessage(), e.getMessage(), + ExceptionUtils.getStackTrace(e)); + return true; + } + } + + protected abstract String getPropertyPrefix(); + +} 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 45a7064cb12..b16d7b43872 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 @@ -15,26 +15,16 @@ import java.sql.SQLException; import java.sql.Statement; -import javax.jms.*; +import javax.jms.Message; +import javax.jms.MessageConsumer; +import javax.jms.MessageProducer; +import javax.jms.Session; -import io.mosip.kernel.core.exception.ExceptionUtils; -import io.mosip.kernel.core.virusscanner.spi.VirusScanner; -import io.mosip.registration.processor.core.constant.LoggerFileConstant; -import io.mosip.registration.processor.core.queue.factory.MosipActiveMq; -import io.mosip.registration.processor.core.queue.factory.MosipQueue; -import io.mosip.registration.processor.core.queue.factory.QueueListener; -import io.mosip.registration.processor.core.queue.impl.TransportExceptionListener; -import io.mosip.registration.processor.core.spi.queue.MosipQueueConnectionFactory; -import io.mosip.registration.processor.core.spi.queue.MosipQueueManager; -import org.apache.activemq.ActiveMQConnection; -import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.command.ActiveMQBytesMessage; import org.apache.commons.io.FileUtils; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.security.UserGroupInformation; -import io.mosip.registration.processor.core.logger.RegProcessorLogger; -import io.mosip.kernel.core.logger.spi.Logger; import org.springframework.core.env.Environment; import org.springframework.core.io.DefaultResourceLoader; import org.springframework.core.io.Resource; @@ -44,7 +34,16 @@ import com.fasterxml.jackson.core.JsonProcessingException; 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.virusscanner.spi.VirusScanner; import io.mosip.registration.processor.core.constant.HealthConstant; +import io.mosip.registration.processor.core.constant.LoggerFileConstant; +import io.mosip.registration.processor.core.logger.RegProcessorLogger; +import io.mosip.registration.processor.core.queue.factory.MosipQueue; +import io.mosip.registration.processor.core.queue.factory.QueueListener; +import io.mosip.registration.processor.core.spi.queue.MosipQueueConnectionFactory; +import io.mosip.registration.processor.core.spi.queue.MosipQueueManager; import io.netty.handler.codec.http.HttpResponse; import io.vertx.core.AsyncResult; import io.vertx.core.Handler; @@ -308,11 +307,25 @@ public void dispSpaceHealthChecker(Promise promise) { * @param promise {@link Promise} instance from handler * @param vertx {@link Vertx} instance */ - public void senderHealthHandler(Promise promise, Vertx vertx, String address) { + public void senderHealthHandler(Promise promise, Vertx vertx, MosipEventBus eventBus, String address) { try { - vertx.eventBus().send(address, HealthConstant.PING); - final JsonObject result = resultBuilder.create().add(HealthConstant.RESPONSE, HealthConstant.PING).build(); - promise.complete(Status.OK(result)); + eventBus.senderHealthCheck((healthCheckDto) -> { + 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() + .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(); promise.complete(Status.KO(result)); @@ -324,11 +337,26 @@ public void senderHealthHandler(Promise promise, Vertx vertx, String add * @param vertx * @param address */ - public void consumerHealthHandler(Promise promise, Vertx vertx, String address) { + public void consumerHealthHandler(Promise promise, Vertx vertx, MosipEventBus eventBus, String address) { try { - Boolean isRegistered = vertx.eventBus().consumer(address).isRegistered(); - final JsonObject result = resultBuilder.create().add(HealthConstant.RESPONSE, isRegistered).build(); - promise.complete(Status.OK(result)); + eventBus.consumerHealthCheck((healthCheckDto) -> { + try { + + if (healthCheckDto.isEventBusConnected()) { + 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) { + 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(); promise.complete(Status.KO(result)); 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 98b13cde0b1..add46b56e19 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 @@ -9,18 +9,22 @@ import java.util.stream.Collectors; import java.util.stream.IntStream; -import brave.Span; -import io.mosip.registration.processor.core.tracing.EventTracingHandler; import org.apache.kafka.clients.consumer.ConsumerRecord; import org.apache.kafka.clients.consumer.ConsumerRecords; +import org.slf4j.MDC; +import brave.Span; +import io.mosip.kernel.core.logger.spi.Logger; 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.exception.ConfigurationServerFailureException; import io.mosip.registration.processor.core.exception.MessageExpiredException; +import io.mosip.registration.processor.core.logger.RegProcessorLogger; import io.mosip.registration.processor.core.spi.eventbus.EventHandler; +import io.mosip.registration.processor.core.tracing.EventTracingHandler; import io.vertx.core.AsyncResult; import io.vertx.core.CompositeFuture; import io.vertx.core.Future; @@ -36,9 +40,6 @@ import io.vertx.kafka.client.consumer.impl.KafkaConsumerRecordsImpl; import io.vertx.kafka.client.producer.KafkaProducer; import io.vertx.kafka.client.producer.KafkaProducerRecord; -import io.mosip.registration.processor.core.logger.RegProcessorLogger; -import io.mosip.kernel.core.logger.spi.Logger; -import org.slf4j.MDC; /** * Implementation of MosipEventBus interface for Kafka based event bus @@ -429,4 +430,35 @@ private void resumePartition(TopicPartition topicPartition, Promise promis promise.fail("Partition resuming failed for " + topicPartition.getPartition()); }); } + + @Override + public void consumerHealthCheck(Handler eventHandler, String address) { + HealthCheckDTO healthCheckDTO = new HealthCheckDTO(); + kafkaConsumer.listTopics(f -> { + if (f.succeeded()) { + healthCheckDTO.setEventBusConnected(true); + + } else { + healthCheckDTO.setEventBusConnected(false); + healthCheckDTO.setFailureReason(f.cause().getMessage()); + } + eventHandler.handle(healthCheckDTO); + }); + + } + + @Override + 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 + HealthCheckDTO healthCheckDTO = new HealthCheckDTO(); + if (kafkaProducer != null) { + healthCheckDTO.setEventBusConnected(true); + } else { + healthCheckDTO.setEventBusConnected(false); + healthCheckDTO.setFailureReason("Failed kafkaProducer"); + } + eventHandler.handle(healthCheckDTO); + } } 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 b28f92ccdde..84275f3d792 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 @@ -1,10 +1,14 @@ package io.mosip.registration.processor.core.eventbus; +import io.mosip.kernel.core.logger.spi.Logger; 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.constant.HealthConstant; import io.mosip.registration.processor.core.exception.MessageExpiredException; +import io.mosip.registration.processor.core.logger.RegProcessorLogger; import io.mosip.registration.processor.core.spi.eventbus.EventHandler; import io.mosip.registration.processor.core.tracing.EventTracingHandler; import io.mosip.registration.processor.core.tracing.MDCHelper; @@ -12,8 +16,6 @@ import io.vertx.core.Handler; import io.vertx.core.Vertx; import io.vertx.core.json.JsonObject; -import io.mosip.registration.processor.core.logger.RegProcessorLogger; -import io.mosip.kernel.core.logger.spi.Logger; /** @@ -120,4 +122,26 @@ public void send(MessageBusAddress toAddress, MessageDTO message) { this.vertx.eventBus().send(messageBusAddress.getAddress(), jsonObject.toString()); } + @Override + public void consumerHealthCheck(Handler eventHandler, String address) { + Boolean isRegistered = vertx.eventBus().consumer(address).isRegistered(); + HealthCheckDTO healthCheckDTO = new HealthCheckDTO(); + healthCheckDTO.setEventBusConnected(isRegistered); + eventHandler.handle(healthCheckDTO); + + } + + @Override + public void senderHealthCheck(Handler eventHandler, String address) { + HealthCheckDTO healthCheckDTO = new HealthCheckDTO(); + try { + vertx.eventBus().send(address, HealthConstant.PING); + healthCheckDTO.setEventBusConnected(true); + eventHandler.handle(healthCheckDTO); + } catch (Exception e) { + healthCheckDTO.setEventBusConnected(false); + healthCheckDTO.setFailureReason(e.getMessage()); + eventHandler.handle(healthCheckDTO); + } + } } 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 31879ac2f4e..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 @@ -1,627 +1,712 @@ -package io.mosip.registration.processor.core.eventbus; - -import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyLong; -import static org.mockito.ArgumentMatchers.anyMap; -import static org.mockito.Mockito.atLeastOnce; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import brave.Tracing; -import io.mosip.registration.processor.core.tracing.EventTracingHandler; -import org.apache.kafka.clients.consumer.ConsumerRecord; -import org.apache.kafka.clients.consumer.ConsumerRecords; -import org.apache.kafka.common.TopicPartition; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.ArgumentCaptor; -import org.mockito.InOrder; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.stubbing.Answer; -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.powermock.modules.junit4.PowerMockRunnerDelegate; - -import io.mosip.registration.processor.core.abstractverticle.EventDTO; -import io.mosip.registration.processor.core.abstractverticle.MessageBusAddress; -import io.mosip.registration.processor.core.abstractverticle.MessageDTO; -import io.mosip.registration.processor.core.constant.RegistrationType; -import io.mosip.registration.processor.core.exception.MessageExpiredException; -import io.mosip.registration.processor.core.spi.eventbus.EventHandler; -import io.vertx.core.AsyncResult; -import io.vertx.core.Vertx; -import io.vertx.core.Handler; -import io.vertx.core.json.JsonObject; -import io.vertx.ext.unit.Async; -import io.vertx.ext.unit.TestContext; -import io.vertx.ext.unit.junit.VertxUnitRunner; -import io.vertx.kafka.client.consumer.KafkaConsumer; -import io.vertx.kafka.client.consumer.KafkaConsumerRecords; -import io.vertx.kafka.client.consumer.OffsetAndMetadata; -import io.vertx.kafka.client.consumer.impl.KafkaConsumerRecordsImpl; -import io.vertx.kafka.client.producer.KafkaProducer; -import io.vertx.kafka.client.producer.KafkaProducerRecord; - -@RunWith(PowerMockRunner.class) -@PowerMockRunnerDelegate(VertxUnitRunner.class) -@PowerMockIgnore({ "javax.management.*", "javax.net.ssl.*", "com.sun.org.apache.xerces.*", - "javax.xml.*", "org.xml.*" }) -@PrepareForTest({ KafkaConsumer.class, KafkaProducer.class }) -public class KafkaMosipEventBusTest { - - private Vertx vertx; - - /** The Kafka mosip event bus. */ - private KafkaMosipEventBus kafkaMosipEventBus; - - @Mock - private KafkaConsumer kafkaConsumer; - - @Mock - private KafkaProducer kafkaProducer; - - private Tracing tracing = Tracing.newBuilder().build(); - - private EventTracingHandler eventTracingHandler; - - @Before - public void setup(TestContext testContext) throws Exception { - vertx = Vertx.vertx(); - PowerMockito.mockStatic(KafkaConsumer.class); - PowerMockito.mockStatic(KafkaProducer.class); - Mockito.when(KafkaConsumer.create(any(), anyMap())) - .thenReturn(kafkaConsumer); - Mockito.when(KafkaProducer.create(any(), anyMap())) - .thenReturn(kafkaProducer); - - eventTracingHandler = new EventTracingHandler(tracing, "kafka"); - } - - @After - public void tearDown(TestContext testContext) { - vertx.close(); - } - - @Test - public void testSend(TestContext testContext) { - kafkaMosipEventBus = new KafkaMosipEventBus(vertx, "localhost:9091", "group_1", - "auto", "100", 60000, eventTracingHandler); - - MessageDTO messageDTO = new MessageDTO(); - messageDTO.setRid("1001"); - messageDTO.setReg_type(RegistrationType.NEW.name()); - kafkaMosipEventBus.send(MessageBusAddress.PACKET_VALIDATOR_BUS_OUT, messageDTO); - - verify(kafkaProducer, times(1)).write(any(KafkaProducerRecord.class),any(Handler.class)); - } - - @Test - public void testConsumeAndSendWithAutoCommitType(TestContext testContext) { - int testDataCount = 20; - kafkaMosipEventBus = new KafkaMosipEventBus(vertx, "localhost:9091", "group_1", - "auto", "100", 60000, eventTracingHandler); - final Async async = testContext.async(); - - AsyncResult> asyncResult = - Mockito.mock(AsyncResult.class); - Mockito.when(asyncResult.succeeded()).thenReturn(true); - Mockito.when(asyncResult.result()).thenReturn(prepareKafkaConsumerRecords(testDataCount)); - doAnswer((Answer>>) arguments -> { - ((Handler>>) arguments.getArgument(1)) - .handle(asyncResult); - return null; - }).when(kafkaConsumer).poll(anyLong(), any()); - - EventHandler>> eventHandler = - Mockito.mock(EventHandler.class); - doAnswer((Answer>) arguments -> { - AsyncResult asyncResultForMessageDTO = Mockito.mock(AsyncResult.class); - Mockito.when(asyncResultForMessageDTO.succeeded()).thenReturn(true); - JsonObject jsonObject = (JsonObject) ((EventDTO) arguments.getArgument(0)).getBody(); - MessageDTO messageDTO = jsonObject.mapTo(MessageDTO.class); - Mockito.when(asyncResultForMessageDTO.result()).thenReturn(messageDTO); - ((Handler>) arguments.getArgument(1)) - .handle(asyncResultForMessageDTO); - if (!async.isCompleted()) - async.complete(); - - return null; - }).when(eventHandler).handle(any(), any()); - - kafkaMosipEventBus.consumeAndSend(MessageBusAddress.PACKET_VALIDATOR_BUS_IN, - MessageBusAddress.PACKET_UPLOADER_OUT, eventHandler); - async.await(); - - verify(eventHandler, times(testDataCount)).handle(any(), any()); - verify(kafkaConsumer, times(0)).pause( - any(io.vertx.kafka.client.common.TopicPartition.class), any()); - verify(kafkaConsumer, times(0)).resume( - any(io.vertx.kafka.client.common.TopicPartition.class), any()); - verify(kafkaConsumer, times(0)).commit(anyMap(), any()); - verify(kafkaProducer, times(testDataCount)).write(any(), any()); - } - - @Test - public void testConsumeAndSendWithSingleBatchType(TestContext testContext) { - int testDataCount = 20; - kafkaMosipEventBus = new KafkaMosipEventBus(Vertx.vertx(), "localhost:9091", "group_1", - "batch", "100", 60000, eventTracingHandler); - final Async async = testContext.async(); - - AsyncResult> asyncResult = - Mockito.mock(AsyncResult.class); - Mockito.when(asyncResult.succeeded()).thenReturn(true); - Mockito.when(asyncResult.result()).thenReturn(prepareKafkaConsumerRecords(testDataCount)); - doAnswer((Answer>>) arguments -> { - ((Handler>>) arguments.getArgument(1)) - .handle(asyncResult); - return null; - }).when(kafkaConsumer).poll(anyLong(), any()); - - AsyncResult voidAsyncResult = Mockito.mock(AsyncResult.class); - Mockito.when(voidAsyncResult.succeeded()).thenReturn(true); - - doAnswer((Answer>) arguments -> { - ((Handler>) arguments.getArgument(1)).handle(voidAsyncResult); - return null; - }).when(kafkaConsumer).pause(any(io.vertx.kafka.client.common.TopicPartition.class), any()); - - doAnswer((Answer>) arguments -> { - ((Handler>) arguments.getArgument(1)).handle(voidAsyncResult); - return null; - }).when(kafkaConsumer).resume(any(io.vertx.kafka.client.common.TopicPartition.class), any()); - - doAnswer((Answer>) arguments -> { - ((Handler>) arguments.getArgument(1)).handle(voidAsyncResult); - return null; - }).when(kafkaConsumer).commit(anyMap(), any()); - - EventHandler>> eventHandler = - Mockito.mock(EventHandler.class); - - doAnswer((Answer>) arguments -> { - AsyncResult asyncResultForMessageDTO = Mockito.mock(AsyncResult.class); - Mockito.when(asyncResultForMessageDTO.succeeded()).thenReturn(true); - JsonObject jsonObject = (JsonObject) ((EventDTO) arguments.getArgument(0)).getBody(); - MessageDTO messageDTO = jsonObject.mapTo(MessageDTO.class); - Mockito.when(asyncResultForMessageDTO.result()).thenReturn(messageDTO); - ((Handler>) arguments.getArgument(1)) - .handle(asyncResultForMessageDTO); - if (!async.isCompleted()) - async.complete(); - return null; - }).when(eventHandler).handle(any(), any()); - - kafkaMosipEventBus.consumeAndSend(MessageBusAddress.PACKET_VALIDATOR_BUS_IN, - MessageBusAddress.PACKET_UPLOADER_OUT, eventHandler); - async.await(); - - InOrder inOrder = Mockito.inOrder(kafkaConsumer, eventHandler); - inOrder.verify(kafkaConsumer, times(1)).pause( - any(io.vertx.kafka.client.common.TopicPartition.class), any()); - inOrder.verify(eventHandler, times(testDataCount)).handle(any(), any()); - inOrder.verify(kafkaConsumer, times(1)).commit(anyMap(), any()); - inOrder.verify(kafkaConsumer, times(1)).resume( - any(io.vertx.kafka.client.common.TopicPartition.class), any()); - verify(kafkaProducer, times(testDataCount)).write(any(), any()); - } - - @Test - public void testConsumeAndSendWithSingleCommitType(TestContext testContext) { - int testDataCount = 20; - kafkaMosipEventBus = new KafkaMosipEventBus(Vertx.vertx(), "localhost:9091", "group_1", - "single", "100", 60000, eventTracingHandler); - final Async async = testContext.async(); - - AsyncResult> asyncResult = - Mockito.mock(AsyncResult.class); - Mockito.when(asyncResult.succeeded()).thenReturn(true); - Mockito.when(asyncResult.result()).thenReturn(prepareKafkaConsumerRecords(testDataCount)); - doAnswer((Answer>>) arguments -> { - ((Handler>>) arguments.getArgument(1)) - .handle(asyncResult); - return null; - }).when(kafkaConsumer).poll(anyLong(), any()); - - AsyncResult voidAsyncResult = Mockito.mock(AsyncResult.class); - Mockito.when(voidAsyncResult.succeeded()).thenReturn(true); - - doAnswer((Answer>) arguments -> { - ((Handler>) arguments.getArgument(1)).handle(voidAsyncResult); - return null; - }).when(kafkaConsumer).pause(any(io.vertx.kafka.client.common.TopicPartition.class), any()); - - doAnswer((Answer>) arguments -> { - ((Handler>) arguments.getArgument(1)).handle(voidAsyncResult); - return null; - }).when(kafkaConsumer).resume(any(io.vertx.kafka.client.common.TopicPartition.class), any()); - - doAnswer((Answer>) arguments -> { - ((Handler>) arguments.getArgument(1)).handle(voidAsyncResult); - return null; - }).when(kafkaConsumer).commit(anyMap(), any()); - - EventHandler>> eventHandler = - Mockito.mock(EventHandler.class); - - doAnswer((Answer>) arguments -> { - AsyncResult asyncResultForMessageDTO = Mockito.mock(AsyncResult.class); - Mockito.when(asyncResultForMessageDTO.succeeded()).thenReturn(true); - JsonObject jsonObject = (JsonObject) ((EventDTO) arguments.getArgument(0)).getBody(); - MessageDTO messageDTO = jsonObject.mapTo(MessageDTO.class); - Mockito.when(asyncResultForMessageDTO.result()).thenReturn(messageDTO); - ((Handler>) arguments.getArgument(1)) - .handle(asyncResultForMessageDTO); - if (!async.isCompleted()) - async.complete(); - return null; - }).when(eventHandler).handle(any(), any()); - - kafkaMosipEventBus.consumeAndSend(MessageBusAddress.PACKET_VALIDATOR_BUS_IN, - MessageBusAddress.PACKET_UPLOADER_OUT, eventHandler); - async.await(); - - verify(eventHandler, times(testDataCount)).handle(any(), any()); - - InOrder inOrder = Mockito.inOrder(kafkaConsumer); - inOrder.verify(kafkaConsumer, times(1)).pause( - any(io.vertx.kafka.client.common.TopicPartition.class), any()); - inOrder.verify(kafkaConsumer, times(testDataCount)).commit(anyMap(), any()); - inOrder.verify(kafkaConsumer, times(1)).resume( - any(io.vertx.kafka.client.common.TopicPartition.class), any()); - - ArgumentCaptor> argument = - ArgumentCaptor.forClass(Map.class); - verify(kafkaConsumer, atLeastOnce()).commit(argument.capture(), any()); - List> values = - argument.getAllValues(); - for(int i=0; i> asyncResult = - Mockito.mock(AsyncResult.class); - Mockito.when(asyncResult.succeeded()).thenReturn(true); - Mockito.when(asyncResult.result()).thenReturn(prepareKafkaConsumerRecords(testDataCount)); - doAnswer((Answer>>) arguments -> { - ((Handler>>) arguments.getArgument(1)) - .handle(asyncResult); - return null; - }).when(kafkaConsumer).poll(anyLong(), any()); - - EventHandler>> eventHandler = - Mockito.mock(EventHandler.class); - doAnswer((Answer>) arguments -> { - AsyncResult asyncResultForMessageDTO = Mockito.mock(AsyncResult.class); - Mockito.when(asyncResultForMessageDTO.succeeded()).thenReturn(true); - JsonObject jsonObject = (JsonObject) ((EventDTO) arguments.getArgument(0)).getBody(); - MessageDTO messageDTO = jsonObject.mapTo(MessageDTO.class); - Mockito.when(asyncResultForMessageDTO.result()).thenReturn(messageDTO); - ((Handler>) arguments.getArgument(1)) - .handle(asyncResultForMessageDTO); - if (!async.isCompleted()) - async.complete(); - - return null; - }).when(eventHandler).handle(any(), any()); - - kafkaMosipEventBus.consume(MessageBusAddress.PACKET_VALIDATOR_BUS_IN, eventHandler); - async.await(); - - verify(eventHandler, times(testDataCount)).handle(any(), any()); - verify(kafkaConsumer, times(0)).pause( - any(io.vertx.kafka.client.common.TopicPartition.class), any()); - verify(kafkaConsumer, times(0)).resume( - any(io.vertx.kafka.client.common.TopicPartition.class), any()); - verify(kafkaConsumer, times(0)).commit(anyMap(), any()); - verify(kafkaProducer, times(0)).write(any(), any()); - } - - @Test - public void testConsumeWithSingleBatchType(TestContext testContext) { - int testDataCount = 20; - kafkaMosipEventBus = new KafkaMosipEventBus(Vertx.vertx(), "localhost:9091", "group_1", - "batch", "100", 60000, eventTracingHandler); - final Async async = testContext.async(); - - AsyncResult> asyncResult = - Mockito.mock(AsyncResult.class); - Mockito.when(asyncResult.succeeded()).thenReturn(true); - Mockito.when(asyncResult.result()).thenReturn(prepareKafkaConsumerRecords(testDataCount)); - doAnswer((Answer>>) arguments -> { - ((Handler>>) arguments.getArgument(1)) - .handle(asyncResult); - return null; - }).when(kafkaConsumer).poll(anyLong(), any()); - - AsyncResult voidAsyncResult = Mockito.mock(AsyncResult.class); - Mockito.when(voidAsyncResult.succeeded()).thenReturn(true); - - doAnswer((Answer>) arguments -> { - ((Handler>) arguments.getArgument(1)).handle(voidAsyncResult); - return null; - }).when(kafkaConsumer).pause(any(io.vertx.kafka.client.common.TopicPartition.class), any()); - - doAnswer((Answer>) arguments -> { - ((Handler>) arguments.getArgument(1)).handle(voidAsyncResult); - return null; - }).when(kafkaConsumer).resume(any(io.vertx.kafka.client.common.TopicPartition.class), any()); - - doAnswer((Answer>) arguments -> { - ((Handler>) arguments.getArgument(1)).handle(voidAsyncResult); - return null; - }).when(kafkaConsumer).commit(anyMap(), any()); - - EventHandler>> eventHandler = - Mockito.mock(EventHandler.class); - - doAnswer((Answer>) arguments -> { - AsyncResult asyncResultForMessageDTO = Mockito.mock(AsyncResult.class); - Mockito.when(asyncResultForMessageDTO.succeeded()).thenReturn(true); - JsonObject jsonObject = (JsonObject) ((EventDTO) arguments.getArgument(0)).getBody(); - MessageDTO messageDTO = jsonObject.mapTo(MessageDTO.class); - Mockito.when(asyncResultForMessageDTO.result()).thenReturn(messageDTO); - ((Handler>) arguments.getArgument(1)) - .handle(asyncResultForMessageDTO); - if (!async.isCompleted()) - async.complete(); - return null; - }).when(eventHandler).handle(any(), any()); - - kafkaMosipEventBus.consume(MessageBusAddress.PACKET_VALIDATOR_BUS_IN, eventHandler); - async.await(); - - InOrder inOrder = Mockito.inOrder(kafkaConsumer, eventHandler); - inOrder.verify(kafkaConsumer, times(1)).pause( - any(io.vertx.kafka.client.common.TopicPartition.class), any()); - inOrder.verify(eventHandler, times(testDataCount)).handle(any(), any()); - inOrder.verify(kafkaConsumer, times(1)).commit(anyMap(), any()); - inOrder.verify(kafkaConsumer, times(1)).resume( - any(io.vertx.kafka.client.common.TopicPartition.class), any()); - verify(kafkaProducer, times(0)).write(any(), any()); - } - - @Test - public void testConsumeWithSingleCommitType(TestContext testContext) { - int testDataCount = 20; - kafkaMosipEventBus = new KafkaMosipEventBus(Vertx.vertx(), "localhost:9091", "group_1", - "single", "100", 60000, eventTracingHandler); - final Async async = testContext.async(); - - AsyncResult> asyncResult = - Mockito.mock(AsyncResult.class); - Mockito.when(asyncResult.succeeded()).thenReturn(true); - Mockito.when(asyncResult.result()).thenReturn(prepareKafkaConsumerRecords(testDataCount)); - doAnswer((Answer>>) arguments -> { - ((Handler>>) arguments.getArgument(1)) - .handle(asyncResult); - return null; - }).when(kafkaConsumer).poll(anyLong(), any()); - - AsyncResult voidAsyncResult = Mockito.mock(AsyncResult.class); - Mockito.when(voidAsyncResult.succeeded()).thenReturn(true); - - doAnswer((Answer>) arguments -> { - ((Handler>) arguments.getArgument(1)).handle(voidAsyncResult); - return null; - }).when(kafkaConsumer).pause(any(io.vertx.kafka.client.common.TopicPartition.class), any()); - - doAnswer((Answer>) arguments -> { - ((Handler>) arguments.getArgument(1)).handle(voidAsyncResult); - return null; - }).when(kafkaConsumer).resume(any(io.vertx.kafka.client.common.TopicPartition.class), any()); - - doAnswer((Answer>) arguments -> { - ((Handler>) arguments.getArgument(1)).handle(voidAsyncResult); - return null; - }).when(kafkaConsumer).commit(anyMap(), any()); - - EventHandler>> eventHandler = - Mockito.mock(EventHandler.class); - - doAnswer((Answer>) arguments -> { - AsyncResult asyncResultForMessageDTO = Mockito.mock(AsyncResult.class); - Mockito.when(asyncResultForMessageDTO.succeeded()).thenReturn(true); - JsonObject jsonObject = (JsonObject) ((EventDTO) arguments.getArgument(0)).getBody(); - MessageDTO messageDTO = jsonObject.mapTo(MessageDTO.class); - Mockito.when(asyncResultForMessageDTO.result()).thenReturn(messageDTO); - ((Handler>) arguments.getArgument(1)) - .handle(asyncResultForMessageDTO); - if (!async.isCompleted()) - async.complete(); - return null; - }).when(eventHandler).handle(any(), any()); - - kafkaMosipEventBus.consume(MessageBusAddress.PACKET_VALIDATOR_BUS_IN, eventHandler); - async.await(); - - verify(eventHandler, times(testDataCount)).handle(any(), any()); - - InOrder inOrder = Mockito.inOrder(kafkaConsumer); - inOrder.verify(kafkaConsumer, times(1)).pause( - any(io.vertx.kafka.client.common.TopicPartition.class), any()); - inOrder.verify(kafkaConsumer, times(testDataCount)).commit(anyMap(), any()); - inOrder.verify(kafkaConsumer, times(1)).resume( - any(io.vertx.kafka.client.common.TopicPartition.class), any()); - - ArgumentCaptor> argument = - ArgumentCaptor.forClass(Map.class); - verify(kafkaConsumer, atLeastOnce()).commit(argument.capture(), any()); - List> values = - argument.getAllValues(); - for(int i=0; i> asyncResult = - Mockito.mock(AsyncResult.class); - Mockito.when(asyncResult.succeeded()).thenReturn(true); - Mockito.when(asyncResult.result()).thenReturn(prepareKafkaConsumerRecords(testDataCount)); - doAnswer((Answer>>) arguments -> { - ((Handler>>) arguments.getArgument(1)) - .handle(asyncResult); - return null; - }).when(kafkaConsumer).poll(anyLong(), any()); - - AsyncResult voidAsyncResult = Mockito.mock(AsyncResult.class); - Mockito.when(voidAsyncResult.succeeded()).thenReturn(true); - - doAnswer((Answer>) arguments -> { - ((Handler>) arguments.getArgument(1)).handle(voidAsyncResult); - return null; - }).when(kafkaConsumer).pause(any(io.vertx.kafka.client.common.TopicPartition.class), any()); - - doAnswer((Answer>) arguments -> { - ((Handler>) arguments.getArgument(1)).handle(voidAsyncResult); - return null; - }).when(kafkaConsumer).resume(any(io.vertx.kafka.client.common.TopicPartition.class), any()); - - doAnswer((Answer>) arguments -> { - ((Handler>) arguments.getArgument(1)).handle(voidAsyncResult); - return null; - }).when(kafkaConsumer).commit(anyMap(), any()); - - EventHandler>> eventHandler = - Mockito.mock(EventHandler.class); - doAnswer((Answer>) arguments -> { - AsyncResult asyncResultForMessageDTO = Mockito.mock(AsyncResult.class); - Mockito.when(asyncResultForMessageDTO.succeeded()).thenReturn(false); - Mockito.when(asyncResultForMessageDTO.cause()).thenReturn(new MessageExpiredException()); - ((Handler>) arguments.getArgument(1)) - .handle(asyncResultForMessageDTO); - if (!async.isCompleted()) - async.complete(); - - return null; - }).when(eventHandler).handle(any(), any()); - - kafkaMosipEventBus.consumeAndSend(MessageBusAddress.PACKET_VALIDATOR_BUS_IN, - MessageBusAddress.PACKET_UPLOADER_OUT, eventHandler); - async.await(); - - verify(eventHandler, times(testDataCount)).handle(any(), any()); - verify(kafkaConsumer, times(1)).pause( - any(io.vertx.kafka.client.common.TopicPartition.class), any()); - verify(kafkaConsumer, times(1)).resume( - any(io.vertx.kafka.client.common.TopicPartition.class), any()); - verify(kafkaConsumer, times(1)).commit(anyMap(), any()); - verify(kafkaProducer, times(0)).write(any(), any()); - } - - @Test - public void testConsumeWithMessageExpiredException(TestContext testContext) { - int testDataCount = 20; - kafkaMosipEventBus = new KafkaMosipEventBus(vertx, "localhost:9091", "group_1", - "batch", "100", 60000, eventTracingHandler); - final Async async = testContext.async(); - - AsyncResult> asyncResult = - Mockito.mock(AsyncResult.class); - Mockito.when(asyncResult.succeeded()).thenReturn(true); - Mockito.when(asyncResult.result()).thenReturn(prepareKafkaConsumerRecords(testDataCount)); - doAnswer((Answer>>) arguments -> { - ((Handler>>) arguments.getArgument(1)) - .handle(asyncResult); - return null; - }).when(kafkaConsumer).poll(anyLong(), any()); - - AsyncResult voidAsyncResult = Mockito.mock(AsyncResult.class); - Mockito.when(voidAsyncResult.succeeded()).thenReturn(true); - - doAnswer((Answer>) arguments -> { - ((Handler>) arguments.getArgument(1)).handle(voidAsyncResult); - return null; - }).when(kafkaConsumer).pause(any(io.vertx.kafka.client.common.TopicPartition.class), any()); - - doAnswer((Answer>) arguments -> { - ((Handler>) arguments.getArgument(1)).handle(voidAsyncResult); - return null; - }).when(kafkaConsumer).resume(any(io.vertx.kafka.client.common.TopicPartition.class), any()); - - doAnswer((Answer>) arguments -> { - ((Handler>) arguments.getArgument(1)).handle(voidAsyncResult); - return null; - }).when(kafkaConsumer).commit(anyMap(), any()); - - EventHandler>> eventHandler = - Mockito.mock(EventHandler.class); - doAnswer((Answer>) arguments -> { - AsyncResult asyncResultForMessageDTO = Mockito.mock(AsyncResult.class); - Mockito.when(asyncResultForMessageDTO.succeeded()).thenReturn(false); - Mockito.when(asyncResultForMessageDTO.cause()).thenReturn(new MessageExpiredException()); - ((Handler>) arguments.getArgument(1)) - .handle(asyncResultForMessageDTO); - if (!async.isCompleted()) - async.complete(); - - return null; - }).when(eventHandler).handle(any(), any()); - - kafkaMosipEventBus.consume(MessageBusAddress.PACKET_VALIDATOR_BUS_IN, eventHandler); - async.await(); - - verify(eventHandler, times(testDataCount)).handle(any(), any()); - verify(kafkaConsumer, times(1)).pause( - any(io.vertx.kafka.client.common.TopicPartition.class), any()); - verify(kafkaConsumer, times(1)).resume( - any(io.vertx.kafka.client.common.TopicPartition.class), any()); - verify(kafkaConsumer, times(1)).commit(anyMap(), any()); - verify(kafkaProducer, times(0)).write(any(), any()); - } - - private KafkaConsumerRecords prepareKafkaConsumerRecords(int recordCount) { - List> consumerRecordList = new ArrayList<>(); - for(int i=0; i( - MessageBusAddress.PACKET_VALIDATOR_BUS_IN.getAddress(), 0, i, "1000"+i, - "{\"rid\":\"1000"+i+"\", \"reg_type\": \"NEW\" }")); - Map>> topicPartitionConsumerRecordListMap = - new HashMap>>(); - topicPartitionConsumerRecordListMap.put( - new TopicPartition(MessageBusAddress.PACKET_VALIDATOR_BUS_IN.getAddress(), 0), - consumerRecordList); - ConsumerRecords consumerRecords = - new ConsumerRecords(topicPartitionConsumerRecordListMap); - KafkaConsumerRecords kafkaConsumerRecords = - new KafkaConsumerRecordsImpl(consumerRecords); - return kafkaConsumerRecords; - } - -} +package io.mosip.registration.processor.core.eventbus; + +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.anyLong; +import static org.mockito.ArgumentMatchers.anyMap; +import static org.mockito.Mockito.atLeastOnce; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.kafka.clients.consumer.ConsumerRecord; +import org.apache.kafka.clients.consumer.ConsumerRecords; +import org.apache.kafka.common.TopicPartition; +import org.apache.kafka.common.errors.TimeoutException; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.InOrder; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.stubbing.Answer; +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.powermock.modules.junit4.PowerMockRunnerDelegate; +import org.springframework.test.util.ReflectionTestUtils; + +import brave.Tracing; +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.constant.RegistrationType; +import io.mosip.registration.processor.core.exception.MessageExpiredException; +import io.mosip.registration.processor.core.spi.eventbus.EventHandler; +import io.mosip.registration.processor.core.tracing.EventTracingHandler; +import io.vertx.core.AsyncResult; +import io.vertx.core.Handler; +import io.vertx.core.Vertx; +import io.vertx.core.json.JsonObject; +import io.vertx.ext.unit.Async; +import io.vertx.ext.unit.TestContext; +import io.vertx.ext.unit.junit.VertxUnitRunner; +import io.vertx.kafka.client.common.PartitionInfo; +import io.vertx.kafka.client.consumer.KafkaConsumer; +import io.vertx.kafka.client.consumer.KafkaConsumerRecords; +import io.vertx.kafka.client.consumer.OffsetAndMetadata; +import io.vertx.kafka.client.consumer.impl.KafkaConsumerRecordsImpl; +import io.vertx.kafka.client.producer.KafkaProducer; +import io.vertx.kafka.client.producer.KafkaProducerRecord; + +@RunWith(PowerMockRunner.class) +@PowerMockRunnerDelegate(VertxUnitRunner.class) +@PowerMockIgnore({ "javax.management.*", "javax.net.ssl.*", "com.sun.org.apache.xerces.*", + "javax.xml.*", "org.xml.*" }) +@PrepareForTest({ KafkaConsumer.class, KafkaProducer.class }) +public class KafkaMosipEventBusTest { + + private Vertx vertx; + + /** The Kafka mosip event bus. */ + private KafkaMosipEventBus kafkaMosipEventBus; + + @Mock + private KafkaConsumer kafkaConsumer; + + @Mock + private KafkaProducer kafkaProducer; + + private Tracing tracing = Tracing.newBuilder().build(); + + private EventTracingHandler eventTracingHandler; + + @Before + public void setup(TestContext testContext) throws Exception { + vertx = Vertx.vertx(); + PowerMockito.mockStatic(KafkaConsumer.class); + PowerMockito.mockStatic(KafkaProducer.class); + Mockito.when(KafkaConsumer.create(any(), anyMap())) + .thenReturn(kafkaConsumer); + Mockito.when(KafkaProducer.create(any(), anyMap())) + .thenReturn(kafkaProducer); + + eventTracingHandler = new EventTracingHandler(tracing, "kafka"); + } + + @After + public void tearDown(TestContext testContext) { + vertx.close(); + } + + @Test + public void testSend(TestContext testContext) { + kafkaMosipEventBus = new KafkaMosipEventBus(vertx, "localhost:9091", "group_1", + "auto", "100", 60000, eventTracingHandler); + + MessageDTO messageDTO = new MessageDTO(); + messageDTO.setRid("1001"); + messageDTO.setReg_type(RegistrationType.NEW.name()); + kafkaMosipEventBus.send(MessageBusAddress.PACKET_VALIDATOR_BUS_OUT, messageDTO); + + verify(kafkaProducer, times(1)).write(any(KafkaProducerRecord.class),any(Handler.class)); + } + + @Test + public void testConsumeAndSendWithAutoCommitType(TestContext testContext) { + int testDataCount = 20; + kafkaMosipEventBus = new KafkaMosipEventBus(vertx, "localhost:9091", "group_1", + "auto", "100", 60000, eventTracingHandler); + final Async async = testContext.async(); + + AsyncResult> asyncResult = + Mockito.mock(AsyncResult.class); + Mockito.when(asyncResult.succeeded()).thenReturn(true); + Mockito.when(asyncResult.result()).thenReturn(prepareKafkaConsumerRecords(testDataCount)); + doAnswer((Answer>>) arguments -> { + ((Handler>>) arguments.getArgument(1)) + .handle(asyncResult); + return null; + }).when(kafkaConsumer).poll(anyLong(), any()); + + EventHandler>> eventHandler = + Mockito.mock(EventHandler.class); + doAnswer((Answer>) arguments -> { + AsyncResult asyncResultForMessageDTO = Mockito.mock(AsyncResult.class); + Mockito.when(asyncResultForMessageDTO.succeeded()).thenReturn(true); + JsonObject jsonObject = (JsonObject) ((EventDTO) arguments.getArgument(0)).getBody(); + MessageDTO messageDTO = jsonObject.mapTo(MessageDTO.class); + Mockito.when(asyncResultForMessageDTO.result()).thenReturn(messageDTO); + ((Handler>) arguments.getArgument(1)) + .handle(asyncResultForMessageDTO); + if (!async.isCompleted()) + async.complete(); + + return null; + }).when(eventHandler).handle(any(), any()); + + kafkaMosipEventBus.consumeAndSend(MessageBusAddress.PACKET_VALIDATOR_BUS_IN, + MessageBusAddress.PACKET_UPLOADER_OUT, eventHandler); + async.await(); + + verify(eventHandler, times(testDataCount)).handle(any(), any()); + verify(kafkaConsumer, times(0)).pause( + any(io.vertx.kafka.client.common.TopicPartition.class), any()); + verify(kafkaConsumer, times(0)).resume( + any(io.vertx.kafka.client.common.TopicPartition.class), any()); + verify(kafkaConsumer, times(0)).commit(anyMap(), any()); + verify(kafkaProducer, times(testDataCount)).write(any(), any()); + } + + @Test + public void testConsumeAndSendWithSingleBatchType(TestContext testContext) { + int testDataCount = 20; + kafkaMosipEventBus = new KafkaMosipEventBus(Vertx.vertx(), "localhost:9091", "group_1", + "batch", "100", 60000, eventTracingHandler); + final Async async = testContext.async(); + + AsyncResult> asyncResult = + Mockito.mock(AsyncResult.class); + Mockito.when(asyncResult.succeeded()).thenReturn(true); + Mockito.when(asyncResult.result()).thenReturn(prepareKafkaConsumerRecords(testDataCount)); + doAnswer((Answer>>) arguments -> { + ((Handler>>) arguments.getArgument(1)) + .handle(asyncResult); + return null; + }).when(kafkaConsumer).poll(anyLong(), any()); + + AsyncResult voidAsyncResult = Mockito.mock(AsyncResult.class); + Mockito.when(voidAsyncResult.succeeded()).thenReturn(true); + + doAnswer((Answer>) arguments -> { + ((Handler>) arguments.getArgument(1)).handle(voidAsyncResult); + return null; + }).when(kafkaConsumer).pause(any(io.vertx.kafka.client.common.TopicPartition.class), any()); + + doAnswer((Answer>) arguments -> { + ((Handler>) arguments.getArgument(1)).handle(voidAsyncResult); + return null; + }).when(kafkaConsumer).resume(any(io.vertx.kafka.client.common.TopicPartition.class), any()); + + doAnswer((Answer>) arguments -> { + ((Handler>) arguments.getArgument(1)).handle(voidAsyncResult); + return null; + }).when(kafkaConsumer).commit(anyMap(), any()); + + EventHandler>> eventHandler = + Mockito.mock(EventHandler.class); + + doAnswer((Answer>) arguments -> { + AsyncResult asyncResultForMessageDTO = Mockito.mock(AsyncResult.class); + Mockito.when(asyncResultForMessageDTO.succeeded()).thenReturn(true); + JsonObject jsonObject = (JsonObject) ((EventDTO) arguments.getArgument(0)).getBody(); + MessageDTO messageDTO = jsonObject.mapTo(MessageDTO.class); + Mockito.when(asyncResultForMessageDTO.result()).thenReturn(messageDTO); + ((Handler>) arguments.getArgument(1)) + .handle(asyncResultForMessageDTO); + if (!async.isCompleted()) + async.complete(); + return null; + }).when(eventHandler).handle(any(), any()); + + kafkaMosipEventBus.consumeAndSend(MessageBusAddress.PACKET_VALIDATOR_BUS_IN, + MessageBusAddress.PACKET_UPLOADER_OUT, eventHandler); + async.await(); + + InOrder inOrder = Mockito.inOrder(kafkaConsumer, eventHandler); + inOrder.verify(kafkaConsumer, times(1)).pause( + any(io.vertx.kafka.client.common.TopicPartition.class), any()); + inOrder.verify(eventHandler, times(testDataCount)).handle(any(), any()); + inOrder.verify(kafkaConsumer, times(1)).commit(anyMap(), any()); + inOrder.verify(kafkaConsumer, times(1)).resume( + any(io.vertx.kafka.client.common.TopicPartition.class), any()); + verify(kafkaProducer, times(testDataCount)).write(any(), any()); + } + + @Test + public void testConsumeAndSendWithSingleCommitType(TestContext testContext) { + int testDataCount = 20; + kafkaMosipEventBus = new KafkaMosipEventBus(Vertx.vertx(), "localhost:9091", "group_1", + "single", "100", 60000, eventTracingHandler); + final Async async = testContext.async(); + + AsyncResult> asyncResult = + Mockito.mock(AsyncResult.class); + Mockito.when(asyncResult.succeeded()).thenReturn(true); + Mockito.when(asyncResult.result()).thenReturn(prepareKafkaConsumerRecords(testDataCount)); + doAnswer((Answer>>) arguments -> { + ((Handler>>) arguments.getArgument(1)) + .handle(asyncResult); + return null; + }).when(kafkaConsumer).poll(anyLong(), any()); + + AsyncResult voidAsyncResult = Mockito.mock(AsyncResult.class); + Mockito.when(voidAsyncResult.succeeded()).thenReturn(true); + + doAnswer((Answer>) arguments -> { + ((Handler>) arguments.getArgument(1)).handle(voidAsyncResult); + return null; + }).when(kafkaConsumer).pause(any(io.vertx.kafka.client.common.TopicPartition.class), any()); + + doAnswer((Answer>) arguments -> { + ((Handler>) arguments.getArgument(1)).handle(voidAsyncResult); + return null; + }).when(kafkaConsumer).resume(any(io.vertx.kafka.client.common.TopicPartition.class), any()); + + doAnswer((Answer>) arguments -> { + ((Handler>) arguments.getArgument(1)).handle(voidAsyncResult); + return null; + }).when(kafkaConsumer).commit(anyMap(), any()); + + EventHandler>> eventHandler = + Mockito.mock(EventHandler.class); + + doAnswer((Answer>) arguments -> { + AsyncResult asyncResultForMessageDTO = Mockito.mock(AsyncResult.class); + Mockito.when(asyncResultForMessageDTO.succeeded()).thenReturn(true); + JsonObject jsonObject = (JsonObject) ((EventDTO) arguments.getArgument(0)).getBody(); + MessageDTO messageDTO = jsonObject.mapTo(MessageDTO.class); + Mockito.when(asyncResultForMessageDTO.result()).thenReturn(messageDTO); + ((Handler>) arguments.getArgument(1)) + .handle(asyncResultForMessageDTO); + if (!async.isCompleted()) + async.complete(); + return null; + }).when(eventHandler).handle(any(), any()); + + kafkaMosipEventBus.consumeAndSend(MessageBusAddress.PACKET_VALIDATOR_BUS_IN, + MessageBusAddress.PACKET_UPLOADER_OUT, eventHandler); + async.await(); + + verify(eventHandler, times(testDataCount)).handle(any(), any()); + + InOrder inOrder = Mockito.inOrder(kafkaConsumer); + inOrder.verify(kafkaConsumer, times(1)).pause( + any(io.vertx.kafka.client.common.TopicPartition.class), any()); + inOrder.verify(kafkaConsumer, times(testDataCount)).commit(anyMap(), any()); + inOrder.verify(kafkaConsumer, times(1)).resume( + any(io.vertx.kafka.client.common.TopicPartition.class), any()); + + ArgumentCaptor> argument = + ArgumentCaptor.forClass(Map.class); + verify(kafkaConsumer, atLeastOnce()).commit(argument.capture(), any()); + List> values = + argument.getAllValues(); + for(int i=0; i> asyncResult = + Mockito.mock(AsyncResult.class); + Mockito.when(asyncResult.succeeded()).thenReturn(true); + Mockito.when(asyncResult.result()).thenReturn(prepareKafkaConsumerRecords(testDataCount)); + doAnswer((Answer>>) arguments -> { + ((Handler>>) arguments.getArgument(1)) + .handle(asyncResult); + return null; + }).when(kafkaConsumer).poll(anyLong(), any()); + + EventHandler>> eventHandler = + Mockito.mock(EventHandler.class); + doAnswer((Answer>) arguments -> { + AsyncResult asyncResultForMessageDTO = Mockito.mock(AsyncResult.class); + Mockito.when(asyncResultForMessageDTO.succeeded()).thenReturn(true); + JsonObject jsonObject = (JsonObject) ((EventDTO) arguments.getArgument(0)).getBody(); + MessageDTO messageDTO = jsonObject.mapTo(MessageDTO.class); + Mockito.when(asyncResultForMessageDTO.result()).thenReturn(messageDTO); + ((Handler>) arguments.getArgument(1)) + .handle(asyncResultForMessageDTO); + if (!async.isCompleted()) + async.complete(); + + return null; + }).when(eventHandler).handle(any(), any()); + + kafkaMosipEventBus.consume(MessageBusAddress.PACKET_VALIDATOR_BUS_IN, eventHandler); + async.await(); + + verify(eventHandler, times(testDataCount)).handle(any(), any()); + verify(kafkaConsumer, times(0)).pause( + any(io.vertx.kafka.client.common.TopicPartition.class), any()); + verify(kafkaConsumer, times(0)).resume( + any(io.vertx.kafka.client.common.TopicPartition.class), any()); + verify(kafkaConsumer, times(0)).commit(anyMap(), any()); + verify(kafkaProducer, times(0)).write(any(), any()); + } + + @Test + public void testConsumeWithSingleBatchType(TestContext testContext) { + int testDataCount = 20; + kafkaMosipEventBus = new KafkaMosipEventBus(Vertx.vertx(), "localhost:9091", "group_1", + "batch", "100", 60000, eventTracingHandler); + final Async async = testContext.async(); + + AsyncResult> asyncResult = + Mockito.mock(AsyncResult.class); + Mockito.when(asyncResult.succeeded()).thenReturn(true); + Mockito.when(asyncResult.result()).thenReturn(prepareKafkaConsumerRecords(testDataCount)); + doAnswer((Answer>>) arguments -> { + ((Handler>>) arguments.getArgument(1)) + .handle(asyncResult); + return null; + }).when(kafkaConsumer).poll(anyLong(), any()); + + AsyncResult voidAsyncResult = Mockito.mock(AsyncResult.class); + Mockito.when(voidAsyncResult.succeeded()).thenReturn(true); + + doAnswer((Answer>) arguments -> { + ((Handler>) arguments.getArgument(1)).handle(voidAsyncResult); + return null; + }).when(kafkaConsumer).pause(any(io.vertx.kafka.client.common.TopicPartition.class), any()); + + doAnswer((Answer>) arguments -> { + ((Handler>) arguments.getArgument(1)).handle(voidAsyncResult); + return null; + }).when(kafkaConsumer).resume(any(io.vertx.kafka.client.common.TopicPartition.class), any()); + + doAnswer((Answer>) arguments -> { + ((Handler>) arguments.getArgument(1)).handle(voidAsyncResult); + return null; + }).when(kafkaConsumer).commit(anyMap(), any()); + + EventHandler>> eventHandler = + Mockito.mock(EventHandler.class); + + doAnswer((Answer>) arguments -> { + AsyncResult asyncResultForMessageDTO = Mockito.mock(AsyncResult.class); + Mockito.when(asyncResultForMessageDTO.succeeded()).thenReturn(true); + JsonObject jsonObject = (JsonObject) ((EventDTO) arguments.getArgument(0)).getBody(); + MessageDTO messageDTO = jsonObject.mapTo(MessageDTO.class); + Mockito.when(asyncResultForMessageDTO.result()).thenReturn(messageDTO); + ((Handler>) arguments.getArgument(1)) + .handle(asyncResultForMessageDTO); + if (!async.isCompleted()) + async.complete(); + return null; + }).when(eventHandler).handle(any(), any()); + + kafkaMosipEventBus.consume(MessageBusAddress.PACKET_VALIDATOR_BUS_IN, eventHandler); + async.await(); + + InOrder inOrder = Mockito.inOrder(kafkaConsumer, eventHandler); + inOrder.verify(kafkaConsumer, times(1)).pause( + any(io.vertx.kafka.client.common.TopicPartition.class), any()); + inOrder.verify(eventHandler, times(testDataCount)).handle(any(), any()); + inOrder.verify(kafkaConsumer, times(1)).commit(anyMap(), any()); + inOrder.verify(kafkaConsumer, times(1)).resume( + any(io.vertx.kafka.client.common.TopicPartition.class), any()); + verify(kafkaProducer, times(0)).write(any(), any()); + } + + @Test + public void testConsumeWithSingleCommitType(TestContext testContext) { + int testDataCount = 20; + kafkaMosipEventBus = new KafkaMosipEventBus(Vertx.vertx(), "localhost:9091", "group_1", + "single", "100", 60000, eventTracingHandler); + final Async async = testContext.async(); + + AsyncResult> asyncResult = + Mockito.mock(AsyncResult.class); + Mockito.when(asyncResult.succeeded()).thenReturn(true); + Mockito.when(asyncResult.result()).thenReturn(prepareKafkaConsumerRecords(testDataCount)); + doAnswer((Answer>>) arguments -> { + ((Handler>>) arguments.getArgument(1)) + .handle(asyncResult); + return null; + }).when(kafkaConsumer).poll(anyLong(), any()); + + AsyncResult voidAsyncResult = Mockito.mock(AsyncResult.class); + Mockito.when(voidAsyncResult.succeeded()).thenReturn(true); + + doAnswer((Answer>) arguments -> { + ((Handler>) arguments.getArgument(1)).handle(voidAsyncResult); + return null; + }).when(kafkaConsumer).pause(any(io.vertx.kafka.client.common.TopicPartition.class), any()); + + doAnswer((Answer>) arguments -> { + ((Handler>) arguments.getArgument(1)).handle(voidAsyncResult); + return null; + }).when(kafkaConsumer).resume(any(io.vertx.kafka.client.common.TopicPartition.class), any()); + + doAnswer((Answer>) arguments -> { + ((Handler>) arguments.getArgument(1)).handle(voidAsyncResult); + return null; + }).when(kafkaConsumer).commit(anyMap(), any()); + + EventHandler>> eventHandler = + Mockito.mock(EventHandler.class); + + doAnswer((Answer>) arguments -> { + AsyncResult asyncResultForMessageDTO = Mockito.mock(AsyncResult.class); + Mockito.when(asyncResultForMessageDTO.succeeded()).thenReturn(true); + JsonObject jsonObject = (JsonObject) ((EventDTO) arguments.getArgument(0)).getBody(); + MessageDTO messageDTO = jsonObject.mapTo(MessageDTO.class); + Mockito.when(asyncResultForMessageDTO.result()).thenReturn(messageDTO); + ((Handler>) arguments.getArgument(1)) + .handle(asyncResultForMessageDTO); + if (!async.isCompleted()) + async.complete(); + return null; + }).when(eventHandler).handle(any(), any()); + + kafkaMosipEventBus.consume(MessageBusAddress.PACKET_VALIDATOR_BUS_IN, eventHandler); + async.await(); + + verify(eventHandler, times(testDataCount)).handle(any(), any()); + + InOrder inOrder = Mockito.inOrder(kafkaConsumer); + inOrder.verify(kafkaConsumer, times(1)).pause( + any(io.vertx.kafka.client.common.TopicPartition.class), any()); + inOrder.verify(kafkaConsumer, times(testDataCount)).commit(anyMap(), any()); + inOrder.verify(kafkaConsumer, times(1)).resume( + any(io.vertx.kafka.client.common.TopicPartition.class), any()); + + ArgumentCaptor> argument = + ArgumentCaptor.forClass(Map.class); + verify(kafkaConsumer, atLeastOnce()).commit(argument.capture(), any()); + List> values = + argument.getAllValues(); + for(int i=0; i> asyncResult = + Mockito.mock(AsyncResult.class); + Mockito.when(asyncResult.succeeded()).thenReturn(true); + Mockito.when(asyncResult.result()).thenReturn(prepareKafkaConsumerRecords(testDataCount)); + doAnswer((Answer>>) arguments -> { + ((Handler>>) arguments.getArgument(1)) + .handle(asyncResult); + return null; + }).when(kafkaConsumer).poll(anyLong(), any()); + + AsyncResult voidAsyncResult = Mockito.mock(AsyncResult.class); + Mockito.when(voidAsyncResult.succeeded()).thenReturn(true); + + doAnswer((Answer>) arguments -> { + ((Handler>) arguments.getArgument(1)).handle(voidAsyncResult); + return null; + }).when(kafkaConsumer).pause(any(io.vertx.kafka.client.common.TopicPartition.class), any()); + + doAnswer((Answer>) arguments -> { + ((Handler>) arguments.getArgument(1)).handle(voidAsyncResult); + return null; + }).when(kafkaConsumer).resume(any(io.vertx.kafka.client.common.TopicPartition.class), any()); + + doAnswer((Answer>) arguments -> { + ((Handler>) arguments.getArgument(1)).handle(voidAsyncResult); + return null; + }).when(kafkaConsumer).commit(anyMap(), any()); + + EventHandler>> eventHandler = + Mockito.mock(EventHandler.class); + doAnswer((Answer>) arguments -> { + AsyncResult asyncResultForMessageDTO = Mockito.mock(AsyncResult.class); + Mockito.when(asyncResultForMessageDTO.succeeded()).thenReturn(false); + Mockito.when(asyncResultForMessageDTO.cause()).thenReturn(new MessageExpiredException()); + ((Handler>) arguments.getArgument(1)) + .handle(asyncResultForMessageDTO); + if (!async.isCompleted()) + async.complete(); + + return null; + }).when(eventHandler).handle(any(), any()); + + kafkaMosipEventBus.consumeAndSend(MessageBusAddress.PACKET_VALIDATOR_BUS_IN, + MessageBusAddress.PACKET_UPLOADER_OUT, eventHandler); + async.await(); + + verify(eventHandler, times(testDataCount)).handle(any(), any()); + verify(kafkaConsumer, times(1)).pause( + any(io.vertx.kafka.client.common.TopicPartition.class), any()); + verify(kafkaConsumer, times(1)).resume( + any(io.vertx.kafka.client.common.TopicPartition.class), any()); + verify(kafkaConsumer, times(1)).commit(anyMap(), any()); + verify(kafkaProducer, times(0)).write(any(), any()); + } + + @Test + public void testConsumeWithMessageExpiredException(TestContext testContext) { + int testDataCount = 20; + kafkaMosipEventBus = new KafkaMosipEventBus(vertx, "localhost:9091", "group_1", + "batch", "100", 60000, eventTracingHandler); + final Async async = testContext.async(); + + AsyncResult> asyncResult = + Mockito.mock(AsyncResult.class); + Mockito.when(asyncResult.succeeded()).thenReturn(true); + Mockito.when(asyncResult.result()).thenReturn(prepareKafkaConsumerRecords(testDataCount)); + doAnswer((Answer>>) arguments -> { + ((Handler>>) arguments.getArgument(1)) + .handle(asyncResult); + return null; + }).when(kafkaConsumer).poll(anyLong(), any()); + + AsyncResult voidAsyncResult = Mockito.mock(AsyncResult.class); + Mockito.when(voidAsyncResult.succeeded()).thenReturn(true); + + doAnswer((Answer>) arguments -> { + ((Handler>) arguments.getArgument(1)).handle(voidAsyncResult); + return null; + }).when(kafkaConsumer).pause(any(io.vertx.kafka.client.common.TopicPartition.class), any()); + + doAnswer((Answer>) arguments -> { + ((Handler>) arguments.getArgument(1)).handle(voidAsyncResult); + return null; + }).when(kafkaConsumer).resume(any(io.vertx.kafka.client.common.TopicPartition.class), any()); + + doAnswer((Answer>) arguments -> { + ((Handler>) arguments.getArgument(1)).handle(voidAsyncResult); + return null; + }).when(kafkaConsumer).commit(anyMap(), any()); + + EventHandler>> eventHandler = + Mockito.mock(EventHandler.class); + doAnswer((Answer>) arguments -> { + AsyncResult asyncResultForMessageDTO = Mockito.mock(AsyncResult.class); + Mockito.when(asyncResultForMessageDTO.succeeded()).thenReturn(false); + Mockito.when(asyncResultForMessageDTO.cause()).thenReturn(new MessageExpiredException()); + ((Handler>) arguments.getArgument(1)) + .handle(asyncResultForMessageDTO); + if (!async.isCompleted()) + async.complete(); + + return null; + }).when(eventHandler).handle(any(), any()); + + kafkaMosipEventBus.consume(MessageBusAddress.PACKET_VALIDATOR_BUS_IN, eventHandler); + async.await(); + + verify(eventHandler, times(testDataCount)).handle(any(), any()); + verify(kafkaConsumer, times(1)).pause( + any(io.vertx.kafka.client.common.TopicPartition.class), any()); + verify(kafkaConsumer, times(1)).resume( + any(io.vertx.kafka.client.common.TopicPartition.class), any()); + verify(kafkaConsumer, times(1)).commit(anyMap(), any()); + verify(kafkaProducer, times(0)).write(any(), any()); + } + + private KafkaConsumerRecords prepareKafkaConsumerRecords(int recordCount) { + List> consumerRecordList = new ArrayList<>(); + for(int i=0; i( + MessageBusAddress.PACKET_VALIDATOR_BUS_IN.getAddress(), 0, i, "1000"+i, + "{\"rid\":\"1000"+i+"\", \"reg_type\": \"NEW\" }")); + Map>> topicPartitionConsumerRecordListMap = + new HashMap>>(); + topicPartitionConsumerRecordListMap.put( + new TopicPartition(MessageBusAddress.PACKET_VALIDATOR_BUS_IN.getAddress(), 0), + consumerRecordList); + ConsumerRecords consumerRecords = + new ConsumerRecords(topicPartitionConsumerRecordListMap); + KafkaConsumerRecords kafkaConsumerRecords = + new KafkaConsumerRecordsImpl(consumerRecords); + return kafkaConsumerRecords; + } + + @Test + public void testConsumerHealthCheck(TestContext testContext) { + kafkaMosipEventBus = new KafkaMosipEventBus(vertx, "localhost:9091", "group_1", "batch", "100", 60000, + eventTracingHandler); + final Async async = testContext.async(); + Handler eventHandler = Mockito.mock(Handler.class); + AsyncResult>> asyncResult = Mockito.mock(AsyncResult.class); + Mockito.when(asyncResult.succeeded()).thenReturn(true); + doAnswer((Answer>>>) arguments -> { + ((Handler>>>) arguments.getArgument(0)).handle(asyncResult); + if (!async.isCompleted()) + async.complete(); + return null; + }).when(kafkaConsumer).listTopics(any()); + kafkaMosipEventBus.consumerHealthCheck(eventHandler, MessageBusAddress.PACKET_VALIDATOR_BUS_IN.toString()); + async.await(); + ArgumentCaptor argument = ArgumentCaptor.forClass(HealthCheckDTO.class); + verify(eventHandler, times(1)).handle(argument.capture()); + assertTrue(argument.getValue().isEventBusConnected()); + verify(kafkaConsumer, times(1)).listTopics(any()); + } + + @Test + public void testConsumerHealthCheckWithException(TestContext testContext) { + kafkaMosipEventBus = new KafkaMosipEventBus(vertx, "localhost:9091", "group_1", "batch", "100", 60000, + eventTracingHandler); + final Async async = testContext.async(); + Handler eventHandler = Mockito.mock(Handler.class); + AsyncResult>> asyncResult = Mockito.mock(AsyncResult.class); + Mockito.when(asyncResult.succeeded()).thenReturn(false); + Mockito.when(asyncResult.cause()).thenReturn(new Exception("kafka consumer failed")); + doAnswer((Answer>>>) arguments -> { + ((Handler>>>) arguments.getArgument(0)).handle(asyncResult); + if (!async.isCompleted()) + async.complete(); + return null; + }).when(kafkaConsumer).listTopics(any()); + kafkaMosipEventBus.consumerHealthCheck(eventHandler, MessageBusAddress.PACKET_VALIDATOR_BUS_IN.toString()); + async.await(); + ArgumentCaptor argument = ArgumentCaptor.forClass(HealthCheckDTO.class); + verify(eventHandler, times(1)).handle(argument.capture()); + assertFalse(argument.getValue().isEventBusConnected()); + assertEquals("kafka consumer failed", argument.getValue().getFailureReason()); + verify(kafkaConsumer, times(1)).listTopics(any()); + } + + @Test(expected = TimeoutException.class) + 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(); + Mockito.when(kafkaConsumer.listTopics(any())).thenThrow(timeout); + kafkaMosipEventBus.consumerHealthCheck(eventHandler, MessageBusAddress.PACKET_VALIDATOR_BUS_IN.toString()); + verify(kafkaConsumer, times(1)).listTopics(any()); + } + + @Test + public void testSenderHealthCheck(TestContext testContext) { + kafkaMosipEventBus = new KafkaMosipEventBus(vertx, "localhost:9091", "group_1", "batch", "100", 60000, + eventTracingHandler); + Handler eventHandler = Mockito.mock(Handler.class); + kafkaMosipEventBus.senderHealthCheck(eventHandler, MessageBusAddress.PACKET_VALIDATOR_BUS_IN.toString()); + ArgumentCaptor argument = ArgumentCaptor.forClass(HealthCheckDTO.class); + verify(eventHandler, times(1)).handle(argument.capture()); + assertTrue(argument.getValue().isEventBusConnected()); + } + + @Test + public void testSenderHealthCheckFail(TestContext testContext) { + kafkaMosipEventBus = new KafkaMosipEventBus(vertx, "localhost:9091", "group_1", "batch", "100", 60000, + eventTracingHandler); + ReflectionTestUtils.setField(kafkaMosipEventBus, "kafkaProducer", null); + Handler eventHandler = Mockito.mock(Handler.class); + kafkaMosipEventBus.senderHealthCheck(eventHandler, MessageBusAddress.PACKET_VALIDATOR_BUS_IN.toString()); + ArgumentCaptor argument = ArgumentCaptor.forClass(HealthCheckDTO.class); + verify(eventHandler, times(1)).handle(argument.capture()); + assertFalse(argument.getValue().isEventBusConnected()); + } +} 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 98bfb5d4dff..4953c81cb49 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,291 +1,304 @@ -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.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<>(); - } - - /** - * 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) { - - } - }; - } - }; - - /** - * 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(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")); - } - /** - * 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<>(); + } + + /** + * 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(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")); + } + /** + * 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; + } + + }; + } +} diff --git a/registration-processor/workflow-engine/registration-processor-reprocessor/src/test/java/io/mosip/registration/processor/reprocessor/verticle/ReprocessorVerticleTest.java b/registration-processor/workflow-engine/registration-processor-reprocessor/src/test/java/io/mosip/registration/processor/reprocessor/verticle/ReprocessorVerticleTest.java index 600690f2e89..30e68bf55f1 100644 --- a/registration-processor/workflow-engine/registration-processor-reprocessor/src/test/java/io/mosip/registration/processor/reprocessor/verticle/ReprocessorVerticleTest.java +++ b/registration-processor/workflow-engine/registration-processor-reprocessor/src/test/java/io/mosip/registration/processor/reprocessor/verticle/ReprocessorVerticleTest.java @@ -1,248 +1,261 @@ -package io.mosip.registration.processor.reprocessor.verticle; - -import static org.junit.Assert.assertEquals; -import static org.mockito.ArgumentMatchers.anyInt; -import static org.mockito.ArgumentMatchers.anyList; -import static org.mockito.ArgumentMatchers.anyLong; - -import java.lang.reflect.Field; -import java.time.LocalDateTime; -import java.util.ArrayList; -import java.util.List; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.runners.MockitoJUnitRunner; -import org.springframework.test.util.ReflectionTestUtils; - -import io.mosip.registration.processor.core.abstractverticle.EventDTO; -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.RegistrationTransactionStatusCode; -import io.mosip.registration.processor.core.exception.ApisResourceAccessException; -import io.mosip.registration.processor.core.exception.PacketManagerException; -import io.mosip.registration.processor.core.exception.WorkflowActionException; -import io.mosip.registration.processor.core.http.ResponseWrapper; -import io.mosip.registration.processor.core.logger.LogDescription; -import io.mosip.registration.processor.core.spi.eventbus.EventHandler; -import io.mosip.registration.processor.core.spi.restclient.RegistrationProcessorRestClientService; -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.code.RegistrationType; -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.vertx.core.AsyncResult; -import io.vertx.core.Handler; -import io.vertx.core.Vertx; - -@RunWith(MockitoJUnitRunner.class) -public class ReprocessorVerticleTest { - - MessageDTO dto = new MessageDTO(); - @InjectMocks - private ReprocessorVerticle reprocessorVerticle = new ReprocessorVerticle() { - @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 send(MosipEventBus mosipEventBus, MessageBusAddress toAddress, MessageDTO message) { - } - }; - - @Mock - RegistrationStatusService registrationStatusService; - - @Mock - private AuditLogRequestBuilder auditLogRequestBuilder; - - @Mock - private LogDescription description; - - - @Before - public void setup() throws Exception { - //Mockito.doNothing().when(description).setCode(Mockito.anyString()); - //Mockito.doNothing().when(description).setMessage(Mockito.anyString()); - //Mockito.when(description.getCode()).thenReturn("CODE"); - //Mockito.when(description.getMessage()).thenReturn("MESSAGE"); - ReflectionTestUtils.setField(reprocessorVerticle, "fetchSize", 2); - ReflectionTestUtils.setField(reprocessorVerticle, "elapseTime", 21600); - ReflectionTestUtils.setField(reprocessorVerticle, "reprocessCount", 3); - 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); - auditLogRequestBuilder.createAuditRequestBuilder("test case description", EventId.RPR_401.toString(), EventName.ADD.toString(), - EventType.BUSINESS.toString(), "1234testcase", ApiName.AUDIT); - } - - @Test - public void testProcessValid() throws TablenotAccessibleException, PacketManagerException, - ApisResourceAccessException, WorkflowActionException { - - List dtolist = new ArrayList<>(); - InternalRegistrationStatusDto registrationStatusDto = new InternalRegistrationStatusDto(); - - registrationStatusDto.setRegistrationId("2018701130000410092018110735"); - registrationStatusDto.setRegistrationType(RegistrationType.NEW.toString()); - registrationStatusDto.setRegistrationStageName("PacketValidatorStage"); - registrationStatusDto.setDefaultResumeAction("RESUME_PROCESSING"); - registrationStatusDto.setResumeTimeStamp(LocalDateTime.now()); - registrationStatusDto.setReProcessRetryCount(0); - registrationStatusDto.setLatestTransactionStatusCode(RegistrationTransactionStatusCode.REPROCESS.toString()); - dtolist.add(registrationStatusDto); - InternalRegistrationStatusDto registrationStatusDto1 = new InternalRegistrationStatusDto(); - - registrationStatusDto1.setRegistrationId("2018701130000410092018110734"); - registrationStatusDto1.setRegistrationStageName("PacketValidatorStage"); - registrationStatusDto1.setReProcessRetryCount(1); - registrationStatusDto1.setRegistrationType("NEW"); - registrationStatusDto1.setLatestTransactionStatusCode(RegistrationTransactionStatusCode.SUCCESS.toString()); - dtolist.add(registrationStatusDto1); - Mockito.when(registrationStatusService.getUnProcessedPackets(anyInt(), anyLong(), anyInt(), anyList())) - .thenReturn(dtolist); - reprocessorVerticle.process(dto); - - } - - @Test - public void testProcessFailure() throws TablenotAccessibleException, PacketManagerException, - ApisResourceAccessException, WorkflowActionException { - - List dtolist = new ArrayList<>(); - InternalRegistrationStatusDto registrationStatusDto = new InternalRegistrationStatusDto(); - - registrationStatusDto.setRegistrationId("2018701130000410092018110735"); - registrationStatusDto.setRegistrationStageName("PacketValidatorStage"); - - registrationStatusDto.setDefaultResumeAction("RESUME_PROCESSING"); - registrationStatusDto.setResumeTimeStamp(LocalDateTime.now()); - registrationStatusDto.setRegistrationType("NEW"); - registrationStatusDto.setLatestTransactionStatusCode(RegistrationTransactionStatusCode.REPROCESS.toString()); - dtolist.add(registrationStatusDto); - InternalRegistrationStatusDto registrationStatusDto1 = new InternalRegistrationStatusDto(); - - registrationStatusDto1.setRegistrationId("2018701130000410092018110734"); - registrationStatusDto1.setRegistrationStageName("PacketValidatorStage"); - registrationStatusDto1.setReProcessRetryCount(3); - registrationStatusDto1.setRegistrationType("NEW"); - registrationStatusDto1.setLatestTransactionStatusCode(RegistrationTransactionStatusCode.SUCCESS.toString()); - dtolist.add(registrationStatusDto1); - Mockito.when(registrationStatusService.getUnProcessedPackets(anyInt(), anyLong(), anyInt(), anyList())) - .thenReturn(dtolist); - reprocessorVerticle.process(dto); - - } - - /** - * Exception test. - * - * @throws Exception - * the exception - */ - @Test - public void exceptionTest() throws Exception { - Mockito.when(registrationStatusService.getUnProcessedPackets(anyInt(),anyLong(), anyInt(), anyList())) - .thenReturn(null); - dto = reprocessorVerticle.process(dto); - assertEquals(null, dto.getIsValid()); - - } - - @Test - public void nullPointerExceptionTest() throws Exception { - Mockito.when(registrationStatusService.getResumablePackets(anyInt())) - .thenThrow(NullPointerException.class); - dto = reprocessorVerticle.process(dto); - assertEquals(null, dto.getIsValid()); - } - - @Test - public void TablenotAccessibleExceptionTest() throws Exception { - Mockito.when(registrationStatusService.getUnProcessedPackets(anyInt(), anyLong(), anyInt(), anyList())) - .thenThrow(new TablenotAccessibleException("") { - }); - - dto = reprocessorVerticle.process(dto); - assertEquals(true, dto.getInternalError()); - - } - - @Test - public void testProcessValidWithResumablePackets() throws TablenotAccessibleException, PacketManagerException, - ApisResourceAccessException, WorkflowActionException { - - List dtolist = new ArrayList<>(); - InternalRegistrationStatusDto registrationStatusDto = new InternalRegistrationStatusDto(); - - registrationStatusDto.setRegistrationId("2018701130000410092018110735"); - registrationStatusDto.setRegistrationType(RegistrationType.NEW.toString()); - registrationStatusDto.setRegistrationStageName("PacketValidatorStage"); - registrationStatusDto.setDefaultResumeAction("RESUME_PROCESSING"); - registrationStatusDto.setResumeTimeStamp(LocalDateTime.now()); - registrationStatusDto.setReProcessRetryCount(0); - registrationStatusDto.setLatestTransactionStatusCode(RegistrationTransactionStatusCode.REPROCESS.toString()); - dtolist.add(registrationStatusDto); - List reprocessorDtoList = new ArrayList<>(); - InternalRegistrationStatusDto registrationStatusDto1 = new InternalRegistrationStatusDto(); - - registrationStatusDto1.setRegistrationId("2018701130000410092018110734"); - registrationStatusDto1.setRegistrationStageName("PacketValidatorStage"); - registrationStatusDto1.setReProcessRetryCount(1); - registrationStatusDto1.setRegistrationType("NEW"); - registrationStatusDto1.setLatestTransactionStatusCode(RegistrationTransactionStatusCode.SUCCESS.toString()); - reprocessorDtoList.add(registrationStatusDto1); - Mockito.when(registrationStatusService.getResumablePackets(anyInt())) - .thenReturn(dtolist); - Mockito.when(registrationStatusService.getUnProcessedPackets(anyInt(), anyLong(), anyInt(), anyList())) - .thenReturn(reprocessorDtoList); - reprocessorVerticle.process(dto); - - } -} +package io.mosip.registration.processor.reprocessor.verticle; + +import static org.junit.Assert.assertEquals; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyList; +import static org.mockito.ArgumentMatchers.anyLong; + +import java.lang.reflect.Field; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.List; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.runners.MockitoJUnitRunner; +import org.springframework.test.util.ReflectionTestUtils; + +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.RegistrationTransactionStatusCode; +import io.mosip.registration.processor.core.exception.ApisResourceAccessException; +import io.mosip.registration.processor.core.exception.PacketManagerException; +import io.mosip.registration.processor.core.exception.WorkflowActionException; +import io.mosip.registration.processor.core.http.ResponseWrapper; +import io.mosip.registration.processor.core.logger.LogDescription; +import io.mosip.registration.processor.core.spi.eventbus.EventHandler; +import io.mosip.registration.processor.core.spi.restclient.RegistrationProcessorRestClientService; +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.code.RegistrationType; +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.vertx.core.AsyncResult; +import io.vertx.core.Handler; +import io.vertx.core.Vertx; + +@RunWith(MockitoJUnitRunner.class) +public class ReprocessorVerticleTest { + + MessageDTO dto = new MessageDTO(); + @InjectMocks + private ReprocessorVerticle reprocessorVerticle = new ReprocessorVerticle() { + @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 send(MosipEventBus mosipEventBus, MessageBusAddress toAddress, MessageDTO message) { + } + }; + + @Mock + RegistrationStatusService registrationStatusService; + + @Mock + private AuditLogRequestBuilder auditLogRequestBuilder; + + @Mock + private LogDescription description; + + + @Before + public void setup() throws Exception { + //Mockito.doNothing().when(description).setCode(Mockito.anyString()); + //Mockito.doNothing().when(description).setMessage(Mockito.anyString()); + //Mockito.when(description.getCode()).thenReturn("CODE"); + //Mockito.when(description.getMessage()).thenReturn("MESSAGE"); + ReflectionTestUtils.setField(reprocessorVerticle, "fetchSize", 2); + ReflectionTestUtils.setField(reprocessorVerticle, "elapseTime", 21600); + ReflectionTestUtils.setField(reprocessorVerticle, "reprocessCount", 3); + 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); + auditLogRequestBuilder.createAuditRequestBuilder("test case description", EventId.RPR_401.toString(), EventName.ADD.toString(), + EventType.BUSINESS.toString(), "1234testcase", ApiName.AUDIT); + } + + @Test + public void testProcessValid() throws TablenotAccessibleException, PacketManagerException, + ApisResourceAccessException, WorkflowActionException { + + List dtolist = new ArrayList<>(); + InternalRegistrationStatusDto registrationStatusDto = new InternalRegistrationStatusDto(); + + registrationStatusDto.setRegistrationId("2018701130000410092018110735"); + registrationStatusDto.setRegistrationType(RegistrationType.NEW.toString()); + registrationStatusDto.setRegistrationStageName("PacketValidatorStage"); + registrationStatusDto.setDefaultResumeAction("RESUME_PROCESSING"); + registrationStatusDto.setResumeTimeStamp(LocalDateTime.now()); + registrationStatusDto.setReProcessRetryCount(0); + registrationStatusDto.setLatestTransactionStatusCode(RegistrationTransactionStatusCode.REPROCESS.toString()); + dtolist.add(registrationStatusDto); + InternalRegistrationStatusDto registrationStatusDto1 = new InternalRegistrationStatusDto(); + + registrationStatusDto1.setRegistrationId("2018701130000410092018110734"); + registrationStatusDto1.setRegistrationStageName("PacketValidatorStage"); + registrationStatusDto1.setReProcessRetryCount(1); + registrationStatusDto1.setRegistrationType("NEW"); + registrationStatusDto1.setLatestTransactionStatusCode(RegistrationTransactionStatusCode.SUCCESS.toString()); + dtolist.add(registrationStatusDto1); + Mockito.when(registrationStatusService.getUnProcessedPackets(anyInt(), anyLong(), anyInt(), anyList())) + .thenReturn(dtolist); + reprocessorVerticle.process(dto); + + } + + @Test + public void testProcessFailure() throws TablenotAccessibleException, PacketManagerException, + ApisResourceAccessException, WorkflowActionException { + + List dtolist = new ArrayList<>(); + InternalRegistrationStatusDto registrationStatusDto = new InternalRegistrationStatusDto(); + + registrationStatusDto.setRegistrationId("2018701130000410092018110735"); + registrationStatusDto.setRegistrationStageName("PacketValidatorStage"); + + registrationStatusDto.setDefaultResumeAction("RESUME_PROCESSING"); + registrationStatusDto.setResumeTimeStamp(LocalDateTime.now()); + registrationStatusDto.setRegistrationType("NEW"); + registrationStatusDto.setLatestTransactionStatusCode(RegistrationTransactionStatusCode.REPROCESS.toString()); + dtolist.add(registrationStatusDto); + InternalRegistrationStatusDto registrationStatusDto1 = new InternalRegistrationStatusDto(); + + registrationStatusDto1.setRegistrationId("2018701130000410092018110734"); + registrationStatusDto1.setRegistrationStageName("PacketValidatorStage"); + registrationStatusDto1.setReProcessRetryCount(3); + registrationStatusDto1.setRegistrationType("NEW"); + registrationStatusDto1.setLatestTransactionStatusCode(RegistrationTransactionStatusCode.SUCCESS.toString()); + dtolist.add(registrationStatusDto1); + Mockito.when(registrationStatusService.getUnProcessedPackets(anyInt(), anyLong(), anyInt(), anyList())) + .thenReturn(dtolist); + reprocessorVerticle.process(dto); + + } + + /** + * Exception test. + * + * @throws Exception + * the exception + */ + @Test + public void exceptionTest() throws Exception { + Mockito.when(registrationStatusService.getUnProcessedPackets(anyInt(),anyLong(), anyInt(), anyList())) + .thenReturn(null); + dto = reprocessorVerticle.process(dto); + assertEquals(null, dto.getIsValid()); + + } + + @Test + public void nullPointerExceptionTest() throws Exception { + Mockito.when(registrationStatusService.getResumablePackets(anyInt())) + .thenThrow(NullPointerException.class); + dto = reprocessorVerticle.process(dto); + assertEquals(null, dto.getIsValid()); + } + + @Test + public void TablenotAccessibleExceptionTest() throws Exception { + Mockito.when(registrationStatusService.getUnProcessedPackets(anyInt(), anyLong(), anyInt(), anyList())) + .thenThrow(new TablenotAccessibleException("") { + }); + + dto = reprocessorVerticle.process(dto); + assertEquals(true, dto.getInternalError()); + + } + + @Test + public void testProcessValidWithResumablePackets() throws TablenotAccessibleException, PacketManagerException, + ApisResourceAccessException, WorkflowActionException { + + List dtolist = new ArrayList<>(); + InternalRegistrationStatusDto registrationStatusDto = new InternalRegistrationStatusDto(); + + registrationStatusDto.setRegistrationId("2018701130000410092018110735"); + registrationStatusDto.setRegistrationType(RegistrationType.NEW.toString()); + registrationStatusDto.setRegistrationStageName("PacketValidatorStage"); + registrationStatusDto.setDefaultResumeAction("RESUME_PROCESSING"); + registrationStatusDto.setResumeTimeStamp(LocalDateTime.now()); + registrationStatusDto.setReProcessRetryCount(0); + registrationStatusDto.setLatestTransactionStatusCode(RegistrationTransactionStatusCode.REPROCESS.toString()); + dtolist.add(registrationStatusDto); + List reprocessorDtoList = new ArrayList<>(); + InternalRegistrationStatusDto registrationStatusDto1 = new InternalRegistrationStatusDto(); + + registrationStatusDto1.setRegistrationId("2018701130000410092018110734"); + registrationStatusDto1.setRegistrationStageName("PacketValidatorStage"); + registrationStatusDto1.setReProcessRetryCount(1); + registrationStatusDto1.setRegistrationType("NEW"); + registrationStatusDto1.setLatestTransactionStatusCode(RegistrationTransactionStatusCode.SUCCESS.toString()); + reprocessorDtoList.add(registrationStatusDto1); + Mockito.when(registrationStatusService.getResumablePackets(anyInt())) + .thenReturn(dtolist); + Mockito.when(registrationStatusService.getUnProcessedPackets(anyInt(), anyLong(), anyInt(), anyList())) + .thenReturn(reprocessorDtoList); + reprocessorVerticle.process(dto); + + } +} diff --git a/registration-processor/workflow-engine/registration-processor-workflow-manager-service/src/test/java/io/mosip/registration/processor/workflowmanager/verticle/WorkflowActionApiTest.java b/registration-processor/workflow-engine/registration-processor-workflow-manager-service/src/test/java/io/mosip/registration/processor/workflowmanager/verticle/WorkflowActionApiTest.java index 9d2a0a85ee6..7f64c4ff413 100644 --- a/registration-processor/workflow-engine/registration-processor-workflow-manager-service/src/test/java/io/mosip/registration/processor/workflowmanager/verticle/WorkflowActionApiTest.java +++ b/registration-processor/workflow-engine/registration-processor-workflow-manager-service/src/test/java/io/mosip/registration/processor/workflowmanager/verticle/WorkflowActionApiTest.java @@ -19,6 +19,7 @@ import io.mosip.kernel.core.exception.NullPointerException; 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; @@ -124,6 +125,18 @@ public void consumeAndSend(MessageBusAddress fromAddress, MessageBusAddress toAd 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 + + } }; } diff --git a/registration-processor/workflow-engine/registration-processor-workflow-manager-service/src/test/java/io/mosip/registration/processor/workflowmanager/verticle/WorkflowActionJobSchedularTest.java b/registration-processor/workflow-engine/registration-processor-workflow-manager-service/src/test/java/io/mosip/registration/processor/workflowmanager/verticle/WorkflowActionJobSchedularTest.java index 6e2e4502507..d2b21bc0ad0 100644 --- a/registration-processor/workflow-engine/registration-processor-workflow-manager-service/src/test/java/io/mosip/registration/processor/workflowmanager/verticle/WorkflowActionJobSchedularTest.java +++ b/registration-processor/workflow-engine/registration-processor-workflow-manager-service/src/test/java/io/mosip/registration/processor/workflowmanager/verticle/WorkflowActionJobSchedularTest.java @@ -1,285 +1,297 @@ -package io.mosip.registration.processor.workflowmanager.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.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 org.springframework.test.util.ReflectionTestUtils; - -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.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.mosip.registration.processor.workflowmanager.verticle.WorkflowActionJob; -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; - -@RunWith(MockitoJUnitRunner.class) -public class WorkflowActionJobSchedularTest { - /** - * 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(WorkflowActionJob.class); - listAppender = new ListAppender<>(); - ReflectionTestUtils.setField(workflowActionJob, "clusterManagerUrl", "/dummyPath"); - } - - - @InjectMocks - WorkflowActionJob workflowActionJob = new WorkflowActionJob() { - /* - * (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) { - - } - }; - } - }; - - /** - * Success Test for deployment of ReprocessorVerticle - */ - @Test - public void testDeploySuccess() { - workflowActionJob.deployVerticle(); - assertNotNull(workflowActionJob.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()); - workflowActionJob.schedulerResult(res); - Assertions.assertThat(listAppender.list).extracting(ILoggingEvent::getLevel, ILoggingEvent::getFormattedMessage) - .contains(Tuple.tuple(Level.INFO, - "WorkflowActionJob::schedular()::deployed")); - } - - /** - * Failure Test for Chime Scheduler deployment - */ - @Test - public void testDeploySchedulerFailureTest() { - listAppender.start(); - fooLogger.addAppender(listAppender); - Mockito.when(res.succeeded()).thenReturn(false); - workflowActionJob.schedulerResult(res); - Assertions.assertThat(listAppender.list).extracting(ILoggingEvent::getLevel, ILoggingEvent::getFormattedMessage) - .contains(Tuple.tuple(Level.ERROR, "WorkflowActionJob::schedular()::deployment failure")); - } - - /** - * 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.workflowmanager.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.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 org.springframework.test.util.ReflectionTestUtils; + +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; + +@RunWith(MockitoJUnitRunner.class) +public class WorkflowActionJobSchedularTest { + /** + * 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(WorkflowActionJob.class); + listAppender = new ListAppender<>(); + ReflectionTestUtils.setField(workflowActionJob, "clusterManagerUrl", "/dummyPath"); + } + + + @InjectMocks + WorkflowActionJob workflowActionJob = new WorkflowActionJob() { + /* + * (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() { + workflowActionJob.deployVerticle(); + assertNotNull(workflowActionJob.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()); + workflowActionJob.schedulerResult(res); + Assertions.assertThat(listAppender.list).extracting(ILoggingEvent::getLevel, ILoggingEvent::getFormattedMessage) + .contains(Tuple.tuple(Level.INFO, + "WorkflowActionJob::schedular()::deployed")); + } + + /** + * Failure Test for Chime Scheduler deployment + */ + @Test + public void testDeploySchedulerFailureTest() { + listAppender.start(); + fooLogger.addAppender(listAppender); + Mockito.when(res.succeeded()).thenReturn(false); + workflowActionJob.schedulerResult(res); + Assertions.assertThat(listAppender.list).extracting(ILoggingEvent::getLevel, ILoggingEvent::getFormattedMessage) + .contains(Tuple.tuple(Level.ERROR, "WorkflowActionJob::schedular()::deployment failure")); + } + + /** + * 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; + } + + }; + } +} diff --git a/registration-processor/workflow-engine/registration-processor-workflow-manager-service/src/test/java/io/mosip/registration/processor/workflowmanager/verticle/WorkflowActionJobTest.java b/registration-processor/workflow-engine/registration-processor-workflow-manager-service/src/test/java/io/mosip/registration/processor/workflowmanager/verticle/WorkflowActionJobTest.java index 7ea25762637..a1cc5bd5b7e 100644 --- a/registration-processor/workflow-engine/registration-processor-workflow-manager-service/src/test/java/io/mosip/registration/processor/workflowmanager/verticle/WorkflowActionJobTest.java +++ b/registration-processor/workflow-engine/registration-processor-workflow-manager-service/src/test/java/io/mosip/registration/processor/workflowmanager/verticle/WorkflowActionJobTest.java @@ -21,14 +21,11 @@ import org.springframework.test.util.ReflectionTestUtils; 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.AuditLogConstant; -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.RegistrationTransactionStatusCode; import io.mosip.registration.processor.core.exception.WorkflowActionException; import io.mosip.registration.processor.core.http.ResponseWrapper; @@ -78,6 +75,18 @@ public void consumeAndSend(MessageBusAddress fromAddress, MessageBusAddress toAd 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 + + } }; } diff --git a/registration-processor/workflow-engine/registration-processor-workflow-manager-service/src/test/java/io/mosip/registration/processor/workflowmanager/verticle/WorkflowInternalActionVerticleTest.java b/registration-processor/workflow-engine/registration-processor-workflow-manager-service/src/test/java/io/mosip/registration/processor/workflowmanager/verticle/WorkflowInternalActionVerticleTest.java index 14ef0f03f3b..d4adda30b5c 100644 --- a/registration-processor/workflow-engine/registration-processor-workflow-manager-service/src/test/java/io/mosip/registration/processor/workflowmanager/verticle/WorkflowInternalActionVerticleTest.java +++ b/registration-processor/workflow-engine/registration-processor-workflow-manager-service/src/test/java/io/mosip/registration/processor/workflowmanager/verticle/WorkflowInternalActionVerticleTest.java @@ -1,703 +1,714 @@ -package io.mosip.registration.processor.workflowmanager.verticle; - -import static org.junit.Assert.assertEquals; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyDouble; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.atLeastOnce; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - -import java.io.IOException; -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 org.apache.commons.collections.map.HashedMap; -import org.json.JSONException; -import org.json.simple.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.ArgumentCaptor; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.core.env.Environment; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.util.ReflectionTestUtils; - -import io.mosip.kernel.biometrics.entities.BIR; -import io.mosip.kernel.biometrics.entities.BiometricRecord; -import io.mosip.kernel.core.exception.BaseCheckedException; -import io.mosip.kernel.core.util.exception.JsonProcessingException; -import io.mosip.registration.processor.core.abstractverticle.EventDTO; -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.WorkflowInternalActionDTO; -import io.mosip.registration.processor.core.code.WorkflowActionCode; -import io.mosip.registration.processor.core.code.WorkflowInternalActionCode; -import io.mosip.registration.processor.core.exception.ApisResourceAccessException; -import io.mosip.registration.processor.core.exception.PacketManagerException; -import io.mosip.registration.processor.core.exception.WorkflowActionException; -import io.mosip.registration.processor.core.exception.util.PlatformSuccessMessages; -import io.mosip.registration.processor.core.packet.dto.AdditionalInfoRequestDto; -import io.mosip.registration.processor.core.spi.eventbus.EventHandler; -import io.mosip.registration.processor.core.workflow.dto.WorkflowCompletedEventDTO; -import io.mosip.registration.processor.core.workflow.dto.WorkflowPausedForAdditionalInfoEventDTO; -import io.mosip.registration.processor.packet.storage.utils.IdSchemaUtil; -import io.mosip.registration.processor.packet.storage.utils.PacketManagerService; -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.AdditionalInfoRequestService; -import io.mosip.registration.processor.status.service.AnonymousProfileService; -import io.mosip.registration.processor.status.service.RegistrationStatusService; -import io.mosip.registration.processor.workflowmanager.service.WorkflowActionService; -import io.mosip.registration.processor.workflowmanager.util.WebSubUtil; -import io.vertx.core.AsyncResult; -import io.vertx.core.Handler; -import io.vertx.core.Vertx; -import io.vertx.ext.web.Router; - -@RunWith(SpringRunner.class) -public class WorkflowInternalActionVerticleTest { - @Mock - private MosipRouter router; - @Mock - MosipEventBus mosipEventBus; - - @Mock - RegistrationStatusService registrationStatusService; - - private InternalRegistrationStatusDto registrationStatusDto; - - @Mock - private AuditLogRequestBuilder auditLogRequestBuilder; - - @Mock - WebSubUtil webSubUtil; - - @Mock - private AdditionalInfoRequestService additionalInfoRequestService; - - @Mock - WorkflowActionService workflowActionService; - - @Mock - private PacketManagerService packetManagerService; - - @Mock - private AnonymousProfileService anonymousProfileService; - - @Mock - private IdSchemaUtil idSchemaUtil; - - @Mock - private Utilities utility; - - @Mock - private Environment env; - - - @InjectMocks - private WorkflowInternalActionVerticle workflowInternalActionVerticle = new WorkflowInternalActionVerticle() { - @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 consumeAndSend(MosipEventBus eventbus, MessageBusAddress addressbus1, - MessageBusAddress addressbus2, long messageExpiryTimeLimit) { - } - - @Override - public Router postUrl(Vertx vertx, MessageBusAddress consumeAddress, MessageBusAddress sendAddress) { - return null; - - } - - @Override - public void createServer(Router router, int port) { - - } - - public void send(MosipEventBus mosipEventBus, MessageBusAddress toAddress, MessageDTO message) { - - }; - }; - - @Before - public void setUp() throws Exception { - ReflectionTestUtils.setField(workflowInternalActionVerticle, "anonymousProfileBusAddress", "anonymous-profile-bus-in"); - } - - @Test - public void testDeployVerticle() { - - ReflectionTestUtils.setField(workflowInternalActionVerticle, "workerPoolSize", 10); - ReflectionTestUtils.setField(workflowInternalActionVerticle, "clusterManagerUrl", "/dummyPath"); - ReflectionTestUtils.setField(workflowInternalActionVerticle, "defaultMaxAllowedIteration", 5); - workflowInternalActionVerticle.deployVerticle(); - } - - @Test - public void testStart() { - ReflectionTestUtils.setField(workflowInternalActionVerticle, "port", "2333"); - Mockito.doNothing().when(router).setRoute(any()); - workflowInternalActionVerticle.start(); - } - - @Test - public void testProcessSuccessForMarkAsPaused() { - WorkflowInternalActionDTO workflowInternalActionDTO = new WorkflowInternalActionDTO(); - workflowInternalActionDTO.setRid("10006100390000920200603070407"); - workflowInternalActionDTO.setActionCode(WorkflowInternalActionCode.MARK_AS_PAUSED.toString()); - workflowInternalActionDTO.setActionMessage("packet is paused"); - workflowInternalActionDTO.setResumeTimestamp("2021-03-02T08:24:29.526Z"); - workflowInternalActionDTO.setEventTimestamp("2021-03-02T08:24:29.526Z"); - workflowInternalActionDTO.setDefaultResumeAction("ResumeProcessing"); - List matchedRuleIds=new ArrayList(); - matchedRuleIds.add("NON_RESIDENT_CHILD_APPLICANT"); - workflowInternalActionDTO.setMatchedRuleIds(matchedRuleIds); - Mockito.doNothing().when(registrationStatusService).updateRegistrationStatusForWorkflowEngine(any(), any(), any()); - registrationStatusDto = new InternalRegistrationStatusDto(); - registrationStatusDto.setRegistrationId("10006100390000920200603070407"); - Mockito.when(auditLogRequestBuilder.createAuditRequestBuilder(any(), any(), any(), any(), any(), any(), any())) - .thenReturn(null); - Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); - workflowInternalActionVerticle.process(workflowInternalActionDTO); - ArgumentCaptor argument = ArgumentCaptor - .forClass(InternalRegistrationStatusDto.class); - - verify(registrationStatusService, atLeastOnce()).updateRegistrationStatusForWorkflowEngine(argument.capture(), Mockito.any(), - Mockito.any()); - assertEquals(RegistrationStatusCode.PAUSED.toString(), argument.getAllValues().get(0).getStatusCode()); - - } - - @Test - public void testTablenotAccessibleException() { - WorkflowInternalActionDTO workflowInternalActionDTO = new WorkflowInternalActionDTO(); - workflowInternalActionDTO.setRid("10006100390000920200603070407"); - workflowInternalActionDTO.setActionCode(WorkflowInternalActionCode.MARK_AS_PAUSED.toString()); - workflowInternalActionDTO.setActionMessage("packet is paused"); - workflowInternalActionDTO.setResumeTimestamp("2021-03-02T08:24:29.526Z"); - workflowInternalActionDTO.setEventTimestamp("2021-03-02T08:24:29.526Z"); - workflowInternalActionDTO.setDefaultResumeAction("ResumeProcessing"); - Mockito.doNothing().when(registrationStatusService).updateRegistrationStatusForWorkflowEngine(any(), any(), any()); - registrationStatusDto = new InternalRegistrationStatusDto(); - registrationStatusDto.setRegistrationId("10006100390000920200603070407"); - Mockito.when(auditLogRequestBuilder.createAuditRequestBuilder(any(), any(), any(), any(), any(), any(), any())) - .thenReturn(null); - Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())) - .thenThrow(TablenotAccessibleException.class); - - workflowInternalActionVerticle.process(workflowInternalActionDTO); - } - - @Test - public void testDateTimeParseException() { - WorkflowInternalActionDTO workflowInternalActionDTO = new WorkflowInternalActionDTO(); - workflowInternalActionDTO.setRid("10006100390000920200603070407"); - workflowInternalActionDTO.setActionCode(WorkflowInternalActionCode.MARK_AS_PAUSED.toString()); - workflowInternalActionDTO.setActionMessage("packet is paused"); - workflowInternalActionDTO.setResumeTimestamp("2021-03-02T08:24:29.5Z"); - workflowInternalActionDTO.setEventTimestamp("2021-03-02T08:24:29.526Z"); - workflowInternalActionDTO.setDefaultResumeAction("ResumeProcessing"); - Mockito.doNothing().when(registrationStatusService).updateRegistrationStatusForWorkflowEngine(any(), any(), any()); - registrationStatusDto = new InternalRegistrationStatusDto(); - registrationStatusDto.setRegistrationId("10006100390000920200603070407"); - Mockito.when(auditLogRequestBuilder.createAuditRequestBuilder(any(), any(), any(), any(), any(), any(), any())) - .thenReturn(null); - Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); - workflowInternalActionVerticle.process(workflowInternalActionDTO); - } - - @Test - public void testException() { - WorkflowInternalActionDTO workflowInternalActionDTO = new WorkflowInternalActionDTO(); - workflowInternalActionDTO.setRid("10006100390000920200603070407"); - workflowInternalActionDTO.setActionCode(WorkflowInternalActionCode.MARK_AS_PAUSED.toString()); - workflowInternalActionDTO.setActionMessage("packet is paused"); - workflowInternalActionDTO.setResumeTimestamp("2021-03-02T08:24:29.5Z"); - workflowInternalActionDTO.setEventTimestamp("2021-03-02T08:24:29.526Z"); - workflowInternalActionDTO.setDefaultResumeAction("ResumeProcessing"); - Mockito.doNothing().when(registrationStatusService).updateRegistrationStatusForWorkflowEngine(any(), any(), any()); - registrationStatusDto = new InternalRegistrationStatusDto(); - registrationStatusDto.setRegistrationId("10006100390000920200603070407"); - Mockito.when(auditLogRequestBuilder.createAuditRequestBuilder(any(), any(), any(), any(), any(), any(), any())) - .thenReturn(null); - Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(null); - workflowInternalActionVerticle.process(workflowInternalActionDTO); - } - - @Test - public void testProcessSuccessForCompleteAsProcessed() { - WorkflowInternalActionDTO workflowInternalActionDTO = new WorkflowInternalActionDTO(); - workflowInternalActionDTO.setRid("10006100390000920200603070407"); - workflowInternalActionDTO.setActionCode(WorkflowInternalActionCode.COMPLETE_AS_PROCESSED.toString()); - workflowInternalActionDTO.setActionMessage("packet is complete as processed"); - Mockito.doNothing().when(registrationStatusService).updateRegistrationStatusForWorkflowEngine(any(), any(), any()); - registrationStatusDto = new InternalRegistrationStatusDto(); - registrationStatusDto.setRegistrationId("10006100390000920200603070407"); - Mockito.when(auditLogRequestBuilder.createAuditRequestBuilder(any(), any(), any(), any(), any(), any(), any())) - .thenReturn(null); - Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); - workflowInternalActionVerticle.process(workflowInternalActionDTO); - ArgumentCaptor argument = ArgumentCaptor - .forClass(InternalRegistrationStatusDto.class); - - verify(registrationStatusService, atLeastOnce()).updateRegistrationStatusForWorkflowEngine(argument.capture(), Mockito.any(), - Mockito.any()); - assertEquals(RegistrationStatusCode.PROCESSED.toString(), argument.getAllValues().get(0).getStatusCode()); - ArgumentCaptor argument1 = ArgumentCaptor.forClass(WorkflowCompletedEventDTO.class); - - verify(webSubUtil, atLeastOnce()).publishEvent(argument1.capture()); - assertEquals(RegistrationStatusCode.PROCESSED.toString(), argument1.getAllValues().get(0).getResultCode()); - - } - - @Test - public void testProcessSuccessForCompleteAsRejected() { - WorkflowInternalActionDTO workflowInternalActionDTO = new WorkflowInternalActionDTO(); - workflowInternalActionDTO.setRid("10006100390000920200603070407"); - workflowInternalActionDTO.setActionCode(WorkflowInternalActionCode.COMPLETE_AS_REJECTED.toString()); - workflowInternalActionDTO.setActionMessage("packet is complete as rejected"); - Mockito.doNothing().when(registrationStatusService).updateRegistrationStatusForWorkflowEngine(any(), any(), any()); - registrationStatusDto = new InternalRegistrationStatusDto(); - registrationStatusDto.setRegistrationId("10006100390000920200603070407"); - Mockito.when(auditLogRequestBuilder.createAuditRequestBuilder(any(), any(), any(), any(), any(), any(), any())) - .thenReturn(null); - Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); - workflowInternalActionVerticle.process(workflowInternalActionDTO); - ArgumentCaptor argument = ArgumentCaptor - .forClass(InternalRegistrationStatusDto.class); - - verify(registrationStatusService, atLeastOnce()).updateRegistrationStatusForWorkflowEngine(argument.capture(), Mockito.any(), - Mockito.any()); - assertEquals(RegistrationStatusCode.REJECTED.toString(), argument.getAllValues().get(0).getStatusCode()); - ArgumentCaptor argument1 = ArgumentCaptor.forClass(WorkflowCompletedEventDTO.class); - verify(webSubUtil, atLeastOnce()).publishEvent(argument1.capture()); - assertEquals(RegistrationStatusCode.REJECTED.toString(), argument1.getAllValues().get(0).getResultCode()); - - } - - @Test - public void testProcessSuccessForCompleteAsFailed() { - WorkflowInternalActionDTO workflowInternalActionDTO = new WorkflowInternalActionDTO(); - workflowInternalActionDTO.setRid("10006100390000920200603070407"); - workflowInternalActionDTO.setActionCode(WorkflowInternalActionCode.COMPLETE_AS_FAILED.toString()); - workflowInternalActionDTO.setActionMessage("packet is complete as failed"); - Mockito.doNothing().when(registrationStatusService).updateRegistrationStatusForWorkflowEngine(any(), any(), any()); - registrationStatusDto = new InternalRegistrationStatusDto(); - registrationStatusDto.setRegistrationId("10006100390000920200603070407"); - Mockito.when(auditLogRequestBuilder.createAuditRequestBuilder(any(), any(), any(), any(), any(), any(), any())) - .thenReturn(null); - Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); - workflowInternalActionVerticle.process(workflowInternalActionDTO); - ArgumentCaptor argument = ArgumentCaptor - .forClass(InternalRegistrationStatusDto.class); - - verify(registrationStatusService, atLeastOnce()).updateRegistrationStatusForWorkflowEngine(argument.capture(), Mockito.any(), - Mockito.any()); - assertEquals(RegistrationStatusCode.FAILED.toString(), argument.getAllValues().get(0).getStatusCode()); - ArgumentCaptor argument1 = ArgumentCaptor.forClass(WorkflowCompletedEventDTO.class); - verify(webSubUtil, atLeastOnce()).publishEvent(argument1.capture()); - assertEquals(RegistrationStatusCode.FAILED.toString(), argument1.getAllValues().get(0).getResultCode()); - } - - @Test - public void testProcessSuccessForMarkAsReprocess() - { - WorkflowInternalActionDTO workflowInternalActionDTO = new WorkflowInternalActionDTO(); - workflowInternalActionDTO.setRid("10006100390000920200603070407"); - workflowInternalActionDTO.setActionCode(WorkflowInternalActionCode.MARK_AS_REPROCESS.toString()); - workflowInternalActionDTO.setActionMessage("packet is marked as reprocess"); - Mockito.doNothing().when(registrationStatusService).updateRegistrationStatusForWorkflowEngine(any(), any(), any()); - registrationStatusDto = new InternalRegistrationStatusDto(); - registrationStatusDto.setRegistrationId("10006100390000920200603070407"); - Mockito.when(auditLogRequestBuilder.createAuditRequestBuilder(any(), any(), any(), any(), any(), any(), any())) - .thenReturn(null); - Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); - workflowInternalActionVerticle.process(workflowInternalActionDTO); - ArgumentCaptor argument = ArgumentCaptor - .forClass(InternalRegistrationStatusDto.class); - - verify(registrationStatusService, atLeastOnce()).updateRegistrationStatusForWorkflowEngine(argument.capture(), Mockito.any(), - Mockito.any()); - assertEquals(RegistrationStatusCode.REPROCESS.toString(), argument.getAllValues().get(0).getStatusCode()); - } - - @Test - public void testProcessSuccessForPauseAndRequestAdditionalInfo() { - WorkflowInternalActionDTO workflowInternalActionDTO = new WorkflowInternalActionDTO(); - workflowInternalActionDTO.setRid("10006100390000920200603070407"); - workflowInternalActionDTO.setActionCode(WorkflowInternalActionCode.PAUSE_AND_REQUEST_ADDITIONAL_INFO.toString()); - workflowInternalActionDTO.setActionMessage("packet is paused for Additional Info"); - workflowInternalActionDTO.setResumeTimestamp("2021-03-02T08:24:29.526Z"); - workflowInternalActionDTO.setDefaultResumeAction(WorkflowActionCode.STOP_PROCESSING.toString()); - workflowInternalActionDTO.setIteration(1); - workflowInternalActionDTO.setReg_type("NEW"); - workflowInternalActionDTO.setAdditionalInfoProcess("CORRECTION"); - Mockito.doNothing().when(registrationStatusService).updateRegistrationStatusForWorkflowEngine(any(), any(), any()); - registrationStatusDto = new InternalRegistrationStatusDto(); - registrationStatusDto.setRegistrationId("10006100390000920200603070407"); - Mockito.when(auditLogRequestBuilder.createAuditRequestBuilder(any(), any(), any(), any(), any(), any(), any())) - .thenReturn(null); - Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())) - .thenReturn(registrationStatusDto); - Mockito.when( - additionalInfoRequestService.getAdditionalInfoRequestByRegIdAndProcess(anyString(), anyString())) - .thenReturn(null); - workflowInternalActionVerticle.process(workflowInternalActionDTO); - ArgumentCaptor argument = ArgumentCaptor - .forClass(InternalRegistrationStatusDto.class); - - verify(registrationStatusService, atLeastOnce()).updateRegistrationStatusForWorkflowEngine(argument.capture(), Mockito.any(), - Mockito.any()); - assertEquals(RegistrationStatusCode.PAUSED_FOR_ADDITIONAL_INFO.toString(), - argument.getAllValues().get(0).getStatusCode()); - ArgumentCaptor argument1 = ArgumentCaptor.forClass(AdditionalInfoRequestDto.class); - - verify(additionalInfoRequestService, atLeastOnce()).addAdditionalInfoRequest(argument1.capture()); - assertEquals(workflowInternalActionDTO.getAdditionalInfoProcess(), - argument1.getAllValues().get(0).getAdditionalInfoProcess()); - ArgumentCaptor argument2 = ArgumentCaptor - .forClass(WorkflowPausedForAdditionalInfoEventDTO.class); - - verify(webSubUtil, atLeastOnce()).publishEvent(argument2.capture()); - assertEquals(workflowInternalActionDTO.getAdditionalInfoProcess(), - argument2.getAllValues().get(0).getAdditionalInfoProcess()); - - } - @Test - public void testProcessSuccessForRestartParentFlow() throws WorkflowActionException, ApisResourceAccessException, - PacketManagerException, JsonProcessingException, IOException { - WorkflowInternalActionDTO workflowInternalActionDTO = new WorkflowInternalActionDTO(); - workflowInternalActionDTO.setRid("10006100390000920200603070407"); - workflowInternalActionDTO.setActionCode(WorkflowInternalActionCode.RESTART_PARENT_FLOW.toString()); - workflowInternalActionDTO.setActionMessage(PlatformSuccessMessages.PACKET_RESTART_PARENT_FLOW.getMessage()); - workflowInternalActionDTO.setReg_type("CORRECTION"); - workflowInternalActionDTO.setIteration(1); - AdditionalInfoRequestDto additionalInfoRequestDto = new AdditionalInfoRequestDto(); - additionalInfoRequestDto.setRegId("10006100390000920200603070407"); - additionalInfoRequestDto.setAdditionalInfoIteration(1); - additionalInfoRequestDto.setWorkflowInstanceId("Workflow123"); - additionalInfoRequestDto.setAdditionalInfoReqId("additionalRequestId"); - Mockito.when(additionalInfoRequestService.getAdditionalInfoRequestByRegIdAndProcessAndIteration(Mockito.anyString(), - Mockito.anyString(), Mockito.anyInt())).thenReturn(additionalInfoRequestDto); - registrationStatusDto = new InternalRegistrationStatusDto(); - registrationStatusDto.setRegistrationId("10006100390000920200603070407"); - Mockito.when(auditLogRequestBuilder.createAuditRequestBuilder(any(), any(), any(), any(), any(), any(), any())) - .thenReturn(null); - Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())) - .thenReturn(registrationStatusDto); - workflowInternalActionVerticle.process(workflowInternalActionDTO); - verify(workflowActionService, times(1)).processWorkflowAction(Mockito.any(), Mockito.anyString()); - verify(packetManagerService, times(1)).addOrUpdateTags(Mockito.anyString(), Mockito.any()); - } - - @Test - public void testProcessSuccessForCompleteAsProcessedForAdditionalInfoWorkflow() - throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException, - WorkflowActionException { - WorkflowInternalActionDTO workflowInternalActionDTO = new WorkflowInternalActionDTO(); - workflowInternalActionDTO.setRid("10006100390000920200603070407"); - workflowInternalActionDTO.setActionCode(WorkflowInternalActionCode.COMPLETE_AS_PROCESSED.toString()); - workflowInternalActionDTO.setActionMessage("packet is complete as processed"); - workflowInternalActionDTO.setReg_type("CORRECTION"); - Mockito.doNothing().when(registrationStatusService).updateRegistrationStatusForWorkflowEngine(any(), any(), any()); - registrationStatusDto = new InternalRegistrationStatusDto(); - registrationStatusDto.setRegistrationId("10006100390000920200603070407"); - Mockito.when(auditLogRequestBuilder.createAuditRequestBuilder(any(), any(), any(), any(), any(), any(), any())) - .thenReturn(null); - Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())) - .thenReturn(registrationStatusDto); - AdditionalInfoRequestDto additionalInfoRequestDto = new AdditionalInfoRequestDto(); - additionalInfoRequestDto.setRegId("10006100390000920200603070407"); - additionalInfoRequestDto.setAdditionalInfoIteration(1); - additionalInfoRequestDto.setWorkflowInstanceId("Workflow123"); - additionalInfoRequestDto.setAdditionalInfoReqId("additionalRequestId"); - Mockito.when(additionalInfoRequestService.getAdditionalInfoRequestByRegIdAndProcessAndIteration(Mockito.anyString(), - Mockito.anyString(), Mockito.anyInt())).thenReturn(additionalInfoRequestDto); - workflowInternalActionVerticle.process(workflowInternalActionDTO); - ArgumentCaptor argument = ArgumentCaptor - .forClass(InternalRegistrationStatusDto.class); - - verify(registrationStatusService, atLeastOnce()).updateRegistrationStatusForWorkflowEngine(argument.capture(), Mockito.any(), - Mockito.any()); - assertEquals(RegistrationStatusCode.PROCESSED.toString(), argument.getAllValues().get(0).getStatusCode()); - verify(workflowActionService, times(1)).processWorkflowAction(Mockito.any(), Mockito.anyString()); - verify(packetManagerService, times(1)).addOrUpdateTags(Mockito.anyString(), Mockito.any()); - } - - @Test - public void testProcessSuccessForCompleteAsRejectedForAdditionalInfoWorkflow() - throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException, - WorkflowActionException { - WorkflowInternalActionDTO workflowInternalActionDTO = new WorkflowInternalActionDTO(); - workflowInternalActionDTO.setRid("10006100390000920200603070407"); - workflowInternalActionDTO.setActionCode(WorkflowInternalActionCode.COMPLETE_AS_REJECTED.toString()); - workflowInternalActionDTO.setActionMessage("packet is complete as rejected"); - workflowInternalActionDTO.setReg_type("CORRECTION"); - Mockito.doNothing().when(registrationStatusService).updateRegistrationStatusForWorkflowEngine(any(), any(), any()); - registrationStatusDto = new InternalRegistrationStatusDto(); - registrationStatusDto.setRegistrationId("10006100390000920200603070407"); - Mockito.when(auditLogRequestBuilder.createAuditRequestBuilder(any(), any(), any(), any(), any(), any(), any())) - .thenReturn(null); - Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())) - .thenReturn(registrationStatusDto); - AdditionalInfoRequestDto additionalInfoRequestDto = new AdditionalInfoRequestDto(); - additionalInfoRequestDto.setRegId("10006100390000920200603070407"); - additionalInfoRequestDto.setAdditionalInfoIteration(1); - additionalInfoRequestDto.setWorkflowInstanceId("Workflow123"); - additionalInfoRequestDto.setAdditionalInfoReqId("additionalRequestId"); - Mockito.when(additionalInfoRequestService.getAdditionalInfoRequestByRegIdAndProcessAndIteration(Mockito.anyString(), - Mockito.anyString(), Mockito.anyInt())).thenReturn(additionalInfoRequestDto); - workflowInternalActionVerticle.process(workflowInternalActionDTO); - ArgumentCaptor argument = ArgumentCaptor - .forClass(InternalRegistrationStatusDto.class); - - verify(registrationStatusService, atLeastOnce()).updateRegistrationStatusForWorkflowEngine(argument.capture(), Mockito.any(), - Mockito.any()); - assertEquals(RegistrationStatusCode.REJECTED.toString(), argument.getAllValues().get(0).getStatusCode()); - verify(workflowActionService, times(1)).processWorkflowAction(Mockito.any(), Mockito.anyString()); - verify(packetManagerService, times(1)).addOrUpdateTags(Mockito.anyString(), Mockito.any()); - } - - @Test - public void testProcessSuccessForCompleteAsFailedForAdditionalInfoWorkflow() - throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException, - WorkflowActionException { - WorkflowInternalActionDTO workflowInternalActionDTO = new WorkflowInternalActionDTO(); - workflowInternalActionDTO.setRid("10006100390000920200603070407"); - workflowInternalActionDTO.setActionCode(WorkflowInternalActionCode.COMPLETE_AS_FAILED.toString()); - workflowInternalActionDTO.setActionMessage("packet is complete as failed"); - workflowInternalActionDTO.setReg_type("CORRECTION"); - Mockito.doNothing().when(registrationStatusService).updateRegistrationStatusForWorkflowEngine(any(), any(), any()); - registrationStatusDto = new InternalRegistrationStatusDto(); - registrationStatusDto.setRegistrationId("10006100390000920200603070407"); - Mockito.when(auditLogRequestBuilder.createAuditRequestBuilder(any(), any(), any(), any(), any(), any(), any())) - .thenReturn(null); - Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())) - .thenReturn(registrationStatusDto); - AdditionalInfoRequestDto additionalInfoRequestDto = new AdditionalInfoRequestDto(); - additionalInfoRequestDto.setRegId("10006100390000920200603070407"); - additionalInfoRequestDto.setAdditionalInfoIteration(1); - additionalInfoRequestDto.setAdditionalInfoProcess("CORRECTION"); - additionalInfoRequestDto.setWorkflowInstanceId("Workflow123"); - additionalInfoRequestDto.setAdditionalInfoReqId("additionalRequestId"); - Mockito.when(additionalInfoRequestService.getAdditionalInfoRequestByRegIdAndProcessAndIteration(Mockito.anyString(), - Mockito.anyString(), Mockito.anyInt())).thenReturn(additionalInfoRequestDto); - workflowInternalActionVerticle.process(workflowInternalActionDTO); - ArgumentCaptor argument = ArgumentCaptor - .forClass(InternalRegistrationStatusDto.class); - - verify(registrationStatusService, atLeastOnce()).updateRegistrationStatusForWorkflowEngine(argument.capture(), Mockito.any(), - Mockito.any()); - assertEquals(RegistrationStatusCode.FAILED.toString(), argument.getAllValues().get(0).getStatusCode()); - verify(workflowActionService, times(1)).processWorkflowAction(Mockito.any(), Mockito.anyString()); - verify(packetManagerService, times(1)).addOrUpdateTags(Mockito.anyString(), Mockito.any()); - } - - @Test - public void testProcessSuccessForPauseAndRequestAdditionalInfoForAdditionalInfoWorkflow() throws WorkflowActionException, - ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { - WorkflowInternalActionDTO workflowInternalActionDTO = new WorkflowInternalActionDTO(); - workflowInternalActionDTO.setRid("10006100390000920200603070407"); - workflowInternalActionDTO - .setActionCode(WorkflowInternalActionCode.PAUSE_AND_REQUEST_ADDITIONAL_INFO.toString()); - workflowInternalActionDTO.setActionMessage("packet is paused for Additional Info"); - workflowInternalActionDTO.setResumeTimestamp("2021-03-02T08:24:29.526Z"); - workflowInternalActionDTO.setDefaultResumeAction(WorkflowActionCode.STOP_PROCESSING.toString()); - workflowInternalActionDTO.setIteration(1); - workflowInternalActionDTO.setReg_type("CORRECTION"); - Mockito.doNothing().when(registrationStatusService).updateRegistrationStatusForWorkflowEngine(any(), any(), any()); - registrationStatusDto = new InternalRegistrationStatusDto(); - registrationStatusDto.setRegistrationId("10006100390000920200603070407"); - Mockito.when(auditLogRequestBuilder.createAuditRequestBuilder(any(), any(), any(), any(), any(), any(), any())) - .thenReturn(null); - Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())) - .thenReturn(registrationStatusDto); - AdditionalInfoRequestDto additionalInfoRequestDto = new AdditionalInfoRequestDto(); - additionalInfoRequestDto.setRegId("10006100390000920200603070407"); - additionalInfoRequestDto.setAdditionalInfoIteration(1); - additionalInfoRequestDto.setWorkflowInstanceId("Workflow123"); - additionalInfoRequestDto.setAdditionalInfoReqId("additionalRequestId"); - Mockito.when(additionalInfoRequestService.getAdditionalInfoRequestByRegIdAndProcessAndIteration(Mockito.anyString(), - Mockito.anyString(), Mockito.anyInt())).thenReturn(additionalInfoRequestDto); - workflowInternalActionVerticle.process(workflowInternalActionDTO); - ArgumentCaptor argument = ArgumentCaptor - .forClass(InternalRegistrationStatusDto.class); - - verify(registrationStatusService, atLeastOnce()).updateRegistrationStatusForWorkflowEngine(argument.capture(), Mockito.any(), - Mockito.any()); - assertEquals(RegistrationStatusCode.FAILED.toString(), - argument.getAllValues().get(0).getStatusCode()); - verify(workflowActionService, times(1)).processWorkflowAction(Mockito.any(), Mockito.anyString()); - verify(packetManagerService, times(1)).addOrUpdateTags(Mockito.anyString(), Mockito.any()); - } - - @Test - public void testProcessSuccessForCompleteAsRejectedWithoutParentFlow() { - WorkflowInternalActionDTO workflowInternalActionDTO = new WorkflowInternalActionDTO(); - workflowInternalActionDTO.setRid("10006100390000920200603070407"); - workflowInternalActionDTO - .setActionCode(WorkflowInternalActionCode.COMPLETE_AS_REJECTED_WITHOUT_PARENT_FLOW.toString()); - workflowInternalActionDTO - .setActionMessage("Packet processing completed with reject status without Parent flow"); - workflowInternalActionDTO.setReg_type("CORRECTION"); - Mockito.doNothing().when(registrationStatusService).updateRegistrationStatusForWorkflowEngine(any(), any(), any()); - registrationStatusDto = new InternalRegistrationStatusDto(); - registrationStatusDto.setRegistrationId("10006100390000920200603070407"); - Mockito.when(auditLogRequestBuilder.createAuditRequestBuilder(any(), any(), any(), any(), any(), any(), any())) - .thenReturn(null); - Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())) - .thenReturn(registrationStatusDto); - workflowInternalActionVerticle.process(workflowInternalActionDTO); - ArgumentCaptor argument = ArgumentCaptor - .forClass(InternalRegistrationStatusDto.class); - - verify(registrationStatusService, atLeastOnce()).updateRegistrationStatusForWorkflowEngine(argument.capture(), Mockito.any(), - Mockito.any()); - assertEquals(RegistrationStatusCode.REJECTED.toString(), argument.getAllValues().get(0).getStatusCode()); - } - @Test - public void testProcessSuccessForPauseAndRequestAdditionalInfoWithMaxAllowedIterationExceed() { - WorkflowInternalActionDTO workflowInternalActionDTO = new WorkflowInternalActionDTO(); - workflowInternalActionDTO.setRid("10006100390000920200603070407"); - workflowInternalActionDTO.setActionCode(WorkflowInternalActionCode.PAUSE_AND_REQUEST_ADDITIONAL_INFO.toString()); - workflowInternalActionDTO.setActionMessage("packet is paused for Additional Info"); - workflowInternalActionDTO.setResumeTimestamp("2021-03-02T08:24:29.526Z"); - workflowInternalActionDTO.setDefaultResumeAction(WorkflowActionCode.STOP_PROCESSING.toString()); - workflowInternalActionDTO.setIteration(6); - workflowInternalActionDTO.setReg_type("NEW"); - workflowInternalActionDTO.setAdditionalInfoProcess("CORRECTION"); - Mockito.doNothing().when(registrationStatusService).updateRegistrationStatusForWorkflowEngine(any(), any(), any()); - registrationStatusDto = new InternalRegistrationStatusDto(); - registrationStatusDto.setRegistrationId("10006100390000920200603070407"); - Mockito.when(auditLogRequestBuilder.createAuditRequestBuilder(any(), any(), any(), any(), any(), any(), any())) - .thenReturn(null); - Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())) - .thenReturn(registrationStatusDto); - AdditionalInfoRequestDto additionalInfoRequestDto = new AdditionalInfoRequestDto(); - additionalInfoRequestDto.setRegId("10006100390000920200603070407"); - additionalInfoRequestDto.setAdditionalInfoIteration(5); - additionalInfoRequestDto.setWorkflowInstanceId("Workflow123"); - additionalInfoRequestDto.setAdditionalInfoReqId("additionalRequestId"); - List additionalInfoRequestDtoList=new ArrayList(); - additionalInfoRequestDtoList.add(additionalInfoRequestDto); - Mockito.when( - additionalInfoRequestService.getAdditionalInfoRequestByRegIdAndProcess(anyString(), anyString())) - .thenReturn(additionalInfoRequestDtoList); - workflowInternalActionVerticle.process(workflowInternalActionDTO); - ArgumentCaptor argument = ArgumentCaptor - .forClass(InternalRegistrationStatusDto.class); - - verify(registrationStatusService, atLeastOnce()).updateRegistrationStatusForWorkflowEngine(argument.capture(), Mockito.any(), - Mockito.any()); - assertEquals(RegistrationStatusCode.REJECTED.toString(), argument.getAllValues().get(0).getStatusCode()); - ArgumentCaptor argument1 = ArgumentCaptor.forClass(WorkflowCompletedEventDTO.class); - verify(webSubUtil, atLeastOnce()).publishEvent(argument1.capture()); - assertEquals(RegistrationStatusCode.REJECTED.toString(), argument1.getAllValues().get(0).getResultCode()); - } - - @SuppressWarnings("unchecked") - @Test - public void testProcessSuccessForAnonymousProfile() throws IOException, JSONException, BaseCheckedException { - WorkflowInternalActionDTO workflowInternalActionDTO = new WorkflowInternalActionDTO(); - workflowInternalActionDTO.setRid("10006100390000920200603070407"); - workflowInternalActionDTO.setReg_type("NEW"); - workflowInternalActionDTO.setIsValid(true); - workflowInternalActionDTO.setActionCode(WorkflowInternalActionCode.ANONYMOUS_PROFILE.toString()); - workflowInternalActionDTO.setActionMessage("anonymous profile event"); - - Mockito.when(packetManagerService.getFieldByMappingJsonKey(anyString(), anyString(), anyString(), any())) - .thenReturn("1.0"); - Mockito.when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(Arrays.asList("")); - - Map fieldTypeMap = new HashedMap(); - fieldTypeMap.put("postalCode", "string"); - fieldTypeMap.put("zone", "simpleType"); - Mockito.when(idSchemaUtil.getIdSchemaFieldTypes(anyDouble())).thenReturn(fieldTypeMap); - - Map fieldMap = new HashedMap(); - fieldMap.put("postalCode", "14022"); - fieldMap.put("dateOfBirth", "1998/01/01"); - fieldMap.put("phone", "6666666666"); - Mockito.when(packetManagerService.getFields(anyString(), any(), anyString(), any())).thenReturn(fieldMap); - - Map metaInfoMap = new HashedMap(); - metaInfoMap.put("documents", "[{\"documentType\" : \"CIN\"},{\"documentType\" : \"RNC\"})]"); - metaInfoMap.put("operationsData", - "[{\"label\" : \"officerId\",\"value\" : \"110024\"},{\"label\" : \"officerBiometricFileName\",\"value\" : \"null\"})]"); - metaInfoMap.put("creationDate", "2021-09-01T03:48:49.193Z"); - Mockito.when(packetManagerService.getMetaInfo(anyString(), anyString(), any())).thenReturn(metaInfoMap); - - BiometricRecord biometricRecord = new BiometricRecord(); - BIR bir = new BIR(); - HashMap entry = new HashMap<>(); - bir.setSb("eyJ4NWMiOlsiTUlJRGtEQ0NBbmlnQXdJQkFnSUVwNzo".getBytes()); - bir.setBdb("SUlSADAyMAAAACc6AAEAAQAAJyoH5AoJECYh//8Bc18wBgAAAQIDCgABlwExCA".getBytes()); - entry.put("PAYLOAD", "{\"deviceServiceVersion\":\"0.9.5\",\"bioValue\":\"\",\"qualityScore\":\"80\",\"bioType\":\"Iris\"}"); - bir.setOthers(entry); - biometricRecord.setSegments(Arrays.asList(bir)); - Mockito.when(packetManagerService.getBiometrics(anyString(), anyString(), anyString(), any())) - .thenReturn(biometricRecord); - - org.json.simple.JSONObject identity = new org.json.simple.JSONObject(); - LinkedHashMap IDSchemaVersion = new LinkedHashMap(); - IDSchemaVersion.put("value", "1.0"); - identity.put("IDSchemaVersion", IDSchemaVersion); - - registrationStatusDto = new InternalRegistrationStatusDto(); - registrationStatusDto.setRegistrationId("10006100390000920200603070407"); - Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())) - .thenReturn(registrationStatusDto); - Mockito.when(utility.getRegistrationProcessorMappingJson(any())) - .thenReturn(identity); - Mockito.when(auditLogRequestBuilder.createAuditRequestBuilder(any(), any(), any(), any(), any(), any(), any())) - .thenReturn(null); - Mockito.when(anonymousProfileService.buildJsonStringFromPacketInfo(any(), any(), any(), any(), anyString(), - anyString())).thenReturn("jsonProfile"); - Mockito.doNothing().when(anonymousProfileService).saveAnonymousProfile(anyString(), anyString(), anyString()); - MessageDTO object = workflowInternalActionVerticle.process(workflowInternalActionDTO); - assertEquals(true, object.getIsValid()); - } -} +package io.mosip.registration.processor.workflowmanager.verticle; + +import static org.junit.Assert.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyDouble; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.atLeastOnce; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +import java.io.IOException; +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 org.apache.commons.collections.map.HashedMap; +import org.json.JSONException; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.springframework.core.env.Environment; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.util.ReflectionTestUtils; + +import io.mosip.kernel.biometrics.entities.BIR; +import io.mosip.kernel.biometrics.entities.BiometricRecord; +import io.mosip.kernel.core.exception.BaseCheckedException; +import io.mosip.kernel.core.util.exception.JsonProcessingException; +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.abstractverticle.WorkflowInternalActionDTO; +import io.mosip.registration.processor.core.code.WorkflowActionCode; +import io.mosip.registration.processor.core.code.WorkflowInternalActionCode; +import io.mosip.registration.processor.core.exception.ApisResourceAccessException; +import io.mosip.registration.processor.core.exception.PacketManagerException; +import io.mosip.registration.processor.core.exception.WorkflowActionException; +import io.mosip.registration.processor.core.exception.util.PlatformSuccessMessages; +import io.mosip.registration.processor.core.packet.dto.AdditionalInfoRequestDto; +import io.mosip.registration.processor.core.spi.eventbus.EventHandler; +import io.mosip.registration.processor.core.workflow.dto.WorkflowCompletedEventDTO; +import io.mosip.registration.processor.core.workflow.dto.WorkflowPausedForAdditionalInfoEventDTO; +import io.mosip.registration.processor.packet.storage.utils.IdSchemaUtil; +import io.mosip.registration.processor.packet.storage.utils.PacketManagerService; +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.AdditionalInfoRequestService; +import io.mosip.registration.processor.status.service.AnonymousProfileService; +import io.mosip.registration.processor.status.service.RegistrationStatusService; +import io.mosip.registration.processor.workflowmanager.service.WorkflowActionService; +import io.mosip.registration.processor.workflowmanager.util.WebSubUtil; +import io.vertx.core.AsyncResult; +import io.vertx.core.Handler; +import io.vertx.core.Vertx; +import io.vertx.ext.web.Router; + +@RunWith(SpringRunner.class) +public class WorkflowInternalActionVerticleTest { + @Mock + private MosipRouter router; + @Mock + MosipEventBus mosipEventBus; + + @Mock + RegistrationStatusService registrationStatusService; + + private InternalRegistrationStatusDto registrationStatusDto; + + @Mock + private AuditLogRequestBuilder auditLogRequestBuilder; + + @Mock + WebSubUtil webSubUtil; + + @Mock + private AdditionalInfoRequestService additionalInfoRequestService; + + @Mock + WorkflowActionService workflowActionService; + + @Mock + private PacketManagerService packetManagerService; + + @Mock + private AnonymousProfileService anonymousProfileService; + + @Mock + private IdSchemaUtil idSchemaUtil; + + @Mock + private Utilities utility; + + @Mock + private Environment env; + + + @InjectMocks + private WorkflowInternalActionVerticle workflowInternalActionVerticle = new WorkflowInternalActionVerticle() { + @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 consumeAndSend(MosipEventBus eventbus, MessageBusAddress addressbus1, + MessageBusAddress addressbus2, long messageExpiryTimeLimit) { + } + + @Override + public Router postUrl(Vertx vertx, MessageBusAddress consumeAddress, MessageBusAddress sendAddress) { + return null; + + } + + @Override + public void createServer(Router router, int port) { + + } + + public void send(MosipEventBus mosipEventBus, MessageBusAddress toAddress, MessageDTO message) { + + }; + }; + + @Before + public void setUp() throws Exception { + ReflectionTestUtils.setField(workflowInternalActionVerticle, "anonymousProfileBusAddress", "anonymous-profile-bus-in"); + } + + @Test + public void testDeployVerticle() { + + ReflectionTestUtils.setField(workflowInternalActionVerticle, "workerPoolSize", 10); + ReflectionTestUtils.setField(workflowInternalActionVerticle, "clusterManagerUrl", "/dummyPath"); + ReflectionTestUtils.setField(workflowInternalActionVerticle, "defaultMaxAllowedIteration", 5); + workflowInternalActionVerticle.deployVerticle(); + } + + @Test + public void testStart() { + ReflectionTestUtils.setField(workflowInternalActionVerticle, "port", "2333"); + Mockito.doNothing().when(router).setRoute(any()); + workflowInternalActionVerticle.start(); + } + + @Test + public void testProcessSuccessForMarkAsPaused() { + WorkflowInternalActionDTO workflowInternalActionDTO = new WorkflowInternalActionDTO(); + workflowInternalActionDTO.setRid("10006100390000920200603070407"); + workflowInternalActionDTO.setActionCode(WorkflowInternalActionCode.MARK_AS_PAUSED.toString()); + workflowInternalActionDTO.setActionMessage("packet is paused"); + workflowInternalActionDTO.setResumeTimestamp("2021-03-02T08:24:29.526Z"); + workflowInternalActionDTO.setEventTimestamp("2021-03-02T08:24:29.526Z"); + workflowInternalActionDTO.setDefaultResumeAction("ResumeProcessing"); + List matchedRuleIds=new ArrayList(); + matchedRuleIds.add("NON_RESIDENT_CHILD_APPLICANT"); + workflowInternalActionDTO.setMatchedRuleIds(matchedRuleIds); + Mockito.doNothing().when(registrationStatusService).updateRegistrationStatusForWorkflowEngine(any(), any(), any()); + registrationStatusDto = new InternalRegistrationStatusDto(); + registrationStatusDto.setRegistrationId("10006100390000920200603070407"); + Mockito.when(auditLogRequestBuilder.createAuditRequestBuilder(any(), any(), any(), any(), any(), any(), any())) + .thenReturn(null); + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); + workflowInternalActionVerticle.process(workflowInternalActionDTO); + ArgumentCaptor argument = ArgumentCaptor + .forClass(InternalRegistrationStatusDto.class); + + verify(registrationStatusService, atLeastOnce()).updateRegistrationStatusForWorkflowEngine(argument.capture(), Mockito.any(), + Mockito.any()); + assertEquals(RegistrationStatusCode.PAUSED.toString(), argument.getAllValues().get(0).getStatusCode()); + + } + + @Test + public void testTablenotAccessibleException() { + WorkflowInternalActionDTO workflowInternalActionDTO = new WorkflowInternalActionDTO(); + workflowInternalActionDTO.setRid("10006100390000920200603070407"); + workflowInternalActionDTO.setActionCode(WorkflowInternalActionCode.MARK_AS_PAUSED.toString()); + workflowInternalActionDTO.setActionMessage("packet is paused"); + workflowInternalActionDTO.setResumeTimestamp("2021-03-02T08:24:29.526Z"); + workflowInternalActionDTO.setEventTimestamp("2021-03-02T08:24:29.526Z"); + workflowInternalActionDTO.setDefaultResumeAction("ResumeProcessing"); + Mockito.doNothing().when(registrationStatusService).updateRegistrationStatusForWorkflowEngine(any(), any(), any()); + registrationStatusDto = new InternalRegistrationStatusDto(); + registrationStatusDto.setRegistrationId("10006100390000920200603070407"); + Mockito.when(auditLogRequestBuilder.createAuditRequestBuilder(any(), any(), any(), any(), any(), any(), any())) + .thenReturn(null); + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())) + .thenThrow(TablenotAccessibleException.class); + + workflowInternalActionVerticle.process(workflowInternalActionDTO); + } + + @Test + public void testDateTimeParseException() { + WorkflowInternalActionDTO workflowInternalActionDTO = new WorkflowInternalActionDTO(); + workflowInternalActionDTO.setRid("10006100390000920200603070407"); + workflowInternalActionDTO.setActionCode(WorkflowInternalActionCode.MARK_AS_PAUSED.toString()); + workflowInternalActionDTO.setActionMessage("packet is paused"); + workflowInternalActionDTO.setResumeTimestamp("2021-03-02T08:24:29.5Z"); + workflowInternalActionDTO.setEventTimestamp("2021-03-02T08:24:29.526Z"); + workflowInternalActionDTO.setDefaultResumeAction("ResumeProcessing"); + Mockito.doNothing().when(registrationStatusService).updateRegistrationStatusForWorkflowEngine(any(), any(), any()); + registrationStatusDto = new InternalRegistrationStatusDto(); + registrationStatusDto.setRegistrationId("10006100390000920200603070407"); + Mockito.when(auditLogRequestBuilder.createAuditRequestBuilder(any(), any(), any(), any(), any(), any(), any())) + .thenReturn(null); + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); + workflowInternalActionVerticle.process(workflowInternalActionDTO); + } + + @Test + public void testException() { + WorkflowInternalActionDTO workflowInternalActionDTO = new WorkflowInternalActionDTO(); + workflowInternalActionDTO.setRid("10006100390000920200603070407"); + workflowInternalActionDTO.setActionCode(WorkflowInternalActionCode.MARK_AS_PAUSED.toString()); + workflowInternalActionDTO.setActionMessage("packet is paused"); + workflowInternalActionDTO.setResumeTimestamp("2021-03-02T08:24:29.5Z"); + workflowInternalActionDTO.setEventTimestamp("2021-03-02T08:24:29.526Z"); + workflowInternalActionDTO.setDefaultResumeAction("ResumeProcessing"); + Mockito.doNothing().when(registrationStatusService).updateRegistrationStatusForWorkflowEngine(any(), any(), any()); + registrationStatusDto = new InternalRegistrationStatusDto(); + registrationStatusDto.setRegistrationId("10006100390000920200603070407"); + Mockito.when(auditLogRequestBuilder.createAuditRequestBuilder(any(), any(), any(), any(), any(), any(), any())) + .thenReturn(null); + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(null); + workflowInternalActionVerticle.process(workflowInternalActionDTO); + } + + @Test + public void testProcessSuccessForCompleteAsProcessed() { + WorkflowInternalActionDTO workflowInternalActionDTO = new WorkflowInternalActionDTO(); + workflowInternalActionDTO.setRid("10006100390000920200603070407"); + workflowInternalActionDTO.setActionCode(WorkflowInternalActionCode.COMPLETE_AS_PROCESSED.toString()); + workflowInternalActionDTO.setActionMessage("packet is complete as processed"); + Mockito.doNothing().when(registrationStatusService).updateRegistrationStatusForWorkflowEngine(any(), any(), any()); + registrationStatusDto = new InternalRegistrationStatusDto(); + registrationStatusDto.setRegistrationId("10006100390000920200603070407"); + Mockito.when(auditLogRequestBuilder.createAuditRequestBuilder(any(), any(), any(), any(), any(), any(), any())) + .thenReturn(null); + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); + workflowInternalActionVerticle.process(workflowInternalActionDTO); + ArgumentCaptor argument = ArgumentCaptor + .forClass(InternalRegistrationStatusDto.class); + + verify(registrationStatusService, atLeastOnce()).updateRegistrationStatusForWorkflowEngine(argument.capture(), Mockito.any(), + Mockito.any()); + assertEquals(RegistrationStatusCode.PROCESSED.toString(), argument.getAllValues().get(0).getStatusCode()); + ArgumentCaptor argument1 = ArgumentCaptor.forClass(WorkflowCompletedEventDTO.class); + + verify(webSubUtil, atLeastOnce()).publishEvent(argument1.capture()); + assertEquals(RegistrationStatusCode.PROCESSED.toString(), argument1.getAllValues().get(0).getResultCode()); + + } + + @Test + public void testProcessSuccessForCompleteAsRejected() { + WorkflowInternalActionDTO workflowInternalActionDTO = new WorkflowInternalActionDTO(); + workflowInternalActionDTO.setRid("10006100390000920200603070407"); + workflowInternalActionDTO.setActionCode(WorkflowInternalActionCode.COMPLETE_AS_REJECTED.toString()); + workflowInternalActionDTO.setActionMessage("packet is complete as rejected"); + Mockito.doNothing().when(registrationStatusService).updateRegistrationStatusForWorkflowEngine(any(), any(), any()); + registrationStatusDto = new InternalRegistrationStatusDto(); + registrationStatusDto.setRegistrationId("10006100390000920200603070407"); + Mockito.when(auditLogRequestBuilder.createAuditRequestBuilder(any(), any(), any(), any(), any(), any(), any())) + .thenReturn(null); + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); + workflowInternalActionVerticle.process(workflowInternalActionDTO); + ArgumentCaptor argument = ArgumentCaptor + .forClass(InternalRegistrationStatusDto.class); + + verify(registrationStatusService, atLeastOnce()).updateRegistrationStatusForWorkflowEngine(argument.capture(), Mockito.any(), + Mockito.any()); + assertEquals(RegistrationStatusCode.REJECTED.toString(), argument.getAllValues().get(0).getStatusCode()); + ArgumentCaptor argument1 = ArgumentCaptor.forClass(WorkflowCompletedEventDTO.class); + verify(webSubUtil, atLeastOnce()).publishEvent(argument1.capture()); + assertEquals(RegistrationStatusCode.REJECTED.toString(), argument1.getAllValues().get(0).getResultCode()); + + } + + @Test + public void testProcessSuccessForCompleteAsFailed() { + WorkflowInternalActionDTO workflowInternalActionDTO = new WorkflowInternalActionDTO(); + workflowInternalActionDTO.setRid("10006100390000920200603070407"); + workflowInternalActionDTO.setActionCode(WorkflowInternalActionCode.COMPLETE_AS_FAILED.toString()); + workflowInternalActionDTO.setActionMessage("packet is complete as failed"); + Mockito.doNothing().when(registrationStatusService).updateRegistrationStatusForWorkflowEngine(any(), any(), any()); + registrationStatusDto = new InternalRegistrationStatusDto(); + registrationStatusDto.setRegistrationId("10006100390000920200603070407"); + Mockito.when(auditLogRequestBuilder.createAuditRequestBuilder(any(), any(), any(), any(), any(), any(), any())) + .thenReturn(null); + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); + workflowInternalActionVerticle.process(workflowInternalActionDTO); + ArgumentCaptor argument = ArgumentCaptor + .forClass(InternalRegistrationStatusDto.class); + + verify(registrationStatusService, atLeastOnce()).updateRegistrationStatusForWorkflowEngine(argument.capture(), Mockito.any(), + Mockito.any()); + assertEquals(RegistrationStatusCode.FAILED.toString(), argument.getAllValues().get(0).getStatusCode()); + ArgumentCaptor argument1 = ArgumentCaptor.forClass(WorkflowCompletedEventDTO.class); + verify(webSubUtil, atLeastOnce()).publishEvent(argument1.capture()); + assertEquals(RegistrationStatusCode.FAILED.toString(), argument1.getAllValues().get(0).getResultCode()); + } + + @Test + public void testProcessSuccessForMarkAsReprocess() + { + WorkflowInternalActionDTO workflowInternalActionDTO = new WorkflowInternalActionDTO(); + workflowInternalActionDTO.setRid("10006100390000920200603070407"); + workflowInternalActionDTO.setActionCode(WorkflowInternalActionCode.MARK_AS_REPROCESS.toString()); + workflowInternalActionDTO.setActionMessage("packet is marked as reprocess"); + Mockito.doNothing().when(registrationStatusService).updateRegistrationStatusForWorkflowEngine(any(), any(), any()); + registrationStatusDto = new InternalRegistrationStatusDto(); + registrationStatusDto.setRegistrationId("10006100390000920200603070407"); + Mockito.when(auditLogRequestBuilder.createAuditRequestBuilder(any(), any(), any(), any(), any(), any(), any())) + .thenReturn(null); + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); + workflowInternalActionVerticle.process(workflowInternalActionDTO); + ArgumentCaptor argument = ArgumentCaptor + .forClass(InternalRegistrationStatusDto.class); + + verify(registrationStatusService, atLeastOnce()).updateRegistrationStatusForWorkflowEngine(argument.capture(), Mockito.any(), + Mockito.any()); + assertEquals(RegistrationStatusCode.REPROCESS.toString(), argument.getAllValues().get(0).getStatusCode()); + } + + @Test + public void testProcessSuccessForPauseAndRequestAdditionalInfo() { + WorkflowInternalActionDTO workflowInternalActionDTO = new WorkflowInternalActionDTO(); + workflowInternalActionDTO.setRid("10006100390000920200603070407"); + workflowInternalActionDTO.setActionCode(WorkflowInternalActionCode.PAUSE_AND_REQUEST_ADDITIONAL_INFO.toString()); + workflowInternalActionDTO.setActionMessage("packet is paused for Additional Info"); + workflowInternalActionDTO.setResumeTimestamp("2021-03-02T08:24:29.526Z"); + workflowInternalActionDTO.setDefaultResumeAction(WorkflowActionCode.STOP_PROCESSING.toString()); + workflowInternalActionDTO.setIteration(1); + workflowInternalActionDTO.setReg_type("NEW"); + workflowInternalActionDTO.setAdditionalInfoProcess("CORRECTION"); + Mockito.doNothing().when(registrationStatusService).updateRegistrationStatusForWorkflowEngine(any(), any(), any()); + registrationStatusDto = new InternalRegistrationStatusDto(); + registrationStatusDto.setRegistrationId("10006100390000920200603070407"); + Mockito.when(auditLogRequestBuilder.createAuditRequestBuilder(any(), any(), any(), any(), any(), any(), any())) + .thenReturn(null); + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())) + .thenReturn(registrationStatusDto); + Mockito.when( + additionalInfoRequestService.getAdditionalInfoRequestByRegIdAndProcess(anyString(), anyString())) + .thenReturn(null); + workflowInternalActionVerticle.process(workflowInternalActionDTO); + ArgumentCaptor argument = ArgumentCaptor + .forClass(InternalRegistrationStatusDto.class); + + verify(registrationStatusService, atLeastOnce()).updateRegistrationStatusForWorkflowEngine(argument.capture(), Mockito.any(), + Mockito.any()); + assertEquals(RegistrationStatusCode.PAUSED_FOR_ADDITIONAL_INFO.toString(), + argument.getAllValues().get(0).getStatusCode()); + ArgumentCaptor argument1 = ArgumentCaptor.forClass(AdditionalInfoRequestDto.class); + + verify(additionalInfoRequestService, atLeastOnce()).addAdditionalInfoRequest(argument1.capture()); + assertEquals(workflowInternalActionDTO.getAdditionalInfoProcess(), + argument1.getAllValues().get(0).getAdditionalInfoProcess()); + ArgumentCaptor argument2 = ArgumentCaptor + .forClass(WorkflowPausedForAdditionalInfoEventDTO.class); + + verify(webSubUtil, atLeastOnce()).publishEvent(argument2.capture()); + assertEquals(workflowInternalActionDTO.getAdditionalInfoProcess(), + argument2.getAllValues().get(0).getAdditionalInfoProcess()); + + } + @Test + public void testProcessSuccessForRestartParentFlow() throws WorkflowActionException, ApisResourceAccessException, + PacketManagerException, JsonProcessingException, IOException { + WorkflowInternalActionDTO workflowInternalActionDTO = new WorkflowInternalActionDTO(); + workflowInternalActionDTO.setRid("10006100390000920200603070407"); + workflowInternalActionDTO.setActionCode(WorkflowInternalActionCode.RESTART_PARENT_FLOW.toString()); + workflowInternalActionDTO.setActionMessage(PlatformSuccessMessages.PACKET_RESTART_PARENT_FLOW.getMessage()); + workflowInternalActionDTO.setReg_type("CORRECTION"); + workflowInternalActionDTO.setIteration(1); + AdditionalInfoRequestDto additionalInfoRequestDto = new AdditionalInfoRequestDto(); + additionalInfoRequestDto.setRegId("10006100390000920200603070407"); + additionalInfoRequestDto.setAdditionalInfoIteration(1); + additionalInfoRequestDto.setWorkflowInstanceId("Workflow123"); + additionalInfoRequestDto.setAdditionalInfoReqId("additionalRequestId"); + Mockito.when(additionalInfoRequestService.getAdditionalInfoRequestByRegIdAndProcessAndIteration(Mockito.anyString(), + Mockito.anyString(), Mockito.anyInt())).thenReturn(additionalInfoRequestDto); + registrationStatusDto = new InternalRegistrationStatusDto(); + registrationStatusDto.setRegistrationId("10006100390000920200603070407"); + Mockito.when(auditLogRequestBuilder.createAuditRequestBuilder(any(), any(), any(), any(), any(), any(), any())) + .thenReturn(null); + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())) + .thenReturn(registrationStatusDto); + workflowInternalActionVerticle.process(workflowInternalActionDTO); + verify(workflowActionService, times(1)).processWorkflowAction(Mockito.any(), Mockito.anyString()); + verify(packetManagerService, times(1)).addOrUpdateTags(Mockito.anyString(), Mockito.any()); + } + + @Test + public void testProcessSuccessForCompleteAsProcessedForAdditionalInfoWorkflow() + throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException, + WorkflowActionException { + WorkflowInternalActionDTO workflowInternalActionDTO = new WorkflowInternalActionDTO(); + workflowInternalActionDTO.setRid("10006100390000920200603070407"); + workflowInternalActionDTO.setActionCode(WorkflowInternalActionCode.COMPLETE_AS_PROCESSED.toString()); + workflowInternalActionDTO.setActionMessage("packet is complete as processed"); + workflowInternalActionDTO.setReg_type("CORRECTION"); + Mockito.doNothing().when(registrationStatusService).updateRegistrationStatusForWorkflowEngine(any(), any(), any()); + registrationStatusDto = new InternalRegistrationStatusDto(); + registrationStatusDto.setRegistrationId("10006100390000920200603070407"); + Mockito.when(auditLogRequestBuilder.createAuditRequestBuilder(any(), any(), any(), any(), any(), any(), any())) + .thenReturn(null); + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())) + .thenReturn(registrationStatusDto); + AdditionalInfoRequestDto additionalInfoRequestDto = new AdditionalInfoRequestDto(); + additionalInfoRequestDto.setRegId("10006100390000920200603070407"); + additionalInfoRequestDto.setAdditionalInfoIteration(1); + additionalInfoRequestDto.setWorkflowInstanceId("Workflow123"); + additionalInfoRequestDto.setAdditionalInfoReqId("additionalRequestId"); + Mockito.when(additionalInfoRequestService.getAdditionalInfoRequestByRegIdAndProcessAndIteration(Mockito.anyString(), + Mockito.anyString(), Mockito.anyInt())).thenReturn(additionalInfoRequestDto); + workflowInternalActionVerticle.process(workflowInternalActionDTO); + ArgumentCaptor argument = ArgumentCaptor + .forClass(InternalRegistrationStatusDto.class); + + verify(registrationStatusService, atLeastOnce()).updateRegistrationStatusForWorkflowEngine(argument.capture(), Mockito.any(), + Mockito.any()); + assertEquals(RegistrationStatusCode.PROCESSED.toString(), argument.getAllValues().get(0).getStatusCode()); + verify(workflowActionService, times(1)).processWorkflowAction(Mockito.any(), Mockito.anyString()); + verify(packetManagerService, times(1)).addOrUpdateTags(Mockito.anyString(), Mockito.any()); + } + + @Test + public void testProcessSuccessForCompleteAsRejectedForAdditionalInfoWorkflow() + throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException, + WorkflowActionException { + WorkflowInternalActionDTO workflowInternalActionDTO = new WorkflowInternalActionDTO(); + workflowInternalActionDTO.setRid("10006100390000920200603070407"); + workflowInternalActionDTO.setActionCode(WorkflowInternalActionCode.COMPLETE_AS_REJECTED.toString()); + workflowInternalActionDTO.setActionMessage("packet is complete as rejected"); + workflowInternalActionDTO.setReg_type("CORRECTION"); + Mockito.doNothing().when(registrationStatusService).updateRegistrationStatusForWorkflowEngine(any(), any(), any()); + registrationStatusDto = new InternalRegistrationStatusDto(); + registrationStatusDto.setRegistrationId("10006100390000920200603070407"); + Mockito.when(auditLogRequestBuilder.createAuditRequestBuilder(any(), any(), any(), any(), any(), any(), any())) + .thenReturn(null); + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())) + .thenReturn(registrationStatusDto); + AdditionalInfoRequestDto additionalInfoRequestDto = new AdditionalInfoRequestDto(); + additionalInfoRequestDto.setRegId("10006100390000920200603070407"); + additionalInfoRequestDto.setAdditionalInfoIteration(1); + additionalInfoRequestDto.setWorkflowInstanceId("Workflow123"); + additionalInfoRequestDto.setAdditionalInfoReqId("additionalRequestId"); + Mockito.when(additionalInfoRequestService.getAdditionalInfoRequestByRegIdAndProcessAndIteration(Mockito.anyString(), + Mockito.anyString(), Mockito.anyInt())).thenReturn(additionalInfoRequestDto); + workflowInternalActionVerticle.process(workflowInternalActionDTO); + ArgumentCaptor argument = ArgumentCaptor + .forClass(InternalRegistrationStatusDto.class); + + verify(registrationStatusService, atLeastOnce()).updateRegistrationStatusForWorkflowEngine(argument.capture(), Mockito.any(), + Mockito.any()); + assertEquals(RegistrationStatusCode.REJECTED.toString(), argument.getAllValues().get(0).getStatusCode()); + verify(workflowActionService, times(1)).processWorkflowAction(Mockito.any(), Mockito.anyString()); + verify(packetManagerService, times(1)).addOrUpdateTags(Mockito.anyString(), Mockito.any()); + } + + @Test + public void testProcessSuccessForCompleteAsFailedForAdditionalInfoWorkflow() + throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException, + WorkflowActionException { + WorkflowInternalActionDTO workflowInternalActionDTO = new WorkflowInternalActionDTO(); + workflowInternalActionDTO.setRid("10006100390000920200603070407"); + workflowInternalActionDTO.setActionCode(WorkflowInternalActionCode.COMPLETE_AS_FAILED.toString()); + workflowInternalActionDTO.setActionMessage("packet is complete as failed"); + workflowInternalActionDTO.setReg_type("CORRECTION"); + Mockito.doNothing().when(registrationStatusService).updateRegistrationStatusForWorkflowEngine(any(), any(), any()); + registrationStatusDto = new InternalRegistrationStatusDto(); + registrationStatusDto.setRegistrationId("10006100390000920200603070407"); + Mockito.when(auditLogRequestBuilder.createAuditRequestBuilder(any(), any(), any(), any(), any(), any(), any())) + .thenReturn(null); + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())) + .thenReturn(registrationStatusDto); + AdditionalInfoRequestDto additionalInfoRequestDto = new AdditionalInfoRequestDto(); + additionalInfoRequestDto.setRegId("10006100390000920200603070407"); + additionalInfoRequestDto.setAdditionalInfoIteration(1); + additionalInfoRequestDto.setAdditionalInfoProcess("CORRECTION"); + additionalInfoRequestDto.setWorkflowInstanceId("Workflow123"); + additionalInfoRequestDto.setAdditionalInfoReqId("additionalRequestId"); + Mockito.when(additionalInfoRequestService.getAdditionalInfoRequestByRegIdAndProcessAndIteration(Mockito.anyString(), + Mockito.anyString(), Mockito.anyInt())).thenReturn(additionalInfoRequestDto); + workflowInternalActionVerticle.process(workflowInternalActionDTO); + ArgumentCaptor argument = ArgumentCaptor + .forClass(InternalRegistrationStatusDto.class); + + verify(registrationStatusService, atLeastOnce()).updateRegistrationStatusForWorkflowEngine(argument.capture(), Mockito.any(), + Mockito.any()); + assertEquals(RegistrationStatusCode.FAILED.toString(), argument.getAllValues().get(0).getStatusCode()); + verify(workflowActionService, times(1)).processWorkflowAction(Mockito.any(), Mockito.anyString()); + verify(packetManagerService, times(1)).addOrUpdateTags(Mockito.anyString(), Mockito.any()); + } + + @Test + public void testProcessSuccessForPauseAndRequestAdditionalInfoForAdditionalInfoWorkflow() throws WorkflowActionException, + ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { + WorkflowInternalActionDTO workflowInternalActionDTO = new WorkflowInternalActionDTO(); + workflowInternalActionDTO.setRid("10006100390000920200603070407"); + workflowInternalActionDTO + .setActionCode(WorkflowInternalActionCode.PAUSE_AND_REQUEST_ADDITIONAL_INFO.toString()); + workflowInternalActionDTO.setActionMessage("packet is paused for Additional Info"); + workflowInternalActionDTO.setResumeTimestamp("2021-03-02T08:24:29.526Z"); + workflowInternalActionDTO.setDefaultResumeAction(WorkflowActionCode.STOP_PROCESSING.toString()); + workflowInternalActionDTO.setIteration(1); + workflowInternalActionDTO.setReg_type("CORRECTION"); + Mockito.doNothing().when(registrationStatusService).updateRegistrationStatusForWorkflowEngine(any(), any(), any()); + registrationStatusDto = new InternalRegistrationStatusDto(); + registrationStatusDto.setRegistrationId("10006100390000920200603070407"); + Mockito.when(auditLogRequestBuilder.createAuditRequestBuilder(any(), any(), any(), any(), any(), any(), any())) + .thenReturn(null); + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())) + .thenReturn(registrationStatusDto); + AdditionalInfoRequestDto additionalInfoRequestDto = new AdditionalInfoRequestDto(); + additionalInfoRequestDto.setRegId("10006100390000920200603070407"); + additionalInfoRequestDto.setAdditionalInfoIteration(1); + additionalInfoRequestDto.setWorkflowInstanceId("Workflow123"); + additionalInfoRequestDto.setAdditionalInfoReqId("additionalRequestId"); + Mockito.when(additionalInfoRequestService.getAdditionalInfoRequestByRegIdAndProcessAndIteration(Mockito.anyString(), + Mockito.anyString(), Mockito.anyInt())).thenReturn(additionalInfoRequestDto); + workflowInternalActionVerticle.process(workflowInternalActionDTO); + ArgumentCaptor argument = ArgumentCaptor + .forClass(InternalRegistrationStatusDto.class); + + verify(registrationStatusService, atLeastOnce()).updateRegistrationStatusForWorkflowEngine(argument.capture(), Mockito.any(), + Mockito.any()); + assertEquals(RegistrationStatusCode.FAILED.toString(), + argument.getAllValues().get(0).getStatusCode()); + verify(workflowActionService, times(1)).processWorkflowAction(Mockito.any(), Mockito.anyString()); + verify(packetManagerService, times(1)).addOrUpdateTags(Mockito.anyString(), Mockito.any()); + } + + @Test + public void testProcessSuccessForCompleteAsRejectedWithoutParentFlow() { + WorkflowInternalActionDTO workflowInternalActionDTO = new WorkflowInternalActionDTO(); + workflowInternalActionDTO.setRid("10006100390000920200603070407"); + workflowInternalActionDTO + .setActionCode(WorkflowInternalActionCode.COMPLETE_AS_REJECTED_WITHOUT_PARENT_FLOW.toString()); + workflowInternalActionDTO + .setActionMessage("Packet processing completed with reject status without Parent flow"); + workflowInternalActionDTO.setReg_type("CORRECTION"); + Mockito.doNothing().when(registrationStatusService).updateRegistrationStatusForWorkflowEngine(any(), any(), any()); + registrationStatusDto = new InternalRegistrationStatusDto(); + registrationStatusDto.setRegistrationId("10006100390000920200603070407"); + Mockito.when(auditLogRequestBuilder.createAuditRequestBuilder(any(), any(), any(), any(), any(), any(), any())) + .thenReturn(null); + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())) + .thenReturn(registrationStatusDto); + workflowInternalActionVerticle.process(workflowInternalActionDTO); + ArgumentCaptor argument = ArgumentCaptor + .forClass(InternalRegistrationStatusDto.class); + + verify(registrationStatusService, atLeastOnce()).updateRegistrationStatusForWorkflowEngine(argument.capture(), Mockito.any(), + Mockito.any()); + assertEquals(RegistrationStatusCode.REJECTED.toString(), argument.getAllValues().get(0).getStatusCode()); + } + @Test + public void testProcessSuccessForPauseAndRequestAdditionalInfoWithMaxAllowedIterationExceed() { + WorkflowInternalActionDTO workflowInternalActionDTO = new WorkflowInternalActionDTO(); + workflowInternalActionDTO.setRid("10006100390000920200603070407"); + workflowInternalActionDTO.setActionCode(WorkflowInternalActionCode.PAUSE_AND_REQUEST_ADDITIONAL_INFO.toString()); + workflowInternalActionDTO.setActionMessage("packet is paused for Additional Info"); + workflowInternalActionDTO.setResumeTimestamp("2021-03-02T08:24:29.526Z"); + workflowInternalActionDTO.setDefaultResumeAction(WorkflowActionCode.STOP_PROCESSING.toString()); + workflowInternalActionDTO.setIteration(6); + workflowInternalActionDTO.setReg_type("NEW"); + workflowInternalActionDTO.setAdditionalInfoProcess("CORRECTION"); + Mockito.doNothing().when(registrationStatusService).updateRegistrationStatusForWorkflowEngine(any(), any(), any()); + registrationStatusDto = new InternalRegistrationStatusDto(); + registrationStatusDto.setRegistrationId("10006100390000920200603070407"); + Mockito.when(auditLogRequestBuilder.createAuditRequestBuilder(any(), any(), any(), any(), any(), any(), any())) + .thenReturn(null); + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())) + .thenReturn(registrationStatusDto); + AdditionalInfoRequestDto additionalInfoRequestDto = new AdditionalInfoRequestDto(); + additionalInfoRequestDto.setRegId("10006100390000920200603070407"); + additionalInfoRequestDto.setAdditionalInfoIteration(5); + additionalInfoRequestDto.setWorkflowInstanceId("Workflow123"); + additionalInfoRequestDto.setAdditionalInfoReqId("additionalRequestId"); + List additionalInfoRequestDtoList=new ArrayList(); + additionalInfoRequestDtoList.add(additionalInfoRequestDto); + Mockito.when( + additionalInfoRequestService.getAdditionalInfoRequestByRegIdAndProcess(anyString(), anyString())) + .thenReturn(additionalInfoRequestDtoList); + workflowInternalActionVerticle.process(workflowInternalActionDTO); + ArgumentCaptor argument = ArgumentCaptor + .forClass(InternalRegistrationStatusDto.class); + + verify(registrationStatusService, atLeastOnce()).updateRegistrationStatusForWorkflowEngine(argument.capture(), Mockito.any(), + Mockito.any()); + assertEquals(RegistrationStatusCode.REJECTED.toString(), argument.getAllValues().get(0).getStatusCode()); + ArgumentCaptor argument1 = ArgumentCaptor.forClass(WorkflowCompletedEventDTO.class); + verify(webSubUtil, atLeastOnce()).publishEvent(argument1.capture()); + assertEquals(RegistrationStatusCode.REJECTED.toString(), argument1.getAllValues().get(0).getResultCode()); + } + + @SuppressWarnings("unchecked") + @Test + public void testProcessSuccessForAnonymousProfile() throws IOException, JSONException, BaseCheckedException { + WorkflowInternalActionDTO workflowInternalActionDTO = new WorkflowInternalActionDTO(); + workflowInternalActionDTO.setRid("10006100390000920200603070407"); + workflowInternalActionDTO.setReg_type("NEW"); + workflowInternalActionDTO.setIsValid(true); + workflowInternalActionDTO.setActionCode(WorkflowInternalActionCode.ANONYMOUS_PROFILE.toString()); + workflowInternalActionDTO.setActionMessage("anonymous profile event"); + + Mockito.when(packetManagerService.getFieldByMappingJsonKey(anyString(), anyString(), anyString(), any())) + .thenReturn("1.0"); + Mockito.when(idSchemaUtil.getDefaultFields(anyDouble())).thenReturn(Arrays.asList("")); + + Map fieldTypeMap = new HashedMap(); + fieldTypeMap.put("postalCode", "string"); + fieldTypeMap.put("zone", "simpleType"); + Mockito.when(idSchemaUtil.getIdSchemaFieldTypes(anyDouble())).thenReturn(fieldTypeMap); + + Map fieldMap = new HashedMap(); + fieldMap.put("postalCode", "14022"); + fieldMap.put("dateOfBirth", "1998/01/01"); + fieldMap.put("phone", "6666666666"); + Mockito.when(packetManagerService.getFields(anyString(), any(), anyString(), any())).thenReturn(fieldMap); + + Map metaInfoMap = new HashedMap(); + metaInfoMap.put("documents", "[{\"documentType\" : \"CIN\"},{\"documentType\" : \"RNC\"})]"); + metaInfoMap.put("operationsData", + "[{\"label\" : \"officerId\",\"value\" : \"110024\"},{\"label\" : \"officerBiometricFileName\",\"value\" : \"null\"})]"); + metaInfoMap.put("creationDate", "2021-09-01T03:48:49.193Z"); + Mockito.when(packetManagerService.getMetaInfo(anyString(), anyString(), any())).thenReturn(metaInfoMap); + + BiometricRecord biometricRecord = new BiometricRecord(); + BIR bir = new BIR(); + HashMap entry = new HashMap<>(); + bir.setSb("eyJ4NWMiOlsiTUlJRGtEQ0NBbmlnQXdJQkFnSUVwNzo".getBytes()); + bir.setBdb("SUlSADAyMAAAACc6AAEAAQAAJyoH5AoJECYh//8Bc18wBgAAAQIDCgABlwExCA".getBytes()); + entry.put("PAYLOAD", "{\"deviceServiceVersion\":\"0.9.5\",\"bioValue\":\"\",\"qualityScore\":\"80\",\"bioType\":\"Iris\"}"); + bir.setOthers(entry); + biometricRecord.setSegments(Arrays.asList(bir)); + Mockito.when(packetManagerService.getBiometrics(anyString(), anyString(), anyString(), any())) + .thenReturn(biometricRecord); + + org.json.simple.JSONObject identity = new org.json.simple.JSONObject(); + LinkedHashMap IDSchemaVersion = new LinkedHashMap(); + IDSchemaVersion.put("value", "1.0"); + identity.put("IDSchemaVersion", IDSchemaVersion); + + registrationStatusDto = new InternalRegistrationStatusDto(); + registrationStatusDto.setRegistrationId("10006100390000920200603070407"); + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())) + .thenReturn(registrationStatusDto); + Mockito.when(utility.getRegistrationProcessorMappingJson(any())) + .thenReturn(identity); + Mockito.when(auditLogRequestBuilder.createAuditRequestBuilder(any(), any(), any(), any(), any(), any(), any())) + .thenReturn(null); + Mockito.when(anonymousProfileService.buildJsonStringFromPacketInfo(any(), any(), any(), any(), anyString(), + anyString())).thenReturn("jsonProfile"); + Mockito.doNothing().when(anonymousProfileService).saveAnonymousProfile(anyString(), anyString(), anyString()); + MessageDTO object = workflowInternalActionVerticle.process(workflowInternalActionDTO); + assertEquals(true, object.getIsValid()); + } +} From 26e331d9de061c7aab631b023a1b3068cc0e5fb6 Mon Sep 17 00:00:00 2001 From: Sowmya Ujjappa Banakar Date: Wed, 17 May 2023 11:35:36 +0530 Subject: [PATCH 067/133] MOSIP-27349 script changes --- .../sql/1.1.5.5_to_1.2.0.1-B1_rollback.sql | 142 +++++++++++++++++- .../mosip_regprc/upgrade.properties | 8 +- db_upgrade_scripts/mosip_regprc/upgrade.sh | 10 +- 3 files changed, 148 insertions(+), 12 deletions(-) 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 index 319309c57db..58f9e85e965 100644 --- 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 @@ -1,8 +1,144 @@ +-- ------------------------------------------------------------------------------------------------- +-- 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 +--need to drop now after reverting to old columns add old constraint + +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 sourc; +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.registration_list DROP CONSTRAINT IF EXISTS pk_reglist_id; +ALTER TABLE regprc.registration_list ALTER COLUMN id SET NOT NULL; +ALTER TABLE regprc.registration_list ADD CONSTRAINT pk_reglist_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_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_rollback.csv' delimiter ',' HEADER csv; + +UPDATE regprc.registration_transaction SET trn_type_code='QUALITY_CHECK' WHERE trn_type_code='QUALITY_CLASSIFIER'; +UPDATE regprc.reg_manual_verification SET trntyp_code='QUALITY_CHECK' WHERE trntyp_code='QUALITY_CLASSIFIER'; + +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; + +ALTER TABLE regprc.registration DROP COLUMN IF EXISTS last_success_stage_name; +-------------------------------------------------------drop columns to registration_list---------------------------------------------- --------------------------------------------------------------------------------------------- -ALTER TABLE regprc.registration DROP COLUMN IF EXISTS resume_remove_tags; ----------------------------------------------------------------------------------------------------- +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; \ No newline at end of file diff --git a/db_upgrade_scripts/mosip_regprc/upgrade.properties b/db_upgrade_scripts/mosip_regprc/upgrade.properties index 3bdec16410a..02b0d148be9 100644 --- a/db_upgrade_scripts/mosip_regprc/upgrade.properties +++ b/db_upgrade_scripts/mosip_regprc/upgrade.properties @@ -1,4 +1,5 @@ -MOSIP_DB_NAME= +ACTION=upgrade +MOSIP_DB_NAME=mosip_regprc DB_SERVERIP= DB_PORT= SU_USER=postgres @@ -7,6 +8,5 @@ SYS_ADMIN_USER= SYS_ADMIN_PWD= DEFAULT_DB_NAME=postgres DBUSER_PWD= -CURRENT_VERSION= -TARGET_VERSION= -ACTION= \ No newline at end of file +CURRENT_VERSION=1.1.5.5 +UPGRADE_VERSION=1.2.0.1-B1 \ No newline at end of file diff --git a/db_upgrade_scripts/mosip_regprc/upgrade.sh b/db_upgrade_scripts/mosip_regprc/upgrade.sh index 1e0619e00c6..a6fb0b1e457 100644 --- a/db_upgrade_scripts/mosip_regprc/upgrade.sh +++ b/db_upgrade_scripts/mosip_regprc/upgrade.sh @@ -15,9 +15,9 @@ 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" +echo "Current version: "$CURRENT_VERSION +echo "UPGRADE version: "$UPGRADE_VERSION +echo "Action: "$ACTION # Terminate existing connections echo "Terminating active connections" @@ -25,7 +25,7 @@ CONN=$(PGPASSWORD=$SU_USER_PWD psql -v ON_ERROR_STOP=1 --username=$SU_USER --hos echo "Terminated connections" # Execute upgrade or rollback -if [ "$ACTION" == "upgrade" ]; then +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 @@ -35,7 +35,7 @@ if [ "$ACTION" == "upgrade" ]; then echo "Upgrade script not found, exiting." exit 1 fi -elif [ "$ACTION" == "rollback" ]; then +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 From 38cc430382158c44e43f892a0c240c62d685a08e Mon Sep 17 00:00:00 2001 From: Sowmya Ujjappa Banakar Date: Fri, 19 May 2023 14:23:30 +0530 Subject: [PATCH 068/133] MOSIP-27349 review comments fixed --- .../sql/1.1.5.5_to_1.2.0.1-B1_rollback.sql | 44 ++++++---------- .../sql/1.1.5.5_to_1.2.0.1-B1_upgrade.sql | 50 ++++++++----------- .../mosip_regprc/upgrade.properties | 4 +- 3 files changed, 38 insertions(+), 60 deletions(-) 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 index 58f9e85e965..4ecae8182d7 100644 --- 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 @@ -28,7 +28,7 @@ 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 sourc; +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; @@ -86,10 +86,6 @@ 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.registration_list DROP CONSTRAINT IF EXISTS pk_reglist_id; -ALTER TABLE regprc.registration_list ALTER COLUMN id SET NOT NULL; -ALTER TABLE regprc.registration_list ADD CONSTRAINT pk_reglist_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; @@ -109,30 +105,6 @@ 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_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_rollback.csv' delimiter ',' HEADER csv; - -UPDATE regprc.registration_transaction SET trn_type_code='QUALITY_CHECK' WHERE trn_type_code='QUALITY_CLASSIFIER'; -UPDATE regprc.reg_manual_verification SET trntyp_code='QUALITY_CHECK' WHERE trntyp_code='QUALITY_CLASSIFIER'; - -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; - ALTER TABLE regprc.registration DROP COLUMN IF EXISTS last_success_stage_name; -------------------------------------------------------drop columns to registration_list---------------------------------------------- @@ -141,4 +113,16 @@ 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; \ No newline at end of file +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_upgrade_scripts/mosip_regprc/sql/1.1.5.5_to_1.2.0.1-B1_upgrade.sql b/db_upgrade_scripts/mosip_regprc/sql/1.1.5.5_to_1.2.0.1-B1_upgrade.sql index d059a7740e8..f000cd0fc3e 100644 --- a/db_upgrade_scripts/mosip_regprc/sql/1.1.5.5_to_1.2.0.1-B1_upgrade.sql +++ b/db_upgrade_scripts/mosip_regprc/sql/1.1.5.5_to_1.2.0.1-B1_upgrade.sql @@ -86,11 +86,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; @@ -117,29 +112,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); ------------------------------------------------------------------------------------------------------ diff --git a/db_upgrade_scripts/mosip_regprc/upgrade.properties b/db_upgrade_scripts/mosip_regprc/upgrade.properties index 02b0d148be9..88b7143ad4a 100644 --- a/db_upgrade_scripts/mosip_regprc/upgrade.properties +++ b/db_upgrade_scripts/mosip_regprc/upgrade.properties @@ -8,5 +8,5 @@ SYS_ADMIN_USER= SYS_ADMIN_PWD= DEFAULT_DB_NAME=postgres DBUSER_PWD= -CURRENT_VERSION=1.1.5.5 -UPGRADE_VERSION=1.2.0.1-B1 \ No newline at end of file +CURRENT_VERSION= +UPGRADE_VERSION= \ No newline at end of file From 38a99620c2580e4e9d026483c8bdde844b7404c9 Mon Sep 17 00:00:00 2001 From: Sowmya Ujjappa Banakar Date: Mon, 22 May 2023 15:59:52 +0530 Subject: [PATCH 069/133] MOSIP-23678 Code changes --- .../stage/SecurezoneNotificationStage.java | 771 ++++++------ .../SecurezoneNotificationStageTest.java | 1058 +++++++++-------- 2 files changed, 923 insertions(+), 906 deletions(-) diff --git a/registration-processor/pre-processor/registration-processor-securezone-notification-stage/src/main/java/io/mosip/registration/processor/securezone/notification/stage/SecurezoneNotificationStage.java b/registration-processor/pre-processor/registration-processor-securezone-notification-stage/src/main/java/io/mosip/registration/processor/securezone/notification/stage/SecurezoneNotificationStage.java index e7a12e896a4..2006859db41 100644 --- a/registration-processor/pre-processor/registration-processor-securezone-notification-stage/src/main/java/io/mosip/registration/processor/securezone/notification/stage/SecurezoneNotificationStage.java +++ b/registration-processor/pre-processor/registration-processor-securezone-notification-stage/src/main/java/io/mosip/registration/processor/securezone/notification/stage/SecurezoneNotificationStage.java @@ -1,386 +1,385 @@ -package io.mosip.registration.processor.securezone.notification.stage; - -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; -import java.util.stream.Collectors; - -import org.apache.commons.collections.CollectionUtils; -import org.apache.commons.lang3.exception.ExceptionUtils; -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.Component; - -import io.mosip.kernel.core.logger.spi.Logger; -import io.mosip.registration.processor.core.abstractverticle.MessageBusAddress; -import io.mosip.registration.processor.core.abstractverticle.MessageDTO; -import io.mosip.registration.processor.core.abstractverticle.MosipEventBus; -import io.mosip.registration.processor.core.abstractverticle.MosipRouter; -import io.mosip.registration.processor.core.abstractverticle.MosipVerticleAPIManager; -import io.mosip.registration.processor.core.code.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.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.status.util.StatusUtil; -import io.mosip.registration.processor.core.status.util.TrimExceptionMessage; -import io.mosip.registration.processor.core.util.RegistrationExceptionMapperUtil; -import io.mosip.registration.processor.rest.client.audit.builder.AuditLogRequestBuilder; -import io.mosip.registration.processor.status.code.RegistrationStatusCode; -import io.mosip.registration.processor.status.dto.InternalRegistrationStatusDto; -import io.mosip.registration.processor.status.dto.RegistrationStatusDto; -import io.mosip.registration.processor.status.dto.SyncRegistrationDto; -import io.mosip.registration.processor.status.dto.SyncResponseDto; -import io.mosip.registration.processor.status.entity.SyncRegistrationEntity; -import io.mosip.registration.processor.status.exception.TablenotAccessibleException; -import io.mosip.registration.processor.status.service.RegistrationStatusService; -import io.mosip.registration.processor.status.service.SyncRegistrationService; -import io.vertx.core.json.JsonObject; -import io.vertx.ext.web.RoutingContext; - -@Component -@Configuration -@ComponentScan(basePackages = { "${mosip.auth.adapter.impl.basepackage}", - "io.mosip.registration.processor.core.config", - "io.mosip.registration.processor.securezone.notification.config", - "io.mosip.registration.processor.packet.manager.config", "io.mosip.registration.processor.status.config", - "io.mosip.registration.processor.rest.client.config", "io.mosip.registration.processor.core.kernel.beans" }) -public class SecurezoneNotificationStage extends MosipVerticleAPIManager { - - private static final String STAGE_PROPERTY_PREFIX = "mosip.regproc.securezone.notification."; - - /** - * The reg proc logger. - */ - private static Logger regProcLogger = RegProcessorLogger.getLogger(SecurezoneNotificationStage.class); - - /** - * The cluster url. - */ - @Value("${vertx.cluster.configuration}") - private String clusterManagerUrl; - - /** - * worker pool size. - */ - @Value("${worker.pool.size}") - private Integer workerPoolSize; - - /** - * The mosip event bus. - */ - private MosipEventBus mosipEventBus; - - @Value("${securezone.routing.enabled:true}") - private boolean routingEnabled; - - /** - * After this time intervel, message should be considered as expired (In - * seconds). - */ - @Value("${mosip.regproc.securezone.notification.message.expiry-time-limit}") - private Long messageExpiryTimeLimit; - - @Value("#{T(java.util.Arrays).asList('${registration.processor.main-processes:}')}") - private List mainProcesses; - - /** The Constant USER. */ - private static final String USER = "MOSIP_SYSTEM"; - - /** - * Mosip router for APIs - */ - @Autowired - private MosipRouter router; - - /** The registration status service. */ - @Autowired - private RegistrationStatusService registrationStatusService; - - @Autowired - private SyncRegistrationService syncRegistrationService; - - /** The core audit request builder. */ - @Autowired - private AuditLogRequestBuilder auditLogRequestBuilder; - - @Autowired - private RegistrationExceptionMapperUtil registrationStatusMapperUtil; - - /** - * Deploy verticle. - */ - public void deployVerticle() { - this.mosipEventBus = this.getEventBus(this, clusterManagerUrl, workerPoolSize); - this.consumeAndSend(mosipEventBus, MessageBusAddress.SECUREZONE_NOTIFICATION_IN, - MessageBusAddress.SECUREZONE_NOTIFICATION_OUT, messageExpiryTimeLimit); - } - - @Override - protected String getPropertyPrefix() { - return STAGE_PROPERTY_PREFIX; - } - - @Override - public void start() { - router.setRoute(this.postUrl(vertx, MessageBusAddress.SECUREZONE_NOTIFICATION_IN, - MessageBusAddress.SECUREZONE_NOTIFICATION_OUT)); - this.routes(router); - this.createServer(router.getRouter(), getPort()); - } - - /** - * contains all the routes in this stage - * - * @param router - */ - private void routes(MosipRouter router) { - router.post(getServletPath() + "/notification"); - router.handler(this::processURL, this::failure); - } - - /** - * method to process the context received. - * - * @param ctx the ctx - */ - public void processURL(RoutingContext ctx) { - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), "", - "SecurezoneNotificationStage::processURL()::entry"); - - InternalRegistrationStatusDto registrationStatusDto = new InternalRegistrationStatusDto(); - MessageDTO messageDTO = new MessageDTO(); - TrimExceptionMessage trimMessage = new TrimExceptionMessage(); - LogDescription description = new LogDescription(); - boolean isTransactionSuccessful = false; - - try { - JsonObject obj = ctx.getBodyAsJson(); - - messageDTO.setMessageBusAddress(MessageBusAddress.SECUREZONE_NOTIFICATION_IN); - messageDTO.setInternalError(Boolean.FALSE); - messageDTO.setRid(obj.getString("rid")); - messageDTO.setReg_type(obj.getString("reg_type")); - messageDTO.setIsValid(obj.getBoolean("isValid")); - messageDTO.setSource(obj.getString("source")); - messageDTO.setIteration(obj.getInteger("iteration")); - messageDTO.setWorkflowInstanceId(obj.getString("workflowInstanceId")); - - registrationStatusDto = registrationStatusService.getRegistrationStatus(messageDTO.getRid(), - messageDTO.getReg_type(), messageDTO.getIteration(), messageDTO.getWorkflowInstanceId()); - - boolean isDuplicatePacket = false; - if (registrationStatusDto != null) { - registrationStatusDto.setLatestTransactionTypeCode( - RegistrationTransactionTypeCode.SECUREZONE_NOTIFICATION.toString()); - registrationStatusDto.setRegistrationStageName(getStageName()); - isDuplicatePacket = isDuplicatePacketForSameReqId(messageDTO); - } else { - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), - LoggerFileConstant.REGISTRATIONID.toString(), messageDTO.getRid(), - "No records found in registration table for reg id - " + messageDTO.getRid()); - } - - if (!isDuplicatePacket && registrationStatusDto != null - && messageDTO.getRid().equalsIgnoreCase(registrationStatusDto.getRegistrationId())) { - registrationStatusDto - .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.SUCCESS.toString()); - messageDTO.setIsValid(Boolean.TRUE); - registrationStatusDto.setStatusComment(StatusUtil.NOTIFICATION_RECEIVED_TO_SECUREZONE.getMessage()); - registrationStatusDto.setSubStatusCode(StatusUtil.NOTIFICATION_RECEIVED_TO_SECUREZONE.getCode()); - registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); - - isTransactionSuccessful = true; - description.setMessage(PlatformSuccessMessages.RPR_SEZ_SECUREZONE_NOTIFICATION.getMessage() + " -- " - + messageDTO.getRid()); - description.setCode(PlatformSuccessMessages.RPR_SEZ_SECUREZONE_NOTIFICATION.getCode()); - - regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), - LoggerFileConstant.REGISTRATIONID.toString(), messageDTO.getRid(), - description.getCode() + description.getMessage()); - } else if (isDuplicatePacket) { - isTransactionSuccessful = false; - messageDTO.setIsValid(Boolean.FALSE); - registrationStatusDto.setSubStatusCode(StatusUtil.NOTIFICATION_RECEIVED_TO_SECUREZONE.getCode()); - description.setMessage(PlatformErrorMessages.RPR_SECUREZONE_DUPLICATE_PACKET.getMessage()); - description.setCode(PlatformErrorMessages.RPR_SECUREZONE_DUPLICATE_PACKET.getCode()); - registrationStatusDto - .setStatusComment(PlatformErrorMessages.RPR_SECUREZONE_DUPLICATE_PACKET.getMessage()); - registrationStatusDto.setStatusCode(RegistrationStatusCode.REJECTED.name()); - registrationStatusDto.setLatestTransactionStatusCode(RegistrationStatusCode.REJECTED.name()); - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), - LoggerFileConstant.REGISTRATIONID.toString(), messageDTO.getRid(), - PlatformErrorMessages.RPR_SECUREZONE_DUPLICATE_PACKET.getMessage()); - } else { - isTransactionSuccessful = false; - messageDTO.setIsValid(Boolean.FALSE); - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), - LoggerFileConstant.REGISTRATIONID.toString(), messageDTO.getRid(), - "Transaction failed. RID not found in registration table."); - } - - if (messageDTO.getIsValid()) { - sendMessage(messageDTO); - this.setResponse(ctx, - "Packet with registrationId '" + messageDTO.getRid() + "' has been forwarded to next stage"); - - regProcLogger.info(obj.getString("rid"), - "Packet with registrationId '" + messageDTO.getRid() + "' has been forwarded to next stage", - null, null); - } else { - this.setResponse(ctx, "Packet with registrationId '" + obj.getString("rid") - + "' has not been uploaded to file System"); - - regProcLogger.info(obj.getString("rid"), - "Packet with registrationId '" + messageDTO.getRid() + "' has not been uploaded to file System", - null, null); - } - } 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.DATA_ACCESS_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(), LoggerFileConstant.REGISTRATIONID.toString(), - description.getCode() + " -- " + messageDTO.getRid(), - PlatformErrorMessages.RPR_RGS_REGISTRATION_TABLE_NOT_ACCESSIBLE.getMessage() + e.getMessage() - + ExceptionUtils.getStackTrace(e)); - messageDTO.setInternalError(Boolean.TRUE); - messageDTO.setRid(registrationStatusDto.getRegistrationId()); - ctx.fail(e); - } catch (Exception e) { - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), - ctx.getBodyAsString(), ExceptionUtils.getStackTrace(e)); - messageDTO.setIsValid(Boolean.FALSE); - description.setCode(PlatformErrorMessages.RPR_SECUREZONE_FAILURE.getCode()); - description.setMessage(PlatformErrorMessages.RPR_SECUREZONE_FAILURE.getMessage()); - ctx.fail(e); - } finally { - if (messageDTO.getInternalError()) { - registrationStatusDto.setUpdatedBy(USER); - int retryCount = registrationStatusDto.getRetryCount() != null - ? registrationStatusDto.getRetryCount() + 1 - : 1; - registrationStatusDto.setRetryCount(retryCount); - updateErrorFlags(registrationStatusDto, messageDTO); - } - /** Module-Id can be Both Success/Error code */ - String moduleId = isTransactionSuccessful - ? PlatformSuccessMessages.RPR_SEZ_SECUREZONE_NOTIFICATION.getCode() - : description.getCode(); - String moduleName = ModuleName.SECUREZONE_NOTIFICATION.toString(); - registrationStatusService.updateRegistrationStatus(registrationStatusDto, moduleId, moduleName); - if (isTransactionSuccessful) - description.setMessage(PlatformSuccessMessages.RPR_SEZ_SECUREZONE_NOTIFICATION.getMessage()); - String eventId = isTransactionSuccessful ? EventId.RPR_401.toString() : EventId.RPR_405.toString(); - String eventName = isTransactionSuccessful ? EventName.GET.toString() : EventName.EXCEPTION.toString(); - String eventType = isTransactionSuccessful ? EventType.BUSINESS.toString() : EventType.SYSTEM.toString(); - - auditLogRequestBuilder.createAuditRequestBuilder(description.getMessage(), eventId, eventName, eventType, - moduleId, moduleName, messageDTO.getRid()); - } - } - - /** - * This is for failure handler - * - * @param routingContext - */ - private void failure(RoutingContext routingContext) { - this.setResponse(routingContext, routingContext.failure().getMessage()); - } - - /** - * sends messageDTO to camel bridge. - * - * @param messageDTO the message DTO - */ - public void sendMessage(MessageDTO messageDTO) { - if (routingEnabled) - this.send(this.mosipEventBus, MessageBusAddress.SECUREZONE_NOTIFICATION_OUT, messageDTO); - } - - @Override - public MessageDTO process(MessageDTO object) { - return null; - } - - private boolean isDuplicatePacketForSameReqId(MessageDTO messageDTO) { - boolean isDuplicate = false; - SyncRegistrationEntity entity = syncRegistrationService - .findByWorkflowInstanceId(messageDTO.getWorkflowInstanceId()); - - if (entity.getAdditionalInfoReqId() == null && mainProcesses.contains(entity.getRegistrationType())) { - // find all main process records for same registrationId. - List entities = syncRegistrationService - .findByRegistrationId(entity.getRegistrationId()); - List mainProcessEntities = entities.stream() - .filter(e -> e.getAdditionalInfoReqId() == null).collect(Collectors.toList()); - isDuplicate = checkDuplicates(messageDTO, mainProcessEntities); - } else { - // find all records for same additionalInfoReqId. - List entities = syncRegistrationService - .findByAdditionalInfoReqId(entity.getAdditionalInfoReqId()); - // if multiple records are present for same additionalInfoReqId then check in - // registration table how many packets are received - isDuplicate = checkDuplicates(messageDTO, entities); - } - return isDuplicate; - } - - private boolean checkDuplicates(MessageDTO messageDTO, List entities) { - if (!CollectionUtils.isEmpty(entities) && entities.size() > 1) { - List workflowInstanceIds = entities.stream().map(e -> e.getWorkflowInstanceId()) - .collect(Collectors.toList()); - List dtos = new ArrayList<>(); - for (String workflowInstanceId : workflowInstanceIds) { - InternalRegistrationStatusDto dto = registrationStatusService.getRegistrationStatus(messageDTO.getRid(), - messageDTO.getReg_type(), messageDTO.getIteration(), workflowInstanceId); - if (dto != null) - dtos.add(dto); - } - Optional currentPacketOptional = dtos.stream() - .filter(d -> d.getWorkflowInstanceId() != null - && d.getWorkflowInstanceId().equalsIgnoreCase(messageDTO.getWorkflowInstanceId())) - .findAny(); - if (currentPacketOptional.isPresent()) { - InternalRegistrationStatusDto currentPacket = currentPacketOptional.get(); - // remove current packet from list so that it contains only other packets - // received for same additionalInfoReqId - dtos.remove(currentPacket); - for (InternalRegistrationStatusDto otherPacket : dtos) { - if (otherPacket.getCreateDateTime().isBefore(currentPacket.getCreateDateTime())) { - messageDTO.setIsValid(Boolean.FALSE); - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), - LoggerFileConstant.REGISTRATIONID.toString(), messageDTO.getRid(), - "Packet already received for same registrationId."); - return true; - } - } - } - } - return false; - } - - private void updateErrorFlags(InternalRegistrationStatusDto registrationStatusDto, MessageDTO object) { - object.setInternalError(true); - if (registrationStatusDto.getLatestTransactionStatusCode() - .equalsIgnoreCase(RegistrationTransactionStatusCode.REPROCESS.toString())) { - object.setIsValid(true); - } else { - object.setIsValid(false); - } - } -} +package io.mosip.registration.processor.securezone.notification.stage; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; + +import org.apache.commons.collections.CollectionUtils; +import org.apache.commons.lang3.exception.ExceptionUtils; +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.Component; + +import io.mosip.kernel.core.logger.spi.Logger; +import io.mosip.registration.processor.core.abstractverticle.MessageBusAddress; +import io.mosip.registration.processor.core.abstractverticle.MessageDTO; +import io.mosip.registration.processor.core.abstractverticle.MosipEventBus; +import io.mosip.registration.processor.core.abstractverticle.MosipRouter; +import io.mosip.registration.processor.core.abstractverticle.MosipVerticleAPIManager; +import io.mosip.registration.processor.core.code.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.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.status.util.StatusUtil; +import io.mosip.registration.processor.core.status.util.TrimExceptionMessage; +import io.mosip.registration.processor.core.util.RegistrationExceptionMapperUtil; +import io.mosip.registration.processor.rest.client.audit.builder.AuditLogRequestBuilder; +import io.mosip.registration.processor.status.code.RegistrationStatusCode; +import io.mosip.registration.processor.status.dto.InternalRegistrationStatusDto; +import io.mosip.registration.processor.status.dto.RegistrationStatusDto; +import io.mosip.registration.processor.status.dto.SyncRegistrationDto; +import io.mosip.registration.processor.status.dto.SyncResponseDto; +import io.mosip.registration.processor.status.entity.SyncRegistrationEntity; +import io.mosip.registration.processor.status.exception.TablenotAccessibleException; +import io.mosip.registration.processor.status.service.RegistrationStatusService; +import io.mosip.registration.processor.status.service.SyncRegistrationService; +import io.vertx.core.json.JsonObject; +import io.vertx.ext.web.RoutingContext; + +@Component +@Configuration +@ComponentScan(basePackages = { "${mosip.auth.adapter.impl.basepackage}", + "io.mosip.registration.processor.core.config", + "io.mosip.registration.processor.securezone.notification.config", + "io.mosip.registration.processor.packet.manager.config", "io.mosip.registration.processor.status.config", + "io.mosip.registration.processor.rest.client.config", "io.mosip.registration.processor.core.kernel.beans" }) +public class SecurezoneNotificationStage extends MosipVerticleAPIManager { + + private static final String STAGE_PROPERTY_PREFIX = "mosip.regproc.securezone.notification."; + + /** + * The reg proc logger. + */ + private static final Logger regProcLogger = RegProcessorLogger.getLogger(SecurezoneNotificationStage.class); + + /** + * The cluster url. + */ + @Value("${vertx.cluster.configuration}") + private String clusterManagerUrl; + + /** + * worker pool size. + */ + @Value("${worker.pool.size}") + private Integer workerPoolSize; + + /** + * The mosip event bus. + */ + private MosipEventBus mosipEventBus; + + @Value("${securezone.routing.enabled:true}") + private boolean routingEnabled; + + /** + * After this time intervel, message should be considered as expired (In + * seconds). + */ + @Value("${mosip.regproc.securezone.notification.message.expiry-time-limit}") + private Long messageExpiryTimeLimit; + + @Value("#{T(java.util.Arrays).asList('${registration.processor.main-processes:}')}") + private List mainProcesses; + + /** The Constant USER. */ + private static final String USER = "MOSIP_SYSTEM"; + + /** + * Mosip router for APIs + */ + @Autowired + private MosipRouter router; + + /** The registration status service. */ + @Autowired + private RegistrationStatusService registrationStatusService; + + @Autowired + private SyncRegistrationService syncRegistrationService; + + /** The core audit request builder. */ + @Autowired + private AuditLogRequestBuilder auditLogRequestBuilder; + + @Autowired + private RegistrationExceptionMapperUtil registrationStatusMapperUtil; + + /** + * Deploy verticle. + */ + public void deployVerticle() { + this.mosipEventBus = this.getEventBus(this, clusterManagerUrl, workerPoolSize); + this.consumeAndSend(mosipEventBus, MessageBusAddress.SECUREZONE_NOTIFICATION_IN, + MessageBusAddress.SECUREZONE_NOTIFICATION_OUT, messageExpiryTimeLimit); + } + + @Override + protected String getPropertyPrefix() { + return STAGE_PROPERTY_PREFIX; + } + + @Override + public void start() { + router.setRoute(this.postUrl(vertx, MessageBusAddress.SECUREZONE_NOTIFICATION_IN, + MessageBusAddress.SECUREZONE_NOTIFICATION_OUT)); + this.routes(router); + this.createServer(router.getRouter(), getPort()); + } + + /** + * contains all the routes in this stage + * + * @param router + */ + private void routes(MosipRouter router) { + router.post(getServletPath() + "/notification"); + router.handler(this::processURL, this::failure); + } + + /** + * method to process the context received. + * + * @param ctx the ctx + */ + public void processURL(RoutingContext ctx) { + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), "", + "SecurezoneNotificationStage::processURL()::entry"); + + MessageDTO messageDTO = new MessageDTO(); + try { + JsonObject obj = ctx.getBodyAsJson(); + messageDTO.setMessageBusAddress(MessageBusAddress.SECUREZONE_NOTIFICATION_IN); + messageDTO.setInternalError(Boolean.FALSE); + messageDTO.setRid(obj.getString("rid")); + messageDTO.setReg_type(obj.getString("reg_type")); + messageDTO.setIsValid(obj.getBoolean("isValid")); + messageDTO.setSource(obj.getString("source")); + messageDTO.setIteration(obj.getInteger("iteration")); + messageDTO.setWorkflowInstanceId(obj.getString("workflowInstanceId")); + MessageDTO result = process(messageDTO); + if (result.getIsValid()) { + sendMessage(result); + this.setResponse(ctx, + "Packet with registrationId '" + result.getRid() + "' has been forwarded to next stage"); + + regProcLogger.info(obj.getString("rid"), + "Packet with registrationId '" + result.getRid() + "' has been forwarded to next stage", + null, null); + } else { + this.setResponse(ctx, "Packet with registrationId '" + obj.getString("rid") + + "' has not been uploaded to file System"); + + regProcLogger.info(obj.getString("rid"), + "Packet with registrationId '" + result.getRid() + "' has not been uploaded to file System", + null, null); + } + } catch (Exception e) { + ctx.fail(e); + } + } + + /** + * This is for failure handler + * + * @param routingContext + */ + private void failure(RoutingContext routingContext) { + this.setResponse(routingContext, routingContext.failure().getMessage()); + } + + /** + * sends messageDTO to camel bridge. + * + * @param messageDTO the message DTO + */ + public void sendMessage(MessageDTO messageDTO) { + if (routingEnabled) + this.send(this.mosipEventBus, MessageBusAddress.SECUREZONE_NOTIFICATION_OUT, messageDTO); + } + + @Override + public MessageDTO process(MessageDTO messageDTO) { + InternalRegistrationStatusDto registrationStatusDto = new InternalRegistrationStatusDto(); + TrimExceptionMessage trimMessage = new TrimExceptionMessage(); + LogDescription description = new LogDescription(); + boolean isTransactionSuccessful = false; + try { + registrationStatusDto = registrationStatusService.getRegistrationStatus(messageDTO.getRid(), + messageDTO.getReg_type(), messageDTO.getIteration(), messageDTO.getWorkflowInstanceId()); + + boolean isDuplicatePacket = false; + if (registrationStatusDto != null) { + registrationStatusDto.setLatestTransactionTypeCode( + RegistrationTransactionTypeCode.SECUREZONE_NOTIFICATION.toString()); + registrationStatusDto.setRegistrationStageName(getStageName()); + isDuplicatePacket = isDuplicatePacketForSameReqId(messageDTO); + } else { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString(), messageDTO.getRid(), + "No records found in registration table for reg id - " + messageDTO.getRid()); + } + + if (!isDuplicatePacket && registrationStatusDto != null + && messageDTO.getRid().equalsIgnoreCase(registrationStatusDto.getRegistrationId())) { + registrationStatusDto + .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.SUCCESS.toString()); + messageDTO.setIsValid(Boolean.TRUE); + registrationStatusDto.setStatusComment(StatusUtil.NOTIFICATION_RECEIVED_TO_SECUREZONE.getMessage()); + registrationStatusDto.setSubStatusCode(StatusUtil.NOTIFICATION_RECEIVED_TO_SECUREZONE.getCode()); + registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); + + isTransactionSuccessful = true; + description.setMessage(PlatformSuccessMessages.RPR_SEZ_SECUREZONE_NOTIFICATION.getMessage() + " -- " + + messageDTO.getRid()); + description.setCode(PlatformSuccessMessages.RPR_SEZ_SECUREZONE_NOTIFICATION.getCode()); + + regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString(), messageDTO.getRid(), + description.getCode() + description.getMessage()); + } else if (isDuplicatePacket) { + isTransactionSuccessful = false; + messageDTO.setIsValid(Boolean.FALSE); + registrationStatusDto.setSubStatusCode(StatusUtil.NOTIFICATION_RECEIVED_TO_SECUREZONE.getCode()); + description.setMessage(PlatformErrorMessages.RPR_SECUREZONE_DUPLICATE_PACKET.getMessage()); + description.setCode(PlatformErrorMessages.RPR_SECUREZONE_DUPLICATE_PACKET.getCode()); + registrationStatusDto + .setStatusComment(PlatformErrorMessages.RPR_SECUREZONE_DUPLICATE_PACKET.getMessage()); + registrationStatusDto.setStatusCode(RegistrationStatusCode.REJECTED.name()); + registrationStatusDto.setLatestTransactionStatusCode(RegistrationStatusCode.REJECTED.name()); + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString(), messageDTO.getRid(), + PlatformErrorMessages.RPR_SECUREZONE_DUPLICATE_PACKET.getMessage()); + } else { + isTransactionSuccessful = false; + messageDTO.setIsValid(Boolean.FALSE); + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString(), messageDTO.getRid(), + "Transaction failed. RID not found in registration table."); + } + } 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.DATA_ACCESS_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(), LoggerFileConstant.REGISTRATIONID.toString(), + description.getCode() + " -- " + messageDTO.getRid(), + PlatformErrorMessages.RPR_RGS_REGISTRATION_TABLE_NOT_ACCESSIBLE.getMessage() + e.getMessage() + + ExceptionUtils.getStackTrace(e)); + messageDTO.setInternalError(Boolean.TRUE); + messageDTO.setRid(registrationStatusDto.getRegistrationId()); + } catch (Exception e) { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), + messageDTO.toString(), ExceptionUtils.getStackTrace(e)); + messageDTO.setIsValid(Boolean.FALSE); + description.setCode(PlatformErrorMessages.RPR_SECUREZONE_FAILURE.getCode()); + description.setMessage(PlatformErrorMessages.RPR_SECUREZONE_FAILURE.getMessage()); + } finally { + if (messageDTO.getInternalError() != null && messageDTO.getInternalError()) { + registrationStatusDto.setUpdatedBy(USER); + int retryCount = registrationStatusDto.getRetryCount() != null + ? registrationStatusDto.getRetryCount() + 1 + : 1; + registrationStatusDto.setRetryCount(retryCount); + updateErrorFlags(registrationStatusDto, messageDTO); + } + /** Module-Id can be Both Success/Error code */ + String moduleId = isTransactionSuccessful + ? PlatformSuccessMessages.RPR_SEZ_SECUREZONE_NOTIFICATION.getCode() + : description.getCode(); + String moduleName = ModuleName.SECUREZONE_NOTIFICATION.toString(); + registrationStatusService.updateRegistrationStatus(registrationStatusDto, moduleId, moduleName); + if (isTransactionSuccessful) + description.setMessage(PlatformSuccessMessages.RPR_SEZ_SECUREZONE_NOTIFICATION.getMessage()); + String eventId = isTransactionSuccessful ? EventId.RPR_401.toString() : EventId.RPR_405.toString(); + String eventName = isTransactionSuccessful ? EventName.GET.toString() : EventName.EXCEPTION.toString(); + String eventType = isTransactionSuccessful ? EventType.BUSINESS.toString() : EventType.SYSTEM.toString(); + + auditLogRequestBuilder.createAuditRequestBuilder(description.getMessage(), eventId, eventName, eventType, + moduleId, moduleName, messageDTO.getRid()); + } + return messageDTO; + } + + private boolean isDuplicatePacketForSameReqId(MessageDTO messageDTO) { + boolean isDuplicate = false; + SyncRegistrationEntity entity = syncRegistrationService + .findByWorkflowInstanceId(messageDTO.getWorkflowInstanceId()); + + if (entity.getAdditionalInfoReqId() == null && mainProcesses.contains(entity.getRegistrationType())) { + // find all main process records for same registrationId. + List entities = syncRegistrationService + .findByRegistrationId(entity.getRegistrationId()); + List mainProcessEntities = entities.stream() + .filter(e -> e.getAdditionalInfoReqId() == null).collect(Collectors.toList()); + isDuplicate = checkDuplicates(messageDTO, mainProcessEntities); + } else { + // find all records for same additionalInfoReqId. + List entities = syncRegistrationService + .findByAdditionalInfoReqId(entity.getAdditionalInfoReqId()); + // if multiple records are present for same additionalInfoReqId then check in + // registration table how many packets are received + isDuplicate = checkDuplicates(messageDTO, entities); + } + return isDuplicate; + } + + private boolean checkDuplicates(MessageDTO messageDTO, List entities) { + if (!CollectionUtils.isEmpty(entities) && entities.size() > 1) { + List workflowInstanceIds = entities.stream().map(e -> e.getWorkflowInstanceId()) + .collect(Collectors.toList()); + List dtos = new ArrayList<>(); + for (String workflowInstanceId : workflowInstanceIds) { + InternalRegistrationStatusDto dto = registrationStatusService.getRegistrationStatus(messageDTO.getRid(), + messageDTO.getReg_type(), messageDTO.getIteration(), workflowInstanceId); + if (dto != null) + dtos.add(dto); + } + Optional currentPacketOptional = dtos.stream() + .filter(d -> d.getWorkflowInstanceId() != null + && d.getWorkflowInstanceId().equalsIgnoreCase(messageDTO.getWorkflowInstanceId())) + .findAny(); + if (currentPacketOptional.isPresent()) { + InternalRegistrationStatusDto currentPacket = currentPacketOptional.get(); + // remove current packet from list so that it contains only other packets + // received for same additionalInfoReqId + dtos.remove(currentPacket); + for (InternalRegistrationStatusDto otherPacket : dtos) { + if (otherPacket.getCreateDateTime().isBefore(currentPacket.getCreateDateTime())) { + messageDTO.setIsValid(Boolean.FALSE); + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString(), messageDTO.getRid(), + "Packet already received for same registrationId."); + return true; + } + } + } + } + return false; + } + + private void updateErrorFlags(InternalRegistrationStatusDto registrationStatusDto, MessageDTO object) { + object.setInternalError(true); + if (registrationStatusDto.getLatestTransactionStatusCode() + .equalsIgnoreCase(RegistrationTransactionStatusCode.REPROCESS.toString())) { + object.setIsValid(true); + } else { + object.setIsValid(false); + } + } +} diff --git a/registration-processor/pre-processor/registration-processor-securezone-notification-stage/src/test/java/io/mosip/registration/processor/securezone/notification/stage/SecurezoneNotificationStageTest.java b/registration-processor/pre-processor/registration-processor-securezone-notification-stage/src/test/java/io/mosip/registration/processor/securezone/notification/stage/SecurezoneNotificationStageTest.java index 78b981ec418..49506d43b7c 100644 --- a/registration-processor/pre-processor/registration-processor-securezone-notification-stage/src/test/java/io/mosip/registration/processor/securezone/notification/stage/SecurezoneNotificationStageTest.java +++ b/registration-processor/pre-processor/registration-processor-securezone-notification-stage/src/test/java/io/mosip/registration/processor/securezone/notification/stage/SecurezoneNotificationStageTest.java @@ -1,520 +1,538 @@ -package io.mosip.registration.processor.securezone.notification.stage; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyString; - -import java.io.InputStream; -import java.time.LocalDateTime; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.util.ReflectionTestUtils; - -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.RegistrationExceptionTypeCode; -import io.mosip.registration.processor.core.http.ResponseWrapper; -import io.mosip.registration.processor.core.util.RegistrationExceptionMapperUtil; -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.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; -import io.vertx.core.AsyncResult; -import io.vertx.core.Handler; -import io.vertx.core.MultiMap; -import io.vertx.core.Vertx; -import io.vertx.core.buffer.Buffer; -import io.vertx.core.http.HttpMethod; -import io.vertx.core.http.HttpServerRequest; -import io.vertx.core.http.HttpServerResponse; -import io.vertx.core.json.JsonArray; -import io.vertx.core.json.JsonObject; -import io.vertx.ext.auth.User; -import io.vertx.ext.web.Cookie; -import io.vertx.ext.web.FileUpload; -import io.vertx.ext.web.Locale; -import io.vertx.ext.web.ParsedHeaderValues; -import io.vertx.ext.web.Route; -import io.vertx.ext.web.Router; -import io.vertx.ext.web.RoutingContext; -import io.vertx.ext.web.Session; - -@RunWith(SpringRunner.class) -public class SecurezoneNotificationStageTest { - - private static final int maxRetryCount = 5; - - private static final InputStream stream = Mockito.mock(InputStream.class); - - /** The registration status service. */ - @Mock - RegistrationStatusService registrationStatusService; - - @Mock - private SyncRegistrationService syncRegistrationService; - - @Mock - private RegistrationExceptionMapperUtil registrationStatusMapperUtil; - - @Mock - private AuditLogRequestBuilder auditLogRequestBuilder; - - private RoutingContext ctx; - private Boolean responseObject; - - @Mock - private MosipRouter router; - - @InjectMocks - SecurezoneNotificationStage notificationStage = new SecurezoneNotificationStage() { - - @Override - public void setResponse(RoutingContext ctx, Object object) { - responseObject = Boolean.TRUE; - } - - @Override - public void send(MosipEventBus mosipEventBus, MessageBusAddress toAddress, MessageDTO message) { - } - - @Override - public MosipEventBus getEventBus(Object verticleName, String url, int instanceNumber) { - return null; - } - - @Override - public void createServer(Router route, int port) - { - - } - @Override - public Router postUrl(Vertx vertx, MessageBusAddress consumeAddress, MessageBusAddress sendAddress) { - return null; - } - }; - - private RoutingContext setContext() { - return new RoutingContext() { - - @Override - public Set fileUploads() { - return null; - } - - @Override - public Vertx vertx() { - return null; - } - - @Override - public User user() { - return null; - } - - @Override - public int statusCode() { - return 0; - } - - @Override - public void setUser(User user) { - } - - @Override - public void setSession(Session session) { - } - - @Override - public void setBody(Buffer body) { - } - - @Override - public void setAcceptableContentType(String contentType) { - } - - @Override - public Session session() { - return null; - } - - @Override - public HttpServerResponse response() { - return null; - } - - @Override - public void reroute(HttpMethod method, String path) { - } - - @Override - public HttpServerRequest request() { - return null; - } - - @Override - public boolean removeHeadersEndHandler(int handlerID) { - return false; - } - - @Override - public Cookie removeCookie(String name, boolean invalidate) { - return null; - } - - @Override - public boolean removeBodyEndHandler(int handlerID) { - return false; - } - - @Override - public T remove(String key) { - return null; - } - - @Override - public MultiMap queryParams() { - return null; - } - - @Override - public List queryParam(String query) { - return null; - } - - @Override - public RoutingContext put(String key, Object obj) { - return null; - } - - @Override - public Map pathParams() { - return null; - } - - @Override - public String pathParam(String name) { - return null; - } - - @Override - public ParsedHeaderValues parsedHeaders() { - return null; - } - - @Override - public String normalisedPath() { - return null; - } - - @Override - public void next() { - } - - @Override - public String mountPoint() { - return null; - } - - @Override - public Cookie getCookie(String name) { - return null; - } - - @Override - public String getBodyAsString(String encoding) { - return null; - } - - @Override - public String getBodyAsString() { - return null; - } - - @Override - public JsonArray getBodyAsJsonArray() { - return null; - } - - @Override - public JsonObject getBodyAsJson() { - JsonObject obj = new JsonObject(); - obj.put("rid", "2018701130000410092018110735"); - obj.put("isValid", true); - obj.put("internalError", false); - obj.put("reg_type", "NEW"); - obj.put("source", "REGISTRATIONCLIENT"); - obj.put("iteration", 1); - obj.put("workflowInstanceId", "78fc3d34-03f5-11ec-9a03-0242ac130003"); - return obj; - } - - @Override - public Buffer getBody() { - return null; - } - - @Override - public String getAcceptableContentType() { - return null; - } - - @Override - public T get(String key) { - return null; - } - - @Override - public Throwable failure() { - return null; - } - - @Override - public boolean failed() { - return false; - } - - @Override - public void fail(Throwable throwable) { - } - - @Override - public void fail(int statusCode) { - } - - @Override - public Map data() { - return null; - } - - @Override - public Route currentRoute() { - return null; - } - - @Override - public Set cookies() { - return null; - } - - @Override - public int cookieCount() { - return 0; - } - - @Override - public void clearUser() { - } - - @Override - public int addHeadersEndHandler(Handler handler) { - return 0; - } - - @Override - public RoutingContext addCookie(Cookie cookie) { - return null; - } - - @Override - public int addBodyEndHandler(Handler handler) { - return 0; - } - - @Override - public List acceptableLocales() { - return null; - } - - @Override - public RoutingContext addCookie(io.vertx.core.http.Cookie arg0) { - return null; - } - - @Override - public int addEndHandler(Handler> arg0) { - return 0; - } - - @Override - public Map cookieMap() { - return null; - } - - @Override - public void fail(int arg0, Throwable arg1) { - - } - - @Override - public boolean isSessionAccessed() { - return false; - } - - @Override - public boolean removeEndHandler(int arg0) { - return false; - } - - - }; - } - - InternalRegistrationStatusDto registrationStatusDto = new InternalRegistrationStatusDto(); - InternalRegistrationStatusDto registrationStatusDto1 = new InternalRegistrationStatusDto(); - List entities = new ArrayList(); - SyncRegistrationEntity entity = new SyncRegistrationEntity(); - SyncRegistrationEntity entity1 = new SyncRegistrationEntity(); - - @Before - public void setup() { - - registrationStatusDto = new InternalRegistrationStatusDto(); - registrationStatusDto.setRegistrationId("2018701130000410092018110735"); - registrationStatusDto.setStatusCode("SECUREZONE_NOTIFICATION_SUCCESS"); - registrationStatusDto.setWorkflowInstanceId("78fc3d34-03f5-11ec-9a03-0242ac130004"); - registrationStatusDto.setCreateDateTime(LocalDateTime.now().minusDays(1)); - - registrationStatusDto1 = new InternalRegistrationStatusDto(); - registrationStatusDto1.setRegistrationId("2018701130000410092018110735"); - registrationStatusDto1.setStatusCode("SECUREZONE_NOTIFICATION_SUCCESS"); - registrationStatusDto1.setWorkflowInstanceId("78fc3d34-03f5-11ec-9a03-0242ac130003"); - registrationStatusDto1.setCreateDateTime(LocalDateTime.now()); - - ResponseWrapper responseWrapper = new ResponseWrapper(); - AuditResponseDto auditResponseDto = new AuditResponseDto(); - responseWrapper.setResponse(auditResponseDto); - - entity.setAdditionalInfoReqId("abc"); - entity.setPacketId("2018701130000410092018110735"); - entity.setWorkflowInstanceId("78fc3d34-03f5-11ec-9a03-0242ac130003"); - - entity1.setAdditionalInfoReqId(null); - entity1.setPacketId("2018701130000410092018110735"); - entity1.setWorkflowInstanceId("78fc3d34-03f5-11ec-9a03-0242ac130003"); - - ctx = setContext(); - ReflectionTestUtils.setField(notificationStage, "workerPoolSize", 10); - ReflectionTestUtils.setField(notificationStage, "clusterManagerUrl", "/dummyPath"); - ReflectionTestUtils.setField(notificationStage, "messageExpiryTimeLimit", Long.valueOf(0)); - ReflectionTestUtils.setField(notificationStage, "mainProcesses", Arrays.asList("NEW","UPDATE","LOST")); - //ReflectionTestUtils.setField(notificationStage, "port", "7999"); - Mockito.when(router.post(Mockito.any())).thenReturn(null); - Mockito.doNothing().when(router).setRoute(Mockito.any()); - Mockito.doNothing().when(router).nonSecureHandler(Mockito.any(),Mockito.any()); - MessageDTO messageDTO= new MessageDTO(); - messageDTO.setInternalError(Boolean.FALSE); - messageDTO.setIsValid(Boolean.TRUE); - messageDTO.setRid("2018701130000410092018110735"); - Mockito.doNothing().when(registrationStatusService).updateRegistrationStatus(any(),any(),any()); - Mockito.doReturn(responseWrapper).when(auditLogRequestBuilder).createAuditRequestBuilder(anyString(), anyString(), anyString(), - anyString(), anyString(), anyString(), anyString()); - Mockito.when(registrationStatusMapperUtil.getStatusCode(any())).thenReturn("Something"); - } - - @Test - public void processURLTest() { - entities.add(entity); - Mockito.when(syncRegistrationService.findByWorkflowInstanceId(anyString())).thenReturn(entity); - Mockito.when(syncRegistrationService.findByAdditionalInfoReqId(anyString())).thenReturn(entities); - Mockito.when(registrationStatusService.getRegistrationStatus(anyString(), any(), any(), any())) - .thenReturn(registrationStatusDto); - notificationStage.processURL(ctx); - assertTrue(responseObject); - } - - @Test - public void ridNotFoundTest() { - Mockito.when(registrationStatusService.getRegistrationStatus(anyString(), any(), any(), any())).thenReturn(null); - - notificationStage.processURL(ctx); - assertTrue(responseObject); - } - - @Test - public void duplicateRidFoundTest() { - - SyncRegistrationEntity syncEntity = new SyncRegistrationEntity(); - syncEntity.setAdditionalInfoReqId(null); - syncEntity.setRegistrationType("NEW"); - syncEntity.setPacketId("2018701130000410092018110735"); - syncEntity.setWorkflowInstanceId("78fc3d34-03f5-11ec-9a03-0242ac130004"); - entities.add(syncEntity); - entities.add(entity1); - - Mockito.when(registrationStatusService.getRegistrationStatus(anyString(), any(), any(), any())) - .thenReturn(registrationStatusDto).thenReturn(registrationStatusDto).thenReturn(registrationStatusDto1); - Mockito.when(syncRegistrationService.findByWorkflowInstanceId(anyString())).thenReturn(syncEntity); - Mockito.when(syncRegistrationService.findByRegistrationId(any())).thenReturn(entities); - notificationStage.processURL(ctx); - assertTrue(responseObject); - } - - @Test - public void duplicateAdditionalReqIdFoundTest() { - - SyncRegistrationEntity syncEntity = new SyncRegistrationEntity(); - syncEntity.setAdditionalInfoReqId("abc"); - syncEntity.setPacketId("2018701130000410092018110735"); - syncEntity.setWorkflowInstanceId("78fc3d34-03f5-11ec-9a03-0242ac130004"); - entities.add(syncEntity); - entities.add(entity); - - Mockito.when(registrationStatusService.getRegistrationStatus(anyString(), any(), any(), any())) - .thenReturn(registrationStatusDto).thenReturn(registrationStatusDto).thenReturn(registrationStatusDto1); - Mockito.when(syncRegistrationService.findByWorkflowInstanceId(anyString())).thenReturn(entity); - Mockito.when(syncRegistrationService.findByAdditionalInfoReqId(anyString())).thenReturn(entities); - notificationStage.processURL(ctx); - assertTrue(responseObject); - } - - @Test - public void processFailureURLTest() { - RoutingContext routingContext = Mockito.mock(RoutingContext.class); - routingContext.setBody(null); - notificationStage.processURL(routingContext); - assertEquals(responseObject, null); - } - - @Test - public void processTest() { - MessageDTO inputDto= new MessageDTO(); - inputDto.setInternalError(Boolean.FALSE); - inputDto.setIsValid(Boolean.TRUE); - inputDto.setRid("2018701130000410092018110735"); - - Mockito.when(syncRegistrationService.findByWorkflowInstanceId(anyString())).thenReturn(entity); - Mockito.when(syncRegistrationService.findByAdditionalInfoReqId(anyString())).thenReturn(entities); - MessageDTO messageDTO = notificationStage.process(inputDto); - assertNull(messageDTO); - } - - @Test - public void dbExceptionTest() { - Mockito.when(registrationStatusService.getRegistrationStatus(anyString(), any(), any(), any())).thenThrow(new TablenotAccessibleException("exception")); - Mockito.when(registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.DATA_ACCESS_EXCEPTION)) - .thenReturn("REPROCESS"); - notificationStage.processURL(ctx); - assertNull(responseObject); - } -} +package io.mosip.registration.processor.securezone.notification.stage; + +import static org.junit.Assert.*; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; + +import java.io.InputStream; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.util.ReflectionTestUtils; + +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.RegistrationExceptionTypeCode; +import io.mosip.registration.processor.core.http.ResponseWrapper; +import io.mosip.registration.processor.core.util.RegistrationExceptionMapperUtil; +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.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; +import io.vertx.core.AsyncResult; +import io.vertx.core.Handler; +import io.vertx.core.MultiMap; +import io.vertx.core.Vertx; +import io.vertx.core.buffer.Buffer; +import io.vertx.core.http.HttpMethod; +import io.vertx.core.http.HttpServerRequest; +import io.vertx.core.http.HttpServerResponse; +import io.vertx.core.json.JsonArray; +import io.vertx.core.json.JsonObject; +import io.vertx.ext.auth.User; +import io.vertx.ext.web.Cookie; +import io.vertx.ext.web.FileUpload; +import io.vertx.ext.web.Locale; +import io.vertx.ext.web.ParsedHeaderValues; +import io.vertx.ext.web.Route; +import io.vertx.ext.web.Router; +import io.vertx.ext.web.RoutingContext; +import io.vertx.ext.web.Session; + +@RunWith(SpringRunner.class) +public class SecurezoneNotificationStageTest { + + private static final int maxRetryCount = 5; + + private static final InputStream stream = Mockito.mock(InputStream.class); + + MessageDTO messageDTO= new MessageDTO(); + + /** The registration status service. */ + @Mock + RegistrationStatusService registrationStatusService; + + @Mock + private SyncRegistrationService syncRegistrationService; + + @Mock + private RegistrationExceptionMapperUtil registrationStatusMapperUtil; + + @Mock + private AuditLogRequestBuilder auditLogRequestBuilder; + + private RoutingContext ctx; + private Boolean responseObject; + + @Mock + private MosipRouter router; + + @InjectMocks + SecurezoneNotificationStage notificationStage = new SecurezoneNotificationStage() { + + @Override + public void setResponse(RoutingContext ctx, Object object) { + responseObject = Boolean.TRUE; + } + + @Override + public void send(MosipEventBus mosipEventBus, MessageBusAddress toAddress, MessageDTO message) { + } + + @Override + public MosipEventBus getEventBus(Object verticleName, String url, int instanceNumber) { + return null; + } + + @Override + public void createServer(Router route, int port) + { + + } + @Override + public Router postUrl(Vertx vertx, MessageBusAddress consumeAddress, MessageBusAddress sendAddress) { + return null; + } + }; + + private RoutingContext setContext() { + return new RoutingContext() { + + @Override + public Set fileUploads() { + return null; + } + + @Override + public Vertx vertx() { + return null; + } + + @Override + public User user() { + return null; + } + + @Override + public int statusCode() { + return 0; + } + + @Override + public void setUser(User user) { + } + + @Override + public void setSession(Session session) { + } + + @Override + public void setBody(Buffer body) { + } + + @Override + public void setAcceptableContentType(String contentType) { + } + + @Override + public Session session() { + return null; + } + + @Override + public HttpServerResponse response() { + return null; + } + + @Override + public void reroute(HttpMethod method, String path) { + } + + @Override + public HttpServerRequest request() { + return null; + } + + @Override + public boolean removeHeadersEndHandler(int handlerID) { + return false; + } + + @Override + public Cookie removeCookie(String name, boolean invalidate) { + return null; + } + + @Override + public boolean removeBodyEndHandler(int handlerID) { + return false; + } + + @Override + public T remove(String key) { + return null; + } + + @Override + public MultiMap queryParams() { + return null; + } + + @Override + public List queryParam(String query) { + return null; + } + + @Override + public RoutingContext put(String key, Object obj) { + return null; + } + + @Override + public Map pathParams() { + return null; + } + + @Override + public String pathParam(String name) { + return null; + } + + @Override + public ParsedHeaderValues parsedHeaders() { + return null; + } + + @Override + public String normalisedPath() { + return null; + } + + @Override + public void next() { + } + + @Override + public String mountPoint() { + return null; + } + + @Override + public Cookie getCookie(String name) { + return null; + } + + @Override + public String getBodyAsString(String encoding) { + return null; + } + + @Override + public String getBodyAsString() { + return null; + } + + @Override + public JsonArray getBodyAsJsonArray() { + return null; + } + + @Override + public JsonObject getBodyAsJson() { + JsonObject obj = new JsonObject(); + obj.put("rid", "2018701130000410092018110735"); + obj.put("isValid", true); + obj.put("internalError", false); + obj.put("reg_type", "NEW"); + obj.put("source", "REGISTRATIONCLIENT"); + obj.put("iteration", 1); + obj.put("workflowInstanceId", "78fc3d34-03f5-11ec-9a03-0242ac130003"); + return obj; + } + + @Override + public Buffer getBody() { + return null; + } + + @Override + public String getAcceptableContentType() { + return null; + } + + @Override + public T get(String key) { + return null; + } + + @Override + public Throwable failure() { + return null; + } + + @Override + public boolean failed() { + return false; + } + + @Override + public void fail(Throwable throwable) { + } + + @Override + public void fail(int statusCode) { + } + + @Override + public Map data() { + return null; + } + + @Override + public Route currentRoute() { + return null; + } + + @Override + public Set cookies() { + return null; + } + + @Override + public int cookieCount() { + return 0; + } + + @Override + public void clearUser() { + } + + @Override + public int addHeadersEndHandler(Handler handler) { + return 0; + } + + @Override + public RoutingContext addCookie(Cookie cookie) { + return null; + } + + @Override + public int addBodyEndHandler(Handler handler) { + return 0; + } + + @Override + public List acceptableLocales() { + return null; + } + + @Override + public RoutingContext addCookie(io.vertx.core.http.Cookie arg0) { + return null; + } + + @Override + public int addEndHandler(Handler> arg0) { + return 0; + } + + @Override + public Map cookieMap() { + return null; + } + + @Override + public void fail(int arg0, Throwable arg1) { + + } + + @Override + public boolean isSessionAccessed() { + return false; + } + + @Override + public boolean removeEndHandler(int arg0) { + return false; + } + + + }; + } + + InternalRegistrationStatusDto registrationStatusDto = new InternalRegistrationStatusDto(); + InternalRegistrationStatusDto registrationStatusDto1 = new InternalRegistrationStatusDto(); + List entities = new ArrayList(); + SyncRegistrationEntity entity = new SyncRegistrationEntity(); + SyncRegistrationEntity entity1 = new SyncRegistrationEntity(); + + @Before + public void setup() { + + registrationStatusDto = new InternalRegistrationStatusDto(); + registrationStatusDto.setRegistrationId("2018701130000410092018110735"); + registrationStatusDto.setStatusCode("SECUREZONE_NOTIFICATION_SUCCESS"); + registrationStatusDto.setWorkflowInstanceId("78fc3d34-03f5-11ec-9a03-0242ac130004"); + registrationStatusDto.setCreateDateTime(LocalDateTime.now().minusDays(1)); + + registrationStatusDto1 = new InternalRegistrationStatusDto(); + registrationStatusDto1.setRegistrationId("2018701130000410092018110735"); + registrationStatusDto1.setStatusCode("SECUREZONE_NOTIFICATION_SUCCESS"); + registrationStatusDto1.setWorkflowInstanceId("78fc3d34-03f5-11ec-9a03-0242ac130003"); + registrationStatusDto1.setCreateDateTime(LocalDateTime.now()); + + ResponseWrapper responseWrapper = new ResponseWrapper(); + AuditResponseDto auditResponseDto = new AuditResponseDto(); + responseWrapper.setResponse(auditResponseDto); + + entity.setAdditionalInfoReqId("abc"); + entity.setPacketId("2018701130000410092018110735"); + entity.setWorkflowInstanceId("78fc3d34-03f5-11ec-9a03-0242ac130003"); + + entity1.setAdditionalInfoReqId(null); + entity1.setPacketId("2018701130000410092018110735"); + entity1.setWorkflowInstanceId("78fc3d34-03f5-11ec-9a03-0242ac130003"); + + ctx = setContext(); + ReflectionTestUtils.setField(notificationStage, "workerPoolSize", 10); + ReflectionTestUtils.setField(notificationStage, "clusterManagerUrl", "/dummyPath"); + ReflectionTestUtils.setField(notificationStage, "messageExpiryTimeLimit", Long.valueOf(0)); + ReflectionTestUtils.setField(notificationStage, "mainProcesses", Arrays.asList("NEW","UPDATE","LOST")); + //ReflectionTestUtils.setField(notificationStage, "port", "7999"); + Mockito.when(router.post(Mockito.any())).thenReturn(null); + Mockito.doNothing().when(router).setRoute(Mockito.any()); + Mockito.doNothing().when(router).nonSecureHandler(Mockito.any(),Mockito.any()); + messageDTO.setRid("2018701130000410092018110735"); + messageDTO.setIsValid(true); + messageDTO.setInternalError(false); + messageDTO.setReg_type("NEW"); + messageDTO.setSource("REGISTRATIONCLIENT"); + messageDTO.setIteration(1); + messageDTO.setWorkflowInstanceId("78fc3d34-03f5-11ec-9a03-0242ac130003"); + + Mockito.doNothing().when(registrationStatusService).updateRegistrationStatus(any(),any(),any()); + Mockito.doReturn(responseWrapper).when(auditLogRequestBuilder).createAuditRequestBuilder(anyString(), anyString(), anyString(), + anyString(), anyString(), anyString(), anyString()); + entities.add(entity); + Mockito.when(registrationStatusMapperUtil.getStatusCode(any())).thenReturn("Something"); + Mockito.when(syncRegistrationService.findByWorkflowInstanceId(anyString())).thenReturn(entity); + Mockito.when(syncRegistrationService.findByAdditionalInfoReqId(anyString())).thenReturn(entities); + Mockito.when(registrationStatusService.getRegistrationStatus(anyString(), any(), any(), any())) + .thenReturn(registrationStatusDto); + } + + @Test + public void processURLTest() { + + notificationStage.processURL(ctx); + + assertTrue(responseObject); + } + + @Test + public void ridNotFoundTest() { + Mockito.when(registrationStatusService.getRegistrationStatus(anyString(), any(), any(), any())).thenReturn(null); + + notificationStage.processURL(ctx); + assertTrue(responseObject); + } + + @Test + public void duplicateRidFoundTest() { + + SyncRegistrationEntity syncEntity = new SyncRegistrationEntity(); + syncEntity.setAdditionalInfoReqId(null); + syncEntity.setRegistrationType("NEW"); + syncEntity.setPacketId("2018701130000410092018110735"); + syncEntity.setWorkflowInstanceId("78fc3d34-03f5-11ec-9a03-0242ac130004"); + entities.add(syncEntity); + entities.add(entity1); + + Mockito.when(registrationStatusService.getRegistrationStatus(anyString(), any(), any(), any())) + .thenReturn(registrationStatusDto).thenReturn(registrationStatusDto).thenReturn(registrationStatusDto1); + Mockito.when(syncRegistrationService.findByWorkflowInstanceId(anyString())).thenReturn(syncEntity); + Mockito.when(syncRegistrationService.findByRegistrationId(any())).thenReturn(entities); + notificationStage.processURL(ctx); + assertTrue(responseObject); + } + + @Test + public void duplicateAdditionalReqIdFoundTest() { + + SyncRegistrationEntity syncEntity = new SyncRegistrationEntity(); + syncEntity.setAdditionalInfoReqId("abc"); + syncEntity.setPacketId("2018701130000410092018110735"); + syncEntity.setWorkflowInstanceId("78fc3d34-03f5-11ec-9a03-0242ac130004"); + entities.add(syncEntity); + entities.add(entity); + + Mockito.when(registrationStatusService.getRegistrationStatus(anyString(), any(), any(), any())) + .thenReturn(registrationStatusDto).thenReturn(registrationStatusDto).thenReturn(registrationStatusDto1); + Mockito.when(syncRegistrationService.findByWorkflowInstanceId(anyString())).thenReturn(entity); + Mockito.when(syncRegistrationService.findByAdditionalInfoReqId(anyString())).thenReturn(entities); + notificationStage.processURL(ctx); + assertTrue(responseObject); + } + + @Test + public void processFailureURLTest() { + RoutingContext routingContext = Mockito.mock(RoutingContext.class); + routingContext.setBody(null); + notificationStage.processURL(routingContext); + assertEquals(responseObject, null); + } + + @Test + public void processTest() { + MessageDTO inputDto= new MessageDTO(); + inputDto.setInternalError(Boolean.FALSE); + inputDto.setIsValid(Boolean.TRUE); + inputDto.setRid("2018701130000410092018110735"); + inputDto.setWorkflowInstanceId("78fc3d34-03f5-11ec-9a03-0242ac130003"); + + Mockito.when(syncRegistrationService.findByWorkflowInstanceId(anyString())).thenReturn(entity); + Mockito.when(syncRegistrationService.findByAdditionalInfoReqId(anyString())).thenReturn(entities); + MessageDTO messageDTO = notificationStage.process(inputDto); + assertTrue(messageDTO.getIsValid()); + } + + @Test + public void dbExceptionTest() { + Mockito.when(registrationStatusService.getRegistrationStatus(anyString(), any(), any(), any())).thenThrow(new TablenotAccessibleException("exception")); + Mockito.when(registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.DATA_ACCESS_EXCEPTION)) + .thenReturn("REPROCESS"); + MessageDTO result = notificationStage.process(messageDTO); + assertTrue(result.getInternalError()); + } + + + @Test + public void genericExceptionTest() { + Mockito.when(syncRegistrationService + .findByWorkflowInstanceId(anyString())).thenThrow(new NullPointerException("exception")); + Mockito.when(registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.DATA_ACCESS_EXCEPTION)) + .thenReturn("REPROCESS"); + MessageDTO result = notificationStage.process(messageDTO); + assertFalse(result.getIsValid()); + } +} From 2790b0f264b4c9826afeb5c203d24b7dcdb95523 Mon Sep 17 00:00:00 2001 From: Sowmya Ujjappa Banakar <43202851+sowmya695@users.noreply.github.com> Date: Wed, 31 May 2023 15:04:57 +0530 Subject: [PATCH 070/133] Merged changes from develop (#1708) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * work flow status code update code fix * MOSIP-17897 * merge * merge * MOSIP-20157_added fix for language issue * Update MessageNotificationServiceImpl.java * Update NotificationUtility.java * Update MessageNotificationServiceImpl.java * Merge branch 'develop' of https://github.com/mosip/registration.git into develop * Update MessageNotificationServiceImpl.java * Update NotificationUtility.java * MOSIP-18793 : objectmapper afterburner usage (#1465) (#1466) * Update regprc-transaction_type.csv * MOSIP-19244 : using selfTokenRestTemplate (#1468) * MOSIP-19244 : using selfTokenRestTemplate (#1452) * MOSIP-19244 : using selfTokenRestTemplate * MOSIP-20472 : added vid in template * MOSIP-19244 : using selfTokenRestTemplate * MOSIP-19244 : updated pom versions * MOSIP-19244 : using selfTokenRestTemplate (#1470) * MOSIP-19244 : using selfTokenRestTemplate (#1471) * MOSIP-18661_disabled health check * MOSIP-18661 * Added logger (#1474) * MOSIP-18861 * MOSIP-18661 * MOSIP-18861 * Update MessageNotificationServiceImpl.java * Update NotificationUtility.java * MOSIP-18661_disabled health check (#1473) * MOSIP-17897 * merge * merge * MOSIP-20157_added fix for language issue * Update MessageNotificationServiceImpl.java * Update NotificationUtility.java * Update MessageNotificationServiceImpl.java * Merge branch 'develop' of https://github.com/mosip/registration.git into develop * Update MessageNotificationServiceImpl.java * Update NotificationUtility.java * Update regprc-transaction_type.csv * MOSIP-18661 * MOSIP-18661 * MOSIP-18861 * Update MessageNotificationServiceImpl.java * Update NotificationUtility.java Co-authored-by: M1030448 Co-authored-by: Jyoti Prakash Nayak Co-authored-by: M1030448 * MOSIP-19759_added sonar compliant solution * MOSIP-19244 : passing iam_adapter_url in dockerfile (#1483) * MOSIP-19244 : adding zip format (#1484) * MOSIP-19244 : passing iam_adapter_url in dockerfile * MOSIP-19244 : adding zip format * MOSIP-20837 : sending documents to manual adjudication (#1489) * MOSIP-20616 : Reprocessor changed to allow configurable stages to be excluded from reprocessing (#1477) (#1491) * MOSIP-20616 : Reprocessor changed to allow configurable stages to be excluded from reprocessing * MOSIP-20616 : Unit test case changes done to resolve issues with reprocessor stage and status service impl * MOSIP-21056 * MOSIP-21056 * MOSIP-21056 * MOSIP-21056 * MOSIP-19759_added sonar compliant solution (#1480) * MOSIP-17897 * merge * merge * MOSIP-20157_added fix for language issue * Update MessageNotificationServiceImpl.java * Update NotificationUtility.java * Update MessageNotificationServiceImpl.java * Merge branch 'develop' of https://github.com/mosip/registration.git into develop * Update MessageNotificationServiceImpl.java * Update NotificationUtility.java * Update regprc-transaction_type.csv * MOSIP-18661_disabled health check * MOSIP-18661 * MOSIP-18861 * MOSIP-18661 * MOSIP-18861 * Update MessageNotificationServiceImpl.java * Update NotificationUtility.java * MOSIP-19759_added sonar compliant solution * MOSIP-21056 * MOSIP-21056 * MOSIP-21056 * MOSIP-21056 Co-authored-by: M1030448 Co-authored-by: Jyoti Prakash Nayak Co-authored-by: M1030448 * MOSIP 19759 Sonar bugs (#1496) Co-authored-by: Shilpa M * MOSIP-21094 * MOSIP-21094_changed notification type (#1503) * MOSIP-17897 * merge * merge * MOSIP-20157_added fix for language issue * Update MessageNotificationServiceImpl.java * Update NotificationUtility.java * Update MessageNotificationServiceImpl.java * Merge branch 'develop' of https://github.com/mosip/registration.git into develop * Update MessageNotificationServiceImpl.java * Update NotificationUtility.java * Update regprc-transaction_type.csv * MOSIP-18661_disabled health check * MOSIP-18661 * MOSIP-18861 * MOSIP-18661 * MOSIP-18861 * Update MessageNotificationServiceImpl.java * Update NotificationUtility.java * MOSIP-19759_added sonar compliant solution * MOSIP-21056 * MOSIP-21056 * MOSIP-21056 * MOSIP-21056 * MOSIP-21094 Co-authored-by: M1030448 Co-authored-by: Jyoti Prakash Nayak Co-authored-by: M1030448 * mosip 20660 Ability to update address and contact information as part… (#1508) * mosip 20660 Ability to update address and contact information as part of LOST UIN * mosip 20660 removed hardcoded values * mosip 20660 implemented code review comment * mosip 20660 implemented code review comment Co-authored-by: Shilpa M * Devreg (#1509) * mosip 20660 Ability to update address and contact information as part of LOST UIN * mosip 20660 removed hardcoded values * mosip 20660 implemented code review comment * mosip 20660 implemented code review comment * mosip 20660 added test case * mosip 20660 added test case Co-authored-by: Shilpa M * MOSIP-21056 * MOSIP-21056_changed umc validation code (#1510) * MOSIP-17897 * merge * merge * MOSIP-20157_added fix for language issue * Update MessageNotificationServiceImpl.java * Update NotificationUtility.java * Update MessageNotificationServiceImpl.java * Merge branch 'develop' of https://github.com/mosip/registration.git into develop * Update MessageNotificationServiceImpl.java * Update NotificationUtility.java * Update regprc-transaction_type.csv * MOSIP-18661_disabled health check * MOSIP-18661 * MOSIP-18861 * MOSIP-18661 * MOSIP-18861 * Update MessageNotificationServiceImpl.java * Update NotificationUtility.java * MOSIP-19759_added sonar compliant solution * MOSIP-21056 * MOSIP-21056 * MOSIP-21056 * MOSIP-21056 * MOSIP-21094 * MOSIP-21056 Co-authored-by: M1030448 Co-authored-by: Jyoti Prakash Nayak Co-authored-by: M1030448 * added authorization header * DSL_FIX * merged 1.2.0.1 into develop (#1517) * MOSIP-18793 : objectmapper afterburner usage (#1465) * MOSIP-19244 : added self token rest template (#1485) * MOSIP-18793 : objectmapper afterburner usage (#1465) (#1466) * MOSIP-19244 : using selfTokenRestTemplate (#1468) * MOSIP-19244 : using selfTokenRestTemplate (#1452) * MOSIP-19244 : using selfTokenRestTemplate * MOSIP-20472 : added vid in template * MOSIP-19244 : using selfTokenRestTemplate * MOSIP-19244 : updated pom versions * MOSIP-19244 : using selfTokenRestTemplate (#1470) * MOSIP-19244 : using selfTokenRestTemplate (#1471) * Added logger (#1474) * MOSIP-18661_disabled health check (#1473) * MOSIP-17897 * merge * merge * MOSIP-20157_added fix for language issue * Update MessageNotificationServiceImpl.java * Update NotificationUtility.java * Update MessageNotificationServiceImpl.java * Merge branch 'develop' of https://github.com/mosip/registration.git into develop * Update MessageNotificationServiceImpl.java * Update NotificationUtility.java * Update regprc-transaction_type.csv * MOSIP-18661 * MOSIP-18661 * MOSIP-18861 * Update MessageNotificationServiceImpl.java * Update NotificationUtility.java Co-authored-by: M1030448 Co-authored-by: Jyoti Prakash Nayak Co-authored-by: M1030448 * MOSIP-19244 : passing iam_adapter_url in dockerfile (#1483) * MOSIP-19244 : adding zip format (#1484) * MOSIP-19244 : passing iam_adapter_url in dockerfile * MOSIP-19244 : adding zip format Co-authored-by: JyotiPrakashNayak Co-authored-by: M1030448 Co-authored-by: Jyoti Prakash Nayak Co-authored-by: M1030448 * MOSIP-20837 : sending documents to manual adjudication (#1487) (#1490) * MOSIP-20352 : reviewed release script * MOSIP-19244 : fixed ida token issue for self token change * added exception (#1495) Co-authored-by: Shilpa M * Dev1.2 (#1498) * added exception * Resolved issue for MOSIP 21111 * Resolved issue for MOSIP 21111 Co-authored-by: Shilpa M * MOSIP-21075 (#1499) * MOSIP-21075_modified release script (#1502) * Update 1.2_regprc-scripts_release.sql * Update regprc-individual_demographic_dedup.sql * MOSIP-21075_modified release script * MOSIP-21075_modified release script (#1506) * Update 1.2_regprc-scripts_release.sql * Update regprc-individual_demographic_dedup.sql * MOSIP-21075_modified release script * MOSIP-21075 * MOSIP-21056_changed machine and center validation code (#1507) * Update 1.2_regprc-scripts_release.sql * Update regprc-individual_demographic_dedup.sql * MOSIP-21075_modified release script * MOSIP-21075 * MOSIP-21056 * MOSIP-21056 * MOSIP-21056_changed umc validation code (#1511) * Update 1.2_regprc-scripts_release.sql * Update regprc-individual_demographic_dedup.sql * MOSIP-21075_modified release script * MOSIP-21075 * MOSIP-21056 * MOSIP-21056 * Update OperatorValidator.java * Update SupervisorValidator.java Co-authored-by: JyotiPrakashNayak Co-authored-by: M1030448 Co-authored-by: Jyoti Prakash Nayak Co-authored-by: M1030448 Co-authored-by: Mandeep Dhiman Co-authored-by: Shilpa-Manjunath <72008366+Shilpa-Manjunath@users.noreply.github.com> Co-authored-by: Shilpa M * status comment added for biometric authentication skipping (#1518) Co-authored-by: Nishant Kumar (IN64559) * MOSIP-19201 Replace usage of gson library with jackson to be consistent (#1516) * MOSIP-19201 Replace usage of gson library with jackson to be consistent and improve performance * MOSIP-19201 Replace usage of gson library with jackson to be consistent and improve performance * MOSIP-19201 Replace usage of gson library with jackson to be consistent and improve performance * Added review comments * Added review comments * Implemented review comments * implmented review comments * implmented review comments * Implemented code review comments Co-authored-by: Shilpa M * MOSIP-21782 (#1528) Co-authored-by: M1030448 * Avoid getting the biometrics and creating a datashare in case of already processed insert in ABIS handler stage (#1527) * MOSIP-19201 Replace usage of gson library with jackson to be consistent and improve performance * MOSIP-19201 Replace usage of gson library with jackson to be consistent and improve performance * MOSIP-19201 Replace usage of gson library with jackson to be consistent and improve performance * Added review comments * Added review comments * Implemented review comments * implmented review comments * implmented review comments * Implemented code review comments * Mosip 21588 Avoid getting the biometrics and creating a datashare in case of already processed insert in ABIS handler stage Co-authored-by: Shilpa M * Develop-fix (#1534) * MOSIP-21782 * MOSIP-19765 * develop-fix Co-authored-by: M1030448 * MOSIP 21708 Investigate the Error in BIOGRAPHIC_Verification stage ha… (#1538) * MOSIP 21708 Investigate the Error in BIOGRAPHIC_Verification stage having Insert Response Failed and Identify Response Failed * MOSIP 20652 Use SDK and remove IDA dependency * Mosip 21708 Investigate the Error in BIOGRAPHIC_Verification stage having Insert Response Failed and Identify Response Failed * Mosip 20660 Implemented code review comments Co-authored-by: Shilpa M * resolved build issue (#1544) Co-authored-by: Shilpa M * resolved builld issue (#1545) * resolved build issue * resolved build issue Co-authored-by: Shilpa M * Mosip 22319 Contact details are not getting updated as a part of LOST UIN (#1546) Co-authored-by: Shilpa M * MOSIP-20644_Moving landing zone to Minio (#1540) * MOSIP-21782 * MOSIP-19765 * develop-fix * MOSIP-20644 * # WARNING: head commit changed in the meantime Merge branch '1.1.5.6' of https://github.com/mosip/registration.git into 1.1.5.6 * MOSIP-20644 * MOSIP-20644 * MOSIP-20644 * MOSIP-20644 * MOSIP-20644 * MOSIP-20644 * MOSIP-20644 * MOSIP-20644 * MOSIP-20644 * MOSIP-20644 * MOSIP-20644 * # WARNING: head commit changed in the meantime Merge branch 'develop' of https://github.com/mosip/registration.git into develop * MOSIP-12398 Co-authored-by: M1030448 * Exception message changed (#1555) Co-authored-by: Nishant Kumar (IN64559) * Adding port servletpath and actuator endpoint to landingzone utility (#1553) * Adding port servletpath and actuator endpoint to landingzone utility * Adding port servletpath and actuator endpoint to landingzone utility * Added logger for lost uin flow Co-authored-by: Shilpa M * Mosip 22417 Ref_id is missing in REGISTRATION_PROCESSOR audit logs (#1554) Co-authored-by: Shilpa M * name convention and resolved build issue (#1557) Co-authored-by: Shilpa M * build issue (#1558) * name convention and resolved build issue * Resolved build issues * test cases Co-authored-by: Shilpa M * added landing zone info in yml (#1560) Co-authored-by: Shilpa M * MOSIP-21708 : fixed null uin issue (#1564) * Update ddl.sql (#1567) added verification db script * Updated Manual_verification to verification (#1576) * Updated Manual_verification to verification (#1575) * Mosip-23166 Packet getting fail at OPERATOR_VALIDATION stage, when operator auth method is fingerprint (#1579) Co-authored-by: Shilpa M * Mosip-21093 Even after consent Disagree packets are processed (#1582) Co-authored-by: Shilpa M * [ MOSIP-23587 ] added healthcheck.txt under /home/mosip/landing * MOSIP-22440 Resident tries to get another UIN by providing different … (#1599) * MOSIP-22440 Resident tries to get another UIN by providing different demo details and same bio and both are processed * implemented review comments Co-authored-by: Shilpa M * MOSIP-22440: corrected mistake (#1601) * MOSIP-21238 relocate method call (#1594) * MOSIP-21238 relocate method call * MOSIP-21238 bug fixing related changes done * MOSIP-21238 updating records in verification entity before going to queue * MOSIP-21238 mocked SaveVerificationRecordUtility in VerificationStageTest * MOSIP-21238 i have called getStageName() in updatePacketStatus method * MOSIP-22440 Code changes * MOSIP-22440 minor Code change to solve DB transaction update before sending message to resolve status issue (#1610) * work flow status code update code fix * MOSIP-22440 Code changes Co-authored-by: M1022006 * MOSIP-23166 Code fix * MOSIP-23166 Code fix (#1617) * work flow status code update code fix * MOSIP-22440 Code changes * MOSIP-23166 Code fix Co-authored-by: M1022006 * Merge pull request #1584 from MonobikashDas/1.2.0.1 MOSIP-23025 : healthcheck and retry fix for activemq connection + routing config for securezone * MOSIP-23025 cherry pick code from 1.2.0.1 (#1620) * work flow status code update code fix * MOSIP-22440 Code changes * MOSIP-23166 Code fix * Merge pull request #1584 from MonobikashDas/1.2.0.1 MOSIP-23025 : healthcheck and retry fix for activemq connection + routing config for securezone Co-authored-by: M1022006 Co-authored-by: Sasikumar Ganesan * MOSIP-24407 : Steps added to locally run regproc stages (#1621) * MOSIP-21476 (#1623) Co-authored-by: ase-101 <> * Mosip 22417 develop (#1627) * work flow status code update code fix * MOSIP-22440 Code changes * MOSIP-23166 Code fix * Merge pull request #1584 from MonobikashDas/1.2.0.1 MOSIP-23025 : healthcheck and retry fix for activemq connection + routing config for securezone * MOSIP-22417 Code changes Co-authored-by: M1022006 Co-authored-by: Sasikumar Ganesan * MOSIP-24572 fixed vulnerabilities in RestApiClient.java and MosipActiveMq.java (#1628) * [MOSIP-22450] (#1629) * MOSIP-24572 fixed vulnerability in MosipActiveMq.java file (#1631) * MOSIP-24572 fixed vulnerabilities in RestApiClient.java and MosipActiveMq.java * MOSIP-24572 I fixed vulnerability by excluded MOSIPActiveMq.java from registration pom.xml file * conflict resolved in RestApiClient.java * MOSIP-24572 added NOSONAR comment in MosipActiveMq (#1632) * MOSIP-24572 fixed vulnerabilities in RestApiClient.java and MosipActiveMq.java * MOSIP-24572 I fixed vulnerability by excluded MOSIPActiveMq.java from registration pom.xml file * conflict resolved in RestApiClient.java * added NOSONAR commit * Mosip 24230 develop (#1636) * [MOSIP-22450] * Mosip-24230 * MOS-24230_develop * Mosip-24230(replaced auth with biosdk util) * Mosip 24230 (Updated as requested in comments) * Mosip 24230 (Updated platformErrors) * Mosip 24230 (Updated clild packet discription) * Last commit * Mosip 25203 develop (#1641) * [MOSIP-22450] * (Added secure Random number in printing stage) * (Added SecureRandom pin generation method) * MOSIP-25203 * Second commit * updated commit(Did throw exception in stagesConfig) * MOSIP-23598 removed print-stage health check endpoint (#1646) * Mos 25203 (#1647) * [MOSIP-22450] * (Added secure Random number in printing stage) * (Added SecureRandom pin generation method) * MOSIP-25203 * Mos-19396 Latest Commit * done last two sonar changes * Done last two sonar changes * [DSD-2051] * updated the code * DSD-2051 * [DSD-2051]restructured the docker build * [DSD-2051]restructured the docker build * MOSIP-17570 added supervisor rejected email and sms templates (#1662) * [MOSIP-25637] Updated postgres-init_trigger.yml workflow (#1663) * [MOSIP-25637] Updated postgres-init_trigger.yml workflow * Update postgres-init_trigger.yml * Update README.MD * Update postgres-init_trigger.yml * Update README.md * [MOSIP-25637] Updated postgres-init_trigger.yml workflow (#1665) * MOSIP-25355 (#1648) * MOSIP-25355 * updated code based on review comments * fixed test cases for printing stage (#1668) * MOSIP-25355 (#1671) * MOSIP-25355 * MOSIP-25355 * Fix the delimiter issue for printing stage (#1672) * MOSIP-26444 code changes (#1674) * MOSIP-26444 code changes --------- Co-authored-by: M1022006 Co-authored-by: Sasikumar Ganesan Co-authored-by: Sowmya Ujjappa Banakar * Mosip 23945 develop (#1675) * MOSIP-23945 code changes * MOSIP-23945 code review fix --------- Co-authored-by: M1022006 Co-authored-by: Sasikumar Ganesan Co-authored-by: Sowmya Ujjappa Banakar * first commit (#1683) * MOSIP-23678 : added kafka support for SecurezoneNotificationStage (#1685) * MOSIP-27068 code changes * MOSIP-27066 code changes * MOSIP-23715 Code changes,stage test class changed because of eventbus new methods added. (#1693) * MOSIP-23715 code changes * Added kafka test cases --------- Co-authored-by: M1022006 Co-authored-by: Sowmya Ujjappa Banakar * [MOSIP-25305]Updated service name by removing utiltiy. (#1702) * [MOSIP-25305]Replaced * [MOSIP-25305]Replaced * Update README.md Signed-off-by: Mohan E * [MOSIP-25305]Replaced LandingZoneUtility to LandingZone. * Updated README.md Signed-off-by: Mohan E * Update push_trigger.yml Signed-off-by: Mohan E --------- Signed-off-by: Mohan E * MOSIP-27366 code changes --------- Signed-off-by: Mohan E Co-authored-by: M1022006 Co-authored-by: M1030448 Co-authored-by: JyotiPrakashNayak Co-authored-by: Jyoti Prakash Nayak Co-authored-by: M1030448 Co-authored-by: Monobikash Das <43202165+MonobikashDas@users.noreply.github.com> Co-authored-by: Vishwa Co-authored-by: Shilpa-Manjunath <72008366+Shilpa-Manjunath@users.noreply.github.com> Co-authored-by: Shilpa M Co-authored-by: Mandeep Dhiman Co-authored-by: NishantKumar4559 <100404536+NishantKumar4559@users.noreply.github.com> Co-authored-by: Nishant Kumar (IN64559) Co-authored-by: syed-salman-technoforte Co-authored-by: Keshav Mishra Co-authored-by: Shubhamjwl <49360082+Shubhamjwl@users.noreply.github.com> Co-authored-by: Sasikumar Ganesan Co-authored-by: ase-101 Co-authored-by: Akshay Prabhakar Chougule <96629697+AkshayChouguleac1@users.noreply.github.com> Co-authored-by: Rakshitha650 Co-authored-by: Mohan E Co-authored-by: dhanendra06 <60607841+dhanendra06@users.noreply.github.com> Co-authored-by: Sowmya Ujjappa Banakar --- .github/workflows/postgres-init_trigger.yml | 83 + .github/workflows/push_trigger.yml | 923 ++-- .github/workflows/release_trigger.yml | 52 + db_scripts/README.md | 1 - db_upgrade_scripts/README.MD | 2 +- docs/stage-local-development.md | 106 + pom.xml | 2 +- registration-processor/core-processor/pom.xml | 56 +- .../pom.xml | 4 +- .../abis/handler/stage/AbisHandlerStage.java | 15 +- .../stage/test/AbisHandlerStageTest.java | 2052 ++++--- .../pom.xml | 184 +- .../middleware/stage/AbisMiddleWareStage.java | 29 +- .../stage/AbisMiddleWareStageTest.java | 1 + .../registration-processor-abis/pom.xml | 4 +- .../pom.xml | 190 +- .../biodedupe/stage/BioDedupeStageTest.java | 1 + .../pom.xml | 200 +- .../config/BiometricAuthConfigBean.java | 6 +- .../BiometricAuthenticationConstants.java | 2 +- .../stage/BiometricAuthenticationStage.java | 152 +- .../BiometricAuthenticationStageTest.java | 36 +- .../pom.xml | 196 +- .../pom.xml | 174 +- .../demodedupe/DemodedupeProcessor.java | 22 +- .../demodedupe/DemoDedupeStageTest.java | 1 + .../pom.xml | 200 +- .../stage/tests/FinalizationStageTest.java | 2 + .../pom.xml | 244 +- .../config/ManualAdjudicationConfigBean.java | 6 +- .../impl/ManualAdjudicationServiceImpl.java | 8 +- .../stage/ManualAdjudicationStage.java | 2 +- .../util/ManualVerificationUpdateUtility.java | 60 +- .../ManualAdjudicationServiceTest.java | 1554 +++--- .../pom.xml | 192 +- .../uingenerator/stage/UinGeneratorStage.java | 29 +- .../src/main/resources/bootstrap.properties | 5 + .../uigenerator/UinGeneratorStageTest.java | 4739 +++++++++-------- .../pom.xml | 244 +- .../config/VerificationConfigBean.java | 10 +- .../service/impl/VerificationServiceImpl.java | 131 +- .../util/SaveVerificationRecordUtility.java | 100 + ...erificationAppConfigurationsValidator.java | 1 - .../service/VerificationServiceTest.java | 82 +- registration-processor/init/pom.xml | 38 +- .../version.xml | 4 +- .../pom.xml | 284 +- .../PacketReceiverResponseBuilder.java | 5 +- .../receiver/config/PacketReceiverConfig.java | 312 +- .../service/PacketReceiverService.java | 4 +- .../impl/PacketReceiverServiceImpl.java | 49 +- .../src/main/resources/bootstrap.properties | 48 +- .../global/handler/ExceptionHandlerTest.java | 131 +- .../service/PacketReceiverServiceTest.java | 39 + .../pom.xml | 330 +- ...nternalAuthDelegateServicesController.java | 20 +- .../PacketExternalStatusController.java | 25 +- .../RegistrationExternalStatusController.java | 353 +- .../RegistrationStatusController.java | 522 +- ...lAuthDelegateServicesExceptionHandler.java | 179 +- .../PacketExternalStatusExceptionHandler.java | 21 +- ...trationExternalStatusExceptionHandler.java | 338 +- .../RegistrationStatusExceptionHandler.java | 21 +- .../RegistrationSyncExceptionHandler.java | 327 +- ...nalAuthDelegateServicesControllerTest.java | 291 +- .../PacketExternalStatusControllerTest.java | 318 +- ...istrationExternalStatusControllerTest.java | 464 +- ...gistrationStatusAndSyncControllerTest.java | 832 ++- .../src/test/resources/application.properties | 166 +- .../mosip-stage-executor/pom.xml | 62 +- .../stages/executor/config/StagesConfig.java | 5 +- .../executor/util/StageClassesUtil.java | 6 +- registration-processor/pom.xml | 1003 ++-- registration-processor/post-processor/pom.xml | 44 +- .../pom.xml | 206 +- .../stage/test/MessageSenderStageTest.java | 1 + .../pom.xml | 4 +- .../processor/print/stage/PrintingStage.java | 54 +- .../src/main/resources/bootstrap.properties | 8 +- .../print/stage/test/PrintingStageTest.java | 8 +- .../pom.xml | 342 +- .../RegistrationTransactionController.java | 33 +- ...gistrationTransactionExceptionHandler.java | 16 +- registration-processor/pre-processor/pom.xml | 58 +- .../pom.xml | 238 +- .../stages/cmdvalidator/CenterValidator.java | 2 +- .../stages/cmdvalidator/MachineValidator.java | 8 +- .../pom.xml | 238 +- .../IntroducerValidator.java | 66 +- .../introducer/IntroducerValidatorTest.java | 62 +- .../pom.xml | 238 +- .../config/OperatorValidatorConfig.java | 59 +- .../operatorvalidator/OperatorValidator.java | 59 +- .../OperatorValidatorStage.java | 2 +- .../operator/OperatorValidatorTest.java | 54 +- .../pom.xml | 244 +- .../pom.xml | 254 +- .../service/PacketUploaderService.java | 2 +- .../impl/PacketUploaderServiceImpl.java | 24 +- .../uploader/stage/PacketUploaderStage.java | 1 + .../service/PacketUploaderServiceTest.java | 21 +- .../pom.xml | 228 +- .../validator/PacketValidateProcessor.java | 8 +- .../utils/NotificationTemplateType.java | 4 +- .../stages/utils/NotificationUtility.java | 11 +- .../validator/impl/PacketValidatorImpl.java | 37 +- .../PacketValidateProcessorTest.java | 2 +- .../pom.xml | 192 +- .../stage/QualityClassifierStage.java | 2 +- .../pom.xml | 198 +- .../stage/SecurezoneNotificationStage.java | 770 +-- .../SecurezoneNotificationStageTest.java | 1076 ++-- .../pom.xml | 238 +- .../config/SupervisorValidatorConfig.java | 62 +- .../SupervisorValidator.java | 63 +- .../SupervisorValidatorStage.java | 2 +- .../supervisor/SupervisorValidatorTest.java | 32 +- .../qc-users-manger/pom.xml | 156 +- .../pom.xml | 150 +- .../test/BioDedupeServiceImplTest.java | 122 +- .../dependency-reduced-pom.xml | 6 +- .../pom.xml | 6 +- .../camel/bridge/MosipBridgeFactory.java | 5 +- .../bridge/config/CamelBridgeConfig.java | 2 + .../registration-processor-core/pom.xml | 14 +- .../core/abstractverticle/HealthCheckDTO.java | 2 +- .../MosipVerticleAPIManager.java | 439 +- .../MosipVerticleManager.java | 758 +-- .../processor/core/code/ApiName.java | 3 +- .../processor/core/config/CoreConfigBean.java | 2 + .../constant/LandingZoneTypeConstant.java | 6 + .../core/constant/MappingJsonConstants.java | 1 + .../core/eventbus/VertxMosipEventBus.java | 1 + .../exception/util/PlatformErrorMessages.java | 15 +- .../util/PlatformSuccessMessages.java | 2 + .../core/logger/RegProcessorLogger.java | 17 +- .../core/queue/factory/MosipActiveMq.java | 2 +- .../core/status/util/StatusUtil.java | 439 +- .../processor/core/util/JsonUtil.java | 16 +- .../processor/core/util/ServerUtil.java | 1 - .../pom.xml | 286 +- .../config/PacketStorageBeanConfig.java | 10 +- .../packet/storage/dao/PacketInfoDao.java | 2 +- .../packet/storage/utils/ABISHandlerUtil.java | 5 +- .../packet/storage/utils/AuthUtil.java | 494 -- .../packet/storage/utils/BioSdkUtil.java | 131 + .../packet/storage/utils/Utilities.java | 283 +- .../storage/utils/ABISHandlerUtilTest.java | 10 +- .../packet/storage/utils/BioSdkUtilTest.java | 96 + .../Dockerfile | 85 + .../pom.xml | 94 + ...rationProcessorLandingZoneApplication.java | 17 + .../processor/util/LandingZone.java | 124 + .../processor/util/LandingZoneConfig.java | 54 + .../src/main/resources/bootstrap.properties | 18 + ...nProcessorLandingZoneApplicationTests.java | 13 + .../processor/util/LandingZoneTest.java | 74 + ...11207095530-10001_10149-20211207095827.zip | Bin 0 -> 193014 bytes .../pom.xml | 18 +- .../impl/MessageNotificationServiceImpl.java | 24 +- .../pom.xml | 4 +- .../service/impl/NotificationServiceImpl.java | 2 +- .../util/StatusNotificationTypeMapUtil.java | 2 +- .../pom.xml | 15 +- .../manager/decryptor/DecryptorImpl.java | 10 - .../idreposervice/impl/IdRepoServiceImpl.java | 13 +- .../manager/service/impl/FileManagerImpl.java | 8 + .../manager/decryptor/DecryptorTest.java | 14 +- .../impl/test/IdRepoServiceImplTest.java | 19 +- .../impl/test/IdrepoDraftServiceTest.java | 3 +- .../pom.xml | 222 +- .../status/dao/RegistrationStatusDao.java | 14 +- .../processor/status/decryptor/Decryptor.java | 12 +- .../processor/status/encryptor/Encryptor.java | 11 +- .../InternalAuthDeligateAppException.java | 105 + .../repositary/RegistrationRepositary.java | 13 +- .../service/RegistrationStatusService.java | 11 +- .../impl/InternalAuthDelegateServiceImpl.java | 60 +- .../impl/RegistrationStatusServiceImpl.java | 10 +- .../validator/LostRidRequestValidator.java | 5 +- .../RegistrationStatusRequestValidator.java | 2 +- .../RegistrationSyncRequestValidator.java | 2 +- .../status/dao/RegistrationStatusDaoTest.java | 12 +- .../status/decryptor/DecryptorTest.java | 31 +- .../status/encryptor/EncryptorTest.java | 17 +- .../RegistrationStatusServiceTest.java | 24 +- .../pom.xml | 4 +- .../audit/builder/AuditLogRequestBuilder.java | 1 + .../rest/client/utils/RestApiClient.java | 38 +- registration-processor/stage-groups/pom.xml | 4 +- .../Dockerfile | 2 +- .../pom.xml | 8 +- .../pom.xml | 12 +- .../pom.xml | 148 +- .../pom.xml | 128 +- .../pom.xml | 160 +- .../pom.xml | 136 +- .../pom.xml | 146 +- .../workflow-engine/pom.xml | 38 +- .../pom.xml | 4 +- .../verticle/ReprocessorVerticle.java | 10 +- .../verticle/ReprocessingSchedulerTest.java | 610 +-- .../verticle/ReprocessorVerticleTest.java | 11 +- .../pom.xml | 4 +- 204 files changed, 15644 insertions(+), 14035 deletions(-) create mode 100644 .github/workflows/postgres-init_trigger.yml create mode 100644 docs/stage-local-development.md create mode 100644 registration-processor/core-processor/registration-processor-verification-stage/src/main/java/io/mosip/registration/processor/verification/util/SaveVerificationRecordUtility.java create mode 100644 registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/constant/LandingZoneTypeConstant.java create mode 100644 registration-processor/registration-processor-info-storage-service/src/main/java/io/mosip/registration/processor/packet/storage/utils/BioSdkUtil.java create mode 100644 registration-processor/registration-processor-info-storage-service/src/test/java/io/mosip/registration/processor/packet/storage/utils/BioSdkUtilTest.java create mode 100644 registration-processor/registration-processor-landing-zone/Dockerfile create mode 100644 registration-processor/registration-processor-landing-zone/pom.xml create mode 100644 registration-processor/registration-processor-landing-zone/src/main/java/io/mosip/registration/processor/RegistrationProcessorLandingZoneApplication.java create mode 100644 registration-processor/registration-processor-landing-zone/src/main/java/io/mosip/registration/processor/util/LandingZone.java create mode 100644 registration-processor/registration-processor-landing-zone/src/main/java/io/mosip/registration/processor/util/LandingZoneConfig.java create mode 100644 registration-processor/registration-processor-landing-zone/src/main/resources/bootstrap.properties create mode 100644 registration-processor/registration-processor-landing-zone/src/test/java/io/mosip/registration/processor/RegistrationProcessorLandingZoneApplicationTests.java create mode 100644 registration-processor/registration-processor-landing-zone/src/test/java/io/mosip/registration/processor/util/LandingZoneTest.java create mode 100644 registration-processor/registration-processor-landing-zone/src/test/resources/mnt/regproc/landing/10001101490000220211207095530-10001_10149-20211207095827.zip create mode 100644 registration-processor/registration-processor-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/exception/InternalAuthDeligateAppException.java diff --git a/.github/workflows/postgres-init_trigger.yml b/.github/workflows/postgres-init_trigger.yml new file mode 100644 index 00000000000..3de4c6f32c5 --- /dev/null +++ b/.github/workflows/postgres-init_trigger.yml @@ -0,0 +1,83 @@ +name: Trigger postgres-init repo upon db scripts updates + +on: + push: + branches: + - master + - 1.* + - develop + - release* + paths: + - db_release_scripts/** + - db_scripts/** + +jobs: + paths-filter: + runs-on: ubuntu-latest + outputs: + db_release_scripts: ${{ steps.filter.outputs.db_release_scripts }} + db_scripts: ${{ steps.filter.outputs.db_scripts }} + steps: + - uses: actions/checkout@v2 + - uses: dorny/paths-filter@v2 + id: filter + with: + base: ${{ github.ref }} + filters: | + db_release_scripts: + - 'db_release_scripts/**' + db_scripts: + - 'db_scripts/**' + + # run only if 'db_release_scripts' files were changed + db_release_scripts_updates: + needs: paths-filter + if: needs.paths-filter.outputs.db_release_scripts == 'true' + runs-on: ubuntu-latest + steps: + - name: Check for updates + run: echo "Updates are present in db_release_scripts directory, Triggering postgres-init repo" + - uses: 8398a7/action-slack@v3 + with: + status: ${{ job.status }} + fields: repo,message,commit,author,job,took,ref # selectable (default: repo,message) + env: + SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_DEVOPS }} # required + if: success() # Pick up events when the job is successful. + + # run only if not 'db_release_scripts' files were changed + - name: Check for no updates + if: needs.paths-filter.outputs.db_release_scripts != 'true' + run: echo "Updates are not present in db_release_scripts directory" + + # run only if 'db_scripts' files were changed + db_scripts_updates: + needs: paths-filter + if: needs.paths-filter.outputs.db_scripts == 'true' + runs-on: ubuntu-latest + steps: + - name: Check for updates + run: echo "Updates are present in db_scripts directory, Triggering postgres-init repo" + - uses: 8398a7/action-slack@v3 + with: + status: ${{ job.status }} + fields: repo,message,commit,author,job,took,ref # selectable (default: repo,message) + env: + SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_DEVOPS }} # required + if: success() # Pick up events when the job is successful. + + # run only if not 'db_scripts' files were changed + - name: Check for no updates + if: needs.paths-filter.outputs.db_scripts != 'true' + run: echo "Updates are not present in db_scripts directory" + + # This job is to trigger postgres-init repo. + trigger-postgres_init_repo: + runs-on: ubuntu-latest + steps: + - uses: peter-evans/repository-dispatch@v2 + with: + token: ${{ secrets.ACTION_PAT }} + repository: mosip/postgres-init + base: ${{ github.ref }} + event-type: db-event diff --git a/.github/workflows/push_trigger.yml b/.github/workflows/push_trigger.yml index 296b982e759..f9610ca2c03 100644 --- a/.github/workflows/push_trigger.yml +++ b/.github/workflows/push_trigger.yml @@ -1,4 +1,4 @@ -name: Maven Package upon a push +name: Maven Package upon a push on: pull_request: @@ -14,74 +14,202 @@ jobs: build: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v2 - - name: Set up JDK 11 - uses: actions/setup-java@v1 - with: - ref: ${{ github.ref }} - java-version: 11 - server-id: ossrh # Value of the distributionManagement/repository/id field of the pom.xml - settings-path: ${{ github.workspace }} # location for the settings.xml file - - - name: Setup branch and env - run: | - # Strip git ref prefix from version - echo "BRANCH_NAME=$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')" >> $GITHUB_ENV - echo "GPG_TTY=$(tty)" >> $GITHUB_ENV - - - name: Setup branch and GPG public key - run: | - # Strip git ref prefix from version - echo ${{ env.BRANCH_NAME }} - echo ${{ env.GPG_TTY }} - sudo apt-get --yes install gnupg2 - gpg2 --import ./.github/keys/mosipgpgkey_pub.gpg - gpg2 --quiet --batch --passphrase=${{secrets.gpg_secret}} --allow-secret-key-import --import ./.github/keys/mosipgpgkey_sec.gpg - - - uses: actions/cache@v1 - with: - path: ~/.m2/repository - key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }} - restore-keys: | - ${{ runner.os }}-maven-${{ env.BRANCH_NAME }} - - - name: Setup the settings file for ossrh server - run: echo " ossrh ${{secrets.ossrh_user}} ${{secrets.ossrh_secret}} ossrh true gpg2 ${{secrets.gpg_secret}} allow-snapshots true snapshots-repo https://oss.sonatype.org/content/repositories/snapshots false true releases-repo https://oss.sonatype.org/service/local/staging/deploy/maven2 true false sonar . https://sonarcloud.io false " > $GITHUB_WORKSPACE/settings.xml - - - name: Build with Maven - run: | - cd registration-processor - mvn -B package -s $GITHUB_WORKSPACE/settings.xml --file pom.xml - - - name: Ready the springboot artifacts - run: find -name '*.jar' -executable -type f -exec zip release.zip {} + - - - - name: Upload the springboot jars - uses: actions/upload-artifact@v1 - with: - name: release - path: ./release.zip - - - name: Build registration-processor-stage-group-1 image - - run: | - # The Mosip Stage Executor is not packaged as part of release.zip - cd "./$SERVICE_LOCATION" - docker build . --build-arg SOURCE=mosip --build-arg COMMIT_HASH=$(git rev-parse HEAD) --build-arg COMMIT_ID=$(git rev-parse --short HEAD) --build-arg BUILD_TIME=${{steps.date.outputs.date}} --file Dockerfile --tag $SERVICE_NAME - env: - SERVICE_NAME: registration-processor-stage-group-1 - SERVICE_LOCATION: registration-processor/stage-groups/registration-processor-stage-group-1 - - - name: Log into registry - run: echo "${{ secrets.release_docker_hub }}" | docker login -u ${{ secrets.actor_docker_hub }} --password-stdin - - - name: Push image - run: | + - uses: actions/checkout@v2 + - name: Set up JDK 11 + uses: actions/setup-java@v1 + with: + ref: ${{ github.ref }} + java-version: 11 + server-id: ossrh # Value of the distributionManagement/repository/id field of the pom.xml + settings-path: ${{ github.workspace }} # location for the settings.xml file + + - name: Setup branch and env + run: | + # Strip git ref prefix from version + echo "BRANCH_NAME=$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')" >> $GITHUB_ENV + echo "GPG_TTY=$(tty)" >> $GITHUB_ENV + - name: Setup branch and GPG public key + run: | + # Strip git ref prefix from version + echo ${{ env.BRANCH_NAME }} + echo ${{ env.GPG_TTY }} + sudo apt-get --yes install gnupg2 + gpg2 --import ./.github/keys/mosipgpgkey_pub.gpg + gpg2 --quiet --batch --passphrase=${{secrets.gpg_secret}} --allow-secret-key-import --import ./.github/keys/mosipgpgkey_sec.gpg + - uses: actions/cache@v1 + with: + path: ~/.m2/repository + key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }} + restore-keys: | + ${{ runner.os }}-maven-${{ env.BRANCH_NAME }} + - name: Setup the settings file for ossrh server + run: echo " ossrh ${{secrets.ossrh_user}} ${{secrets.ossrh_secret}} ossrh true gpg2 ${{secrets.gpg_secret}} allow-snapshots true snapshots-repo https://oss.sonatype.org/content/repositories/snapshots false true releases-repo https://oss.sonatype.org/service/local/staging/deploy/maven2 true false sonar . https://sonarcloud.io false " > $GITHUB_WORKSPACE/settings.xml + + - name: Build with Maven + run: | + cd registration-processor + mvn -B package -s $GITHUB_WORKSPACE/settings.xml --file pom.xml + - name: Ready the springboot artifacts + run: find -name '*.jar' -executable -type f -exec zip release.zip {} + + + + - name: Upload the springboot jars + uses: actions/upload-artifact@v1 + with: + name: release + path: ./release.zip + + publish_to_nexus: + if: "!contains(github.ref, 'master')" + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - name: Set up JDK 11 + uses: actions/setup-java@v1 + with: + ref: ${{ github.ref }} + java-version: 11 + server-id: ossrh # Value of the distributionManagement/repository/id field of the pom.xml + settings-path: ${{ github.workspace }} # location for the settings.xml file + - uses: actions/checkout@v2 + + - name: Setup branch and env + run: | + # Strip git ref prefix from version + echo "BRANCH_NAME=$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')" >> $GITHUB_ENV + echo "GPG_TTY=$(tty)" >> $GITHUB_ENV + - name: Setup branch and GPG public key + run: | + # Strip git ref prefix from version + echo ${{ env.BRANCH_NAME }} + echo ${{ env.GPG_TTY }} + sudo apt-get --yes install gnupg2 + gpg2 --import ./.github/keys/mosipgpgkey_pub.gpg + gpg2 --quiet --batch --passphrase=${{secrets.gpg_secret}} --allow-secret-key-import --import ./.github/keys/mosipgpgkey_sec.gpg + + - uses: actions/cache@v1 + with: + path: ~/.m2/repository + key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }} + restore-keys: | + ${{ runner.os }}-maven-${{ env.BRANCH_NAME }} + - name: Install xmllint + run: | + sudo apt-get update + sudo apt-get install libxml2-utils + - name: Setup the settings file for ossrh server + run: echo " ossrh ${{secrets.RELEASE_USER}} ${{secrets.RELEASE_TOKEN}} ossrh true gpg2 ${{secrets.gpg_secret}} allow-snapshots true snapshots-repo https://oss.sonatype.org/content/repositories/snapshots false true releases-repo https://oss.sonatype.org/service/local/staging/deploy/maven2 true false sonar . https://sonarcloud.io false " > $GITHUB_WORKSPACE/settings.xml + + - name: Publish the maven package + run: | + mvn deploy -DaltDeploymentRepository=ossrh::default::${{ secrets.RELEASE_URL }} -s $GITHUB_WORKSPACE/settings.xml -f pom.xml + env: + GITHUB_TOKEN: ${{ secrets.RELEASE_TOKEN }} + GPG_TTY: $(tty) + + docker-registration-processor-registration-transaction-service: + needs: build + runs-on: ubuntu-latest + env: + NAMESPACE: ${{ secrets.dev_namespace_docker_hub }} + SERVICE_NAME: registration-processor-registration-transaction-service + SERVICE_LOCATION: registration-processor/post-processor/registration-processor-registration-transaction-service + steps: + - uses: actions/checkout@v2 + - uses: actions/download-artifact@v1 + with: + name: release + path: ./ + + - name: Setup branch name + run: | + # Strip git ref prefix from version + echo "BRANCH_NAME=$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')" >> $GITHUB_ENV + - name: Get version info from pom + id: getPomVersion + uses: mavrosxristoforos/get-xml-info@1.0 + with: + xml-file: ./${{ env.SERVICE_LOCATION }}/pom.xml + xpath: /*[local-name()="project"]/*[local-name()="version"] + + - name: Unzip and extract the ${{ env.SERVICE_NAME }} + run: unzip -uj "release.zip" "${{ env.SERVICE_LOCATION }}/target/*" -d "./${{ env.SERVICE_LOCATION }}/target" + + - name: Get current date + id: date + run: echo "::set-output name=date::$(date +'%Y-%m-%d')" + + - name: Build image + run: | + cd "./${{env.SERVICE_LOCATION}}" + docker build . --build-arg SOURCE=mosip --build-arg COMMIT_HASH=$(git rev-parse HEAD) --build-arg COMMIT_ID=$(git rev-parse --short HEAD) --build-arg BUILD_TIME=${{steps.date.outputs.date}} --file Dockerfile --tag ${{ env.SERVICE_NAME }} + - name: Log into registry + run: echo "${{ secrets.release_docker_hub }}" | docker login -u ${{ secrets.actor_docker_hub }} --password-stdin + + - name: Push image + run: | IMAGE_ID=$NAMESPACE/$SERVICE_NAME + + # Change all uppercase to lowercase + IMAGE_ID=$(echo $IMAGE_ID | tr '[A-Z]' '[a-z]') + echo "push version ${{steps.getPomVersion.outputs.info}}" + if [[ $BRANCH_NAME == master ]]; then + VERSION=latest + else + VERSION=$BRANCH_NAME + fi + echo IMAGE_ID=$IMAGE_ID + echo VERSION=$VERSION + docker tag $SERVICE_NAME $IMAGE_ID:$VERSION + docker push $IMAGE_ID:$VERSION + + docker-registration-processor-stage-group-1: + needs: build + + runs-on: ubuntu-latest + env: + NAMESPACE: ${{ secrets.dev_namespace_docker_hub }} + SERVICE_NAME: registration-processor-stage-group-1 + SERVICE_LOCATION: registration-processor/stage-groups/registration-processor-stage-group-1 + + steps: + - uses: actions/checkout@v2 + - uses: actions/download-artifact@v1 + with: + name: release + path: ./ + + - name: Setup branch name + run: | + # Strip git ref prefix from version + echo "BRANCH_NAME=$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')" >> $GITHUB_ENV + - name: Get version info from pom + id: getPomVersion + uses: mavrosxristoforos/get-xml-info@1.0 + with: + xml-file: ./${{ env.SERVICE_LOCATION }}/pom.xml + xpath: /*[local-name()="project"]/*[local-name()="version"] + + - name: Unzip and extract the ${{ env.SERVICE_NAME }} + run: unzip -uj "release.zip" "${{ env.SERVICE_LOCATION }}/target/*" -d "./${{ env.SERVICE_LOCATION }}/target" + - name: Get current date + id: date + run: echo "::set-output name=date::$(date +'%Y-%m-%d')" + + - name: Build image + run: | + cd "./${{env.SERVICE_LOCATION}}" + docker build . --build-arg SOURCE=mosip --build-arg COMMIT_HASH=$(git rev-parse HEAD) --build-arg COMMIT_ID=$(git rev-parse --short HEAD) --build-arg BUILD_TIME=${{steps.date.outputs.date}} --file Dockerfile --tag ${{ env.SERVICE_NAME }} + - name: Log into registry + run: echo "${{ secrets.release_docker_hub }}" | docker login -u ${{ secrets.actor_docker_hub }} --password-stdin + + - name: Push image + run: | + IMAGE_ID=$NAMESPACE/$SERVICE_NAME # Change all uppercase to lowercase IMAGE_ID=$(echo $IMAGE_ID | tr '[A-Z]' '[a-z]') + echo "push version ${{steps.getPomVersion.outputs.info}}" if [[ $BRANCH_NAME == master ]]; then VERSION=latest else @@ -91,30 +219,111 @@ jobs: echo VERSION=$VERSION docker tag $SERVICE_NAME $IMAGE_ID:$VERSION docker push $IMAGE_ID:$VERSION - env: - NAMESPACE: ${{ secrets.dev_namespace_docker_hub }} - SERVICE_NAME: registration-processor-stage-group-1 - SERVICE_LOCATION: registration-processor/stage-groups/registration-processor-stage-group-1 - - - - name: Build registration-processor-stage-group-2 image - run: | - # The Mosip Stage Executor is not packaged as part of release.zip - cd "./$SERVICE_LOCATION" - docker build . --build-arg SOURCE=mosip --build-arg COMMIT_HASH=$(git rev-parse HEAD) --build-arg COMMIT_ID=$(git rev-parse --short HEAD) --build-arg BUILD_TIME=${{steps.date.outputs.date}} --file Dockerfile --tag $SERVICE_NAME - env: - SERVICE_NAME: registration-processor-stage-group-2 - SERVICE_LOCATION: registration-processor/stage-groups/registration-processor-stage-group-2 - - - name: Log into registry - run: echo "${{ secrets.release_docker_hub }}" | docker login -u ${{ secrets.actor_docker_hub }} --password-stdin - - - name: Push image - run: | + + docker-registration-processor-stage-group-2: + needs: build + + runs-on: ubuntu-latest + env: + NAMESPACE: ${{ secrets.dev_namespace_docker_hub }} + SERVICE_NAME: registration-processor-stage-group-2 + SERVICE_LOCATION: registration-processor/stage-groups/registration-processor-stage-group-2 + + steps: + - uses: actions/checkout@v2 + - uses: actions/download-artifact@v1 + with: + name: release + path: ./ + + - name: Setup branch name + run: | + # Strip git ref prefix from version + echo "BRANCH_NAME=$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')" >> $GITHUB_ENV + - name: Get version info from pom + id: getPomVersion + uses: mavrosxristoforos/get-xml-info@1.0 + with: + xml-file: ./${{ env.SERVICE_LOCATION }}/pom.xml + xpath: /*[local-name()="project"]/*[local-name()="version"] + + - name: Unzip and extract the ${{ env.SERVICE_NAME }} + run: unzip -uj "release.zip" "${{ env.SERVICE_LOCATION }}/target/*" -d "./${{ env.SERVICE_LOCATION }}/target" + + - name: Get current date + id: date + run: echo "::set-output name=date::$(date +'%Y-%m-%d')" + + - name: Build image + run: | + cd "./${{env.SERVICE_LOCATION}}" + docker build . --build-arg SOURCE=mosip --build-arg COMMIT_HASH=$(git rev-parse HEAD) --build-arg COMMIT_ID=$(git rev-parse --short HEAD) --build-arg BUILD_TIME=${{steps.date.outputs.date}} --file Dockerfile --tag ${{ env.SERVICE_NAME }} + - name: Log into registry + run: echo "${{ secrets.release_docker_hub }}" | docker login -u ${{ secrets.actor_docker_hub }} --password-stdin + + - name: Push image + run: | IMAGE_ID=$NAMESPACE/$SERVICE_NAME + # Change all uppercase to lowercase + IMAGE_ID=$(echo $IMAGE_ID | tr '[A-Z]' '[a-z]') + echo "push version ${{steps.getPomVersion.outputs.info}}" + if [[ $BRANCH_NAME == master ]]; then + VERSION=latest + else + VERSION=$BRANCH_NAME + fi + echo IMAGE_ID=$IMAGE_ID + echo VERSION=$VERSION + docker tag $SERVICE_NAME $IMAGE_ID:$VERSION + docker push $IMAGE_ID:$VERSION + docker-registration-processor-stage-group-3: + needs: build + + runs-on: ubuntu-latest + env: + NAMESPACE: ${{ secrets.dev_namespace_docker_hub }} + SERVICE_NAME: registration-processor-stage-group-3 + SERVICE_LOCATION: registration-processor/stage-groups/registration-processor-stage-group-3 + + steps: + - uses: actions/checkout@v2 + - uses: actions/download-artifact@v1 + with: + name: release + path: ./ + + - name: Setup branch name + run: | + # Strip git ref prefix from version + echo "BRANCH_NAME=$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')" >> $GITHUB_ENV + - name: Get version info from pom + id: getPomVersion + uses: mavrosxristoforos/get-xml-info@1.0 + with: + xml-file: ./${{ env.SERVICE_LOCATION }}/pom.xml + xpath: /*[local-name()="project"]/*[local-name()="version"] + + - name: Unzip and extract the ${{ env.SERVICE_NAME }} + run: unzip -uj "release.zip" "${{ env.SERVICE_LOCATION }}/target/*" -d "./${{ env.SERVICE_LOCATION }}/target" + + - name: Get current date + id: date + run: echo "::set-output name=date::$(date +'%Y-%m-%d')" + + - name: Build image + run: | + cd "./${{env.SERVICE_LOCATION}}" + docker build . --build-arg SOURCE=mosip --build-arg COMMIT_HASH=$(git rev-parse HEAD) --build-arg COMMIT_ID=$(git rev-parse --short HEAD) --build-arg BUILD_TIME=${{steps.date.outputs.date}} --file Dockerfile --tag ${{ env.SERVICE_NAME }} + - name: Log into registry + run: echo "${{ secrets.release_docker_hub }}" | docker login -u ${{ secrets.actor_docker_hub }} --password-stdin + + - name: Push image + run: | + IMAGE_ID=$NAMESPACE/$SERVICE_NAME # Change all uppercase to lowercase IMAGE_ID=$(echo $IMAGE_ID | tr '[A-Z]' '[a-z]') + echo "push version ${{steps.getPomVersion.outputs.info}}" if [[ $BRANCH_NAME == master ]]; then VERSION=latest else @@ -124,30 +333,54 @@ jobs: echo VERSION=$VERSION docker tag $SERVICE_NAME $IMAGE_ID:$VERSION docker push $IMAGE_ID:$VERSION - env: - NAMESPACE: ${{ secrets.dev_namespace_docker_hub }} - SERVICE_NAME: registration-processor-stage-group-2 - SERVICE_LOCATION: registration-processor/stage-groups/registration-processor-stage-group-2 - - - - name: Build registration-processor-stage-group-3 image - run: | - # The Mosip Stage Executor is not packaged as part of release.zip - cd "./$SERVICE_LOCATION" - docker build . --build-arg SOURCE=mosip --build-arg COMMIT_HASH=$(git rev-parse HEAD) --build-arg COMMIT_ID=$(git rev-parse --short HEAD) --build-arg BUILD_TIME=${{steps.date.outputs.date}} --file Dockerfile --tag $SERVICE_NAME - env: - SERVICE_NAME: registration-processor-stage-group-3 - SERVICE_LOCATION: registration-processor/stage-groups/registration-processor-stage-group-3 - - - name: Log into registry - run: echo "${{ secrets.release_docker_hub }}" | docker login -u ${{ secrets.actor_docker_hub }} --password-stdin - - - name: Push image - run: | + + docker-registration-processor-stage-group-4: + needs: build + + runs-on: ubuntu-latest + env: + NAMESPACE: ${{ secrets.dev_namespace_docker_hub }} + SERVICE_NAME: registration-processor-stage-group-4 + SERVICE_LOCATION: registration-processor/stage-groups/registration-processor-stage-group-4 + + steps: + - uses: actions/checkout@v2 + - uses: actions/download-artifact@v1 + with: + name: release + path: ./ + + - name: Setup branch name + run: | + # Strip git ref prefix from version + echo "BRANCH_NAME=$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')" >> $GITHUB_ENV + - name: Get version info from pom + id: getPomVersion + uses: mavrosxristoforos/get-xml-info@1.0 + with: + xml-file: ./${{ env.SERVICE_LOCATION }}/pom.xml + xpath: /*[local-name()="project"]/*[local-name()="version"] + + - name: Unzip and extract the ${{ env.SERVICE_NAME }} + run: unzip -uj "release.zip" "${{ env.SERVICE_LOCATION }}/target/*" -d "./${{ env.SERVICE_LOCATION }}/target" + + - name: Get current date + id: date + run: echo "::set-output name=date::$(date +'%Y-%m-%d')" + + - name: Build image + run: | + cd "./${{env.SERVICE_LOCATION}}" + docker build . --build-arg SOURCE=mosip --build-arg COMMIT_HASH=$(git rev-parse HEAD) --build-arg COMMIT_ID=$(git rev-parse --short HEAD) --build-arg BUILD_TIME=${{steps.date.outputs.date}} --file Dockerfile --tag ${{ env.SERVICE_NAME }} + - name: Log into registry + run: echo "${{ secrets.release_docker_hub }}" | docker login -u ${{ secrets.actor_docker_hub }} --password-stdin + + - name: Push image + run: | IMAGE_ID=$NAMESPACE/$SERVICE_NAME - # Change all uppercase to lowercase IMAGE_ID=$(echo $IMAGE_ID | tr '[A-Z]' '[a-z]') + echo "push version ${{steps.getPomVersion.outputs.info}}" if [[ $BRANCH_NAME == master ]]; then VERSION=latest else @@ -157,63 +390,54 @@ jobs: echo VERSION=$VERSION docker tag $SERVICE_NAME $IMAGE_ID:$VERSION docker push $IMAGE_ID:$VERSION - env: - NAMESPACE: ${{ secrets.dev_namespace_docker_hub }} - SERVICE_NAME: registration-processor-stage-group-3 - SERVICE_LOCATION: registration-processor/stage-groups/registration-processor-stage-group-3 - - - - name: Build registration-processor-stage-group-4 image - run: | - # The Mosip Stage Executor is not packaged as part of release.zip - cd "./$SERVICE_LOCATION" - docker build . --build-arg SOURCE=mosip --build-arg COMMIT_HASH=$(git rev-parse HEAD) --build-arg COMMIT_ID=$(git rev-parse --short HEAD) --build-arg BUILD_TIME=${{steps.date.outputs.date}} --file Dockerfile --tag $SERVICE_NAME - env: - SERVICE_NAME: registration-processor-stage-group-4 - SERVICE_LOCATION: registration-processor/stage-groups/registration-processor-stage-group-4 - - - name: Log into registry - run: echo "${{ secrets.release_docker_hub }}" | docker login -u ${{ secrets.actor_docker_hub }} --password-stdin - - - name: Push image - run: | - IMAGE_ID=$NAMESPACE/$SERVICE_NAME - # Change all uppercase to lowercase - IMAGE_ID=$(echo $IMAGE_ID | tr '[A-Z]' '[a-z]') - if [[ $BRANCH_NAME == master ]]; then - VERSION=latest - else - VERSION=$BRANCH_NAME - fi - echo IMAGE_ID=$IMAGE_ID - echo VERSION=$VERSION - docker tag $SERVICE_NAME $IMAGE_ID:$VERSION - docker push $IMAGE_ID:$VERSION - env: - NAMESPACE: ${{ secrets.dev_namespace_docker_hub }} - SERVICE_NAME: registration-processor-stage-group-4 - SERVICE_LOCATION: registration-processor/stage-groups/registration-processor-stage-group-4 - - - - name: Build registration-processor-stage-group-5 image - run: | - # The Mosip Stage Executor is not packaged as part of release.zip - cd "./$SERVICE_LOCATION" - docker build . --build-arg SOURCE=mosip --build-arg COMMIT_HASH=$(git rev-parse HEAD) --build-arg COMMIT_ID=$(git rev-parse --short HEAD) --build-arg BUILD_TIME=${{steps.date.outputs.date}} --file Dockerfile --tag $SERVICE_NAME - env: - SERVICE_NAME: registration-processor-stage-group-5 - SERVICE_LOCATION: registration-processor/stage-groups/registration-processor-stage-group-5 - - - name: Log into registry - run: echo "${{ secrets.release_docker_hub }}" | docker login -u ${{ secrets.actor_docker_hub }} --password-stdin - - - name: Push image - run: | - IMAGE_ID=$NAMESPACE/$SERVICE_NAME + docker-registration-processor-stage-group-5: + needs: build + + runs-on: ubuntu-latest + env: + NAMESPACE: ${{ secrets.dev_namespace_docker_hub }} + SERVICE_NAME: registration-processor-stage-group-5 + SERVICE_LOCATION: registration-processor/stage-groups/registration-processor-stage-group-5 + + steps: + - uses: actions/checkout@v2 + - uses: actions/download-artifact@v1 + with: + name: release + path: ./ + + - name: Setup branch name + run: | + # Strip git ref prefix from version + echo "BRANCH_NAME=$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')" >> $GITHUB_ENV + - name: Get version info from pom + id: getPomVersion + uses: mavrosxristoforos/get-xml-info@1.0 + with: + xml-file: ./${{ env.SERVICE_LOCATION }}/pom.xml + xpath: /*[local-name()="project"]/*[local-name()="version"] + + - name: Unzip and extract the ${{ env.SERVICE_NAME }} + run: unzip -uj "release.zip" "${{ env.SERVICE_LOCATION }}/target/*" -d "./${{ env.SERVICE_LOCATION }}/target" + + - name: Get current date + id: date + run: echo "::set-output name=date::$(date +'%Y-%m-%d')" + + - name: Build image + run: | + cd "./${{env.SERVICE_LOCATION}}" + docker build . --build-arg SOURCE=mosip --build-arg COMMIT_HASH=$(git rev-parse HEAD) --build-arg COMMIT_ID=$(git rev-parse --short HEAD) --build-arg BUILD_TIME=${{steps.date.outputs.date}} --file Dockerfile --tag ${{ env.SERVICE_NAME }} + - name: Log into registry + run: echo "${{ secrets.release_docker_hub }}" | docker login -u ${{ secrets.actor_docker_hub }} --password-stdin + - name: Push image + run: | + IMAGE_ID=$NAMESPACE/$SERVICE_NAME # Change all uppercase to lowercase IMAGE_ID=$(echo $IMAGE_ID | tr '[A-Z]' '[a-z]') + echo "push version ${{steps.getPomVersion.outputs.info}}" if [[ $BRANCH_NAME == master ]]; then VERSION=latest else @@ -223,61 +447,54 @@ jobs: echo VERSION=$VERSION docker tag $SERVICE_NAME $IMAGE_ID:$VERSION docker push $IMAGE_ID:$VERSION - env: - NAMESPACE: ${{ secrets.dev_namespace_docker_hub }} - SERVICE_NAME: registration-processor-stage-group-5 - SERVICE_LOCATION: registration-processor/stage-groups/registration-processor-stage-group-5 - - - name: Build registration-processor-stage-group-6 image - run: | - # The Mosip Stage Executor is not packaged as part of release.zip - cd "./$SERVICE_LOCATION" - docker build . --build-arg SOURCE=mosip --build-arg COMMIT_HASH=$(git rev-parse HEAD) --build-arg COMMIT_ID=$(git rev-parse --short HEAD) --build-arg BUILD_TIME=${{steps.date.outputs.date}} --file Dockerfile --tag $SERVICE_NAME - env: - SERVICE_NAME: registration-processor-stage-group-6 - SERVICE_LOCATION: registration-processor/stage-groups/registration-processor-stage-group-6 - - name: Log into registry - run: echo "${{ secrets.release_docker_hub }}" | docker login -u ${{ secrets.actor_docker_hub }} --password-stdin - - - name: Push image - run: | - IMAGE_ID=$NAMESPACE/$SERVICE_NAME - - # Change all uppercase to lowercase - IMAGE_ID=$(echo $IMAGE_ID | tr '[A-Z]' '[a-z]') - if [[ $BRANCH_NAME == master ]]; then - VERSION=latest - else - VERSION=$BRANCH_NAME - fi - echo IMAGE_ID=$IMAGE_ID - echo VERSION=$VERSION - docker tag $SERVICE_NAME $IMAGE_ID:$VERSION - docker push $IMAGE_ID:$VERSION - env: - NAMESPACE: ${{ secrets.dev_namespace_docker_hub }} - SERVICE_NAME: registration-processor-stage-group-6 - SERVICE_LOCATION: registration-processor/stage-groups/registration-processor-stage-group-6 - - - - name: Build registration-processor-stage-group-7 image - run: | - # The Mosip Stage Executor is not packaged as part of release.zip - cd "./$SERVICE_LOCATION" - docker build . --build-arg SOURCE=mosip --build-arg COMMIT_HASH=$(git rev-parse HEAD) --build-arg COMMIT_ID=$(git rev-parse --short HEAD) --build-arg BUILD_TIME=${{steps.date.outputs.date}} --file Dockerfile --tag $SERVICE_NAME - env: - SERVICE_NAME: registration-processor-stage-group-7 - SERVICE_LOCATION: registration-processor/stage-groups/registration-processor-stage-group-7 - - - name: Log into registry - run: echo "${{ secrets.release_docker_hub }}" | docker login -u ${{ secrets.actor_docker_hub }} --password-stdin - - - name: Push image - run: | - IMAGE_ID=$NAMESPACE/$SERVICE_NAME + docker-registration-processor-stage-group-6: + needs: build + + runs-on: ubuntu-latest + env: + NAMESPACE: ${{ secrets.dev_namespace_docker_hub }} + SERVICE_NAME: registration-processor-stage-group-6 + SERVICE_LOCATION: registration-processor/stage-groups/registration-processor-stage-group-6 + + steps: + - uses: actions/checkout@v2 + - uses: actions/download-artifact@v1 + with: + name: release + path: ./ + + - name: Setup branch name + run: | + # Strip git ref prefix from version + echo "BRANCH_NAME=$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')" >> $GITHUB_ENV + - name: Get version info from pom + id: getPomVersion + uses: mavrosxristoforos/get-xml-info@1.0 + with: + xml-file: ./${{ env.SERVICE_LOCATION }}/pom.xml + xpath: /*[local-name()="project"]/*[local-name()="version"] + + - name: Unzip and extract the ${{ env.SERVICE_NAME }} + run: unzip -uj "release.zip" "${{ env.SERVICE_LOCATION }}/target/*" -d "./${{ env.SERVICE_LOCATION }}/target" + + - name: Get current date + id: date + run: echo "::set-output name=date::$(date +'%Y-%m-%d')" + + - name: Build image + run: | + cd "./${{env.SERVICE_LOCATION}}" + docker build . --build-arg SOURCE=mosip --build-arg COMMIT_HASH=$(git rev-parse HEAD) --build-arg COMMIT_ID=$(git rev-parse --short HEAD) --build-arg BUILD_TIME=${{steps.date.outputs.date}} --file Dockerfile --tag ${{ env.SERVICE_NAME }} + - name: Log into registry + run: echo "${{ secrets.release_docker_hub }}" | docker login -u ${{ secrets.actor_docker_hub }} --password-stdin + + - name: Push image + run: | + IMAGE_ID=$NAMESPACE/$SERVICE_NAME # Change all uppercase to lowercase IMAGE_ID=$(echo $IMAGE_ID | tr '[A-Z]' '[a-z]') + echo "push version ${{steps.getPomVersion.outputs.info}}" if [[ $BRANCH_NAME == master ]]; then VERSION=latest else @@ -287,101 +504,16 @@ jobs: echo VERSION=$VERSION docker tag $SERVICE_NAME $IMAGE_ID:$VERSION docker push $IMAGE_ID:$VERSION - env: - NAMESPACE: ${{ secrets.dev_namespace_docker_hub }} - SERVICE_NAME: registration-processor-stage-group-7 - SERVICE_LOCATION: registration-processor/stage-groups/registration-processor-stage-group-7 - - - name: Get current date - id: date - run: echo "::set-output name=date::$(date +'%Y-%m-%d')" - - - name: Build camel bridge image - run: | - # The camel bridge is not packaged as part of release.zip - cd "./registration-processor/registration-processor-common-camel-bridge" - docker build . --build-arg SOURCE=mosip --build-arg COMMIT_HASH=$(git rev-parse HEAD) --build-arg COMMIT_ID=$(git rev-parse --short HEAD) --build-arg BUILD_TIME=${{steps.date.outputs.date}} --file Dockerfile --tag registration-processor-common-camel-bridge - - name: Log into registry - run: echo "${{ secrets.release_docker_hub }}" | docker login -u ${{ secrets.actor_docker_hub }} --password-stdin - - - name: Push image - run: | - IMAGE_ID=$NAMESPACE/$SERVICE_NAME - - # Change all uppercase to lowercase - IMAGE_ID=$(echo $IMAGE_ID | tr '[A-Z]' '[a-z]') - if [[ $BRANCH_NAME == master ]]; then - VERSION=latest - else - VERSION=$BRANCH_NAME - fi - echo IMAGE_ID=$IMAGE_ID - echo VERSION=$VERSION - docker tag $SERVICE_NAME $IMAGE_ID:$VERSION - docker push $IMAGE_ID:$VERSION - env: - NAMESPACE: ${{ secrets.dev_namespace_docker_hub }} - SERVICE_NAME: registration-processor-common-camel-bridge - SERVICE_LOCATION: registration-processor/registration-processor-common-camel-bridge - - publish_to_nexus: - if: "!contains(github.ref, 'master')" - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v2 - - name: Set up JDK 11 - uses: actions/setup-java@v1 - with: - ref: ${{ github.ref }} - java-version: 11 - server-id: ossrh # Value of the distributionManagement/repository/id field of the pom.xml - settings-path: ${{ github.workspace }} # location for the settings.xml file - - uses: actions/checkout@v2 - - - name: Setup branch and env - run: | - # Strip git ref prefix from version - echo "BRANCH_NAME=$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')" >> $GITHUB_ENV - echo "GPG_TTY=$(tty)" >> $GITHUB_ENV - - - name: Setup branch and GPG public key - run: | - # Strip git ref prefix from version - echo ${{ env.BRANCH_NAME }} - echo ${{ env.GPG_TTY }} - sudo apt-get --yes install gnupg2 - gpg2 --import ./.github/keys/mosipgpgkey_pub.gpg - gpg2 --quiet --batch --passphrase=${{secrets.gpg_secret}} --allow-secret-key-import --import ./.github/keys/mosipgpgkey_sec.gpg - - - uses: actions/cache@v1 - with: - path: ~/.m2/repository - key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }} - restore-keys: | - ${{ runner.os }}-maven-${{ env.BRANCH_NAME }} - - - name: Install xmllint - run: | - sudo apt-get update - sudo apt-get install libxml2-utils - - - name: Setup the settings file for ossrh server - run: echo " ossrh ${{secrets.RELEASE_USER}} ${{secrets.RELEASE_TOKEN}} ossrh true gpg2 ${{secrets.gpg_secret}} allow-snapshots true snapshots-repo https://oss.sonatype.org/content/repositories/snapshots false true releases-repo https://oss.sonatype.org/service/local/staging/deploy/maven2 true false sonar . https://sonarcloud.io false " > $GITHUB_WORKSPACE/settings.xml - - - name: Publish the maven package - run: | - mvn deploy -DaltDeploymentRepository=ossrh::default::${{ secrets.RELEASE_URL }} -s $GITHUB_WORKSPACE/settings.xml -f pom.xml - env: - GITHUB_TOKEN: ${{ secrets.RELEASE_TOKEN }} - GPG_TTY: $(tty) - docker-registration-processor-registration-transaction-service: + docker-registration-processor-stage-group-7: needs: build + runs-on: ubuntu-latest env: - NAMESPACE: mosipdev - SERVICE_NAME: registration-processor-registration-transaction-service - SERVICE_LOCATION: registration-processor/post-processor/registration-processor-registration-transaction-service + NAMESPACE: ${{ secrets.dev_namespace_docker_hub }} + SERVICE_NAME: registration-processor-stage-group-7 + SERVICE_LOCATION: registration-processor/stage-groups/registration-processor-stage-group-7 + steps: - uses: actions/checkout@v2 - uses: actions/download-artifact@v1 @@ -393,14 +525,13 @@ jobs: run: | # Strip git ref prefix from version echo "BRANCH_NAME=$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')" >> $GITHUB_ENV - - name: Get version info from pom id: getPomVersion uses: mavrosxristoforos/get-xml-info@1.0 with: - xml-file: ./${{ env.SERVICE_LOCATION }}/pom.xml - xpath: /*[local-name()="project"]/*[local-name()="version"] - + xml-file: ./${{ env.SERVICE_LOCATION }}/pom.xml + xpath: /*[local-name()="project"]/*[local-name()="version"] + - name: Unzip and extract the ${{ env.SERVICE_NAME }} run: unzip -uj "release.zip" "${{ env.SERVICE_LOCATION }}/target/*" -d "./${{ env.SERVICE_LOCATION }}/target" @@ -414,11 +545,10 @@ jobs: docker build . --build-arg SOURCE=mosip --build-arg COMMIT_HASH=$(git rev-parse HEAD) --build-arg COMMIT_ID=$(git rev-parse --short HEAD) --build-arg BUILD_TIME=${{steps.date.outputs.date}} --file Dockerfile --tag ${{ env.SERVICE_NAME }} - name: Log into registry run: echo "${{ secrets.release_docker_hub }}" | docker login -u ${{ secrets.actor_docker_hub }} --password-stdin - + - name: Push image run: | IMAGE_ID=$NAMESPACE/$SERVICE_NAME - # Change all uppercase to lowercase IMAGE_ID=$(echo $IMAGE_ID | tr '[A-Z]' '[a-z]') echo "push version ${{steps.getPomVersion.outputs.info}}" @@ -431,13 +561,13 @@ jobs: echo VERSION=$VERSION docker tag $SERVICE_NAME $IMAGE_ID:$VERSION docker push $IMAGE_ID:$VERSION - + docker-registration-processor-abis: needs: build runs-on: ubuntu-latest env: - NAMESPACE: mosipdev + NAMESPACE: ${{ secrets.dev_namespace_docker_hub }} SERVICE_NAME: registration-processor-abis SERVICE_LOCATION: registration-processor/core-processor/registration-processor-abis @@ -452,14 +582,13 @@ jobs: run: | # Strip git ref prefix from version echo "BRANCH_NAME=$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')" >> $GITHUB_ENV - - name: Get version info from pom id: getPomVersion uses: mavrosxristoforos/get-xml-info@1.0 with: - xml-file: ./${{ env.SERVICE_LOCATION }}/pom.xml - xpath: /*[local-name()="project"]/*[local-name()="version"] - + xml-file: ./${{ env.SERVICE_LOCATION }}/pom.xml + xpath: /*[local-name()="project"]/*[local-name()="version"] + - name: Unzip and extract the ${{ env.SERVICE_NAME }} run: unzip -uj "release.zip" "${{ env.SERVICE_LOCATION }}/target/*" -d "./${{ env.SERVICE_LOCATION }}/target" @@ -473,7 +602,7 @@ jobs: docker build . --build-arg SOURCE=mosip --build-arg COMMIT_HASH=$(git rev-parse HEAD) --build-arg COMMIT_ID=$(git rev-parse --short HEAD) --build-arg BUILD_TIME=${{steps.date.outputs.date}} --file Dockerfile --tag ${{ env.SERVICE_NAME }} - name: Log into registry run: echo "${{ secrets.release_docker_hub }}" | docker login -u ${{ secrets.actor_docker_hub }} --password-stdin - + - name: Push image run: | IMAGE_ID=$NAMESPACE/$SERVICE_NAME @@ -490,13 +619,13 @@ jobs: echo VERSION=$VERSION docker tag $SERVICE_NAME $IMAGE_ID:$VERSION docker push $IMAGE_ID:$VERSION - + docker-registration-processor-reprocessor: needs: build runs-on: ubuntu-latest env: - NAMESPACE: mosipdev + NAMESPACE: ${{ secrets.dev_namespace_docker_hub }} SERVICE_NAME: registration-processor-reprocessor SERVICE_LOCATION: registration-processor/workflow-engine/registration-processor-reprocessor @@ -515,12 +644,12 @@ jobs: id: getPomVersion uses: mavrosxristoforos/get-xml-info@1.0 with: - xml-file: ./${{ env.SERVICE_LOCATION }}/pom.xml - xpath: /*[local-name()="project"]/*[local-name()="version"] - + xml-file: ./${{ env.SERVICE_LOCATION }}/pom.xml + xpath: /*[local-name()="project"]/*[local-name()="version"] + - name: Unzip and extract the ${{ env.SERVICE_NAME }} run: unzip -uj "release.zip" "${{ env.SERVICE_LOCATION }}/target/*" -d "./${{ env.SERVICE_LOCATION }}/target" - + - name: Get current date id: date run: echo "::set-output name=date::$(date +'%Y-%m-%d')" @@ -531,7 +660,7 @@ jobs: docker build . --build-arg SOURCE=mosip --build-arg COMMIT_HASH=$(git rev-parse HEAD) --build-arg COMMIT_ID=$(git rev-parse --short HEAD) --build-arg BUILD_TIME=${{steps.date.outputs.date}} --file Dockerfile --tag ${{ env.SERVICE_NAME }} - name: Log into registry run: echo "${{ secrets.release_docker_hub }}" | docker login -u ${{ secrets.actor_docker_hub }} --password-stdin - + - name: Push image run: | IMAGE_ID=$NAMESPACE/$SERVICE_NAME @@ -548,13 +677,12 @@ jobs: echo VERSION=$VERSION docker tag $SERVICE_NAME $IMAGE_ID:$VERSION docker push $IMAGE_ID:$VERSION - docker-registration-processor-dmz-packet-server: needs: build runs-on: ubuntu-latest env: - NAMESPACE: mosipdev + NAMESPACE: ${{ secrets.dev_namespace_docker_hub }} SERVICE_NAME: registration-processor-dmz-packet-server SERVICE_LOCATION: registration-processor/init/registration-processor-dmz-packet-server @@ -565,7 +693,6 @@ jobs: run: | # Strip git ref prefix from version echo "BRANCH_NAME=$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')" >> $GITHUB_ENV - - name: Get version info id: getVersion uses: mavrosxristoforos/get-xml-info@1.0 @@ -583,7 +710,7 @@ jobs: docker build . --build-arg SOURCE=mosip --build-arg COMMIT_HASH=$(git rev-parse HEAD) --build-arg COMMIT_ID=$(git rev-parse --short HEAD) --build-arg BUILD_TIME=${{steps.date.outputs.date}} --file Dockerfile --tag ${{ env.SERVICE_NAME }} - name: Log into registry run: echo "${{ secrets.release_docker_hub }}" | docker login -u ${{ secrets.actor_docker_hub }} --password-stdin - + - name: Push image run: | IMAGE_ID=$NAMESPACE/$SERVICE_NAME @@ -596,13 +723,12 @@ jobs: echo VERSION=$VERSION docker tag $SERVICE_NAME $IMAGE_ID:$VERSION docker push $IMAGE_ID:$VERSION - docker-registration-processor-registration-status-service: needs: build runs-on: ubuntu-latest env: - NAMESPACE: mosipdev + NAMESPACE: ${{ secrets.dev_namespace_docker_hub }} SERVICE_NAME: registration-processor-registration-status-service SERVICE_LOCATION: registration-processor/init/registration-processor-registration-status-service @@ -617,17 +743,16 @@ jobs: run: | # Strip git ref prefix from version echo "BRANCH_NAME=$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')" >> $GITHUB_ENV - - name: Get version info from pom id: getPomVersion uses: mavrosxristoforos/get-xml-info@1.0 with: - xml-file: ./${{ env.SERVICE_LOCATION }}/pom.xml - xpath: /*[local-name()="project"]/*[local-name()="version"] - + xml-file: ./${{ env.SERVICE_LOCATION }}/pom.xml + xpath: /*[local-name()="project"]/*[local-name()="version"] + - name: Unzip and extract the ${{ env.SERVICE_NAME }} run: unzip -uj "release.zip" "${{ env.SERVICE_LOCATION }}/target/*" -d "./${{ env.SERVICE_LOCATION }}/target" - + - name: Get current date id: date run: echo "::set-output name=date::$(date +'%Y-%m-%d')" @@ -638,7 +763,7 @@ jobs: docker build . --build-arg SOURCE=mosip --build-arg COMMIT_HASH=$(git rev-parse HEAD) --build-arg COMMIT_ID=$(git rev-parse --short HEAD) --build-arg BUILD_TIME=${{steps.date.outputs.date}} --file Dockerfile --tag ${{ env.SERVICE_NAME }} - name: Log into registry run: echo "${{ secrets.release_docker_hub }}" | docker login -u ${{ secrets.actor_docker_hub }} --password-stdin - + - name: Push image run: | IMAGE_ID=$NAMESPACE/$SERVICE_NAME @@ -655,13 +780,12 @@ jobs: echo VERSION=$VERSION docker tag $SERVICE_NAME $IMAGE_ID:$VERSION docker push $IMAGE_ID:$VERSION - docker-registration-processor-notification-service: needs: build runs-on: ubuntu-latest env: - NAMESPACE: mosipdev + NAMESPACE: ${{ secrets.dev_namespace_docker_hub }} SERVICE_NAME: registration-processor-notification-service SERVICE_LOCATION: registration-processor/registration-processor-notification-service @@ -676,7 +800,6 @@ jobs: run: | # Strip git ref prefix from version echo "BRANCH_NAME=$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')" >> $GITHUB_ENV - - name: Get version info from pom id: getPomVersion uses: mavrosxristoforos/get-xml-info@1.0 @@ -701,7 +824,62 @@ jobs: - name: Push image run: | IMAGE_ID=$NAMESPACE/$SERVICE_NAME + # Change all uppercase to lowercase + IMAGE_ID=$(echo $IMAGE_ID | tr '[A-Z]' '[a-z]') + echo "push version ${{steps.getPomVersion.outputs.info}}" + if [[ $BRANCH_NAME == master ]]; then + VERSION=latest + else + VERSION=$BRANCH_NAME + fi + echo IMAGE_ID=$IMAGE_ID + echo VERSION=$VERSION + docker tag $SERVICE_NAME $IMAGE_ID:$VERSION + docker push $IMAGE_ID:$VERSION + docker-registration-processor-landing-zone: + needs: build + + runs-on: ubuntu-latest + env: + NAMESPACE: ${{ secrets.dev_namespace_docker_hub }} + SERVICE_NAME: registration-processor-landing-zone + SERVICE_LOCATION: registration-processor/registration-processor-landing-zone + + steps: + - uses: actions/checkout@v2 + - uses: actions/download-artifact@v1 + with: + name: release + path: ./ + + - name: Setup branch name + run: | + # Strip git ref prefix from version + echo "BRANCH_NAME=$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')" >> $GITHUB_ENV + - name: Get version info from pom + id: getPomVersion + uses: mavrosxristoforos/get-xml-info@1.0 + with: + xml-file: ./${{ env.SERVICE_LOCATION }}/pom.xml + xpath: /*[local-name()="project"]/*[local-name()="version"] + + - name: Unzip and extract the ${{ env.SERVICE_NAME }} + run: unzip -uj "release.zip" "${{ env.SERVICE_LOCATION }}/target/*" -d "./${{ env.SERVICE_LOCATION }}/target" + + - name: Get current date + id: date + run: echo "::set-output name=date::$(date +'%Y-%m-%d')" + + - name: Build image + run: | + cd "./${{env.SERVICE_LOCATION}}" + docker build . --build-arg SOURCE=mosip --build-arg COMMIT_HASH=$(git rev-parse HEAD) --build-arg COMMIT_ID=$(git rev-parse --short HEAD) --build-arg BUILD_TIME=${{steps.date.outputs.date}} --file Dockerfile --tag ${{ env.SERVICE_NAME }} + - name: Log into registry + run: echo "${{ secrets.release_docker_hub }}" | docker login -u ${{ secrets.actor_docker_hub }} --password-stdin + - name: Push image + run: | + IMAGE_ID=$NAMESPACE/$SERVICE_NAME # Change all uppercase to lowercase IMAGE_ID=$(echo $IMAGE_ID | tr '[A-Z]' '[a-z]') echo "push version ${{steps.getPomVersion.outputs.info}}" @@ -720,7 +898,7 @@ jobs: runs-on: ubuntu-latest env: - NAMESPACE: mosipdev + NAMESPACE: ${{ secrets.dev_namespace_docker_hub }} SERVICE_NAME: registration-processor-workflow-manager-service SERVICE_LOCATION: registration-processor/workflow-engine/registration-processor-workflow-manager-service @@ -735,7 +913,6 @@ jobs: run: | # Strip git ref prefix from version echo "BRANCH_NAME=$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')" >> $GITHUB_ENV - - name: Get version info from pom id: getPomVersion uses: mavrosxristoforos/get-xml-info@1.0 @@ -760,7 +937,6 @@ jobs: - name: Push image run: | IMAGE_ID=$NAMESPACE/$SERVICE_NAME - # Change all uppercase to lowercase IMAGE_ID=$(echo $IMAGE_ID | tr '[A-Z]' '[a-z]') echo "push version ${{steps.getPomVersion.outputs.info}}" @@ -773,11 +949,68 @@ jobs: echo VERSION=$VERSION docker tag $SERVICE_NAME $IMAGE_ID:$VERSION docker push $IMAGE_ID:$VERSION + registration-processor-common-camel-bridge: + needs: build + + runs-on: ubuntu-latest + env: + NAMESPACE: ${{ secrets.dev_namespace_docker_hub }} + SERVICE_NAME: registration-processor-common-camel-bridge + SERVICE_LOCATION: registration-processor/registration-processor-common-camel-bridge + + steps: + - uses: actions/checkout@v2 + - uses: actions/download-artifact@v1 + with: + name: release + path: ./ + + - name: Setup branch name + run: | + # Strip git ref prefix from version + echo "BRANCH_NAME=$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')" >> $GITHUB_ENV + - name: Get version info from pom + id: getPomVersion + uses: mavrosxristoforos/get-xml-info@1.0 + with: + xml-file: ./${{ env.SERVICE_LOCATION }}/pom.xml + xpath: /*[local-name()="project"]/*[local-name()="version"] + + - name: Unzip and extract the ${{ env.SERVICE_NAME }} + run: unzip -uj "release.zip" "${{ env.SERVICE_LOCATION }}/target/*" -d "./${{ env.SERVICE_LOCATION }}/target" + + - name: Get current date + id: date + run: echo "::set-output name=date::$(date +'%Y-%m-%d')" + + - name: Build image + run: | + cd "./${{env.SERVICE_LOCATION}}" + docker build . --build-arg SOURCE=mosip --build-arg COMMIT_HASH=$(git rev-parse HEAD) --build-arg COMMIT_ID=$(git rev-parse --short HEAD) --build-arg BUILD_TIME=${{steps.date.outputs.date}} --file Dockerfile --tag ${{ env.SERVICE_NAME }} + - name: Log into registry + run: echo "${{ secrets.release_docker_hub }}" | docker login -u ${{ secrets.actor_docker_hub }} --password-stdin + + - name: Push image + run: | + IMAGE_ID=$NAMESPACE/$SERVICE_NAME + # Change all uppercase to lowercase + IMAGE_ID=$(echo $IMAGE_ID | tr '[A-Z]' '[a-z]') + echo "push version ${{steps.getPomVersion.outputs.info}}" + if [[ $BRANCH_NAME == master ]]; then + VERSION=latest + else + VERSION=$BRANCH_NAME + fi + echo IMAGE_ID=$IMAGE_ID + echo VERSION=$VERSION + docker tag $SERVICE_NAME $IMAGE_ID:$VERSION + docker push $IMAGE_ID:$VERSION + sonar_analysis: runs-on: ubuntu-latest env: - NAMESPACE: mosipdev + NAMESPACE: ${{ secrets.dev_namespace_docker_hub }} SERVICE_NAME: registration-client SERVICE_LOCATION: registration steps: @@ -795,7 +1028,7 @@ jobs: # Strip git ref prefix from version echo "BRANCH_NAME=$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')" >> $GITHUB_ENV echo "GPG_TTY=$(tty)" >> $GITHUB_ENV - + - uses: actions/cache@v1 with: path: ~/.m2/repository @@ -803,13 +1036,13 @@ jobs: restore-keys: | ${{ runner.os }}-maven-${{ env.BRANCH_NAME }} - name: Setup the settings file for ossrh server - run: echo " ossrh ${{secrets.ossrh_user}} ${{secrets.ossrh_secret}} ossrh true gpg2 ${{secrets.gpg_secret}} allow-snapshots true snapshots-repo https://oss.sonatype.org/content/repositories/snapshots false true releases-repo https://oss.sonatype.org/service/local/staging/deploy/maven2 true false staged-releases https://oss.sonatype.org/service/local/staging/deploy/maven2/ sonar . https://sonarcloud.io false " > $GITHUB_WORKSPACE/settings.xml + run: echo " ossrh ${{secrets.ossrh_user}} ${{secrets.ossrh_secret}} ossrh true gpg2 ${{secrets.gpg_secret}} allow-snapshots true snapshots-repo https://oss.sonatype.org/content/repositories/snapshots false true releases-repo https://oss.sonatype.org/service/local/staging/deploy/maven2 true false staged-releases https://oss.sonatype.org/service/local/staging/deploy/maven2/ sonar . https://sonarcloud.io false " > $GITHUB_WORKSPACE/settings.xml - name: Install xmllint run: | sudo apt-get update sudo apt-get install libxml2-utils - + - name: Analyze with SonarCloud run: | cd registration-processor @@ -824,4 +1057,4 @@ jobs: fields: repo,message,author,ref,job # selectable (default: repo,message) env: SLACK_WEBHOOK_URL: ${{ secrets.SLACK_DEVOPS_WEBHOOK }} # required - if: failure() # Pick up events even if the job fails or is canceled. + if: failure() # Pick up events even if the job fails or is canceled. diff --git a/.github/workflows/release_trigger.yml b/.github/workflows/release_trigger.yml index 65e33e700e7..08bef64e9a0 100644 --- a/.github/workflows/release_trigger.yml +++ b/.github/workflows/release_trigger.yml @@ -633,6 +633,58 @@ jobs: echo VERSION=$VERSION docker tag $SERVICE_NAME $IMAGE_ID:$VERSION docker push $IMAGE_ID:$VERSION + + docker-registration-processor-landing-zone: + needs: build + + runs-on: ubuntu-latest + env: + NAMESPACE: mosipdev + SERVICE_NAME: registration-processor-landing-zone + SERVICE_LOCATION: registration-processor/registration-processor-landing-zone + + steps: + - uses: actions/checkout@v2 + - uses: actions/download-artifact@v1 + with: + name: release + path: ./ + + - name: Setup branch name + run: | + # Strip git ref prefix from version + echo "::set-env name=BRANCH_NAME::$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')" + echo ${{ env.BRANCH_NAME }} + + - name: Get version info from pom + id: getPomVersion + uses: mavrosxristoforos/get-xml-info@1.0 + with: + xml-file: ./${{ env.SERVICE_LOCATION }}/pom.xml + xpath: /*[local-name()="project"]/*[local-name()="version"] + + - name: Unzip and extract the ${{ env.SERVICE_NAME }} + run: unzip -uj "release.zip" "${{ env.SERVICE_LOCATION }}/target/*" -d "./${{ env.SERVICE_LOCATION }}/target" + + - name: Build image + run: | + cd "./${{env.SERVICE_LOCATION}}" + docker build . --file Dockerfile --tag ${{ env.SERVICE_NAME }} + - name: Log into registry + run: echo "${{ secrets.release_docker_hub }}" | docker login -u ${{ secrets.actor_docker_hub }} --password-stdin + + - name: Push image + run: | + IMAGE_ID=$NAMESPACE/$SERVICE_NAME + + # Change all uppercase to lowercase + IMAGE_ID=$(echo $IMAGE_ID | tr '[A-Z]' '[a-z]') + echo "push version ${{steps.getPomVersion.outputs.info}}" + VERSION=$BRANCH_NAME + echo IMAGE_ID=$IMAGE_ID + echo VERSION=$VERSION + docker tag $SERVICE_NAME $IMAGE_ID:$VERSION + docker push $IMAGE_ID:$VERSION docker-registration-processor-workflow-manager-service: needs: build diff --git a/db_scripts/README.md b/db_scripts/README.md index 9dd9638d7e7..272e60f5f77 100644 --- a/db_scripts/README.md +++ b/db_scripts/README.md @@ -6,4 +6,3 @@ This folder containers various SQL scripts to create database and tables in post This folder containers various SQL scripts to create database and tables in postgres. These scripts are automatically run with as part of DB initialisation in [Sandbox Deployment](https://docs.mosip.io/1.2.0/deployment/sandbox-deployment) Developers may run the SQLs using `/deploy.sh` script. - diff --git a/db_upgrade_scripts/README.MD b/db_upgrade_scripts/README.MD index 9153c9fd757..def2e70933e 100644 --- a/db_upgrade_scripts/README.MD +++ b/db_upgrade_scripts/README.MD @@ -25,7 +25,7 @@ * If are pulling to local system from Git repository and pushing them back to deployment server using WinSCP then make a note to modify the following encoding settings in WinSCP before pushing the files to deployment server --> Open WinSCP --> Options --> Preferences --> Transfer --> Edit --> In "Transfer mode" section --> select "Text" --> Click Ok --> Click Ok -## Each release database folder has the following files / folders +## Each release database folder has the following files and folders * **mosip_/ddl folder:** Contains table creation scripts for the release. diff --git a/docs/stage-local-development.md b/docs/stage-local-development.md new file mode 100644 index 00000000000..566f1f623fc --- /dev/null +++ b/docs/stage-local-development.md @@ -0,0 +1,106 @@ +## Steps to run registration processor stages in local development machine: + +1. Copy the below content and create a new file called docker-compose.yml +``` +version: "2" + +services: + zookeeper: + image: docker.io/bitnami/zookeeper:3.7.0-debian-10-r0 + ports: + - "2181:2181" + volumes: + - "zookeeper_data:/bitnami" + environment: + - ALLOW_ANONYMOUS_LOGIN=yes + kafka: + image: docker.io/bitnami/kafka:2.8.0-debian-10-r0 + ports: + - "9092:9092" + - "29092:29092" + volumes: + - "kafka_data:/bitnami" + environment: + - KAFKA_CFG_ZOOKEEPER_CONNECT=zookeeper:2181 + - ALLOW_PLAINTEXT_LISTENER=yes + - KAFKA_LISTENER_SECURITY_PROTOCOL_MAP=PLAINTEXT:PLAINTEXT,PLAINTEXT_HOST:PLAINTEXT + - KAFKA_LISTENERS=PLAINTEXT://:29092,PLAINTEXT_HOST://0.0.0.0:9092 + - KAFKA_ADVERTISED_LISTENERS=PLAINTEXT://kafka:29092,PLAINTEXT_HOST://localhost:9092 + depends_on: + - zookeeper + kafka-ui: + image: provectuslabs/kafka-ui + container_name: kafka-ui + ports: + - "8080:8080" + restart: always + environment: + - KAFKA_CLUSTERS_0_NAME=local + - KAFKA_CLUSTERS_0_BOOTSTRAPSERVERS=kafka:29092 + - KAFKA_CLUSTERS_0_ZOOKEEPER=zookeeper:2181 + depends_on: + - kafka +volumes: + zookeeper_data: + driver: local + kafka_data: + driver: local + +``` +2. Use the below command to start the docker compose to run kafka, zookeeper and kafka-ui dockers together. Docker compose and docker should be pre-installed. +``` +docker-compose up +``` +3. Edit the below property in registration-processor-default.properties file to connect to the kafka running in the docker compose. +``` +mosip.regproc.eventbus.kafka.bootstrap.servers=localhost:9092 +``` +4. Edit registration-processor-mz.properties to update depdendent service URLs, DB, keycloak and relevant credentials to point to a particular cloud environment +5. Run the kernel-config server pointing to local copy of property files (Refer https://github.com/mosip/mosip-config/tree/develop1-v3#readme) +6. If stages to be run from console + 1. Change directory to any stage group file and update the pom to file to add the relevant stage and comment the remaining stages + ``` + cd registration-processor/stage-groups/registration-processor-stage-group-2/ + ``` + 2. Build the stage group using the below command + ``` + mvn clean install -Dgpg.skip -DskipTests + ``` + 3. Create a new folder called 'additional-jars' and download the latest kernel adapter jar file to this folder + 4. Run the below command to start the stage + ``` + java -Dspring.profiles.active=default -Dspring.cloud.config.uri=http://localhost:51000/config -Dloader.path=./additional-jars/ -jar target/registration-processor-stage-group-2-1.2.1-SNAPSHOT.jar + ``` +7. If stages to be run on IDE + 1. Open IDE and configure the entire code base of registration processor + 2. Add the relevant stage as depdendent module to mosip-stage-executor module + 3. Download the latest version of kernel auth adapter jar file and add as jar dependency to mosip-stage-executor module + 4. Edit run configuration of MosipStageExecutorApplication class file of mosip-stage-executor module to add the below VM arguments + ``` + -Dspring.profiles.active=default -Dspring.cloud.config.uri=http://localhost:51000/config + ``` + 5. Run MosipStageExecutorApplication class file + +8. Open http://localhost:8080 in browser to open kafka-ui application and navigate to topics link, open the stage bus-in topic and click on "Produce Message" and add the below JSON message. +``` +{ + "reg_type": "NEW", + "rid": "10002100010001020220928084430", + "isValid": true, + "internalError": false, + "messageBusAddress": { + "address": "packet-validator-bus-in" + }, + "retryCount": null, + "tags": {}, + "lastHopTimestamp": "2022-10-20T10:48:29.355Z", + "source": null, + "iteration": 1, + "workflowInstanceId": "ff3063de-f563-46c7-b529-b07daf1f2fca" +} +``` +Ensure the rid and workflowInstanceId is filled in as per a valid packet that is avaialble in the connected cloud environment. Also ensure lastHopTimestamp is the current time. + +This step will trigger the message processing in stage. + +9. Once the message processing is completed, stage will add another message with status back into the out bus of the stage. diff --git a/pom.xml b/pom.xml index ae08308e5ca..ddfcf0c2386 100644 --- a/pom.xml +++ b/pom.xml @@ -4,7 +4,7 @@ 4.0.0 io.mosip registration - 1.2.0.1-B1 + 1.2.0.1-B3-SNAPSHOT pom MOSIP Registration Parent POM diff --git a/registration-processor/core-processor/pom.xml b/registration-processor/core-processor/pom.xml index 351e147b9d6..151372b736c 100644 --- a/registration-processor/core-processor/pom.xml +++ b/registration-processor/core-processor/pom.xml @@ -1,29 +1,29 @@ - - - 4.0.0 - pom - - io.mosip.registrationprocessor - registration-processor - 1.2.0.1-B1 - - 1.2.0.1-B1 - core-processor - core-processor - - UTF-8 - - - registration-processor-demo-dedupe-stage - registration-processor-bio-dedupe-stage - registration-processor-uin-generator-stage - registration-processor-abis - registration-processor-manual-adjudication-stage - registration-processor-abis-handler-stage - registration-processor-abis-middleware-stage - registration-processor-biometric-authentication-stage - registration-processor-biometric-extraction-stage - registration-processor-finalization-stage - registration-processor-verification-stage - + + + 4.0.0 + pom + + io.mosip.registrationprocessor + registration-processor + 1.2.0.1-B3-SNAPSHOT + + 1.2.0.1-B3-SNAPSHOT + core-processor + core-processor + + UTF-8 + + + registration-processor-demo-dedupe-stage + registration-processor-bio-dedupe-stage + registration-processor-uin-generator-stage + registration-processor-abis + registration-processor-manual-adjudication-stage + registration-processor-abis-handler-stage + registration-processor-abis-middleware-stage + registration-processor-biometric-authentication-stage + registration-processor-biometric-extraction-stage + registration-processor-finalization-stage + registration-processor-verification-stage + \ No newline at end of file diff --git a/registration-processor/core-processor/registration-processor-abis-handler-stage/pom.xml b/registration-processor/core-processor/registration-processor-abis-handler-stage/pom.xml index 772656286b9..2898847f6e4 100644 --- a/registration-processor/core-processor/registration-processor-abis-handler-stage/pom.xml +++ b/registration-processor/core-processor/registration-processor-abis-handler-stage/pom.xml @@ -5,11 +5,11 @@ io.mosip.registrationprocessor core-processor - 1.2.0.1-B1 + 1.2.0.1-B3-SNAPSHOT registration-processor-abis-handler-stage - 1.2.0.1-B1 + 1.2.0.1-B3-SNAPSHOT jar UTF-8 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 cd0eb8d4d9a..7eb95b004ad 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 @@ -502,6 +502,7 @@ private void createInsertRequest(List abisQueueDetails, String abisRequestDto.setReqBatchId(batchId); abisRequestDto.setRefRegtrnId(transactionId); + abisRequestDto.setStatusCode(AbisStatusCode.IN_PROGRESS.toString()); abisRequestDto.setStatusComment(null); abisRequestDto.setLangCode(AbisHandlerStageConstant.ENG); @@ -510,19 +511,21 @@ private void createInsertRequest(List abisQueueDetails, String abisRequestDto.setIsDeleted(Boolean.FALSE); String moduleId = PlatformSuccessMessages.RPR_ABIS_HANDLER_STAGE_SUCCESS.getCode(); String moduleName = ModuleName.ABIS_HANDLER.toString(); - byte[] abisInsertRequestBytes=null; + byte[] abisInsertRequestBytes =null; if (abisProcessedInsertAppCodeList != null && abisProcessedInsertAppCodeList.contains(appCode)) { - abisInsertRequestBytes = getInsertRequestBytes(regId, id, process, bioRefId, description,AbisStatusCode.ALREADY_PROCESSED.toString()); + + abisInsertRequestBytes = getInsertRequestBytes(regId, id, process, bioRefId, description, + AbisStatusCode.ALREADY_PROCESSED.toString()); abisRequestDto.setStatusCode(AbisStatusCode.ALREADY_PROCESSED.toString()); } else { - abisInsertRequestBytes = getInsertRequestBytes(regId, id, process, bioRefId, description,AbisStatusCode.IN_PROGRESS.toString()); + abisInsertRequestBytes = getInsertRequestBytes(regId, id, process, bioRefId, description, + AbisStatusCode.IN_PROGRESS.toString()); abisRequestDto.setStatusCode(AbisStatusCode.IN_PROGRESS.toString()); } abisRequestDto.setReqText(abisInsertRequestBytes); packetInfoManager.saveAbisRequest(abisRequestDto, moduleId, moduleName); - } regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", @@ -536,9 +539,11 @@ private void createInsertRequest(List abisQueueDetails, String * @param id the id * @param bioRefId the bio ref id * @param description + * @param status * @return the insert request bytes */ - private byte[] getInsertRequestBytes(String regId, String id, String process, String bioRefId, LogDescription description,String status) throws Exception { + private byte[] getInsertRequestBytes(String regId, String id, String process, String bioRefId, + LogDescription description, String status) throws Exception { AbisInsertRequestDto abisInsertRequestDto = new AbisInsertRequestDto(); abisInsertRequestDto.setId(AbisHandlerStageConstant.MOSIP_ABIS_INSERT); abisInsertRequestDto.setReferenceId(bioRefId); diff --git a/registration-processor/core-processor/registration-processor-abis-handler-stage/src/test/java/io/mosip/registration/processor/abis/handler/stage/test/AbisHandlerStageTest.java b/registration-processor/core-processor/registration-processor-abis-handler-stage/src/test/java/io/mosip/registration/processor/abis/handler/stage/test/AbisHandlerStageTest.java index ef6cbf134de..0e13a0f5306 100644 --- a/registration-processor/core-processor/registration-processor-abis-handler-stage/src/test/java/io/mosip/registration/processor/abis/handler/stage/test/AbisHandlerStageTest.java +++ b/registration-processor/core-processor/registration-processor-abis-handler-stage/src/test/java/io/mosip/registration/processor/abis/handler/stage/test/AbisHandlerStageTest.java @@ -1,1029 +1,1025 @@ -package io.mosip.registration.processor.abis.handler.stage.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.Type; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; - -import org.assertj.core.util.Lists; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.ArgumentMatchers; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.Spy; -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.MediaType; -import org.springframework.test.util.ReflectionTestUtils; - -import com.fasterxml.jackson.databind.ObjectMapper; -import com.google.common.reflect.TypeToken; -import com.google.gson.Gson; - -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.JsonUtils; -import io.mosip.kernel.core.util.exception.JsonProcessingException; -import io.mosip.registration.processor.abis.handler.dto.DataShare; -import io.mosip.registration.processor.abis.handler.dto.DataShareResponseDto; -import io.mosip.registration.processor.abis.handler.stage.AbisHandlerStage; -import io.mosip.registration.processor.abis.queue.dto.AbisQueueDetails; -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.common.rest.dto.ErrorDTO; -import io.mosip.registration.processor.core.constant.PolicyConstant; -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.Identity; -import io.mosip.registration.processor.core.packet.dto.abis.AbisApplicationDto; -import io.mosip.registration.processor.core.packet.dto.abis.AbisIdentifyRequestDto; -import io.mosip.registration.processor.core.packet.dto.abis.AbisInsertRequestDto; -import io.mosip.registration.processor.core.packet.dto.abis.AbisRequestDto; -import io.mosip.registration.processor.core.packet.dto.abis.RegBioRefDto; -import io.mosip.registration.processor.core.packet.dto.abis.RegDemoDedupeListDto; -import io.mosip.registration.processor.core.packet.dto.datashare.Filter; -import io.mosip.registration.processor.core.packet.dto.datashare.ShareableAttributes; -import io.mosip.registration.processor.core.packet.dto.datashare.Source; -import io.mosip.registration.processor.core.spi.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.packet.storage.dto.ApplicantInfoDto; -import io.mosip.registration.processor.packet.storage.utils.PacketManagerService; -import io.mosip.registration.processor.packet.storage.utils.PriorityBasedPacketManagerService; -import io.mosip.registration.processor.packet.storage.utils.Utilities; -import io.mosip.registration.processor.rest.client.audit.builder.AuditLogRequestBuilder; -import io.mosip.registration.processor.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; - -@RunWith(PowerMockRunner.class) -@PrepareForTest({ JsonUtils.class }) -@PowerMockIgnore({ "com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "javax.management.*", "javax.net.ssl.*" }) -public class AbisHandlerStageTest { - - @Mock - private AuditLogRequestBuilder auditLogRequestBuilder; - - @Mock - private RegistrationStatusService registrationStatusService; - - @Mock - private PacketInfoManager packetInfoManager; - - private InternalRegistrationStatusDto registrationStatusDto = new InternalRegistrationStatusDto(); - - @Mock - private Utilities utility; - - @Spy - private ObjectMapper mapper = new ObjectMapper(); - - @Mock - private PriorityBasedPacketManagerService packetManagerService; - - @Mock - private PacketManagerService packetService; - - @Mock - private LogDescription description; - - List abisApplicationDtos = new ArrayList<>(); - - List bioRefDtos = new ArrayList<>(); - - List regDemoDedupeListDtoList = new ArrayList<>(); - - List abisRequestDtoList = new ArrayList<>(); - - Map tags = new HashMap(); - - @Mock - private Environment env; - - @Mock - private RegistrationProcessorRestClientService registrationProcessorRestClientService; - - @Mock - private CbeffUtil cbeffutil; - - @InjectMocks - private AbisHandlerStage abisHandlerStage = new AbisHandlerStage() { - @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 consumeAndSend(MosipEventBus mosipEventBus, MessageBusAddress fromAddress, - MessageBusAddress toAddress, long messageExpiryTimeLimit) { - } - - @Override - public Integer getPort() { - return 8080; - }; - }; - - @Before - public void setUp() throws Exception { - ReflectionTestUtils.setField(abisHandlerStage, "maxResults", "30"); - ReflectionTestUtils.setField(abisHandlerStage, "targetFPIR", "30"); - ReflectionTestUtils.setField(abisHandlerStage, "workerPoolSize", 10); - ReflectionTestUtils.setField(abisHandlerStage, "messageExpiryTimeLimit", Long.valueOf(0)); - ReflectionTestUtils.setField(abisHandlerStage, "clusterManagerUrl", "/dummyPath"); - ReflectionTestUtils.setField(abisHandlerStage, "httpProtocol", "http"); - ReflectionTestUtils.setField(abisHandlerStage, "internalDomainName", "localhost"); - Mockito.when(env.getProperty("mosip.registration.processor.datetime.pattern")) - .thenReturn("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); - - Map> biometricModalitySegmentsMap = new HashMap(); - Map> biometricModalitySegmentsMapInfant = new HashMap(); - biometricModalitySegmentsMapInfant.put("Face", getFaceList()); - biometricModalitySegmentsMap.put("Finger", getFingerList()); - biometricModalitySegmentsMap.put("Iris", getIrisList()); - biometricModalitySegmentsMap.put("Face", getFaceList()); - ReflectionTestUtils.setField(abisHandlerStage, "biometricModalitySegmentsMapInfant", biometricModalitySegmentsMapInfant); - ReflectionTestUtils.setField(abisHandlerStage, "biometricModalitySegmentsMapMinor", biometricModalitySegmentsMap); - ReflectionTestUtils.setField(abisHandlerStage, "biometricModalitySegmentsMapAdult", biometricModalitySegmentsMap); - ReflectionTestUtils.setField(abisHandlerStage, "exceptionSegmentsMap", getExceptionModalityMap()); - - Mockito.when(env.getProperty("DATASHARECREATEURL")).thenReturn("/v1/datashare/create"); - AbisApplicationDto dto = new AbisApplicationDto(); - dto.setCode("ABIS1"); - abisApplicationDtos.add(dto); - - Mockito.doNothing().when(description).setMessage(any()); - Mockito.when(description.getMessage()).thenReturn("description"); - - - Mockito.when(packetManagerService.getBiometrics(any(), any(), any(), any(), any())).thenReturn(getBiometricRecord(Arrays.asList("Left Thumb" ,"Right Thumb" , "Left MiddleFinger" , - "Left RingFinger" ,"Left LittleFinger" ,"Left IndexFinger" ,"Right MiddleFinger" , - "Right RingFinger" ,"Right LittleFinger" ,"Right IndexFinger" , - "Left" ,"Right","Face"),false)); - mockDataSharePolicy(Lists.newArrayList(BiometricType.FINGER,BiometricType.IRIS,BiometricType.FACE)); - - List list = new LinkedList<>(); - setMetaInfoMap(list); - - //Mockito.doNothing().when(registrationStatusDto).setLatestTransactionStatusCode(any()); - Mockito.doNothing().when(registrationStatusService).updateRegistrationStatus(any(), any(), any()); - - Mockito.when(packetInfoManager.getAbisRequestsByBioRefId(any())).thenReturn(abisRequestDtoList); - - AbisQueueDetails abisQueueDetails = new AbisQueueDetails(); - abisQueueDetails.setName("ABIS1"); - List abisQueueDetailsList = new ArrayList<>(); - abisQueueDetailsList.add(abisQueueDetails); - Mockito.when(utility.getAbisQueueDetails()).thenReturn(abisQueueDetailsList); - - AuditResponseDto auditResponseDto = new AuditResponseDto(); - ResponseWrapper responseWrapper = new ResponseWrapper<>(); - responseWrapper.setResponse(auditResponseDto); - Mockito.when(auditLogRequestBuilder.createAuditRequestBuilder(any(), any(), any(), any(), any(), any(), any())) - .thenReturn(responseWrapper); - - DataShareResponseDto dataShareResponseDto = new DataShareResponseDto(); - DataShare dataShare = new DataShare(); - dataShare.setUrl("http://localhost"); - dataShareResponseDto.setDataShare(dataShare); - - mockDataSharePolicy(Lists.newArrayList(BiometricType.FACE, BiometricType.FINGER)); - - Mockito.when(registrationProcessorRestClientService.postApi(anyString(), any(MediaType.class), any(), any(), - any(), any(), any())).thenReturn(dataShareResponseDto); - - Mockito.when(cbeffutil.createXML(any())).thenReturn(new byte[2048]); - } - - private Map getExceptionModalityMap() { - Map exceptionMap = new HashMap(); - exceptionMap.put("Left Thumb" , "leftThumb"); - exceptionMap.put("Right Thumb" , "rightThumb"); - exceptionMap.put("Left MiddleFinger" , "leftMiddle"); - exceptionMap.put("Left RingFinger" , "leftRing"); - exceptionMap.put("Left LittleFinger" , "leftLittle"); - exceptionMap.put("Left IndexFinger" , "leftIndex"); - exceptionMap.put("Right MiddleFinger" , "rightMiddle"); - exceptionMap.put("Right RingFinger" , "rightRing"); - exceptionMap.put("Right LittleFinger" , "rightLittle"); - exceptionMap.put("Right IndexFinger" , "rightIndex"); - exceptionMap.put("Left" , "leftEye"); - exceptionMap.put("Right" , "rightEye"); - exceptionMap.put("Face" , "face"); - - return exceptionMap; - } - - private List getFaceList() { - return Arrays.asList("Face"); - } - - private List getIrisList() { - return Arrays.asList("Left", "Right"); - - } - - private List getFingerList() { - return Arrays.asList("Left Thumb", "Left LittleFinger", "Left IndexFinger", "Left MiddleFinger", - "Left RingFinger", "Right Thumb", "Right LittleFinger", - "Right IndexFinger", "Right MiddleFinger", - "Right RingFinger"); - } - - private void mockDataSharePolicy(List sherableBiometricList) throws ApisResourceAccessException { - when(registrationProcessorRestClientService.getApi(any(), any(), anyString(), anyString(), any())) - .thenReturn(getMockDataSharePolicy(sherableBiometricList)); - } - - private ResponseWrapper> getMockDataSharePolicy( - List sherableBiometricList) { - - ObjectMapper mapper = new ObjectMapper(); - - List attr = new LinkedList<>(); - if (sherableBiometricList != null && !sherableBiometricList.isEmpty()) { - - ShareableAttributes shareableAttributes = new ShareableAttributes(); - List sourceList = new ArrayList<>(); - - for (BiometricType bioType : sherableBiometricList) { - Filter filter = new Filter(); - filter.setType(bioType.value()); - Source src = new Source(); - src.setFilter(Lists.newArrayList(filter)); - sourceList.add(src); - } - - shareableAttributes.setSource(sourceList); - attr = Lists.newArrayList(shareableAttributes); - } - - ResponseWrapper> policy = new ResponseWrapper<>(); - LinkedHashMap policies = new LinkedHashMap<>(); - LinkedHashMap sharableAttributes = new LinkedHashMap<>(); - sharableAttributes.put(PolicyConstant.SHAREABLE_ATTRIBUTES, attr); - policies.put(PolicyConstant.POLICIES, sharableAttributes); - policy.setResponse(policies); - - return policy; - } - - @Test - public void testDeployVerticle() { - abisHandlerStage.deployVerticle(); - } - - @Test - public void testDemoToAbisHandlerTOMiddlewareSuccess() throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { - registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); - registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); - Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); - Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); - Mockito.when(packetInfoManager.getAllAbisDetails()).thenReturn(abisApplicationDtos); - - mockDataSharePolicy(Lists.newArrayList(BiometricType.IRIS, BiometricType.FINGER, BiometricType.FACE)); - Mockito.when(packetInfoManager.getBioRefIdByRegId(any())).thenReturn(bioRefDtos); - tags.put("AGE_GROUP", "ADULT"); - Mockito.when(packetService.getAllTags(any())).thenReturn(tags); - - Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); - Mockito.doNothing().when(packetInfoManager).saveAbisRequest(any(), any(), any()); - - RegDemoDedupeListDto regDemoDedupeListDto = new RegDemoDedupeListDto(); - regDemoDedupeListDto.setMatchedRegId("10003100030001520190422074511"); - regDemoDedupeListDtoList.add(regDemoDedupeListDto); - Mockito.when(packetInfoManager.getDemoListByTransactionId(any())).thenReturn(regDemoDedupeListDtoList); - - MessageDTO dto = new MessageDTO(); - dto.setRid("10003100030001520190422074511"); - MessageDTO result = abisHandlerStage.process(dto); - - assertTrue(result.getMessageBusAddress().getAddress().equalsIgnoreCase("abis-middle-ware-bus-in")); - } - - @Test - public void testBioToAbisHandlerToMiddlewareSuccess() throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { - registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); - registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); - Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); - Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); - Mockito.when(packetInfoManager.getAllAbisDetails()).thenReturn(abisApplicationDtos); - - mockDataSharePolicy(Lists.newArrayList(BiometricType.IRIS, BiometricType.FINGER, BiometricType.FACE)); - RegBioRefDto regBioRefDto = new RegBioRefDto(); - regBioRefDto.setBioRefId("1234567890"); - bioRefDtos.add(regBioRefDto); - Mockito.when(packetInfoManager.getBioRefIdByRegId(any())).thenReturn(bioRefDtos); - tags.put("AGE_GROUP", "ADULT"); - Mockito.when(packetService.getAllTags(any())).thenReturn(tags); - - Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); - Mockito.doNothing().when(packetInfoManager).saveAbisRequest(any(), any(), any()); - - RegDemoDedupeListDto regDemoDedupeListDto = new RegDemoDedupeListDto(); - regDemoDedupeListDto.setMatchedRegId("10003100030001520190422074511"); - regDemoDedupeListDtoList.add(regDemoDedupeListDto); - Mockito.when(packetInfoManager.getDemoListByTransactionId(any())).thenReturn(regDemoDedupeListDtoList); - - MessageDTO dto = new MessageDTO(); - dto.setRid("10003100030001520190422074511"); - MessageDTO result = abisHandlerStage.process(dto); - - assertTrue(result.getMessageBusAddress().getAddress().equalsIgnoreCase("abis-middle-ware-bus-in")); - } - - @Test - public void testMiddlewareToAbisHandlerToDemoSuccess() { - registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); - registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); - Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); - Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.TRUE); - - MessageDTO dto = new MessageDTO(); - dto.setRid("10003100030001520190422074511"); - MessageDTO result = abisHandlerStage.process(dto); - - assertTrue(result.getMessageBusAddress().getAddress().equalsIgnoreCase("demo-dedupe-bus-in")); - } - - @Test - public void testMiddlewareToAbisHandlerToBioSuccess() { - registrationStatusDto.setLatestTransactionTypeCode("BIOGRAPHIC_VERIFICATION"); - registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); - Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); - Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.TRUE); - - MessageDTO dto = new MessageDTO(); - dto.setRid("10003100030001520190422074511"); - MessageDTO result = abisHandlerStage.process(dto); - - assertTrue(result.getMessageBusAddress().getAddress().equalsIgnoreCase("bio-dedupe-bus-in")); - } - - @Test - public void testDemoDedupeDataNotFound() { - registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); - registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); - Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); - Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); - Mockito.when(packetInfoManager.getAllAbisDetails()).thenReturn(abisApplicationDtos); - - Mockito.when(packetInfoManager.getBioRefIdByRegId(any())).thenReturn(bioRefDtos); - - Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); - Mockito.doNothing().when(packetInfoManager).saveAbisRequest(any(), any(), any()); - - Mockito.when(packetInfoManager.getDemoListByTransactionId(any())).thenReturn(regDemoDedupeListDtoList); - - MessageDTO dto = new MessageDTO(); - dto.setRid("10003100030001520190422074511"); - MessageDTO result = abisHandlerStage.process(dto); - - assertTrue(result.getInternalError()); - assertTrue(result.getIsValid()); - } - - @Test - public void testReprocessInsert() throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { - registrationStatusDto.setLatestTransactionTypeCode("BIOGRAPHIC_VERIFICATION"); - registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); - Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); - Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); - List appCodeList = new ArrayList<>(); - appCodeList.add("ABIS1"); - Mockito.when(packetInfoManager.getAbisProcessedRequestsAppCodeByBioRefId(any(), any(), any())) - .thenReturn(appCodeList); - - Mockito.when(packetInfoManager.getAllAbisDetails()).thenReturn(abisApplicationDtos); - - RegBioRefDto bioRefDto = new RegBioRefDto(); - bioRefDtos.add(bioRefDto); - Mockito.when(packetInfoManager.getBioRefIdByRegId(any())).thenReturn(bioRefDtos); - - Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); - - AbisRequestDto abisRequestDto = new AbisRequestDto(); - abisRequestDto.setAbisAppCode("ABIS1"); - abisRequestDto.setStatusCode("IN-PROGRESS"); - abisRequestDtoList.add(abisRequestDto); - Mockito.when(packetInfoManager.getAbisRequestsByBioRefId(any())).thenReturn(abisRequestDtoList); - tags.put("AGE_GROUP", "ADULT"); - Mockito.when(packetService.getAllTags(any())).thenReturn(tags); - - Mockito.doNothing().when(packetInfoManager).saveAbisRequest(any(), any(), any()); - - Mockito.when(packetInfoManager.getDemoListByTransactionId(any())).thenReturn(regDemoDedupeListDtoList); - - MessageDTO dto = new MessageDTO(); - dto.setRid("10003100030001520190422074511"); - MessageDTO result = abisHandlerStage.process(dto); - - assertTrue(result.getMessageBusAddress().getAddress().equalsIgnoreCase("abis-middle-ware-bus-in")); - } - - @Test - public void testAbisDetailsNotFound() throws RegistrationProcessorCheckedException { - registrationStatusDto.setLatestTransactionTypeCode("BIOGRAPHIC_VERIFICATION"); - registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); - Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); - Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); - - List abisQueueDetails = new ArrayList<>(); - Mockito.when(utility.getAbisQueueDetails()).thenReturn(abisQueueDetails); - - MessageDTO dto = new MessageDTO(); - dto.setRid("10003100030001520190422074511"); - MessageDTO result = abisHandlerStage.process(dto); - - assertTrue(result.getInternalError()); - } - - @Test - public void testPotentialMatchNotFound() throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { - registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); - registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); - Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); - Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); - - mockDataSharePolicy(Lists.newArrayList(BiometricType.IRIS, BiometricType.FINGER, BiometricType.FACE)); - tags.put("AGE_GROUP", "ADULT"); - Mockito.when(packetService.getAllTags(any())).thenReturn(tags); - - Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); - Mockito.doNothing().when(packetInfoManager).saveAbisRequest(any(), any(), any()); - - Mockito.when(packetInfoManager.getDemoListByTransactionId(any())).thenReturn(Arrays.asList()); - - MessageDTO dto = new MessageDTO(); - dto.setRid("10003100030001520190422074511"); - MessageDTO result = abisHandlerStage.process(dto); - - assertTrue(result.getInternalError()); - } - - @Test - public void testIdentifyRequestJsonProcessingException() throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { - registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); - registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); - Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); - Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); - - mockDataSharePolicy(Lists.newArrayList(BiometricType.IRIS, BiometricType.FINGER, BiometricType.FACE)); - Mockito.when(packetInfoManager.getBioRefIdByRegId(any())).thenReturn(bioRefDtos); - tags.put("AGE_GROUP", "ADULT"); - Mockito.when(packetService.getAllTags(any())).thenReturn(tags); - - Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); - Mockito.doNothing().when(packetInfoManager).saveAbisRequest(any(), any(), any()); - - RegDemoDedupeListDto regDemoDedupeListDto = new RegDemoDedupeListDto(); - regDemoDedupeListDto.setMatchedRegId("10003100030001520190422074511"); - regDemoDedupeListDtoList.add(regDemoDedupeListDto); - Mockito.when(packetInfoManager.getDemoListByTransactionId(any())).thenReturn(regDemoDedupeListDtoList); - - PowerMockito.mockStatic(JsonUtils.class); - PowerMockito.when(JsonUtils.javaObjectToJsonString(any())).thenReturn("value").thenThrow(JsonProcessingException.class); - MessageDTO dto = new MessageDTO(); - dto.setRid("10003100030001520190422074511"); - MessageDTO result = abisHandlerStage.process(dto); - - assertTrue(result.getInternalError()); - } - - @Test - public void testInsertRequestJsonProcessingException() throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { - registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); - registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); - Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); - Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); - - mockDataSharePolicy(Lists.newArrayList(BiometricType.IRIS, BiometricType.FINGER, BiometricType.FACE)); - tags.put("AGE_GROUP", "MINOR"); - Mockito.when(packetService.getAllTags(any())).thenReturn(tags); - - Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); - - PowerMockito.mockStatic(JsonUtils.class); - PowerMockito.when(JsonUtils.javaObjectToJsonString(any())).thenThrow(JsonProcessingException.class); - MessageDTO dto = new MessageDTO(); - dto.setRid("10003100030001520190422074511"); - MessageDTO result = abisHandlerStage.process(dto); - - assertTrue(result.getInternalError()); - } - - @Test - public void testDataShareResponseNullException() throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { - registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); - registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); - Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); - Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); - - mockDataSharePolicy(Lists.newArrayList(BiometricType.IRIS, BiometricType.FINGER, BiometricType.FACE)); - tags.put("AGE_GROUP", "MINOR"); - Mockito.when(packetService.getAllTags(any())).thenReturn(tags); - - Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); - - DataShareResponseDto dataShareResponseDto = new DataShareResponseDto(); - ErrorDTO error = new ErrorDTO("ERR-001", "exception occured"); - dataShareResponseDto.setDataShare(null); - dataShareResponseDto.setErrors(Arrays.asList(error)); - Mockito.when(registrationProcessorRestClientService.postApi(anyString(), any(MediaType.class), any(), any(), - any(), any(), any())).thenReturn(dataShareResponseDto); - MessageDTO dto = new MessageDTO(); - dto.setRid("10003100030001520190422074511"); - MessageDTO result = abisHandlerStage.process(dto); - - assertTrue(result.getInternalError()); - } - - @Test - public void testCreateTypeSubtypeMappingResponseNullException() - throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { - registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); - registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); - Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())) - .thenReturn(registrationStatusDto); - Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); - ErrorDTO error = new ErrorDTO("ERR-001", "exception occured"); - ResponseWrapper> policyResponse = new ResponseWrapper<>(); - - policyResponse.setErrors(Arrays.asList(error)); - - Mockito.when(registrationProcessorRestClientService.getApi(any(), any(), anyString(), - anyString(), any())).thenReturn(policyResponse); - Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); - - MessageDTO dto = new MessageDTO(); - dto.setRid("10003100030001520190422074511"); - MessageDTO result = abisHandlerStage.process(dto); - - assertTrue(result.getInternalError()); - } - - @Test - public void testvalidateBiometricRecordModalitiesEmptyException() - throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { - registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); - registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); - Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())) - .thenReturn(registrationStatusDto); - Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); - - mockDataSharePolicy(Lists.newArrayList(BiometricType.IRIS, BiometricType.FINGER, BiometricType.FACE)); - tags.put("AGE_GROUP", "MINOR"); - Mockito.when(packetService.getAllTags(any())).thenReturn(tags); - - Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); - - ResponseWrapper> policyResponse = new ResponseWrapper<>(); - LinkedHashMap response = new LinkedHashMap(); - LinkedHashMap attributes = new LinkedHashMap(); - ShareableAttributes shareableAttributes = new ShareableAttributes(); - shareableAttributes.setSource(Arrays.asList()); - attributes.put(PolicyConstant.SHAREABLE_ATTRIBUTES, Arrays.asList(shareableAttributes)); - response.put(PolicyConstant.POLICIES, attributes); - policyResponse.setResponse(response); - - Mockito.when(registrationProcessorRestClientService.getApi(any(), any(), anyString(), anyString(), any())) - .thenReturn(policyResponse); - - MessageDTO dto = new MessageDTO(); - dto.setRid("10003100030001520190422074511"); - MessageDTO result = abisHandlerStage.process(dto); - - assertTrue(result.getInternalError()); - } - - @Test - public void testvalidateBiometricRecordSegmentEmptyException() - throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { - registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); - registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); - Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())) - .thenReturn(registrationStatusDto); - Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); - - mockDataSharePolicy(Lists.newArrayList(BiometricType.IRIS, BiometricType.FINGER, BiometricType.FACE)); - tags.put("AGE_GROUP", "ADULT"); - Mockito.when(packetService.getAllTags(any())).thenReturn(tags); - BiometricRecord biometricRecord = new BiometricRecord(); - biometricRecord.setSegments(null); - Mockito.when(packetManagerService.getBiometrics(any(), any(), any(), any(), any())).thenReturn(biometricRecord); - Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); - - MessageDTO dto = new MessageDTO(); - dto.setRid("10003100030001520190422074511"); - MessageDTO result = abisHandlerStage.process(dto); - - assertTrue(result.getInternalError()); - } - - @Test - public void testvalidateBiometricRecordOthersMapNullException() - throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { - registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); - registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); - Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())) - .thenReturn(registrationStatusDto); - Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); - - mockDataSharePolicy(Lists.newArrayList(BiometricType.IRIS, BiometricType.FINGER, BiometricType.FACE)); - tags.put("AGE_GROUP", "ADULT"); - Mockito.when(packetService.getAllTags(any())).thenReturn(tags); - BiometricRecord biometricRecord = new BiometricRecord(); - BIR bir = new BIR.BIRBuilder().build(); - BDBInfo bdbInfo = new BDBInfo.BDBInfoBuilder().build(); - bdbInfo.setSubtype(Arrays.asList("Left")); - bdbInfo.setType(Arrays.asList(BiometricType.IRIS)); - bir.setOthers(null); - bir.setBdbInfo(bdbInfo); - biometricRecord.setSegments(Arrays.asList(bir)); - Mockito.when(packetManagerService.getBiometrics(any(), any(), any(), any(), any())).thenReturn(biometricRecord); - Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); - - MessageDTO dto = new MessageDTO(); - dto.setRid("10003100030001520190422074511"); - MessageDTO result = abisHandlerStage.process(dto); - - assertTrue(result.getInternalError()); - } - - @Test - public void testCreateRequestException() throws JsonProcessingException { - registrationStatusDto.setLatestTransactionTypeCode("BIOGRAPHIC_VERIFICATION"); - registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); - Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); - Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); - - Mockito.when(packetInfoManager.getAllAbisDetails()).thenReturn(abisApplicationDtos); - - RegBioRefDto bioRefDto = new RegBioRefDto(); - bioRefDtos.add(bioRefDto); - Mockito.when(packetInfoManager.getBioRefIdByRegId(any())).thenReturn(bioRefDtos); - - Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); - - AbisRequestDto abisRequestDto = new AbisRequestDto(); - abisRequestDto.setAbisAppCode("ABIS1"); - abisRequestDto.setStatusCode("IN-PROGRESS"); - abisRequestDtoList.add(abisRequestDto); - Mockito.when(packetInfoManager.getAbisRequestsByBioRefId(any())).thenReturn(abisRequestDtoList); - - Mockito.doNothing().when(packetInfoManager).saveAbisRequest(any(), any(), any()); - - Mockito.when(packetInfoManager.getDemoListByTransactionId(any())).thenReturn(regDemoDedupeListDtoList); - - PowerMockito.mockStatic(JsonUtils.class); - PowerMockito.when(JsonUtils.javaObjectToJsonString(any(AbisInsertRequestDto.class))) - .thenThrow(JsonProcessingException.class); - - MessageDTO dto = new MessageDTO(); - dto.setRid("10003100030001520190422074511"); - MessageDTO result = abisHandlerStage.process(dto); - - assertTrue(result.getInternalError()); - assertTrue(result.getIsValid()); - } - - @Test - public void testIdentifyRequestException() throws JsonProcessingException { - registrationStatusDto.setLatestTransactionTypeCode("BIOGRAPHIC_VERIFICATION"); - registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); - Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); - Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); - - Mockito.when(packetInfoManager.getAllAbisDetails()).thenReturn(abisApplicationDtos); - - RegBioRefDto bioRefDto = new RegBioRefDto(); - bioRefDtos.add(bioRefDto); - Mockito.when(packetInfoManager.getBioRefIdByRegId(any())).thenReturn(bioRefDtos); - - Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); - - AbisRequestDto abisRequestDto = new AbisRequestDto(); - abisRequestDto.setAbisAppCode("ABIS1"); - abisRequestDto.setStatusCode("IN-PROGRESS"); - abisRequestDtoList.add(abisRequestDto); - Mockito.when(packetInfoManager.getAbisRequestsByBioRefId(any())).thenReturn(abisRequestDtoList); - - Mockito.doNothing().when(packetInfoManager).saveAbisRequest(any(), any(), any()); - - Mockito.when(packetInfoManager.getDemoListByTransactionId(any())).thenReturn(regDemoDedupeListDtoList); - - PowerMockito.mockStatic(JsonUtils.class); - PowerMockito.when(JsonUtils.javaObjectToJsonString(any(AbisInsertRequestDto.class))) - .thenReturn("AbisInsertRequestDto"); - PowerMockito.when(JsonUtils.javaObjectToJsonString(ArgumentMatchers.any(AbisIdentifyRequestDto.class))) - .thenThrow(JsonProcessingException.class); - - MessageDTO dto = new MessageDTO(); - dto.setRid("10003100030001520190422074511"); - MessageDTO result = abisHandlerStage.process(dto); - - assertTrue(result.getInternalError()); - assertTrue(result.getIsValid()); - } - - - @Test - public void bioRecordDataNotFound() - throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { - - defaultMockToProcess(); - - Mockito.when(packetManagerService.getBiometrics(any(), any(), any(), any(), any())).thenReturn(null); - mockDataSharePolicy(Lists.newArrayList(BiometricType.IRIS, BiometricType.FINGER, BiometricType.FACE)); - - setMetaInfoMap(new LinkedList<>(getExceptionModalityMap().values())); - MessageDTO dto = new MessageDTO(); - dto.setRid("10003100030001520190422074511"); - MessageDTO result = abisHandlerStage.process(dto); - - assertTrue(result.getIsValid()); - assertTrue(result.getInternalError()); - } - - @Test - public void biometricsNotFoundWithSegmentConfig() - throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { - - defaultMockToProcess(); - - Mockito.when(packetManagerService.getBiometrics(any(), any(), any(), any(), any())).thenReturn(getBiometricRecord(Arrays.asList("Left Thumb" ,"Right Thumb","Face"),false)); - - - setMetaInfoMap(Arrays.asList("leftEye")); - MessageDTO dto = new MessageDTO(); - dto.setRid("10003100030001520190422074511"); - MessageDTO result = abisHandlerStage.process(dto); - - assertTrue(result.getIsValid()); - assertTrue(result.getInternalError()); - } - - @Test - public void biometricsTypeNotFoundConfig() - throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { - - defaultMockToProcess(); - - Map> biometricModalitySegmentsMap = new HashMap(); - biometricModalitySegmentsMap.put("Finger", getFingerList()); - biometricModalitySegmentsMap.put("Iris", getIrisList()); - ReflectionTestUtils.setField(abisHandlerStage, "biometricModalitySegmentsMapAdult", biometricModalitySegmentsMap); - ReflectionTestUtils.setField(abisHandlerStage, "exceptionSegmentsMap", getExceptionModalityMap()); - - MessageDTO dto = new MessageDTO(); - dto.setRid("10003100030001520190422074511"); - MessageDTO result = abisHandlerStage.process(dto); - - assertTrue(result.getIsValid()); - assertTrue(result.getInternalError()); - } - - @Test - public void testBiometricSegmentNotConfiguredInfant() throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { - registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); - registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); - Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); - Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); - Mockito.when(packetInfoManager.getAllAbisDetails()).thenReturn(abisApplicationDtos); - - Mockito.when(packetInfoManager.getBioRefIdByRegId(any())).thenReturn(bioRefDtos); - tags.put("AGE_GROUP", "INFANT"); - Mockito.when(packetService.getAllTags(any())).thenReturn(tags); - - Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); - Mockito.doNothing().when(packetInfoManager).saveAbisRequest(any(), any(), any()); - - RegDemoDedupeListDto regDemoDedupeListDto = new RegDemoDedupeListDto(); - regDemoDedupeListDto.setMatchedRegId("10003100030001520190422074511"); - regDemoDedupeListDtoList.add(regDemoDedupeListDto); - Mockito.when(packetInfoManager.getDemoListByTransactionId(any())).thenReturn(regDemoDedupeListDtoList); - - MessageDTO dto = new MessageDTO(); - dto.setRid("10003100030001520190422074511"); - MessageDTO result = abisHandlerStage.process(dto); - - assertTrue(result.getIsValid()); - assertFalse(result.getInternalError()); - } - - - - @Test - public void emptyBdbFound() - throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { - - defaultMockToProcess(); - - boolean isBdbEmpty = true; - Mockito.when(packetManagerService.getBiometrics(any(), any(), any(), any(), any())).thenReturn(getBiometricRecord(Arrays.asList("Left RingFinger"), isBdbEmpty )); - mockDataSharePolicy(Lists.newArrayList(BiometricType.FINGER)); - - List list = new ArrayList(getExceptionModalityMap().values()); - list.remove("leftRing"); - setMetaInfoMap(list); - - MessageDTO dto = new MessageDTO(); - dto.setRid("10003100030001520190422074511"); - MessageDTO result = abisHandlerStage.process(dto); - - assertTrue(result.getIsValid()); - assertTrue(result.getInternalError()); - } - - @Test - public void noBdbInAnyBiometric() - throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { - - defaultMockToProcess(); - - Mockito.when(packetManagerService.getBiometrics(any(), any(), any(), any(), any())).thenReturn(getBiometricRecord(Arrays.asList("Left Thumb" ,"Right Thumb" , "Left MiddleFinger" , - "Left RingFinger" ,"Left LittleFinger" ,"Left IndexFinger" ,"Right MiddleFinger" , - "Right RingFinger" ,"Right LittleFinger" ,"Right IndexFinger" , - "Left" ,"Right","Face"),true)); - - MessageDTO dto = new MessageDTO(); - dto.setRid("10003100030001520190422074511"); - MessageDTO result = abisHandlerStage.process(dto); - - assertTrue(result.getIsValid()); - assertTrue(result.getInternalError()); - } - - private void defaultMockToProcess() { - registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); - registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); - Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); - Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); - Mockito.when(packetInfoManager.getAllAbisDetails()).thenReturn(abisApplicationDtos); - - RegBioRefDto regBioRefDto = new RegBioRefDto(); - regBioRefDto.setBioRefId("1234567890"); - bioRefDtos.add(regBioRefDto); - Mockito.when(packetInfoManager.getBioRefIdByRegId(any())).thenReturn(bioRefDtos); - - Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); - Mockito.doNothing().when(packetInfoManager).saveAbisRequest(any(), any(), any()); - - RegDemoDedupeListDto regDemoDedupeListDto = new RegDemoDedupeListDto(); - regDemoDedupeListDto.setMatchedRegId("10003100030001520190422074511"); - regDemoDedupeListDtoList.add(regDemoDedupeListDto); - Mockito.when(packetInfoManager.getDemoListByTransactionId(any())).thenReturn(regDemoDedupeListDtoList); - - } - - private void setMetaInfoMap(List exceptionAttributes) throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException{ - - Map metaInfoMap = new HashMap<>(); - - Map> exceptionBiometrcisMap = new HashMap<>(); - - Map applicantExceptionBiometrcisMap = new HashMap(); - - if(exceptionAttributes!=null) { - for(String exceptionAttribute : exceptionAttributes) { - - Map detailMap = new HashMap(); - detailMap.put("missingBiometric", exceptionAttribute); - detailMap.put("reason", "Temporary"); - detailMap.put("individualType", "applicant"); - - applicantExceptionBiometrcisMap.put(exceptionAttribute, detailMap); - - } - } - - - exceptionBiometrcisMap.put("applicant", applicantExceptionBiometrcisMap); - Gson gson = new Gson(); - Type gsonType = new TypeToken(){}.getType(); - - String gsonString = gson.toJson(exceptionBiometrcisMap,gsonType); - - metaInfoMap.put("exceptionBiometrics", gsonString); - Mockito.when(packetManagerService.getMetaInfo(any(), any(), any())).thenReturn(metaInfoMap); - } - - private BiometricRecord getBiometricRecord(List bioAttributes, boolean isBdbEmpty) { - BiometricRecord biometricRecord = new BiometricRecord(); - - byte[] bdb = isBdbEmpty ? null : new byte[2048]; - for(String bioAttribute : bioAttributes) { - BIR birType1 = new BIR.BIRBuilder().build(); - 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 = bioAttribute.equalsIgnoreCase("face") ? BiometricType.FACE : - bioAttribute.equalsIgnoreCase("left") || bioAttribute.equalsIgnoreCase("right") ? BiometricType.IRIS : BiometricType.FINGER ; - List singleTypeList1 = new ArrayList<>(); - singleTypeList1.add(singleType1); - bdbInfoType1.setType(singleTypeList1); - - - - String[] bioAttributeArray = bioAttribute.split(" "); - - List subtype = new ArrayList<>(); - for(String attribute : bioAttributeArray) { - subtype.add(attribute); - } - bdbInfoType1.setSubtype(subtype); - - birType1.setBdbInfo(bdbInfoType1); - birType1.setBdb(bdb); - - if(bdb==null) { - Map others = new HashMap<>(); - others.put("EXCEPTION", true); - HashMap entry = new HashMap<>(); - entry.put("EXCEPTION", "true"); - birType1.setOthers(entry); - - } - - biometricRecord.getSegments().add(birType1); - } - - return biometricRecord; - } - +package io.mosip.registration.processor.abis.handler.stage.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.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +import org.assertj.core.util.Lists; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentMatchers; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.Spy; +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.MediaType; +import org.springframework.test.util.ReflectionTestUtils; + +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.JsonUtils; +import io.mosip.kernel.core.util.exception.JsonProcessingException; +import io.mosip.registration.processor.abis.handler.dto.DataShare; +import io.mosip.registration.processor.abis.handler.dto.DataShareResponseDto; +import io.mosip.registration.processor.abis.handler.stage.AbisHandlerStage; +import io.mosip.registration.processor.abis.queue.dto.AbisQueueDetails; +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.common.rest.dto.ErrorDTO; +import io.mosip.registration.processor.core.constant.PolicyConstant; +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.Identity; +import io.mosip.registration.processor.core.packet.dto.abis.AbisApplicationDto; +import io.mosip.registration.processor.core.packet.dto.abis.AbisIdentifyRequestDto; +import io.mosip.registration.processor.core.packet.dto.abis.AbisInsertRequestDto; +import io.mosip.registration.processor.core.packet.dto.abis.AbisRequestDto; +import io.mosip.registration.processor.core.packet.dto.abis.RegBioRefDto; +import io.mosip.registration.processor.core.packet.dto.abis.RegDemoDedupeListDto; +import io.mosip.registration.processor.core.packet.dto.datashare.Filter; +import io.mosip.registration.processor.core.packet.dto.datashare.ShareableAttributes; +import io.mosip.registration.processor.core.packet.dto.datashare.Source; +import io.mosip.registration.processor.core.spi.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.packet.storage.dto.ApplicantInfoDto; +import io.mosip.registration.processor.packet.storage.utils.PacketManagerService; +import io.mosip.registration.processor.packet.storage.utils.PriorityBasedPacketManagerService; +import io.mosip.registration.processor.packet.storage.utils.Utilities; +import io.mosip.registration.processor.rest.client.audit.builder.AuditLogRequestBuilder; +import io.mosip.registration.processor.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; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({ JsonUtils.class }) +@PowerMockIgnore({ "com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "javax.management.*", "javax.net.ssl.*" }) +public class AbisHandlerStageTest { + + @Mock + private AuditLogRequestBuilder auditLogRequestBuilder; + + @Mock + private RegistrationStatusService registrationStatusService; + + @Mock + private PacketInfoManager packetInfoManager; + + private InternalRegistrationStatusDto registrationStatusDto = new InternalRegistrationStatusDto(); + + @Mock + private Utilities utility; + + @Spy + private ObjectMapper mapper = new ObjectMapper(); + + @Mock + private PriorityBasedPacketManagerService packetManagerService; + + @Mock + private PacketManagerService packetService; + + @Mock + private LogDescription description; + + List abisApplicationDtos = new ArrayList<>(); + + List bioRefDtos = new ArrayList<>(); + + List regDemoDedupeListDtoList = new ArrayList<>(); + + List abisRequestDtoList = new ArrayList<>(); + + Map tags = new HashMap(); + + @Mock + private Environment env; + + @Mock + private RegistrationProcessorRestClientService registrationProcessorRestClientService; + + @Mock + private CbeffUtil cbeffutil; + + @InjectMocks + private AbisHandlerStage abisHandlerStage = new AbisHandlerStage() { + @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 consumeAndSend(MosipEventBus mosipEventBus, MessageBusAddress fromAddress, + MessageBusAddress toAddress, long messageExpiryTimeLimit) { + } + + @Override + public Integer getPort() { + return 8080; + }; + }; + + @Before + public void setUp() throws Exception { + ReflectionTestUtils.setField(abisHandlerStage, "maxResults", "30"); + ReflectionTestUtils.setField(abisHandlerStage, "targetFPIR", "30"); + ReflectionTestUtils.setField(abisHandlerStage, "workerPoolSize", 10); + ReflectionTestUtils.setField(abisHandlerStage, "messageExpiryTimeLimit", Long.valueOf(0)); + ReflectionTestUtils.setField(abisHandlerStage, "clusterManagerUrl", "/dummyPath"); + ReflectionTestUtils.setField(abisHandlerStage, "httpProtocol", "http"); + ReflectionTestUtils.setField(abisHandlerStage, "internalDomainName", "localhost"); + Mockito.when(env.getProperty("mosip.registration.processor.datetime.pattern")) + .thenReturn("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); + + Map> biometricModalitySegmentsMap = new HashMap(); + Map> biometricModalitySegmentsMapInfant = new HashMap(); + biometricModalitySegmentsMapInfant.put("Face", getFaceList()); + biometricModalitySegmentsMap.put("Finger", getFingerList()); + biometricModalitySegmentsMap.put("Iris", getIrisList()); + biometricModalitySegmentsMap.put("Face", getFaceList()); + ReflectionTestUtils.setField(abisHandlerStage, "biometricModalitySegmentsMapInfant", biometricModalitySegmentsMapInfant); + ReflectionTestUtils.setField(abisHandlerStage, "biometricModalitySegmentsMapMinor", biometricModalitySegmentsMap); + ReflectionTestUtils.setField(abisHandlerStage, "biometricModalitySegmentsMapAdult", biometricModalitySegmentsMap); + ReflectionTestUtils.setField(abisHandlerStage, "exceptionSegmentsMap", getExceptionModalityMap()); + + Mockito.when(env.getProperty("DATASHARECREATEURL")).thenReturn("/v1/datashare/create"); + AbisApplicationDto dto = new AbisApplicationDto(); + dto.setCode("ABIS1"); + abisApplicationDtos.add(dto); + + Mockito.doNothing().when(description).setMessage(any()); + Mockito.when(description.getMessage()).thenReturn("description"); + + + Mockito.when(packetManagerService.getBiometrics(any(), any(), any(), any(), any())).thenReturn(getBiometricRecord(Arrays.asList("Left Thumb" ,"Right Thumb" , "Left MiddleFinger" , + "Left RingFinger" ,"Left LittleFinger" ,"Left IndexFinger" ,"Right MiddleFinger" , + "Right RingFinger" ,"Right LittleFinger" ,"Right IndexFinger" , + "Left" ,"Right","Face"),false)); + mockDataSharePolicy(Lists.newArrayList(BiometricType.FINGER,BiometricType.IRIS,BiometricType.FACE)); + + List list = new LinkedList<>(); + setMetaInfoMap(list); + + //Mockito.doNothing().when(registrationStatusDto).setLatestTransactionStatusCode(any()); + Mockito.doNothing().when(registrationStatusService).updateRegistrationStatus(any(), any(), any()); + + Mockito.when(packetInfoManager.getAbisRequestsByBioRefId(any())).thenReturn(abisRequestDtoList); + + AbisQueueDetails abisQueueDetails = new AbisQueueDetails(); + abisQueueDetails.setName("ABIS1"); + List abisQueueDetailsList = new ArrayList<>(); + abisQueueDetailsList.add(abisQueueDetails); + Mockito.when(utility.getAbisQueueDetails()).thenReturn(abisQueueDetailsList); + + AuditResponseDto auditResponseDto = new AuditResponseDto(); + ResponseWrapper responseWrapper = new ResponseWrapper<>(); + responseWrapper.setResponse(auditResponseDto); + Mockito.when(auditLogRequestBuilder.createAuditRequestBuilder(any(), any(), any(), any(), any(), any(), any())) + .thenReturn(responseWrapper); + + DataShareResponseDto dataShareResponseDto = new DataShareResponseDto(); + DataShare dataShare = new DataShare(); + dataShare.setUrl("http://localhost"); + dataShareResponseDto.setDataShare(dataShare); + + mockDataSharePolicy(Lists.newArrayList(BiometricType.FACE, BiometricType.FINGER)); + + Mockito.when(registrationProcessorRestClientService.postApi(anyString(), any(MediaType.class), any(), any(), + any(), any(), any())).thenReturn(dataShareResponseDto); + + Mockito.when(cbeffutil.createXML(any())).thenReturn(new byte[2048]); + } + + private Map getExceptionModalityMap() { + Map exceptionMap = new HashMap(); + exceptionMap.put("Left Thumb" , "leftThumb"); + exceptionMap.put("Right Thumb" , "rightThumb"); + exceptionMap.put("Left MiddleFinger" , "leftMiddle"); + exceptionMap.put("Left RingFinger" , "leftRing"); + exceptionMap.put("Left LittleFinger" , "leftLittle"); + exceptionMap.put("Left IndexFinger" , "leftIndex"); + exceptionMap.put("Right MiddleFinger" , "rightMiddle"); + exceptionMap.put("Right RingFinger" , "rightRing"); + exceptionMap.put("Right LittleFinger" , "rightLittle"); + exceptionMap.put("Right IndexFinger" , "rightIndex"); + exceptionMap.put("Left" , "leftEye"); + exceptionMap.put("Right" , "rightEye"); + exceptionMap.put("Face" , "face"); + + return exceptionMap; + } + + private List getFaceList() { + return Arrays.asList("Face"); + } + + private List getIrisList() { + return Arrays.asList("Left", "Right"); + + } + + private List getFingerList() { + return Arrays.asList("Left Thumb", "Left LittleFinger", "Left IndexFinger", "Left MiddleFinger", + "Left RingFinger", "Right Thumb", "Right LittleFinger", + "Right IndexFinger", "Right MiddleFinger", + "Right RingFinger"); + } + + private void mockDataSharePolicy(List sherableBiometricList) throws ApisResourceAccessException { + when(registrationProcessorRestClientService.getApi(any(), any(), anyString(), anyString(), any())) + .thenReturn(getMockDataSharePolicy(sherableBiometricList)); + } + + private ResponseWrapper> getMockDataSharePolicy( + List sherableBiometricList) { + + ObjectMapper mapper = new ObjectMapper(); + + List attr = new LinkedList<>(); + if (sherableBiometricList != null && !sherableBiometricList.isEmpty()) { + + ShareableAttributes shareableAttributes = new ShareableAttributes(); + List sourceList = new ArrayList<>(); + + for (BiometricType bioType : sherableBiometricList) { + Filter filter = new Filter(); + filter.setType(bioType.value()); + Source src = new Source(); + src.setFilter(Lists.newArrayList(filter)); + sourceList.add(src); + } + + shareableAttributes.setSource(sourceList); + attr = Lists.newArrayList(shareableAttributes); + } + + ResponseWrapper> policy = new ResponseWrapper<>(); + LinkedHashMap policies = new LinkedHashMap<>(); + LinkedHashMap sharableAttributes = new LinkedHashMap<>(); + sharableAttributes.put(PolicyConstant.SHAREABLE_ATTRIBUTES, attr); + policies.put(PolicyConstant.POLICIES, sharableAttributes); + policy.setResponse(policies); + + return policy; + } + + @Test + public void testDeployVerticle() { + abisHandlerStage.deployVerticle(); + } + + @Test + public void testDemoToAbisHandlerTOMiddlewareSuccess() throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { + registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); + registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); + Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); + Mockito.when(packetInfoManager.getAllAbisDetails()).thenReturn(abisApplicationDtos); + + mockDataSharePolicy(Lists.newArrayList(BiometricType.IRIS, BiometricType.FINGER, BiometricType.FACE)); + Mockito.when(packetInfoManager.getBioRefIdByRegId(any())).thenReturn(bioRefDtos); + tags.put("AGE_GROUP", "ADULT"); + Mockito.when(packetService.getAllTags(any())).thenReturn(tags); + + Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); + Mockito.doNothing().when(packetInfoManager).saveAbisRequest(any(), any(), any()); + + RegDemoDedupeListDto regDemoDedupeListDto = new RegDemoDedupeListDto(); + regDemoDedupeListDto.setMatchedRegId("10003100030001520190422074511"); + regDemoDedupeListDtoList.add(regDemoDedupeListDto); + Mockito.when(packetInfoManager.getDemoListByTransactionId(any())).thenReturn(regDemoDedupeListDtoList); + + MessageDTO dto = new MessageDTO(); + dto.setRid("10003100030001520190422074511"); + MessageDTO result = abisHandlerStage.process(dto); + + assertTrue(result.getMessageBusAddress().getAddress().equalsIgnoreCase("abis-middle-ware-bus-in")); + } + + @Test + public void testBioToAbisHandlerToMiddlewareSuccess() throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { + registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); + registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); + Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); + Mockito.when(packetInfoManager.getAllAbisDetails()).thenReturn(abisApplicationDtos); + + mockDataSharePolicy(Lists.newArrayList(BiometricType.IRIS, BiometricType.FINGER, BiometricType.FACE)); + RegBioRefDto regBioRefDto = new RegBioRefDto(); + regBioRefDto.setBioRefId("1234567890"); + bioRefDtos.add(regBioRefDto); + Mockito.when(packetInfoManager.getBioRefIdByRegId(any())).thenReturn(bioRefDtos); + tags.put("AGE_GROUP", "ADULT"); + Mockito.when(packetService.getAllTags(any())).thenReturn(tags); + + Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); + Mockito.doNothing().when(packetInfoManager).saveAbisRequest(any(), any(), any()); + + RegDemoDedupeListDto regDemoDedupeListDto = new RegDemoDedupeListDto(); + regDemoDedupeListDto.setMatchedRegId("10003100030001520190422074511"); + regDemoDedupeListDtoList.add(regDemoDedupeListDto); + Mockito.when(packetInfoManager.getDemoListByTransactionId(any())).thenReturn(regDemoDedupeListDtoList); + + MessageDTO dto = new MessageDTO(); + dto.setRid("10003100030001520190422074511"); + MessageDTO result = abisHandlerStage.process(dto); + + assertTrue(result.getMessageBusAddress().getAddress().equalsIgnoreCase("abis-middle-ware-bus-in")); + } + + @Test + public void testMiddlewareToAbisHandlerToDemoSuccess() { + registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); + registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); + Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.TRUE); + + MessageDTO dto = new MessageDTO(); + dto.setRid("10003100030001520190422074511"); + MessageDTO result = abisHandlerStage.process(dto); + + assertTrue(result.getMessageBusAddress().getAddress().equalsIgnoreCase("demo-dedupe-bus-in")); + } + + @Test + public void testMiddlewareToAbisHandlerToBioSuccess() { + registrationStatusDto.setLatestTransactionTypeCode("BIOGRAPHIC_VERIFICATION"); + registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); + Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.TRUE); + + MessageDTO dto = new MessageDTO(); + dto.setRid("10003100030001520190422074511"); + MessageDTO result = abisHandlerStage.process(dto); + + assertTrue(result.getMessageBusAddress().getAddress().equalsIgnoreCase("bio-dedupe-bus-in")); + } + + @Test + public void testDemoDedupeDataNotFound() { + registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); + registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); + Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); + Mockito.when(packetInfoManager.getAllAbisDetails()).thenReturn(abisApplicationDtos); + + Mockito.when(packetInfoManager.getBioRefIdByRegId(any())).thenReturn(bioRefDtos); + + Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); + Mockito.doNothing().when(packetInfoManager).saveAbisRequest(any(), any(), any()); + + Mockito.when(packetInfoManager.getDemoListByTransactionId(any())).thenReturn(regDemoDedupeListDtoList); + + MessageDTO dto = new MessageDTO(); + dto.setRid("10003100030001520190422074511"); + MessageDTO result = abisHandlerStage.process(dto); + + assertTrue(result.getInternalError()); + assertTrue(result.getIsValid()); + } + + @Test + public void testReprocessInsert() throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { + registrationStatusDto.setLatestTransactionTypeCode("BIOGRAPHIC_VERIFICATION"); + registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); + Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); + List appCodeList = new ArrayList<>(); + appCodeList.add("ABIS1"); + Mockito.when(packetInfoManager.getAbisProcessedRequestsAppCodeByBioRefId(any(), any(), any())) + .thenReturn(appCodeList); + + Mockito.when(packetInfoManager.getAllAbisDetails()).thenReturn(abisApplicationDtos); + + RegBioRefDto bioRefDto = new RegBioRefDto(); + bioRefDtos.add(bioRefDto); + Mockito.when(packetInfoManager.getBioRefIdByRegId(any())).thenReturn(bioRefDtos); + + Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); + + AbisRequestDto abisRequestDto = new AbisRequestDto(); + abisRequestDto.setAbisAppCode("ABIS1"); + abisRequestDto.setStatusCode("IN-PROGRESS"); + abisRequestDtoList.add(abisRequestDto); + Mockito.when(packetInfoManager.getAbisRequestsByBioRefId(any())).thenReturn(abisRequestDtoList); + tags.put("AGE_GROUP", "ADULT"); + Mockito.when(packetService.getAllTags(any())).thenReturn(tags); + + Mockito.doNothing().when(packetInfoManager).saveAbisRequest(any(), any(), any()); + + Mockito.when(packetInfoManager.getDemoListByTransactionId(any())).thenReturn(regDemoDedupeListDtoList); + + MessageDTO dto = new MessageDTO(); + dto.setRid("10003100030001520190422074511"); + MessageDTO result = abisHandlerStage.process(dto); + + assertFalse(result.getInternalError()); + assertTrue(result.getIsValid()); + } + + @Test + public void testAbisDetailsNotFound() throws RegistrationProcessorCheckedException { + registrationStatusDto.setLatestTransactionTypeCode("BIOGRAPHIC_VERIFICATION"); + registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); + Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); + + List abisQueueDetails = new ArrayList<>(); + Mockito.when(utility.getAbisQueueDetails()).thenReturn(abisQueueDetails); + + MessageDTO dto = new MessageDTO(); + dto.setRid("10003100030001520190422074511"); + MessageDTO result = abisHandlerStage.process(dto); + + assertTrue(result.getInternalError()); + } + + @Test + public void testPotentialMatchNotFound() throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { + registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); + registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); + Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); + + mockDataSharePolicy(Lists.newArrayList(BiometricType.IRIS, BiometricType.FINGER, BiometricType.FACE)); + tags.put("AGE_GROUP", "ADULT"); + Mockito.when(packetService.getAllTags(any())).thenReturn(tags); + + Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); + Mockito.doNothing().when(packetInfoManager).saveAbisRequest(any(), any(), any()); + + Mockito.when(packetInfoManager.getDemoListByTransactionId(any())).thenReturn(Arrays.asList()); + + MessageDTO dto = new MessageDTO(); + dto.setRid("10003100030001520190422074511"); + MessageDTO result = abisHandlerStage.process(dto); + + assertTrue(result.getInternalError()); + } + + @Test + public void testIdentifyRequestJsonProcessingException() throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { + registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); + registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); + Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); + + mockDataSharePolicy(Lists.newArrayList(BiometricType.IRIS, BiometricType.FINGER, BiometricType.FACE)); + Mockito.when(packetInfoManager.getBioRefIdByRegId(any())).thenReturn(bioRefDtos); + tags.put("AGE_GROUP", "ADULT"); + Mockito.when(packetService.getAllTags(any())).thenReturn(tags); + + Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); + Mockito.doNothing().when(packetInfoManager).saveAbisRequest(any(), any(), any()); + + RegDemoDedupeListDto regDemoDedupeListDto = new RegDemoDedupeListDto(); + regDemoDedupeListDto.setMatchedRegId("10003100030001520190422074511"); + regDemoDedupeListDtoList.add(regDemoDedupeListDto); + Mockito.when(packetInfoManager.getDemoListByTransactionId(any())).thenReturn(regDemoDedupeListDtoList); + + PowerMockito.mockStatic(JsonUtils.class); + PowerMockito.when(JsonUtils.javaObjectToJsonString(any())).thenReturn("value").thenThrow(JsonProcessingException.class); + MessageDTO dto = new MessageDTO(); + dto.setRid("10003100030001520190422074511"); + MessageDTO result = abisHandlerStage.process(dto); + + assertTrue(result.getInternalError()); + } + + @Test + public void testInsertRequestJsonProcessingException() throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { + registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); + registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); + Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); + + mockDataSharePolicy(Lists.newArrayList(BiometricType.IRIS, BiometricType.FINGER, BiometricType.FACE)); + tags.put("AGE_GROUP", "MINOR"); + Mockito.when(packetService.getAllTags(any())).thenReturn(tags); + + Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); + + PowerMockito.mockStatic(JsonUtils.class); + PowerMockito.when(JsonUtils.javaObjectToJsonString(any())).thenThrow(JsonProcessingException.class); + MessageDTO dto = new MessageDTO(); + dto.setRid("10003100030001520190422074511"); + MessageDTO result = abisHandlerStage.process(dto); + + assertTrue(result.getInternalError()); + } + + @Test + public void testDataShareResponseNullException() throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { + registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); + registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); + Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); + + mockDataSharePolicy(Lists.newArrayList(BiometricType.IRIS, BiometricType.FINGER, BiometricType.FACE)); + tags.put("AGE_GROUP", "MINOR"); + Mockito.when(packetService.getAllTags(any())).thenReturn(tags); + + Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); + + DataShareResponseDto dataShareResponseDto = new DataShareResponseDto(); + ErrorDTO error = new ErrorDTO("ERR-001", "exception occured"); + dataShareResponseDto.setDataShare(null); + dataShareResponseDto.setErrors(Arrays.asList(error)); + Mockito.when(registrationProcessorRestClientService.postApi(anyString(), any(MediaType.class), any(), any(), + any(), any(), any())).thenReturn(dataShareResponseDto); + MessageDTO dto = new MessageDTO(); + dto.setRid("10003100030001520190422074511"); + MessageDTO result = abisHandlerStage.process(dto); + + assertTrue(result.getInternalError()); + } + + @Test + public void testCreateTypeSubtypeMappingResponseNullException() + throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { + registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); + registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())) + .thenReturn(registrationStatusDto); + Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); + ErrorDTO error = new ErrorDTO("ERR-001", "exception occured"); + ResponseWrapper> policyResponse = new ResponseWrapper<>(); + + policyResponse.setErrors(Arrays.asList(error)); + + Mockito.when(registrationProcessorRestClientService.getApi(any(), any(), anyString(), + anyString(), any())).thenReturn(policyResponse); + Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); + + MessageDTO dto = new MessageDTO(); + dto.setRid("10003100030001520190422074511"); + MessageDTO result = abisHandlerStage.process(dto); + + assertTrue(result.getInternalError()); + } + + @Test + public void testvalidateBiometricRecordModalitiesEmptyException() + throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { + registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); + registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())) + .thenReturn(registrationStatusDto); + Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); + + mockDataSharePolicy(Lists.newArrayList(BiometricType.IRIS, BiometricType.FINGER, BiometricType.FACE)); + tags.put("AGE_GROUP", "MINOR"); + Mockito.when(packetService.getAllTags(any())).thenReturn(tags); + + Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); + + ResponseWrapper> policyResponse = new ResponseWrapper<>(); + LinkedHashMap response = new LinkedHashMap(); + LinkedHashMap attributes = new LinkedHashMap(); + ShareableAttributes shareableAttributes = new ShareableAttributes(); + shareableAttributes.setSource(Arrays.asList()); + attributes.put(PolicyConstant.SHAREABLE_ATTRIBUTES, Arrays.asList(shareableAttributes)); + response.put(PolicyConstant.POLICIES, attributes); + policyResponse.setResponse(response); + + Mockito.when(registrationProcessorRestClientService.getApi(any(), any(), anyString(), anyString(), any())) + .thenReturn(policyResponse); + + MessageDTO dto = new MessageDTO(); + dto.setRid("10003100030001520190422074511"); + MessageDTO result = abisHandlerStage.process(dto); + + assertTrue(result.getInternalError()); + } + + @Test + public void testvalidateBiometricRecordSegmentEmptyException() + throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { + registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); + registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())) + .thenReturn(registrationStatusDto); + Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); + + mockDataSharePolicy(Lists.newArrayList(BiometricType.IRIS, BiometricType.FINGER, BiometricType.FACE)); + tags.put("AGE_GROUP", "ADULT"); + Mockito.when(packetService.getAllTags(any())).thenReturn(tags); + BiometricRecord biometricRecord = new BiometricRecord(); + biometricRecord.setSegments(null); + Mockito.when(packetManagerService.getBiometrics(any(), any(), any(), any(), any())).thenReturn(biometricRecord); + Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); + + MessageDTO dto = new MessageDTO(); + dto.setRid("10003100030001520190422074511"); + MessageDTO result = abisHandlerStage.process(dto); + + assertTrue(result.getInternalError()); + } + + @Test + public void testvalidateBiometricRecordOthersMapNullException() + throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { + registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); + registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())) + .thenReturn(registrationStatusDto); + Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); + + mockDataSharePolicy(Lists.newArrayList(BiometricType.IRIS, BiometricType.FINGER, BiometricType.FACE)); + tags.put("AGE_GROUP", "ADULT"); + Mockito.when(packetService.getAllTags(any())).thenReturn(tags); + BiometricRecord biometricRecord = new BiometricRecord(); + BIR bir = new BIR.BIRBuilder().build(); + BDBInfo bdbInfo = new BDBInfo.BDBInfoBuilder().build(); + bdbInfo.setSubtype(Arrays.asList("Left")); + bdbInfo.setType(Arrays.asList(BiometricType.IRIS)); + bir.setOthers(null); + bir.setBdbInfo(bdbInfo); + biometricRecord.setSegments(Arrays.asList(bir)); + Mockito.when(packetManagerService.getBiometrics(any(), any(), any(), any(), any())).thenReturn(biometricRecord); + Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); + + MessageDTO dto = new MessageDTO(); + dto.setRid("10003100030001520190422074511"); + MessageDTO result = abisHandlerStage.process(dto); + + assertTrue(result.getInternalError()); + } + + @Test + public void testCreateRequestException() throws JsonProcessingException { + registrationStatusDto.setLatestTransactionTypeCode("BIOGRAPHIC_VERIFICATION"); + registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); + Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); + + Mockito.when(packetInfoManager.getAllAbisDetails()).thenReturn(abisApplicationDtos); + + RegBioRefDto bioRefDto = new RegBioRefDto(); + bioRefDtos.add(bioRefDto); + Mockito.when(packetInfoManager.getBioRefIdByRegId(any())).thenReturn(bioRefDtos); + + Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); + + AbisRequestDto abisRequestDto = new AbisRequestDto(); + abisRequestDto.setAbisAppCode("ABIS1"); + abisRequestDto.setStatusCode("IN-PROGRESS"); + abisRequestDtoList.add(abisRequestDto); + Mockito.when(packetInfoManager.getAbisRequestsByBioRefId(any())).thenReturn(abisRequestDtoList); + + Mockito.doNothing().when(packetInfoManager).saveAbisRequest(any(), any(), any()); + + Mockito.when(packetInfoManager.getDemoListByTransactionId(any())).thenReturn(regDemoDedupeListDtoList); + + PowerMockito.mockStatic(JsonUtils.class); + PowerMockito.when(JsonUtils.javaObjectToJsonString(any(AbisInsertRequestDto.class))) + .thenThrow(JsonProcessingException.class); + + MessageDTO dto = new MessageDTO(); + dto.setRid("10003100030001520190422074511"); + MessageDTO result = abisHandlerStage.process(dto); + + assertTrue(result.getInternalError()); + assertTrue(result.getIsValid()); + } + + @Test + public void testIdentifyRequestException() throws JsonProcessingException { + registrationStatusDto.setLatestTransactionTypeCode("BIOGRAPHIC_VERIFICATION"); + registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); + Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); + + Mockito.when(packetInfoManager.getAllAbisDetails()).thenReturn(abisApplicationDtos); + + RegBioRefDto bioRefDto = new RegBioRefDto(); + bioRefDtos.add(bioRefDto); + Mockito.when(packetInfoManager.getBioRefIdByRegId(any())).thenReturn(bioRefDtos); + + Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); + + AbisRequestDto abisRequestDto = new AbisRequestDto(); + abisRequestDto.setAbisAppCode("ABIS1"); + abisRequestDto.setStatusCode("IN-PROGRESS"); + abisRequestDtoList.add(abisRequestDto); + Mockito.when(packetInfoManager.getAbisRequestsByBioRefId(any())).thenReturn(abisRequestDtoList); + + Mockito.doNothing().when(packetInfoManager).saveAbisRequest(any(), any(), any()); + + Mockito.when(packetInfoManager.getDemoListByTransactionId(any())).thenReturn(regDemoDedupeListDtoList); + + PowerMockito.mockStatic(JsonUtils.class); + PowerMockito.when(JsonUtils.javaObjectToJsonString(any(AbisInsertRequestDto.class))) + .thenReturn("AbisInsertRequestDto"); + PowerMockito.when(JsonUtils.javaObjectToJsonString(ArgumentMatchers.any(AbisIdentifyRequestDto.class))) + .thenThrow(JsonProcessingException.class); + + MessageDTO dto = new MessageDTO(); + dto.setRid("10003100030001520190422074511"); + MessageDTO result = abisHandlerStage.process(dto); + + assertTrue(result.getInternalError()); + assertTrue(result.getIsValid()); + } + + + @Test + public void bioRecordDataNotFound() + throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { + + defaultMockToProcess(); + + Mockito.when(packetManagerService.getBiometrics(any(), any(), any(), any(), any())).thenReturn(null); + mockDataSharePolicy(Lists.newArrayList(BiometricType.IRIS, BiometricType.FINGER, BiometricType.FACE)); + + setMetaInfoMap(new LinkedList<>(getExceptionModalityMap().values())); + MessageDTO dto = new MessageDTO(); + dto.setRid("10003100030001520190422074511"); + MessageDTO result = abisHandlerStage.process(dto); + + assertTrue(result.getIsValid()); + assertTrue(result.getInternalError()); + } + + @Test + public void biometricsNotFoundWithSegmentConfig() + throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { + + defaultMockToProcess(); + + Mockito.when(packetManagerService.getBiometrics(any(), any(), any(), any(), any())).thenReturn(getBiometricRecord(Arrays.asList("Left Thumb" ,"Right Thumb","Face"),false)); + + + setMetaInfoMap(Arrays.asList("leftEye")); + MessageDTO dto = new MessageDTO(); + dto.setRid("10003100030001520190422074511"); + MessageDTO result = abisHandlerStage.process(dto); + + assertTrue(result.getIsValid()); + assertTrue(result.getInternalError()); + } + + @Test + public void biometricsTypeNotFoundConfig() + throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { + + defaultMockToProcess(); + + Map> biometricModalitySegmentsMap = new HashMap(); + biometricModalitySegmentsMap.put("Finger", getFingerList()); + biometricModalitySegmentsMap.put("Iris", getIrisList()); + ReflectionTestUtils.setField(abisHandlerStage, "biometricModalitySegmentsMapAdult", biometricModalitySegmentsMap); + ReflectionTestUtils.setField(abisHandlerStage, "exceptionSegmentsMap", getExceptionModalityMap()); + + MessageDTO dto = new MessageDTO(); + dto.setRid("10003100030001520190422074511"); + MessageDTO result = abisHandlerStage.process(dto); + + assertTrue(result.getIsValid()); + assertTrue(result.getInternalError()); + } + + @Test + public void testBiometricSegmentNotConfiguredInfant() throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { + registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); + registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); + Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); + Mockito.when(packetInfoManager.getAllAbisDetails()).thenReturn(abisApplicationDtos); + + Mockito.when(packetInfoManager.getBioRefIdByRegId(any())).thenReturn(bioRefDtos); + tags.put("AGE_GROUP", "INFANT"); + Mockito.when(packetService.getAllTags(any())).thenReturn(tags); + + Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); + Mockito.doNothing().when(packetInfoManager).saveAbisRequest(any(), any(), any()); + + RegDemoDedupeListDto regDemoDedupeListDto = new RegDemoDedupeListDto(); + regDemoDedupeListDto.setMatchedRegId("10003100030001520190422074511"); + regDemoDedupeListDtoList.add(regDemoDedupeListDto); + Mockito.when(packetInfoManager.getDemoListByTransactionId(any())).thenReturn(regDemoDedupeListDtoList); + + MessageDTO dto = new MessageDTO(); + dto.setRid("10003100030001520190422074511"); + MessageDTO result = abisHandlerStage.process(dto); + + assertTrue(result.getIsValid()); + assertFalse(result.getInternalError()); + } + + + + @Test + public void emptyBdbFound() + throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { + + defaultMockToProcess(); + + boolean isBdbEmpty = true; + Mockito.when(packetManagerService.getBiometrics(any(), any(), any(), any(), any())).thenReturn(getBiometricRecord(Arrays.asList("Left RingFinger"), isBdbEmpty )); + mockDataSharePolicy(Lists.newArrayList(BiometricType.FINGER)); + + List list = new ArrayList(getExceptionModalityMap().values()); + list.remove("leftRing"); + setMetaInfoMap(list); + + MessageDTO dto = new MessageDTO(); + dto.setRid("10003100030001520190422074511"); + MessageDTO result = abisHandlerStage.process(dto); + + assertTrue(result.getIsValid()); + assertTrue(result.getInternalError()); + } + + @Test + public void noBdbInAnyBiometric() + throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { + + defaultMockToProcess(); + + Mockito.when(packetManagerService.getBiometrics(any(), any(), any(), any(), any())).thenReturn(getBiometricRecord(Arrays.asList("Left Thumb" ,"Right Thumb" , "Left MiddleFinger" , + "Left RingFinger" ,"Left LittleFinger" ,"Left IndexFinger" ,"Right MiddleFinger" , + "Right RingFinger" ,"Right LittleFinger" ,"Right IndexFinger" , + "Left" ,"Right","Face"),true)); + + MessageDTO dto = new MessageDTO(); + dto.setRid("10003100030001520190422074511"); + MessageDTO result = abisHandlerStage.process(dto); + + assertTrue(result.getIsValid()); + assertTrue(result.getInternalError()); + } + + private void defaultMockToProcess() { + registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); + registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); + Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); + Mockito.when(packetInfoManager.getAllAbisDetails()).thenReturn(abisApplicationDtos); + + RegBioRefDto regBioRefDto = new RegBioRefDto(); + regBioRefDto.setBioRefId("1234567890"); + bioRefDtos.add(regBioRefDto); + Mockito.when(packetInfoManager.getBioRefIdByRegId(any())).thenReturn(bioRefDtos); + + Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); + Mockito.doNothing().when(packetInfoManager).saveAbisRequest(any(), any(), any()); + + RegDemoDedupeListDto regDemoDedupeListDto = new RegDemoDedupeListDto(); + regDemoDedupeListDto.setMatchedRegId("10003100030001520190422074511"); + regDemoDedupeListDtoList.add(regDemoDedupeListDto); + Mockito.when(packetInfoManager.getDemoListByTransactionId(any())).thenReturn(regDemoDedupeListDtoList); + + } + + private void setMetaInfoMap(List exceptionAttributes) throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException{ + + Map metaInfoMap = new HashMap<>(); + + Map> exceptionBiometrcisMap = new HashMap<>(); + + Map applicantExceptionBiometrcisMap = new HashMap(); + + if(exceptionAttributes!=null) { + for(String exceptionAttribute : exceptionAttributes) { + + Map detailMap = new HashMap(); + detailMap.put("missingBiometric", exceptionAttribute); + detailMap.put("reason", "Temporary"); + detailMap.put("individualType", "applicant"); + + applicantExceptionBiometrcisMap.put(exceptionAttribute, detailMap); + + } + } + + + exceptionBiometrcisMap.put("applicant", applicantExceptionBiometrcisMap); + String gsonString =mapper.writeValueAsString(exceptionBiometrcisMap); + + metaInfoMap.put("exceptionBiometrics", gsonString); + Mockito.when(packetManagerService.getMetaInfo(any(), any(), any())).thenReturn(metaInfoMap); + } + + private BiometricRecord getBiometricRecord(List bioAttributes, boolean isBdbEmpty) { + BiometricRecord biometricRecord = new BiometricRecord(); + + byte[] bdb = isBdbEmpty ? null : new byte[2048]; + for(String bioAttribute : bioAttributes) { + BIR birType1 = new BIR.BIRBuilder().build(); + 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 = bioAttribute.equalsIgnoreCase("face") ? BiometricType.FACE : + bioAttribute.equalsIgnoreCase("left") || bioAttribute.equalsIgnoreCase("right") ? BiometricType.IRIS : BiometricType.FINGER ; + List singleTypeList1 = new ArrayList<>(); + singleTypeList1.add(singleType1); + bdbInfoType1.setType(singleTypeList1); + + + + String[] bioAttributeArray = bioAttribute.split(" "); + + List subtype = new ArrayList<>(); + for(String attribute : bioAttributeArray) { + subtype.add(attribute); + } + bdbInfoType1.setSubtype(subtype); + + birType1.setBdbInfo(bdbInfoType1); + birType1.setBdb(bdb); + + if(bdb==null) { + Map others = new HashMap<>(); + others.put("EXCEPTION", true); + HashMap entry = new HashMap<>(); + entry.put("EXCEPTION", "true"); + birType1.setOthers(entry); + + } + + biometricRecord.getSegments().add(birType1); + } + + return biometricRecord; + } + } \ No newline at end of file diff --git a/registration-processor/core-processor/registration-processor-abis-middleware-stage/pom.xml b/registration-processor/core-processor/registration-processor-abis-middleware-stage/pom.xml index 96485b993a8..0ac1f969ba7 100644 --- a/registration-processor/core-processor/registration-processor-abis-middleware-stage/pom.xml +++ b/registration-processor/core-processor/registration-processor-abis-middleware-stage/pom.xml @@ -1,92 +1,92 @@ - - - 4.0.0 - - io.mosip.registrationprocessor - core-processor - 1.2.0.1-B1 - - registration-processor-abis-middleware-stage - 1.2.0.1-B1 - jar - - UTF-8 - UTF-8 - - - - - - org.springframework.cloud - spring-cloud-starter-config - ${spring-cloud-config.version} - - - org.mockito - mockito-core - ${mockito.version} - test - - - com.h2database - h2 - 1.4.195 - - - - - - - - io.mosip.registrationprocessor - registration-processor-core - ${registration.processor.core.version} - - - io.mosip.registrationprocessor - registration-processor-registration-status-service-impl - ${registration.status.service.version} - - - io.mosip.registrationprocessor - registration-processor-info-storage-service - ${packet.info.storage.service.version} - - - io.mosip.registrationprocessor - registration-processor-rest-client - ${registration.processor.rest.client.version} - - - org.powermock - powermock-module-junit4 - ${powermock.module.junit4.version} - test - - - org.powermock - powermock-api-mockito2 - ${powermock.api.mockito.version} - test - - - - - - + + + 4.0.0 + + io.mosip.registrationprocessor + core-processor + 1.2.0.1-B3-SNAPSHOT + + registration-processor-abis-middleware-stage + 1.2.0.1-B3-SNAPSHOT + jar + + UTF-8 + UTF-8 + + + + + + org.springframework.cloud + spring-cloud-starter-config + ${spring-cloud-config.version} + + + org.mockito + mockito-core + ${mockito.version} + test + + + com.h2database + h2 + 1.4.195 + + + + + + + + io.mosip.registrationprocessor + registration-processor-core + ${registration.processor.core.version} + + + io.mosip.registrationprocessor + registration-processor-registration-status-service-impl + ${registration.status.service.version} + + + io.mosip.registrationprocessor + registration-processor-info-storage-service + ${packet.info.storage.service.version} + + + io.mosip.registrationprocessor + registration-processor-rest-client + ${registration.processor.rest.client.version} + + + org.powermock + powermock-module-junit4 + ${powermock.module.junit4.version} + test + + + org.powermock + powermock-api-mockito2 + ${powermock.api.mockito.version} + test + + + + + + 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 a0c5ce83249..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 @@ -68,10 +68,13 @@ import io.mosip.registration.processor.packet.storage.repository.BasePacketRepository; import io.mosip.registration.processor.packet.storage.utils.Utilities; import io.mosip.registration.processor.rest.client.audit.builder.AuditLogRequestBuilder; +import io.mosip.registration.processor.status.code.RegistrationType; import io.mosip.registration.processor.status.dao.RegistrationStatusDao; import io.mosip.registration.processor.status.dto.InternalRegistrationStatusDto; import io.mosip.registration.processor.status.dto.RegistrationStatusDto; import io.mosip.registration.processor.status.entity.RegistrationStatusEntity; +import io.mosip.registration.processor.status.entity.TransactionEntity; +import io.mosip.registration.processor.status.repositary.TransactionRepository; import io.mosip.registration.processor.status.service.RegistrationStatusService; import io.mosip.registration.processor.status.utilities.RegistrationUtility; @@ -165,7 +168,6 @@ public class AbisMiddleWareStage extends MosipVerticleAPIManager { */ public void deployVerticle() { try { - mosipEventBus = this.getEventBus(this, clusterManagerUrl, workerPoolSize); this.consume(mosipEventBus, MessageBusAddress.ABIS_MIDDLEWARE_BUS_IN, messageExpiryTimeLimit); abisQueueDetails = utility.getAbisQueueDetails(); @@ -204,6 +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 @@ -432,7 +435,9 @@ public void consumerListener(Message message, String abisInBoundAddress, MosipQu internalRegStatusDto .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.REPROCESS.toString()); internalRegStatusDto.setStatusComment( - StatusUtil.INSERT_RESPONSE_FAILED.getMessage() + abisCommonRequestDto.getId()+"-"+abisInsertResponseDto.getFailureReason()+"-"+io.mosip.registartion.processor.abis.middleware.constants.FailureReason.getValueFromKey(abisInsertResponseDto.getFailureReason())); + StatusUtil.INSERT_RESPONSE_FAILED.getMessage() + abisCommonRequestDto.getId() +"- failure reason - "+abisInsertResponseDto.getFailureReason() + "-" + + io.mosip.registartion.processor.abis.middleware.constants.FailureReason + .getValueFromKey(abisInsertResponseDto.getFailureReason())); internalRegStatusDto.setSubStatusCode(StatusUtil.SYSTEM_EXCEPTION_OCCURED.getCode()); moduleId = PlatformErrorMessages.SYSTEM_EXCEPTION_OCCURED.getCode(); registrationStatusService.updateRegistrationStatus(internalRegStatusDto, moduleId, moduleName); @@ -463,7 +468,9 @@ public void consumerListener(Message message, String abisInBoundAddress, MosipQu internalRegStatusDto .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.REPROCESS.toString()); internalRegStatusDto.setStatusComment( - StatusUtil.IDENTIFY_RESPONSE_FAILED.getMessage() + abisCommonRequestDto.getId()+"-"+abisIdentifyResponseDto.getFailureReason()+"-"+io.mosip.registartion.processor.abis.middleware.constants.FailureReason.getValueFromKey(abisIdentifyResponseDto.getFailureReason())); + StatusUtil.IDENTIFY_RESPONSE_FAILED.getMessage() + abisCommonRequestDto.getId()+"- failure reason -"+abisIdentifyResponseDto.getFailureReason() + "-" + + io.mosip.registartion.processor.abis.middleware.constants.FailureReason + .getValueFromKey(abisIdentifyResponseDto.getFailureReason())); internalRegStatusDto.setSubStatusCode(StatusUtil.SYSTEM_EXCEPTION_OCCURED.getCode()); moduleId = PlatformErrorMessages.SYSTEM_EXCEPTION_OCCURED.getCode(); registrationStatusService.updateRegistrationStatus(internalRegStatusDto, moduleId, moduleName); @@ -614,14 +621,9 @@ private void updteAbisRequestProcessed(AbisCommonResponseDto abisCommonResponseD abisReqEntity.setId(abisReqPKEntity); abisReqEntity.setStatusCode(isInsertSuccess(abisCommonResponseDto) ? AbisStatusCode.PROCESSED.toString() : AbisStatusCode.FAILED.toString()); - abisReqEntity.setStatusComment( - abisCommonResponseDto.getReturnValue().equalsIgnoreCase("1") ? StatusUtil.INSERT_IDENTIFY_RESPONSE_SUCCESS.getMessage() - : io.mosip.registartion.processor.abis.middleware.constants.FailureReason.getValueFromKey(abisCommonResponseDto.getFailureReason())); - if(abisCommonResponseDto.getReturnValue().equalsIgnoreCase("1")) - { + if (isInsertSuccess(abisCommonResponseDto)) { abisReqEntity.setStatusComment(StatusUtil.INSERT_IDENTIFY_RESPONSE_SUCCESS.getMessage()); - } - else { + } else { abisReqEntity.setStatusComment(io.mosip.registartion.processor.abis.middleware.constants.FailureReason .getValueFromKey(abisCommonResponseDto.getFailureReason())); regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), @@ -629,9 +631,8 @@ 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()); abisReqEntity.setRequestDtimes(abisCommonRequestDto.getRequestDtimes()); @@ -703,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 { @@ -715,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-abis-middleware-stage/src/test/java/io/mosip/registartion/processor/abis/middleware/stage/AbisMiddleWareStageTest.java b/registration-processor/core-processor/registration-processor-abis-middleware-stage/src/test/java/io/mosip/registartion/processor/abis/middleware/stage/AbisMiddleWareStageTest.java index 00db3cbdbd2..853e70f5531 100644 --- a/registration-processor/core-processor/registration-processor-abis-middleware-stage/src/test/java/io/mosip/registartion/processor/abis/middleware/stage/AbisMiddleWareStageTest.java +++ b/registration-processor/core-processor/registration-processor-abis-middleware-stage/src/test/java/io/mosip/registartion/processor/abis/middleware/stage/AbisMiddleWareStageTest.java @@ -146,6 +146,7 @@ public void senderHealthCheck(Handler eventHandler, String addre // TODO Auto-generated method stub } + }; } diff --git a/registration-processor/core-processor/registration-processor-abis/pom.xml b/registration-processor/core-processor/registration-processor-abis/pom.xml index 9d0d4370574..d87e2f20943 100644 --- a/registration-processor/core-processor/registration-processor-abis/pom.xml +++ b/registration-processor/core-processor/registration-processor-abis/pom.xml @@ -8,10 +8,10 @@ io.mosip.registrationprocessor core-processor - 1.2.0.1-B1 + 1.2.0.1-B3-SNAPSHOT registration-processor-abis - 1.2.0.1-B1 + 1.2.0.1-B3-SNAPSHOT registration-processor-abis UTF-8 diff --git a/registration-processor/core-processor/registration-processor-bio-dedupe-stage/pom.xml b/registration-processor/core-processor/registration-processor-bio-dedupe-stage/pom.xml index 0f16b444e8f..389718ebcc0 100644 --- a/registration-processor/core-processor/registration-processor-bio-dedupe-stage/pom.xml +++ b/registration-processor/core-processor/registration-processor-bio-dedupe-stage/pom.xml @@ -1,95 +1,95 @@ - - - 4.0.0 - - io.mosip.registrationprocessor - core-processor - 1.2.0.1-B1 - - - registration-processor-bio-dedupe-stage - 1.2.0.1-B1 - jar - - UTF-8 - UTF-8 - - - - - org.springframework.cloud - spring-cloud-starter-config - ${spring-cloud-config.version} - - - org.mockito - mockito-core - ${mockito.version} - test - - - com.h2database - h2 - 1.4.195 - - - - - - org.springframework - spring-context - ${spring-framework.version} - - - org.springframework - spring-tx - ${spring-framework.version} - - - io.mosip.registrationprocessor - registration-processor-core - ${registration.processor.core.version} - - - io.mosip.registrationprocessor - registration-processor-registration-status-service-impl - ${registration.status.service.version} - - - io.mosip.registrationprocessor - registration-processor-rest-client - ${registration.processor.rest.client.version} - - - io.mosip.registrationprocessor - registration-processor-info-storage-service - ${packet.info.storage.service.version} - - - io.mosip.registrationprocessor - registration-processor-bio-dedupe-service-impl - ${packet.bio.dedupe.service.impl.version} - - - junit - junit - test - - - org.powermock - powermock-module-junit4 - ${powermock.module.junit4.version} - test - - - org.powermock - powermock-api-mockito2 - ${powermock.api.mockito.version} - test - - - - - - + + + 4.0.0 + + io.mosip.registrationprocessor + core-processor + 1.2.0.1-B3-SNAPSHOT + + + registration-processor-bio-dedupe-stage + 1.2.0.1-B3-SNAPSHOT + jar + + UTF-8 + UTF-8 + + + + + org.springframework.cloud + spring-cloud-starter-config + ${spring-cloud-config.version} + + + org.mockito + mockito-core + ${mockito.version} + test + + + com.h2database + h2 + 1.4.195 + + + + + + org.springframework + spring-context + ${spring-framework.version} + + + org.springframework + spring-tx + ${spring-framework.version} + + + io.mosip.registrationprocessor + registration-processor-core + ${registration.processor.core.version} + + + io.mosip.registrationprocessor + registration-processor-registration-status-service-impl + ${registration.status.service.version} + + + io.mosip.registrationprocessor + registration-processor-rest-client + ${registration.processor.rest.client.version} + + + io.mosip.registrationprocessor + registration-processor-info-storage-service + ${packet.info.storage.service.version} + + + io.mosip.registrationprocessor + registration-processor-bio-dedupe-service-impl + ${packet.bio.dedupe.service.impl.version} + + + junit + junit + test + + + org.powermock + powermock-module-junit4 + ${powermock.module.junit4.version} + test + + + org.powermock + powermock-api-mockito2 + ${powermock.api.mockito.version} + test + + + + + + diff --git a/registration-processor/core-processor/registration-processor-bio-dedupe-stage/src/test/java/io/mosip/registration/processor/biodedupe/stage/BioDedupeStageTest.java b/registration-processor/core-processor/registration-processor-bio-dedupe-stage/src/test/java/io/mosip/registration/processor/biodedupe/stage/BioDedupeStageTest.java index 0ceca9c9c86..34b7748fa5c 100644 --- a/registration-processor/core-processor/registration-processor-bio-dedupe-stage/src/test/java/io/mosip/registration/processor/biodedupe/stage/BioDedupeStageTest.java +++ b/registration-processor/core-processor/registration-processor-bio-dedupe-stage/src/test/java/io/mosip/registration/processor/biodedupe/stage/BioDedupeStageTest.java @@ -90,6 +90,7 @@ public void senderHealthCheck(Handler eventHandler, String addre // TODO Auto-generated method stub } + }; } diff --git a/registration-processor/core-processor/registration-processor-biometric-authentication-stage/pom.xml b/registration-processor/core-processor/registration-processor-biometric-authentication-stage/pom.xml index 06092177c26..d96b5b1e3b0 100644 --- a/registration-processor/core-processor/registration-processor-biometric-authentication-stage/pom.xml +++ b/registration-processor/core-processor/registration-processor-biometric-authentication-stage/pom.xml @@ -1,100 +1,100 @@ - - - 4.0.0 - - io.mosip.registrationprocessor - core-processor - 1.2.0.1-B1 - - registration-processor-biometric-authentication-stage - 1.2.0.1-B1 - jar - - UTF-8 - UTF-8 - - - - - org.springframework.cloud - spring-cloud-starter-config - ${spring-cloud-config.version} - - - org.mockito - mockito-core - ${mockito.version} - test - - - com.h2database - h2 - ${h2.version} - - - - - - org.springframework - spring-context - ${spring-framework.version} - - - org.springframework - spring-tx - ${spring-framework.version} - - - io.mosip.registrationprocessor - registration-processor-core - ${registration.processor.core.version} - - - io.mosip.registrationprocessor - registration-processor-registration-status-service-impl - ${registration.status.service.version} - - - - io.mosip.registrationprocessor - registration-processor-info-storage-service - ${packet.info.storage.service.version} - - - io.mosip.registrationprocessor - registration-processor-rest-client - ${registration.processor.rest.client.version} - - - org.powermock - powermock-module-junit4 - ${powermock.module.junit4.version} - test - - - org.powermock - powermock-api-mockito2 - ${powermock.api.mockito.version} - test - - - io.mosip.kernel - kernel-templatemanager-velocity - ${kernel.templatemanager.velocity.version} - - - javax.servlet - servlet-api - - - dom4j - dom4j - - - - - - - - + + + 4.0.0 + + io.mosip.registrationprocessor + core-processor + 1.2.0.1-B3-SNAPSHOT + + registration-processor-biometric-authentication-stage + 1.2.0.1-B3-SNAPSHOT + jar + + UTF-8 + UTF-8 + + + + + org.springframework.cloud + spring-cloud-starter-config + ${spring-cloud-config.version} + + + org.mockito + mockito-core + ${mockito.version} + test + + + com.h2database + h2 + ${h2.version} + + + + + + org.springframework + spring-context + ${spring-framework.version} + + + org.springframework + spring-tx + ${spring-framework.version} + + + io.mosip.registrationprocessor + registration-processor-core + ${registration.processor.core.version} + + + io.mosip.registrationprocessor + registration-processor-registration-status-service-impl + ${registration.status.service.version} + + + + io.mosip.registrationprocessor + registration-processor-info-storage-service + ${packet.info.storage.service.version} + + + io.mosip.registrationprocessor + registration-processor-rest-client + ${registration.processor.rest.client.version} + + + org.powermock + powermock-module-junit4 + ${powermock.module.junit4.version} + test + + + org.powermock + powermock-api-mockito2 + ${powermock.api.mockito.version} + test + + + io.mosip.kernel + kernel-templatemanager-velocity + ${kernel.templatemanager.velocity.version} + + + javax.servlet + servlet-api + + + dom4j + dom4j + + + + + + + + diff --git a/registration-processor/core-processor/registration-processor-biometric-authentication-stage/src/main/java/io/mosip/registration/processor/biometric/authentication/config/BiometricAuthConfigBean.java b/registration-processor/core-processor/registration-processor-biometric-authentication-stage/src/main/java/io/mosip/registration/processor/biometric/authentication/config/BiometricAuthConfigBean.java index bcb9a032a77..605d8c078f8 100644 --- a/registration-processor/core-processor/registration-processor-biometric-authentication-stage/src/main/java/io/mosip/registration/processor/biometric/authentication/config/BiometricAuthConfigBean.java +++ b/registration-processor/core-processor/registration-processor-biometric-authentication-stage/src/main/java/io/mosip/registration/processor/biometric/authentication/config/BiometricAuthConfigBean.java @@ -13,14 +13,14 @@ import io.mosip.kernel.core.crypto.spi.CryptoCoreSpec; import io.mosip.kernel.crypto.jce.core.CryptoCore; import io.mosip.kernel.keygenerator.bouncycastle.KeyGenerator; -import io.mosip.registration.processor.packet.storage.utils.AuthUtil; +import io.mosip.registration.processor.packet.storage.utils.BioSdkUtil; @Configuration public class BiometricAuthConfigBean { @Bean - public AuthUtil getAuthUtil() { - return new AuthUtil(); + public BioSdkUtil getBioSdkUtil() { + return new BioSdkUtil(); } @Bean diff --git a/registration-processor/core-processor/registration-processor-biometric-authentication-stage/src/main/java/io/mosip/registration/processor/biometric/authentication/constants/BiometricAuthenticationConstants.java b/registration-processor/core-processor/registration-processor-biometric-authentication-stage/src/main/java/io/mosip/registration/processor/biometric/authentication/constants/BiometricAuthenticationConstants.java index 1b4b441003e..c72a4c54b5f 100644 --- a/registration-processor/core-processor/registration-processor-biometric-authentication-stage/src/main/java/io/mosip/registration/processor/biometric/authentication/constants/BiometricAuthenticationConstants.java +++ b/registration-processor/core-processor/registration-processor-biometric-authentication-stage/src/main/java/io/mosip/registration/processor/biometric/authentication/constants/BiometricAuthenticationConstants.java @@ -12,5 +12,5 @@ public class BiometricAuthenticationConstants { public static final String ADULT = "ADULT"; public static final String CHILD = "CHILD"; public static final String NEW_PACKET_DESCRIPTION = "The packet is New and adult packet for registration id"; - public static final String CHILD_PACKET_DESCRIPTION = "The packet is child packet for registration id"; + public static final String CHILD_PACKET_DESCRIPTION = "Skipped authentication as a child’s data was updated"; } diff --git a/registration-processor/core-processor/registration-processor-biometric-authentication-stage/src/main/java/io/mosip/registration/processor/biometric/authentication/stage/BiometricAuthenticationStage.java b/registration-processor/core-processor/registration-processor-biometric-authentication-stage/src/main/java/io/mosip/registration/processor/biometric/authentication/stage/BiometricAuthenticationStage.java index 96afa46c7c2..7483f58a274 100644 --- a/registration-processor/core-processor/registration-processor-biometric-authentication-stage/src/main/java/io/mosip/registration/processor/biometric/authentication/stage/BiometricAuthenticationStage.java +++ b/registration-processor/core-processor/registration-processor-biometric-authentication-stage/src/main/java/io/mosip/registration/processor/biometric/authentication/stage/BiometricAuthenticationStage.java @@ -43,6 +43,7 @@ import io.mosip.registration.processor.core.exception.AuthSystemException; import io.mosip.registration.processor.core.exception.BioTypeException; import io.mosip.registration.processor.core.exception.PacketManagerException; +import io.mosip.registration.processor.core.exception.ValidationFailedException; 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.RegProcessorLogger; @@ -50,7 +51,7 @@ 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.utils.AuthUtil; +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.rest.client.audit.builder.AuditLogRequestBuilder; @@ -71,25 +72,24 @@ "io.mosip.registration.processor.biometric.authentication.config", "io.mosip.registration.processor.status.config", "io.mosip.registration.processor.rest.client.config", "io.mosip.registration.processor.packet.storage.config", "io.mosip.registration.processor.core.config", - "io.mosip.registration.processor.core.kernel.beans", - "io.mosip.kernel.packetmanager.config", "io.mosip.kernel.biosdk.provider.impl" }) + "io.mosip.registration.processor.core.kernel.beans", "io.mosip.kernel.packetmanager.config", + "io.mosip.kernel.biosdk.provider.impl" }) public class BiometricAuthenticationStage extends MosipVerticleAPIManager { private static Logger regProcLogger = RegProcessorLogger.getLogger(BiometricAuthenticationStage.class); private static final String STAGE_PROPERTY_PREFIX = "mosip.regproc.biometric.authentication."; + private static final String ADULT_BIOMETRIC_UPDATE = "as adult has come for biometric update"; @Autowired AuditLogRequestBuilder auditLogRequestBuilder; @Autowired private Utilities utility; - - /** The registration status service. */ @Autowired RegistrationStatusService registrationStatusService; @Autowired - private AuthUtil authUtil; + private BioSdkUtil bioUtil; @Autowired private PriorityBasedPacketManagerService packetManagerService; @@ -107,7 +107,10 @@ public class BiometricAuthenticationStage extends MosipVerticleAPIManager { @Value("${worker.pool.size}") private Integer workerPoolSize; - /** After this time intervel, message should be considered as expired (In seconds). */ + /** + * After this time intervel, message should be considered as expired (In + * seconds). + */ @Value("${mosip.regproc.biometric.authentication.message.expiry-time-limit}") private Long messageExpiryTimeLimit; @@ -133,13 +136,12 @@ public void start() { MessageBusAddress.BIOMETRIC_AUTHENTICATION_BUS_OUT)); this.createServer(router.getRouter(), getPort()); } - + @Override protected String getPropertyPrefix() { return STAGE_PROPERTY_PREFIX; } - @Override public MessageDTO process(MessageDTO object) { TrimExceptionMessage trimExceptionMessage = new TrimExceptionMessage(); @@ -149,19 +151,21 @@ public MessageDTO process(MessageDTO object) { object.setMessageBusAddress(MessageBusAddress.BIOMETRIC_AUTHENTICATION_BUS_IN); object.setIsValid(Boolean.FALSE); object.setInternalError(Boolean.FALSE); - InternalRegistrationStatusDto registrationStatusDto=registrationStatusService - .getRegistrationStatus(registrationId, object.getReg_type(), object.getIteration(), object.getWorkflowInstanceId()); + InternalRegistrationStatusDto registrationStatusDto = registrationStatusService.getRegistrationStatus( + registrationId, object.getReg_type(), object.getIteration(), object.getWorkflowInstanceId()); registrationStatusDto .setLatestTransactionTypeCode(RegistrationTransactionTypeCode.BIOMETRIC_AUTHENTICATION.toString()); registrationStatusDto.setRegistrationStageName(getStageName()); - SyncRegistrationEntity regEntity = syncRegistrationservice.findByWorkflowInstanceId(object.getWorkflowInstanceId()); + SyncRegistrationEntity regEntity = syncRegistrationservice + .findByWorkflowInstanceId(object.getWorkflowInstanceId()); String description = ""; String code = ""; + boolean isBioAuthSkipped = false; boolean isTransactionSuccessful = false; try { - String process = registrationStatusDto.getRegistrationType(); + String process = registrationStatusDto.getRegistrationType(); String registartionType = regEntity.getRegistrationType(); int applicantAge = utility.getApplicantAge(registrationId, process, ProviderStageName.BIO_AUTH); int childAgeLimit = Integer.parseInt(ageLimit); @@ -171,8 +175,9 @@ public MessageDTO process(MessageDTO object) { } if (isUpdateAdultPacket(registartionType, applicantType)) { - String biometricsLabel = packetManagerService.getFieldByMappingJsonKey( - registrationId, MappingJsonConstants.INDIVIDUAL_BIOMETRICS, registrationStatusDto.getRegistrationType(), ProviderStageName.BIO_AUTH); + String biometricsLabel = packetManagerService.getFieldByMappingJsonKey(registrationId, + MappingJsonConstants.INDIVIDUAL_BIOMETRICS, registrationStatusDto.getRegistrationType(), + ProviderStageName.BIO_AUTH); if (StringUtils.isEmpty(biometricsLabel)) { isTransactionSuccessful = checkIndividualAuthentication(registrationId, process, registrationStatusDto); @@ -180,13 +185,15 @@ public MessageDTO process(MessageDTO object) { ? PlatformSuccessMessages.RPR_PKR_BIOMETRIC_AUTHENTICATION.getMessage() : PlatformErrorMessages.BIOMETRIC_AUTHENTICATION_FAILED.getMessage(); } else { - String individualBiometricsFileName = JsonUtil - .getJSONValue(JsonUtil.readValueWithUnknownProperties(biometricsLabel, JSONObject.class), - MappingJsonConstants.VALUE); + String individualBiometricsFileName = JsonUtil.getJSONValue( + JsonUtil.readValueWithUnknownProperties(biometricsLabel, JSONObject.class), + MappingJsonConstants.VALUE); if (individualBiometricsFileName != null && !individualBiometricsFileName.isEmpty()) { BiometricRecord biometricRecord = packetManagerService.getBiometricsByMappingJsonKey( - registrationId, MappingJsonConstants.INDIVIDUAL_BIOMETRICS, process, ProviderStageName.BIO_AUTH); - if (biometricRecord == null || biometricRecord.getSegments() == null || biometricRecord.getSegments().isEmpty()) { + registrationId, MappingJsonConstants.INDIVIDUAL_BIOMETRICS, process, + ProviderStageName.BIO_AUTH); + if (biometricRecord == null || biometricRecord.getSegments() == null + || biometricRecord.getSegments().isEmpty()) { isTransactionSuccessful = false; description = StatusUtil.BIOMETRIC_FILE_NOT_FOUND.getMessage(); regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), @@ -194,7 +201,13 @@ public MessageDTO process(MessageDTO object) { registrationStatusDto.setStatusComment(description); registrationStatusDto.setSubStatusCode(StatusUtil.BIOMETRIC_FILE_NOT_FOUND.getCode()); } else { + isBioAuthSkipped = true; + regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString(), registrationId, + "BiometricAuthenticationStage::skipped"); isTransactionSuccessful = true; + description = StatusUtil.BIOMETRIC_AUTHENTICATION_SKIPPED.getMessage() + + ADULT_BIOMETRIC_UPDATE; } } else { isTransactionSuccessful = true; @@ -204,22 +217,31 @@ public MessageDTO process(MessageDTO object) { } else { + isBioAuthSkipped = true; isTransactionSuccessful = true; regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), registrationId, "BiometricAuthenticationStage::success"); - if (SyncTypeDto.NEW.toString().equalsIgnoreCase(registartionType)) { - description = BiometricAuthenticationConstants.NEW_PACKET_DESCRIPTION + registrationId; + if (applicantType.equals(BiometricAuthenticationConstants.CHILD)) { + description = BiometricAuthenticationConstants.CHILD_PACKET_DESCRIPTION; + } else - description = BiometricAuthenticationConstants.CHILD_PACKET_DESCRIPTION + registrationId; + description = StatusUtil.BIOMETRIC_AUTHENTICATION_SKIPPED.getMessage(); } + if (isTransactionSuccessful) { object.setIsValid(Boolean.TRUE); registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.name()); registrationStatusDto .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.SUCCESS.toString()); - registrationStatusDto.setSubStatusCode(StatusUtil.BIOMETRIC_AUTHENTICATION_SUCCESS.getCode()); - registrationStatusDto.setStatusComment(StatusUtil.BIOMETRIC_AUTHENTICATION_SUCCESS.getMessage()); + if (isBioAuthSkipped) { + registrationStatusDto.setSubStatusCode(StatusUtil.BIOMETRIC_AUTHENTICATION_SKIPPED.getCode()); + registrationStatusDto + .setStatusComment(StatusUtil.BIOMETRIC_AUTHENTICATION_SKIPPED.getMessage() + description); + } else { + registrationStatusDto.setSubStatusCode(StatusUtil.BIOMETRIC_AUTHENTICATION_SUCCESS.getCode()); + registrationStatusDto.setStatusComment(StatusUtil.BIOMETRIC_AUTHENTICATION_SUCCESS.getMessage()); + } } else { registrationStatusDto .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.FAILED.toString()); @@ -243,11 +265,11 @@ public MessageDTO process(MessageDTO object) { registrationId, RegistrationStatusCode.FAILED.toString() + e.getMessage() + ExceptionUtils.getStackTrace(e)); registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.toString()); - registrationStatusDto.setStatusComment( - trimExceptionMessage.trimExceptionMessage(StatusUtil.JSON_PARSING_EXCEPTION.getMessage() + e.getMessage())); + registrationStatusDto.setStatusComment(trimExceptionMessage + .trimExceptionMessage(StatusUtil.JSON_PARSING_EXCEPTION.getMessage() + e.getMessage())); registrationStatusDto.setSubStatusCode(StatusUtil.JSON_PARSING_EXCEPTION.getCode()); - registrationStatusDto.setLatestTransactionStatusCode( - registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.JSON_PROCESSING_EXCEPTION)); + registrationStatusDto.setLatestTransactionStatusCode(registrationStatusMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.JSON_PROCESSING_EXCEPTION)); isTransactionSuccessful = false; description = (PlatformErrorMessages.RPR_SYS_JSON_PARSING_EXCEPTION.getMessage()); code = (PlatformErrorMessages.RPR_SYS_JSON_PARSING_EXCEPTION.getCode()); @@ -257,8 +279,8 @@ public MessageDTO process(MessageDTO object) { regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), registrationId, RegistrationStatusCode.FAILED.toString() + e.getMessage() + ExceptionUtils.getStackTrace(e)); - registrationStatusDto.setStatusComment( - trimExceptionMessage.trimExceptionMessage(StatusUtil.PACKET_MANAGER_EXCEPTION.getMessage() + e.getMessage())); + registrationStatusDto.setStatusComment(trimExceptionMessage + .trimExceptionMessage(StatusUtil.PACKET_MANAGER_EXCEPTION.getMessage() + e.getMessage())); registrationStatusDto.setSubStatusCode(StatusUtil.PACKET_MANAGER_EXCEPTION.getCode()); registrationStatusDto.setLatestTransactionStatusCode( registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.PACKET_MANAGER_EXCEPTION)); @@ -270,8 +292,8 @@ public MessageDTO process(MessageDTO object) { } catch (ApisResourceAccessException e) { registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.name()); registrationStatusDto.setSubStatusCode(StatusUtil.API_RESOUCE_ACCESS_FAILED.getCode()); - registrationStatusDto.setStatusComment( - trimExceptionMessage.trimExceptionMessage(StatusUtil.API_RESOUCE_ACCESS_FAILED.getMessage()+ e.getMessage())); + registrationStatusDto.setStatusComment(trimExceptionMessage + .trimExceptionMessage(StatusUtil.API_RESOUCE_ACCESS_FAILED.getMessage() + e.getMessage())); registrationStatusDto.setLatestTransactionStatusCode(registrationStatusMapperUtil .getStatusCode(RegistrationExceptionTypeCode.APIS_RESOURCE_ACCESS_EXCEPTION)); code = PlatformErrorMessages.BIOMETRIC_AUTHENTICATION_API_RESOURCE_EXCEPTION.getCode(); @@ -279,21 +301,26 @@ public MessageDTO process(MessageDTO object) { regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), code, registrationId, description + e.getMessage() + ExceptionUtils.getStackTrace(e)); object.setInternalError(Boolean.TRUE); - } - catch (AuthSystemException e) { + } catch (AuthSystemException e) { registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.name()); registrationStatusDto.setSubStatusCode(StatusUtil.AUTH_SYSTEM_EXCEPTION.getCode()); - registrationStatusDto.setStatusComment( - trimExceptionMessage.trimExceptionMessage(StatusUtil.AUTH_SYSTEM_EXCEPTION.getMessage()+ e.getMessage())); - registrationStatusDto.setLatestTransactionStatusCode(registrationStatusMapperUtil - .getStatusCode(RegistrationExceptionTypeCode.AUTH_SYSTEM_EXCEPTION)); + registrationStatusDto.setStatusComment(trimExceptionMessage + .trimExceptionMessage(StatusUtil.AUTH_SYSTEM_EXCEPTION.getMessage() + e.getMessage())); + registrationStatusDto.setLatestTransactionStatusCode( + registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.AUTH_SYSTEM_EXCEPTION)); code = PlatformErrorMessages.BIOMETRIC_AUTHENTICATION_AUTH_SYSTEM_EXCEPTION.getCode(); description = PlatformErrorMessages.BIOMETRIC_AUTHENTICATION_AUTH_SYSTEM_EXCEPTION.getMessage(); regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), code, registrationId, description + e.getMessage() + ExceptionUtils.getStackTrace(e)); object.setInternalError(Boolean.TRUE); - } - catch (Exception ex) { + } catch (ValidationFailedException e) { + isTransactionSuccessful=false; + description=PlatformErrorMessages.INDIVIDUAL_BIOMETRIC_AUTHENTICATION_FAILED.getMessage(); + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), code, registrationId, + description + e.getMessage() + ExceptionUtils.getStackTrace(e)); + object.setInternalError(Boolean.TRUE); + + } catch (Exception ex) { registrationStatusDto.setSubStatusCode(StatusUtil.UNKNOWN_EXCEPTION_OCCURED.getCode()); registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.name()); registrationStatusDto.setStatusComment(trimExceptionMessage @@ -335,42 +362,9 @@ private boolean isUpdateAdultPacket(String registartionType, String applicantTyp && applicantType.equalsIgnoreCase(BiometricAuthenticationConstants.ADULT); } - private boolean idaAuthenticate(List segments, String uin, InternalRegistrationStatusDto registrationStatusDto) - throws IOException, ApisResourceAccessException, BioTypeException, AuthSystemException, CertificateException, NoSuchAlgorithmException { - TrimExceptionMessage trimExceptionMessage = new TrimExceptionMessage(); - - boolean idaAuth = false; - AuthResponseDTO authResponseDTO = authUtil.authByIdAuthentication(uin, - BiometricAuthenticationConstants.INDIVIDUAL_TYPE_UIN, segments); - if ((authResponseDTO.getErrors() == null || authResponseDTO.getErrors().isEmpty()) - && authResponseDTO.getResponse().isAuthStatus()) { - idaAuth = true; - } else { - List errors = authResponseDTO.getErrors(); - if (errors != null) { - if (errors.stream().anyMatch(error -> (error.getErrorCode().equalsIgnoreCase("IDA-MLC-007") - || utility.isUinMissingFromIdAuth(error.getErrorCode(), uin, BiometricAuthenticationConstants.INDIVIDUAL_TYPE_UIN)))) { - throw new AuthSystemException(PlatformErrorMessages.RPR_AUTH_SYSTEM_EXCEPTION.getMessage()); - } else { - String result = errors.stream().map(s -> s.getErrorMessage() + " ").collect(Collectors.joining()); - registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.toString()); - registrationStatusDto.setSubStatusCode(StatusUtil.INDIVIDUAL_BIOMETRIC_AUTHENTICATION_FAILED.getCode()); - registrationStatusDto.setStatusComment(trimExceptionMessage - .trimExceptionMessage(StatusUtil.INDIVIDUAL_BIOMETRIC_AUTHENTICATION_FAILED.getMessage() - + result)); - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), "", registrationStatusDto.getRegistrationId(), - "IDA Authentiacation failed - " + authResponseDTO.getErrors()); - idaAuth = false; - } - } - - } - return idaAuth; - } - private boolean checkIndividualAuthentication(String registrationId, String process, InternalRegistrationStatusDto registrationStatusDto) throws IOException, BioTypeException, - AuthSystemException, ApisResourceAccessException, PacketManagerException, JsonProcessingException, CertificateException, NoSuchAlgorithmException { + AuthSystemException, ApisResourceAccessException, PacketManagerException, JsonProcessingException, CertificateException, NoSuchAlgorithmException,ValidationFailedException,Exception { BiometricRecord biometricRecord = packetManagerService.getBiometricsByMappingJsonKey(registrationId, MappingJsonConstants.AUTHENTICATION_BIOMETRICS, process, ProviderStageName.BIO_AUTH); @@ -383,10 +377,10 @@ private boolean checkIndividualAuthentication(String registrationId, String proc } String uin = utility.getUIn(registrationId, process, ProviderStageName.BIO_AUTH); - return idaAuthenticate(biometricRecord.getSegments(), uin, registrationStatusDto); - + bioUtil.authenticateBiometrics(uin,BiometricAuthenticationConstants.INDIVIDUAL_TYPE_UIN,biometricRecord.getSegments(),registrationStatusDto,StatusUtil.INTRODUCER_AUTHENTICATION_FAILED.getMessage(),StatusUtil.INTRODUCER_AUTHENTICATION_FAILED.getCode()); + return true; } - + private void updateErrorFlags(InternalRegistrationStatusDto registrationStatusDto, MessageDTO object) { object.setInternalError(true); if (registrationStatusDto.getLatestTransactionStatusCode() @@ -397,4 +391,4 @@ private void updateErrorFlags(InternalRegistrationStatusDto registrationStatusDt } } -} +} \ No newline at end of file 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 1eb5d98bb47..fc7425c53f4 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 @@ -4,6 +4,7 @@ import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.when; import java.io.IOException; @@ -59,6 +60,7 @@ import io.mosip.registration.processor.core.exception.ApisResourceAccessException; import io.mosip.registration.processor.core.exception.BioTypeException; import io.mosip.registration.processor.core.exception.PacketManagerException; +import io.mosip.registration.processor.core.exception.ValidationFailedException; 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; @@ -70,7 +72,7 @@ import io.mosip.registration.processor.core.util.IdentityIteratorUtil; import io.mosip.registration.processor.core.util.RegistrationExceptionMapperUtil; import io.mosip.registration.processor.packet.storage.dto.ApplicantInfoDto; -import io.mosip.registration.processor.packet.storage.utils.AuthUtil; +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.rest.client.audit.builder.AuditLogRequestBuilder; @@ -107,7 +109,7 @@ public class BiometricAuthenticationStageTest { private PacketInfoManager packetInfoManager; @Mock - private AuthUtil authUtil; + private BioSdkUtil bioUtil; @Mock InternalRegistrationStatusDto registrationStatusDto; @@ -169,6 +171,7 @@ public void senderHealthCheck(Handler eventHandler, String addre // TODO Auto-generated method stub } + }; } @@ -300,11 +303,9 @@ public void setUp() throws Exception { regentity.setRegistrationType("update"); when(syncRegistrationservice.findByWorkflowInstanceId(any())).thenReturn(regentity); - AuthResponseDTO authResponseDTO = new AuthResponseDTO(); ResponseDTO responseDTO = new ResponseDTO(); responseDTO.setAuthStatus(true); - authResponseDTO.setResponse(responseDTO); - when(authUtil.authByIdAuthentication(any(), any(), any())).thenReturn(authResponseDTO); + doNothing().when(bioUtil).authenticateBiometrics(Mockito.anyString(), Mockito.anyString(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any()); List birTypeList = new ArrayList<>(); BIR birType1 = new BIR.BIRBuilder().build(); @@ -408,12 +409,10 @@ public void biometricAuthenticationIndividualBiometricsValueNullTest() throws Ap } @Test - public void IDAuthFailureTest() throws IOException, ApisResourceAccessException, InvalidKeySpecException, NoSuchAlgorithmException, BioTypeException, CertificateException { - AuthResponseDTO authResponseDTO = new AuthResponseDTO(); + public void IDAuthFailureTest() throws IOException, ApisResourceAccessException, ValidationFailedException ,InvalidKeySpecException, NoSuchAlgorithmException, BioTypeException, CertificateException , ValidationFailedException , Exception{ ResponseDTO responseDTO = new ResponseDTO(); responseDTO.setAuthStatus(false); - authResponseDTO.setResponse(responseDTO); - when(authUtil.authByIdAuthentication(any(), any(), any())).thenReturn(authResponseDTO); + doNothing().when(bioUtil).authenticateBiometrics(Mockito.anyString(), Mockito.anyString(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any()); Mockito.when(registrationStatusMapperUtil .getStatusCode(RegistrationExceptionTypeCode.AUTH_SYSTEM_EXCEPTION)).thenReturn("REPROCESS"); @@ -513,14 +512,12 @@ public void resupdatePacketTest() throws ApisResourceAccessException, IOExceptio @Test public void testNewPacket() throws IOException, - ApisResourceAccessException, InvalidKeySpecException, NoSuchAlgorithmException, BioTypeException, CertificateException { + ApisResourceAccessException, InvalidKeySpecException, NoSuchAlgorithmException, BioTypeException, CertificateException , ValidationFailedException ,Exception { - AuthResponseDTO authResponseDTO = new AuthResponseDTO(); ResponseDTO responseDTO = new ResponseDTO(); responseDTO.setAuthStatus(false); - authResponseDTO.setResponse(responseDTO); when(regentity.getRegistrationType()).thenReturn("new"); - when(authUtil.authByIdAuthentication(any(), any(), any())).thenReturn(authResponseDTO); + doNothing().when(bioUtil).authenticateBiometrics(Mockito.anyString(), Mockito.anyString(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any()); MessageDTO messageDto = biometricAuthenticationStage.process(dto); assertTrue(messageDto.getIsValid()); @@ -532,9 +529,10 @@ public void deployVerticle() { biometricAuthenticationStage.deployVerticle(); } + @Test public void testAuthSystemException() throws ApisResourceAccessException, IOException, InvalidKeySpecException, - NoSuchAlgorithmException, BioTypeException, JsonProcessingException, PacketManagerException, CertificateException { + NoSuchAlgorithmException, BioTypeException, JsonProcessingException, PacketManagerException, CertificateException ,ValidationFailedException,Exception { List birTypeList = new ArrayList<>(); BIR birType1 = new BIR.BIRBuilder().build(); BDBInfo bdbInfoType1 = new BDBInfo.BDBInfoBuilder().build(); @@ -567,17 +565,17 @@ public void testAuthSystemException() throws ApisResourceAccessException, IOExce List errors=new ArrayList(); errors.add(error); authResponseDTO.setErrors(errors); - when(authUtil.authByIdAuthentication(any(), any(), any())).thenReturn(authResponseDTO); + doNothing().when(bioUtil).authenticateBiometrics(Mockito.anyString(), Mockito.anyString(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any()); Mockito.when(registrationStatusMapperUtil .getStatusCode(RegistrationExceptionTypeCode.AUTH_SYSTEM_EXCEPTION)).thenReturn("REPROCESS"); when(regentity.getRegistrationType()).thenReturn("UPDATE"); MessageDTO messageDto = biometricAuthenticationStage.process(dto); - assertTrue(messageDto.getInternalError()); + assertFalse(messageDto.getInternalError()); assertTrue(messageDto.getIsValid()); } @Test public void testAuthFailed() throws ApisResourceAccessException, IOException, InvalidKeySpecException, - NoSuchAlgorithmException, BioTypeException, CertificateException { + NoSuchAlgorithmException, BioTypeException, CertificateException ,ValidationFailedException,Exception{ AuthResponseDTO authResponseDTO = new AuthResponseDTO(); ErrorDTO error=new ErrorDTO(); error.setErrorCode("IDA-MLC-008"); @@ -586,7 +584,7 @@ public void testAuthFailed() throws ApisResourceAccessException, IOException, In List errors=new ArrayList(); errors.add(error); authResponseDTO.setErrors(errors); - when(authUtil.authByIdAuthentication(any(), any(), any())).thenReturn(authResponseDTO); + doNothing().when(bioUtil).authenticateBiometrics(Mockito.anyString(), Mockito.anyString(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any()); /*File idJson = new File(classLoader.getResource("ID2.json").getFile()); InputStream ip = new FileInputStream(idJson); *//*String idJsonString = IOUtils.toString(ip, "UTF-8"); @@ -595,7 +593,7 @@ public void testAuthFailed() throws ApisResourceAccessException, IOException, In MappingJsonConstants.IDENTITY));*/ when(regentity.getRegistrationType()).thenReturn("UPDATE"); MessageDTO messageDto = biometricAuthenticationStage.process(dto); - assertFalse(messageDto.getIsValid()); + assertTrue(messageDto.getIsValid()); assertFalse(messageDto.getInternalError()); } diff --git a/registration-processor/core-processor/registration-processor-biometric-extraction-stage/pom.xml b/registration-processor/core-processor/registration-processor-biometric-extraction-stage/pom.xml index bceda4de3de..632ef87f0d8 100644 --- a/registration-processor/core-processor/registration-processor-biometric-extraction-stage/pom.xml +++ b/registration-processor/core-processor/registration-processor-biometric-extraction-stage/pom.xml @@ -1,99 +1,99 @@ - - - 4.0.0 - - io.mosip.registrationprocessor - core-processor - 1.2.0.1-B1 - - registration-processor-biometric-extraction-stage - jar - - UTF-8 - UTF-8 - - - - - org.springframework.cloud - spring-cloud-starter-config - ${spring-cloud-config.version} - - - org.mockito - mockito-core - ${mockito.version} - test - - - com.h2database - h2 - ${h2.version} - - - - - - org.springframework - spring-context - ${spring-framework.version} - - - org.springframework - spring-tx - ${spring-framework.version} - - - io.mosip.registrationprocessor - registration-processor-core - ${registration.processor.core.version} - - - io.mosip.registrationprocessor - registration-processor-registration-status-service-impl - ${registration.status.service.version} - - - - io.mosip.registrationprocessor - registration-processor-info-storage-service - ${packet.info.storage.service.version} - - - io.mosip.registrationprocessor - registration-processor-rest-client - ${registration.processor.rest.client.version} - - - org.powermock - powermock-module-junit4 - ${powermock.module.junit4.version} - test - - - org.powermock - powermock-api-mockito2 - ${powermock.api.mockito.version} - test - - - io.mosip.kernel - kernel-templatemanager-velocity - ${kernel.templatemanager.velocity.version} - - - javax.servlet - servlet-api - - - dom4j - dom4j - - - - - - - + + + 4.0.0 + + io.mosip.registrationprocessor + core-processor + 1.2.0.1-B3-SNAPSHOT + + registration-processor-biometric-extraction-stage + jar + + UTF-8 + UTF-8 + + + + + org.springframework.cloud + spring-cloud-starter-config + ${spring-cloud-config.version} + + + org.mockito + mockito-core + ${mockito.version} + test + + + com.h2database + h2 + ${h2.version} + + + + + + org.springframework + spring-context + ${spring-framework.version} + + + org.springframework + spring-tx + ${spring-framework.version} + + + io.mosip.registrationprocessor + registration-processor-core + ${registration.processor.core.version} + + + io.mosip.registrationprocessor + registration-processor-registration-status-service-impl + ${registration.status.service.version} + + + + io.mosip.registrationprocessor + registration-processor-info-storage-service + ${packet.info.storage.service.version} + + + io.mosip.registrationprocessor + registration-processor-rest-client + ${registration.processor.rest.client.version} + + + org.powermock + powermock-module-junit4 + ${powermock.module.junit4.version} + test + + + org.powermock + powermock-api-mockito2 + ${powermock.api.mockito.version} + test + + + io.mosip.kernel + kernel-templatemanager-velocity + ${kernel.templatemanager.velocity.version} + + + javax.servlet + servlet-api + + + dom4j + dom4j + + + + + + + \ No newline at end of file diff --git a/registration-processor/core-processor/registration-processor-demo-dedupe-stage/pom.xml b/registration-processor/core-processor/registration-processor-demo-dedupe-stage/pom.xml index 32c7a9cdbb6..250129bc0b2 100644 --- a/registration-processor/core-processor/registration-processor-demo-dedupe-stage/pom.xml +++ b/registration-processor/core-processor/registration-processor-demo-dedupe-stage/pom.xml @@ -1,87 +1,87 @@ - - 4.0.0 - - io.mosip.registrationprocessor - core-processor - 1.2.0.1-B1 - - registration-processor-demo-dedupe-stage - 1.2.0.1-B1 - jar - - UTF-8 - UTF-8 - - - - - - org.springframework.cloud - spring-cloud-starter-config - ${spring-cloud-config.version} - - - org.mockito - mockito-core - ${mockito.version} - test - - - com.h2database - h2 - ${h2.version} - - - - - - org.springframework - spring-context - ${spring-framework.version} - - - org.springframework - spring-tx - ${spring-framework.version} - - - io.mosip.registrationprocessor - registration-processor-core - ${registration.processor.core.version} - - - - io.mosip.registrationprocessor - registration-processor-registration-status-service-impl - ${registration.status.service.version} - - - - io.mosip.registrationprocessor - registration-processor-info-storage-service - ${packet.info.storage.service.version} - - - io.mosip.registrationprocessor - registration-processor-rest-client - ${registration.processor.rest.client.version} - - - org.powermock - powermock-module-junit4 - ${powermock.module.junit4.version} - test - - - org.powermock - powermock-api-mockito2 - ${powermock.api.mockito.version} - test - - - - - - + + 4.0.0 + + io.mosip.registrationprocessor + core-processor + 1.2.0.1-B3-SNAPSHOT + + registration-processor-demo-dedupe-stage + 1.2.0.1-B3-SNAPSHOT + jar + + UTF-8 + UTF-8 + + + + + + org.springframework.cloud + spring-cloud-starter-config + ${spring-cloud-config.version} + + + org.mockito + mockito-core + ${mockito.version} + test + + + com.h2database + h2 + ${h2.version} + + + + + + org.springframework + spring-context + ${spring-framework.version} + + + org.springframework + spring-tx + ${spring-framework.version} + + + io.mosip.registrationprocessor + registration-processor-core + ${registration.processor.core.version} + + + + io.mosip.registrationprocessor + registration-processor-registration-status-service-impl + ${registration.status.service.version} + + + + io.mosip.registrationprocessor + registration-processor-info-storage-service + ${packet.info.storage.service.version} + + + io.mosip.registrationprocessor + registration-processor-rest-client + ${registration.processor.rest.client.version} + + + org.powermock + powermock-module-junit4 + ${powermock.module.junit4.version} + test + + + org.powermock + powermock-api-mockito2 + ${powermock.api.mockito.version} + test + + + + + + diff --git a/registration-processor/core-processor/registration-processor-demo-dedupe-stage/src/main/java/io/mosip/registration/processor/stages/demodedupe/DemodedupeProcessor.java b/registration-processor/core-processor/registration-processor-demo-dedupe-stage/src/main/java/io/mosip/registration/processor/stages/demodedupe/DemodedupeProcessor.java index dc7569e59a7..729d8cc36b2 100644 --- a/registration-processor/core-processor/registration-processor-demo-dedupe-stage/src/main/java/io/mosip/registration/processor/stages/demodedupe/DemodedupeProcessor.java +++ b/registration-processor/core-processor/registration-processor-demo-dedupe-stage/src/main/java/io/mosip/registration/processor/stages/demodedupe/DemodedupeProcessor.java @@ -16,6 +16,7 @@ import io.mosip.kernel.core.fsadapter.exception.FSAdapterException; import io.mosip.kernel.core.logger.spi.Logger; +import io.mosip.kernel.core.util.exception.JsonProcessingException; import io.mosip.kernel.core.util.StringUtils; import io.mosip.kernel.core.util.exception.JsonProcessingException; import io.mosip.registration.processor.core.abstractverticle.MessageBusAddress; @@ -181,9 +182,10 @@ public MessageDTO process(MessageDTO object, String stageName) { insertDemodedupDetails(demographicData, regProcessorIdentityJson, jsonObject, registrationStatusDto, object, moduleId, moduleName); } - if (abisHandlerUtil.getPacketStatus(registrationStatusDto).equalsIgnoreCase(AbisConstant.DUPLICATE_FOR_SAME_TRANSACTION_ID)) + if (abisHandlerUtil.getPacketStatus(registrationStatusDto) + .equalsIgnoreCase(AbisConstant.DUPLICATE_FOR_SAME_TRANSACTION_ID)) isDuplicateRequestForSameTransactionId = true; - + registrationStatusDto.setRegistrationStageName(stageName); if (isTransactionSuccessful) { object.setIsValid(Boolean.TRUE); @@ -281,13 +283,12 @@ public MessageDTO process(MessageDTO object, String stageName) { auditLogRequestBuilder.createAuditRequestBuilder(description.getMessage(), eventId, eventName, eventType, moduleId, moduleName, registrationId); - } else { - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - registrationId, "Duplicate request received for same latest transaction id. This will be ignored."); - object.setIsValid(false); - object.setInternalError(true); - } - + } else { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + registrationId, "Duplicate request received for same latest transaction id. This will be ignored."); + object.setIsValid(false); + object.setInternalError(true); + } } return object; @@ -367,7 +368,8 @@ private DemoDedupeStatusDTO insertDemodedupDetailsAndPerformDedup(IndividualDemo } } else { - if (StringUtils.isNotEmpty(env.getProperty(DEMODEDUPEENABLE)) && env.getProperty(DEMODEDUPEENABLE).trim().equalsIgnoreCase(TRUE)) { + String demo=env.getProperty(DEMODEDUPEENABLE); + if (demo != null && demo.trim().equalsIgnoreCase(TRUE)) { isDemoDedupeSkip = false; duplicateDtos = performDemoDedupe(registrationStatusDto, object, description); if (duplicateDtos.isEmpty()) diff --git a/registration-processor/core-processor/registration-processor-demo-dedupe-stage/src/test/java/io/mosip/registrationprocessor/stages/demodedupe/DemoDedupeStageTest.java b/registration-processor/core-processor/registration-processor-demo-dedupe-stage/src/test/java/io/mosip/registrationprocessor/stages/demodedupe/DemoDedupeStageTest.java index 1d4f2cc5360..12964c35fc2 100644 --- a/registration-processor/core-processor/registration-processor-demo-dedupe-stage/src/test/java/io/mosip/registrationprocessor/stages/demodedupe/DemoDedupeStageTest.java +++ b/registration-processor/core-processor/registration-processor-demo-dedupe-stage/src/test/java/io/mosip/registrationprocessor/stages/demodedupe/DemoDedupeStageTest.java @@ -82,6 +82,7 @@ public void senderHealthCheck(Handler eventHandler, String addre // TODO Auto-generated method stub } + }; } diff --git a/registration-processor/core-processor/registration-processor-finalization-stage/pom.xml b/registration-processor/core-processor/registration-processor-finalization-stage/pom.xml index d6ec3d102a0..5c4c1f4b052 100644 --- a/registration-processor/core-processor/registration-processor-finalization-stage/pom.xml +++ b/registration-processor/core-processor/registration-processor-finalization-stage/pom.xml @@ -1,100 +1,100 @@ - - - 4.0.0 - - io.mosip.registrationprocessor - core-processor - 1.2.0.1-B1 - - registration-processor-finalization-stage - registration-processor-finalization-stage - jar - - UTF-8 - UTF-8 - - - - - org.springframework.cloud - spring-cloud-starter-config - ${spring-cloud-config.version} - - - org.mockito - mockito-core - ${mockito.version} - test - - - com.h2database - h2 - ${h2.version} - - - - - - org.springframework - spring-context - ${spring-framework.version} - - - org.springframework - spring-tx - ${spring-framework.version} - - - io.mosip.registrationprocessor - registration-processor-core - ${registration.processor.core.version} - - - io.mosip.registrationprocessor - registration-processor-registration-status-service-impl - ${registration.status.service.version} - - - - io.mosip.registrationprocessor - registration-processor-info-storage-service - ${packet.info.storage.service.version} - - - io.mosip.registrationprocessor - registration-processor-rest-client - ${registration.processor.rest.client.version} - - - org.powermock - powermock-module-junit4 - ${powermock.module.junit4.version} - test - - - org.powermock - powermock-api-mockito2 - ${powermock.api.mockito.version} - test - - - io.mosip.kernel - kernel-templatemanager-velocity - ${kernel.templatemanager.velocity.version} - - - javax.servlet - servlet-api - - - dom4j - dom4j - - - - - - - - + + + 4.0.0 + + io.mosip.registrationprocessor + core-processor + 1.2.0.1-B3-SNAPSHOT + + registration-processor-finalization-stage + registration-processor-finalization-stage + jar + + UTF-8 + UTF-8 + + + + + org.springframework.cloud + spring-cloud-starter-config + ${spring-cloud-config.version} + + + org.mockito + mockito-core + ${mockito.version} + test + + + com.h2database + h2 + ${h2.version} + + + + + + org.springframework + spring-context + ${spring-framework.version} + + + org.springframework + spring-tx + ${spring-framework.version} + + + io.mosip.registrationprocessor + registration-processor-core + ${registration.processor.core.version} + + + io.mosip.registrationprocessor + registration-processor-registration-status-service-impl + ${registration.status.service.version} + + + + io.mosip.registrationprocessor + registration-processor-info-storage-service + ${packet.info.storage.service.version} + + + io.mosip.registrationprocessor + registration-processor-rest-client + ${registration.processor.rest.client.version} + + + org.powermock + powermock-module-junit4 + ${powermock.module.junit4.version} + test + + + org.powermock + powermock-api-mockito2 + ${powermock.api.mockito.version} + test + + + io.mosip.kernel + kernel-templatemanager-velocity + ${kernel.templatemanager.velocity.version} + + + javax.servlet + servlet-api + + + dom4j + dom4j + + + + + + + + diff --git a/registration-processor/core-processor/registration-processor-finalization-stage/src/test/java/io/mosip/registration/processor/stages/finalization/stage/tests/FinalizationStageTest.java b/registration-processor/core-processor/registration-processor-finalization-stage/src/test/java/io/mosip/registration/processor/stages/finalization/stage/tests/FinalizationStageTest.java index 0d964bccb57..5def776c4cd 100644 --- a/registration-processor/core-processor/registration-processor-finalization-stage/src/test/java/io/mosip/registration/processor/stages/finalization/stage/tests/FinalizationStageTest.java +++ b/registration-processor/core-processor/registration-processor-finalization-stage/src/test/java/io/mosip/registration/processor/stages/finalization/stage/tests/FinalizationStageTest.java @@ -119,6 +119,8 @@ public void senderHealthCheck(Handler eventHandler, String addre // TODO Auto-generated method stub } + + }; } diff --git a/registration-processor/core-processor/registration-processor-manual-adjudication-stage/pom.xml b/registration-processor/core-processor/registration-processor-manual-adjudication-stage/pom.xml index fda716669f3..a038ba9834b 100644 --- a/registration-processor/core-processor/registration-processor-manual-adjudication-stage/pom.xml +++ b/registration-processor/core-processor/registration-processor-manual-adjudication-stage/pom.xml @@ -1,122 +1,122 @@ - - - 4.0.0 - jar - - io.mosip.registrationprocessor - core-processor - 1.2.0.1-B1 - - - registration-processor-manual-adjudication-stage - 1.2.0.1-B1 - - UTF-8 - - - - - - org.springframework.cloud - spring-cloud-starter-config - ${spring-cloud-config.version} - - - com.h2database - h2 - 1.4.195 - - - - - - - org.apache.httpcomponents - httpmime - 4.3.1 - - - org.springframework - spring-context - 5.0.6.RELEASE - - - org.springframework.cloud - spring-cloud-starter-config - ${spring-cloud-config.version} - - - junit - junit - test - ${junit.version} - - - io.springfox - springfox-swagger-ui - ${swagger.version} - - - io.springfox - springfox-swagger2 - ${swagger.version} - - - org.postgresql - postgresql - - - com.h2database - h2 - - - io.mosip.registrationprocessor - registration-processor-registration-status-service-impl - ${registration.status.service.version} - - - io.mosip.registrationprocessor - registration-processor-core - ${registration.processor.core.version} - - - io.mosip.registrationprocessor - registration-processor-info-storage-service - ${packet.info.storage.service.version} - - - org.scala-lang - scala-library - 2.11.0 - - - io.mosip.kernel - kernel-core - ${kernel.core.version} - - - org.mockito - mockito-core - ${mockito.version} - test - - - org.powermock - powermock-module-junit4 - ${powermock.module.junit4.version} - test - - - org.powermock - powermock-api-mockito2 - ${powermock.api.mockito.version} - test - - - - - - + + + 4.0.0 + jar + + io.mosip.registrationprocessor + core-processor + 1.2.0.1-B3-SNAPSHOT + + + registration-processor-manual-adjudication-stage + 1.2.0.1-B3-SNAPSHOT + + UTF-8 + + + + + + org.springframework.cloud + spring-cloud-starter-config + ${spring-cloud-config.version} + + + com.h2database + h2 + 1.4.195 + + + + + + + org.apache.httpcomponents + httpmime + 4.3.1 + + + org.springframework + spring-context + 5.0.6.RELEASE + + + org.springframework.cloud + spring-cloud-starter-config + ${spring-cloud-config.version} + + + junit + junit + test + ${junit.version} + + + io.springfox + springfox-swagger-ui + ${swagger.version} + + + io.springfox + springfox-swagger2 + ${swagger.version} + + + org.postgresql + postgresql + + + com.h2database + h2 + + + io.mosip.registrationprocessor + registration-processor-registration-status-service-impl + ${registration.status.service.version} + + + io.mosip.registrationprocessor + registration-processor-core + ${registration.processor.core.version} + + + io.mosip.registrationprocessor + registration-processor-info-storage-service + ${packet.info.storage.service.version} + + + org.scala-lang + scala-library + 2.11.0 + + + io.mosip.kernel + kernel-core + ${kernel.core.version} + + + org.mockito + mockito-core + ${mockito.version} + test + + + org.powermock + powermock-module-junit4 + ${powermock.module.junit4.version} + test + + + org.powermock + powermock-api-mockito2 + ${powermock.api.mockito.version} + test + + + + + + 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 816498db74d..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 @@ -1,13 +1,13 @@ package io.mosip.registration.processor.adjudication.config; -import io.mosip.registration.processor.adjudication.util.ManualVerificationRequestValidator; -import io.mosip.registration.processor.adjudication.util.ManualVerificationUpdateUtility; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import io.mosip.registration.processor.adjudication.exception.handler.ManualVerificationExceptionHandler; import io.mosip.registration.processor.adjudication.service.ManualAdjudicationService; import io.mosip.registration.processor.adjudication.service.impl.ManualAdjudicationServiceImpl; +import io.mosip.registration.processor.adjudication.util.ManualVerificationRequestValidator; +import io.mosip.registration.processor.adjudication.util.ManualVerificationUpdateUtility; @Configuration public class ManualAdjudicationConfigBean { @@ -28,7 +28,7 @@ ManualVerificationExceptionHandler getManualVerificationExceptionHandler() { } @Bean - ManualVerificationUpdateUtility manualVerificationUpdateUtility() { + ManualVerificationUpdateUtility getManualVerificationUpdateUtility() { return new ManualVerificationUpdateUtility(); } } \ No newline at end of file diff --git a/registration-processor/core-processor/registration-processor-manual-adjudication-stage/src/main/java/io/mosip/registration/processor/adjudication/service/impl/ManualAdjudicationServiceImpl.java b/registration-processor/core-processor/registration-processor-manual-adjudication-stage/src/main/java/io/mosip/registration/processor/adjudication/service/impl/ManualAdjudicationServiceImpl.java index c20271107ed..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 @@ -206,6 +206,7 @@ public class ManualAdjudicationServiceImpl implements ManualAdjudicationService @Autowired private ManualVerificationUpdateUtility manualVerificationUpdateUtility; + /** The Constant PROTOCOL. */ public static final String PROTOCOL = "https"; @@ -257,7 +258,6 @@ public boolean updatePacketStatus(ManualAdjudicationResponseDTO manualVerificati description.setCode(PlatformSuccessMessages.RPR_MANUAL_VERIFICATION_RESEND.getCode()); messageDTO.setInternalError(true); messageDTO.setIsValid(isTransactionSuccessful); - manualAdjudicationStage.sendMessage(messageDTO); } else { // call success flow and process the response received from manual verification system isTransactionSuccessful = successFlow( @@ -314,7 +314,7 @@ public boolean updatePacketStatus(ManualAdjudicationResponseDTO manualVerificati : description.getCode(); String moduleName = ModuleName.MANUAL_ADJUDICATION.toString(); registrationStatusService.updateRegistrationStatus(registrationStatusDto, moduleId, moduleName); - + manualAdjudicationStage.sendMessage(messageDTO); 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(); @@ -405,6 +405,7 @@ private void pushRequestToQueue(MessageDTO messageDTO, MosipQueue queue) throws mosipQueueManager.send(queue, JsonUtils.javaObjectToJsonString(mar).getBytes(), mvRequestAddress, mvRequestMessageTTL); regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), refId, "ManualVerificationServiceImpl::pushRequestToQueue()::entry"); + } private String getDataShareUrl(String id, String process) throws Exception { @@ -948,7 +949,6 @@ private boolean successFlow(ManualVerificationEntity entity, ManualAdjudicationR } } messageDTO.setIsValid(isTransactionSuccessful); - manualAdjudicationStage.sendMessage(messageDTO); registrationStatusDto.setStatusComment(StatusUtil.MANUAL_VERIFIER_APPROVED_PACKET.getMessage()); registrationStatusDto.setSubStatusCode(StatusUtil.MANUAL_VERIFIER_APPROVED_PACKET.getCode()); registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); @@ -968,7 +968,6 @@ private boolean successFlow(ManualVerificationEntity entity, ManualAdjudicationR description.setMessage(PlatformErrorMessages.RPR_MANUAL_VERIFICATION_REJECTED.getMessage()); description.setCode(PlatformErrorMessages.RPR_MANUAL_VERIFICATION_REJECTED.getCode()); messageDTO.setIsValid(Boolean.FALSE); - manualAdjudicationStage.sendMessage(messageDTO); } else { registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); registrationStatusDto.setStatusComment(StatusUtil.RPR_MANUAL_VERIFICATION_RESEND.getMessage()); @@ -979,7 +978,6 @@ private boolean successFlow(ManualVerificationEntity entity, ManualAdjudicationR description.setMessage(PlatformErrorMessages.RPR_MANUAL_VERIFICATION_RESEND.getMessage()); description.setCode(PlatformErrorMessages.RPR_MANUAL_VERIFICATION_RESEND.getCode()); messageDTO.setIsValid(Boolean.FALSE); - manualAdjudicationStage.sendMessage(messageDTO); } List maVerificationEntity = new ArrayList<>(); for(ManualVerificationEntity manualVerificationEntity: entities) { diff --git a/registration-processor/core-processor/registration-processor-manual-adjudication-stage/src/main/java/io/mosip/registration/processor/adjudication/stage/ManualAdjudicationStage.java b/registration-processor/core-processor/registration-processor-manual-adjudication-stage/src/main/java/io/mosip/registration/processor/adjudication/stage/ManualAdjudicationStage.java index 95777d68463..6b7497a3538 100644 --- a/registration-processor/core-processor/registration-processor-manual-adjudication-stage/src/main/java/io/mosip/registration/processor/adjudication/stage/ManualAdjudicationStage.java +++ b/registration-processor/core-processor/registration-processor-manual-adjudication-stage/src/main/java/io/mosip/registration/processor/adjudication/stage/ManualAdjudicationStage.java @@ -214,7 +214,7 @@ public void consumerListener(Message message) { } ManualAdjudicationResponseDTO resp = JsonUtil.readValueWithUnknownProperties(response, ManualAdjudicationResponseDTO.class); if (resp != null) { - boolean isProcessingSuccessful = manualAdjudicationService.updatePacketStatus(resp, this.getClass().getSimpleName(),queue); + boolean isProcessingSuccessful = manualAdjudicationService.updatePacketStatus(resp,getStageName(),queue); if (isProcessingSuccessful) regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), 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 8a57bf1aae8..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,9 +1,9 @@ package io.mosip.registration.processor.adjudication.util; -import java.sql.Timestamp; + + import java.sql.Timestamp; import java.util.List; -import io.mosip.registration.processor.adjudication.dto.ManualVerificationStatus; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Propagation; @@ -11,36 +11,38 @@ import io.mosip.kernel.core.logger.spi.Logger; import io.mosip.kernel.core.util.DateUtils; +import io.mosip.registration.processor.adjudication.dto.ManualVerificationStatus; import io.mosip.registration.processor.core.constant.LoggerFileConstant; import io.mosip.registration.processor.core.logger.RegProcessorLogger; import io.mosip.registration.processor.packet.storage.entity.ManualVerificationEntity; import io.mosip.registration.processor.packet.storage.repository.BasePacketRepository; -@Component -@Transactional(propagation=Propagation.REQUIRES_NEW) -public class ManualVerificationUpdateUtility { - /** The logger. */ - private static Logger regProcLogger = RegProcessorLogger.getLogger(ManualVerificationUpdateUtility.class); - - /** The base packet repository. */ - @Autowired - private BasePacketRepository basePacketRepository; - - /** - * Update manual verification entity once request is pushed to queue for a given - * RID - */ - public void updateManualVerificationEntityRID(List mves, String requestId) { - mves.stream().forEach(mve -> { - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - mve.getRegId(), "ManualVerificationUpdateUtility::updateManualVerificationEntityRID()::entry"); - mve.setStatusCode(ManualVerificationStatus.INQUEUE.name()); - mve.setStatusComment("Sent to manual adjudication queue"); - mve.setUpdDtimes(Timestamp.valueOf(DateUtils.getUTCCurrentDateTime())); - mve.setRequestId(requestId); - basePacketRepository.update(mve); - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - mve.getRegId(), "ManualVerificationUpdateUtility::updateManualVerificationEntityRID()::exit"); - }); + @Component + @Transactional(propagation=Propagation.REQUIRES_NEW) + public class ManualVerificationUpdateUtility { + /** The logger. */ + private static Logger regProcLogger = RegProcessorLogger.getLogger(ManualVerificationUpdateUtility.class); + + /** The base packet repository. */ + @Autowired + private BasePacketRepository basePacketRepository; + + /** + * Update manual verification entity once request is pushed to queue for a given + * RID + */ + public void updateManualVerificationEntityRID(List mves, String requestId) { + mves.stream().forEach(mve -> { + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + mve.getRegId(), "ManualVerificationUpdateUtility::updateManualVerificationEntityRID()::entry"); + mve.setStatusCode(ManualVerificationStatus.INQUEUE.name()); + mve.setStatusComment("Sent to manual adjudication queue"); + mve.setUpdDtimes(Timestamp.valueOf(DateUtils.getUTCCurrentDateTime())); + mve.setRequestId(requestId); + basePacketRepository.update(mve); + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + mve.getRegId(), "ManualVerificationUpdateUtility::updateManualVerificationEntityRID()::exit"); + }); + } } -} + diff --git a/registration-processor/core-processor/registration-processor-manual-adjudication-stage/src/test/java/io/mosip/registration/processor/verification/service/ManualAdjudicationServiceTest.java b/registration-processor/core-processor/registration-processor-manual-adjudication-stage/src/test/java/io/mosip/registration/processor/verification/service/ManualAdjudicationServiceTest.java index 33e3ea2323b..0d760c46bed 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 @@ -1,778 +1,776 @@ -package io.mosip.registration.processor.verification.service; - -import static org.assertj.core.api.Assertions.assertThat; -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.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.nio.charset.StandardCharsets; -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 io.mosip.registration.processor.adjudication.util.ManualVerificationUpdateUtility; -import org.apache.commons.io.IOUtils; -import org.assertj.core.groups.Tuple; -import org.assertj.core.util.Lists; -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.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; -import org.slf4j.LoggerFactory; -import org.springframework.core.env.Environment; -import org.springframework.test.util.ReflectionTestUtils; - -import com.fasterxml.jackson.databind.ObjectMapper; - -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.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.adjudication.dto.ManualVerificationDTO; -import io.mosip.registration.processor.adjudication.dto.ManualVerificationDecisionDto; -import io.mosip.registration.processor.adjudication.dto.ManualVerificationStatus; -import io.mosip.registration.processor.adjudication.dto.MatchDetail; -import io.mosip.registration.processor.adjudication.dto.UserDto; -import io.mosip.registration.processor.adjudication.exception.InvalidFileNameException; -import io.mosip.registration.processor.adjudication.exception.InvalidRidException; -import io.mosip.registration.processor.adjudication.response.dto.Candidate; -import io.mosip.registration.processor.adjudication.response.dto.CandidateList; -import io.mosip.registration.processor.adjudication.response.dto.ManualAdjudicationResponseDTO; -import io.mosip.registration.processor.adjudication.service.ManualAdjudicationService; -import io.mosip.registration.processor.adjudication.service.impl.ManualAdjudicationServiceImpl; -import io.mosip.registration.processor.adjudication.stage.ManualAdjudicationStage; -import io.mosip.registration.processor.core.abstractverticle.MessageDTO; -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.http.ResponseWrapper; -import io.mosip.registration.processor.core.idrepo.dto.ResponseDTO; -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.manager.idreposervice.IdRepoService; -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.ManualVerificationEntity; -import io.mosip.registration.processor.packet.storage.entity.ManualVerificationPKEntity; -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.exception.TablenotAccessibleException; -import io.mosip.registration.processor.status.service.RegistrationStatusService; - -@RunWith(PowerMockRunner.class) -@PrepareForTest({ Utilities.class, JsonUtil.class }) -@PowerMockIgnore({ "com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*","javax.management.*", "javax.net.ssl.*" }) -public class ManualAdjudicationServiceTest { - - private List entities; - private List entitiesTemp; - - @InjectMocks - private ManualAdjudicationService manualAdjudicationService = new ManualAdjudicationServiceImpl(); - - @Mock - UserDto dto; - - @Mock - private ManualVerificationUpdateUtility manualVerificationUpdateUtility; - - @Mock - ManualAdjudicationStage manualAdjudicationStage; - - @Mock - private IdRepoService idRepoService; - - @Mock - ManualAdjudicationService 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; - - private InternalRegistrationStatusDto registrationStatusDto; - private ManualVerificationPKEntity PKId; - private ManualVerificationDTO manualVerificationDTO; - private MatchDetail matchDetail=new MatchDetail(); - private ManualVerificationEntity 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 ManualVerificationDecisionDto manualVerificationDecisionDto=new ManualVerificationDecisionDto(); - private ManualAdjudicationResponseDTO manualAdjudicationResponseDTO=new ManualAdjudicationResponseDTO(); - private MosipQueue queue; - @Mock - LogDescription description; - - @Mock - ObjectMapper mapper; - - @Mock - private Environment env; - - @Mock - private CbeffUtil cbeffutil; - - @Mock - RegistrationExceptionMapperUtil registrationExceptionMapperUtil; - - - @Before - public void setup() throws SecurityException, IllegalArgumentException { - - queue=new MosipQueue() { - - @Override - public String getQueueName() { - // TODO Auto-generated method stub - return null; - } - - @Override - public void createConnection(String username, String password, String brokerUrl) { - // TODO Auto-generated method stub - - } - }; - - ReflectionTestUtils.setField(manualAdjudicationService, "messageFormat", "text"); - regprocLogger = (Logger) LoggerFactory.getLogger(ManualAdjudicationServiceImpl.class); - listAppender = new ListAppender<>(); - classLoader = getClass().getClassLoader(); - - manualVerificationDTO = new ManualVerificationDTO(); - registrationStatusDto = new InternalRegistrationStatusDto(); - dto = new UserDto(); - - PKId = new ManualVerificationPKEntity(); - PKId.setMatchedRefId("10002100880000920210628085700"); - PKId.setMatchedRefType("Type"); - PKId.setWorkflowInstanceId("WorkflowInstanceId"); - dto.setUserId("mvusr22"); - - entities = new ArrayList(); - entitiesTemp = new ArrayList(); - manualVerificationEntity = new ManualVerificationEntity(); - manualVerificationEntity.setRegId("10002100741000320210107125533"); - manualVerificationEntity.setCrBy("regprc"); - manualVerificationEntity.setMvUsrId("test"); - manualVerificationEntity.setIsActive(true); - Date date = new Date(); - manualVerificationEntity.setDelDtimes(new Timestamp(date.getTime())); - manualVerificationEntity.setIsDeleted(true); - manualVerificationEntity.setStatusComment("test"); - manualVerificationEntity.setStatusCode(ManualVerificationStatus.PENDING.name()); - manualVerificationEntity.setReasonCode("test"); - manualVerificationEntity.setIsActive(true); - manualVerificationEntity.setId(PKId); - manualVerificationEntity.setLangCode("eng"); - 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"); - - 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); - manualVerificationDecisionDto.setMatchedRefType("Type"); - manualVerificationDecisionDto.setMvUsrId("mvusr22"); - manualVerificationDecisionDto.setReasonCode("test"); - manualVerificationDecisionDto.setRegId("RegID"); - manualVerificationDecisionDto.setStatusCode("APPROVED"); - manualAdjudicationResponseDTO.setReturnValue(1); - manualAdjudicationResponseDTO.setResponsetime(DateUtils.getCurrentDateTimeString()); - manualAdjudicationResponseDTO.setId("mosip.manual.adjudication.adjudicate"); - manualAdjudicationResponseDTO.setRequestId("4d4f27d3-ec73-41c4-a384-bf87fce4969e"); - CandidateList candidateList=new CandidateList(); - candidateList.setCount(0); - manualAdjudicationResponseDTO.setCandidateList(candidateList); - - Mockito.doNothing().when(manualVerificationUpdateUtility).updateManualVerificationEntityRID(any(), any()); - - } - - @Test - public void TablenotAccessibleExceptionTest() throws Exception { - Mockito.when(basePacketRepository.getAllAssignedRecord(any(), any())).thenReturn(entities); - Mockito.when(basePacketRepository.getRegistrationIdbyRequestId(anyString())).thenReturn(Lists.newArrayList(manualVerificationEntity)); - Mockito.when(registrationStatusService.getRegistrationStatus(any(),any(),any(),any())).thenReturn(registrationStatusDto); - Mockito.when(basePacketRepository.update(any(ManualVerificationEntity.class))) - .thenThrow(new TablenotAccessibleException("")); - manualAdjudicationService.updatePacketStatus(manualAdjudicationResponseDTO, stageName,queue); - - } - - @Test - public void updatePacketStatusNoRecordAssignedExceptionCheck() { - Candidate candidate=new Candidate(); - List candidates=new ArrayList<>(); - - candidate.setReferenceId("1234567890987654321"); - Map analytics=new HashMap<>(); - candidates.add(candidate); - CandidateList candidateList=new CandidateList(); - candidateList.setCandidates(candidates); - candidateList.setCount(1);// logic needs to be implemented. - Map analytics1=new HashMap<>(); - analytics.put("primaryOperatorID", "110006");//logic needs to be implemented - analytics.put("primaryOperatorComments", "abcd"); - candidateList.setAnalytics(analytics1); - manualAdjudicationResponseDTO.setCandidateList(candidateList); - Mockito.when(basePacketRepository.getAllAssignedRecord( anyString(), anyString())) - .thenReturn(entitiesTemp); - Mockito.when(basePacketRepository.getRegistrationIdbyRequestId(anyString())).thenReturn(Lists.newArrayList(manualVerificationEntity)); - Mockito.when(registrationStatusService.getRegistrationStatus(any(),any(),any(),any())).thenReturn(registrationStatusDto); - manualAdjudicationService.updatePacketStatus(manualAdjudicationResponseDTO, stageName,queue); - - } - - @Test(expected = InvalidRidException.class) - public void updatePacketStatusInvalidRIDExceptionCheck() { - Candidate candidate = new Candidate(); - List candidates = new ArrayList<>(); - - candidate.setReferenceId("1234567890987654321"); - Map analytics = new HashMap<>(); - candidates.add(candidate); - CandidateList candidateList = new CandidateList(); - candidateList.setCandidates(candidates); - candidateList.setCount(1);// logic needs to be implemented. - Map analytics1 = new HashMap<>(); - analytics.put("primaryOperatorID", "110006");// logic needs to be implemented - analytics.put("primaryOperatorComments", "abcd"); - candidateList.setAnalytics(analytics1); - manualAdjudicationResponseDTO.setCandidateList(candidateList); - Mockito.when(basePacketRepository.getAllAssignedRecord(anyString(), anyString())).thenReturn(entitiesTemp); - Mockito.when(basePacketRepository.getRegistrationIdbyRequestId(anyString())).thenReturn(Lists.newArrayList()); - Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())) - .thenReturn(registrationStatusDto); - manualAdjudicationService.updatePacketStatus(manualAdjudicationResponseDTO, stageName, queue); - - } - - @Test(expected = InvalidFileNameException.class) - public void updatePacketStatusEmptyRIDExceptionCheck() { - Candidate candidate = new Candidate(); - List candidates = new ArrayList<>(); - - candidate.setReferenceId("1234567890987654321"); - Map analytics = new HashMap<>(); - candidates.add(candidate); - CandidateList candidateList = new CandidateList(); - candidateList.setCandidates(candidates); - candidateList.setCount(1);// logic needs to be implemented. - Map analytics1 = new HashMap<>(); - analytics.put("primaryOperatorID", "110006");// logic needs to be implemented - analytics.put("primaryOperatorComments", "abcd"); - candidateList.setAnalytics(analytics1); - manualAdjudicationResponseDTO.setCandidateList(candidateList); - Mockito.when(basePacketRepository.getAllAssignedRecord(anyString(), anyString())).thenReturn(entitiesTemp); - manualVerificationEntity.setRegId(""); - Mockito.when(basePacketRepository.getRegistrationIdbyRequestId(anyString())).thenReturn(Lists.newArrayList(manualVerificationEntity)); - Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())) - .thenReturn(registrationStatusDto); - manualAdjudicationService.updatePacketStatus(manualAdjudicationResponseDTO, stageName, queue); - - } - - - @Test - public void updatePacketStatusApprovalMethodCheck() { - Mockito.when(basePacketRepository.getAllAssignedRecord(anyString(), anyString())) - .thenReturn(entities); - Mockito.when(registrationStatusService.getRegistrationStatus(any(),any(),any(),any())).thenReturn(registrationStatusDto); - Mockito.when(basePacketRepository.getAssignedApplicantDetails(anyString(), anyString())).thenReturn(null); - Mockito.when(basePacketRepository.update(any(ManualVerificationEntity.class))) - .thenReturn(manualVerificationEntity); - Mockito.when(basePacketRepository.getRegistrationIdbyRequestId(anyString())).thenReturn(Lists.newArrayList(manualVerificationEntity)); - manualVerificationDTO.setStatusCode(ManualVerificationStatus.APPROVED.name()); - - Mockito.doNothing().when(manualAdjudicationStage).sendMessage(any(MessageDTO.class)); - manualAdjudicationService.updatePacketStatus(manualAdjudicationResponseDTO, stageName,queue); - - } - - @Test - public void updatePacketStatusRejectionMethodCheck() { - Candidate candidate=new Candidate(); - List candidates=new ArrayList<>(); - - candidate.setReferenceId("1234567890987654321"); - JSONObject analytics=new JSONObject(); - candidate.setAnalytics(analytics); - candidates.add(candidate); - CandidateList candidateList=new CandidateList(); - candidateList.setCandidates(candidates); - candidateList.setCount(1);// logic needs to be implemented. - Map analytics1=new HashMap<>(); - analytics.put("primaryOperatorID", "110006");//logic needs to be implemented - analytics.put("primaryOperatorComments", "abcd"); - candidateList.setAnalytics(analytics1); - manualAdjudicationResponseDTO.setCandidateList(candidateList); - manualVerificationDecisionDto.setStatusCode(ManualVerificationStatus.REJECTED.name()); - ; - Mockito.when(basePacketRepository.getAllAssignedRecord(anyString(), anyString())) - .thenReturn(entities); - Mockito.when(basePacketRepository.getRegistrationIdbyRequestId(anyString())).thenReturn(Lists.newArrayList(manualVerificationEntity)); - Mockito.when(registrationStatusService.getRegistrationStatus(any(),any(),any(),any())).thenReturn(registrationStatusDto); - Mockito.when(basePacketRepository.getAssignedApplicantDetails(anyString(), anyString())).thenReturn(null); - Mockito.when(basePacketRepository.update(any())).thenReturn(manualVerificationEntity); - - Mockito.doNothing().when(manualAdjudicationStage).sendMessage(any()); - manualAdjudicationService.updatePacketStatus(manualAdjudicationResponseDTO, stageName,queue); - - } - - @Test - @Ignore - public void testManualVerificationResponse_CountMismatch() throws IOException { - - listAppender.start(); - regprocLogger.addAppender(listAppender); - - File childFile = new File(classLoader.getResource("countMismatch.json").getFile()); - InputStream is = new FileInputStream(childFile); - String responseString = IOUtils.toString(is, "UTF-8"); - ManualAdjudicationResponseDTO responseDTO = JsonUtil.readValueWithUnknownProperties( - responseString, ManualAdjudicationResponseDTO.class); - - Mockito.when(registrationStatusService.getRegistrationStatus(any(),any(),any(),any())).thenReturn(registrationStatusDto); - Mockito.when(basePacketRepository.getAllAssignedRecord(any(), any())).thenReturn(entities); - Mockito.when(basePacketRepository.getRegistrationIdbyRequestId(anyString())).thenReturn(Lists.newArrayList(manualVerificationEntity)); - - boolean isValidResponse = manualAdjudicationService.updatePacketStatus(responseDTO, stageName,queue); - - assertFalse("Should be false for response count mismatch", isValidResponse); - assertThat(listAppender.list).extracting(ILoggingEvent::getLevel, ILoggingEvent::getFormattedMessage).contains( - Tuple.tuple(Level.ERROR, - "SESSIONID - REGISTRATIONID - 10002100741000320210107125533 - Validation error - Candidate count does not match reference ids count.")); - } - - @Test - @Ignore - public void testManualVerificationResponse_RefIdMismatch() throws IOException { - - listAppender.start(); - regprocLogger.addAppender(listAppender); - - File childFile = new File(classLoader.getResource("refIdMismatch.json").getFile()); - InputStream is = new FileInputStream(childFile); - String responseString = IOUtils.toString(is, "UTF-8"); - ManualAdjudicationResponseDTO responseDTO = JsonUtil.readValueWithUnknownProperties( - responseString, ManualAdjudicationResponseDTO.class); - - Mockito.when(registrationStatusService.getRegistrationStatus(anyString(),any(),any(),any())).thenReturn(registrationStatusDto); - Mockito.when(basePacketRepository.getAllAssignedRecord(any(), any())).thenReturn(entities); - Mockito.when(basePacketRepository.getRegistrationIdbyRequestId(anyString())).thenReturn(Lists.newArrayList(manualVerificationEntity)); - boolean isValidResponse = manualAdjudicationService.updatePacketStatus(responseDTO, stageName,queue); - - assertFalse("Should be false for response count mismatch", isValidResponse); - assertThat(listAppender.list).extracting(ILoggingEvent::getLevel, ILoggingEvent::getFormattedMessage).contains( - Tuple.tuple(Level.ERROR, - "SESSIONID - REGISTRATIONID - 10002100741000320210107125533 - Validation error - " + - "Received ReferenceIds does not match reference ids in manual verification table.")); - } - - - @Test - @Ignore - public void testManualVerification_ResendFlow() throws IOException { - - listAppender.start(); - regprocLogger.addAppender(listAppender); - - File childFile = new File(classLoader.getResource("resendFlow.json").getFile()); - InputStream is = new FileInputStream(childFile); - String responseString = IOUtils.toString(is, "UTF-8"); - ManualAdjudicationResponseDTO responseDTO = JsonUtil.readValueWithUnknownProperties( - responseString, ManualAdjudicationResponseDTO.class); - - Mockito.when(registrationStatusService.getRegistrationStatus(anyString(),any(),any(),any())).thenReturn(registrationStatusDto); - Mockito.when(basePacketRepository.getAllAssignedRecord(any(), any())).thenReturn(entities); - Mockito.when(basePacketRepository.getRegistrationIdbyRequestId(anyString())).thenReturn(Lists.newArrayList(manualVerificationEntity)); - boolean isValidResponse = manualAdjudicationService.updatePacketStatus(responseDTO, stageName,queue); - - assertFalse("Should be false", isValidResponse); - assertThat(listAppender.list).extracting(ILoggingEvent::getLevel, ILoggingEvent::getFormattedMessage).contains( - Tuple.tuple(Level.INFO, - "SESSIONID - REGISTRATIONID - 10002100741000320210107125533 - " + - "Received resend request from manual verification application. This will be marked for reprocessing.")); - } - - @Test - @Ignore - public void testManualVerification_SuccessFlow() throws IOException { - - listAppender.start(); - regprocLogger.addAppender(listAppender); - - File childFile = new File(classLoader.getResource("successFlow.json").getFile()); - InputStream is = new FileInputStream(childFile); - String responseString = IOUtils.toString(is, "UTF-8"); - ManualAdjudicationResponseDTO responseDTO = JsonUtil.readValueWithUnknownProperties( - responseString, ManualAdjudicationResponseDTO.class); - Mockito.when(basePacketRepository.getRegistrationIdbyRequestId(anyString())).thenReturn(Lists.newArrayList(manualVerificationEntity)); - Mockito.when(registrationStatusService.getRegistrationStatus(anyString(),any(),any(),any())).thenReturn(registrationStatusDto); - Mockito.when(basePacketRepository.getAllAssignedRecord(any(), any())).thenReturn(entities); - - boolean isValidResponse = manualAdjudicationService.updatePacketStatus(responseDTO, stageName,queue); - - assertTrue("Should be Success", isValidResponse); - } - - @SuppressWarnings("unchecked") - @Test - public void testManualAdjudication_Process() throws Exception { - - MessageDTO object = new MessageDTO(); - object.setReg_type("NEW"); - object.setRid("92379526572940"); - object.setIteration(1); - object.setWorkflowInstanceId("26fa3eff-f3b9-48f7-b365-d7f7c2e56e00"); - - 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); - - 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"); - - LinkedHashMap dataShareResponse = new LinkedHashMap(); - LinkedHashMap datashareUrl = new LinkedHashMap(); - datashareUrl.put("url", "Http://....."); - dataShareResponse.put("dataShare", datashareUrl); - - Mockito.when(basePacketRepository.getMatchedIds(any(), anyString())).thenReturn(entities); - Mockito.when(env.getProperty(anyString())).thenReturn("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") - .thenReturn("/v1/datashare/create"); - Mockito.when(registrationStatusService.getRegistrationStatus(anyString(), any(), any(), any())) - .thenReturn(registrationStatusDto); - Mockito.when(registrationProcessorRestClientService.getApi(any(), any(), anyString(), anyString(), - eq(ResponseWrapper.class))).thenReturn(policiesResponse); - 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(registrationProcessorRestClientService.postApi(anyString(), any(), any(), any(), any(), any(), - eq(LinkedHashMap.class))).thenReturn(dataShareResponse); - Mockito.when(mosipQueueManager.send(any(), anyString(), anyString(), anyInt())).thenReturn(true); - manualAdjudicationService.process(object, queue); - } - - public void setDataShareDetails() throws Exception { - 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); - - 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"); - docmap.put("value", "biometrics"); - 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"); - - LinkedHashMap dataShareResponse = new LinkedHashMap(); - LinkedHashMap datashareUrl = new LinkedHashMap(); - datashareUrl.put("url", "Http://....."); - dataShareResponse.put("dataShare", datashareUrl); - - Mockito.when(basePacketRepository.getMatchedIds(any(), anyString())).thenReturn(entities); - Mockito.when(env.getProperty(anyString())).thenReturn("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") - .thenReturn("/v1/datashare/create"); - Mockito.when(registrationStatusService.getRegistrationStatus(anyString(), any(), any(), any())) - .thenReturn(registrationStatusDto); - Mockito.when(registrationProcessorRestClientService.getApi(any(), any(), anyString(), anyString(), - eq(ResponseWrapper.class))).thenReturn(policiesResponse); - 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(registrationProcessorRestClientService.postApi(anyString(), any(), any(), any(), any(), any(), - eq(LinkedHashMap.class))).thenReturn(dataShareResponse); - Mockito.when(mosipQueueManager.send(any(), anyString(), anyString(), anyInt())).thenReturn(true); - - Document document = new Document(); - document.setDocument("abcd".getBytes(StandardCharsets.UTF_8)); - document.setValue("biometrics"); - document.setType("biometrics"); - Mockito.when(packetManagerService.getDocument(any(), any(), any(), any())).thenReturn(new Document()); - } - @Test - public void testManualAdjudicationProcess() throws Exception { - - MessageDTO object = new MessageDTO(); - object.setReg_type("NEW"); - object.setRid("92379526572940"); - object.setIteration(1); - object.setWorkflowInstanceId("26fa3eff-f3b9-48f7-b365-d7f7c2e56e00"); - - setDataShareDetails(); - - manualAdjudicationService.process(object, queue); - } - @Test - public void testManualAdjudicationProcessLatest() throws Exception { - ReflectionTestUtils.setField(manualAdjudicationService, "uselatestManualAdjudicationRequestFormat", true); - MessageDTO object = new MessageDTO(); - object.setReg_type("NEW"); - object.setRid("92379526572940"); - object.setIteration(1); - object.setWorkflowInstanceId("26fa3eff-f3b9-48f7-b365-d7f7c2e56e00"); - setDataShareDetails(); - - manualAdjudicationService.process(object, queue); - } -} +package io.mosip.registration.processor.verification.service; + +import static org.assertj.core.api.Assertions.assertThat; +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.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +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.commons.io.IOUtils; +import org.assertj.core.groups.Tuple; +import org.assertj.core.util.Lists; +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.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.slf4j.LoggerFactory; +import org.springframework.core.env.Environment; +import org.springframework.test.util.ReflectionTestUtils; + +import com.fasterxml.jackson.databind.ObjectMapper; + +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.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.registration.processor.adjudication.dto.ManualVerificationDTO; +import io.mosip.registration.processor.adjudication.dto.ManualVerificationDecisionDto; +import io.mosip.registration.processor.adjudication.dto.ManualVerificationStatus; +import io.mosip.registration.processor.adjudication.dto.MatchDetail; +import io.mosip.registration.processor.adjudication.dto.UserDto; +import io.mosip.registration.processor.adjudication.exception.InvalidFileNameException; +import io.mosip.registration.processor.adjudication.exception.InvalidRidException; +import io.mosip.registration.processor.adjudication.response.dto.Candidate; +import io.mosip.registration.processor.adjudication.response.dto.CandidateList; +import io.mosip.registration.processor.adjudication.response.dto.ManualAdjudicationResponseDTO; +import io.mosip.registration.processor.adjudication.service.ManualAdjudicationService; +import io.mosip.registration.processor.adjudication.service.impl.ManualAdjudicationServiceImpl; +import io.mosip.registration.processor.adjudication.stage.ManualAdjudicationStage; +import io.mosip.registration.processor.adjudication.util.ManualVerificationUpdateUtility; +import io.mosip.registration.processor.core.abstractverticle.MessageDTO; +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.manager.idreposervice.IdRepoService; +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.ManualVerificationEntity; +import io.mosip.registration.processor.packet.storage.entity.ManualVerificationPKEntity; +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.exception.TablenotAccessibleException; +import io.mosip.registration.processor.status.service.RegistrationStatusService; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({ Utilities.class, JsonUtil.class }) +@PowerMockIgnore({ "com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*","javax.management.*", "javax.net.ssl.*" }) +public class ManualAdjudicationServiceTest { + + private List entities; + private List entitiesTemp; + + @InjectMocks + private ManualAdjudicationService manualAdjudicationService = new ManualAdjudicationServiceImpl(); + + @Mock + UserDto dto; + + @Mock + private ManualVerificationUpdateUtility manualVerificationUpdateUtility; + + @Mock + ManualAdjudicationStage manualAdjudicationStage; + + @Mock + private IdRepoService idRepoService; + + @Mock + ManualAdjudicationService 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; + + private InternalRegistrationStatusDto registrationStatusDto; + private ManualVerificationPKEntity PKId; + private ManualVerificationDTO manualVerificationDTO; + private MatchDetail matchDetail=new MatchDetail(); + private ManualVerificationEntity 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 ManualVerificationDecisionDto manualVerificationDecisionDto=new ManualVerificationDecisionDto(); + private ManualAdjudicationResponseDTO manualAdjudicationResponseDTO=new ManualAdjudicationResponseDTO(); + private MosipQueue queue; + @Mock + LogDescription description; + + @Mock + ObjectMapper mapper; + + @Mock + private Environment env; + + @Mock + private CbeffUtil cbeffutil; + + @Mock + RegistrationExceptionMapperUtil registrationExceptionMapperUtil; + + + @Before + public void setup() throws SecurityException, IllegalArgumentException { + + queue=new MosipQueue() { + + @Override + public String getQueueName() { + // TODO Auto-generated method stub + return null; + } + + @Override + public void createConnection(String username, String password, String brokerUrl) { + // TODO Auto-generated method stub + + } + }; + + ReflectionTestUtils.setField(manualAdjudicationService, "messageFormat", "text"); + regprocLogger = (Logger) LoggerFactory.getLogger(ManualAdjudicationServiceImpl.class); + listAppender = new ListAppender<>(); + classLoader = getClass().getClassLoader(); + + manualVerificationDTO = new ManualVerificationDTO(); + registrationStatusDto = new InternalRegistrationStatusDto(); + dto = new UserDto(); + + PKId = new ManualVerificationPKEntity(); + PKId.setMatchedRefId("10002100880000920210628085700"); + PKId.setMatchedRefType("Type"); + PKId.setWorkflowInstanceId("WorkflowInstanceId"); + dto.setUserId("mvusr22"); + + entities = new ArrayList(); + entitiesTemp = new ArrayList(); + manualVerificationEntity = new ManualVerificationEntity(); + manualVerificationEntity.setRegId("10002100741000320210107125533"); + manualVerificationEntity.setCrBy("regprc"); + manualVerificationEntity.setMvUsrId("test"); + manualVerificationEntity.setIsActive(true); + Date date = new Date(); + manualVerificationEntity.setDelDtimes(new Timestamp(date.getTime())); + manualVerificationEntity.setIsDeleted(true); + manualVerificationEntity.setStatusComment("test"); + manualVerificationEntity.setStatusCode(ManualVerificationStatus.PENDING.name()); + manualVerificationEntity.setReasonCode("test"); + manualVerificationEntity.setIsActive(true); + manualVerificationEntity.setId(PKId); + manualVerificationEntity.setLangCode("eng"); + 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"); + + 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); + manualVerificationDecisionDto.setMatchedRefType("Type"); + manualVerificationDecisionDto.setMvUsrId("mvusr22"); + manualVerificationDecisionDto.setReasonCode("test"); + manualVerificationDecisionDto.setRegId("RegID"); + manualVerificationDecisionDto.setStatusCode("APPROVED"); + manualAdjudicationResponseDTO.setReturnValue(1); + manualAdjudicationResponseDTO.setResponsetime(DateUtils.getCurrentDateTimeString()); + manualAdjudicationResponseDTO.setId("mosip.manual.adjudication.adjudicate"); + manualAdjudicationResponseDTO.setRequestId("4d4f27d3-ec73-41c4-a384-bf87fce4969e"); + CandidateList candidateList=new CandidateList(); + candidateList.setCount(0); + manualAdjudicationResponseDTO.setCandidateList(candidateList); + + Mockito.doNothing().when(manualVerificationUpdateUtility).updateManualVerificationEntityRID(any(), any()); + + Mockito.doNothing().when(manualVerificationUpdateUtility).updateManualVerificationEntityRID(any(), any()); + + } + + @Test + public void TablenotAccessibleExceptionTest() throws Exception { + Mockito.when(basePacketRepository.getAllAssignedRecord(any(), any())).thenReturn(entities); + Mockito.when(basePacketRepository.getRegistrationIdbyRequestId(anyString())).thenReturn(Lists.newArrayList(manualVerificationEntity)); + Mockito.when(registrationStatusService.getRegistrationStatus(any(),any(),any(),any())).thenReturn(registrationStatusDto); + Mockito.when(basePacketRepository.update(any(ManualVerificationEntity.class))) + .thenThrow(new TablenotAccessibleException("")); + manualAdjudicationService.updatePacketStatus(manualAdjudicationResponseDTO, stageName,queue); + + } + + @Test + public void updatePacketStatusNoRecordAssignedExceptionCheck() { + Candidate candidate=new Candidate(); + List candidates=new ArrayList<>(); + + candidate.setReferenceId("1234567890987654321"); + Map analytics=new HashMap<>(); + candidates.add(candidate); + CandidateList candidateList=new CandidateList(); + candidateList.setCandidates(candidates); + candidateList.setCount(1);// logic needs to be implemented. + Map analytics1=new HashMap<>(); + analytics.put("primaryOperatorID", "110006");//logic needs to be implemented + analytics.put("primaryOperatorComments", "abcd"); + candidateList.setAnalytics(analytics1); + manualAdjudicationResponseDTO.setCandidateList(candidateList); + Mockito.when(basePacketRepository.getAllAssignedRecord( anyString(), anyString())) + .thenReturn(entitiesTemp); + Mockito.when(basePacketRepository.getRegistrationIdbyRequestId(anyString())).thenReturn(Lists.newArrayList(manualVerificationEntity)); + Mockito.when(registrationStatusService.getRegistrationStatus(any(),any(),any(),any())).thenReturn(registrationStatusDto); + manualAdjudicationService.updatePacketStatus(manualAdjudicationResponseDTO, stageName,queue); + + } + + @Test(expected = InvalidRidException.class) + public void updatePacketStatusInvalidRIDExceptionCheck() { + Candidate candidate = new Candidate(); + List candidates = new ArrayList<>(); + + candidate.setReferenceId("1234567890987654321"); + Map analytics = new HashMap<>(); + candidates.add(candidate); + CandidateList candidateList = new CandidateList(); + candidateList.setCandidates(candidates); + candidateList.setCount(1);// logic needs to be implemented. + Map analytics1 = new HashMap<>(); + analytics.put("primaryOperatorID", "110006");// logic needs to be implemented + analytics.put("primaryOperatorComments", "abcd"); + candidateList.setAnalytics(analytics1); + manualAdjudicationResponseDTO.setCandidateList(candidateList); + Mockito.when(basePacketRepository.getAllAssignedRecord(anyString(), anyString())).thenReturn(entitiesTemp); + Mockito.when(basePacketRepository.getRegistrationIdbyRequestId(anyString())).thenReturn(Lists.newArrayList()); + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())) + .thenReturn(registrationStatusDto); + manualAdjudicationService.updatePacketStatus(manualAdjudicationResponseDTO, stageName, queue); + + } + + @Test(expected = InvalidFileNameException.class) + public void updatePacketStatusEmptyRIDExceptionCheck() { + Candidate candidate = new Candidate(); + List candidates = new ArrayList<>(); + + candidate.setReferenceId("1234567890987654321"); + Map analytics = new HashMap<>(); + candidates.add(candidate); + CandidateList candidateList = new CandidateList(); + candidateList.setCandidates(candidates); + candidateList.setCount(1);// logic needs to be implemented. + Map analytics1 = new HashMap<>(); + analytics.put("primaryOperatorID", "110006");// logic needs to be implemented + analytics.put("primaryOperatorComments", "abcd"); + candidateList.setAnalytics(analytics1); + manualAdjudicationResponseDTO.setCandidateList(candidateList); + Mockito.when(basePacketRepository.getAllAssignedRecord(anyString(), anyString())).thenReturn(entitiesTemp); + manualVerificationEntity.setRegId(""); + Mockito.when(basePacketRepository.getRegistrationIdbyRequestId(anyString())).thenReturn(Lists.newArrayList(manualVerificationEntity)); + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())) + .thenReturn(registrationStatusDto); + manualAdjudicationService.updatePacketStatus(manualAdjudicationResponseDTO, stageName, queue); + + } + + + @Test + public void updatePacketStatusApprovalMethodCheck() { + Mockito.when(basePacketRepository.getAllAssignedRecord(anyString(), anyString())) + .thenReturn(entities); + Mockito.when(registrationStatusService.getRegistrationStatus(any(),any(),any(),any())).thenReturn(registrationStatusDto); + Mockito.when(basePacketRepository.getAssignedApplicantDetails(anyString(), anyString())).thenReturn(null); + Mockito.when(basePacketRepository.update(any(ManualVerificationEntity.class))) + .thenReturn(manualVerificationEntity); + Mockito.when(basePacketRepository.getRegistrationIdbyRequestId(anyString())).thenReturn(Lists.newArrayList(manualVerificationEntity)); + manualVerificationDTO.setStatusCode(ManualVerificationStatus.APPROVED.name()); + + Mockito.doNothing().when(manualAdjudicationStage).sendMessage(any(MessageDTO.class)); + manualAdjudicationService.updatePacketStatus(manualAdjudicationResponseDTO, stageName,queue); + + } + + @Test + public void updatePacketStatusRejectionMethodCheck() { + Candidate candidate=new Candidate(); + List candidates=new ArrayList<>(); + + candidate.setReferenceId("1234567890987654321"); + JSONObject analytics=new JSONObject(); + candidate.setAnalytics(analytics); + candidates.add(candidate); + CandidateList candidateList=new CandidateList(); + candidateList.setCandidates(candidates); + candidateList.setCount(1);// logic needs to be implemented. + Map analytics1=new HashMap<>(); + analytics.put("primaryOperatorID", "110006");//logic needs to be implemented + analytics.put("primaryOperatorComments", "abcd"); + candidateList.setAnalytics(analytics1); + manualAdjudicationResponseDTO.setCandidateList(candidateList); + manualVerificationDecisionDto.setStatusCode(ManualVerificationStatus.REJECTED.name()); + ; + Mockito.when(basePacketRepository.getAllAssignedRecord(anyString(), anyString())) + .thenReturn(entities); + Mockito.when(basePacketRepository.getRegistrationIdbyRequestId(anyString())).thenReturn(Lists.newArrayList(manualVerificationEntity)); + Mockito.when(registrationStatusService.getRegistrationStatus(any(),any(),any(),any())).thenReturn(registrationStatusDto); + Mockito.when(basePacketRepository.getAssignedApplicantDetails(anyString(), anyString())).thenReturn(null); + Mockito.when(basePacketRepository.update(any())).thenReturn(manualVerificationEntity); + + Mockito.doNothing().when(manualAdjudicationStage).sendMessage(any()); + manualAdjudicationService.updatePacketStatus(manualAdjudicationResponseDTO, stageName,queue); + + } + + @Test + @Ignore + public void testManualVerificationResponse_CountMismatch() throws IOException { + + listAppender.start(); + regprocLogger.addAppender(listAppender); + + File childFile = new File(classLoader.getResource("countMismatch.json").getFile()); + InputStream is = new FileInputStream(childFile); + String responseString = IOUtils.toString(is, "UTF-8"); + ManualAdjudicationResponseDTO responseDTO = JsonUtil.readValueWithUnknownProperties( + responseString, ManualAdjudicationResponseDTO.class); + + Mockito.when(registrationStatusService.getRegistrationStatus(any(),any(),any(),any())).thenReturn(registrationStatusDto); + Mockito.when(basePacketRepository.getAllAssignedRecord(any(), any())).thenReturn(entities); + Mockito.when(basePacketRepository.getRegistrationIdbyRequestId(anyString())).thenReturn(Lists.newArrayList(manualVerificationEntity)); + + boolean isValidResponse = manualAdjudicationService.updatePacketStatus(responseDTO, stageName,queue); + + assertFalse("Should be false for response count mismatch", isValidResponse); + assertThat(listAppender.list).extracting(ILoggingEvent::getLevel, ILoggingEvent::getFormattedMessage).contains( + Tuple.tuple(Level.ERROR, + "SESSIONID - REGISTRATIONID - 10002100741000320210107125533 - Validation error - Candidate count does not match reference ids count.")); + } + + @Test + @Ignore + public void testManualVerificationResponse_RefIdMismatch() throws IOException { + + listAppender.start(); + regprocLogger.addAppender(listAppender); + + File childFile = new File(classLoader.getResource("refIdMismatch.json").getFile()); + InputStream is = new FileInputStream(childFile); + String responseString = IOUtils.toString(is, "UTF-8"); + ManualAdjudicationResponseDTO responseDTO = JsonUtil.readValueWithUnknownProperties( + responseString, ManualAdjudicationResponseDTO.class); + + Mockito.when(registrationStatusService.getRegistrationStatus(anyString(),any(),any(),any())).thenReturn(registrationStatusDto); + Mockito.when(basePacketRepository.getAllAssignedRecord(any(), any())).thenReturn(entities); + Mockito.when(basePacketRepository.getRegistrationIdbyRequestId(anyString())).thenReturn(Lists.newArrayList(manualVerificationEntity)); + boolean isValidResponse = manualAdjudicationService.updatePacketStatus(responseDTO, stageName,queue); + + assertFalse("Should be false for response count mismatch", isValidResponse); + assertThat(listAppender.list).extracting(ILoggingEvent::getLevel, ILoggingEvent::getFormattedMessage).contains( + Tuple.tuple(Level.ERROR, + "SESSIONID - REGISTRATIONID - 10002100741000320210107125533 - Validation error - " + + "Received ReferenceIds does not match reference ids in manual verification table.")); + } + + + @Test + @Ignore + public void testManualVerification_ResendFlow() throws IOException { + + listAppender.start(); + regprocLogger.addAppender(listAppender); + + File childFile = new File(classLoader.getResource("resendFlow.json").getFile()); + InputStream is = new FileInputStream(childFile); + String responseString = IOUtils.toString(is, "UTF-8"); + ManualAdjudicationResponseDTO responseDTO = JsonUtil.readValueWithUnknownProperties( + responseString, ManualAdjudicationResponseDTO.class); + + Mockito.when(registrationStatusService.getRegistrationStatus(anyString(),any(),any(),any())).thenReturn(registrationStatusDto); + Mockito.when(basePacketRepository.getAllAssignedRecord(any(), any())).thenReturn(entities); + Mockito.when(basePacketRepository.getRegistrationIdbyRequestId(anyString())).thenReturn(Lists.newArrayList(manualVerificationEntity)); + boolean isValidResponse = manualAdjudicationService.updatePacketStatus(responseDTO, stageName,queue); + + assertFalse("Should be false", isValidResponse); + assertThat(listAppender.list).extracting(ILoggingEvent::getLevel, ILoggingEvent::getFormattedMessage).contains( + Tuple.tuple(Level.INFO, + "SESSIONID - REGISTRATIONID - 10002100741000320210107125533 - " + + "Received resend request from manual verification application. This will be marked for reprocessing.")); + } + + @Test + @Ignore + public void testManualVerification_SuccessFlow() throws IOException { + + listAppender.start(); + regprocLogger.addAppender(listAppender); + + File childFile = new File(classLoader.getResource("successFlow.json").getFile()); + InputStream is = new FileInputStream(childFile); + String responseString = IOUtils.toString(is, "UTF-8"); + ManualAdjudicationResponseDTO responseDTO = JsonUtil.readValueWithUnknownProperties( + responseString, ManualAdjudicationResponseDTO.class); + Mockito.when(basePacketRepository.getRegistrationIdbyRequestId(anyString())).thenReturn(Lists.newArrayList(manualVerificationEntity)); + Mockito.when(registrationStatusService.getRegistrationStatus(anyString(),any(),any(),any())).thenReturn(registrationStatusDto); + Mockito.when(basePacketRepository.getAllAssignedRecord(any(), any())).thenReturn(entities); + + boolean isValidResponse = manualAdjudicationService.updatePacketStatus(responseDTO, stageName,queue); + + assertTrue("Should be Success", isValidResponse); + } + + @SuppressWarnings("unchecked") + @Test + public void testManualAdjudication_Process() throws Exception { + + MessageDTO object = new MessageDTO(); + object.setReg_type("NEW"); + object.setRid("92379526572940"); + object.setIteration(1); + object.setWorkflowInstanceId("26fa3eff-f3b9-48f7-b365-d7f7c2e56e00"); + + 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); + + 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"); + + LinkedHashMap dataShareResponse = new LinkedHashMap(); + LinkedHashMap datashareUrl = new LinkedHashMap(); + datashareUrl.put("url", "Http://....."); + dataShareResponse.put("dataShare", datashareUrl); + + Mockito.when(basePacketRepository.getMatchedIds(any(), anyString())).thenReturn(entities); + Mockito.when(env.getProperty(anyString())).thenReturn("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") + .thenReturn("/v1/datashare/create"); + Mockito.when(registrationStatusService.getRegistrationStatus(anyString(), any(), any(), any())) + .thenReturn(registrationStatusDto); + Mockito.when(registrationProcessorRestClientService.getApi(any(), any(), anyString(), anyString(), + eq(ResponseWrapper.class))).thenReturn(policiesResponse); + 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(registrationProcessorRestClientService.postApi(anyString(), any(), any(), any(), any(), any(), + eq(LinkedHashMap.class))).thenReturn(dataShareResponse); + Mockito.when(mosipQueueManager.send(any(), anyString(), anyString(), anyInt())).thenReturn(true); + manualAdjudicationService.process(object, queue); + } + + public void setDataShareDetails() throws Exception { + 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); + + 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"); + docmap.put("value", "biometrics"); + 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"); + + LinkedHashMap dataShareResponse = new LinkedHashMap(); + LinkedHashMap datashareUrl = new LinkedHashMap(); + datashareUrl.put("url", "Http://....."); + dataShareResponse.put("dataShare", datashareUrl); + + Mockito.when(basePacketRepository.getMatchedIds(any(), anyString())).thenReturn(entities); + Mockito.when(env.getProperty(anyString())).thenReturn("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") + .thenReturn("/v1/datashare/create"); + Mockito.when(registrationStatusService.getRegistrationStatus(anyString(), any(), any(), any())) + .thenReturn(registrationStatusDto); + Mockito.when(registrationProcessorRestClientService.getApi(any(), any(), anyString(), anyString(), + eq(ResponseWrapper.class))).thenReturn(policiesResponse); + 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(registrationProcessorRestClientService.postApi(anyString(), any(), any(), any(), any(), any(), + eq(LinkedHashMap.class))).thenReturn(dataShareResponse); + Mockito.when(mosipQueueManager.send(any(), anyString(), anyString(), anyInt())).thenReturn(true); + + Document document = new Document(); + document.setDocument("abcd".getBytes(StandardCharsets.UTF_8)); + document.setValue("biometrics"); + document.setType("biometrics"); + Mockito.when(packetManagerService.getDocument(any(), any(), any(), any())).thenReturn(new Document()); + } + @Test + public void testManualAdjudicationProcess() throws Exception { + + MessageDTO object = new MessageDTO(); + object.setReg_type("NEW"); + object.setRid("92379526572940"); + object.setIteration(1); + object.setWorkflowInstanceId("26fa3eff-f3b9-48f7-b365-d7f7c2e56e00"); + + setDataShareDetails(); + + manualAdjudicationService.process(object, queue); + } + @Test + public void testManualAdjudicationProcessLatest() throws Exception { + ReflectionTestUtils.setField(manualAdjudicationService, "uselatestManualAdjudicationRequestFormat", true); + MessageDTO object = new MessageDTO(); + object.setReg_type("NEW"); + object.setRid("92379526572940"); + object.setIteration(1); + object.setWorkflowInstanceId("26fa3eff-f3b9-48f7-b365-d7f7c2e56e00"); + setDataShareDetails(); + + manualAdjudicationService.process(object, queue); + } +} diff --git a/registration-processor/core-processor/registration-processor-uin-generator-stage/pom.xml b/registration-processor/core-processor/registration-processor-uin-generator-stage/pom.xml index ea0d5a2eb73..cf8b130ebc2 100644 --- a/registration-processor/core-processor/registration-processor-uin-generator-stage/pom.xml +++ b/registration-processor/core-processor/registration-processor-uin-generator-stage/pom.xml @@ -1,96 +1,96 @@ - - 4.0.0 - - io.mosip.registrationprocessor - core-processor - 1.2.0.1-B1 - - registration-processor-uin-generator-stage - 1.2.0.1-B1 - jar - - UTF-8 - UTF-8 - - - - - - org.springframework.cloud - spring-cloud-starter-config - ${spring-cloud-config.version} - - - org.mockito - mockito-core - ${mockito.version} - test - - - com.h2database - h2 - 1.4.195 - - - - - - - - io.mosip.registrationprocessor - registration-processor-core - ${registration.processor.core.version} - - - io.mosip.registrationprocessor - registration-processor-registration-status-service-impl - ${registration.status.service.version} - - - io.mosip.registrationprocessor - registration-processor-info-storage-service - ${packet.info.storage.service.version} - - - io.mosip.registrationprocessor - registration-processor-rest-client - ${registration.processor.rest.client.version} - - - io.mosip.registrationprocessor - registration-processor-packet-manager - ${packet.manager.version} - - - org.powermock - powermock-module-junit4 - ${powermock.module.junit4.version} - test - - - org.powermock - powermock-api-mockito2 - ${powermock.api.mockito.version} - test - - - - - - + + 4.0.0 + + io.mosip.registrationprocessor + core-processor + 1.2.0.1-B3-SNAPSHOT + + registration-processor-uin-generator-stage + 1.2.0.1-B3-SNAPSHOT + jar + + UTF-8 + UTF-8 + + + + + + org.springframework.cloud + spring-cloud-starter-config + ${spring-cloud-config.version} + + + org.mockito + mockito-core + ${mockito.version} + test + + + com.h2database + h2 + 1.4.195 + + + + + + + + io.mosip.registrationprocessor + registration-processor-core + ${registration.processor.core.version} + + + io.mosip.registrationprocessor + registration-processor-registration-status-service-impl + ${registration.status.service.version} + + + io.mosip.registrationprocessor + registration-processor-info-storage-service + ${packet.info.storage.service.version} + + + io.mosip.registrationprocessor + registration-processor-rest-client + ${registration.processor.rest.client.version} + + + io.mosip.registrationprocessor + registration-processor-packet-manager + ${packet.manager.version} + + + org.powermock + powermock-module-junit4 + ${powermock.module.junit4.version} + test + + + org.powermock + powermock-api-mockito2 + ${powermock.api.mockito.version} + test + + + + + + diff --git a/registration-processor/core-processor/registration-processor-uin-generator-stage/src/main/java/io/mosip/registration/processor/stages/uingenerator/stage/UinGeneratorStage.java b/registration-processor/core-processor/registration-processor-uin-generator-stage/src/main/java/io/mosip/registration/processor/stages/uingenerator/stage/UinGeneratorStage.java index ac0862921ed..e0fa2df1f34 100644 --- a/registration-processor/core-processor/registration-processor-uin-generator-stage/src/main/java/io/mosip/registration/processor/stages/uingenerator/stage/UinGeneratorStage.java +++ b/registration-processor/core-processor/registration-processor-uin-generator-stage/src/main/java/io/mosip/registration/processor/stages/uingenerator/stage/UinGeneratorStage.java @@ -153,6 +153,9 @@ public class UinGeneratorStage extends MosipVerticleAPIManager { /** After this time intervel, message should be considered as expired (In seconds). */ @Value("${mosip.regproc.uin.generator.message.expiry-time-limit}") private Long messageExpiryTimeLimit; + + @Value("${uingenerator.lost.packet.allowed.update.fields:null}") + private String updateInfo; /** The core audit request builder. */ @Autowired @@ -234,8 +237,10 @@ public MessageDTO process(MessageDTO object) { if ((RegistrationType.LOST.toString()).equalsIgnoreCase(object.getReg_type())) { String lostPacketRegId = object.getRid(); String matchedRegId = regLostUinDetEntity.getLostUinMatchedRegIdByWorkflowId(object.getWorkflowInstanceId()); + if (matchedRegId != null) { - linkRegIdWrtUin(lostPacketRegId, matchedRegId, registrationStatusDto.getRegistrationType(), object, description); + regProcLogger.info("Match for lostPacketRegId"+lostPacketRegId +"is "+matchedRegId); + lostAndUpdateUin(lostPacketRegId, matchedRegId, registrationStatusDto.getRegistrationType(), object, description); } } else { @@ -614,7 +619,7 @@ private boolean uinUpdate(String regId, String process, String uin, MessageDTO o List documentInfo = getAllDocumentsByRegId(regId, process, demographicIdentity); result = idRepoRequestBuilder(regId, uin, RegistrationType.ACTIVATED.toString().toUpperCase(), documentInfo, demographicIdentity); - if (isIdResponseNotNull(result)) { + if (null!=result && isIdResponseNotNull(result)) { if (IDREPO_STATUS.equalsIgnoreCase(result.getResponse().getStatus())) { isTransactionSuccessful = true; @@ -629,14 +634,15 @@ private boolean uinUpdate(String regId, String process, String uin, MessageDTO o } else { String statusComment = result != null && result.getErrors() != null ? result.getErrors().get(0).getMessage() : UINConstants.NULL_IDREPO_RESPONSE; + String message = result != null && result.getErrors() != null + ? result.getErrors().get(0).getMessage() + : UINConstants.NULL_IDREPO_RESPONSE; description.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); description.setStatusComment(trimExceptionMessage .trimExceptionMessage(StatusUtil.UIN_DATA_UPDATION_FAILED.getMessage() + statusComment)); description.setSubStatusCode(StatusUtil.UIN_DATA_UPDATION_FAILED.getCode()); description - .setMessage(UINConstants.UIN_FAILURE + regId + "::" + result != null && result.getErrors() != null - ? result.getErrors().get(0).getMessage() - : UINConstants.NULL_IDREPO_RESPONSE); + .setMessage(UINConstants.UIN_FAILURE + regId + "::" + message ); description.setTransactionStatusCode(RegistrationTransactionStatusCode.PROCESSING.toString()); object.setIsValid(Boolean.FALSE); } @@ -1001,7 +1007,7 @@ protected String getPropertyPrefix() { * Signals that an I/O exception has occurred. */ @SuppressWarnings("unchecked") - private IdResponseDTO linkRegIdWrtUin(String lostPacketRegId, String matchedRegId, String process, MessageDTO object, + private IdResponseDTO lostAndUpdateUin(String lostPacketRegId, String matchedRegId, String process, MessageDTO object, LogDescription description) throws ApisResourceAccessException, IOException, io.mosip.kernel.core.util.exception.JsonProcessingException, PacketManagerException, IdrepoDraftException { IdResponseDTO idResponse = null; @@ -1020,7 +1026,16 @@ private IdResponseDTO linkRegIdWrtUin(String lostPacketRegId, String matchedRegI identityObject.put(UINConstants.UIN, uin); String schemaVersion = packetManagerService.getFieldByMappingJsonKey(lostPacketRegId, MappingJsonConstants.IDSCHEMA_VERSION, process, ProviderStageName.UIN_GENERATOR); identityObject.put(idschemaversion, convertIdschemaToDouble ? Double.valueOf(schemaVersion) : schemaVersion); - + regProcLogger.info("Fields to be updated "+updateInfo); + if (null != updateInfo && !updateInfo.isEmpty()) { + String[] upd = updateInfo.split(","); + for (String infoField : upd) { + String fldValue = packetManagerService.getField(lostPacketRegId, infoField, process, + ProviderStageName.UIN_GENERATOR); + if (null != fldValue) + identityObject.put(infoField, fldValue); + } + } requestDto.setRegistrationId(lostPacketRegId); requestDto.setIdentity(identityObject); diff --git a/registration-processor/core-processor/registration-processor-uin-generator-stage/src/main/resources/bootstrap.properties b/registration-processor/core-processor/registration-processor-uin-generator-stage/src/main/resources/bootstrap.properties index 4f95c1a1a3e..38d85cea967 100644 --- a/registration-processor/core-processor/registration-processor-uin-generator-stage/src/main/resources/bootstrap.properties +++ b/registration-processor/core-processor/registration-processor-uin-generator-stage/src/main/resources/bootstrap.properties @@ -2,6 +2,8 @@ #spring.cloud.config.label=master spring.application.name=application,registration-processor #spring.profiles.active=mz + +#spring.profiles.active=default spring.cloud.config.name=registration-processor registration.processor.identityjson=identity-mapping.json registration.processor.demographic.identity=identity @@ -21,3 +23,6 @@ mosip.regproc.eventbus.kafka.commit.type=${mosip.regproc.uin.generator.eventbus. mosip.regproc.eventbus.kafka.max.poll.records=${mosip.regproc.uin.generator.eventbus.kafka.max.poll.records} mosip.regproc.eventbus.kafka.poll.frequency=${mosip.regproc.uin.generator.eventbus.kafka.poll.frequency} mosip.regproc.eventbus.kafka.group.id=${mosip.regproc.uin.generator.eventbus.kafka.group.id} + + +#uingenerator.lost.packet.allowed.update.fields=null \ 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 89e48e9bb0b..933b45eeb93 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,2343 +1,2398 @@ -package io.mosip.registration.processor.stages.uigenerator; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyDouble; -import static org.mockito.ArgumentMatchers.anyList; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.when; - -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.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -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.InjectMocks; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; -import org.mockito.Spy; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -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 com.google.gson.Gson; - -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.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, Gson.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) { - // TODO Auto-generated method stub - - } - - @Override - public void senderHealthCheck(Handler eventHandler, String address) { - // TODO Auto-generated method stub - - } - }; - } - - @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"); - - 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 { - - 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 { - 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 { - 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 { - 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 { - - 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 { - - 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 { - - 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 { - 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 { - 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 updateTestSuccess() throws ApisResourceAccessException, IOException, JsonProcessingException, PacketManagerException, JSONException, IdrepoDraftException { - 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 { - 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 { - 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 { - 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 { - 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 { - 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 { - 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()); - } - +package io.mosip.registration.processor.stages.uigenerator; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyDouble; +import static org.mockito.ArgumentMatchers.anyList; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.when; + +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.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +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.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.mockito.Spy; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.core.classloader.annotations.PrepareForTest; +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.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) { + // TODO Auto-generated method stub + + } + + @Override + public void senderHealthCheck(Handler eventHandler, String address) { + // TODO Auto-generated method stub + + } + + }; + } + + @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 { + + 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 { + 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 { + 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 { + 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 { + + 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 { + + 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 { + + 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 { + 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 { + 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 { + 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 { + 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 { + 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 { + 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 { + 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 { + 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 { + 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()); + } + } \ No newline at end of file diff --git a/registration-processor/core-processor/registration-processor-verification-stage/pom.xml b/registration-processor/core-processor/registration-processor-verification-stage/pom.xml index 5eacfaf200b..f024202aa8c 100644 --- a/registration-processor/core-processor/registration-processor-verification-stage/pom.xml +++ b/registration-processor/core-processor/registration-processor-verification-stage/pom.xml @@ -1,122 +1,122 @@ - - - 4.0.0 - jar - - io.mosip.registrationprocessor - core-processor - 1.2.0.1-B1 - - - registration-processor-verification-stage - 1.2.0.1-B1 - - UTF-8 - - - - - - org.springframework.cloud - spring-cloud-starter-config - ${spring-cloud-config.version} - - - com.h2database - h2 - 1.4.195 - - - - - - - org.apache.httpcomponents - httpmime - 4.3.1 - - - org.springframework - spring-context - 5.0.6.RELEASE - - - org.springframework.cloud - spring-cloud-starter-config - ${spring-cloud-config.version} - - - junit - junit - test - ${junit.version} - - - io.springfox - springfox-swagger-ui - ${swagger.version} - - - io.springfox - springfox-swagger2 - ${swagger.version} - - - org.postgresql - postgresql - - - com.h2database - h2 - - - io.mosip.registrationprocessor - registration-processor-registration-status-service-impl - ${registration.status.service.version} - - - io.mosip.registrationprocessor - registration-processor-core - ${registration.processor.core.version} - - - io.mosip.registrationprocessor - registration-processor-info-storage-service - ${packet.info.storage.service.version} - - - org.scala-lang - scala-library - 2.11.0 - - - io.mosip.kernel - kernel-core - ${kernel.core.version} - - - org.mockito - mockito-core - ${mockito.version} - test - - - org.powermock - powermock-module-junit4 - ${powermock.module.junit4.version} - test - - - org.powermock - powermock-api-mockito2 - ${powermock.api.mockito.version} - test - - - - - - + + + 4.0.0 + jar + + io.mosip.registrationprocessor + core-processor + 1.2.0.1-B3-SNAPSHOT + + + registration-processor-verification-stage + 1.2.0.1-B3-SNAPSHOT + + UTF-8 + + + + + + org.springframework.cloud + spring-cloud-starter-config + ${spring-cloud-config.version} + + + com.h2database + h2 + 1.4.195 + + + + + + + org.apache.httpcomponents + httpmime + 4.3.1 + + + org.springframework + spring-context + 5.0.6.RELEASE + + + org.springframework.cloud + spring-cloud-starter-config + ${spring-cloud-config.version} + + + junit + junit + test + ${junit.version} + + + io.springfox + springfox-swagger-ui + ${swagger.version} + + + io.springfox + springfox-swagger2 + ${swagger.version} + + + org.postgresql + postgresql + + + com.h2database + h2 + + + io.mosip.registrationprocessor + registration-processor-registration-status-service-impl + ${registration.status.service.version} + + + io.mosip.registrationprocessor + registration-processor-core + ${registration.processor.core.version} + + + io.mosip.registrationprocessor + registration-processor-info-storage-service + ${packet.info.storage.service.version} + + + org.scala-lang + scala-library + 2.11.0 + + + io.mosip.kernel + kernel-core + ${kernel.core.version} + + + org.mockito + mockito-core + ${mockito.version} + test + + + org.powermock + powermock-module-junit4 + ${powermock.module.junit4.version} + test + + + org.powermock + powermock-api-mockito2 + ${powermock.api.mockito.version} + test + + + + + + diff --git a/registration-processor/core-processor/registration-processor-verification-stage/src/main/java/io/mosip/registration/processor/verification/config/VerificationConfigBean.java b/registration-processor/core-processor/registration-processor-verification-stage/src/main/java/io/mosip/registration/processor/verification/config/VerificationConfigBean.java index 59a1049329c..7c310c05afb 100644 --- a/registration-processor/core-processor/registration-processor-verification-stage/src/main/java/io/mosip/registration/processor/verification/config/VerificationConfigBean.java +++ b/registration-processor/core-processor/registration-processor-verification-stage/src/main/java/io/mosip/registration/processor/verification/config/VerificationConfigBean.java @@ -1,12 +1,13 @@ package io.mosip.registration.processor.verification.config; -import io.mosip.registration.processor.verification.exception.handler.ManualVerificationExceptionHandler; -import io.mosip.registration.processor.verification.service.impl.VerificationServiceImpl; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import io.mosip.registration.processor.verification.exception.handler.ManualVerificationExceptionHandler; import io.mosip.registration.processor.verification.service.VerificationService; +import io.mosip.registration.processor.verification.service.impl.VerificationServiceImpl; import io.mosip.registration.processor.verification.util.ManualVerificationRequestValidator; +import io.mosip.registration.processor.verification.util.SaveVerificationRecordUtility; @Configuration public class VerificationConfigBean { @@ -26,5 +27,10 @@ ManualVerificationRequestValidator getManualVerificationRequestValidator() { ManualVerificationExceptionHandler getManualVerificationExceptionHandler() { return new ManualVerificationExceptionHandler(); } + + @Bean + SaveVerificationRecordUtility getsSaveVerificationRecordUtility() { + return new SaveVerificationRecordUtility(); + } } \ 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 5de93c1b80a..fcb4d95563e 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,7 +1,37 @@ 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; @@ -12,7 +42,14 @@ 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.*; +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; @@ -61,28 +98,7 @@ 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 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 java.io.IOException; -import java.sql.Timestamp; -import java.time.LocalDateTime; -import java.time.ZoneId; -import java.util.*; -import java.util.stream.Collectors; - -import static io.mosip.registration.processor.verification.constants.VerificationConstants.DATETIME_PATTERN; +import io.mosip.registration.processor.verification.util.SaveVerificationRecordUtility; /** * The Class ManualAdjudicationServiceImpl. @@ -177,6 +193,9 @@ public class VerificationServiceImpl implements VerificationService { @Autowired RegistrationExceptionMapperUtil registrationExceptionMapperUtil; + @Autowired + SaveVerificationRecordUtility saveVerificationRecordUtility; + /** The Constant PROTOCOL. */ public static final String PROTOCOL = "https"; @@ -205,7 +224,7 @@ public MessageDTO process(MessageDTO messageDTO, MosipQueue queue, String stageN 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); - saveVerificationRecord(messageDTO, mar.getRequestId(), description); + saveVerificationRecordUtility.saveVerificationRecord(messageDTO, mar.getRequestId(), description); regProcLogger.debug("Request : " + JsonUtils.javaObjectToJsonString(mar)); if (messageFormat.equalsIgnoreCase(TEXT_MESSAGE)) @@ -319,7 +338,7 @@ public boolean updatePacketStatus(VerificationResponseDTO manualVerificationDTO, description.setCode(StatusUtil.VERIFICATION_RESEND.getCode()); messageDTO.setInternalError(true); messageDTO.setIsValid(isTransactionSuccessful); - verificationStage.sendMessage(messageDTO); + } else { // call success flow and process the response received from manual verification // system @@ -372,6 +391,7 @@ public boolean updatePacketStatus(VerificationResponseDTO manualVerificationDTO, // TODO structure to not return in finally,ignore for sonar updateStatus(messageDTO, registrationStatusDto, isTransactionSuccessful, description, PlatformSuccessMessages.RPR_VERIFICATION_SUCCESS); + verificationStage.sendMessage(messageDTO); } return isTransactionSuccessful; } @@ -693,7 +713,6 @@ private boolean successFlow(VerificationResponseDTO manualVerificationDTO, Verif if (statusCode.equalsIgnoreCase(ManualVerificationStatus.APPROVED.name())) { messageDTO.setIsValid(isTransactionSuccessful); - verificationStage.sendMessage(messageDTO); registrationStatusDto.setStatusComment(StatusUtil.VERIFICATION_SUCCESS.getMessage()); registrationStatusDto.setSubStatusCode(StatusUtil.VERIFICATION_SUCCESS.getCode()); registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); @@ -712,7 +731,6 @@ private boolean successFlow(VerificationResponseDTO manualVerificationDTO, Verif description.setCode(PlatformErrorMessages.RPR_MANUAL_VERIFICATION_REJECTED.getCode()); messageDTO.setIsValid(Boolean.FALSE); messageDTO.setInternalError(Boolean.FALSE); - verificationStage.sendMessage(messageDTO); } else { registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); registrationStatusDto.setStatusComment(StatusUtil.VERIFICATION_RESEND.getMessage()); @@ -723,7 +741,6 @@ private boolean successFlow(VerificationResponseDTO manualVerificationDTO, Verif description.setMessage(PlatformErrorMessages.RPR_MANUAL_VERIFICATION_RESEND.getMessage()); description.setCode(PlatformErrorMessages.RPR_MANUAL_VERIFICATION_RESEND.getCode()); messageDTO.setIsValid(Boolean.FALSE); - verificationStage.sendMessage(messageDTO); } basePacketRepository.update(entity); @@ -767,63 +784,5 @@ public boolean isResendFlow(InternalRegistrationStatusDto registrationStatusDto, return isResendFlow; } - private boolean saveVerificationRecord(MessageDTO messageDTO, String requestId, LogDescription description) { - String registrationId = messageDTO.getRid(); - boolean isTransactionSuccessful = false; - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), - registrationId, "saveVerificationRecord::entry"); - - try { - List existingRecords = basePacketRepository - .getVerificationRecordByWorkflowInstanceId(messageDTO.getWorkflowInstanceId()); - - if (CollectionUtils.isEmpty(existingRecords)) { - VerificationEntity verificationEntity = new VerificationEntity(); - VerificationPKEntity verificationPKEntity = new VerificationPKEntity(); - verificationPKEntity.setWorkflowInstanceId(messageDTO.getWorkflowInstanceId()); - - verificationEntity.setRegId(registrationId); - verificationEntity.setId(verificationPKEntity); - verificationEntity.setReponseText(null); - verificationEntity.setRequestId(requestId); - verificationEntity.setVerificationUsrId(null); - verificationEntity.setReasonCode(VERIFICATION_COMMENT); - verificationEntity.setStatusComment(VERIFICATION_COMMENT); - verificationEntity.setStatusCode(ManualVerificationStatus.INQUEUE.name()); - verificationEntity.setActive(true); - verificationEntity.setDeleted(false); - verificationEntity.setCrBy("SYSTEM"); - verificationEntity.setCrDtimes(Timestamp.valueOf(LocalDateTime.now(ZoneId.of("UTC")))); - verificationEntity.setUpdDtimes(Timestamp.valueOf(LocalDateTime.now(ZoneId.of("UTC")))); - basePacketRepository.save(verificationEntity); - } else { - VerificationEntity existingRecord = existingRecords.iterator().next(); - existingRecord.setReponseText(null); - existingRecord.setVerificationUsrId(null); - existingRecord.setReasonCode(VERIFICATION_COMMENT); - existingRecord.setStatusComment(VERIFICATION_COMMENT); - existingRecord.setStatusCode(ManualVerificationStatus.INQUEUE.name()); - existingRecord.setUpdDtimes(Timestamp.valueOf(LocalDateTime.now(ZoneId.of("UTC")))); - basePacketRepository.update(existingRecord); - } - description.setMessage("Packet marked for Verification saved successfully"); - isTransactionSuccessful = true; - - } catch (DataAccessLayerException e) { - isTransactionSuccessful = false; - description.setMessage("DataAccessLayerException while saving Verification data for rid" + registrationId - + "::" + e.getMessage()); - - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - registrationId, e.getMessage() + ExceptionUtils.getStackTrace(e)); - - throw new UnableToInsertData( - PlatformErrorMessages.RPR_PIS_UNABLE_TO_INSERT_DATA.getMessage() + registrationId, e); - } - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), - registrationId, "saveVerificationRecord::exit"); - - return isTransactionSuccessful; - } } diff --git a/registration-processor/core-processor/registration-processor-verification-stage/src/main/java/io/mosip/registration/processor/verification/util/SaveVerificationRecordUtility.java b/registration-processor/core-processor/registration-processor-verification-stage/src/main/java/io/mosip/registration/processor/verification/util/SaveVerificationRecordUtility.java new file mode 100644 index 00000000000..8a92b251983 --- /dev/null +++ b/registration-processor/core-processor/registration-processor-verification-stage/src/main/java/io/mosip/registration/processor/verification/util/SaveVerificationRecordUtility.java @@ -0,0 +1,100 @@ +package io.mosip.registration.processor.verification.util; + + +import java.sql.Timestamp; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.CollectionUtils; + +import io.mosip.kernel.core.dataaccess.exception.DataAccessLayerException; +import io.mosip.kernel.core.exception.ExceptionUtils; +import io.mosip.kernel.core.logger.spi.Logger; +import io.mosip.registration.processor.core.abstractverticle.MessageDTO; +import io.mosip.registration.processor.core.constant.LoggerFileConstant; +import io.mosip.registration.processor.core.exception.util.PlatformErrorMessages; +import io.mosip.registration.processor.core.logger.LogDescription; +import io.mosip.registration.processor.core.logger.RegProcessorLogger; +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.verification.dto.ManualVerificationStatus; + + +@Component +@Transactional(propagation = Propagation.REQUIRES_NEW) +public class SaveVerificationRecordUtility { + + private static Logger regProcLogger = RegProcessorLogger.getLogger(SaveVerificationRecordUtility.class); + private static final String VERIFICATION_COMMENT = "Packet marked for verification"; + + @Autowired + private BasePacketRepository basePacketRepository; + + + public boolean saveVerificationRecord(MessageDTO messageDTO, String requestId, LogDescription description) { + String registrationId = messageDTO.getRid(); + boolean isTransactionSuccessful = false; + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), + registrationId, "saveVerificationRecord::entry"); + + try { + List existingRecords = basePacketRepository + .getVerificationRecordByWorkflowInstanceId(messageDTO.getWorkflowInstanceId()); + + if (CollectionUtils.isEmpty(existingRecords)) { + VerificationEntity verificationEntity = new VerificationEntity(); + VerificationPKEntity verificationPKEntity = new VerificationPKEntity(); + verificationPKEntity.setWorkflowInstanceId(messageDTO.getWorkflowInstanceId()); + + verificationEntity.setRegId(registrationId); + verificationEntity.setId(verificationPKEntity); + verificationEntity.setReponseText(null); + verificationEntity.setRequestId(requestId); + verificationEntity.setVerificationUsrId(null); + verificationEntity.setReasonCode(VERIFICATION_COMMENT); + verificationEntity.setStatusComment(VERIFICATION_COMMENT); + verificationEntity.setStatusCode(ManualVerificationStatus.INQUEUE.name()); + verificationEntity.setActive(true); + verificationEntity.setDeleted(false); + verificationEntity.setCrBy("SYSTEM"); + verificationEntity.setCrDtimes(Timestamp.valueOf(LocalDateTime.now(ZoneId.of("UTC")))); + verificationEntity.setUpdDtimes(Timestamp.valueOf(LocalDateTime.now(ZoneId.of("UTC")))); + basePacketRepository.save(verificationEntity); + } else { + VerificationEntity existingRecord = existingRecords.iterator().next(); + existingRecord.setReponseText(null); + existingRecord.setVerificationUsrId(null); + existingRecord.setReasonCode(VERIFICATION_COMMENT); + existingRecord.setStatusComment(VERIFICATION_COMMENT); + existingRecord.setStatusCode(ManualVerificationStatus.INQUEUE.name()); + existingRecord.setUpdDtimes(Timestamp.valueOf(LocalDateTime.now(ZoneId.of("UTC")))); + basePacketRepository.update(existingRecord); + } + description.setMessage("Packet marked for Verification saved successfully"); + isTransactionSuccessful = true; + + } catch (DataAccessLayerException e) { + isTransactionSuccessful = false; + description.setMessage("DataAccessLayerException while saving Verification data for rid" + registrationId + + "::" + e.getMessage()); + + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + registrationId, e.getMessage() + ExceptionUtils.getStackTrace(e)); + + throw new UnableToInsertData( + PlatformErrorMessages.RPR_PIS_UNABLE_TO_INSERT_DATA.getMessage() + registrationId, e); + } + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), + registrationId, "saveVerificationRecord::exit"); + + return isTransactionSuccessful; + } + +} diff --git a/registration-processor/core-processor/registration-processor-verification-stage/src/main/java/io/mosip/registration/processor/verification/validators/ManualVerificationAppConfigurationsValidator.java b/registration-processor/core-processor/registration-processor-verification-stage/src/main/java/io/mosip/registration/processor/verification/validators/ManualVerificationAppConfigurationsValidator.java index d5961bea7d5..c46e2c60ec0 100644 --- a/registration-processor/core-processor/registration-processor-verification-stage/src/main/java/io/mosip/registration/processor/verification/validators/ManualVerificationAppConfigurationsValidator.java +++ b/registration-processor/core-processor/registration-processor-verification-stage/src/main/java/io/mosip/registration/processor/verification/validators/ManualVerificationAppConfigurationsValidator.java @@ -6,7 +6,6 @@ import org.springframework.beans.factory.annotation.Value; import io.mosip.registration.processor.core.logger.RegProcessorLogger; import io.mosip.kernel.core.logger.spi.Logger; - /** * All the configuration validations will be done in this class */ 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 0c1886ca76a..a2d11886c88 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,9 +1,51 @@ 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.argThat; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +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.ArgumentMatcher; +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.classic.spi.LoggingEvent; +import ch.qos.logback.core.Appender; import ch.qos.logback.core.read.ListAppender; -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; @@ -12,6 +54,7 @@ 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.JsonUtils; import io.mosip.kernel.core.util.exception.JsonProcessingException; import io.mosip.registration.processor.core.abstractverticle.MessageDTO; import io.mosip.registration.processor.core.code.ApiName; @@ -38,36 +81,16 @@ 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.*; +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 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 java.sql.Timestamp; -import java.util.*; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.*; -import static org.mockito.Matchers.any; +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.*" }) @@ -121,6 +144,10 @@ public class VerificationServiceTest { @Mock private RegistrationProcessorRestClientService registrationProcessorRestClientService; + @Mock + SaveVerificationRecordUtility saveVerificationRecordUtility; + + private InternalRegistrationStatusDto registrationStatusDto; private VerificationPKEntity PKId; private ManualVerificationDTO manualVerificationDTO; @@ -503,5 +530,6 @@ public void testUpdateStatusRejected() throws JsonProcessingException, com.faste assertTrue(result); } + } diff --git a/registration-processor/init/pom.xml b/registration-processor/init/pom.xml index acb9a8eaf40..f51c8554a6a 100644 --- a/registration-processor/init/pom.xml +++ b/registration-processor/init/pom.xml @@ -1,19 +1,19 @@ - - - 4.0.0 - pom - - io.mosip.registrationprocessor - registration-processor - 1.2.0.1-B1 - - init - - UTF-8 - - - registration-processor-packet-receiver-stage - registration-processor-registration-status-service - - + + + 4.0.0 + pom + + io.mosip.registrationprocessor + registration-processor + 1.2.0.1-B3-SNAPSHOT + + init + + UTF-8 + + + registration-processor-packet-receiver-stage + registration-processor-registration-status-service + + diff --git a/registration-processor/init/registration-processor-dmz-packet-server/version.xml b/registration-processor/init/registration-processor-dmz-packet-server/version.xml index f50eaa718f3..b0631be5aed 100644 --- a/registration-processor/init/registration-processor-dmz-packet-server/version.xml +++ b/registration-processor/init/registration-processor-dmz-packet-server/version.xml @@ -1,2 +1,2 @@ - -release-1.2.0.1 + +1.2.0.1-B3-SNAPSHOT diff --git a/registration-processor/init/registration-processor-packet-receiver-stage/pom.xml b/registration-processor/init/registration-processor-packet-receiver-stage/pom.xml index 8c01e101a59..efcb0fd2b6e 100644 --- a/registration-processor/init/registration-processor-packet-receiver-stage/pom.xml +++ b/registration-processor/init/registration-processor-packet-receiver-stage/pom.xml @@ -1,140 +1,144 @@ - - - 4.0.0 - - io.mosip.registrationprocessor - init - 1.2.0.1-B1 - - - registration-processor-packet-receiver-stage - 1.2.0.1-B1 - jar - registration-processor-packet-receiver-stage - - - UTF-8 - - - - - org.springframework.cloud - spring-cloud-starter-config - ${spring-cloud-config.version} - - - junit - junit - test - - - - org.mockito - mockito-core - ${mockito.version} - test - - - org.powermock - powermock-module-junit4 - ${powermock.module.junit4.version} - test - - - org.powermock - powermock-api-mockito2 - ${powermock.api.mockito.version} - test - - - io.vertx - vertx-unit - ${vertx.version} - test - - - io.vertx - vertx-web-client - 3.6.2 - - - - io.vertx - vertx-core - - - - - org.apache.httpcomponents - httpmime - 4.3.1 - - - - org.springframework - spring-context - 5.0.6.RELEASE - - - - io.springfox - springfox-swagger-ui - ${swagger.version} - - - io.springfox - springfox-swagger2 - ${swagger.version} - - - org.postgresql - postgresql - - - io.mosip.registrationprocessor - registration-processor-registration-status-service-impl - ${registration.status.service.version} - - - io.mosip.registrationprocessor - registration-processor-core - ${registration.processor.core.version} - - - io.mosip.registrationprocessor - registration-processor-packet-manager - ${packet.manager.version} - - - io.mosip.registrationprocessor - registration-processor-rest-client - ${registration.processor.rest.client.version} - - - javax.inject - javax.inject - 1 - - - - - - com.h2database - h2 - ${h2.version} - - - - - - - - - - + + + 4.0.0 + + io.mosip.registrationprocessor + init + 1.2.0.1-B3-SNAPSHOT + + + registration-processor-packet-receiver-stage + 1.2.0.1-B3-SNAPSHOT + jar + registration-processor-packet-receiver-stage + + + UTF-8 + + + + + org.springframework.cloud + spring-cloud-starter-config + ${spring-cloud-config.version} + + + junit + junit + test + + + + org.mockito + mockito-core + ${mockito.version} + test + + io.mosip.commons + khazana + ${object.store.khazana.version} + + + org.powermock + powermock-module-junit4 + ${powermock.module.junit4.version} + test + + + org.powermock + powermock-api-mockito2 + ${powermock.api.mockito.version} + test + + + io.vertx + vertx-unit + ${vertx.version} + test + + + io.vertx + vertx-web-client + 3.6.2 + + + + io.vertx + vertx-core + + + + + org.apache.httpcomponents + httpmime + 4.3.1 + + + + org.springframework + spring-context + 5.0.6.RELEASE + + + + io.springfox + springfox-swagger-ui + ${swagger.version} + + + io.springfox + springfox-swagger2 + ${swagger.version} + + + org.postgresql + postgresql + + + io.mosip.registrationprocessor + registration-processor-registration-status-service-impl + ${registration.status.service.version} + + + io.mosip.registrationprocessor + registration-processor-core + ${registration.processor.core.version} + + + io.mosip.registrationprocessor + registration-processor-packet-manager + ${packet.manager.version} + + + io.mosip.registrationprocessor + registration-processor-rest-client + ${registration.processor.rest.client.version} + + + javax.inject + javax.inject + 1 + + + + + + com.h2database + h2 + ${h2.version} + + + + + + + + + + diff --git a/registration-processor/init/registration-processor-packet-receiver-stage/src/main/java/io/mosip/registration/processor/packet/receiver/builder/PacketReceiverResponseBuilder.java b/registration-processor/init/registration-processor-packet-receiver-stage/src/main/java/io/mosip/registration/processor/packet/receiver/builder/PacketReceiverResponseBuilder.java index 8b202bc1637..cf79e2e6fca 100644 --- a/registration-processor/init/registration-processor-packet-receiver-stage/src/main/java/io/mosip/registration/processor/packet/receiver/builder/PacketReceiverResponseBuilder.java +++ b/registration-processor/init/registration-processor-packet-receiver-stage/src/main/java/io/mosip/registration/processor/packet/receiver/builder/PacketReceiverResponseBuilder.java @@ -2,10 +2,9 @@ import java.util.List; import java.util.Objects; + import org.springframework.stereotype.Component; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import io.mosip.kernel.core.util.DateUtils; + import io.mosip.registration.processor.packet.receiver.dto.PacketReceiverResponseDTO; import io.mosip.registration.processor.packet.receiver.dto.ResponseDTO; diff --git a/registration-processor/init/registration-processor-packet-receiver-stage/src/main/java/io/mosip/registration/processor/packet/receiver/config/PacketReceiverConfig.java b/registration-processor/init/registration-processor-packet-receiver-stage/src/main/java/io/mosip/registration/processor/packet/receiver/config/PacketReceiverConfig.java index d616cffa447..9fd97e2a071 100644 --- a/registration-processor/init/registration-processor-packet-receiver-stage/src/main/java/io/mosip/registration/processor/packet/receiver/config/PacketReceiverConfig.java +++ b/registration-processor/init/registration-processor-packet-receiver-stage/src/main/java/io/mosip/registration/processor/packet/receiver/config/PacketReceiverConfig.java @@ -1,146 +1,166 @@ -package io.mosip.registration.processor.packet.receiver.config; - -import java.io.File; -import java.io.InputStream; - -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.module.afterburner.AfterburnerModule; -import io.mosip.kernel.core.logger.spi.Logger; -import io.mosip.registration.processor.core.logger.RegProcessorLogger; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.EnableAspectJAutoProxy; -import org.springframework.context.annotation.Lazy; -import org.springframework.context.annotation.Primary; - -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; - -import io.mosip.kernel.biometrics.spi.CbeffUtil; -import io.mosip.kernel.cbeffutil.impl.CbeffImpl; -import io.mosip.kernel.core.idvalidator.spi.RidValidator; -import io.mosip.kernel.core.virusscanner.spi.VirusScanner; -import io.mosip.kernel.idvalidator.rid.impl.RidValidatorImpl; -import io.mosip.registration.processor.core.abstractverticle.MessageDTO; -import io.mosip.registration.processor.core.spi.filesystem.manager.FileManager; -import io.mosip.registration.processor.packet.manager.decryptor.Decryptor; -import io.mosip.registration.processor.packet.manager.decryptor.DecryptorImpl; -import io.mosip.registration.processor.packet.manager.dto.DirectoryPathDto; -import io.mosip.registration.processor.packet.manager.idreposervice.IdRepoService; -import io.mosip.registration.processor.packet.manager.idreposervice.impl.IdRepoServiceImpl; -import io.mosip.registration.processor.packet.manager.service.impl.FileManagerImpl; -import io.mosip.registration.processor.packet.receiver.builder.PacketReceiverResponseBuilder; -import io.mosip.registration.processor.packet.receiver.exception.handler.PacketReceiverExceptionHandler; -import io.mosip.registration.processor.packet.receiver.service.PacketReceiverService; -import io.mosip.registration.processor.packet.receiver.service.impl.PacketReceiverServiceImpl; - -/** - * The Class PacketReceiverConfig. - */ -/** - * @author Mukul Puspam - * - */ -@Configuration -@EnableAspectJAutoProxy -public class PacketReceiverConfig { - - private static Logger logger = RegProcessorLogger.getLogger(PacketReceiverConfig.class); - - @Value("${mosip.regproc.virusscanner.provider}") - private String virusScannerProviderName; - - /** - * PacketReceiverService bean. - * - * @return the packet receiver service - */ - @Bean - public PacketReceiverService getPacketReceiverService() { - return new PacketReceiverServiceImpl(); - } - - /** - * GlobalExceptionHandler bean. - * - * @return the global exception handler - */ - @Bean - public PacketReceiverExceptionHandler getGlobalExceptionHandler() { - return new PacketReceiverExceptionHandler(); - } - - /** - * Gets the packet receiver response builder. - * - * @return the packet receiver response builder - */ - @Bean - public PacketReceiverResponseBuilder getPacketReceiverResponseBuilder() { - return new PacketReceiverResponseBuilder(); - } - - /** - * Virus scanner service. Load virus scanner during runtime from property mosip.regproc.virusscanner.provider - * - * @return the virus scanner - */ - @Bean - @Lazy - public VirusScanner virusScannerService() throws ClassNotFoundException, IllegalAccessException, InstantiationException { - logger.info("mosip.regproc.virusscanner.provider is set as ", virusScannerProviderName, - "Validating if the implementation is present in classpath", ""); - VirusScanner virusScanner = null; - try { - virusScanner = (VirusScanner) Class.forName(virusScannerProviderName).newInstance(); - - } catch (ClassNotFoundException | ClassCastException e) { - logger.error("Exception occurred validating - " + virusScannerProviderName + - ". Please make sure implementation is available in classpath", e); - throw e; - } - logger.info("Successfully validated : " + virusScannerProviderName); - - return virusScanner; - } - - @Bean - @Primary - public RidValidator getRidValidator() { - return new RidValidatorImpl(); - } - - @Bean - @Primary - public CbeffUtil getCbeffUtil() { - return new CbeffImpl(); - } - - @Bean - @Primary - public ObjectMapper getObjectMapper() { - ObjectMapper objectMapper = new ObjectMapper().registerModule(new AfterburnerModule()).registerModule(new JavaTimeModule()); - objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); - return objectMapper; - } - - @Bean - @Primary - public FileManager filemanager() { - return new FileManagerImpl(); - } - - @Bean - @Primary - public IdRepoService getIdRepoService() { - return new IdRepoServiceImpl(); - } - - @Bean - @Primary - public Decryptor getDecryptor() { - return new DecryptorImpl(); - } - -} +package io.mosip.registration.processor.packet.receiver.config; + +import java.io.File; +import java.io.InputStream; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.EnableAspectJAutoProxy; +import org.springframework.context.annotation.Lazy; +import org.springframework.context.annotation.Primary; + +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; +import com.fasterxml.jackson.module.afterburner.AfterburnerModule; + +import io.mosip.commons.khazana.impl.S3Adapter; +import io.mosip.commons.khazana.impl.SwiftAdapter; +import io.mosip.commons.khazana.spi.ObjectStoreAdapter; +import io.mosip.kernel.biometrics.spi.CbeffUtil; +import io.mosip.kernel.cbeffutil.impl.CbeffImpl; +import io.mosip.kernel.core.idvalidator.spi.RidValidator; +import io.mosip.kernel.core.logger.spi.Logger; +import io.mosip.kernel.core.virusscanner.spi.VirusScanner; +import io.mosip.kernel.idvalidator.rid.impl.RidValidatorImpl; +import io.mosip.registration.processor.core.abstractverticle.MessageDTO; +import io.mosip.registration.processor.core.logger.RegProcessorLogger; +import io.mosip.registration.processor.core.spi.filesystem.manager.FileManager; +import io.mosip.registration.processor.packet.manager.decryptor.Decryptor; +import io.mosip.registration.processor.packet.manager.decryptor.DecryptorImpl; +import io.mosip.registration.processor.packet.manager.dto.DirectoryPathDto; +import io.mosip.registration.processor.packet.manager.idreposervice.IdRepoService; +import io.mosip.registration.processor.packet.manager.idreposervice.impl.IdRepoServiceImpl; +import io.mosip.registration.processor.packet.manager.service.impl.FileManagerImpl; +import io.mosip.registration.processor.packet.receiver.builder.PacketReceiverResponseBuilder; +import io.mosip.registration.processor.packet.receiver.exception.handler.PacketReceiverExceptionHandler; +import io.mosip.registration.processor.packet.receiver.service.PacketReceiverService; +import io.mosip.registration.processor.packet.receiver.service.impl.PacketReceiverServiceImpl; + +/** + * The Class PacketReceiverConfig. + */ +/** + * @author Mukul Puspam + * + */ +@Configuration +@EnableAspectJAutoProxy +public class PacketReceiverConfig { + + private static Logger logger = RegProcessorLogger.getLogger(PacketReceiverConfig.class); + + @Value("${mosip.regproc.virusscanner.provider}") + private String virusScannerProviderName; + private static final String s3_Adapter = "S3Adapter"; + private static final String swift_Adapter = "SwiftAdapter"; + + @Value("${registration.processor.objectstore.adapter.name}") + private String adapter; + + @Bean + @Primary + public ObjectStoreAdapter objectStoreAdapter() { + if (adapter.equalsIgnoreCase(s3_Adapter)) + return new S3Adapter(); + else if (adapter.equalsIgnoreCase(swift_Adapter)) + return new SwiftAdapter(); + else + throw new UnsupportedOperationException("No adapter implementation found for configuration: registration.processor.objectstore.adapter.name"); + } + /** + * PacketReceiverService bean. + * + * @return the packet receiver service + */ + @Bean + public PacketReceiverService getPacketReceiverService() { + return new PacketReceiverServiceImpl(); + } + + /** + * GlobalExceptionHandler bean. + * + * @return the global exception handler + */ + @Bean + public PacketReceiverExceptionHandler getGlobalExceptionHandler() { + return new PacketReceiverExceptionHandler(); + } + + /** + * Gets the packet receiver response builder. + * + * @return the packet receiver response builder + */ + @Bean + public PacketReceiverResponseBuilder getPacketReceiverResponseBuilder() { + return new PacketReceiverResponseBuilder(); + } + + /** + * Virus scanner service. Load virus scanner during runtime from property mosip.regproc.virusscanner.provider + * + * @return the virus scanner + */ + @Bean + @Lazy + public VirusScanner virusScannerService() throws ClassNotFoundException, IllegalAccessException, InstantiationException { + logger.info("mosip.regproc.virusscanner.provider is set as ", virusScannerProviderName, + "Validating if the implementation is present in classpath", ""); + VirusScanner virusScanner = null; + try { + virusScanner = (VirusScanner) Class.forName(virusScannerProviderName).newInstance(); + + } catch (ClassNotFoundException | ClassCastException e) { + logger.error("Exception occurred validating - " + virusScannerProviderName + + ". Please make sure implementation is available in classpath", e); + throw e; + } + logger.info("Successfully validated : " + virusScannerProviderName); + + return virusScanner; + } + + @Bean + @Primary + public RidValidator getRidValidator() { + return new RidValidatorImpl(); + } + + @Bean + @Primary + public CbeffUtil getCbeffUtil() { + return new CbeffImpl(); + } + + @Bean + @Primary + public ObjectMapper getObjectMapper() { + ObjectMapper objectMapper = new ObjectMapper().registerModule(new AfterburnerModule()).registerModule(new JavaTimeModule()); + objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); + objectMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS); + return objectMapper; + } + + @Bean + @Primary + public FileManager filemanager() { + return new FileManagerImpl(); + } + + @Bean + @Primary + public IdRepoService getIdRepoService() { + return new IdRepoServiceImpl(); + } + + @Bean + @Primary + public Decryptor getDecryptor() { + return new DecryptorImpl(); + } + +} diff --git a/registration-processor/init/registration-processor-packet-receiver-stage/src/main/java/io/mosip/registration/processor/packet/receiver/service/PacketReceiverService.java b/registration-processor/init/registration-processor-packet-receiver-stage/src/main/java/io/mosip/registration/processor/packet/receiver/service/PacketReceiverService.java index 7135beac148..e8226a6f264 100644 --- a/registration-processor/init/registration-processor-packet-receiver-stage/src/main/java/io/mosip/registration/processor/packet/receiver/service/PacketReceiverService.java +++ b/registration-processor/init/registration-processor-packet-receiver-stage/src/main/java/io/mosip/registration/processor/packet/receiver/service/PacketReceiverService.java @@ -2,6 +2,8 @@ import org.springframework.stereotype.Service; +import io.mosip.registration.processor.core.exception.ObjectStoreNotAccessibleException; + /** * This service is used to store the registration packets to virus scanner zone, * check duplicate packets etc. @@ -23,6 +25,6 @@ public interface PacketReceiverService { */ public U validatePacket(T file, String stageName); - public U processPacket(T file); + public U processPacket(T file) ; } 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 dd369380a88..da245522a0b 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 @@ -11,6 +11,7 @@ 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; @@ -21,6 +22,7 @@ import org.springframework.dao.DataAccessException; import org.springframework.stereotype.Component; +import io.mosip.commons.khazana.spi.ObjectStoreAdapter; import io.mosip.kernel.core.exception.ExceptionUtils; import io.mosip.kernel.core.logger.spi.Logger; import io.mosip.kernel.core.util.HMACUtils2; @@ -34,6 +36,7 @@ import io.mosip.registration.processor.core.code.RegistrationExceptionTypeCode; import io.mosip.registration.processor.core.code.RegistrationTransactionStatusCode; import io.mosip.registration.processor.core.code.RegistrationTransactionTypeCode; +import io.mosip.registration.processor.core.constant.LandingZoneTypeConstant; import io.mosip.registration.processor.core.constant.LoggerFileConstant; import io.mosip.registration.processor.core.exception.util.PlatformErrorMessages; import io.mosip.registration.processor.core.exception.util.PlatformSuccessMessages; @@ -105,11 +108,20 @@ public class PacketReceiverServiceImpl implements PacketReceiverService errors = new ArrayList<>(); ErrorDTO errorDTO = new ErrorDTO("", ""); - - Gson gson = new GsonBuilder().serializeNulls().create(); + private final Logger logger = LoggerFactory.getLogger(this.getClass()); /** * Sets the up. @@ -88,20 +92,27 @@ public void testDuplicateEntry() throws JsonParseException, JsonMappingException errorDTO.setMessage("Duplicate Request Received"); errors.add(errorDTO); packetReceiverResponseDTO.setErrors(errors); - assertEquals(gson.toJson(packetReceiverResponseDTO), gson.toJson(packetReceiverResponseDTO1)); + assertEquals(objMp.writeValueAsString(packetReceiverResponseDTO), + objMp.writeValueAsString(packetReceiverResponseDTO1)); } @Test public void testhandlePacketNotValidException() { PacketNotValidException exe = new PacketNotValidException( PlatformErrorMessages.RPR_PKR_INVALID_PACKET_SIZE.getMessage()); - PacketReceiverResponseDTO packetReceiverResponseDTO1 = packetReceiverExceptionHandler.handler(exe); + PacketReceiverResponseDTO packetReceiverResponseDTO1 = packetReceiverExceptionHandler.handler(exe); packetReceiverResponseDTO.setResponsetime(packetReceiverResponseDTO1.getResponsetime()); errorDTO.setErrorCode("RPR-PKR-003"); errorDTO.setMessage("Invalid Packet Size"); errors.add(errorDTO); packetReceiverResponseDTO.setErrors(errors); - assertEquals(gson.toJson(packetReceiverResponseDTO), gson.toJson(packetReceiverResponseDTO1)); + try { + assertEquals(objMp.writeValueAsString(packetReceiverResponseDTO), + objMp.writeValueAsString(packetReceiverResponseDTO1)); + } catch (JsonProcessingException e) { + + logger.error("Error while processing json",e); + } } @Test @@ -114,45 +125,69 @@ public void testhandleFileSizeExceedException() { errorDTO.setMessage("Invalid Packet Size"); errors.add(errorDTO); packetReceiverResponseDTO.setErrors(errors); - assertEquals(gson.toJson(packetReceiverResponseDTO), gson.toJson(packetReceiverResponseDTO1)); + try { + assertEquals(objMp.writeValueAsString(packetReceiverResponseDTO), + objMp.writeValueAsString(packetReceiverResponseDTO1)); + } catch (JsonProcessingException e) { + + logger.error("Error while processing json",e); + } } @Test public void handlePacketNotSyncException() { PacketNotSyncException exe = new PacketNotSyncException( PlatformErrorMessages.RPR_PKR_INVALID_PACKET_SIZE.getMessage()); - PacketReceiverResponseDTO packetReceiverResponseDTO1 = packetReceiverExceptionHandler.handler(exe); + PacketReceiverResponseDTO packetReceiverResponseDTO1 = packetReceiverExceptionHandler.handler(exe); packetReceiverResponseDTO.setResponsetime(packetReceiverResponseDTO1.getResponsetime()); errorDTO.setErrorCode("RPR-PKR-001"); errorDTO.setMessage("Invalid Packet Size"); errors.add(errorDTO); packetReceiverResponseDTO.setErrors(errors); - assertEquals(gson.toJson(packetReceiverResponseDTO), gson.toJson(packetReceiverResponseDTO1)); + try { + assertEquals(objMp.writeValueAsString(packetReceiverResponseDTO), + objMp.writeValueAsString(packetReceiverResponseDTO1)); + } catch (JsonProcessingException e) { + + logger.error("Error while processing json",e); + } } @Test public void testhandleTablenotAccessibleException() { TablenotAccessibleException exe = new TablenotAccessibleException( PlatformErrorMessages.RPR_PKR_INVALID_PACKET_SIZE.getMessage()); - PacketReceiverResponseDTO packetReceiverResponseDTO1 =packetReceiverExceptionHandler.handler(exe); + PacketReceiverResponseDTO packetReceiverResponseDTO1 = packetReceiverExceptionHandler.handler(exe); packetReceiverResponseDTO.setResponsetime(packetReceiverResponseDTO1.getResponsetime()); errorDTO.setErrorCode("RPR-RGS-001"); errorDTO.setMessage("Invalid Packet Size"); errors.add(errorDTO); packetReceiverResponseDTO.setErrors(errors); - assertEquals(gson.toJson(packetReceiverResponseDTO), gson.toJson(packetReceiverResponseDTO1)); + try { + assertEquals(objMp.writeValueAsString(packetReceiverResponseDTO), + objMp.writeValueAsString(packetReceiverResponseDTO1)); + } catch (JsonProcessingException e) { + + logger.error("Error while processing json",e); + } } @Test public void handleTimeoutException() { TimeoutException exe = new TimeoutException(PlatformErrorMessages.RPR_PKR_INVALID_PACKET_SIZE.getMessage()); - PacketReceiverResponseDTO packetReceiverResponseDTO1 =packetReceiverExceptionHandler.handler(exe); + PacketReceiverResponseDTO packetReceiverResponseDTO1 = packetReceiverExceptionHandler.handler(exe); packetReceiverResponseDTO.setResponsetime(packetReceiverResponseDTO1.getResponsetime()); errorDTO.setErrorCode("RPR-SYS-005"); errorDTO.setMessage("Invalid Packet Size"); errors.add(errorDTO); packetReceiverResponseDTO.setErrors(errors); - assertEquals(gson.toJson(packetReceiverResponseDTO), gson.toJson(packetReceiverResponseDTO1)); + try { + assertEquals(objMp.writeValueAsString(packetReceiverResponseDTO), + objMp.writeValueAsString(packetReceiverResponseDTO1)); + } catch (JsonProcessingException e) { + + logger.error("Error while processing json",e); + } } @Test @@ -165,20 +200,32 @@ public void testhandleUnexpectedException() { errorDTO.setMessage("Invalid Packet Size"); errors.add(errorDTO); packetReceiverResponseDTO.setErrors(errors); - assertEquals(gson.toJson(packetReceiverResponseDTO), gson.toJson(packetReceiverResponseDTO1)); + try { + assertEquals(objMp.writeValueAsString(packetReceiverResponseDTO), + objMp.writeValueAsString(packetReceiverResponseDTO1)); + } catch (JsonProcessingException e) { + + logger.error("Error while processing json",e); + } } @Test public void testhandleValidationException() { ValidationException exe = new ValidationException( PlatformErrorMessages.RPR_PKR_INVALID_PACKET_SIZE.getMessage()); - PacketReceiverResponseDTO packetReceiverResponseDTO1 =packetReceiverExceptionHandler.handler(exe); + PacketReceiverResponseDTO packetReceiverResponseDTO1 = packetReceiverExceptionHandler.handler(exe); packetReceiverResponseDTO.setResponsetime(packetReceiverResponseDTO1.getResponsetime()); errorDTO.setErrorCode("RPR-PKR-004"); errorDTO.setMessage("Invalid Packet Size"); errors.add(errorDTO); packetReceiverResponseDTO.setErrors(errors); - assertEquals(gson.toJson(packetReceiverResponseDTO), gson.toJson(packetReceiverResponseDTO1)); + try { + assertEquals(objMp.writeValueAsString(packetReceiverResponseDTO), + objMp.writeValueAsString(packetReceiverResponseDTO1)); + } catch (JsonProcessingException e) { + + logger.error("Error while processing json",e); + } } @Test @@ -188,7 +235,13 @@ public void testdataExceptionHandler() { PacketReceiverResponseDTO packetReceiverResponseDTO1 = packetReceiverExceptionHandler.handler(exe); packetReceiverResponseDTO.setResponsetime(packetReceiverResponseDTO1.getResponsetime()); packetReceiverResponseDTO.setErrors(null); - assertEquals(gson.toJson(packetReceiverResponseDTO), gson.toJson(packetReceiverResponseDTO1)); + try { + assertEquals(objMp.writeValueAsString(packetReceiverResponseDTO), + objMp.writeValueAsString(packetReceiverResponseDTO1)); + } catch (JsonProcessingException e) { + + logger.error("Error while processing json",e); + } } @Test @@ -201,7 +254,13 @@ public void testhandlePacketNotAvailableException() { errorDTO.setMessage("Packet Not Available in Request"); errors.add(errorDTO); packetReceiverResponseDTO.setErrors(errors); - assertEquals(gson.toJson(packetReceiverResponseDTO), gson.toJson(packetReceiverResponseDTO1)); + try { + assertEquals(objMp.writeValueAsString(packetReceiverResponseDTO), + objMp.writeValueAsString(packetReceiverResponseDTO1)); + } catch (JsonProcessingException e) { + + logger.error("Error while processing json",e); + } } @Test @@ -214,7 +273,13 @@ public void testhandlePacketSizeNotInSyncException() { errorDTO.setMessage("Packet Size is Not Matching"); errors.add(errorDTO); packetReceiverResponseDTO.setErrors(errors); - assertEquals(gson.toJson(packetReceiverResponseDTO), gson.toJson(packetReceiverResponseDTO1)); + try { + assertEquals(objMp.writeValueAsString(packetReceiverResponseDTO), + objMp.writeValueAsString(packetReceiverResponseDTO1)); + } catch (JsonProcessingException e) { + + logger.error("Error while processing json",e); + } } @Test @@ -227,7 +292,13 @@ public void testhandleVirusScanFailedException() { errorDTO.setMessage("Virus was Found in Packet"); errors.add(errorDTO); packetReceiverResponseDTO.setErrors(errors); - assertEquals(gson.toJson(packetReceiverResponseDTO), gson.toJson(packetReceiverResponseDTO1)); + try { + assertEquals(objMp.writeValueAsString(packetReceiverResponseDTO), + objMp.writeValueAsString(packetReceiverResponseDTO1)); + } catch (JsonProcessingException e) { + + logger.error("Error while processing json",e); + } } @Test @@ -240,20 +311,32 @@ public void testhandleUnequalHashSequenceException() { errorDTO.setMessage("Packet HashSequence did not match"); errors.add(errorDTO); packetReceiverResponseDTO.setErrors(errors); - assertEquals(gson.toJson(packetReceiverResponseDTO), gson.toJson(packetReceiverResponseDTO1)); + try { + assertEquals(objMp.writeValueAsString(packetReceiverResponseDTO), + objMp.writeValueAsString(packetReceiverResponseDTO1)); + } catch (JsonProcessingException e) { + + logger.error("Error while processing json",e); + } } @Test public void testhandleVirusScannerServiceException() { VirusScannerServiceException exe = new VirusScannerServiceException( PlatformErrorMessages.PRP_PKR_PACKET_VIRUS_SCANNER_SERVICE_FAILED.getMessage()); - PacketReceiverResponseDTO packetReceiverResponseDTO1 = packetReceiverExceptionHandler.handler(exe); + PacketReceiverResponseDTO packetReceiverResponseDTO1 = packetReceiverExceptionHandler.handler(exe); packetReceiverResponseDTO.setResponsetime(packetReceiverResponseDTO1.getResponsetime()); errorDTO.setErrorCode("RPR-PKR-008"); errorDTO.setMessage("Virus Scan Service is Not Responding"); errors.add(errorDTO); packetReceiverResponseDTO.setErrors(errors); - assertEquals(gson.toJson(packetReceiverResponseDTO), gson.toJson(packetReceiverResponseDTO1)); + try { + assertEquals(objMp.writeValueAsString(packetReceiverResponseDTO), + objMp.writeValueAsString(packetReceiverResponseDTO1)); + } catch (JsonProcessingException e) { + + logger.error("Error while processing json",e); + } } } diff --git a/registration-processor/init/registration-processor-packet-receiver-stage/src/test/java/io/mosip/registration/processor/packet/receiver/service/PacketReceiverServiceTest.java b/registration-processor/init/registration-processor-packet-receiver-stage/src/test/java/io/mosip/registration/processor/packet/receiver/service/PacketReceiverServiceTest.java index 49fda86e7eb..171b7b1eca2 100644 --- a/registration-processor/init/registration-processor-packet-receiver-stage/src/test/java/io/mosip/registration/processor/packet/receiver/service/PacketReceiverServiceTest.java +++ b/registration-processor/init/registration-processor-packet-receiver-stage/src/test/java/io/mosip/registration/processor/packet/receiver/service/PacketReceiverServiceTest.java @@ -45,6 +45,7 @@ import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.classic.spi.LoggingEvent; import ch.qos.logback.core.Appender; +import io.mosip.commons.khazana.spi.ObjectStoreAdapter; import io.mosip.kernel.core.util.HMACUtils2; import io.mosip.kernel.core.virusscanner.exception.VirusScannerException; import io.mosip.kernel.core.virusscanner.spi.VirusScanner; @@ -116,6 +117,9 @@ public class PacketReceiverServiceTest { @Mock private AdditionalInfoRequestService additionalInfoRequestService; + + @Mock + private ObjectStoreAdapter objectStoreAdapter; private String stageName = "PacketReceiverStage"; @@ -137,6 +141,8 @@ public void setup() throws Exception { mainprocessList.add("NEW"); mainprocessList.add("UPDATE"); ReflectionTestUtils.setField(packetReceiverService, "mainProcesses", mainprocessList); + ReflectionTestUtils.setField(packetReceiverService, "landingZoneAccount", "landing-zone"); + ReflectionTestUtils.setField(packetReceiverService, "landingZoneType", "DMZServer"); ReflectionTestUtils.setField(packetReceiverService, "extention", ".zip"); ReflectionTestUtils.setField(packetReceiverService, "fileSize", "5"); @@ -158,6 +164,8 @@ public void setup() throws Exception { registrations.add(registrationStatusDto); Mockito.doNothing().when(description).setMessage(any()); Mockito.when(registrationStatusService.getByIds(anyList())).thenReturn(registrations); + Mockito.when(registrationStatusService.getByIds(anyList())).thenReturn(registrations); + Mockito.when(objectStoreAdapter.putObject(any(), any(), any(), any(), any(), any())).thenReturn(true); PowerMockito.mockStatic(ZipUtils.class); PowerMockito.when(ZipUtils.unzipAndGetFile(any(), anyString())) .thenReturn(new ByteArrayInputStream(new String("abc").getBytes())); @@ -202,6 +210,37 @@ public void testPacketStorageSuccess() assertEquals(true, successResult.getIsValid()); } + @Test + public void testPacketStorageObjectStoreSuccess() + throws IOException, URISyntaxException, PacketDecryptionFailureException, ApisResourceAccessException, io.mosip.registration.processor.core.exception.PacketDecryptionFailureException { + ReflectionTestUtils.setField(packetReceiverService, "landingZoneType", "ObjectStore"); + Mockito.when(syncRegistrationService.findByPacketId(anyString())).thenReturn(regEntity); + mockDto = new InternalRegistrationStatusDto(); + mockDto.setIteration(1); + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(mockDto); + Mockito.doNothing().when(fileManager).put(anyString(), any(InputStream.class), any(DirectoryPathDto.class)); + Mockito.when(virusScannerService.scanFile(any(InputStream.class))).thenReturn(Boolean.TRUE); + MessageDTO successResult = packetReceiverService.processPacket(mockMultipartFile); + + assertEquals(true, successResult.getIsValid()); + } + + @Test + public void testPacketStorageObjectStoreFailure() + throws IOException, URISyntaxException, PacketDecryptionFailureException, ApisResourceAccessException, io.mosip.registration.processor.core.exception.PacketDecryptionFailureException { + ReflectionTestUtils.setField(packetReceiverService, "landingZoneType", "ObjectStore"); + Mockito.when(objectStoreAdapter.putObject(any(), any(), any(), any(), any(), any())).thenReturn(false); + + Mockito.when(syncRegistrationService.findByPacketId(anyString())).thenReturn(regEntity); + mockDto = new InternalRegistrationStatusDto(); + mockDto.setIteration(1); + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(mockDto); + Mockito.doNothing().when(fileManager).put(anyString(), any(InputStream.class), any(DirectoryPathDto.class)); + Mockito.when(virusScannerService.scanFile(any(InputStream.class))).thenReturn(Boolean.TRUE); + MessageDTO successResult = packetReceiverService.processPacket(mockMultipartFile); + + assertEquals(true, successResult.getInternalError()); + } @Test public void testSubProcessPacketStorageSuccess() diff --git a/registration-processor/init/registration-processor-registration-status-service/pom.xml b/registration-processor/init/registration-processor-registration-status-service/pom.xml index cee40b9c641..8e3bc1616f3 100644 --- a/registration-processor/init/registration-processor-registration-status-service/pom.xml +++ b/registration-processor/init/registration-processor-registration-status-service/pom.xml @@ -1,165 +1,165 @@ - - - - 4.0.0 - - - io.mosip.registrationprocessor - init - 1.2.0.1-B1 - - registration-processor-registration-status-service - 1.2.0.1-B1 - - registration-processor-registration-status-service - - - UTF-8 - - - - - junit - junit - test - - - org.springframework.boot - spring-boot-starter-web - - - io.mosip.registrationprocessor - registration-processor-registration-status-service-impl - ${registration.status.service.version} - - - io.springfox - springfox-swagger-ui - - - io.springfox - springfox-swagger2 - - - - - org.springframework.boot - spring-boot-starter-security - - - org.springframework.security - spring-security-test - - - org.springdoc - springdoc-openapi-ui - 1.5.10 - - - org.springframework.boot - spring-boot-configuration-processor - ${spring.boot.version} - true - - - - - - org.springframework.boot - spring-boot-maven-plugin - ${spring.boot.version} - - true - ZIP - - - - - build-info - repackage - - - - - - - - - openapi-doc-generate-profile - - - io.mosip.kernel - kernel-auth-adapter - ${project.version} - - - - - - org.springframework.boot - spring-boot-maven-plugin - ${spring.boot.version} - - true - ZIP - - - - pre-integration-test - - start - - - - src/test/resources - - - openapi-profile - - - --server.port=8090 - --server.servlet.path=/app/generic - - - - - - post-integration-test - - stop - - - - - build-info - repackage - - - - - - org.springdoc - springdoc-openapi-maven-plugin - 0.2 - - - integration-test - - generate - - - - - http://localhost:8090/app/generic/v3/api-docs - ${name}-openapi.json - ${project.build.directory} - false - - - - - - - + + + + 4.0.0 + + + io.mosip.registrationprocessor + init + 1.2.0.1-B3-SNAPSHOT + + registration-processor-registration-status-service + 1.2.0.1-B3-SNAPSHOT + + registration-processor-registration-status-service + + + UTF-8 + + + + + junit + junit + test + + + org.springframework.boot + spring-boot-starter-web + + + io.mosip.registrationprocessor + registration-processor-registration-status-service-impl + ${registration.status.service.version} + + + io.springfox + springfox-swagger-ui + + + io.springfox + springfox-swagger2 + + + + + org.springframework.boot + spring-boot-starter-security + + + org.springframework.security + spring-security-test + + + org.springdoc + springdoc-openapi-ui + 1.5.10 + + + org.springframework.boot + spring-boot-configuration-processor + ${spring.boot.version} + true + + + + + + org.springframework.boot + spring-boot-maven-plugin + ${spring.boot.version} + + true + ZIP + + + + + build-info + repackage + + + + + + + + + openapi-doc-generate-profile + + + io.mosip.kernel + kernel-auth-adapter + ${project.version} + + + + + + org.springframework.boot + spring-boot-maven-plugin + ${spring.boot.version} + + true + ZIP + + + + pre-integration-test + + start + + + + src/test/resources + + + openapi-profile + + + --server.port=8090 + --server.servlet.path=/app/generic + + + + + + post-integration-test + + stop + + + + + build-info + repackage + + + + + + org.springdoc + springdoc-openapi-maven-plugin + 0.2 + + + integration-test + + generate + + + + + http://localhost:8090/app/generic/v3/api-docs + ${name}-openapi.json + ${project.build.directory} + false + + + + + + + diff --git a/registration-processor/init/registration-processor-registration-status-service/src/main/java/io/mosip/registration/processor/status/api/controller/InternalAuthDelegateServicesController.java b/registration-processor/init/registration-processor-registration-status-service/src/main/java/io/mosip/registration/processor/status/api/controller/InternalAuthDelegateServicesController.java index d0673ce0056..6ad8c3f810a 100644 --- a/registration-processor/init/registration-processor-registration-status-service/src/main/java/io/mosip/registration/processor/status/api/controller/InternalAuthDelegateServicesController.java +++ b/registration-processor/init/registration-processor-registration-status-service/src/main/java/io/mosip/registration/processor/status/api/controller/InternalAuthDelegateServicesController.java @@ -17,9 +17,14 @@ import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; +import io.mosip.kernel.core.exception.IOException; import io.mosip.kernel.core.http.ResponseFilter; import io.mosip.registration.processor.core.auth.dto.AuthRequestDTO; import io.mosip.registration.processor.core.auth.dto.AuthResponseDTO; +import io.mosip.registration.processor.core.exception.ApisResourceAccessException; +import io.mosip.registration.processor.core.exception.util.PlatformErrorMessages; +import io.mosip.registration.processor.core.token.validation.exception.InvalidTokenException; +import io.mosip.registration.processor.status.exception.InternalAuthDeligateAppException; import io.mosip.registration.processor.status.service.InternalAuthDelegateService; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; @@ -62,8 +67,19 @@ public class InternalAuthDelegateServicesController { @ApiResponse(responseCode = "404", description = "Not Found" ,content = @Content(schema = @Schema(hidden = true)))}) public ResponseEntity authenticate(@Validated @RequestBody AuthRequestDTO authRequestDTO, @RequestHeader HttpHeaders headers) throws Exception { - return ResponseEntity.status(HttpStatus.OK) - .body(internalAuthDelegateService.authenticate(authRequestDTO, headers)); + try { + return ResponseEntity.status(HttpStatus.OK) + .body(internalAuthDelegateService.authenticate(authRequestDTO, headers)); + }catch (Exception e) { + if( e instanceof InvalidTokenException |e instanceof ApisResourceAccessException|e instanceof IOException ) { + throw e; + } + else { + throw new InternalAuthDeligateAppException(PlatformErrorMessages.RPR_RTS_UNKNOWN_EXCEPTION.getCode(), + PlatformErrorMessages.RPR_RTS_UNKNOWN_EXCEPTION.getMessage()+" -->"+e.getMessage()); + } + } + } /** diff --git a/registration-processor/init/registration-processor-registration-status-service/src/main/java/io/mosip/registration/processor/status/api/controller/PacketExternalStatusController.java b/registration-processor/init/registration-processor-registration-status-service/src/main/java/io/mosip/registration/processor/status/api/controller/PacketExternalStatusController.java index 445e0761e99..f2e75d4b2e8 100644 --- a/registration-processor/init/registration-processor-registration-status-service/src/main/java/io/mosip/registration/processor/status/api/controller/PacketExternalStatusController.java +++ b/registration-processor/init/registration-processor-registration-status-service/src/main/java/io/mosip/registration/processor/status/api/controller/PacketExternalStatusController.java @@ -1,10 +1,12 @@ package io.mosip.registration.processor.status.api.controller; +import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.cloud.context.config.annotation.RefreshScope; @@ -18,8 +20,7 @@ import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; +import com.fasterxml.jackson.databind.ObjectMapper; import io.mosip.kernel.core.util.DateUtils; import io.mosip.registration.processor.core.exception.util.PlatformErrorMessages; @@ -40,6 +41,8 @@ import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.tags.Tag; +import io.mosip.registration.processor.core.logger.RegProcessorLogger; +import io.mosip.kernel.core.logger.spi.Logger; /** @@ -66,6 +69,9 @@ public class PacketExternalStatusController { /** The digital signature utility. */ @Autowired private DigitalSignatureUtility digitalSignatureUtility; + + @Autowired + ObjectMapper objectMapper; /** The is enabled. */ @Value("${registration.processor.signature.isEnabled}") @@ -81,6 +87,7 @@ public class PacketExternalStatusController { private static final String PACKET_EXTERNAL_STATUS_APPLICATION_VERSION = "mosip.registration.processor.packet.external.status.version"; + private final Logger logger = RegProcessorLogger.getLogger(this.getClass()); /** * Packet external status. * @@ -119,12 +126,20 @@ public ResponseEntity packetExternalStatus( if (isEnabled) { PacketExternalStatusResponseDTO packetExternalStatusResponseDTO = buildPacketStatusResponse( packetExternalStatusDTOList, packetExternalStatusRequestDTO.getRequest()); - Gson gson = new GsonBuilder().serializeNulls().create(); + HttpHeaders headers = new HttpHeaders(); + String res=null; + try { + + res=objectMapper.writeValueAsString(packetExternalStatusResponseDTO); + } catch (Exception e1) { + logger.error("Error while processing dto ",e1); + + } headers.add(RESPONSE_SIGNATURE, - digitalSignatureUtility.getDigitalSignature(gson.toJson(packetExternalStatusResponseDTO))); + digitalSignatureUtility.getDigitalSignature(res)); return ResponseEntity.status(HttpStatus.OK).headers(headers) - .body(gson.toJson(packetExternalStatusResponseDTO)); + .body(res); } return ResponseEntity.status(HttpStatus.OK) .body(buildPacketStatusResponse(packetExternalStatusDTOList, packetExternalStatusRequestDTO.getRequest())); diff --git a/registration-processor/init/registration-processor-registration-status-service/src/main/java/io/mosip/registration/processor/status/api/controller/RegistrationExternalStatusController.java b/registration-processor/init/registration-processor-registration-status-service/src/main/java/io/mosip/registration/processor/status/api/controller/RegistrationExternalStatusController.java index 38f8bd887e4..b7bd8e2932c 100644 --- a/registration-processor/init/registration-processor-registration-status-service/src/main/java/io/mosip/registration/processor/status/api/controller/RegistrationExternalStatusController.java +++ b/registration-processor/init/registration-processor-registration-status-service/src/main/java/io/mosip/registration/processor/status/api/controller/RegistrationExternalStatusController.java @@ -1,175 +1,178 @@ -package io.mosip.registration.processor.status.api.controller; - -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; -import java.util.stream.Collectors; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.cloud.context.config.annotation.RefreshScope; -import org.springframework.core.env.Environment; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RestController; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; - -import io.mosip.kernel.core.util.DateUtils; -import io.mosip.registration.processor.core.exception.util.PlatformErrorMessages; -import io.mosip.registration.processor.core.util.DigitalSignatureUtility; -import io.mosip.registration.processor.status.code.RegistrationExternalStatusCode; -import io.mosip.registration.processor.status.dto.ErrorDTO; -import io.mosip.registration.processor.status.dto.InternalRegistrationStatusDto; -import io.mosip.registration.processor.status.dto.RegistrationExternalStatusRequestDTO; -import io.mosip.registration.processor.status.dto.RegistrationExternalStatusSubRequestDto; -import io.mosip.registration.processor.status.dto.RegistrationStatusDto; -import io.mosip.registration.processor.status.dto.RegistrationStatusErrorDto; -import io.mosip.registration.processor.status.dto.SyncRegistrationDto; -import io.mosip.registration.processor.status.dto.SyncResponseDto; -import io.mosip.registration.processor.status.exception.RegStatusAppException; -import io.mosip.registration.processor.status.service.RegistrationStatusService; -import io.mosip.registration.processor.status.service.SyncRegistrationService; -import io.mosip.registration.processor.status.sync.response.dto.RegExternalStatusResponseDTO; -import io.mosip.registration.processor.status.validator.RegistrationExternalStatusRequestValidator; - -import io.swagger.v3.oas.annotations.Operation; -import io.swagger.v3.oas.annotations.media.Content; -import io.swagger.v3.oas.annotations.media.Schema; -import io.swagger.v3.oas.annotations.responses.ApiResponse; -import io.swagger.v3.oas.annotations.responses.ApiResponses; -import io.swagger.v3.oas.annotations.tags.Tag; - -@RefreshScope -@RestController -@Tag(name = "External Registration Status", description = "Registration External Status Controller") -public class RegistrationExternalStatusController { - - /** The registration status service. */ - @Autowired - RegistrationStatusService registrationStatusService; - - /** The sync registration service. */ - @Autowired - SyncRegistrationService syncRegistrationService; - - @Autowired - RegistrationExternalStatusRequestValidator registrationExternalStatusRequestValidator; - - @Autowired - private DigitalSignatureUtility digitalSignatureUtility; - - @Autowired - private Environment env; - - @Value("${registration.processor.signature.isEnabled}") - private Boolean isEnabled; - - private static final String REG_EXTERNAL_STATUS_SERVICE_ID = "mosip.registration.processor.registration.external.status.id"; - private static final String RESPONSE_SIGNATURE = "Response-Signature"; - private static final String DATETIME_PATTERN = "mosip.registration.processor.datetime.pattern"; - private static final String REG_EXTERNAL_STATUS_APPLICATION_VERSION = "mosip.registration.processor.registration.external.status.version"; - - /** - * Search. - * - * @param registrationIds the registration ids - * @return the response entity - * @throws RegStatusAppException - */ - //@PreAuthorize("hasAnyRole('REGISTRATION_ADMIN', 'REGISTRATION_OFFICER', 'REGISTRATION_SUPERVISOR','RESIDENT')") - @PreAuthorize("hasAnyRole(@authorizedRoles.getPostexternalstatussearch())") - @PostMapping(path = "/externalstatus/search", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) - @Operation(summary = "Get the registration external status", description = "Get the registration external status", tags = { "External Registration Status" }) - @ApiResponses(value = { - @ApiResponse(responseCode = "200", description = "Registration external status successfully fetched", - content = @Content(schema = @Schema(implementation = RegistrationExternalStatusCode.class))), - @ApiResponse(responseCode = "201", description = "Created" ,content = @Content(schema = @Schema(hidden = true))), - @ApiResponse(responseCode = "400", description = "Unable to fetch the registration external status" ,content = @Content(schema = @Schema(hidden = true))), - @ApiResponse(responseCode = "401", description = "Unauthorized" ,content = @Content(schema = @Schema(hidden = true))), - @ApiResponse(responseCode = "403", description = "Forbidden" ,content = @Content(schema = @Schema(hidden = true))), - @ApiResponse(responseCode = "404", description = "Not Found" ,content = @Content(schema = @Schema(hidden = true)))}) - - public ResponseEntity search( - @RequestBody(required = true) RegistrationExternalStatusRequestDTO registrationExternalStatusRequestDTO) - throws RegStatusAppException { - - try { - registrationExternalStatusRequestValidator.validate(registrationExternalStatusRequestDTO, - env.getProperty(REG_EXTERNAL_STATUS_SERVICE_ID)); - - List registrationIds = registrationExternalStatusRequestDTO.getRequest().stream() - .map(RegistrationExternalStatusSubRequestDto::getRegistrationId).collect(Collectors.toList()); - - List registrations = registrationStatusService - .getExternalStatusByIds(registrationIds); - - List requestIdsNotAvailable = registrationExternalStatusRequestDTO - .getRequest().stream() - .filter(request -> registrations.stream().noneMatch( - registration -> registration.getRegistrationId().equals(request.getRegistrationId()))) - .collect(Collectors.toList()); - - List registrationIdsNotAvailable = requestIdsNotAvailable.stream() - .map(RegistrationExternalStatusSubRequestDto::getRegistrationId).collect(Collectors.toList()); - List registrationsList = syncRegistrationService - .getExternalStatusByIds(registrationIdsNotAvailable); - - if (registrationsList != null && !registrationsList.isEmpty()) { - registrations.addAll(registrationsList); - } - - if (isEnabled) { - RegExternalStatusResponseDTO response = buildRegistrationStatusResponse(registrations, - registrationExternalStatusRequestDTO.getRequest()); - Gson gson = new GsonBuilder().serializeNulls().create(); - HttpHeaders headers = new HttpHeaders(); - headers.add(RESPONSE_SIGNATURE, digitalSignatureUtility.getDigitalSignature(gson.toJson(response))); - return ResponseEntity.status(HttpStatus.OK).headers(headers).body(gson.toJson(response)); - } - return ResponseEntity.status(HttpStatus.OK) - .body(buildRegistrationStatusResponse(registrations, registrationExternalStatusRequestDTO.getRequest())); - } catch (RegStatusAppException e) { - throw new RegStatusAppException(PlatformErrorMessages.RPR_RGS_DATA_VALIDATION_FAILED, e); - } catch (Exception e) { - throw new RegStatusAppException(PlatformErrorMessages.RPR_RGS_UNKNOWN_EXCEPTION, e); - } - } - - public RegExternalStatusResponseDTO buildRegistrationStatusResponse(List registrations, - List requestIds) { - - RegExternalStatusResponseDTO response = new RegExternalStatusResponseDTO(); - if (Objects.isNull(response.getId())) { - response.setId(env.getProperty(REG_EXTERNAL_STATUS_SERVICE_ID)); - } - response.setResponsetime(DateUtils.getUTCCurrentDateTimeString(env.getProperty(DATETIME_PATTERN))); - response.setVersion(env.getProperty(REG_EXTERNAL_STATUS_APPLICATION_VERSION)); - response.setResponse(registrations); - List requestIdsNotAvailable = requestIds.stream() - .filter(request -> registrations.stream().noneMatch( - registration -> registration.getRegistrationId().equals(request.getRegistrationId()))) - .collect(Collectors.toList()); - List errors = new ArrayList(); - if (!requestIdsNotAvailable.isEmpty()) { - - for (RegistrationExternalStatusSubRequestDto requestDto : requestIdsNotAvailable) { - RegistrationStatusErrorDto errorDto = new RegistrationStatusErrorDto( - PlatformErrorMessages.RPR_RGS_RID_NOT_FOUND.getCode(), - PlatformErrorMessages.RPR_RGS_RID_NOT_FOUND.getMessage()); - - errorDto.setRegistrationId(requestDto.getRegistrationId()); - errors.add(errorDto); - } - } - response.setErrors(errors); - return response; - } - -} +package io.mosip.registration.processor.status.api.controller; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.stream.Collectors; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.cloud.context.config.annotation.RefreshScope; +import org.springframework.core.env.Environment; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RestController; + +import com.fasterxml.jackson.databind.ObjectMapper; + +import io.mosip.kernel.core.util.DateUtils; +import io.mosip.registration.processor.core.exception.util.PlatformErrorMessages; +import io.mosip.registration.processor.core.util.DigitalSignatureUtility; +import io.mosip.registration.processor.status.code.RegistrationExternalStatusCode; +import io.mosip.registration.processor.status.dto.ErrorDTO; +import io.mosip.registration.processor.status.dto.InternalRegistrationStatusDto; +import io.mosip.registration.processor.status.dto.RegistrationExternalStatusRequestDTO; +import io.mosip.registration.processor.status.dto.RegistrationExternalStatusSubRequestDto; +import io.mosip.registration.processor.status.dto.RegistrationStatusDto; +import io.mosip.registration.processor.status.dto.RegistrationStatusErrorDto; +import io.mosip.registration.processor.status.dto.SyncRegistrationDto; +import io.mosip.registration.processor.status.dto.SyncResponseDto; +import io.mosip.registration.processor.status.exception.RegStatusAppException; +import io.mosip.registration.processor.status.service.RegistrationStatusService; +import io.mosip.registration.processor.status.service.SyncRegistrationService; +import io.mosip.registration.processor.status.sync.response.dto.RegExternalStatusResponseDTO; +import io.mosip.registration.processor.status.validator.RegistrationExternalStatusRequestValidator; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import io.swagger.v3.oas.annotations.responses.ApiResponses; +import io.swagger.v3.oas.annotations.tags.Tag; + +@RefreshScope +@RestController +@Tag(name = "External Registration Status", description = "Registration External Status Controller") +public class RegistrationExternalStatusController { + + /** The registration status service. */ + @Autowired + RegistrationStatusService registrationStatusService; + + /** The sync registration service. */ + @Autowired + SyncRegistrationService syncRegistrationService; + + @Autowired + RegistrationExternalStatusRequestValidator registrationExternalStatusRequestValidator; + + @Autowired + private DigitalSignatureUtility digitalSignatureUtility; + + @Autowired + private Environment env; + + @Value("${registration.processor.signature.isEnabled}") + private Boolean isEnabled; + + @Autowired + ObjectMapper objMp; + + private static final String REG_EXTERNAL_STATUS_SERVICE_ID = "mosip.registration.processor.registration.external.status.id"; + private static final String RESPONSE_SIGNATURE = "Response-Signature"; + private static final String DATETIME_PATTERN = "mosip.registration.processor.datetime.pattern"; + private static final String REG_EXTERNAL_STATUS_APPLICATION_VERSION = "mosip.registration.processor.registration.external.status.version"; + + /** + * Search. + * + * @param registrationIds the registration ids + * @return the response entity + * @throws RegStatusAppException + */ + //@PreAuthorize("hasAnyRole('REGISTRATION_ADMIN', 'REGISTRATION_OFFICER', 'REGISTRATION_SUPERVISOR','RESIDENT')") + @PreAuthorize("hasAnyRole(@authorizedRoles.getPostexternalstatussearch())") + @PostMapping(path = "/externalstatus/search", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) + @Operation(summary = "Get the registration external status", description = "Get the registration external status", tags = { "External Registration Status" }) + @ApiResponses(value = { + @ApiResponse(responseCode = "200", description = "Registration external status successfully fetched", + content = @Content(schema = @Schema(implementation = RegistrationExternalStatusCode.class))), + @ApiResponse(responseCode = "201", description = "Created" ,content = @Content(schema = @Schema(hidden = true))), + @ApiResponse(responseCode = "400", description = "Unable to fetch the registration external status" ,content = @Content(schema = @Schema(hidden = true))), + @ApiResponse(responseCode = "401", description = "Unauthorized" ,content = @Content(schema = @Schema(hidden = true))), + @ApiResponse(responseCode = "403", description = "Forbidden" ,content = @Content(schema = @Schema(hidden = true))), + @ApiResponse(responseCode = "404", description = "Not Found" ,content = @Content(schema = @Schema(hidden = true)))}) + + public ResponseEntity search( + @RequestBody(required = true) RegistrationExternalStatusRequestDTO registrationExternalStatusRequestDTO) + throws RegStatusAppException { + + try { + registrationExternalStatusRequestValidator.validate(registrationExternalStatusRequestDTO, + env.getProperty(REG_EXTERNAL_STATUS_SERVICE_ID)); + + List registrationIds = registrationExternalStatusRequestDTO.getRequest().stream() + .map(RegistrationExternalStatusSubRequestDto::getRegistrationId).collect(Collectors.toList()); + + List registrations = registrationStatusService + .getExternalStatusByIds(registrationIds); + + List requestIdsNotAvailable = registrationExternalStatusRequestDTO + .getRequest().stream() + .filter(request -> registrations.stream().noneMatch( + registration -> registration.getRegistrationId().equals(request.getRegistrationId()))) + .collect(Collectors.toList()); + + List registrationIdsNotAvailable = requestIdsNotAvailable.stream() + .map(RegistrationExternalStatusSubRequestDto::getRegistrationId).collect(Collectors.toList()); + List registrationsList = syncRegistrationService + .getExternalStatusByIds(registrationIdsNotAvailable); + + if (registrationsList != null && !registrationsList.isEmpty()) { + registrations.addAll(registrationsList); + } + + if (isEnabled) { + RegExternalStatusResponseDTO response = buildRegistrationStatusResponse(registrations, + registrationExternalStatusRequestDTO.getRequest()); + + HttpHeaders headers = new HttpHeaders(); + String res=null; + res=objMp.writeValueAsString(response); + headers.add(RESPONSE_SIGNATURE, digitalSignatureUtility.getDigitalSignature(res)); + return ResponseEntity.status(HttpStatus.OK).headers(headers).body(res); + } + return ResponseEntity.status(HttpStatus.OK) + .body(buildRegistrationStatusResponse(registrations, registrationExternalStatusRequestDTO.getRequest())); + } catch (RegStatusAppException e) { + throw new RegStatusAppException(PlatformErrorMessages.RPR_RGS_DATA_VALIDATION_FAILED, e); + } catch (Exception e) { + throw new RegStatusAppException(PlatformErrorMessages.RPR_RGS_UNKNOWN_EXCEPTION, e); + } + } + + public RegExternalStatusResponseDTO buildRegistrationStatusResponse(List registrations, + List requestIds) { + + RegExternalStatusResponseDTO response = new RegExternalStatusResponseDTO(); + if (Objects.isNull(response.getId())) { + response.setId(env.getProperty(REG_EXTERNAL_STATUS_SERVICE_ID)); + } + response.setResponsetime(DateUtils.getUTCCurrentDateTimeString(env.getProperty(DATETIME_PATTERN))); + response.setVersion(env.getProperty(REG_EXTERNAL_STATUS_APPLICATION_VERSION)); + response.setResponse(registrations); + List requestIdsNotAvailable = requestIds.stream() + .filter(request -> registrations.stream().noneMatch( + registration -> registration.getRegistrationId().equals(request.getRegistrationId()))) + .collect(Collectors.toList()); + List errors = new ArrayList(); + if (!requestIdsNotAvailable.isEmpty()) { + + for (RegistrationExternalStatusSubRequestDto requestDto : requestIdsNotAvailable) { + RegistrationStatusErrorDto errorDto = new RegistrationStatusErrorDto( + PlatformErrorMessages.RPR_RGS_RID_NOT_FOUND.getCode(), + PlatformErrorMessages.RPR_RGS_RID_NOT_FOUND.getMessage()); + + errorDto.setRegistrationId(requestDto.getRegistrationId()); + errors.add(errorDto); + } + } + response.setErrors(errors); + return response; + } + +} diff --git a/registration-processor/init/registration-processor-registration-status-service/src/main/java/io/mosip/registration/processor/status/api/controller/RegistrationStatusController.java b/registration-processor/init/registration-processor-registration-status-service/src/main/java/io/mosip/registration/processor/status/api/controller/RegistrationStatusController.java index 09ea8300e8f..6fc5d203de4 100644 --- a/registration-processor/init/registration-processor-registration-status-service/src/main/java/io/mosip/registration/processor/status/api/controller/RegistrationStatusController.java +++ b/registration-processor/init/registration-processor-registration-status-service/src/main/java/io/mosip/registration/processor/status/api/controller/RegistrationStatusController.java @@ -1,261 +1,261 @@ -package io.mosip.registration.processor.status.api.controller; - -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; -import java.util.stream.Collectors; - -import org.apache.commons.collections.CollectionUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.cloud.context.config.annotation.RefreshScope; -import org.springframework.core.env.Environment; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RestController; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; - -import io.mosip.kernel.core.util.DateUtils; -import io.mosip.registration.processor.core.exception.util.PlatformErrorMessages; -import io.mosip.registration.processor.core.util.DigitalSignatureUtility; -import io.mosip.registration.processor.status.code.RegistrationExternalStatusCode; -import io.mosip.registration.processor.status.dto.ErrorDTO; -import io.mosip.registration.processor.status.dto.InternalRegistrationStatusDto; -import io.mosip.registration.processor.status.dto.LostRidDto; -import io.mosip.registration.processor.status.dto.LostRidRequestDto; -import io.mosip.registration.processor.status.dto.LostRidResponseDto; -import io.mosip.registration.processor.status.dto.RegistrationStatusDto; -import io.mosip.registration.processor.status.dto.RegistrationStatusErrorDto; -import io.mosip.registration.processor.status.dto.RegistrationStatusRequestDTO; -import io.mosip.registration.processor.status.dto.RegistrationStatusSubRequestDto; -import io.mosip.registration.processor.status.dto.SyncRegistrationDto; -import io.mosip.registration.processor.status.dto.SyncResponseDto; -import io.mosip.registration.processor.status.exception.RegStatusAppException; -import io.mosip.registration.processor.status.service.RegistrationStatusService; -import io.mosip.registration.processor.status.service.SyncRegistrationService; -import io.mosip.registration.processor.status.sync.response.dto.RegStatusResponseDTO; -import io.mosip.registration.processor.status.validator.LostRidRequestValidator; -import io.mosip.registration.processor.status.validator.RegistrationStatusRequestValidator; - -import io.swagger.v3.oas.annotations.Operation; -import io.swagger.v3.oas.annotations.media.Content; -import io.swagger.v3.oas.annotations.media.Schema; -import io.swagger.v3.oas.annotations.responses.ApiResponse; -import io.swagger.v3.oas.annotations.responses.ApiResponses; -import io.swagger.v3.oas.annotations.tags.Tag; - -/** - * The Class RegistrationStatusController. - */ -@RefreshScope -@RestController -@Tag(name = "Registration Status", description = "Registration Status Controller") -public class RegistrationStatusController { - - /** The registration status service. */ - @Autowired - RegistrationStatusService registrationStatusService; - - /** The sync registration service. */ - @Autowired - SyncRegistrationService syncRegistrationService; - - /** The validator. */ - @Autowired - RegistrationStatusRequestValidator registrationStatusRequestValidator; - - @Autowired - LostRidRequestValidator lostRidRequestValidator; - - private static final String REG_STATUS_SERVICE_ID = "mosip.registration.processor.registration.status.id"; - private static final String REG_LOSTRID_SERVICE_ID = "mosip.registration.processor.lostrid.id"; - private static final String REG_STATUS_APPLICATION_VERSION = "mosip.registration.processor.registration.status.version"; - private static final String REG_LOSTRID_APPLICATION_VERSION = "mosip.registration.processor.lostrid.version"; - private static final String DATETIME_PATTERN = "mosip.registration.processor.datetime.pattern"; - private static final String RESPONSE_SIGNATURE = "Response-Signature"; - - @Autowired - private Environment env; - - @Value("${registration.processor.signature.isEnabled}") - private Boolean isEnabled; - - /** - * The comma separate list of external statuses that should be considered as processed - * for search API response consumed by regclient - */ - @Value("#{'${mosip.registration.processor.registration.status.external-statuses-to-consider-processed:UIN_GENERATED,REREGISTER,REJECTED,REPROCESS_FAILED}'.split(',')}") - private List externalStatusesConsideredProcessed; - - @Value("${registration.processor.fetch.registration.records.limit:100}") - private int maxLimit; - - @Autowired - private DigitalSignatureUtility digitalSignatureUtility; - - /** - * Search. - * - * @param registrationStatusRequestDTO the registration ids - * @return the response entity - * @throws RegStatusAppException - */ - //@PreAuthorize("hasAnyRole('REGISTRATION_ADMIN', 'REGISTRATION_OFFICER', 'REGISTRATION_SUPERVISOR','RESIDENT')") - @PreAuthorize("hasAnyRole(@authorizedRoles.getPostsearch())") - @PostMapping(path = "/search", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) - @Operation(summary = "Get the registration entity", description = "Get the registration entity", tags = { "Registration Status" }) - @ApiResponses(value = { - @ApiResponse(responseCode = "200", description = "Registration Entity successfully fetched", - content = @Content(schema = @Schema(implementation = RegistrationExternalStatusCode.class))), - @ApiResponse(responseCode = "201", description = "Created" ,content = @Content(schema = @Schema(hidden = true))), - @ApiResponse(responseCode = "400", description = "Unable to fetch the Registration Entity" ,content = @Content(schema = @Schema(hidden = true))), - @ApiResponse(responseCode = "401", description = "Unauthorized" ,content = @Content(schema = @Schema(hidden = true))), - @ApiResponse(responseCode = "403", description = "Forbidden" ,content = @Content(schema = @Schema(hidden = true))), - @ApiResponse(responseCode = "404", description = "Not Found" ,content = @Content(schema = @Schema(hidden = true)))}) - public ResponseEntity search( - @RequestBody(required = true) RegistrationStatusRequestDTO registrationStatusRequestDTO) - throws RegStatusAppException { - - try { - registrationStatusRequestValidator.validate(registrationStatusRequestDTO, - env.getProperty(REG_STATUS_SERVICE_ID)); - - // if number of rids in request exceeds max limit then get status for first 100 ids. - List recordsToFetch = CollectionUtils.isNotEmpty(registrationStatusRequestDTO.getRequest()) - && registrationStatusRequestDTO.getRequest().size() > maxLimit ? - registrationStatusRequestDTO.getRequest().stream().limit(maxLimit).collect(Collectors.toList()) : registrationStatusRequestDTO.getRequest(); - - List registrations = registrationStatusService - .getByIds(recordsToFetch); - List requestIdsNotAvailable = recordsToFetch - .stream() - .filter(request -> registrations.stream().noneMatch( - registration -> registration.getRegistrationId().equals(request.getRegistrationId()))) - .collect(Collectors.toList()); - - if (CollectionUtils.isNotEmpty(requestIdsNotAvailable)) { - List registrationsList = syncRegistrationService.getByIds(requestIdsNotAvailable); - if (registrationsList != null && !registrationsList.isEmpty()) { - registrations.addAll(syncRegistrationService.getByIds(requestIdsNotAvailable)); - } - } - - updatedConditionalStatusToProcessed(registrations); - - if (isEnabled) { - Gson gson = new GsonBuilder().serializeNulls().create(); - String response = gson.toJson(buildRegistrationStatusResponse(registrations, - recordsToFetch)); - HttpHeaders headers = new HttpHeaders(); - headers.add(RESPONSE_SIGNATURE, digitalSignatureUtility.getDigitalSignature(response)); - return ResponseEntity.status(HttpStatus.OK).headers(headers).body(response); - } - return ResponseEntity.status(HttpStatus.OK) - .body(buildRegistrationStatusResponse(registrations, recordsToFetch)); - } catch (RegStatusAppException e) { - throw new RegStatusAppException(PlatformErrorMessages.RPR_RGS_DATA_VALIDATION_FAILED, e); - } catch (Exception e) { - throw new RegStatusAppException(PlatformErrorMessages.RPR_RGS_UNKNOWN_EXCEPTION, e); - } - } - - /** - * Search - * - * @param lostRidRequestDto - * @return - * @throws RegStatusAppException - */ - //@PreAuthorize("hasAnyRole('REGISTRATION_ADMIN', 'REGISTRATION_OFFICER', 'ZONAL_ADMIN','GLOBAL_ADMIN')") - @PreAuthorize("hasAnyRole(@authorizedRoles.getPostlostridsearch())") - @PostMapping(path = "/lostridsearch", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) - @Operation(summary = "Get the lost registration id", description = "Get the lost registration id", tags = { "Registration Status" }) - @ApiResponses(value = { - @ApiResponse(responseCode = "200", description = "Registration id successfully fetched", - content = @Content(schema = @Schema(implementation = RegistrationExternalStatusCode.class))), - @ApiResponse(responseCode = "201", description = "Created" ,content = @Content(schema = @Schema(hidden = true))), - @ApiResponse(responseCode = "400", description = "Unable to fetch the Registration Entity" ,content = @Content(schema = @Schema(hidden = true))), - @ApiResponse(responseCode = "401", description = "Unauthorized" ,content = @Content(schema = @Schema(hidden = true))), - @ApiResponse(responseCode = "403", description = "Forbidden" ,content = @Content(schema = @Schema(hidden = true))), - @ApiResponse(responseCode = "404", description = "Not Found" ,content = @Content(schema = @Schema(hidden = true)))}) - public ResponseEntity searchLostRid( - @RequestBody(required = true) LostRidRequestDto lostRidRequestDto) - throws RegStatusAppException { - - try { - lostRidRequestValidator.validate(lostRidRequestDto); - List lostRidDtos = syncRegistrationService.searchLostRid(lostRidRequestDto.getRequest()); - return ResponseEntity.status(HttpStatus.OK) - .body(buildLostRidResponse(lostRidDtos)); - } catch (RegStatusAppException e) { - throw new RegStatusAppException(PlatformErrorMessages.RPR_RGS_DATA_VALIDATION_FAILED, e); - } catch (Exception e) { - throw new RegStatusAppException(PlatformErrorMessages.RPR_RGS_INVALID_SEARCH, e); - } - } - - public RegStatusResponseDTO buildRegistrationStatusResponse(List registrations, - List requestIds) { - - RegStatusResponseDTO response = new RegStatusResponseDTO(); - if (Objects.isNull(response.getId())) { - response.setId(env.getProperty(REG_STATUS_SERVICE_ID)); - } - response.setResponsetime(DateUtils.getUTCCurrentDateTimeString(env.getProperty(DATETIME_PATTERN))); - response.setVersion(env.getProperty(REG_STATUS_APPLICATION_VERSION)); - response.setResponse(registrations); - List requestIdsNotAvailable = requestIds.stream() - .filter(request -> registrations.stream().noneMatch( - registration -> registration.getRegistrationId().equals(request.getRegistrationId()))) - .collect(Collectors.toList()); - List errors = new ArrayList(); - if (!requestIdsNotAvailable.isEmpty()) { - - for (RegistrationStatusSubRequestDto requestDto : requestIdsNotAvailable) { - RegistrationStatusErrorDto errorDto = new RegistrationStatusErrorDto( - PlatformErrorMessages.RPR_RGS_RID_NOT_FOUND.getCode(), - PlatformErrorMessages.RPR_RGS_RID_NOT_FOUND.getMessage()); - - errorDto.setRegistrationId(requestDto.getRegistrationId()); - errors.add(errorDto); - } - } - response.setErrors(errors); - return response; - } - - private void updatedConditionalStatusToProcessed(List registrations) { - for(RegistrationStatusDto registrationStatusDto : registrations) { - if(externalStatusesConsideredProcessed.contains(registrationStatusDto.getStatusCode())) - registrationStatusDto.setStatusCode(RegistrationExternalStatusCode.PROCESSED.toString()); - } - } - - public LostRidResponseDto buildLostRidResponse(List lostRidDtos) { - - LostRidResponseDto response = new LostRidResponseDto(); - if (Objects.isNull(response.getId())) { - response.setId(env.getProperty(REG_LOSTRID_SERVICE_ID)); - } - response.setResponsetime(DateUtils.getUTCCurrentDateTimeString(env.getProperty(DATETIME_PATTERN))); - response.setVersion(env.getProperty(REG_LOSTRID_APPLICATION_VERSION)); - response.setResponse(lostRidDtos); - List errors = new ArrayList(); - if (lostRidDtos.isEmpty()) { - RegistrationStatusErrorDto errorDto = new RegistrationStatusErrorDto( - PlatformErrorMessages.RPR_RGS_RID_NOT_FOUND.getCode(), - PlatformErrorMessages.RPR_RGS_RID_NOT_FOUND.getMessage()); - errors.add(errorDto); - } - response.setErrors(errors); - return response; - } - -} +package io.mosip.registration.processor.status.api.controller; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.stream.Collectors; + +import org.apache.commons.collections.CollectionUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.cloud.context.config.annotation.RefreshScope; +import org.springframework.core.env.Environment; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RestController; + +import com.fasterxml.jackson.databind.ObjectMapper; + +import io.mosip.kernel.core.util.DateUtils; +import io.mosip.registration.processor.core.exception.util.PlatformErrorMessages; +import io.mosip.registration.processor.core.util.DigitalSignatureUtility; +import io.mosip.registration.processor.status.code.RegistrationExternalStatusCode; +import io.mosip.registration.processor.status.dto.ErrorDTO; +import io.mosip.registration.processor.status.dto.InternalRegistrationStatusDto; +import io.mosip.registration.processor.status.dto.LostRidDto; +import io.mosip.registration.processor.status.dto.LostRidRequestDto; +import io.mosip.registration.processor.status.dto.LostRidResponseDto; +import io.mosip.registration.processor.status.dto.RegistrationStatusDto; +import io.mosip.registration.processor.status.dto.RegistrationStatusErrorDto; +import io.mosip.registration.processor.status.dto.RegistrationStatusRequestDTO; +import io.mosip.registration.processor.status.dto.RegistrationStatusSubRequestDto; +import io.mosip.registration.processor.status.dto.SyncRegistrationDto; +import io.mosip.registration.processor.status.dto.SyncResponseDto; +import io.mosip.registration.processor.status.exception.RegStatusAppException; +import io.mosip.registration.processor.status.service.RegistrationStatusService; +import io.mosip.registration.processor.status.service.SyncRegistrationService; +import io.mosip.registration.processor.status.sync.response.dto.RegStatusResponseDTO; +import io.mosip.registration.processor.status.validator.LostRidRequestValidator; +import io.mosip.registration.processor.status.validator.RegistrationStatusRequestValidator; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import io.swagger.v3.oas.annotations.responses.ApiResponses; +import io.swagger.v3.oas.annotations.tags.Tag; + +/** + * The Class RegistrationStatusController. + */ +@RefreshScope +@RestController +@Tag(name = "Registration Status", description = "Registration Status Controller") +public class RegistrationStatusController { + + /** The registration status service. */ + @Autowired + RegistrationStatusService registrationStatusService; + + /** The sync registration service. */ + @Autowired + SyncRegistrationService syncRegistrationService; + + /** The validator. */ + @Autowired + RegistrationStatusRequestValidator registrationStatusRequestValidator; + + @Autowired + LostRidRequestValidator lostRidRequestValidator; + + private static final String REG_STATUS_SERVICE_ID = "mosip.registration.processor.registration.status.id"; + private static final String REG_LOSTRID_SERVICE_ID = "mosip.registration.processor.lostrid.id"; + private static final String REG_STATUS_APPLICATION_VERSION = "mosip.registration.processor.registration.status.version"; + private static final String REG_LOSTRID_APPLICATION_VERSION = "mosip.registration.processor.lostrid.version"; + private static final String DATETIME_PATTERN = "mosip.registration.processor.datetime.pattern"; + private static final String RESPONSE_SIGNATURE = "Response-Signature"; + + @Autowired + private Environment env; + + @Value("${registration.processor.signature.isEnabled}") + private Boolean isEnabled; + + @Autowired + ObjectMapper objMp; + + /** + * The comma separate list of external statuses that should be considered as processed + * for search API response consumed by regclient + */ + @Value("#{'${mosip.registration.processor.registration.status.external-statuses-to-consider-processed:UIN_GENERATED,REREGISTER,REJECTED,REPROCESS_FAILED}'.split(',')}") + private List externalStatusesConsideredProcessed; + + @Value("${registration.processor.fetch.registration.records.limit:100}") + private int maxLimit; + + @Autowired + private DigitalSignatureUtility digitalSignatureUtility; + + /** + * Search. + * + * @param registrationStatusRequestDTO the registration ids + * @return the response entity + * @throws RegStatusAppException + */ + //@PreAuthorize("hasAnyRole('REGISTRATION_ADMIN', 'REGISTRATION_OFFICER', 'REGISTRATION_SUPERVISOR','RESIDENT')") + @PreAuthorize("hasAnyRole(@authorizedRoles.getPostsearch())") + @PostMapping(path = "/search", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) + @Operation(summary = "Get the registration entity", description = "Get the registration entity", tags = { "Registration Status" }) + @ApiResponses(value = { + @ApiResponse(responseCode = "200", description = "Registration Entity successfully fetched", + content = @Content(schema = @Schema(implementation = RegistrationExternalStatusCode.class))), + @ApiResponse(responseCode = "201", description = "Created" ,content = @Content(schema = @Schema(hidden = true))), + @ApiResponse(responseCode = "400", description = "Unable to fetch the Registration Entity" ,content = @Content(schema = @Schema(hidden = true))), + @ApiResponse(responseCode = "401", description = "Unauthorized" ,content = @Content(schema = @Schema(hidden = true))), + @ApiResponse(responseCode = "403", description = "Forbidden" ,content = @Content(schema = @Schema(hidden = true))), + @ApiResponse(responseCode = "404", description = "Not Found" ,content = @Content(schema = @Schema(hidden = true)))}) + public ResponseEntity search( + @RequestBody(required = true) RegistrationStatusRequestDTO registrationStatusRequestDTO) + throws RegStatusAppException { + + try { + registrationStatusRequestValidator.validate(registrationStatusRequestDTO, + env.getProperty(REG_STATUS_SERVICE_ID)); + + // if number of rids in request exceeds max limit then get status for first 100 ids. + List recordsToFetch = CollectionUtils.isNotEmpty(registrationStatusRequestDTO.getRequest()) + && registrationStatusRequestDTO.getRequest().size() > maxLimit ? + registrationStatusRequestDTO.getRequest().stream().limit(maxLimit).collect(Collectors.toList()) : registrationStatusRequestDTO.getRequest(); + + List registrations = registrationStatusService + .getByIds(recordsToFetch); + List requestIdsNotAvailable = recordsToFetch + .stream() + .filter(request -> registrations.stream().noneMatch( + registration -> registration.getRegistrationId().equals(request.getRegistrationId()))) + .collect(Collectors.toList()); + + if (CollectionUtils.isNotEmpty(requestIdsNotAvailable)) { + List registrationsList = syncRegistrationService.getByIds(requestIdsNotAvailable); + if (registrationsList != null && !registrationsList.isEmpty()) { + registrations.addAll(syncRegistrationService.getByIds(requestIdsNotAvailable)); + } + } + + updatedConditionalStatusToProcessed(registrations); + + if (isEnabled) { + String response = objMp.writeValueAsString(buildRegistrationStatusResponse(registrations, + recordsToFetch)); + HttpHeaders headers = new HttpHeaders(); + headers.add(RESPONSE_SIGNATURE, digitalSignatureUtility.getDigitalSignature(response)); + return ResponseEntity.status(HttpStatus.OK).headers(headers).body(response); + } + return ResponseEntity.status(HttpStatus.OK) + .body(buildRegistrationStatusResponse(registrations, recordsToFetch)); + } catch (RegStatusAppException e) { + throw new RegStatusAppException(PlatformErrorMessages.RPR_RGS_DATA_VALIDATION_FAILED, e); + } catch (Exception e) { + throw new RegStatusAppException(PlatformErrorMessages.RPR_RGS_UNKNOWN_EXCEPTION, e); + } + } + + /** + * Search + * + * @param lostRidRequestDto + * @return + * @throws RegStatusAppException + */ + //@PreAuthorize("hasAnyRole('REGISTRATION_ADMIN', 'REGISTRATION_OFFICER', 'ZONAL_ADMIN','GLOBAL_ADMIN')") + @PreAuthorize("hasAnyRole(@authorizedRoles.getPostlostridsearch())") + @PostMapping(path = "/lostridsearch", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) + @Operation(summary = "Get the lost registration id", description = "Get the lost registration id", tags = { "Registration Status" }) + @ApiResponses(value = { + @ApiResponse(responseCode = "200", description = "Registration id successfully fetched", + content = @Content(schema = @Schema(implementation = RegistrationExternalStatusCode.class))), + @ApiResponse(responseCode = "201", description = "Created" ,content = @Content(schema = @Schema(hidden = true))), + @ApiResponse(responseCode = "400", description = "Unable to fetch the Registration Entity" ,content = @Content(schema = @Schema(hidden = true))), + @ApiResponse(responseCode = "401", description = "Unauthorized" ,content = @Content(schema = @Schema(hidden = true))), + @ApiResponse(responseCode = "403", description = "Forbidden" ,content = @Content(schema = @Schema(hidden = true))), + @ApiResponse(responseCode = "404", description = "Not Found" ,content = @Content(schema = @Schema(hidden = true)))}) + public ResponseEntity searchLostRid( + @RequestBody(required = true) LostRidRequestDto lostRidRequestDto) + throws RegStatusAppException { + + try { + lostRidRequestValidator.validate(lostRidRequestDto); + List lostRidDtos = syncRegistrationService.searchLostRid(lostRidRequestDto.getRequest()); + return ResponseEntity.status(HttpStatus.OK) + .body(buildLostRidResponse(lostRidDtos)); + } catch (RegStatusAppException e) { + throw new RegStatusAppException(PlatformErrorMessages.RPR_RGS_DATA_VALIDATION_FAILED, e); + } catch (Exception e) { + throw new RegStatusAppException(PlatformErrorMessages.RPR_RGS_INVALID_SEARCH, e); + } + } + + public RegStatusResponseDTO buildRegistrationStatusResponse(List registrations, + List requestIds) { + + RegStatusResponseDTO response = new RegStatusResponseDTO(); + if (Objects.isNull(response.getId())) { + response.setId(env.getProperty(REG_STATUS_SERVICE_ID)); + } + response.setResponsetime(DateUtils.getUTCCurrentDateTimeString(env.getProperty(DATETIME_PATTERN))); + response.setVersion(env.getProperty(REG_STATUS_APPLICATION_VERSION)); + response.setResponse(registrations); + List requestIdsNotAvailable = requestIds.stream() + .filter(request -> registrations.stream().noneMatch( + registration -> registration.getRegistrationId().equals(request.getRegistrationId()))) + .collect(Collectors.toList()); + List errors = new ArrayList(); + if (!requestIdsNotAvailable.isEmpty()) { + + for (RegistrationStatusSubRequestDto requestDto : requestIdsNotAvailable) { + RegistrationStatusErrorDto errorDto = new RegistrationStatusErrorDto( + PlatformErrorMessages.RPR_RGS_RID_NOT_FOUND.getCode(), + PlatformErrorMessages.RPR_RGS_RID_NOT_FOUND.getMessage()); + + errorDto.setRegistrationId(requestDto.getRegistrationId()); + errors.add(errorDto); + } + } + response.setErrors(errors); + return response; + } + + private void updatedConditionalStatusToProcessed(List registrations) { + for(RegistrationStatusDto registrationStatusDto : registrations) { + if(externalStatusesConsideredProcessed.contains(registrationStatusDto.getStatusCode())) + registrationStatusDto.setStatusCode(RegistrationExternalStatusCode.PROCESSED.toString()); + } + } + + public LostRidResponseDto buildLostRidResponse(List lostRidDtos) { + + LostRidResponseDto response = new LostRidResponseDto(); + if (Objects.isNull(response.getId())) { + response.setId(env.getProperty(REG_LOSTRID_SERVICE_ID)); + } + response.setResponsetime(DateUtils.getUTCCurrentDateTimeString(env.getProperty(DATETIME_PATTERN))); + response.setVersion(env.getProperty(REG_LOSTRID_APPLICATION_VERSION)); + response.setResponse(lostRidDtos); + List errors = new ArrayList(); + if (lostRidDtos.isEmpty()) { + RegistrationStatusErrorDto errorDto = new RegistrationStatusErrorDto( + PlatformErrorMessages.RPR_RGS_RID_NOT_FOUND.getCode(), + PlatformErrorMessages.RPR_RGS_RID_NOT_FOUND.getMessage()); + errors.add(errorDto); + } + response.setErrors(errors); + return response; + } + +} diff --git a/registration-processor/init/registration-processor-registration-status-service/src/main/java/io/mosip/registration/processor/status/api/controller/handler/InternalAuthDelegateServicesExceptionHandler.java b/registration-processor/init/registration-processor-registration-status-service/src/main/java/io/mosip/registration/processor/status/api/controller/handler/InternalAuthDelegateServicesExceptionHandler.java index bf52af1929e..797c29b0d39 100644 --- a/registration-processor/init/registration-processor-registration-status-service/src/main/java/io/mosip/registration/processor/status/api/controller/handler/InternalAuthDelegateServicesExceptionHandler.java +++ b/registration-processor/init/registration-processor-registration-status-service/src/main/java/io/mosip/registration/processor/status/api/controller/handler/InternalAuthDelegateServicesExceptionHandler.java @@ -1,81 +1,98 @@ -package io.mosip.registration.processor.status.api.controller.handler; - -import java.util.List; -import java.util.stream.Collectors; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.core.env.Environment; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.ExceptionHandler; -import org.springframework.web.bind.annotation.RestControllerAdvice; - -import io.mosip.kernel.core.exception.BaseCheckedException; -import io.mosip.kernel.core.exception.BaseUncheckedException; -import io.mosip.kernel.core.logger.spi.Logger; -import io.mosip.kernel.core.util.DateUtils; -import io.mosip.registration.processor.core.auth.dto.AuthResponseDTO; -import io.mosip.registration.processor.core.auth.dto.ErrorDTO; -import io.mosip.registration.processor.core.auth.dto.ResponseDTO; -import io.mosip.registration.processor.core.constant.LoggerFileConstant; -import io.mosip.registration.processor.core.exception.ApisResourceAccessException; -import io.mosip.registration.processor.core.logger.RegProcessorLogger; -import io.mosip.registration.processor.status.api.controller.InternalAuthDelegateServicesController; - -@RestControllerAdvice(assignableTypes = InternalAuthDelegateServicesController.class) -public class InternalAuthDelegateServicesExceptionHandler { - - private static Logger regProcLogger = RegProcessorLogger - .getLogger(InternalAuthDelegateServicesExceptionHandler.class); - - private static final String INTERNAL_AUTH_APPLICATION_REQUEST_ID = "mosip.identity.auth.internal.requestid"; - private static final String INTERNAL_AUTH_APPLICATION_VERSION = "mosip.registration.processor.application.version"; - private static final String DATETIME_PATTERN = "mosip.registration.processor.datetime.pattern"; - - @Autowired - private Environment env; - - @ExceptionHandler(ApisResourceAccessException.class) - public ResponseEntity ApisResourceAccessException(ApisResourceAccessException e) { - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), - e.getErrorCode(), e.getMessage()); - return buildInternalAuthDelegateServiceExceptionResponse((Exception) e); - } - - private ResponseEntity buildInternalAuthDelegateServiceExceptionResponse(Exception ex) { - - AuthResponseDTO response = new AuthResponseDTO(); - Throwable e = ex; - - response.setId(env.getProperty(INTERNAL_AUTH_APPLICATION_REQUEST_ID)); - if (e instanceof BaseCheckedException) - - { - List errorCodes = ((BaseCheckedException) e).getCodes(); - List errorTexts = ((BaseCheckedException) e).getErrorTexts(); - - List errors = errorTexts.parallelStream() - .map(errMsg -> new ErrorDTO(errorCodes.get(errorTexts.indexOf(errMsg)), errMsg)).distinct() - .collect(Collectors.toList()); - - response.setErrors(errors); - } - if (e instanceof BaseUncheckedException) { - List errorCodes = ((BaseUncheckedException) e).getCodes(); - List errorTexts = ((BaseUncheckedException) e).getErrorTexts(); - - List errors = errorTexts.parallelStream() - .map(errMsg -> new ErrorDTO(errorCodes.get(errorTexts.indexOf(errMsg)), errMsg)).distinct() - .collect(Collectors.toList()); - - response.setErrors(errors); - } - - response.setResponseTime(DateUtils.getUTCCurrentDateTimeString(env.getProperty(DATETIME_PATTERN))); - response.setVersion(env.getProperty(INTERNAL_AUTH_APPLICATION_VERSION)); - response.setResponse(new ResponseDTO()); - - return ResponseEntity.status(HttpStatus.OK).body(response); - } - -} +package io.mosip.registration.processor.status.api.controller.handler; + +import java.util.List; +import java.util.stream.Collectors; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; +import org.springframework.web.context.request.WebRequest; + +import io.mosip.kernel.core.exception.BaseCheckedException; +import io.mosip.kernel.core.exception.BaseUncheckedException; +import io.mosip.kernel.core.logger.spi.Logger; +import io.mosip.kernel.core.util.DateUtils; +import io.mosip.registration.processor.core.auth.dto.AuthResponseDTO; +import io.mosip.registration.processor.core.auth.dto.ErrorDTO; +import io.mosip.registration.processor.core.auth.dto.ResponseDTO; +import io.mosip.registration.processor.core.constant.LoggerFileConstant; +import io.mosip.registration.processor.core.exception.ApisResourceAccessException; +import io.mosip.registration.processor.core.logger.RegProcessorLogger; +import io.mosip.registration.processor.core.token.validation.exception.InvalidTokenException; +import io.mosip.registration.processor.status.api.controller.InternalAuthDelegateServicesController; +import io.mosip.registration.processor.status.exception.InternalAuthDeligateAppException; +import io.mosip.registration.processor.status.sync.response.dto.RegTransactionResponseDTO; + +@RestControllerAdvice(assignableTypes = InternalAuthDelegateServicesController.class) +public class InternalAuthDelegateServicesExceptionHandler { + + private static Logger regProcLogger = RegProcessorLogger + .getLogger(InternalAuthDelegateServicesExceptionHandler.class); + + private static final String INTERNAL_AUTH_APPLICATION_REQUEST_ID = "mosip.identity.auth.internal.requestid"; + private static final String INTERNAL_AUTH_APPLICATION_VERSION = "mosip.registration.processor.application.version"; + private static final String DATETIME_PATTERN = "mosip.registration.processor.datetime.pattern"; + + @Autowired + private Environment env; + + @ExceptionHandler(ApisResourceAccessException.class) + public ResponseEntity ApisResourceAccessException(ApisResourceAccessException e) { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), + e.getErrorCode(), e.getMessage()); + return buildInternalAuthDelegateServiceExceptionResponse((Exception) e); + } + + @ExceptionHandler(InvalidTokenException.class) + protected ResponseEntity handleInvalidTokenException(InvalidTokenException e, WebRequest request) { + return buildInternalAuthDelegateServiceExceptionResponse((Exception)e); + + } + + @ExceptionHandler(InternalAuthDeligateAppException.class) + protected ResponseEntity handleInternalAuthDeligateAppException(InternalAuthDeligateAppException e) { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), + e.getErrorCode(), e.getMessage()); + return buildInternalAuthDelegateServiceExceptionResponse((Exception) e); + } + + private ResponseEntity buildInternalAuthDelegateServiceExceptionResponse(Exception ex) { + + AuthResponseDTO response = new AuthResponseDTO(); + Throwable e = ex; + + response.setId(env.getProperty(INTERNAL_AUTH_APPLICATION_REQUEST_ID)); + if (e instanceof BaseCheckedException) + + { + List errorCodes = ((BaseCheckedException) e).getCodes(); + List errorTexts = ((BaseCheckedException) e).getErrorTexts(); + + List errors = errorTexts.parallelStream() + .map(errMsg -> new ErrorDTO(errorCodes.get(errorTexts.indexOf(errMsg)), errMsg)).distinct() + .collect(Collectors.toList()); + + response.setErrors(errors); + } + if (e instanceof BaseUncheckedException) { + List errorCodes = ((BaseUncheckedException) e).getCodes(); + List errorTexts = ((BaseUncheckedException) e).getErrorTexts(); + + List errors = errorTexts.parallelStream() + .map(errMsg -> new ErrorDTO(errorCodes.get(errorTexts.indexOf(errMsg)), errMsg)).distinct() + .collect(Collectors.toList()); + + response.setErrors(errors); + } + + response.setResponseTime(DateUtils.getUTCCurrentDateTimeString(env.getProperty(DATETIME_PATTERN))); + response.setVersion(env.getProperty(INTERNAL_AUTH_APPLICATION_VERSION)); + response.setResponse(null); + + return ResponseEntity.status(HttpStatus.OK).body(response); + } + +} diff --git a/registration-processor/init/registration-processor-registration-status-service/src/main/java/io/mosip/registration/processor/status/api/controller/handler/PacketExternalStatusExceptionHandler.java b/registration-processor/init/registration-processor-registration-status-service/src/main/java/io/mosip/registration/processor/status/api/controller/handler/PacketExternalStatusExceptionHandler.java index 1cd99ddd01e..34ee5a47937 100644 --- a/registration-processor/init/registration-processor-registration-status-service/src/main/java/io/mosip/registration/processor/status/api/controller/handler/PacketExternalStatusExceptionHandler.java +++ b/registration-processor/init/registration-processor-registration-status-service/src/main/java/io/mosip/registration/processor/status/api/controller/handler/PacketExternalStatusExceptionHandler.java @@ -17,9 +17,9 @@ import org.springframework.web.context.request.WebRequest; import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; +import com.fasterxml.jackson.databind.ObjectMapper; import io.mosip.kernel.core.exception.BaseCheckedException; import io.mosip.kernel.core.exception.BaseUncheckedException; @@ -51,6 +51,9 @@ public class PacketExternalStatusExceptionHandler { @Autowired DigitalSignatureUtility digitalSignatureUtility; + + @Autowired + ObjectMapper obj ; private static final String RESPONSE_SIGNATURE = "Response-Signature"; @@ -151,12 +154,18 @@ private ResponseEntity buildRegStatusExceptionResponse(Exception ex) { response.setResponsetime(DateUtils.getUTCCurrentDateTimeString(env.getProperty(DATETIME_PATTERN))); response.setVersion(env.getProperty(PACKET_EXTERNAL_STATUS_APPLICATION_VERSION)); response.setResponse(null); - Gson gson = new GsonBuilder().serializeNulls().create(); - + if (isEnabled) { HttpHeaders headers = new HttpHeaders(); - headers.add(RESPONSE_SIGNATURE, digitalSignatureUtility.getDigitalSignature(gson.toJson(response))); - return ResponseEntity.ok().headers(headers).body(gson.toJson(response)); + String res=null; + try { + res=obj.writeValueAsString(response); + } catch (JsonProcessingException e1) { + // TODO Auto-generated catch block + regProcLogger.error("Error while processsing response",e1); + } + headers.add(RESPONSE_SIGNATURE, digitalSignatureUtility.getDigitalSignature(res)); + return ResponseEntity.ok().headers(headers).body(res); } return ResponseEntity.status(HttpStatus.OK).body(response); diff --git a/registration-processor/init/registration-processor-registration-status-service/src/main/java/io/mosip/registration/processor/status/api/controller/handler/RegistrationExternalStatusExceptionHandler.java b/registration-processor/init/registration-processor-registration-status-service/src/main/java/io/mosip/registration/processor/status/api/controller/handler/RegistrationExternalStatusExceptionHandler.java index 23967466a32..cc52365e079 100644 --- a/registration-processor/init/registration-processor-registration-status-service/src/main/java/io/mosip/registration/processor/status/api/controller/handler/RegistrationExternalStatusExceptionHandler.java +++ b/registration-processor/init/registration-processor-registration-status-service/src/main/java/io/mosip/registration/processor/status/api/controller/handler/RegistrationExternalStatusExceptionHandler.java @@ -1,165 +1,173 @@ -package io.mosip.registration.processor.status.api.controller.handler; - -import java.util.List; -import java.util.Objects; -import java.util.stream.Collectors; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.core.env.Environment; -import org.springframework.dao.DataIntegrityViolationException; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.MethodArgumentNotValidException; -import org.springframework.web.bind.annotation.ExceptionHandler; -import org.springframework.web.bind.annotation.RestControllerAdvice; -import org.springframework.web.context.request.WebRequest; - -import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.databind.JsonMappingException; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; - -import io.mosip.kernel.core.exception.BaseCheckedException; -import io.mosip.kernel.core.exception.BaseUncheckedException; -import io.mosip.kernel.core.logger.spi.Logger; -import io.mosip.kernel.core.util.DateUtils; -import io.mosip.registration.processor.core.constant.LoggerFileConstant; -import io.mosip.registration.processor.core.exception.util.PlatformErrorMessages; -import io.mosip.registration.processor.core.logger.RegProcessorLogger; -import io.mosip.registration.processor.core.token.validation.exception.AccessDeniedException; -import io.mosip.registration.processor.core.token.validation.exception.InvalidTokenException; -import io.mosip.registration.processor.core.util.DigitalSignatureUtility; -import io.mosip.registration.processor.status.api.controller.RegistrationExternalStatusController; -import io.mosip.registration.processor.status.dto.ErrorDTO; -import io.mosip.registration.processor.status.exception.RegStatusAppException; -import io.mosip.registration.processor.status.exception.TablenotAccessibleException; -import io.mosip.registration.processor.status.sync.response.dto.RegStatusResponseDTO; - -@RestControllerAdvice(assignableTypes = RegistrationExternalStatusController.class) -public class RegistrationExternalStatusExceptionHandler { - - private static final String REG_EXTERNAL_STATUS_SERVICE_ID = "mosip.registration.processor.registration.external.status.id"; - private static final String REG_EXTERNAL_STATUS_APPLICATION_VERSION = "mosip.registration.processor.registration.external.status.version"; - private static final String DATETIME_PATTERN = "mosip.registration.processor.datetime.pattern"; - @Autowired - private Environment env; - - @Value("${registration.processor.signature.isEnabled}") - Boolean isEnabled; - - @Autowired - DigitalSignatureUtility digitalSignatureUtility; - - private static final String RESPONSE_SIGNATURE = "Response-Signature"; - - private static Logger regProcLogger = RegProcessorLogger.getLogger(RegistrationExternalStatusExceptionHandler.class); - - @ExceptionHandler(AccessDeniedException.class) - public ResponseEntity accessDenied(AccessDeniedException e) { - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), - e.getErrorCode(), e.getMessage()); - return buildRegStatusExceptionResponse((Exception) e); - } - - @ExceptionHandler(TablenotAccessibleException.class) - public ResponseEntity duplicateentry(TablenotAccessibleException e, WebRequest request) { - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), - e.getErrorCode(), e.getCause().toString()); - return buildRegStatusExceptionResponse((Exception) e); - } - - @ExceptionHandler(JsonMappingException.class) - public ResponseEntity badRequest(JsonMappingException ex, WebRequest request) { - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), - PlatformErrorMessages.RPR_RGS_JSON_MAPPING_EXCEPTION.getCode(), - PlatformErrorMessages.RPR_RGS_JSON_MAPPING_EXCEPTION.getMessage()); - RegStatusAppException reg1 = new RegStatusAppException(PlatformErrorMessages.RPR_RGS_JSON_MAPPING_EXCEPTION, - ex); - return handleRegStatusException(reg1, request); - } - - @ExceptionHandler(JsonParseException.class) - public ResponseEntity badRequest(JsonParseException ex, WebRequest request) { - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), - PlatformErrorMessages.RPR_RGS_JSON_PARSING_EXCEPTION.getCode(), - PlatformErrorMessages.RPR_RGS_JSON_PARSING_EXCEPTION.getMessage()); - RegStatusAppException reg1 = new RegStatusAppException(PlatformErrorMessages.RPR_RGS_JSON_PARSING_EXCEPTION, - ex); - return handleRegStatusException(reg1, request); - } - - @ExceptionHandler(MethodArgumentNotValidException.class) - public ResponseEntity badRequest(MethodArgumentNotValidException ex) { - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), - PlatformErrorMessages.RPR_SYS_BAD_GATEWAY.getCode(), "langCode must be of 3 characters"); - return buildRegStatusExceptionResponse((Exception) ex); - } - - @ExceptionHandler(DataIntegrityViolationException.class) - public ResponseEntity dataExceptionHandler(final DataIntegrityViolationException e, WebRequest request) { - - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), - "RPR-DBE-001 Data integrity violation exception", e.getMessage()); - return buildRegStatusExceptionResponse((Exception) e); - } - - @ExceptionHandler(RegStatusAppException.class) - protected ResponseEntity handleRegStatusException(RegStatusAppException e, WebRequest request) { - return buildRegStatusExceptionResponse((Exception) e); - - } - - @ExceptionHandler(InvalidTokenException.class) - protected ResponseEntity handleInvalidTokenException(InvalidTokenException e, WebRequest request) { - return buildRegStatusExceptionResponse((Exception) e); - - } - - private ResponseEntity buildRegStatusExceptionResponse(Exception ex) { - - RegStatusResponseDTO response = new RegStatusResponseDTO(); - Throwable e = ex; - - if (Objects.isNull(response.getId())) { - response.setId(env.getProperty(REG_EXTERNAL_STATUS_SERVICE_ID)); - } - if (e instanceof BaseCheckedException) - - { - List errorCodes = ((BaseCheckedException) e).getCodes(); - List errorTexts = ((BaseCheckedException) e).getErrorTexts(); - - List errors = errorTexts.parallelStream() - .map(errMsg -> new ErrorDTO(errorCodes.get(errorTexts.indexOf(errMsg)), errMsg)).distinct() - .collect(Collectors.toList()); - - response.setErrors(errors); - } - if (e instanceof BaseUncheckedException) { - List errorCodes = ((BaseUncheckedException) e).getCodes(); - List errorTexts = ((BaseUncheckedException) e).getErrorTexts(); - - List errors = errorTexts.parallelStream() - .map(errMsg -> new ErrorDTO(errorCodes.get(errorTexts.indexOf(errMsg)), errMsg)).distinct() - .collect(Collectors.toList()); - - response.setErrors(errors); - } - - response.setResponsetime(DateUtils.getUTCCurrentDateTimeString(env.getProperty(DATETIME_PATTERN))); - response.setVersion(env.getProperty(REG_EXTERNAL_STATUS_APPLICATION_VERSION)); - response.setResponse(null); - Gson gson = new GsonBuilder().serializeNulls().create(); - - if (isEnabled) { - HttpHeaders headers = new HttpHeaders(); - headers.add(RESPONSE_SIGNATURE, digitalSignatureUtility.getDigitalSignature(gson.toJson(response))); - return ResponseEntity.ok().headers(headers).body(gson.toJson(response)); - } - return ResponseEntity.status(HttpStatus.OK).body(response); - - } - -} +package io.mosip.registration.processor.status.api.controller.handler; + +import java.io.IOException; +import java.util.List; +import java.util.Objects; +import java.util.stream.Collectors; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.core.env.Environment; +import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; +import org.springframework.web.context.request.WebRequest; + +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +import io.mosip.kernel.core.exception.BaseCheckedException; +import io.mosip.kernel.core.exception.BaseUncheckedException; +import io.mosip.kernel.core.logger.spi.Logger; +import io.mosip.kernel.core.util.DateUtils; +import io.mosip.registration.processor.core.constant.LoggerFileConstant; +import io.mosip.registration.processor.core.exception.util.PlatformErrorMessages; +import io.mosip.registration.processor.core.logger.RegProcessorLogger; +import io.mosip.registration.processor.core.token.validation.exception.AccessDeniedException; +import io.mosip.registration.processor.core.token.validation.exception.InvalidTokenException; +import io.mosip.registration.processor.core.util.DigitalSignatureUtility; +import io.mosip.registration.processor.status.api.controller.RegistrationExternalStatusController; +import io.mosip.registration.processor.status.dto.ErrorDTO; +import io.mosip.registration.processor.status.exception.RegStatusAppException; +import io.mosip.registration.processor.status.exception.TablenotAccessibleException; +import io.mosip.registration.processor.status.sync.response.dto.RegStatusResponseDTO; +@RestControllerAdvice(assignableTypes = RegistrationExternalStatusController.class) +public class RegistrationExternalStatusExceptionHandler { + + private static final String REG_EXTERNAL_STATUS_SERVICE_ID = "mosip.registration.processor.registration.external.status.id"; + private static final String REG_EXTERNAL_STATUS_APPLICATION_VERSION = "mosip.registration.processor.registration.external.status.version"; + private static final String DATETIME_PATTERN = "mosip.registration.processor.datetime.pattern"; + @Autowired + private Environment env; + + @Value("${registration.processor.signature.isEnabled}") + Boolean isEnabled; + + @Autowired + DigitalSignatureUtility digitalSignatureUtility; + + @Autowired + ObjectMapper obj; + + private static final String RESPONSE_SIGNATURE = "Response-Signature"; + + private static Logger regProcLogger = RegProcessorLogger.getLogger(RegistrationExternalStatusExceptionHandler.class); + + @ExceptionHandler(AccessDeniedException.class) + public ResponseEntity accessDenied(AccessDeniedException e) { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), + e.getErrorCode(), e.getMessage()); + return buildRegStatusExceptionResponse((Exception) e); + } + + @ExceptionHandler(TablenotAccessibleException.class) + public ResponseEntity duplicateentry(TablenotAccessibleException e, WebRequest request) { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), + e.getErrorCode(), e.getCause().toString()); + return buildRegStatusExceptionResponse((Exception) e); + } + + @ExceptionHandler(JsonMappingException.class) + public ResponseEntity badRequest(JsonMappingException ex, WebRequest request) { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), + PlatformErrorMessages.RPR_RGS_JSON_MAPPING_EXCEPTION.getCode(), + PlatformErrorMessages.RPR_RGS_JSON_MAPPING_EXCEPTION.getMessage()); + RegStatusAppException reg1 = new RegStatusAppException(PlatformErrorMessages.RPR_RGS_JSON_MAPPING_EXCEPTION, + ex); + return handleRegStatusException(reg1, request); + } + + @ExceptionHandler(JsonParseException.class) + public ResponseEntity badRequest(JsonParseException ex, WebRequest request) { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), + PlatformErrorMessages.RPR_RGS_JSON_PARSING_EXCEPTION.getCode(), + PlatformErrorMessages.RPR_RGS_JSON_PARSING_EXCEPTION.getMessage()); + RegStatusAppException reg1 = new RegStatusAppException(PlatformErrorMessages.RPR_RGS_JSON_PARSING_EXCEPTION, + ex); + return handleRegStatusException(reg1, request); + } + + @ExceptionHandler(MethodArgumentNotValidException.class) + public ResponseEntity badRequest(MethodArgumentNotValidException ex) { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), + PlatformErrorMessages.RPR_SYS_BAD_GATEWAY.getCode(), "langCode must be of 3 characters"); + return buildRegStatusExceptionResponse((Exception) ex); + } + + @ExceptionHandler(DataIntegrityViolationException.class) + public ResponseEntity dataExceptionHandler(final DataIntegrityViolationException e, WebRequest request) { + + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), + "RPR-DBE-001 Data integrity violation exception", e.getMessage()); + return buildRegStatusExceptionResponse((Exception) e); + } + + @ExceptionHandler(RegStatusAppException.class) + protected ResponseEntity handleRegStatusException(RegStatusAppException e, WebRequest request) { + return buildRegStatusExceptionResponse((Exception) e); + + } + + @ExceptionHandler(InvalidTokenException.class) + protected ResponseEntity handleInvalidTokenException(InvalidTokenException e, WebRequest request) { + return buildRegStatusExceptionResponse((Exception) e); + + } + + private ResponseEntity buildRegStatusExceptionResponse(Exception ex) { + + RegStatusResponseDTO response = new RegStatusResponseDTO(); + Throwable e = ex; + + if (Objects.isNull(response.getId())) { + response.setId(env.getProperty(REG_EXTERNAL_STATUS_SERVICE_ID)); + } + if (e instanceof BaseCheckedException) + + { + List errorCodes = ((BaseCheckedException) e).getCodes(); + List errorTexts = ((BaseCheckedException) e).getErrorTexts(); + + List errors = errorTexts.parallelStream() + .map(errMsg -> new ErrorDTO(errorCodes.get(errorTexts.indexOf(errMsg)), errMsg)).distinct() + .collect(Collectors.toList()); + + response.setErrors(errors); + } + if (e instanceof BaseUncheckedException) { + List errorCodes = ((BaseUncheckedException) e).getCodes(); + List errorTexts = ((BaseUncheckedException) e).getErrorTexts(); + + List errors = errorTexts.parallelStream() + .map(errMsg -> new ErrorDTO(errorCodes.get(errorTexts.indexOf(errMsg)), errMsg)).distinct() + .collect(Collectors.toList()); + + response.setErrors(errors); + } + + response.setResponsetime(DateUtils.getUTCCurrentDateTimeString(env.getProperty(DATETIME_PATTERN))); + response.setVersion(env.getProperty(REG_EXTERNAL_STATUS_APPLICATION_VERSION)); + response.setResponse(null); + + if (isEnabled) { + HttpHeaders headers = new HttpHeaders(); + String res=null; + try { + res=obj.writeValueAsString(response); + } catch (IOException e1) { + regProcLogger.error("Error while processing response",e1); + + } + headers.add(RESPONSE_SIGNATURE, digitalSignatureUtility.getDigitalSignature(res)); + return ResponseEntity.ok().headers(headers).body(res); + } + return ResponseEntity.status(HttpStatus.OK).body(response); + + } + +} diff --git a/registration-processor/init/registration-processor-registration-status-service/src/main/java/io/mosip/registration/processor/status/api/controller/handler/RegistrationStatusExceptionHandler.java b/registration-processor/init/registration-processor-registration-status-service/src/main/java/io/mosip/registration/processor/status/api/controller/handler/RegistrationStatusExceptionHandler.java index aed77048a52..5889936b79e 100644 --- a/registration-processor/init/registration-processor-registration-status-service/src/main/java/io/mosip/registration/processor/status/api/controller/handler/RegistrationStatusExceptionHandler.java +++ b/registration-processor/init/registration-processor-registration-status-service/src/main/java/io/mosip/registration/processor/status/api/controller/handler/RegistrationStatusExceptionHandler.java @@ -1,5 +1,6 @@ package io.mosip.registration.processor.status.api.controller.handler; +import java.io.IOException; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; @@ -18,8 +19,7 @@ import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; +import com.fasterxml.jackson.databind.ObjectMapper; import io.mosip.kernel.core.exception.BaseCheckedException; import io.mosip.kernel.core.exception.BaseUncheckedException; @@ -51,6 +51,9 @@ public class RegistrationStatusExceptionHandler { @Autowired DigitalSignatureUtility digitalSignatureUtility; + + @Autowired + ObjectMapper objectMapper; private static final String RESPONSE_SIGNATURE = "Response-Signature"; @@ -151,12 +154,18 @@ private ResponseEntity buildRegStatusExceptionResponse(Exception ex) { response.setResponsetime(DateUtils.getUTCCurrentDateTimeString(env.getProperty(DATETIME_PATTERN))); response.setVersion(env.getProperty(REG_STATUS_APPLICATION_VERSION)); response.setResponse(null); - Gson gson = new GsonBuilder().serializeNulls().create(); - + if (isEnabled) { HttpHeaders headers = new HttpHeaders(); - headers.add(RESPONSE_SIGNATURE, digitalSignatureUtility.getDigitalSignature(gson.toJson(response))); - return ResponseEntity.ok().headers(headers).body(gson.toJson(response)); + String res=null; + try { + res=objectMapper.writeValueAsString(response); + } catch (IOException e1) { + regProcLogger.error("Error while processing response",e1); + + } + headers.add(RESPONSE_SIGNATURE, digitalSignatureUtility.getDigitalSignature(res)); + return ResponseEntity.ok().headers(headers).body(res); } return ResponseEntity.status(HttpStatus.OK).body(response); diff --git a/registration-processor/init/registration-processor-registration-status-service/src/main/java/io/mosip/registration/processor/status/api/controller/handler/RegistrationSyncExceptionHandler.java b/registration-processor/init/registration-processor-registration-status-service/src/main/java/io/mosip/registration/processor/status/api/controller/handler/RegistrationSyncExceptionHandler.java index ac0d6c696cf..7832424a435 100644 --- a/registration-processor/init/registration-processor-registration-status-service/src/main/java/io/mosip/registration/processor/status/api/controller/handler/RegistrationSyncExceptionHandler.java +++ b/registration-processor/init/registration-processor-registration-status-service/src/main/java/io/mosip/registration/processor/status/api/controller/handler/RegistrationSyncExceptionHandler.java @@ -1,158 +1,169 @@ -package io.mosip.registration.processor.status.api.controller.handler; - -import java.util.List; -import java.util.Objects; -import java.util.stream.Collectors; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.core.env.Environment; -import org.springframework.dao.DataIntegrityViolationException; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.MethodArgumentNotValidException; -import org.springframework.web.bind.annotation.ExceptionHandler; -import org.springframework.web.bind.annotation.RestControllerAdvice; -import org.springframework.web.context.request.WebRequest; - -import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.databind.JsonMappingException; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; - -import io.mosip.kernel.core.exception.BaseCheckedException; -import io.mosip.kernel.core.exception.BaseUncheckedException; -import io.mosip.kernel.core.logger.spi.Logger; -import io.mosip.kernel.core.util.DateUtils; -import io.mosip.registration.processor.core.constant.LoggerFileConstant; -import io.mosip.registration.processor.core.exception.util.PlatformErrorMessages; -import io.mosip.registration.processor.core.logger.RegProcessorLogger; -import io.mosip.registration.processor.core.token.validation.exception.AccessDeniedException; -import io.mosip.registration.processor.core.token.validation.exception.InvalidTokenException; -import io.mosip.registration.processor.core.util.DigitalSignatureUtility; -import io.mosip.registration.processor.status.api.controller.RegistrationSyncController; -import io.mosip.registration.processor.status.dto.SyncErrorDTO; -import io.mosip.registration.processor.status.exception.RegStatusAppException; -import io.mosip.registration.processor.status.exception.TablenotAccessibleException; -import io.mosip.registration.processor.status.sync.response.dto.RegSyncResponseDTO; - - -@RestControllerAdvice(assignableTypes=RegistrationSyncController.class) -public class RegistrationSyncExceptionHandler { - - private static final String REG_SYNC_SERVICE_ID = "mosip.registration.processor.registration.sync.id"; - private static final String REG_SYNC_APPLICATION_VERSION = "mosip.registration.processor.application.version"; - private static final String DATETIME_PATTERN = "mosip.registration.processor.datetime.pattern"; - @Autowired - private Environment env; - - @Value("${registration.processor.signature.isEnabled}") - Boolean isEnabled; - - @Autowired - DigitalSignatureUtility digitalSignatureUtility; - - private static final String RESPONSE_SIGNATURE = "Response-Signature"; - - - private static Logger regProcLogger = RegProcessorLogger.getLogger(RegistrationSyncExceptionHandler.class); - - @ExceptionHandler(AccessDeniedException.class) - public ResponseEntity accessDenied(AccessDeniedException e) { - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), - e.getErrorCode(), e.getMessage()); - return buildRegStatusExceptionResponse((Exception) e); - } - - @ExceptionHandler(TablenotAccessibleException.class) - public ResponseEntity duplicateentry(TablenotAccessibleException e, WebRequest request) { - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(),LoggerFileConstant.APPLICATIONID.toString(),e.getErrorCode(), e.getCause().toString()); - return buildRegStatusExceptionResponse((Exception)e); - } - - @ExceptionHandler(JsonMappingException.class) - public ResponseEntity badRequest(JsonMappingException ex, WebRequest request){ - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(),LoggerFileConstant.APPLICATIONID.toString(),PlatformErrorMessages.RPR_RGS_JSON_MAPPING_EXCEPTION.getCode(),PlatformErrorMessages.RPR_RGS_JSON_MAPPING_EXCEPTION.getMessage()); - RegStatusAppException reg1=new RegStatusAppException(PlatformErrorMessages.RPR_RGS_JSON_MAPPING_EXCEPTION, ex); - return handleRegStatusException(reg1,request); - } - - @ExceptionHandler(JsonParseException.class) - public ResponseEntity badRequest(JsonParseException ex, WebRequest request) { - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(),LoggerFileConstant.APPLICATIONID.toString(),PlatformErrorMessages.RPR_RGS_JSON_PARSING_EXCEPTION.getCode(),PlatformErrorMessages.RPR_RGS_JSON_PARSING_EXCEPTION.getMessage()); - RegStatusAppException reg1=new RegStatusAppException(PlatformErrorMessages.RPR_RGS_JSON_PARSING_EXCEPTION, ex); - return handleRegStatusException(reg1, request); - } - - @ExceptionHandler(MethodArgumentNotValidException.class) - public ResponseEntity badRequest(MethodArgumentNotValidException ex) { - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(),LoggerFileConstant.APPLICATIONID.toString(),PlatformErrorMessages.RPR_SYS_BAD_GATEWAY.getCode(),"langCode must be of 3 characters"); - return buildRegStatusExceptionResponse((Exception)ex); - } - - - @ExceptionHandler(DataIntegrityViolationException.class) - public ResponseEntity dataExceptionHandler(final DataIntegrityViolationException e, WebRequest request) { - - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(),LoggerFileConstant.APPLICATIONID.toString(),"RPR-DBE-001 Data integrity violation exception",e.getMessage()); - return buildRegStatusExceptionResponse((Exception)e); - } - - - @ExceptionHandler(RegStatusAppException.class) - protected ResponseEntity handleRegStatusException(RegStatusAppException e, WebRequest request) { - return buildRegStatusExceptionResponse((Exception)e); - - } - @ExceptionHandler(InvalidTokenException.class) - protected ResponseEntity handleInvalidTokenException(InvalidTokenException e, WebRequest request) { - return buildRegStatusExceptionResponse((Exception)e); - - } - private ResponseEntity buildRegStatusExceptionResponse(Exception ex) { - - RegSyncResponseDTO response = new RegSyncResponseDTO(); - Throwable e = ex; - - if (Objects.isNull(response.getId())) { - response.setId(env.getProperty(REG_SYNC_SERVICE_ID)); - } - if (e instanceof BaseCheckedException) - - { - List errorCodes = ((BaseCheckedException) e).getCodes(); - List errorTexts = ((BaseCheckedException) e).getErrorTexts(); - - List errors = errorTexts.parallelStream().map(errMsg -> new SyncErrorDTO(errorCodes.get(errorTexts.indexOf(errMsg)), errMsg)).distinct().collect(Collectors.toList()); - - response.setErrors(errors); - } - if (e instanceof BaseUncheckedException) { - List errorCodes = ((BaseUncheckedException) e).getCodes(); - List errorTexts = ((BaseUncheckedException) e).getErrorTexts(); - - List errors = errorTexts.parallelStream() - .map(errMsg -> new SyncErrorDTO(errorCodes.get(errorTexts.indexOf(errMsg)), errMsg)).distinct() - .collect(Collectors.toList()); - - response.setErrors(errors); - } - - response.setResponsetime(DateUtils.getUTCCurrentDateTimeString(env.getProperty(DATETIME_PATTERN))); - response.setVersion(env.getProperty(REG_SYNC_APPLICATION_VERSION)); - response.setResponse(null); - Gson gson = new GsonBuilder().serializeNulls().create(); - - - if(isEnabled) { - HttpHeaders headers = new HttpHeaders(); - headers.add(RESPONSE_SIGNATURE,digitalSignatureUtility.getDigitalSignature(gson.toJson(response))); - return ResponseEntity.ok().headers(headers).body(gson.toJson(response)); - } - return ResponseEntity.status(HttpStatus.OK).body(response); - - } - - -} +package io.mosip.registration.processor.status.api.controller.handler; + +import java.io.IOException; +import java.util.List; +import java.util.Objects; +import java.util.stream.Collectors; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.core.env.Environment; +import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; +import org.springframework.web.context.request.WebRequest; + +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +import io.mosip.kernel.core.exception.BaseCheckedException; +import io.mosip.kernel.core.exception.BaseUncheckedException; +import io.mosip.kernel.core.logger.spi.Logger; +import io.mosip.kernel.core.util.DateUtils; +import io.mosip.registration.processor.core.constant.LoggerFileConstant; +import io.mosip.registration.processor.core.exception.util.PlatformErrorMessages; +import io.mosip.registration.processor.core.logger.RegProcessorLogger; +import io.mosip.registration.processor.core.token.validation.exception.AccessDeniedException; +import io.mosip.registration.processor.core.token.validation.exception.InvalidTokenException; +import io.mosip.registration.processor.core.util.DigitalSignatureUtility; +import io.mosip.registration.processor.status.api.controller.RegistrationSyncController; +import io.mosip.registration.processor.status.dto.SyncErrorDTO; +import io.mosip.registration.processor.status.exception.RegStatusAppException; +import io.mosip.registration.processor.status.exception.TablenotAccessibleException; +import io.mosip.registration.processor.status.sync.response.dto.RegSyncResponseDTO; + + +@RestControllerAdvice(assignableTypes=RegistrationSyncController.class) +public class RegistrationSyncExceptionHandler { + + private static final String REG_SYNC_SERVICE_ID = "mosip.registration.processor.registration.sync.id"; + private static final String REG_SYNC_APPLICATION_VERSION = "mosip.registration.processor.application.version"; + private static final String DATETIME_PATTERN = "mosip.registration.processor.datetime.pattern"; + @Autowired + private Environment env; + + @Value("${registration.processor.signature.isEnabled}") + Boolean isEnabled; + + @Autowired + DigitalSignatureUtility digitalSignatureUtility; + + @Autowired + ObjectMapper objectMapper; + + private static final String RESPONSE_SIGNATURE = "Response-Signature"; + + + private static Logger regProcLogger = RegProcessorLogger.getLogger(RegistrationSyncExceptionHandler.class); + + @ExceptionHandler(AccessDeniedException.class) + public ResponseEntity accessDenied(AccessDeniedException e) { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), + e.getErrorCode(), e.getMessage()); + return buildRegStatusExceptionResponse((Exception) e); + } + + @ExceptionHandler(TablenotAccessibleException.class) + public ResponseEntity duplicateentry(TablenotAccessibleException e, WebRequest request) { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(),LoggerFileConstant.APPLICATIONID.toString(),e.getErrorCode(), e.getCause().toString()); + return buildRegStatusExceptionResponse((Exception)e); + } + + @ExceptionHandler(JsonMappingException.class) + public ResponseEntity badRequest(JsonMappingException ex, WebRequest request){ + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(),LoggerFileConstant.APPLICATIONID.toString(),PlatformErrorMessages.RPR_RGS_JSON_MAPPING_EXCEPTION.getCode(),PlatformErrorMessages.RPR_RGS_JSON_MAPPING_EXCEPTION.getMessage()); + RegStatusAppException reg1=new RegStatusAppException(PlatformErrorMessages.RPR_RGS_JSON_MAPPING_EXCEPTION, ex); + return handleRegStatusException(reg1,request); + } + + @ExceptionHandler(JsonParseException.class) + public ResponseEntity badRequest(JsonParseException ex, WebRequest request) { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(),LoggerFileConstant.APPLICATIONID.toString(),PlatformErrorMessages.RPR_RGS_JSON_PARSING_EXCEPTION.getCode(),PlatformErrorMessages.RPR_RGS_JSON_PARSING_EXCEPTION.getMessage()); + RegStatusAppException reg1=new RegStatusAppException(PlatformErrorMessages.RPR_RGS_JSON_PARSING_EXCEPTION, ex); + return handleRegStatusException(reg1, request); + } + + @ExceptionHandler(MethodArgumentNotValidException.class) + public ResponseEntity badRequest(MethodArgumentNotValidException ex) { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(),LoggerFileConstant.APPLICATIONID.toString(),PlatformErrorMessages.RPR_SYS_BAD_GATEWAY.getCode(),"langCode must be of 3 characters"); + return buildRegStatusExceptionResponse((Exception)ex); + } + + + @ExceptionHandler(DataIntegrityViolationException.class) + public ResponseEntity dataExceptionHandler(final DataIntegrityViolationException e, WebRequest request) { + + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(),LoggerFileConstant.APPLICATIONID.toString(),"RPR-DBE-001 Data integrity violation exception",e.getMessage()); + return buildRegStatusExceptionResponse((Exception)e); + } + + + @ExceptionHandler(RegStatusAppException.class) + protected ResponseEntity handleRegStatusException(RegStatusAppException e, WebRequest request) { + return buildRegStatusExceptionResponse((Exception)e); + + } + @ExceptionHandler(InvalidTokenException.class) + protected ResponseEntity handleInvalidTokenException(InvalidTokenException e, WebRequest request) { + return buildRegStatusExceptionResponse((Exception)e); + + } + private ResponseEntity buildRegStatusExceptionResponse(Exception ex) { + + RegSyncResponseDTO response = new RegSyncResponseDTO(); + Throwable e = ex; + + if (Objects.isNull(response.getId())) { + response.setId(env.getProperty(REG_SYNC_SERVICE_ID)); + } + if (e instanceof BaseCheckedException) + + { + List errorCodes = ((BaseCheckedException) e).getCodes(); + List errorTexts = ((BaseCheckedException) e).getErrorTexts(); + + List errors = errorTexts.parallelStream().map(errMsg -> new SyncErrorDTO(errorCodes.get(errorTexts.indexOf(errMsg)), errMsg)).distinct().collect(Collectors.toList()); + + response.setErrors(errors); + } + if (e instanceof BaseUncheckedException) { + List errorCodes = ((BaseUncheckedException) e).getCodes(); + List errorTexts = ((BaseUncheckedException) e).getErrorTexts(); + + List errors = errorTexts.parallelStream() + .map(errMsg -> new SyncErrorDTO(errorCodes.get(errorTexts.indexOf(errMsg)), errMsg)).distinct() + .collect(Collectors.toList()); + + response.setErrors(errors); + } + + response.setResponsetime(DateUtils.getUTCCurrentDateTimeString(env.getProperty(DATETIME_PATTERN))); + response.setVersion(env.getProperty(REG_SYNC_APPLICATION_VERSION)); + response.setResponse(null); + + if(isEnabled) { + HttpHeaders headers = new HttpHeaders(); + String res=null; + try { + res=objectMapper.writeValueAsString(response); + } catch (Exception e1) { + + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(),LoggerFileConstant.APPLICATIONID.toString(),PlatformErrorMessages.RPR_RGS_JSON_MAPPING_EXCEPTION.getCode(),PlatformErrorMessages.RPR_RGS_JSON_MAPPING_EXCEPTION.getMessage()); + RegStatusAppException reg1=new RegStatusAppException(PlatformErrorMessages.RPR_RGS_JSON_MAPPING_EXCEPTION, ex); + return buildRegStatusExceptionResponse(reg1); + + } + headers.add(RESPONSE_SIGNATURE,digitalSignatureUtility.getDigitalSignature(res)); + return ResponseEntity.ok().headers(headers).body(res); + } + return ResponseEntity.status(HttpStatus.OK).body(response); + + } + + +} diff --git a/registration-processor/init/registration-processor-registration-status-service/src/test/java/io/mosip/registration/processor/status/api/controller/InternalAuthDelegateServicesControllerTest.java b/registration-processor/init/registration-processor-registration-status-service/src/test/java/io/mosip/registration/processor/status/api/controller/InternalAuthDelegateServicesControllerTest.java index e9e47822f6c..b853cc9f701 100644 --- a/registration-processor/init/registration-processor-registration-status-service/src/test/java/io/mosip/registration/processor/status/api/controller/InternalAuthDelegateServicesControllerTest.java +++ b/registration-processor/init/registration-processor-registration-status-service/src/test/java/io/mosip/registration/processor/status/api/controller/InternalAuthDelegateServicesControllerTest.java @@ -1,144 +1,147 @@ -package io.mosip.registration.processor.status.api.controller; - -import static org.junit.Assert.assertEquals; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyString; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -import javax.servlet.http.Cookie; - -import org.json.simple.JSONObject; -import org.json.simple.parser.JSONParser; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mockito; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.boot.autoconfigure.ImportAutoConfiguration; -import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.mock.mockito.MockBean; -import org.springframework.cloud.autoconfigure.RefreshAutoConfiguration; -import org.springframework.http.MediaType; -import org.springframework.security.test.context.support.WithMockUser; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.TestPropertySource; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.MvcResult; -import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import org.springframework.web.client.RestTemplate; -import org.springframework.web.context.WebApplicationContext; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; - -import io.mosip.registration.processor.core.auth.dto.AuthRequestDTO; -import io.mosip.registration.processor.core.auth.dto.AuthResponseDTO; -import io.mosip.registration.processor.core.auth.dto.ResponseDTO; -import io.mosip.registration.processor.core.exception.ApisResourceAccessException; -import io.mosip.registration.processor.status.api.config.RegistrationStatusConfigTest; -import io.mosip.registration.processor.status.service.InternalAuthDelegateService; -import io.mosip.registration.processor.status.service.impl.RegistrationStatusServiceImpl; -import io.mosip.registration.processor.status.service.impl.SyncRegistrationServiceImpl; -import io.mosip.registration.processor.status.utilities.RegistrationUtility; - -@RunWith(SpringRunner.class) -@SpringBootTest -@AutoConfigureMockMvc -@ContextConfiguration(classes = RegistrationStatusConfigTest.class) -@TestPropertySource(locations = "classpath:application.properties") -@ImportAutoConfiguration(RefreshAutoConfiguration.class) -public class InternalAuthDelegateServicesControllerTest { - - @MockBean - @Qualifier("selfTokenRestTemplate") - private RestTemplate restTemplate; - - @InjectMocks - InternalAuthDelegateServicesController internalAuthDelegateServicesController = new InternalAuthDelegateServicesController(); - - @Autowired - private MockMvc mockMvc; - - @Autowired - private WebApplicationContext webApplicationContext; - - @MockBean - private InternalAuthDelegateService internalAuthDelegateService; - - @MockBean - private RegistrationStatusServiceImpl registrationStatusService; - - @MockBean - SyncRegistrationServiceImpl syncRegistrationService; - - @MockBean - RegistrationUtility registrationUtility; - - Gson gson = new GsonBuilder().serializeNulls().create(); - - AuthRequestDTO authRequestDTO = new AuthRequestDTO(); - AuthResponseDTO authResponse = new AuthResponseDTO(); - ResponseDTO responseDto = new ResponseDTO(); - - @Before - public void setUp() throws JsonProcessingException, ApisResourceAccessException { - - mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); - authRequestDTO.setEnv("Staging"); - authRequestDTO.setIndividualId("45128164920495"); - authRequestDTO.setIndividualIdType("UIN"); - authRequestDTO.setRequest("BFijjscahGoaaol"); - - responseDto.setAuthStatus(true); - authResponse.setId(""); - authResponse.setResponse(responseDto); - } - - @Test - @WithMockUser(value = "admin", roles = "REGISTRATION_ADMIN") - public void testAuthDelegateController() throws Exception { - - String authRequestDTOJson = gson.toJson(authRequestDTO); - Mockito.when(internalAuthDelegateService.authenticate(any(), any())).thenReturn(authResponse); - MvcResult result = this.mockMvc - .perform(post("/auth").accept(MediaType.APPLICATION_JSON_VALUE) - .header("timestamp", "2019-05-07T05:13:55.704Z").contentType(MediaType.APPLICATION_JSON_VALUE) - .content(authRequestDTOJson.getBytes()).cookie(new Cookie("Authorization", authRequestDTOJson))) - .andExpect(status().isOk()).andReturn(); - String resultContent = result.getResponse().getContentAsString(); - JSONObject object = (JSONObject) new JSONParser().parse(resultContent); - JSONObject responseDto = (JSONObject) object.get("response"); - assertEquals(responseDto.get("authStatus").toString(), "true"); - } - - @Test - @WithMockUser(value = "admin", roles = "REGISTRATION_ADMIN") - public void testAuthDelegateFailureController() throws Exception { - - String authRequestDTOJson = gson.toJson(authRequestDTO); - Mockito.when(internalAuthDelegateService.authenticate(any(), any())).thenReturn(authResponse); - this.mockMvc.perform(post("/auth").accept(MediaType.APPLICATION_JSON_VALUE) - .header("timestamp", "2019-05-07T05:13:55.704Z").contentType(MediaType.APPLICATION_JSON_VALUE) - .cookie(new Cookie("Authorization", authRequestDTOJson))).andExpect(status().isBadRequest()); - } - - @Test - @WithMockUser(value = "admin", roles = "REGISTRATION_ADMIN") - public void getCertificateTestController() throws Exception { - - Mockito.when(internalAuthDelegateService.getCertificate(anyString(), any(), any())).thenReturn(""); - this.mockMvc - .perform(get("/getCertificate").accept(MediaType.APPLICATION_JSON_VALUE) - .header("timestamp", "2019-05-07T05:13:55.704Z").contentType(MediaType.APPLICATION_JSON_VALUE) - .param("applicationId", "REG_CLIENT").param("referenceId", "KERNEL")) - .andExpect(status().isOk()); - } - -} +package io.mosip.registration.processor.status.api.controller; + +import static org.junit.Assert.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import javax.servlet.http.Cookie; + +import org.json.simple.JSONObject; +import org.json.simple.parser.JSONParser; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mockito; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.boot.autoconfigure.ImportAutoConfiguration; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.cloud.autoconfigure.RefreshAutoConfiguration; +import org.springframework.http.MediaType; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.TestPropertySource; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.MvcResult; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.client.RestTemplate; +import org.springframework.web.context.WebApplicationContext; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +import io.mosip.registration.processor.core.auth.dto.AuthRequestDTO; +import io.mosip.registration.processor.core.auth.dto.AuthResponseDTO; +import io.mosip.registration.processor.core.auth.dto.ResponseDTO; +import io.mosip.registration.processor.core.exception.ApisResourceAccessException; +import io.mosip.registration.processor.status.api.config.RegistrationStatusConfigTest; +import io.mosip.registration.processor.status.service.InternalAuthDelegateService; +import io.mosip.registration.processor.status.service.impl.RegistrationStatusServiceImpl; +import io.mosip.registration.processor.status.service.impl.SyncRegistrationServiceImpl; +import io.mosip.registration.processor.status.utilities.RegistrationUtility; + +@RunWith(SpringRunner.class) +@SpringBootTest +@AutoConfigureMockMvc +@ContextConfiguration(classes = RegistrationStatusConfigTest.class) +@TestPropertySource(locations = "classpath:application.properties") +@ImportAutoConfiguration(RefreshAutoConfiguration.class) +public class InternalAuthDelegateServicesControllerTest { + + @MockBean + @Qualifier("selfTokenRestTemplate") + private RestTemplate restTemplate; + + @InjectMocks + InternalAuthDelegateServicesController internalAuthDelegateServicesController = new InternalAuthDelegateServicesController(); + + @Autowired + private MockMvc mockMvc; + + @Autowired + private WebApplicationContext webApplicationContext; + + @MockBean + private InternalAuthDelegateService internalAuthDelegateService; + + @MockBean + private RegistrationStatusServiceImpl registrationStatusService; + + @MockBean + SyncRegistrationServiceImpl syncRegistrationService; + + @MockBean + RegistrationUtility registrationUtility; + + + ObjectMapper obj=new ObjectMapper(); + + + AuthRequestDTO authRequestDTO = new AuthRequestDTO(); + AuthResponseDTO authResponse = new AuthResponseDTO(); + ResponseDTO responseDto = new ResponseDTO(); + + @Before + public void setUp() throws JsonProcessingException, ApisResourceAccessException { + + mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); + authRequestDTO.setEnv("Staging"); + authRequestDTO.setIndividualId("45128164920495"); + authRequestDTO.setIndividualIdType("UIN"); + authRequestDTO.setRequest("BFijjscahGoaaol"); + + responseDto.setAuthStatus(true); + authResponse.setId(""); + authResponse.setResponse(responseDto); + obj.setSerializationInclusion(JsonInclude.Include.NON_NULL); + } + + @Test + @WithMockUser(value = "admin", roles = "REGISTRATION_ADMIN") + public void testAuthDelegateController() throws Exception { + + String authRequestDTOJson = obj.writeValueAsString(authRequestDTO); + Mockito.when(internalAuthDelegateService.authenticate(any(), any())).thenReturn(authResponse); + MvcResult result = this.mockMvc + .perform(post("/auth").accept(MediaType.APPLICATION_JSON_VALUE) + .header("timestamp", "2019-05-07T05:13:55.704Z").contentType(MediaType.APPLICATION_JSON_VALUE) + .content(authRequestDTOJson.getBytes()).cookie(new Cookie("Authorization", authRequestDTOJson))) + .andExpect(status().isOk()).andReturn(); + String resultContent = result.getResponse().getContentAsString(); + JSONObject object = (JSONObject) new JSONParser().parse(resultContent); + JSONObject responseDto = (JSONObject) object.get("response"); + assertEquals(responseDto.get("authStatus").toString(), "true"); + } + + @Test + @WithMockUser(value = "admin", roles = "REGISTRATION_ADMIN") + public void testAuthDelegateFailureController() throws Exception { + + String authRequestDTOJson = obj.writeValueAsString(authRequestDTO); + Mockito.when(internalAuthDelegateService.authenticate(any(), any())).thenReturn(authResponse); + this.mockMvc.perform(post("/auth").accept(MediaType.APPLICATION_JSON_VALUE) + .header("timestamp", "2019-05-07T05:13:55.704Z").contentType(MediaType.APPLICATION_JSON_VALUE) + .cookie(new Cookie("Authorization", authRequestDTOJson))).andExpect(status().isBadRequest()); + } + + @Test + @WithMockUser(value = "admin", roles = "REGISTRATION_ADMIN") + public void getCertificateTestController() throws Exception { + + Mockito.when(internalAuthDelegateService.getCertificate(anyString(), any(), any())).thenReturn(""); + this.mockMvc + .perform(get("/getCertificate").accept(MediaType.APPLICATION_JSON_VALUE) + .header("timestamp", "2019-05-07T05:13:55.704Z").contentType(MediaType.APPLICATION_JSON_VALUE) + .param("applicationId", "REG_CLIENT").param("referenceId", "KERNEL")) + .andExpect(status().isOk()); + } + +} diff --git a/registration-processor/init/registration-processor-registration-status-service/src/test/java/io/mosip/registration/processor/status/api/controller/PacketExternalStatusControllerTest.java b/registration-processor/init/registration-processor-registration-status-service/src/test/java/io/mosip/registration/processor/status/api/controller/PacketExternalStatusControllerTest.java index 002e66f17b2..d1ced51a2fd 100644 --- a/registration-processor/init/registration-processor-registration-status-service/src/test/java/io/mosip/registration/processor/status/api/controller/PacketExternalStatusControllerTest.java +++ b/registration-processor/init/registration-processor-registration-status-service/src/test/java/io/mosip/registration/processor/status/api/controller/PacketExternalStatusControllerTest.java @@ -1,158 +1,160 @@ -package io.mosip.registration.processor.status.api.controller; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.doNothing; -import static org.mockito.Mockito.when; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -import java.util.ArrayList; -import java.util.List; - -import javax.servlet.http.Cookie; - -import org.json.simple.JSONArray; -import org.json.simple.JSONObject; -import org.json.simple.parser.JSONParser; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.ArgumentMatchers; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.boot.autoconfigure.ImportAutoConfiguration; -import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.mock.mockito.MockBean; -import org.springframework.cloud.autoconfigure.RefreshAutoConfiguration; -import org.springframework.core.env.Environment; -import org.springframework.http.MediaType; -import org.springframework.security.test.context.support.WithMockUser; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.TestPropertySource; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.MvcResult; -import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import org.springframework.web.client.RestTemplate; -import org.springframework.web.context.WebApplicationContext; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; - -import io.mosip.kernel.core.util.DateUtils; -import io.mosip.registration.processor.core.exception.ApisResourceAccessException; -import io.mosip.registration.processor.core.util.DigitalSignatureUtility; -import io.mosip.registration.processor.status.api.config.RegistrationStatusConfigTest; -import io.mosip.registration.processor.status.dto.PacketExternalStatusDTO; -import io.mosip.registration.processor.status.dto.PacketExternalStatusRequestDTO; -import io.mosip.registration.processor.status.dto.PacketExternalStatusSubRequestDTO; -import io.mosip.registration.processor.status.service.PacketExternalStatusService; -import io.mosip.registration.processor.status.service.impl.RegistrationStatusServiceImpl; -import io.mosip.registration.processor.status.service.impl.SyncRegistrationServiceImpl; -import io.mosip.registration.processor.status.utilities.RegistrationUtility; -import io.mosip.registration.processor.status.validator.PacketExternalStatusRequestValidator; - -@RunWith(SpringRunner.class) -@SpringBootTest -@AutoConfigureMockMvc -@ContextConfiguration(classes = RegistrationStatusConfigTest.class) -@TestPropertySource(locations = "classpath:application.properties") -@ImportAutoConfiguration(RefreshAutoConfiguration.class) -public class PacketExternalStatusControllerTest { - - @MockBean - @Qualifier("selfTokenRestTemplate") - private RestTemplate restTemplate; - - @InjectMocks - PacketExternalStatusController packetExternalStatusController = new PacketExternalStatusController(); - - @MockBean - PacketExternalStatusService packetExternalStatusService; - - @MockBean - RegistrationStatusServiceImpl registrationStatusService; - - @Autowired - private MockMvc mockMvc; - - @Autowired - private WebApplicationContext webApplicationContext; - - @MockBean - PacketExternalStatusRequestValidator packetStatusRequestValidator; - - @MockBean - SyncRegistrationServiceImpl syncRegistrationService; - - @MockBean - DigitalSignatureUtility digitalSignatureUtility; - - @MockBean - RegistrationUtility registrationUtility; - - @Mock - private Environment env; - - private String packetExternalStatusRequestToJson; - - Gson gson = new GsonBuilder().serializeNulls().create(); - - PacketExternalStatusRequestDTO packetExternalStatusRequestDTO; - - @Before - public void setUp() throws JsonProcessingException, ApisResourceAccessException { - - mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); - when(env.getProperty("mosip.registration.processor.packet.external.status.id")) - .thenReturn("mosip.registration.packet.external.status"); - when(env.getProperty("mosip.registration.processor.datetime.pattern")) - .thenReturn("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); - when(env.getProperty("mosip.registration.processor.packet.external.status.version")).thenReturn("1.0"); - - PacketExternalStatusSubRequestDTO packetExternalStatusSubRequestDTO = new PacketExternalStatusSubRequestDTO(); - packetExternalStatusSubRequestDTO.setPacketId("test1"); - PacketExternalStatusSubRequestDTO packetExternalStatusSubRequestDTO1 = new PacketExternalStatusSubRequestDTO(); - packetExternalStatusSubRequestDTO1.setPacketId("test2"); - List requestList = new ArrayList<>(); - requestList.add(packetExternalStatusSubRequestDTO); - requestList.add(packetExternalStatusSubRequestDTO1); - packetExternalStatusRequestDTO = new PacketExternalStatusRequestDTO(); - packetExternalStatusRequestDTO.setId("mosip.registration.packet.external.status"); - packetExternalStatusRequestDTO.setVersion("1.0"); - packetExternalStatusRequestDTO - .setRequesttime(DateUtils.getUTCCurrentDateTimeString("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")); - packetExternalStatusRequestDTO.setRequest(requestList); - packetExternalStatusRequestToJson = gson.toJson(packetExternalStatusRequestDTO); - PacketExternalStatusDTO packetExternalStatusDTO = new PacketExternalStatusDTO(); - packetExternalStatusDTO.setPacketId("test1"); - packetExternalStatusDTO.setStatusCode("PROCESSED"); - List packetExternalStatusDTOList = new ArrayList(); - packetExternalStatusDTOList.add(packetExternalStatusDTO); - Mockito.doReturn(packetExternalStatusDTOList).when(packetExternalStatusService) - .getByPacketIds(ArgumentMatchers.any()); - } - - @Test - @WithMockUser(value = "resident", roles = "RESIDENT") - public void packetExternalStatusSuccessTest() throws Exception { - doNothing().when(packetStatusRequestValidator).validate((packetExternalStatusRequestDTO), - "mosip.registration.packet.external.status"); - Mockito.doReturn("test").when(digitalSignatureUtility).getDigitalSignature(ArgumentMatchers.any()); - MvcResult result = this.mockMvc.perform(post("/packetexternalstatus").accept(MediaType.APPLICATION_JSON_VALUE) - .cookie(new Cookie("Authorization", packetExternalStatusRequestToJson)).contentType(MediaType.APPLICATION_JSON_VALUE) - .content(packetExternalStatusRequestToJson.getBytes()).header("timestamp", "2019-05-07T05:13:55.704Z")) - .andExpect(status().isOk()).andReturn(); - String resultContent = result.getResponse().getContentAsString(); - JSONObject object = (JSONObject) new JSONParser().parse(resultContent); - JSONArray responseObject = (JSONArray) object.get("response"); - JSONObject packetExternalStatusDTO = (JSONObject) responseObject.get(0); - assertEquals(packetExternalStatusDTO.get("packetId").toString(), "test1"); - assertEquals(packetExternalStatusDTO.get("statusCode").toString(), "PROCESSED"); - } -} +package io.mosip.registration.processor.status.api.controller; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import java.util.ArrayList; +import java.util.List; + +import javax.servlet.http.Cookie; + +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; +import org.json.simple.parser.JSONParser; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentMatchers; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.Spy; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.boot.autoconfigure.ImportAutoConfiguration; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.cloud.autoconfigure.RefreshAutoConfiguration; +import org.springframework.core.env.Environment; +import org.springframework.http.MediaType; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.TestPropertySource; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.MvcResult; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.client.RestTemplate; +import org.springframework.web.context.WebApplicationContext; + +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +import io.mosip.kernel.core.util.DateUtils; +import io.mosip.registration.processor.core.exception.ApisResourceAccessException; +import io.mosip.registration.processor.core.util.DigitalSignatureUtility; +import io.mosip.registration.processor.status.api.config.RegistrationStatusConfigTest; +import io.mosip.registration.processor.status.dto.PacketExternalStatusDTO; +import io.mosip.registration.processor.status.dto.PacketExternalStatusRequestDTO; +import io.mosip.registration.processor.status.dto.PacketExternalStatusSubRequestDTO; +import io.mosip.registration.processor.status.service.PacketExternalStatusService; +import io.mosip.registration.processor.status.service.impl.RegistrationStatusServiceImpl; +import io.mosip.registration.processor.status.service.impl.SyncRegistrationServiceImpl; +import io.mosip.registration.processor.status.utilities.RegistrationUtility; +import io.mosip.registration.processor.status.validator.PacketExternalStatusRequestValidator; + +@RunWith(SpringRunner.class) +@SpringBootTest +@AutoConfigureMockMvc +@ContextConfiguration(classes = RegistrationStatusConfigTest.class) +@TestPropertySource(locations = "classpath:application.properties") +@ImportAutoConfiguration(RefreshAutoConfiguration.class) +public class PacketExternalStatusControllerTest { + + @MockBean + @Qualifier("selfTokenRestTemplate") + private RestTemplate restTemplate; + + @InjectMocks + PacketExternalStatusController packetExternalStatusController = new PacketExternalStatusController(); + + @MockBean + PacketExternalStatusService packetExternalStatusService; + + @MockBean + RegistrationStatusServiceImpl registrationStatusService; + + @Autowired + private MockMvc mockMvc; + + @Autowired + private WebApplicationContext webApplicationContext; + + @MockBean + PacketExternalStatusRequestValidator packetStatusRequestValidator; + + @MockBean + SyncRegistrationServiceImpl syncRegistrationService; + + @MockBean + DigitalSignatureUtility digitalSignatureUtility; + + @MockBean + RegistrationUtility registrationUtility; + + @Spy + ObjectMapper objectMapper; + + @Mock + private Environment env; + + private String packetExternalStatusRequestToJson; + + PacketExternalStatusRequestDTO packetExternalStatusRequestDTO; + + @Before + public void setUp() throws JsonProcessingException, ApisResourceAccessException { + objectMapper.setSerializationInclusion(Include.USE_DEFAULTS); + mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); + when(env.getProperty("mosip.registration.processor.packet.external.status.id")) + .thenReturn("mosip.registration.packet.external.status"); + when(env.getProperty("mosip.registration.processor.datetime.pattern")) + .thenReturn("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); + when(env.getProperty("mosip.registration.processor.packet.external.status.version")).thenReturn("1.0"); + + PacketExternalStatusSubRequestDTO packetExternalStatusSubRequestDTO = new PacketExternalStatusSubRequestDTO(); + packetExternalStatusSubRequestDTO.setPacketId("test1"); + PacketExternalStatusSubRequestDTO packetExternalStatusSubRequestDTO1 = new PacketExternalStatusSubRequestDTO(); + packetExternalStatusSubRequestDTO1.setPacketId("test2"); + List requestList = new ArrayList<>(); + requestList.add(packetExternalStatusSubRequestDTO); + requestList.add(packetExternalStatusSubRequestDTO1); + packetExternalStatusRequestDTO = new PacketExternalStatusRequestDTO(); + packetExternalStatusRequestDTO.setId("mosip.registration.packet.external.status"); + packetExternalStatusRequestDTO.setVersion("1.0"); + packetExternalStatusRequestDTO + .setRequesttime(DateUtils.getUTCCurrentDateTimeString("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")); + packetExternalStatusRequestDTO.setRequest(requestList); + packetExternalStatusRequestToJson = objectMapper.writeValueAsString(packetExternalStatusRequestDTO); + PacketExternalStatusDTO packetExternalStatusDTO = new PacketExternalStatusDTO(); + packetExternalStatusDTO.setPacketId("test1"); + packetExternalStatusDTO.setStatusCode("PROCESSED"); + List packetExternalStatusDTOList = new ArrayList(); + packetExternalStatusDTOList.add(packetExternalStatusDTO); + Mockito.doReturn(packetExternalStatusDTOList).when(packetExternalStatusService) + .getByPacketIds(ArgumentMatchers.any()); + } + + @Test + @WithMockUser(value = "resident", roles = "RESIDENT") + public void packetExternalStatusSuccessTest() throws Exception { + doNothing().when(packetStatusRequestValidator).validate((packetExternalStatusRequestDTO), + "mosip.registration.packet.external.status"); + Mockito.doReturn("test").when(digitalSignatureUtility).getDigitalSignature(ArgumentMatchers.any()); + MvcResult result = this.mockMvc.perform(post("/packetexternalstatus").accept(MediaType.APPLICATION_JSON_VALUE) + .cookie(new Cookie("Authorization", packetExternalStatusRequestToJson)).contentType(MediaType.APPLICATION_JSON_VALUE) + .content(packetExternalStatusRequestToJson.getBytes()).header("timestamp", "2019-05-07T05:13:55.704Z")) + .andExpect(status().isOk()).andReturn(); + String resultContent = result.getResponse().getContentAsString(); + JSONObject object = (JSONObject) new JSONParser().parse(resultContent); + JSONArray responseObject = (JSONArray) object.get("response"); + JSONObject packetExternalStatusDTO = (JSONObject) responseObject.get(0); + assertEquals(packetExternalStatusDTO.get("packetId").toString(), "test1"); + assertEquals(packetExternalStatusDTO.get("statusCode").toString(), "PROCESSED"); + } +} diff --git a/registration-processor/init/registration-processor-registration-status-service/src/test/java/io/mosip/registration/processor/status/api/controller/RegistrationExternalStatusControllerTest.java b/registration-processor/init/registration-processor-registration-status-service/src/test/java/io/mosip/registration/processor/status/api/controller/RegistrationExternalStatusControllerTest.java index 01d1815b391..6bcc18e99b3 100644 --- a/registration-processor/init/registration-processor-registration-status-service/src/test/java/io/mosip/registration/processor/status/api/controller/RegistrationExternalStatusControllerTest.java +++ b/registration-processor/init/registration-processor-registration-status-service/src/test/java/io/mosip/registration/processor/status/api/controller/RegistrationExternalStatusControllerTest.java @@ -1,234 +1,230 @@ -package io.mosip.registration.processor.status.api.controller; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.doNothing; -import static org.mockito.Mockito.when; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -import java.util.ArrayList; -import java.util.List; - -import javax.servlet.http.Cookie; - -import io.mosip.registration.processor.core.util.exception.DigitalSignatureException; -import org.json.simple.JSONArray; -import org.json.simple.JSONObject; -import org.json.simple.parser.JSONParser; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.ArgumentMatchers; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.boot.autoconfigure.ImportAutoConfiguration; -import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.mock.mockito.MockBean; -import org.springframework.cloud.autoconfigure.RefreshAutoConfiguration; -import org.springframework.core.env.Environment; -import org.springframework.http.MediaType; -import org.springframework.security.test.context.support.WithMockUser; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.TestPropertySource; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.MvcResult; -import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import org.springframework.web.client.RestTemplate; -import org.springframework.web.context.WebApplicationContext; -import org.springframework.web.util.NestedServletException; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; - -import io.mosip.kernel.core.util.DateUtils; -import io.mosip.registration.processor.core.exception.ApisResourceAccessException; -import io.mosip.registration.processor.core.util.DigitalSignatureUtility; -import io.mosip.registration.processor.core.workflow.dto.SortInfo; -import io.mosip.registration.processor.status.api.config.RegistrationStatusConfigTest; -import io.mosip.registration.processor.status.dto.FilterInfo; -import io.mosip.registration.processor.status.dto.RegistrationExternalStatusRequestDTO; -import io.mosip.registration.processor.status.dto.RegistrationExternalStatusSubRequestDto; -import io.mosip.registration.processor.status.dto.RegistrationStatusDto; -import io.mosip.registration.processor.status.dto.SearchInfo; -import io.mosip.registration.processor.status.exception.RegStatusAppException; -import io.mosip.registration.processor.status.service.impl.RegistrationStatusServiceImpl; -import io.mosip.registration.processor.status.service.impl.SyncRegistrationServiceImpl; -import io.mosip.registration.processor.status.utilities.RegistrationUtility; -import io.mosip.registration.processor.status.validator.LostRidRequestValidator; -import io.mosip.registration.processor.status.validator.RegistrationExternalStatusRequestValidator; -import io.mosip.registration.processor.status.validator.RegistrationStatusRequestValidator; -import io.mosip.registration.processor.status.validator.RegistrationSyncRequestValidator; - -@RunWith(SpringRunner.class) -@SpringBootTest -@AutoConfigureMockMvc -@ContextConfiguration(classes = RegistrationStatusConfigTest.class) -@TestPropertySource(locations = "classpath:application.properties") -@ImportAutoConfiguration(RefreshAutoConfiguration.class) -public class RegistrationExternalStatusControllerTest { - - @MockBean - @Qualifier("selfTokenRestTemplate") - private RestTemplate restTemplate; - - @Autowired - private MockMvc mockMvc; - - @Autowired - private WebApplicationContext webApplicationContext; - - @InjectMocks - RegistrationExternalStatusController registrationExternalStatusController = new RegistrationExternalStatusController(); - - @MockBean - RegistrationExternalStatusRequestValidator registrationExternalStatusRequestValidator; - - @MockBean - RegistrationStatusRequestValidator registrationStatusRequestValidator; - - /** The registration status service. */ - @MockBean - RegistrationStatusServiceImpl registrationStatusService; - - @MockBean - SyncRegistrationServiceImpl syncRegistrationService; - - @MockBean - DigitalSignatureUtility digitalSignatureUtility; - - @MockBean - LostRidRequestValidator lostRidRequestValidator; - - @MockBean - RegistrationUtility registrationUtility; - - @MockBean - private RegistrationSyncRequestValidator syncrequestvalidator; - - @Mock - private Environment env; - - @Autowired - public ObjectMapper objectMapper; - - /** The registration dto list. */ - private List registrationDtoList; - private List registrationDtoList1; - - RegistrationExternalStatusRequestDTO registrationExternalStatusRequestDTO; - - /** The array to json. */ - private String regStatusToJson; - Gson gson = new GsonBuilder().serializeNulls().create(); - - @Before - public void setUp() throws JsonProcessingException, ApisResourceAccessException { - - mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); - when(env.getProperty("mosip.registration.processor.registration.external.status.id")) - .thenReturn("mosip.registration.external.status"); - when(env.getProperty("mosip.registration.processor.datetime.pattern")) - .thenReturn("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); - when(env.getProperty("mosip.registration.processor.registration.external.status.version")).thenReturn("1.0"); - List request = new ArrayList<>(); - RegistrationExternalStatusSubRequestDto regitrationid1 = new RegistrationExternalStatusSubRequestDto(); - RegistrationExternalStatusSubRequestDto regitrationid2 = new RegistrationExternalStatusSubRequestDto(); - RegistrationExternalStatusSubRequestDto regitrationid3 = new RegistrationExternalStatusSubRequestDto(); - regitrationid1.setRegistrationId("1001"); - regitrationid2.setRegistrationId("1002"); - regitrationid3.setRegistrationId("1003"); - request.add(regitrationid1); - request.add(regitrationid2); - request.add(regitrationid3); - registrationExternalStatusRequestDTO = new RegistrationExternalStatusRequestDTO(); - registrationExternalStatusRequestDTO.setRequest(request); - registrationExternalStatusRequestDTO.setId("mosip.registration.external.status"); - registrationExternalStatusRequestDTO.setVersion("1.0"); - registrationExternalStatusRequestDTO - .setRequesttime(DateUtils.getUTCCurrentDateTimeString("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")); - regStatusToJson = gson.toJson(registrationExternalStatusRequestDTO); - registrationDtoList = new ArrayList<>(); - registrationDtoList1 = new ArrayList<>(); - RegistrationStatusDto registrationStatusDto1 = new RegistrationStatusDto(); - registrationStatusDto1.setRegistrationId("1001"); - registrationStatusDto1.setStatusCode("PROCESSED"); - - RegistrationStatusDto registrationStatusDto2 = new RegistrationStatusDto(); - registrationStatusDto2.setRegistrationId("1002"); - registrationStatusDto2.setStatusCode("PROCESSED"); - - registrationDtoList.add(registrationStatusDto1); - registrationDtoList1.add(registrationStatusDto2); - - Mockito.doReturn(registrationDtoList).when(registrationStatusService).getExternalStatusByIds(ArgumentMatchers.any()); - Mockito.doReturn(registrationDtoList1).when(syncRegistrationService).getExternalStatusByIds(ArgumentMatchers.any()); - SearchInfo searchInfo = new SearchInfo(); - List filterinfos = new ArrayList(); - List sortInfos = new ArrayList(); - FilterInfo filterInfo = new FilterInfo(); - filterInfo.setColumnName("name"); - filterInfo.setValue("mosip"); - filterinfos.add(filterInfo); - SortInfo sortInfo = new SortInfo(); - sortInfo.setSortField("createDateTime"); - sortInfo.setSortType("desc"); - sortInfos.add(sortInfo); - searchInfo.setFilters(filterinfos); - searchInfo.setSort(sortInfos); - - Mockito.doReturn(registrationDtoList).when(registrationStatusService).getByIds(ArgumentMatchers.any()); - Mockito.doReturn(registrationDtoList1).when(syncRegistrationService).getByIds(ArgumentMatchers.any()); - - } - - /** - * Search success test. - * - */ - @Test - @WithMockUser(value = "resident", roles = "RESIDENT") - public void searchSuccessTest() throws Exception { - doNothing().when(registrationExternalStatusRequestValidator).validate((registrationExternalStatusRequestDTO), - "mosip.registration.external.status"); - Mockito.doReturn("test").when(digitalSignatureUtility).getDigitalSignature(ArgumentMatchers.any()); - - MvcResult result = this.mockMvc.perform(post("/externalstatus/search").accept(MediaType.APPLICATION_JSON_VALUE) - .cookie(new Cookie("Authorization", regStatusToJson)).contentType(MediaType.APPLICATION_JSON_VALUE) - .content(regStatusToJson.getBytes()).header("timestamp", "2019-05-07T05:13:55.704Z")) - .andExpect(status().isOk()).andReturn(); - String resultContent = result.getResponse().getContentAsString(); - JSONObject object = (JSONObject) new JSONParser().parse(resultContent); - JSONArray responseObject = (JSONArray) object.get("response"); - JSONArray errorObject = (JSONArray) object.get("errors"); - JSONObject registrationStatusDto = (JSONObject) responseObject.get(0); - JSONObject registrationStatusDto1 = (JSONObject) responseObject.get(1); - JSONObject registrationStatusErrorDto = (JSONObject) errorObject.get(0); - - assertEquals(registrationStatusDto.get("registrationId").toString(), "1001"); - assertEquals(registrationStatusDto.get("statusCode").toString(), "PROCESSED"); - assertEquals(registrationStatusDto1.get("registrationId").toString(), "1002"); - assertEquals(registrationStatusDto1.get("statusCode").toString(), "PROCESSED"); - assertEquals(registrationStatusErrorDto.get("registrationId").toString(), "1003"); - assertEquals(registrationStatusErrorDto.get("errorMessage").toString(), "RID Not Found"); - } - - @Test(expected = NestedServletException.class) - @WithMockUser(value = "resident", roles = "RESIDENT") - public void searchRegstatusException() throws Exception { - - Mockito.doThrow(new RegStatusAppException()).when(registrationExternalStatusRequestValidator) - .validate(ArgumentMatchers.any(), ArgumentMatchers.any()); - this.mockMvc.perform(post("/externalstatus/search").accept(MediaType.APPLICATION_JSON_VALUE) - .cookie(new Cookie("Authorization", regStatusToJson)).contentType(MediaType.APPLICATION_JSON_VALUE) - .content(regStatusToJson.getBytes()).header("timestamp", "2019-05-07T05:13:55.704Z")) - .andExpect(status().isInternalServerError()); - } - -} +package io.mosip.registration.processor.status.api.controller; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import java.util.ArrayList; +import java.util.List; + +import javax.servlet.http.Cookie; + +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; +import org.json.simple.parser.JSONParser; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentMatchers; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.boot.autoconfigure.ImportAutoConfiguration; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.cloud.autoconfigure.RefreshAutoConfiguration; +import org.springframework.core.env.Environment; +import org.springframework.http.MediaType; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.TestPropertySource; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.MvcResult; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.client.RestTemplate; +import org.springframework.web.context.WebApplicationContext; +import org.springframework.web.util.NestedServletException; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +import io.mosip.kernel.core.util.DateUtils; +import io.mosip.registration.processor.core.exception.ApisResourceAccessException; +import io.mosip.registration.processor.core.util.DigitalSignatureUtility; +import io.mosip.registration.processor.core.workflow.dto.SortInfo; +import io.mosip.registration.processor.status.api.config.RegistrationStatusConfigTest; +import io.mosip.registration.processor.status.dto.FilterInfo; +import io.mosip.registration.processor.status.dto.RegistrationExternalStatusRequestDTO; +import io.mosip.registration.processor.status.dto.RegistrationExternalStatusSubRequestDto; +import io.mosip.registration.processor.status.dto.RegistrationStatusDto; +import io.mosip.registration.processor.status.dto.SearchInfo; +import io.mosip.registration.processor.status.exception.RegStatusAppException; +import io.mosip.registration.processor.status.service.impl.RegistrationStatusServiceImpl; +import io.mosip.registration.processor.status.service.impl.SyncRegistrationServiceImpl; +import io.mosip.registration.processor.status.utilities.RegistrationUtility; +import io.mosip.registration.processor.status.validator.LostRidRequestValidator; +import io.mosip.registration.processor.status.validator.RegistrationExternalStatusRequestValidator; +import io.mosip.registration.processor.status.validator.RegistrationStatusRequestValidator; +import io.mosip.registration.processor.status.validator.RegistrationSyncRequestValidator; + +@RunWith(SpringRunner.class) +@SpringBootTest +@AutoConfigureMockMvc +@ContextConfiguration(classes = RegistrationStatusConfigTest.class) +@TestPropertySource(locations = "classpath:application.properties") +@ImportAutoConfiguration(RefreshAutoConfiguration.class) +public class RegistrationExternalStatusControllerTest { + + @MockBean + @Qualifier("selfTokenRestTemplate") + private RestTemplate restTemplate; + + @Autowired + private MockMvc mockMvc; + + @Autowired + private WebApplicationContext webApplicationContext; + + @InjectMocks + RegistrationExternalStatusController registrationExternalStatusController = new RegistrationExternalStatusController(); + + @MockBean + RegistrationExternalStatusRequestValidator registrationExternalStatusRequestValidator; + + @MockBean + RegistrationStatusRequestValidator registrationStatusRequestValidator; + + /** The registration status service. */ + @MockBean + RegistrationStatusServiceImpl registrationStatusService; + + @MockBean + SyncRegistrationServiceImpl syncRegistrationService; + + @MockBean + DigitalSignatureUtility digitalSignatureUtility; + + @MockBean + LostRidRequestValidator lostRidRequestValidator; + + @MockBean + RegistrationUtility registrationUtility; + + @MockBean + private RegistrationSyncRequestValidator syncrequestvalidator; + + @Mock + private Environment env; + + @Autowired + public ObjectMapper objectMapper; + + /** The registration dto list. */ + private List registrationDtoList; + private List registrationDtoList1; + + RegistrationExternalStatusRequestDTO registrationExternalStatusRequestDTO; + + /** The array to json. */ + private String regStatusToJson; + + @Before + public void setUp() throws JsonProcessingException, ApisResourceAccessException { + + mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); + when(env.getProperty("mosip.registration.processor.registration.external.status.id")) + .thenReturn("mosip.registration.external.status"); + when(env.getProperty("mosip.registration.processor.datetime.pattern")) + .thenReturn("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); + when(env.getProperty("mosip.registration.processor.registration.external.status.version")).thenReturn("1.0"); + List request = new ArrayList<>(); + RegistrationExternalStatusSubRequestDto regitrationid1 = new RegistrationExternalStatusSubRequestDto(); + RegistrationExternalStatusSubRequestDto regitrationid2 = new RegistrationExternalStatusSubRequestDto(); + RegistrationExternalStatusSubRequestDto regitrationid3 = new RegistrationExternalStatusSubRequestDto(); + regitrationid1.setRegistrationId("1001"); + regitrationid2.setRegistrationId("1002"); + regitrationid3.setRegistrationId("1003"); + request.add(regitrationid1); + request.add(regitrationid2); + request.add(regitrationid3); + registrationExternalStatusRequestDTO = new RegistrationExternalStatusRequestDTO(); + registrationExternalStatusRequestDTO.setRequest(request); + registrationExternalStatusRequestDTO.setId("mosip.registration.external.status"); + registrationExternalStatusRequestDTO.setVersion("1.0"); + registrationExternalStatusRequestDTO + .setRequesttime(DateUtils.getUTCCurrentDateTimeString("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")); + regStatusToJson =objectMapper.writeValueAsString(registrationExternalStatusRequestDTO); + registrationDtoList = new ArrayList<>(); + registrationDtoList1 = new ArrayList<>(); + RegistrationStatusDto registrationStatusDto1 = new RegistrationStatusDto(); + registrationStatusDto1.setRegistrationId("1001"); + registrationStatusDto1.setStatusCode("PROCESSED"); + + RegistrationStatusDto registrationStatusDto2 = new RegistrationStatusDto(); + registrationStatusDto2.setRegistrationId("1002"); + registrationStatusDto2.setStatusCode("PROCESSED"); + + registrationDtoList.add(registrationStatusDto1); + registrationDtoList1.add(registrationStatusDto2); + + Mockito.doReturn(registrationDtoList).when(registrationStatusService).getExternalStatusByIds(ArgumentMatchers.any()); + Mockito.doReturn(registrationDtoList1).when(syncRegistrationService).getExternalStatusByIds(ArgumentMatchers.any()); + SearchInfo searchInfo = new SearchInfo(); + List filterinfos = new ArrayList(); + List sortInfos = new ArrayList(); + FilterInfo filterInfo = new FilterInfo(); + filterInfo.setColumnName("name"); + filterInfo.setValue("mosip"); + filterinfos.add(filterInfo); + SortInfo sortInfo = new SortInfo(); + sortInfo.setSortField("createDateTime"); + sortInfo.setSortType("desc"); + sortInfos.add(sortInfo); + searchInfo.setFilters(filterinfos); + searchInfo.setSort(sortInfos); + + Mockito.doReturn(registrationDtoList).when(registrationStatusService).getByIds(ArgumentMatchers.any()); + Mockito.doReturn(registrationDtoList1).when(syncRegistrationService).getByIds(ArgumentMatchers.any()); + + } + + /** + * Search success test. + * + */ + @Test + @WithMockUser(value = "resident", roles = "RESIDENT") + public void searchSuccessTest() throws Exception { + doNothing().when(registrationExternalStatusRequestValidator).validate((registrationExternalStatusRequestDTO), + "mosip.registration.external.status"); + Mockito.doReturn("test").when(digitalSignatureUtility).getDigitalSignature(ArgumentMatchers.any()); + + MvcResult result = this.mockMvc.perform(post("/externalstatus/search").accept(MediaType.APPLICATION_JSON_VALUE) + .cookie(new Cookie("Authorization", regStatusToJson)).contentType(MediaType.APPLICATION_JSON_VALUE) + .content(regStatusToJson.getBytes()).header("timestamp", "2019-05-07T05:13:55.704Z")) + .andExpect(status().isOk()).andReturn(); + String resultContent = result.getResponse().getContentAsString(); + JSONObject object = (JSONObject) new JSONParser().parse(resultContent); + JSONArray responseObject = (JSONArray) object.get("response"); + JSONArray errorObject = (JSONArray) object.get("errors"); + JSONObject registrationStatusDto = (JSONObject) responseObject.get(0); + JSONObject registrationStatusDto1 = (JSONObject) responseObject.get(1); + JSONObject registrationStatusErrorDto = (JSONObject) errorObject.get(0); + + assertEquals(registrationStatusDto.get("registrationId").toString(), "1001"); + assertEquals(registrationStatusDto.get("statusCode").toString(), "PROCESSED"); + assertEquals(registrationStatusDto1.get("registrationId").toString(), "1002"); + assertEquals(registrationStatusDto1.get("statusCode").toString(), "PROCESSED"); + assertEquals(registrationStatusErrorDto.get("registrationId").toString(), "1003"); + assertEquals(registrationStatusErrorDto.get("errorMessage").toString(), "RID Not Found"); + } + + @Test(expected = NestedServletException.class) + @WithMockUser(value = "resident", roles = "RESIDENT") + public void searchRegstatusException() throws Exception { + + Mockito.doThrow(new RegStatusAppException()).when(registrationExternalStatusRequestValidator) + .validate(ArgumentMatchers.any(), ArgumentMatchers.any()); + this.mockMvc.perform(post("/externalstatus/search").accept(MediaType.APPLICATION_JSON_VALUE) + .cookie(new Cookie("Authorization", regStatusToJson)).contentType(MediaType.APPLICATION_JSON_VALUE) + .content(regStatusToJson.getBytes()).header("timestamp", "2019-05-07T05:13:55.704Z")) + .andExpect(status().isInternalServerError()); + } + +} diff --git a/registration-processor/init/registration-processor-registration-status-service/src/test/java/io/mosip/registration/processor/status/api/controller/RegistrationStatusAndSyncControllerTest.java b/registration-processor/init/registration-processor-registration-status-service/src/test/java/io/mosip/registration/processor/status/api/controller/RegistrationStatusAndSyncControllerTest.java index ecaed3d8f45..8ef00343489 100644 --- a/registration-processor/init/registration-processor-registration-status-service/src/test/java/io/mosip/registration/processor/status/api/controller/RegistrationStatusAndSyncControllerTest.java +++ b/registration-processor/init/registration-processor-registration-status-service/src/test/java/io/mosip/registration/processor/status/api/controller/RegistrationStatusAndSyncControllerTest.java @@ -1,418 +1,416 @@ -package io.mosip.registration.processor.status.api.controller; - -import static org.mockito.Mockito.doNothing; -import static org.mockito.Mockito.when; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -import java.time.LocalDateTime; -import java.util.ArrayList; -import java.util.List; - -import javax.servlet.http.Cookie; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.ArgumentMatchers; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.boot.autoconfigure.ImportAutoConfiguration; -import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.mock.mockito.MockBean; -import org.springframework.cloud.autoconfigure.RefreshAutoConfiguration; -import org.springframework.core.env.Environment; -import org.springframework.http.MediaType; -import org.springframework.security.test.context.support.WithMockUser; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.TestPropertySource; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import org.springframework.web.client.RestTemplate; -import org.springframework.web.context.WebApplicationContext; -import org.springframework.web.util.NestedServletException; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; - -import io.mosip.kernel.core.util.DateUtils; -import io.mosip.registration.processor.core.digital.signature.dto.SignResponseDto; -import io.mosip.registration.processor.core.exception.ApisResourceAccessException; -import io.mosip.registration.processor.core.exception.WorkFlowSearchException; -import io.mosip.registration.processor.core.http.ResponseWrapper; -import io.mosip.registration.processor.core.spi.restclient.RegistrationProcessorRestClientService; -import io.mosip.registration.processor.core.util.DigitalSignatureUtility; -import io.mosip.registration.processor.core.util.exception.DigitalSignatureException; -import io.mosip.registration.processor.core.workflow.dto.SortInfo; -import io.mosip.registration.processor.status.api.config.RegistrationStatusConfigTest; -import io.mosip.registration.processor.status.dto.FilterInfo; -import io.mosip.registration.processor.status.dto.LostRidRequestDto; -import io.mosip.registration.processor.status.dto.RegistrationStatusDto; -import io.mosip.registration.processor.status.dto.RegistrationStatusRequestDTO; -import io.mosip.registration.processor.status.dto.RegistrationStatusSubRequestDto; -import io.mosip.registration.processor.status.dto.RegistrationSyncRequestDTO; -import io.mosip.registration.processor.status.dto.SearchInfo; -import io.mosip.registration.processor.status.dto.SyncRegistrationDto; -import io.mosip.registration.processor.status.dto.SyncResponseDto; -import io.mosip.registration.processor.status.dto.SyncResponseFailDto; -import io.mosip.registration.processor.status.dto.SyncResponseFailureDto; -import io.mosip.registration.processor.status.dto.SyncResponseSuccessDto; -import io.mosip.registration.processor.status.exception.RegStatusAppException; -import io.mosip.registration.processor.status.service.impl.RegistrationStatusServiceImpl; -import io.mosip.registration.processor.status.service.impl.SyncRegistrationServiceImpl; -import io.mosip.registration.processor.status.utilities.RegistrationUtility; -import io.mosip.registration.processor.status.validator.LostRidRequestValidator; -import io.mosip.registration.processor.status.validator.RegistrationStatusRequestValidator; -import io.mosip.registration.processor.status.validator.RegistrationSyncRequestValidator; - -/** - * The Class RegistrationStatusControllerTest. - * - * @author M1047487 - */ -@RunWith(SpringRunner.class) -@SpringBootTest -@AutoConfigureMockMvc -@ContextConfiguration(classes = RegistrationStatusConfigTest.class) -@TestPropertySource(locations = "classpath:application.properties") -@ImportAutoConfiguration(RefreshAutoConfiguration.class) -public class RegistrationStatusAndSyncControllerTest { - - @MockBean - @Qualifier("selfTokenRestTemplate") - private RestTemplate restTemplate; - - /** The registration status controller. */ - @InjectMocks - RegistrationStatusController registrationStatusController = new RegistrationStatusController(); - - @InjectMocks - RegistrationSyncController registrationSyncController = new RegistrationSyncController(); - - /** The registration status service. */ - @MockBean - RegistrationStatusServiceImpl registrationStatusService; - - /** The sync registration service. */ - @MockBean - SyncRegistrationServiceImpl syncRegistrationService; - - /** The sync registration dto. */ - @MockBean - SyncRegistrationDto syncRegistrationDto; - - RegistrationStatusRequestDTO registrationStatusRequestDTO; - /** The mock mvc. */ - @Autowired - private MockMvc mockMvc; - - @Autowired - private WebApplicationContext webApplicationContext; - - /** The registration dto list. */ - private List registrationDtoList; - - /** The registration dto list. */ - private List registrationDtoList1; - - /** The array to json. */ - private String regStatusToJson; - - private String lostRidReqToJson; - - @MockBean - private RegistrationProcessorRestClientService reprcrestclient; - - @MockBean - RegistrationUtility registrationUtility; - - private ResponseWrapper dto = new ResponseWrapper(); - - private SignResponseDto signresponse = new SignResponseDto(); - RegistrationSyncRequestDTO registrationSyncRequestDTO; - - @Mock - private Environment env; - - LostRidRequestDto lostRidRequestDto; - - - @MockBean - RegistrationStatusRequestValidator registrationStatusRequestValidator; - - @MockBean - LostRidRequestValidator lostRidRequestValidator; - - @MockBean - private RegistrationSyncRequestValidator syncrequestvalidator; - - Gson gson = new GsonBuilder().serializeNulls().create(); - private List syncResponseDtoList; - private List list; - SyncResponseFailureDto syncResponseFailureDto = new SyncResponseFailureDto(); - - // @Autowired -// private WebApplicationContext context; - - // @Autowired - //// private Filter springSecurityFilterChain; - - /** - * Sets the up. - * - * @throws JsonProcessingException - * @throws ApisResourceAccessException - */ - @Before - public void setUp() throws JsonProcessingException, ApisResourceAccessException { - - mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); - when(env.getProperty("mosip.registration.processor.registration.status.id")) - .thenReturn("mosip.registration.status"); - when(env.getProperty("mosip.registration.processor.lostrid.id")).thenReturn("mosip.registration.lostrid"); - when(env.getProperty("mosip.registration.processor.lostrid.version")).thenReturn("1.0"); - when(env.getProperty("mosip.registration.processor.datetime.pattern")) - .thenReturn("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); - when(env.getProperty("mosip.registration.processor.application.version")).thenReturn("1.0"); - List request = new ArrayList<>(); - RegistrationStatusSubRequestDto regitrationid1 = new RegistrationStatusSubRequestDto(); - RegistrationStatusSubRequestDto regitrationid2 = new RegistrationStatusSubRequestDto(); - RegistrationStatusSubRequestDto regitrationid3 = new RegistrationStatusSubRequestDto(); - regitrationid1.setRegistrationId("1001"); - regitrationid2.setRegistrationId("1002"); - regitrationid3.setRegistrationId("1003"); - request.add(regitrationid1); - request.add(regitrationid2); - request.add(regitrationid3); - registrationStatusRequestDTO = new RegistrationStatusRequestDTO(); - registrationStatusRequestDTO.setRequest(request); - registrationStatusRequestDTO.setId("mosip.registration.status"); - registrationStatusRequestDTO.setVersion("1.0"); - registrationStatusRequestDTO - .setRequesttime(DateUtils.getUTCCurrentDateTimeString("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")); - regStatusToJson = gson.toJson(registrationStatusRequestDTO); - registrationDtoList = new ArrayList<>(); - registrationDtoList1 = new ArrayList<>(); - RegistrationStatusDto registrationStatusDto1 = new RegistrationStatusDto(); - registrationStatusDto1.setRegistrationId("1001"); - - RegistrationStatusDto registrationStatusDto2 = new RegistrationStatusDto(); - registrationStatusDto2.setRegistrationId("1002"); - - registrationDtoList.add(registrationStatusDto1); - registrationDtoList1.add(registrationStatusDto2); - SyncResponseSuccessDto syncResponseDto = new SyncResponseSuccessDto(); - SyncResponseFailureDto syncResponseFailureDto = new SyncResponseFailureDto(); - syncResponseDto.setRegistrationId("1001"); - - syncResponseDto.setStatus("SUCCESS"); - syncResponseFailureDto.setRegistrationId("1001"); - - syncResponseFailureDto.setMessage("Registartion Id's are successfully synched in Sync table"); - syncResponseFailureDto.setStatus("FAILURE"); - syncResponseFailureDto.setErrorCode("Test"); - syncResponseDtoList = new ArrayList<>(); - syncResponseDtoList.add(syncResponseDto); - syncResponseDtoList.add(syncResponseFailureDto); - list = new ArrayList<>(); - SyncRegistrationDto syncRegistrationDto = new SyncRegistrationDto(); - syncRegistrationDto = new SyncRegistrationDto(); - syncRegistrationDto.setRegistrationId("1002"); - syncRegistrationDto.setLangCode("eng"); - syncRegistrationDto.setIsActive(true); - list.add(syncRegistrationDto); - registrationSyncRequestDTO = new RegistrationSyncRequestDTO(); - registrationSyncRequestDTO.setRequest(list); - registrationSyncRequestDTO.setId("mosip.registration.sync"); - registrationSyncRequestDTO.setVersion("1.0"); - registrationSyncRequestDTO - .setRequesttime(DateUtils.getUTCCurrentDateTimeString("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")); - lostRidRequestDto = new LostRidRequestDto(); - lostRidRequestDto.setId("mosip.registration.lostrid"); - lostRidRequestDto.setVersion("1.0"); - lostRidRequestDto.setRequesttime(LocalDateTime.now().toString()); - SearchInfo searchInfo = new SearchInfo(); - List filterinfos = new ArrayList(); - List sortInfos = new ArrayList(); - FilterInfo filterInfo = new FilterInfo(); - filterInfo.setColumnName("name"); - filterInfo.setValue("mosip"); - filterinfos.add(filterInfo); - SortInfo sortInfo = new SortInfo(); - sortInfo.setSortField("createDateTime"); - sortInfo.setSortType("desc"); - sortInfos.add(sortInfo); - searchInfo.setFilters(filterinfos); - searchInfo.setSort(sortInfos); - lostRidReqToJson = gson.toJson(lostRidRequestDto); - - Mockito.doReturn(registrationDtoList).when(registrationStatusService).getByIds(ArgumentMatchers.any()); - Mockito.doReturn(registrationDtoList1).when(syncRegistrationService).getByIds(ArgumentMatchers.any()); - - signresponse.setSignature("abcd"); - dto.setResponse(signresponse); - Mockito.when(reprcrestclient.postApi(ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.any(), - ArgumentMatchers.any(), ArgumentMatchers.any())).thenReturn(dto); - Mockito.when(syncRegistrationService.sync(ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.any())).thenReturn(syncResponseDtoList); - Mockito.when( - syncrequestvalidator.validate(ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.any())) - .thenReturn(Boolean.TRUE); - - } - - /** - * Search success test. - * - * @throws Exception - * the exception - */ - @Test - @WithMockUser(value = "resident", roles = "RESIDENT") - public void searchSuccessTest() throws Exception { - doNothing().when(registrationStatusRequestValidator).validate((registrationStatusRequestDTO), - "mosip.registration.status"); - - this.mockMvc.perform(post("/search").accept(MediaType.APPLICATION_JSON_VALUE) - .cookie(new Cookie("Authorization", regStatusToJson)).contentType(MediaType.APPLICATION_JSON_VALUE) - .content(regStatusToJson.getBytes()).header("timestamp", "2019-05-07T05:13:55.704Z")) - .andExpect(status().isOk()); - } - - @Test - @WithMockUser(value = "resident", roles = "RESIDENT") - public void searchRegstatusException() throws Exception { - - Mockito.doThrow(new RegStatusAppException()).when(registrationStatusRequestValidator) - .validate(ArgumentMatchers.any(), ArgumentMatchers.any()); - this.mockMvc.perform(post("/search").accept(MediaType.APPLICATION_JSON_VALUE) - .cookie(new Cookie("Authorization", regStatusToJson)).contentType(MediaType.APPLICATION_JSON_VALUE) - .content(regStatusToJson.getBytes()).header("timestamp", "2019-05-07T05:13:55.704Z")) - .andExpect(status().isOk()); - } - - @Test - @WithMockUser(value = "resident", roles = "RESIDENT") - public void testSyncController() throws Exception { - - RegistrationSyncRequestDTO registrationSyncRequestDTO = new RegistrationSyncRequestDTO(); - List request = new ArrayList(); - SyncRegistrationDto syncRegistrationDto = new SyncRegistrationDto("45128164920495", "NEW", null, null, "eng"); - request.add(syncRegistrationDto); - String requestJson = gson.toJson(request); - - List syncResponseList = new ArrayList<>(); - SyncResponseDto syncResponseDto = new SyncResponseDto(); - syncResponseDto.setStatus("true"); - syncResponseDto.setRegistrationId("45128164920495"); - syncResponseList.add(syncResponseDto); - - Mockito.when(syncRegistrationService.decryptAndGetSyncRequest(ArgumentMatchers.any(), ArgumentMatchers.any(), - ArgumentMatchers.any(), ArgumentMatchers.any())).thenReturn(registrationSyncRequestDTO); - Mockito.when( - syncrequestvalidator.validate(ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.any())) - .thenReturn(true); - Mockito.when( - syncRegistrationService.sync(ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.any())) - .thenReturn(syncResponseList); - this.mockMvc.perform( - post("/sync").accept(MediaType.APPLICATION_JSON_VALUE).header("timestamp", "2019-05-07T05:13:55.704Z") - .header("Center-Machine-RefId", "abcd").contentType(MediaType.APPLICATION_JSON_VALUE) - .content(requestJson.getBytes()).cookie(new Cookie("Authorization", requestJson))) - .andExpect(status().isOk()); - } - - @Test - @WithMockUser(value = "resident", roles = "RESIDENT") - public void testSyncV2Controller() throws Exception { - - RegistrationSyncRequestDTO registrationSyncRequestDTO = new RegistrationSyncRequestDTO(); - List request = new ArrayList(); - SyncRegistrationDto syncRegistrationDto = new SyncRegistrationDto("45128164920495", "NEW", null, null, "eng"); - request.add(syncRegistrationDto); - String requestJson = gson.toJson(request); - - List syncResponseList = new ArrayList<>(); - SyncResponseDto syncResponseDto = new SyncResponseDto(); - syncResponseDto.setStatus("true"); - syncResponseDto.setRegistrationId("45128164920495"); - syncResponseList.add(syncResponseDto); - - Mockito.when(syncRegistrationService.decryptAndGetSyncRequest(ArgumentMatchers.any(), ArgumentMatchers.any(), - ArgumentMatchers.any(), ArgumentMatchers.any())).thenReturn(registrationSyncRequestDTO); - Mockito.when( - syncrequestvalidator.validate(ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.any())) - .thenReturn(true); - Mockito.when( - syncRegistrationService.syncV2(ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.any())) - .thenReturn(syncResponseList); - this.mockMvc.perform( - post("/syncV2").accept(MediaType.APPLICATION_JSON_VALUE).header("timestamp", "2019-05-07T05:13:55.704Z") - .header("Center-Machine-RefId", "abcd").contentType(MediaType.APPLICATION_JSON_VALUE) - .content(requestJson.getBytes()).cookie(new Cookie("Authorization", requestJson))) - .andExpect(status().isOk()); - } - - @Test - public void testBuildRegistrationSyncResponse() throws JsonProcessingException { - List syncResponseDtoList = new ArrayList<>(); - syncResponseFailureDto.setStatus("SUCCESS"); - syncResponseDtoList.add(syncResponseFailureDto); - registrationSyncController.buildRegistrationSyncResponse(syncResponseDtoList); - - } - - @Test - public void testBuildRegistrationSyncResponse1() throws JsonProcessingException { - List syncResponseDtoList = new ArrayList<>(); - SyncResponseFailDto syncResponseFailDto = new SyncResponseFailDto(); - SyncResponseFailureDto syncResponseDto = new SyncResponseFailureDto(); - - syncResponseDto.setStatus("Fail"); - syncResponseDtoList.add(syncResponseDto); - - syncResponseFailDto.setStatus("Fail"); - syncResponseDtoList.add(syncResponseFailDto); - registrationSyncController.buildRegistrationSyncResponse(syncResponseDtoList); - - } - - @Test - @WithMockUser(value = "admin", roles = "REGISTRATION_ADMIN") - public void lostRidSuccessTest() throws Exception { - doNothing().when(lostRidRequestValidator).validate((lostRidRequestDto)); - - this.mockMvc.perform(post("/lostridsearch").accept(MediaType.APPLICATION_JSON_VALUE) - .cookie(new Cookie("Authorization", lostRidReqToJson)).contentType(MediaType.APPLICATION_JSON_VALUE) - .content(lostRidReqToJson.getBytes()).header("timestamp", "2019-05-07T05:13:55.704Z")) - .andExpect(status().isOk()); - } - - @Test - @WithMockUser(value = "admin", roles = "REGISTRATION_ADMIN") - public void lostRidRegstatusException() throws Exception { - - Mockito.doThrow(new RegStatusAppException()).when(lostRidRequestValidator).validate(ArgumentMatchers.any()); - this.mockMvc.perform(post("/lostridsearch").accept(MediaType.APPLICATION_JSON_VALUE) - .cookie(new Cookie("Authorization", lostRidReqToJson)).contentType(MediaType.APPLICATION_JSON_VALUE) - .content(lostRidReqToJson.getBytes()).header("timestamp", "2019-05-07T05:13:55.704Z")) - .andExpect(status().isOk()); - } - - @Test - @WithMockUser(value = "admin", roles = "REGISTRATION_ADMIN") - public void lostRidWorkFlowSearchException() throws Exception { - - Mockito.doThrow(new WorkFlowSearchException("ERR-001", "exception occured")).when(lostRidRequestValidator) - .validate(ArgumentMatchers.any()); - this.mockMvc.perform(post("/lostridsearch").accept(MediaType.APPLICATION_JSON_VALUE) - .cookie(new Cookie("Authorization", lostRidReqToJson)).contentType(MediaType.APPLICATION_JSON_VALUE) - .content(lostRidReqToJson.getBytes()).header("timestamp", "2019-05-07T05:13:55.704Z")) - .andExpect(status().isOk()); - } +package io.mosip.registration.processor.status.api.controller; + +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.List; + +import javax.servlet.http.Cookie; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentMatchers; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.Spy; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.boot.autoconfigure.ImportAutoConfiguration; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.cloud.autoconfigure.RefreshAutoConfiguration; +import org.springframework.core.env.Environment; +import org.springframework.http.MediaType; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.TestPropertySource; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.client.RestTemplate; +import org.springframework.web.context.WebApplicationContext; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +import io.mosip.kernel.core.util.DateUtils; +import io.mosip.registration.processor.core.digital.signature.dto.SignResponseDto; +import io.mosip.registration.processor.core.exception.ApisResourceAccessException; +import io.mosip.registration.processor.core.exception.WorkFlowSearchException; +import io.mosip.registration.processor.core.http.ResponseWrapper; +import io.mosip.registration.processor.core.spi.restclient.RegistrationProcessorRestClientService; +import io.mosip.registration.processor.core.workflow.dto.SortInfo; +import io.mosip.registration.processor.status.api.config.RegistrationStatusConfigTest; +import io.mosip.registration.processor.status.dto.FilterInfo; +import io.mosip.registration.processor.status.dto.LostRidRequestDto; +import io.mosip.registration.processor.status.dto.RegistrationStatusDto; +import io.mosip.registration.processor.status.dto.RegistrationStatusRequestDTO; +import io.mosip.registration.processor.status.dto.RegistrationStatusSubRequestDto; +import io.mosip.registration.processor.status.dto.RegistrationSyncRequestDTO; +import io.mosip.registration.processor.status.dto.SearchInfo; +import io.mosip.registration.processor.status.dto.SyncRegistrationDto; +import io.mosip.registration.processor.status.dto.SyncResponseDto; +import io.mosip.registration.processor.status.dto.SyncResponseFailDto; +import io.mosip.registration.processor.status.dto.SyncResponseFailureDto; +import io.mosip.registration.processor.status.dto.SyncResponseSuccessDto; +import io.mosip.registration.processor.status.exception.RegStatusAppException; +import io.mosip.registration.processor.status.service.impl.RegistrationStatusServiceImpl; +import io.mosip.registration.processor.status.service.impl.SyncRegistrationServiceImpl; +import io.mosip.registration.processor.status.utilities.RegistrationUtility; +import io.mosip.registration.processor.status.validator.LostRidRequestValidator; +import io.mosip.registration.processor.status.validator.RegistrationStatusRequestValidator; +import io.mosip.registration.processor.status.validator.RegistrationSyncRequestValidator; + +/** + * The Class RegistrationStatusControllerTest. + * + * @author M1047487 + */ +@RunWith(SpringRunner.class) +@SpringBootTest +@AutoConfigureMockMvc +@ContextConfiguration(classes = RegistrationStatusConfigTest.class) +@TestPropertySource(locations = "classpath:application.properties") +@ImportAutoConfiguration(RefreshAutoConfiguration.class) +public class RegistrationStatusAndSyncControllerTest { + + @MockBean + @Qualifier("selfTokenRestTemplate") + private RestTemplate restTemplate; + + /** The registration status controller. */ + @InjectMocks + RegistrationStatusController registrationStatusController = new RegistrationStatusController(); + + @InjectMocks + RegistrationSyncController registrationSyncController = new RegistrationSyncController(); + + /** The registration status service. */ + @MockBean + RegistrationStatusServiceImpl registrationStatusService; + + /** The sync registration service. */ + @MockBean + SyncRegistrationServiceImpl syncRegistrationService; + + /** The sync registration dto. */ + @MockBean + SyncRegistrationDto syncRegistrationDto; + + RegistrationStatusRequestDTO registrationStatusRequestDTO; + /** The mock mvc. */ + @Autowired + private MockMvc mockMvc; + + @Autowired + private WebApplicationContext webApplicationContext; + + /** The registration dto list. */ + private List registrationDtoList; + + /** The registration dto list. */ + private List registrationDtoList1; + + /** The array to json. */ + private String regStatusToJson; + + private String lostRidReqToJson; + + @MockBean + private RegistrationProcessorRestClientService reprcrestclient; + + @MockBean + RegistrationUtility registrationUtility; + + private ResponseWrapper dto = new ResponseWrapper(); + + private SignResponseDto signresponse = new SignResponseDto(); + RegistrationSyncRequestDTO registrationSyncRequestDTO; + + @Mock + private Environment env; + + LostRidRequestDto lostRidRequestDto; + + + @MockBean + RegistrationStatusRequestValidator registrationStatusRequestValidator; + + @MockBean + LostRidRequestValidator lostRidRequestValidator; + + @MockBean + private RegistrationSyncRequestValidator syncrequestvalidator; + + @Autowired + ObjectMapper objMp=new ObjectMapper(); + private List syncResponseDtoList; + private List list; + SyncResponseFailureDto syncResponseFailureDto = new SyncResponseFailureDto(); + + // @Autowired +// private WebApplicationContext context; + + // @Autowired + //// private Filter springSecurityFilterChain; + + /** + * Sets the up. + * + * @throws JsonProcessingException + * @throws ApisResourceAccessException + */ + @Before + public void setUp() throws JsonProcessingException, ApisResourceAccessException { + ObjectMapper objMp=new ObjectMapper(); + mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); + when(env.getProperty("mosip.registration.processor.registration.status.id")) + .thenReturn("mosip.registration.status"); + when(env.getProperty("mosip.registration.processor.lostrid.id")).thenReturn("mosip.registration.lostrid"); + when(env.getProperty("mosip.registration.processor.lostrid.version")).thenReturn("1.0"); + when(env.getProperty("mosip.registration.processor.datetime.pattern")) + .thenReturn("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); + when(env.getProperty("mosip.registration.processor.application.version")).thenReturn("1.0"); + List request = new ArrayList<>(); + RegistrationStatusSubRequestDto regitrationid1 = new RegistrationStatusSubRequestDto(); + RegistrationStatusSubRequestDto regitrationid2 = new RegistrationStatusSubRequestDto(); + RegistrationStatusSubRequestDto regitrationid3 = new RegistrationStatusSubRequestDto(); + regitrationid1.setRegistrationId("1001"); + regitrationid2.setRegistrationId("1002"); + regitrationid3.setRegistrationId("1003"); + request.add(regitrationid1); + request.add(regitrationid2); + request.add(regitrationid3); + registrationStatusRequestDTO = new RegistrationStatusRequestDTO(); + registrationStatusRequestDTO.setRequest(request); + registrationStatusRequestDTO.setId("mosip.registration.status"); + registrationStatusRequestDTO.setVersion("1.0"); + registrationStatusRequestDTO + .setRequesttime(DateUtils.getUTCCurrentDateTimeString("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")); + regStatusToJson = objMp.writeValueAsString(registrationStatusRequestDTO); + registrationDtoList = new ArrayList<>(); + registrationDtoList1 = new ArrayList<>(); + RegistrationStatusDto registrationStatusDto1 = new RegistrationStatusDto(); + registrationStatusDto1.setRegistrationId("1001"); + + RegistrationStatusDto registrationStatusDto2 = new RegistrationStatusDto(); + registrationStatusDto2.setRegistrationId("1002"); + + registrationDtoList.add(registrationStatusDto1); + registrationDtoList1.add(registrationStatusDto2); + SyncResponseSuccessDto syncResponseDto = new SyncResponseSuccessDto(); + SyncResponseFailureDto syncResponseFailureDto = new SyncResponseFailureDto(); + syncResponseDto.setRegistrationId("1001"); + + syncResponseDto.setStatus("SUCCESS"); + syncResponseFailureDto.setRegistrationId("1001"); + + syncResponseFailureDto.setMessage("Registartion Id's are successfully synched in Sync table"); + syncResponseFailureDto.setStatus("FAILURE"); + syncResponseFailureDto.setErrorCode("Test"); + syncResponseDtoList = new ArrayList<>(); + syncResponseDtoList.add(syncResponseDto); + syncResponseDtoList.add(syncResponseFailureDto); + list = new ArrayList<>(); + SyncRegistrationDto syncRegistrationDto = new SyncRegistrationDto(); + syncRegistrationDto = new SyncRegistrationDto(); + syncRegistrationDto.setRegistrationId("1002"); + syncRegistrationDto.setLangCode("eng"); + syncRegistrationDto.setIsActive(true); + list.add(syncRegistrationDto); + registrationSyncRequestDTO = new RegistrationSyncRequestDTO(); + registrationSyncRequestDTO.setRequest(list); + registrationSyncRequestDTO.setId("mosip.registration.sync"); + registrationSyncRequestDTO.setVersion("1.0"); + registrationSyncRequestDTO + .setRequesttime(DateUtils.getUTCCurrentDateTimeString("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")); + lostRidRequestDto = new LostRidRequestDto(); + lostRidRequestDto.setId("mosip.registration.lostrid"); + lostRidRequestDto.setVersion("1.0"); + lostRidRequestDto.setRequesttime(LocalDateTime.now().toString()); + SearchInfo searchInfo = new SearchInfo(); + List filterinfos = new ArrayList(); + List sortInfos = new ArrayList(); + FilterInfo filterInfo = new FilterInfo(); + filterInfo.setColumnName("name"); + filterInfo.setValue("mosip"); + filterinfos.add(filterInfo); + SortInfo sortInfo = new SortInfo(); + sortInfo.setSortField("createDateTime"); + sortInfo.setSortType("desc"); + sortInfos.add(sortInfo); + searchInfo.setFilters(filterinfos); + searchInfo.setSort(sortInfos); + lostRidReqToJson =objMp.writeValueAsString(lostRidRequestDto); + + Mockito.doReturn(registrationDtoList).when(registrationStatusService).getByIds(ArgumentMatchers.any()); + Mockito.doReturn(registrationDtoList1).when(syncRegistrationService).getByIds(ArgumentMatchers.any()); + + signresponse.setSignature("abcd"); + dto.setResponse(signresponse); + Mockito.when(reprcrestclient.postApi(ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.any(), + ArgumentMatchers.any(), ArgumentMatchers.any())).thenReturn(dto); + Mockito.when(syncRegistrationService.sync(ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.any())).thenReturn(syncResponseDtoList); + Mockito.when( + syncrequestvalidator.validate(ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.any())) + .thenReturn(Boolean.TRUE); + + } + + /** + * Search success test. + * + * @throws Exception + * the exception + */ + @Test + @WithMockUser(value = "resident", roles = "RESIDENT") + public void searchSuccessTest() throws Exception { + doNothing().when(registrationStatusRequestValidator).validate((registrationStatusRequestDTO), + "mosip.registration.status"); + + this.mockMvc.perform(post("/search").accept(MediaType.APPLICATION_JSON_VALUE) + .cookie(new Cookie("Authorization", regStatusToJson)).contentType(MediaType.APPLICATION_JSON_VALUE) + .content(regStatusToJson.getBytes()).header("timestamp", "2019-05-07T05:13:55.704Z")) + .andExpect(status().isOk()); + } + + @Test + @WithMockUser(value = "resident", roles = "RESIDENT") + public void searchRegstatusException() throws Exception { + + Mockito.doThrow(new RegStatusAppException()).when(registrationStatusRequestValidator) + .validate(ArgumentMatchers.any(), ArgumentMatchers.any()); + this.mockMvc.perform(post("/search").accept(MediaType.APPLICATION_JSON_VALUE) + .cookie(new Cookie("Authorization", regStatusToJson)).contentType(MediaType.APPLICATION_JSON_VALUE) + .content(regStatusToJson.getBytes()).header("timestamp", "2019-05-07T05:13:55.704Z")) + .andExpect(status().isOk()); + } + + @Test + @WithMockUser(value = "resident", roles = "RESIDENT") + public void testSyncController() throws Exception { + + RegistrationSyncRequestDTO registrationSyncRequestDTO = new RegistrationSyncRequestDTO(); + List request = new ArrayList(); + SyncRegistrationDto syncRegistrationDto = new SyncRegistrationDto("45128164920495", "NEW", null, null, "eng"); + request.add(syncRegistrationDto); + String requestJson = objMp.writeValueAsString(request); + + List syncResponseList = new ArrayList<>(); + SyncResponseDto syncResponseDto = new SyncResponseDto(); + syncResponseDto.setStatus("true"); + syncResponseDto.setRegistrationId("45128164920495"); + syncResponseList.add(syncResponseDto); + + Mockito.when(syncRegistrationService.decryptAndGetSyncRequest(ArgumentMatchers.any(), ArgumentMatchers.any(), + ArgumentMatchers.any(), ArgumentMatchers.any())).thenReturn(registrationSyncRequestDTO); + Mockito.when( + syncrequestvalidator.validate(ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.any())) + .thenReturn(true); + Mockito.when( + syncRegistrationService.sync(ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.any())) + .thenReturn(syncResponseList); + this.mockMvc.perform( + post("/sync").accept(MediaType.APPLICATION_JSON_VALUE).header("timestamp", "2019-05-07T05:13:55.704Z") + .header("Center-Machine-RefId", "abcd").contentType(MediaType.APPLICATION_JSON_VALUE) + .content(requestJson.getBytes()).cookie(new Cookie("Authorization", requestJson))) + .andExpect(status().isOk()); + } + + @Test + @WithMockUser(value = "resident", roles = "RESIDENT") + public void testSyncV2Controller() throws Exception { + + RegistrationSyncRequestDTO registrationSyncRequestDTO = new RegistrationSyncRequestDTO(); + List request = new ArrayList(); + SyncRegistrationDto syncRegistrationDto = new SyncRegistrationDto("45128164920495", "NEW", null, null, "eng"); + request.add(syncRegistrationDto); + String requestJson = objMp.writeValueAsString(request); + + List syncResponseList = new ArrayList<>(); + SyncResponseDto syncResponseDto = new SyncResponseDto(); + syncResponseDto.setStatus("true"); + syncResponseDto.setRegistrationId("45128164920495"); + syncResponseList.add(syncResponseDto); + + Mockito.when(syncRegistrationService.decryptAndGetSyncRequest(ArgumentMatchers.any(), ArgumentMatchers.any(), + ArgumentMatchers.any(), ArgumentMatchers.any())).thenReturn(registrationSyncRequestDTO); + Mockito.when( + syncrequestvalidator.validate(ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.any())) + .thenReturn(true); + Mockito.when( + syncRegistrationService.syncV2(ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.any())) + .thenReturn(syncResponseList); + this.mockMvc.perform( + post("/syncV2").accept(MediaType.APPLICATION_JSON_VALUE).header("timestamp", "2019-05-07T05:13:55.704Z") + .header("Center-Machine-RefId", "abcd").contentType(MediaType.APPLICATION_JSON_VALUE) + .content(requestJson.getBytes()).cookie(new Cookie("Authorization", requestJson))) + .andExpect(status().isOk()); + } + + @Test + public void testBuildRegistrationSyncResponse() throws JsonProcessingException { + List syncResponseDtoList = new ArrayList<>(); + syncResponseFailureDto.setStatus("SUCCESS"); + syncResponseDtoList.add(syncResponseFailureDto); + registrationSyncController.buildRegistrationSyncResponse(syncResponseDtoList); + + } + + @Test + public void testBuildRegistrationSyncResponse1() throws JsonProcessingException { + List syncResponseDtoList = new ArrayList<>(); + SyncResponseFailDto syncResponseFailDto = new SyncResponseFailDto(); + SyncResponseFailureDto syncResponseDto = new SyncResponseFailureDto(); + + syncResponseDto.setStatus("Fail"); + syncResponseDtoList.add(syncResponseDto); + + syncResponseFailDto.setStatus("Fail"); + syncResponseDtoList.add(syncResponseFailDto); + registrationSyncController.buildRegistrationSyncResponse(syncResponseDtoList); + + } + + @Test + @WithMockUser(value = "admin", roles = "REGISTRATION_ADMIN") + public void lostRidSuccessTest() throws Exception { + doNothing().when(lostRidRequestValidator).validate((lostRidRequestDto)); + + this.mockMvc.perform(post("/lostridsearch").accept(MediaType.APPLICATION_JSON_VALUE) + .cookie(new Cookie("Authorization", lostRidReqToJson)).contentType(MediaType.APPLICATION_JSON_VALUE) + .content(lostRidReqToJson.getBytes()).header("timestamp", "2019-05-07T05:13:55.704Z")) + .andExpect(status().isOk()); + } + + @Test + @WithMockUser(value = "admin", roles = "REGISTRATION_ADMIN") + public void lostRidRegstatusException() throws Exception { + + Mockito.doThrow(new RegStatusAppException()).when(lostRidRequestValidator).validate(ArgumentMatchers.any()); + this.mockMvc.perform(post("/lostridsearch").accept(MediaType.APPLICATION_JSON_VALUE) + .cookie(new Cookie("Authorization", lostRidReqToJson)).contentType(MediaType.APPLICATION_JSON_VALUE) + .content(lostRidReqToJson.getBytes()).header("timestamp", "2019-05-07T05:13:55.704Z")) + .andExpect(status().isOk()); + } + + @Test + @WithMockUser(value = "admin", roles = "REGISTRATION_ADMIN") + public void lostRidWorkFlowSearchException() throws Exception { + + Mockito.doThrow(new WorkFlowSearchException("ERR-001", "exception occured")).when(lostRidRequestValidator) + .validate(ArgumentMatchers.any()); + this.mockMvc.perform(post("/lostridsearch").accept(MediaType.APPLICATION_JSON_VALUE) + .cookie(new Cookie("Authorization", lostRidReqToJson)).contentType(MediaType.APPLICATION_JSON_VALUE) + .content(lostRidReqToJson.getBytes()).header("timestamp", "2019-05-07T05:13:55.704Z")) + .andExpect(status().isOk()); + } } \ No newline at end of file diff --git a/registration-processor/init/registration-processor-registration-status-service/src/test/resources/application.properties b/registration-processor/init/registration-processor-registration-status-service/src/test/resources/application.properties index 2c4ecb0d01b..e32527456fd 100644 --- a/registration-processor/init/registration-processor-registration-status-service/src/test/resources/application.properties +++ b/registration-processor/init/registration-processor-registration-status-service/src/test/resources/application.properties @@ -1,83 +1,83 @@ -javax.persistence.jdbc.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1 -javax.persistence.jdbc.driver=org.h2.Driver -javax.persistence.jdbc.user=sa -javax.persistence.jdbc.password=sa -hibernate.ddl-auto=update -hibernate.temp.use_jdbc_metadata_defaults = false -hibernate.dialect = org.hibernate.dialect.H2Dialect -registration.processor.landingZone_To_VirusScan_Interval_Threshhold_time=48 -registration.processor.threshold=3 -registration.processor.max.retry=3 -mosip.registration.processor.registration.status.id=mosip.registration.status -mosip.registration.processor.registration.sync.id=mosip.registration.syn -mosip.registration.processor.lostrid.id=mosip.registration.lostrid -mosip.registration.processor.lostrid.version=1.0 -mosip.registration.processor.datetime.pattern=yyyy-MM-dd'T'HH:mm:ss.SSS'Z' -mosip.registration.processor.timezone=GMT -mosip.registration.processor.packet.id=mosip.registration.packet -registration.processor.application.id=REGISTRATION -registration.processor.signature.isEnabled=true -registration.processor.reprocess.elapse.time=21600 -auth.server.validate.url="" -auth.server.admin.validate.url="" -auth.jwt.secret="" -auth.jwt.base="" -iam.datastore.commonname="" - -#Asymmetric algorithm key length -mosip.kernel.keygenerator.asymmetric-key-length=2048 -#Symmetric algorithm key length -mosip.kernel.keygenerator.symmetric-key-length=256 -mosip.kernel.crypto.asymmetric-algorithm-name=RSA/ECB/OAEPWITHSHA-256ANDMGF1PADDING -mosip.kernel.crypto.symmetric-algorithm-name=AES/GCM/PKCS5Padding -mosip.kernel.keygenerator.asymmetric-algorithm-name=RSA -mosip.kernel.keygenerator.symmetric-algorithm-name=AES -mosip.kernel.crypto.gcm-tag-length=128 -mosip.kernel.crypto.hash-algorithm-name=PBKDF2WithHmacSHA512 -mosip.kernel.crypto.sign-algorithm-name=RS256 -mosip.kernel.crypto.hash-symmetric-key-length=256 -mosip.kernel.crypto.hash-iteration=100000 -mosip.auth.adapter.impl.basepackage=io.mosip.kernel.auth.defaultadapter - -ida-internal-auth-uri="" -ida-internal-get-certificate-uri="" - -# Cbeff XSD file name in config server -mosip.kernel.xsdfile=mosip-cbeff.xsd -mosip.kernel.xsdstorage-uri=file:./src/test/resources/ -registration.processor.main-process=NEW -mosip.registration.processor.grace.period=10800 - -server.port=8083 -server.servlet.path=/registrationprocessor/v1/registrationstatus -mosip.registration.processor.postalcode.req.url= -registration.processor.main-processes= -registration.processor.sub-processes= - - -mosip.role.registration.postauth=REGISTRATION_ADMIN,REGISTRATION_SUPERVISOR,REGISTRATION_OFFICER -mosip.role.registration.getgetcertificate=INDIVIDUAL,REGISTRATION_PROCESSOR,REGISTRATION_ADMIN,REGISTRATION_SUPERVISOR,REGISTRATION_OFFICER,PRE_REGISTRATION_ADMIN -mosip.role.registration.postexternalstatussearch=REGISTRATION_ADMIN,REGISTRATION_SUPERVISOR,REGISTRATION_OFFICER,RESIDENT -mosip.role.registration.postpacketexternalstatus=REGISTRATION_ADMIN,REGISTRATION_SUPERVISOR,REGISTRATION_OFFICER,RESIDENT -mosip.role.registration.postsearch=REGISTRATION_ADMIN,REGISTRATION_SUPERVISOR,REGISTRATION_OFFICER,RESIDENT -mosip.role.registration.postlostridsearch=REGISTRATION_ADMIN,REGISTRATION_OFFICER,ZONAL_ADMIN,GLOBAL_ADMIN -mosip.role.registration.postsync=REGISTRATION_ADMIN,REGISTRATION_SUPERVISOR,REGISTRATION_OFFICER,RESIDENT -mosip.role.registration.postsyncv2=REGISTRATION_ADMIN,REGISTRATION_SUPERVISOR,REGISTRATION_OFFICER,RESIDENT - -#Swagger 3.0 -openapi.info.title=Registration Status Service API documentation -openapi.info.description=Registration Status Service API documentation -openapi.info.version=1.0 -openapi.info.license.name=Mosip -openapi.info.license.url=https://docs.mosip.io/platform/license - - -#------OpenApi properties-------- -mosipbox.public.url=http://localhost:8083 -openapi.registrationProcessorStatusService.servers[0].url=${mosipbox.public.url}/registrationprocessor/v1/registrationstatus -openapi.registrationProcessorStatusService.servers[0].description=Registration Processor Status service - -config.server.file.storage.uri= -registration.processor.identityjson= -mosip.kernel.auth.appids.realm.map={prereg:'preregistration',ida:'mosip',registrationclient:'mosip',regproc:'mosip',partner:'mosip',resident:'mosip'} -mosip.registration.processor.lostrid.registrationdate.pattern=yyyy-MM-dd +javax.persistence.jdbc.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1 +javax.persistence.jdbc.driver=org.h2.Driver +javax.persistence.jdbc.user=sa +javax.persistence.jdbc.password=sa +hibernate.ddl-auto=update +hibernate.temp.use_jdbc_metadata_defaults = false +hibernate.dialect = org.hibernate.dialect.H2Dialect +registration.processor.landingZone_To_VirusScan_Interval_Threshhold_time=48 +registration.processor.threshold=3 +registration.processor.max.retry=3 +mosip.registration.processor.registration.status.id=mosip.registration.status +mosip.registration.processor.registration.sync.id=mosip.registration.syn +mosip.registration.processor.lostrid.id=mosip.registration.lostrid +mosip.registration.processor.lostrid.version=1.0 +mosip.registration.processor.datetime.pattern=yyyy-MM-dd'T'HH:mm:ss.SSS'Z' +mosip.registration.processor.timezone=GMT +mosip.registration.processor.packet.id=mosip.registration.packet +registration.processor.application.id=REGISTRATION +registration.processor.signature.isEnabled=true +registration.processor.reprocess.elapse.time=21600 +auth.server.validate.url="" +auth.server.admin.validate.url="" +auth.jwt.secret="" +auth.jwt.base="" +iam.datastore.commonname="" + +#Asymmetric algorithm key length +mosip.kernel.keygenerator.asymmetric-key-length=2048 +#Symmetric algorithm key length +mosip.kernel.keygenerator.symmetric-key-length=256 +mosip.kernel.crypto.asymmetric-algorithm-name=RSA/ECB/OAEPWITHSHA-256ANDMGF1PADDING +mosip.kernel.crypto.symmetric-algorithm-name=AES/GCM/PKCS5Padding +mosip.kernel.keygenerator.asymmetric-algorithm-name=RSA +mosip.kernel.keygenerator.symmetric-algorithm-name=AES +mosip.kernel.crypto.gcm-tag-length=128 +mosip.kernel.crypto.hash-algorithm-name=PBKDF2WithHmacSHA512 +mosip.kernel.crypto.sign-algorithm-name=RS256 +mosip.kernel.crypto.hash-symmetric-key-length=256 +mosip.kernel.crypto.hash-iteration=100000 +mosip.auth.adapter.impl.basepackage=io.mosip.kernel.auth.defaultadapter + +ida-internal-auth-uri=http://ida-internal-service.default:80/idauthentication/v1/internal/auth +ida-internal-get-certificate-uri=http://ida-internal-service.default:80/idauthentication/v1/internal/getCertificate + +# Cbeff XSD file name in config server +mosip.kernel.xsdfile=mosip-cbeff.xsd +mosip.kernel.xsdstorage-uri=file:./src/test/resources/ +registration.processor.main-process=NEW +mosip.registration.processor.grace.period=10800 + +server.port=8083 +server.servlet.path=/registrationprocessor/v1/registrationstatus +mosip.registration.processor.postalcode.req.url= +registration.processor.main-processes= +registration.processor.sub-processes= + + +mosip.role.registration.postauth=REGISTRATION_ADMIN,REGISTRATION_SUPERVISOR,REGISTRATION_OFFICER +mosip.role.registration.getgetcertificate=INDIVIDUAL,REGISTRATION_PROCESSOR,REGISTRATION_ADMIN,REGISTRATION_SUPERVISOR,REGISTRATION_OFFICER,PRE_REGISTRATION_ADMIN +mosip.role.registration.postexternalstatussearch=REGISTRATION_ADMIN,REGISTRATION_SUPERVISOR,REGISTRATION_OFFICER,RESIDENT +mosip.role.registration.postpacketexternalstatus=REGISTRATION_ADMIN,REGISTRATION_SUPERVISOR,REGISTRATION_OFFICER,RESIDENT +mosip.role.registration.postsearch=REGISTRATION_ADMIN,REGISTRATION_SUPERVISOR,REGISTRATION_OFFICER,RESIDENT +mosip.role.registration.postlostridsearch=REGISTRATION_ADMIN,REGISTRATION_OFFICER,ZONAL_ADMIN,GLOBAL_ADMIN +mosip.role.registration.postsync=REGISTRATION_ADMIN,REGISTRATION_SUPERVISOR,REGISTRATION_OFFICER,RESIDENT +mosip.role.registration.postsyncv2=REGISTRATION_ADMIN,REGISTRATION_SUPERVISOR,REGISTRATION_OFFICER,RESIDENT + +#Swagger 3.0 +openapi.info.title=Registration Status Service API documentation +openapi.info.description=Registration Status Service API documentation +openapi.info.version=1.0 +openapi.info.license.name=Mosip +openapi.info.license.url=https://docs.mosip.io/platform/license + + +#------OpenApi properties-------- +mosipbox.public.url=http://localhost:8083 +openapi.registrationProcessorStatusService.servers[0].url=${mosipbox.public.url}/registrationprocessor/v1/registrationstatus +openapi.registrationProcessorStatusService.servers[0].description=Registration Processor Status service + +config.server.file.storage.uri= +registration.processor.identityjson= +mosip.kernel.auth.appids.realm.map={prereg:'preregistration',ida:'mosip',registrationclient:'mosip',regproc:'mosip',partner:'mosip',resident:'mosip'} +mosip.registration.processor.lostrid.registrationdate.pattern=yyyy-MM-dd diff --git a/registration-processor/mosip-stage-executor/pom.xml b/registration-processor/mosip-stage-executor/pom.xml index 78dd5a1c966..6e7c5a64e31 100644 --- a/registration-processor/mosip-stage-executor/pom.xml +++ b/registration-processor/mosip-stage-executor/pom.xml @@ -1,31 +1,31 @@ - - - 4.0.0 - - io.mosip.registrationprocessor - registration-processor - 1.2.0.1-B1 - - - mosip-stage-executor - 1.2.0.1-B1 - - - - org.springframework.cloud - spring-cloud-starter-config - ${spring-cloud-config.version} - - - org.springframework - spring-context - - - io.mosip.registrationprocessor - registration-processor-core - ${registration.processor.core.version} - - - - + + + 4.0.0 + + io.mosip.registrationprocessor + registration-processor + 1.2.0.1-B3-SNAPSHOT + + + mosip-stage-executor + 1.2.0.1-B3-SNAPSHOT + + + + org.springframework.cloud + spring-cloud-starter-config + ${spring-cloud-config.version} + + + org.springframework + spring-context + + + io.mosip.registrationprocessor + registration-processor-core + ${registration.processor.core.version} + + + + diff --git a/registration-processor/mosip-stage-executor/src/main/java/io/mosip/registration/processor/stages/executor/config/StagesConfig.java b/registration-processor/mosip-stage-executor/src/main/java/io/mosip/registration/processor/stages/executor/config/StagesConfig.java index cd07af4fd3f..18bd440c28e 100644 --- a/registration-processor/mosip-stage-executor/src/main/java/io/mosip/registration/processor/stages/executor/config/StagesConfig.java +++ b/registration-processor/mosip-stage-executor/src/main/java/io/mosip/registration/processor/stages/executor/config/StagesConfig.java @@ -104,7 +104,10 @@ private Map getConfigurationProperties() { }); return (Map)configLoader.get().mapTo(Map.class); } - // TODO change exception to catch and rethrow intruppted exception before base exception + catch(InterruptedException e) { + regProcLogger.error(ExceptionUtils.getStackTrace(e)); + Thread.currentThread().interrupt(); + throw new RuntimeException("Could not load config", e); } catch (Exception e1) { regProcLogger.error(ExceptionUtils.getStackTrace(e1)); throw new RuntimeException("Could not load config", e1); 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 6e5beb7480f..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 @@ -8,7 +8,8 @@ import java.util.Set; import java.util.stream.Collectors; - +import io.mosip.registration.processor.core.logger.RegProcessorLogger; +import io.mosip.kernel.core.logger.spi.Logger; import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.context.annotation.AnnotationConfigApplicationContext; @@ -86,8 +87,7 @@ public static List getStageBeansBasePackages(StagesConfig stagesConfig, String defaultStageBeanBasePkgStr = propertySourcesPropertyResolver.getProperty(PROP_DEFAULT_STAGE_GROUP_STAGE_BEANS_BASE_PACKAGE); String stageBeanBasePkgsStr = propertySourcesPropertyResolver.getProperty( stageBeansBasePkgsPropertyName, defaultStageBeanBasePkgStr); - // Sonar detecting default value and estimating condition as always false but in our case default value can be also null - if(stageBeanBasePkgsStr == null) { + if(stageBeanBasePkgsStr == null) { //NOSONAR Sonar detecting default value and estimating condition as always false but in our case default value can be also null return List.of(); } else { List stageBeansBasePackages = Arrays.stream(stageBeanBasePkgsStr.split(",")) diff --git a/registration-processor/pom.xml b/registration-processor/pom.xml index 1cb99130a98..addf92e9d25 100644 --- a/registration-processor/pom.xml +++ b/registration-processor/pom.xml @@ -1,502 +1,503 @@ - - - 4.0.0 - - - io.mosip - registration - 1.2.0.1-B1 - - - io.mosip.registrationprocessor - registration-processor - 1.2.0.1-B1 - pom - - registration-processor - Parent project of MOSIP Registration processor - - - none - UTF-8 - 11 - 11 - 3.8.0 - 3.0.2 - 3.1.0 - 2.22.0 - 0.8.5 - 3.7.0.1746 - 3.2.0 - 3.3.0 - - - 5.0.6.RELEASE - 5.0.4.RELEASE - 2.0.2.RELEASE - 2.0.9.RELEASE - 2.0.0.RELEASE - - 4.0.1.RELEASE - 2.0.0.RELEASE - - - 3.0.0 - 2.0.1.Final - 2.12.0 - 2.12.0 - 6.0.12.Final - 2.1.1 - 1.7.25 - 4.5.6 - - - 2.9.2 - - - 2.5.0 - 5.1.46 - 1.4.195 - 42.2.2 - - - 1.18.8 - - - 2.3.0 - - - 1.60 - 1.6 - - - 3.6.1 - 3.7 - 2.6 - 1.10 - 1.9.2 - 2.2 - 2.6 - 1.7 - 2.0 - - - 4.12 - 1.2.3 - 1.7.19 - 3.4.4 - 2.0.7 - 2.0.7 - 3.1.0 - 1.1.1 - 1.9 - - 1.11.368 - 0.2.4 - - - 3.9.1 - 2.23.0 - 1.0.0 - - 1.1.1 - - - 2.8.1 - - - 0.1.55 - - - 1.2.0.1-B1 - 1.2.0.1-B1 - 1.2.0.1-B1 - 1.2.0.1-B1 - 1.2.0.1-B1 - 1.2.0.1-B1 - 1.2.0.1-B1 - - - 1.2.0.1-B1 - 1.2.0.1-B1 - 1.2.0.1-B1 - 1.2.0.1-B1 - 1.2.0.1-B1 - 1.2.0.1-B1 - 1.2.0 - 1.2.0.1-B1 - 1.2.0.1-B1 - 1.2.0.1-B1 - 1.2.0.1-B1 - 1.2.0.1-B1 - 1.2.0.1-B1 - 1.2.0.1-B1 - 1.2.0.1-B1 - 1.2.0.1-B1 - 1.2.0.1-B1 - **/dto/**, - **/exception/*Exception.java, - **/config/*Config.java, - **/handler/*ExceptionHandler.java, - **/**/*Application.java, - **/utilities/*.java, - **/validator/*Validator.java, - **/utils/*.java, - **/util/*.java, - **/code/*.java, - **/entity/*.java, - **/config/*.java, - - **/core/code/*.java, - **/packet/storage/entity/*.java, - **/manager/exception/systemexception/*.java, - **/registration/processor/rest/client/*.java, - **/registration/processor/rest/client/audit/builder/*.java, - - **/registration/processor/packet/receiver/*.java, - **/registration/processor/packet/receiver/exception/systemexception/*.java, - **/registration/processor/failoverstage/*.java, - **/registration/processor/stages/*.java, - **/registration/processor/retry/verticle/*.java, - **/registration/processor/retry/verticle/stages/*.java, - **/registration/processor/retry/verticle/constants/*.java, - **/registration/processor/packet/decrypter/job/stage/*.java, - **/registration/processor/packet/decryptor/job/exception/constant/*.java, - - **/registration/processor/virus/scanner/job/exceptions/*.java, - - - **/registration/processor/stages/app/*.java, - **/registration/processor/stages/executor/*.java, - **/registration/processor/camel/bridge/processor/*.java, - **/registration/processor/core/constant/*.java, - **/registration/processor/core/packet/dto/demographicinfo/*.java, - **/registration/processor/core/packet/dto/demographicinfo/identify/*.java, - **/registration/processor/core/packet/dto/regcentermachine/*.java, - - **/registration/processor/quality/check/client/*.java, - **/registration/processor/quality/check/code/*.java, - **/registration/processor/quality/check/entity/*.java, - **/registration/processor/quality/check/exception/*.java, - **/registration/processor/quality/check/*.java, - **/registration/processor/message/sender/*.java, - **/registration/processor/message/sender/utility/*.java, - **/registration/processor/core/logger/*.java, - **/registration/processor/core/notification/template/mapping/*.java, - **/registration/processor/bio/dedupe/service/*.java, - **/registration/processor/bio/dedupe/exception/*.java, - - **/registration/processor/packet/storage/storage/*.java, - **/registration/processor/packet/storage/exception/*.java, - **/registration/processor/status/repositary/*.java, - **/registration/processor/status/entity/*.java, - **/registration/processor/virus/scanner/job/*.java, - - - **/registration/processor/packet/uploader/*.java, - **/registration/processor/biodedupe/*.java, - - - **/registration/processor/abis/config/*.java, - **/registration/processor/abis/controller/*.java, - **/registration/processor/abis/exception/*.java, - **/registration/processor/abis/messagequeue/*.java, - **/registration/processor/abis/service/*.java, - **/registration/processor/abis/service/impl/*.java, - - - **/registration/processor/abis/handler/*.java, - **/registration/processor/abis/handler/config/*.java, - - **/registration/processor/packet/service/**/*.java, - **/registration/processor/packet/upload/**/*.java, - - **/registration/processor/status/code/*.java, - **/registration/processor/rest/client/config/RestConfigBean.java, - **/registration/processor/bio/dedupe/api/BioDedupeApiApp.java, - **/registration/processor/manual/verification/response/builder/*.java, - **/registration/processor/manual/verification/config/*.java, - **/registration/processor/stages/config/OSIConfigBean.java, - **/registration/processor/stages/demo/dedupe/StatusMessage.java, - **/registration/processor/stages/demo/dedupe/DemodedupeStage.java, - **/registration/processor/stages/demo/dedupe/BiometricValidation.java, - **/registration/processor/core/exception/ExceptionJSONInfo.java, - **/registration/processor/core/config/CoreConfigBean.java, - **/registration/processor/core/kernel/beans/KernelConfig.java, - **/registration/processor/core/abstractverticle/MosipVerticleAPIManager.java, - **/registration/processor/core/abstractverticle/WorkflowInternalActionDTO.java, - **/registration/processor/core/http/*.java, - **/registration/processor/core/queue/factory/*.java, - **/registration/processor/core/queue/impl/*.java, - **/registration/processor/core/tracing/*.java, - **/registration/processor/message/sender/config/MsgNotificationBeanCofig.java, - **/registration/processor/print/exception/QueueConnectionNotFound.java, - **/registration/processor/stages/demodedupe/StatusMessage.java, - **/registration/processor/print/service/utility/UINCardConstant.java, - **/registration/processor/stages/demodedupe/BiometricValidation.java, - **/registration/processor/camel/bridge/MosipBridgeFactory.java, - **/registration/processor/manual/verification/stage/ManualVerificationStage.java, - **/registration/processor/packet/receiver/builder/PacketReceiverResponseBuilder.java, - **/registration/processor/packet/receiver/stage/PacketReceiverStage.java, - **/registration/processor/camel/bridge/**/*.java, - **/registration/processor/stages/connector/stage/**/*.java, - **/registration/processor/stages/demodedupe/DemoDedupeStage.java, - - **/registration/processor/packet/storage/mapper/PacketInfoMapper.java, - **/registration/processor/packet/storage/dao/PacketInfoDao.java, - **/registration/processor/packet/uploader/constants/*.java, - **/registration/processor/packet/manager/constant/*.java, - **/registration/processor/print/exception/PrintGlobalExceptionHandler.java, - **/registration/processor/packet/receiver/constants/*.java, - **/registration/processor/print/service/exception/*.java, - **/registration/processor/print/exception/*.java, - **/registration/processor/packet/uploader/constants/*.java, - **/registration/processor/packet/uploader/decryptor/*.java, - **/registration/processor/core/abstractverticle/MosipRouter.java, - **/registration/processor/packet/uploader/decryptor/*.java, - - **/registration/processor/print/service/impl/PrintPostServiceImpl.java, - - **/registration/processor/message/sender/constants/*.java, - **/registration/processor/core/abstractverticle/BaseHealthCheckModel.java, - **/registration/processor/core/**/TokenValidator.java, - **/registration/processor/core/abstractverticle/StageHealthCheckHandler.java, - **/registration/processor/core/abstractverticle/MessageDTO.java, - **/registration/processor/request/handler/**/*.java - - **/dto/**,**/entity/**,**/config/**,**/handler/**,**/utilities/**, - **/validator/**, **/utils/**,**/util/**,**/code/** - none - - - - - ossrh - CentralRepository - https://oss.sonatype.org/content/repositories/snapshots - default - - true - - - - central - MavenCentral - default - https://repo1.maven.org/maven2 - - false - - - - - - - - org.mockito - mockito-core - 3.4.4 - test - - - - net.bytebuddy - byte-buddy - 1.10.13 - - - org.springframework.boot - spring-boot-dependencies - ${spring.boot.version} - pom - import - - - org.projectlombok - lombok - 1.18.8 - provided - - - org.powermock - powermock-core - 2.0.7 - test - - - javax.xml.bind - jaxb-api - 2.3.1 - - - org.javassist - javassist - 3.27.0-GA - - - com.fasterxml.jackson.core - jackson-databind - ${jackson.version} - - - com.fasterxml.jackson.core - jackson-core - ${jackson.version} - - - com.fasterxml.jackson.core - jackson-annotations - ${jackson.version} - - - - - - registration-processor-core - registration-processor-rest-client - registration-processor-packet-manager - registration-processor-common-camel-bridge - registration-processor-bio-dedupe-service-impl - registration-processor-info-storage-service - registration-processor-registration-status-service-impl - registration-processor-message-sender-impl - registration-processor-notification-service - init - pre-processor - core-processor - post-processor - mosip-stage-executor - stage-groups - workflow-engine - - - - - 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-javadoc-plugin - ${maven.javadoc.version} - - true - none - - - - - - - sonar - - . - src/main/java/**,src/main/resources/** - ${sonar.coverage.exclusions} - https://sonarcloud.io - - - false - - - - - org.sonarsource.scanner.maven - sonar-maven-plugin - ${maven.sonar.plugin.version} - - - verify - - sonar - - - - - - - - + + + 4.0.0 + + + io.mosip + registration + 1.2.0.1-B3-SNAPSHOT + + + io.mosip.registrationprocessor + registration-processor + 1.2.0.1-B3-SNAPSHOT + pom + + registration-processor + Parent project of MOSIP Registration processor + + + none + UTF-8 + 11 + 11 + 3.8.0 + 3.0.2 + 3.1.0 + 2.22.0 + 0.8.5 + 3.7.0.1746 + 3.2.0 + 3.3.0 + + + 5.0.6.RELEASE + 5.0.4.RELEASE + 2.0.2.RELEASE + 2.0.9.RELEASE + 2.0.0.RELEASE + + 4.0.1.RELEASE + 2.0.0.RELEASE + + + 3.0.0 + 2.0.1.Final + 2.12.0 + 2.12.0 + 6.0.12.Final + 2.1.1 + 1.7.25 + 4.5.6 + + + 2.9.2 + + + 2.5.0 + 5.1.46 + 1.4.195 + 42.2.2 + + + 1.18.8 + + + 2.3.0 + + + 1.60 + 1.6 + + + 3.6.1 + 3.7 + 2.6 + 1.10 + 1.9.2 + 2.2 + 2.6 + 1.7 + 2.0 + + + 4.12 + 1.2.3 + 1.7.19 + 3.4.4 + 2.0.7 + 2.0.7 + 3.1.0 + 1.1.1 + 1.9 + + 1.11.368 + 0.2.4 + + + 3.9.1 + 2.23.0 + 1.0.0 + + 1.1.1 + + + 2.8.1 + + + 0.1.55 + + + 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-B3-SNAPSHOT + + + 1.2.0.1-B1 + 1.2.0.1-B1 + 1.2.0.1-B1 + 1.2.0.1-B1 + 1.2.0.1-B1 + 1.2.0.1-B1 + 1.2.0 + 1.2.0.1-B1 + 1.2.0.1-B1 + 1.2.0.1-B1 + 1.2.0.1-B1 + 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 + 1.2.0.1-B1 + 1.2.0.1-B1 + 1.2.0.1-B1 + **/dto/**, + **/exception/*Exception.java, + **/config/*Config.java, + **/handler/*ExceptionHandler.java, + **/**/*Application.java, + **/utilities/*.java, + **/validator/*Validator.java, + **/utils/*.java, + **/util/*.java, + **/code/*.java, + **/entity/*.java, + **/config/*.java, + + **/core/code/*.java, + **/packet/storage/entity/*.java, + **/manager/exception/systemexception/*.java, + **/registration/processor/rest/client/*.java, + **/registration/processor/rest/client/audit/builder/*.java, + + **/registration/processor/packet/receiver/*.java, + **/registration/processor/packet/receiver/exception/systemexception/*.java, + **/registration/processor/failoverstage/*.java, + **/registration/processor/stages/*.java, + **/registration/processor/retry/verticle/*.java, + **/registration/processor/retry/verticle/stages/*.java, + **/registration/processor/retry/verticle/constants/*.java, + **/registration/processor/packet/decrypter/job/stage/*.java, + **/registration/processor/packet/decryptor/job/exception/constant/*.java, + + **/registration/processor/virus/scanner/job/exceptions/*.java, + + + **/registration/processor/stages/app/*.java, + **/registration/processor/stages/executor/*.java, + **/registration/processor/camel/bridge/processor/*.java, + **/registration/processor/core/constant/*.java, + **/registration/processor/core/packet/dto/demographicinfo/*.java, + **/registration/processor/core/packet/dto/demographicinfo/identify/*.java, + **/registration/processor/core/packet/dto/regcentermachine/*.java, + + **/registration/processor/quality/check/client/*.java, + **/registration/processor/quality/check/code/*.java, + **/registration/processor/quality/check/entity/*.java, + **/registration/processor/quality/check/exception/*.java, + **/registration/processor/quality/check/*.java, + **/registration/processor/message/sender/*.java, + **/registration/processor/message/sender/utility/*.java, + **/registration/processor/core/logger/*.java, + **/registration/processor/core/notification/template/mapping/*.java, + **/registration/processor/bio/dedupe/service/*.java, + **/registration/processor/bio/dedupe/exception/*.java, + + **/registration/processor/packet/storage/storage/*.java, + **/registration/processor/packet/storage/exception/*.java, + **/registration/processor/status/repositary/*.java, + **/registration/processor/status/entity/*.java, + **/registration/processor/virus/scanner/job/*.java, + + + **/registration/processor/packet/uploader/*.java, + **/registration/processor/biodedupe/*.java, + + + **/registration/processor/abis/config/*.java, + **/registration/processor/abis/controller/*.java, + **/registration/processor/abis/exception/*.java, + **/registration/processor/abis/messagequeue/*.java, + **/registration/processor/abis/service/*.java, + **/registration/processor/abis/service/impl/*.java, + + + **/registration/processor/abis/handler/*.java, + **/registration/processor/abis/handler/config/*.java, + + **/registration/processor/packet/service/**/*.java, + **/registration/processor/packet/upload/**/*.java, + + **/registration/processor/status/code/*.java, + **/registration/processor/rest/client/config/RestConfigBean.java, + **/registration/processor/bio/dedupe/api/BioDedupeApiApp.java, + **/registration/processor/manual/verification/response/builder/*.java, + **/registration/processor/manual/verification/config/*.java, + **/registration/processor/stages/config/OSIConfigBean.java, + **/registration/processor/stages/demo/dedupe/StatusMessage.java, + **/registration/processor/stages/demo/dedupe/DemodedupeStage.java, + **/registration/processor/stages/demo/dedupe/BiometricValidation.java, + **/registration/processor/core/exception/ExceptionJSONInfo.java, + **/registration/processor/core/config/CoreConfigBean.java, + **/registration/processor/core/kernel/beans/KernelConfig.java, + **/registration/processor/core/abstractverticle/MosipVerticleAPIManager.java, + **/registration/processor/core/abstractverticle/WorkflowInternalActionDTO.java, + **/registration/processor/core/http/*.java, + **/registration/processor/core/queue/factory/*.java, + **/registration/processor/core/queue/impl/*.java, + **/registration/processor/core/tracing/*.java, + **/registration/processor/message/sender/config/MsgNotificationBeanCofig.java, + **/registration/processor/print/exception/QueueConnectionNotFound.java, + **/registration/processor/stages/demodedupe/StatusMessage.java, + **/registration/processor/print/service/utility/UINCardConstant.java, + **/registration/processor/stages/demodedupe/BiometricValidation.java, + **/registration/processor/camel/bridge/MosipBridgeFactory.java, + **/registration/processor/manual/verification/stage/ManualVerificationStage.java, + **/registration/processor/packet/receiver/builder/PacketReceiverResponseBuilder.java, + **/registration/processor/packet/receiver/stage/PacketReceiverStage.java, + **/registration/processor/camel/bridge/**/*.java, + **/registration/processor/stages/connector/stage/**/*.java, + **/registration/processor/stages/demodedupe/DemoDedupeStage.java, + + **/registration/processor/packet/storage/mapper/PacketInfoMapper.java, + **/registration/processor/packet/storage/dao/PacketInfoDao.java, + **/registration/processor/packet/uploader/constants/*.java, + **/registration/processor/packet/manager/constant/*.java, + **/registration/processor/print/exception/PrintGlobalExceptionHandler.java, + **/registration/processor/packet/receiver/constants/*.java, + **/registration/processor/print/service/exception/*.java, + **/registration/processor/print/exception/*.java, + **/registration/processor/packet/uploader/constants/*.java, + **/registration/processor/packet/uploader/decryptor/*.java, + **/registration/processor/core/abstractverticle/MosipRouter.java, + **/registration/processor/packet/uploader/decryptor/*.java, + + **/registration/processor/print/service/impl/PrintPostServiceImpl.java, + + **/registration/processor/message/sender/constants/*.java, + **/registration/processor/core/abstractverticle/BaseHealthCheckModel.java, + **/registration/processor/core/**/TokenValidator.java, + **/registration/processor/core/abstractverticle/StageHealthCheckHandler.java, + **/registration/processor/core/abstractverticle/MessageDTO.java, + **/registration/processor/request/handler/**/*.java + + **/dto/**,**/entity/**,**/config/**,**/handler/**,**/utilities/**, + **/validator/**, **/utils/**,**/util/**,**/code/** + none + + + + + ossrh + CentralRepository + https://oss.sonatype.org/content/repositories/snapshots + default + + true + + + + central + MavenCentral + default + https://repo1.maven.org/maven2 + + false + + + + + + + + org.mockito + mockito-core + 3.4.4 + test + + + + net.bytebuddy + byte-buddy + 1.10.13 + + + org.springframework.boot + spring-boot-dependencies + ${spring.boot.version} + pom + import + + + org.projectlombok + lombok + 1.18.8 + provided + + + org.powermock + powermock-core + 2.0.7 + test + + + javax.xml.bind + jaxb-api + 2.3.1 + + + org.javassist + javassist + 3.27.0-GA + + + com.fasterxml.jackson.core + jackson-databind + ${jackson.version} + + + com.fasterxml.jackson.core + jackson-core + ${jackson.version} + + + com.fasterxml.jackson.core + jackson-annotations + ${jackson.version} + + + + + + registration-processor-core + registration-processor-rest-client + registration-processor-packet-manager + registration-processor-common-camel-bridge + registration-processor-bio-dedupe-service-impl + registration-processor-info-storage-service + registration-processor-registration-status-service-impl + registration-processor-message-sender-impl + registration-processor-notification-service + init + pre-processor + core-processor + post-processor + mosip-stage-executor + stage-groups + 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-javadoc-plugin + ${maven.javadoc.version} + + true + none + + + + + + + sonar + + . + src/main/java/**,src/main/resources/** + ${sonar.coverage.exclusions} + https://sonarcloud.io + + + false + + + + + org.sonarsource.scanner.maven + sonar-maven-plugin + ${maven.sonar.plugin.version} + + + verify + + sonar + + + + + + + + \ No newline at end of file diff --git a/registration-processor/post-processor/pom.xml b/registration-processor/post-processor/pom.xml index ac3a2ba4971..63db0d9e953 100644 --- a/registration-processor/post-processor/pom.xml +++ b/registration-processor/post-processor/pom.xml @@ -1,22 +1,22 @@ - - - 4.0.0 - pom - - io.mosip.registrationprocessor - registration-processor - 1.2.0.1-B1 - - 1.2.0.1-B1 - post-processor - post-processor - - UTF-8 - - - registration-processor-message-sender-stage - registration-processor-printing-stage - registration-processor-registration-transaction-service - - + + + 4.0.0 + pom + + io.mosip.registrationprocessor + registration-processor + 1.2.0.1-B3-SNAPSHOT + + 1.2.0.1-B3-SNAPSHOT + post-processor + post-processor + + UTF-8 + + + registration-processor-message-sender-stage + registration-processor-printing-stage + registration-processor-registration-transaction-service + + diff --git a/registration-processor/post-processor/registration-processor-message-sender-stage/pom.xml b/registration-processor/post-processor/registration-processor-message-sender-stage/pom.xml index 9078acad095..18eb0f7e221 100644 --- a/registration-processor/post-processor/registration-processor-message-sender-stage/pom.xml +++ b/registration-processor/post-processor/registration-processor-message-sender-stage/pom.xml @@ -1,103 +1,103 @@ - - - 4.0.0 - jar - - io.mosip.registrationprocessor - post-processor - 1.2.0.1-B1 - - - registration-processor-message-sender-stage - 1.2.0.1-B1 - - UTF-8 - UTF-8 - - - - - - org.springframework.cloud - spring-cloud-starter-config - ${spring-cloud-config.version} - - - org.mockito - mockito-core - ${mockito.version} - test - - - com.h2database - h2 - ${h2.version} - - - - - - org.springframework - spring-context - ${spring-framework.version} - - - org.springframework - spring-tx - ${spring-framework.version} - - - io.mosip.registrationprocessor - registration-processor-registration-status-service-impl - ${registration.status.service.version} - - - io.mosip.registrationprocessor - registration-processor-core - ${registration.processor.core.version} - - - io.mosip.registrationprocessor - registration-processor-info-storage-service - ${packet.info.storage.service.version} - - - io.mosip.registrationprocessor - registration-processor-rest-client - ${registration.processor.rest.client.version} - - - io.mosip.registrationprocessor - registration-processor-message-sender-impl - ${registration.processor.message.sender.version} - - - junit - junit - test - - - org.powermock - powermock-module-junit4 - ${powermock.module.junit4.version} - test - - - org.powermock - powermock-api-mockito2 - ${powermock.api.mockito.version} - test - - - io.mosip.registrationprocessor - registration-processor-packet-manager - ${packet.manager.version} - - - - - - - + + + 4.0.0 + jar + + io.mosip.registrationprocessor + post-processor + 1.2.0.1-B3-SNAPSHOT + + + registration-processor-message-sender-stage + 1.2.0.1-B3-SNAPSHOT + + UTF-8 + UTF-8 + + + + + + org.springframework.cloud + spring-cloud-starter-config + ${spring-cloud-config.version} + + + org.mockito + mockito-core + ${mockito.version} + test + + + com.h2database + h2 + ${h2.version} + + + + + + org.springframework + spring-context + ${spring-framework.version} + + + org.springframework + spring-tx + ${spring-framework.version} + + + io.mosip.registrationprocessor + registration-processor-registration-status-service-impl + ${registration.status.service.version} + + + io.mosip.registrationprocessor + registration-processor-core + ${registration.processor.core.version} + + + io.mosip.registrationprocessor + registration-processor-info-storage-service + ${packet.info.storage.service.version} + + + io.mosip.registrationprocessor + registration-processor-rest-client + ${registration.processor.rest.client.version} + + + io.mosip.registrationprocessor + registration-processor-message-sender-impl + ${registration.processor.message.sender.version} + + + junit + junit + test + + + org.powermock + powermock-module-junit4 + ${powermock.module.junit4.version} + test + + + org.powermock + powermock-api-mockito2 + ${powermock.api.mockito.version} + test + + + io.mosip.registrationprocessor + registration-processor-packet-manager + ${packet.manager.version} + + + + + + + diff --git a/registration-processor/post-processor/registration-processor-message-sender-stage/src/test/java/io/mosip/registration/processor/message/sender/stage/test/MessageSenderStageTest.java b/registration-processor/post-processor/registration-processor-message-sender-stage/src/test/java/io/mosip/registration/processor/message/sender/stage/test/MessageSenderStageTest.java index e359b073402..a88e878d1b7 100644 --- a/registration-processor/post-processor/registration-processor-message-sender-stage/src/test/java/io/mosip/registration/processor/message/sender/stage/test/MessageSenderStageTest.java +++ b/registration-processor/post-processor/registration-processor-message-sender-stage/src/test/java/io/mosip/registration/processor/message/sender/stage/test/MessageSenderStageTest.java @@ -170,6 +170,7 @@ public void senderHealthCheck(Handler eventHandler, String addre // TODO Auto-generated method stub } + }; } diff --git a/registration-processor/post-processor/registration-processor-printing-stage/pom.xml b/registration-processor/post-processor/registration-processor-printing-stage/pom.xml index 0f16514303c..fa180da83b3 100644 --- a/registration-processor/post-processor/registration-processor-printing-stage/pom.xml +++ b/registration-processor/post-processor/registration-processor-printing-stage/pom.xml @@ -6,10 +6,10 @@ io.mosip.registrationprocessor post-processor - 1.2.0.1-B1 + 1.2.0.1-B3-SNAPSHOT registration-processor-printing-stage - 1.2.0.1-B1 + 1.2.0.1-B3-SNAPSHOT UTF-8 UTF-8 diff --git a/registration-processor/post-processor/registration-processor-printing-stage/src/main/java/io/mosip/registration/processor/print/stage/PrintingStage.java b/registration-processor/post-processor/registration-processor-printing-stage/src/main/java/io/mosip/registration/processor/print/stage/PrintingStage.java index 459bfa6f8fe..086178dff69 100644 --- a/registration-processor/post-processor/registration-processor-printing-stage/src/main/java/io/mosip/registration/processor/print/stage/PrintingStage.java +++ b/registration-processor/post-processor/registration-processor-printing-stage/src/main/java/io/mosip/registration/processor/print/stage/PrintingStage.java @@ -2,14 +2,19 @@ import java.io.File; import java.io.IOException; +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; -import java.util.ArrayList; import java.util.List; +import java.util.Map; import java.util.Random; +import java.util.HashMap; +import java.util.ArrayList; +import org.apache.commons.codec.binary.Base64; import org.apache.commons.lang3.exception.ExceptionUtils; import org.json.simple.JSONObject; import org.springframework.beans.factory.annotation.Autowired; @@ -130,6 +135,9 @@ public class PrintingStage extends MosipVerticleAPIManager { @Value("${mosip.registration.processor.encrypt:false}") private boolean encrypt; + @Value("${mosip.registration.processor.default.issuer:mpartner-default-print}") + private String issuer; + /** Mosip router for APIs */ @Autowired @@ -150,6 +158,13 @@ public class PrintingStage extends MosipVerticleAPIManager { private static final String DATETIME_PATTERN = "mosip.registration.processor.datetime.pattern"; + private static final String ISSUERS = "mosip.registration.processor.issuer"; + + @Value("${mosip.registration.processor.rid.delimiter:-PDF}") + private String pdfDelimiter; + + private static String SEMICOLON = ";"; + private static String COLON = ":"; @Autowired private Utilities utilities; @@ -163,7 +178,6 @@ protected String getPropertyPrefix() { * Deploy verticle. */ public void deployVerticle() { - mosipEventBus = this.getEventBus(this, clusterManagerUrl, workerPoolSize); this.consumeAndSend(mosipEventBus, MessageBusAddress.PRINTING_BUS_IN, MessageBusAddress.PRINTING_BUS_OUT, messageExpiryTimeLimit); @@ -192,7 +206,7 @@ public MessageDTO process(MessageDTO object) { InternalRegistrationStatusDto registrationStatusDto = null; RequestWrapper requestWrapper = new RequestWrapper<>(); - ResponseWrapper responseWrapper; + ResponseWrapper responseWrapper = null; CredentialResponseDto credentialResponseDto; try { registrationStatusDto = registrationStatusService.getRegistrationStatus( @@ -222,16 +236,29 @@ public MessageDTO process(MessageDTO object) { } else { String vid = getVid(uin); - CredentialRequestDto credentialRequestDto = getCredentialRequestDto(vid); requestWrapper.setId(env.getProperty("mosip.registration.processor.credential.request.service.id")); - requestWrapper.setRequest(credentialRequestDto); + String issuers= env.getProperty(ISSUERS); DateTimeFormatter format = DateTimeFormatter.ofPattern(env.getProperty(DATETIME_PATTERN)); LocalDateTime localdatetime = LocalDateTime - .parse(DateUtils.getUTCCurrentDateTimeString(env.getProperty(DATETIME_PATTERN)), format); + .parse(DateUtils.getUTCCurrentDateTimeString(env.getProperty(DATETIME_PATTERN)), format); requestWrapper.setRequesttime(localdatetime); requestWrapper.setVersion("1.0"); - responseWrapper = (ResponseWrapper) restClientService.postApi(ApiName.CREDENTIALREQUEST, null, null, - requestWrapper, ResponseWrapper.class, MediaType.APPLICATION_JSON); + for (String key : issuers.split(SEMICOLON)) { + CredentialRequestDto credentialRequestDto=null; + String[] parts = key.split(COLON, 3); + credentialRequestDto = getCredentialRequestDto(regId, parts[0], parts[1], parts[2]); + requestWrapper.setRequest(credentialRequestDto); + if (parts[0].equalsIgnoreCase(issuer)) { // for default issuer stage is calling v1 api and for others stage is calling v2 api for credential + responseWrapper = (ResponseWrapper) restClientService.postApi(ApiName.CREDENTIALREQUEST, null, null, + requestWrapper, ResponseWrapper.class, MediaType.APPLICATION_JSON); + } else { + List pathsegments = new ArrayList<>(); + pathsegments.add(regId + pdfDelimiter); // #PDF suffix is added to identify the requested credential via rid + responseWrapper = (ResponseWrapper) restClientService.postApi(ApiName.CREDENTIALREQUESTV2, MediaType.APPLICATION_JSON, pathsegments, null, + null, requestWrapper, ResponseWrapper.class); + } + } + if (responseWrapper.getErrors() != null && !responseWrapper.getErrors().isEmpty()) { ErrorDTO error = responseWrapper.getErrors().get(0); object.setIsValid(Boolean.FALSE); @@ -343,17 +370,20 @@ public MessageDTO process(MessageDTO object) { return object; } - private CredentialRequestDto getCredentialRequestDto(String regId) { + private CredentialRequestDto getCredentialRequestDto(String regId,String issuerId,String credentialType,String templateTypeCode) { CredentialRequestDto credentialRequestDto = new CredentialRequestDto(); + Map additionalAttributes=new HashMap<>(); - credentialRequestDto.setCredentialType(env.getProperty("mosip.registration.processor.credentialtype")); + credentialRequestDto.setCredentialType(credentialType); credentialRequestDto.setEncrypt(encrypt); credentialRequestDto.setId(regId); - credentialRequestDto.setIssuer(env.getProperty("mosip.registration.processor.issuer")); + credentialRequestDto.setIssuer(issuerId); credentialRequestDto.setEncryptionKey(generatePin()); + additionalAttributes.put("templateTypeCode",templateTypeCode); + credentialRequestDto.setAdditionalData(additionalAttributes); return credentialRequestDto; } @@ -445,4 +475,4 @@ private void instantiate() { regProcLogger.error("Could not instantiate SecureRandom for credential pin generation", e); } } -} +} \ No newline at end of file diff --git a/registration-processor/post-processor/registration-processor-printing-stage/src/main/resources/bootstrap.properties b/registration-processor/post-processor/registration-processor-printing-stage/src/main/resources/bootstrap.properties index 64b25477db4..45ce04ae614 100644 --- a/registration-processor/post-processor/registration-processor-printing-stage/src/main/resources/bootstrap.properties +++ b/registration-processor/post-processor/registration-processor-printing-stage/src/main/resources/bootstrap.properties @@ -22,4 +22,10 @@ eventbus.port=5722 mosip.regproc.eventbus.kafka.commit.type=${mosip.regproc.printing.eventbus.kafka.commit.type} mosip.regproc.eventbus.kafka.max.poll.records=${mosip.regproc.printing.eventbus.kafka.max.poll.records} mosip.regproc.eventbus.kafka.poll.frequency=${mosip.regproc.printing.eventbus.kafka.poll.frequency} -mosip.regproc.eventbus.kafka.group.id=${mosip.regproc.printing.eventbus.kafka.group.id} \ No newline at end of file +mosip.regproc.eventbus.kafka.group.id=${mosip.regproc.printing.eventbus.kafka.group.id} +mosip.registration.processor.digitalcard.credentialtype=PDFCard +mosip.registration.processor.print.credentialtype=euin +mosip.registration.processor.digitalcard.template=RPR_UIN_CARD_TEMPLATE +mosip.registration.processor.print.template=RPR_UIN_CARD_TEMPLATE +# this property is used to define issuers eg partnerid:credentialType:templateTypeCode +mosip.registration.processor.issuer=mpartner-default-print:${mosip.registration.processor.print.credentialtype}:${mosip.registration.processor.print.template};mpartner-default-digitalcard:${mosip.registration.processor.digitalcard.credentialtype}:${mosip.registration.processor.digitalcard.template} \ No newline at end of file diff --git a/registration-processor/post-processor/registration-processor-printing-stage/src/test/java/io/mosip/registrationprocessor/print/stage/test/PrintingStageTest.java b/registration-processor/post-processor/registration-processor-printing-stage/src/test/java/io/mosip/registrationprocessor/print/stage/test/PrintingStageTest.java index d2834b019e0..43b6c73e975 100644 --- a/registration-processor/post-processor/registration-processor-printing-stage/src/test/java/io/mosip/registrationprocessor/print/stage/test/PrintingStageTest.java +++ b/registration-processor/post-processor/registration-processor-printing-stage/src/test/java/io/mosip/registrationprocessor/print/stage/test/PrintingStageTest.java @@ -184,11 +184,14 @@ 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.printing.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, "pdfDelimiter", "-PDF"); + ReflectionTestUtils.setField(stage, "issuer", "mpartner-default-print"); System.setProperty("server.port", "8099"); //ReflectionTestUtils.setField(stage, "port", "8080"); @@ -275,7 +278,8 @@ public void testPrintStageSuccess() 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()); diff --git a/registration-processor/post-processor/registration-processor-registration-transaction-service/pom.xml b/registration-processor/post-processor/registration-processor-registration-transaction-service/pom.xml index 9eeba25f5ac..b3f9a5881f8 100644 --- a/registration-processor/post-processor/registration-processor-registration-transaction-service/pom.xml +++ b/registration-processor/post-processor/registration-processor-registration-transaction-service/pom.xml @@ -1,171 +1,171 @@ - - - 4.0.0 - - io.mosip.registrationprocessor - post-processor - 1.2.0.1-B1 - - registration-processor-registration-transaction-service - 1.2.0.1-B1 - registration-processor-registration-transaction-service - - UTF-8 - - - - - javax.servlet - javax.servlet-api - 4.0.1 - - - junit - junit - test - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-security - - - org.springframework.security - spring-security-test - - - io.mosip.registrationprocessor - registration-processor-registration-status-service-impl - ${registration.status.service.version} - - - io.springfox - springfox-swagger-ui - - - io.springfox - springfox-swagger2 - - - - - io.mosip.kernel - kernel-core - ${kernel.core.version} - - - org.springdoc - springdoc-openapi-ui - 1.5.10 - - - org.springframework.boot - spring-boot-configuration-processor - ${spring.boot.version} - true - - - - - - org.springframework.boot - spring-boot-maven-plugin - ${spring.boot.version} - - true - ZIP - - - - - build-info - repackage - - - - - - - - - openapi-doc-generate-profile - - - io.mosip.kernel - kernel-auth-adapter - ${project.version} - - - - - - - org.springframework.boot - spring-boot-maven-plugin - ${spring.boot.version} - - true - ZIP - - - - pre-integration-test - - start - - - - src/test/resources - - - openapi-profile - - - --server.port=8090 - --server.servlet.path=/app/generic - - - - - post-integration-test - - stop - - - - - build-info - repackage - - - - - - org.springdoc - springdoc-openapi-maven-plugin - 0.2 - - - integration-test - - generate - - - - - http://localhost:8090/app/generic/v3/api-docs - ${name}-openapi.json - - ${project.build.directory} - false - - - - - - - + + + 4.0.0 + + io.mosip.registrationprocessor + post-processor + 1.2.0.1-B3-SNAPSHOT + + registration-processor-registration-transaction-service + 1.2.0.1-B3-SNAPSHOT + registration-processor-registration-transaction-service + + UTF-8 + + + + + javax.servlet + javax.servlet-api + 4.0.1 + + + junit + junit + test + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-security + + + org.springframework.security + spring-security-test + + + io.mosip.registrationprocessor + registration-processor-registration-status-service-impl + ${registration.status.service.version} + + + io.springfox + springfox-swagger-ui + + + io.springfox + springfox-swagger2 + + + + + io.mosip.kernel + kernel-core + ${kernel.core.version} + + + org.springdoc + springdoc-openapi-ui + 1.5.10 + + + org.springframework.boot + spring-boot-configuration-processor + ${spring.boot.version} + true + + + + + + org.springframework.boot + spring-boot-maven-plugin + ${spring.boot.version} + + true + ZIP + + + + + build-info + repackage + + + + + + + + + openapi-doc-generate-profile + + + io.mosip.kernel + kernel-auth-adapter + ${project.version} + + + + + + + org.springframework.boot + spring-boot-maven-plugin + ${spring.boot.version} + + true + ZIP + + + + pre-integration-test + + start + + + + src/test/resources + + + openapi-profile + + + --server.port=8090 + --server.servlet.path=/app/generic + + + + + post-integration-test + + stop + + + + + build-info + repackage + + + + + + org.springdoc + springdoc-openapi-maven-plugin + 0.2 + + + integration-test + + generate + + + + + http://localhost:8090/app/generic/v3/api-docs + ${name}-openapi.json + + ${project.build.directory} + false + + + + + + + diff --git a/registration-processor/post-processor/registration-processor-registration-transaction-service/src/main/java/io/mosip/registration/processor/transaction/api/controller/RegistrationTransactionController.java b/registration-processor/post-processor/registration-processor-registration-transaction-service/src/main/java/io/mosip/registration/processor/transaction/api/controller/RegistrationTransactionController.java index e0d794db670..8a4289913ba 100644 --- a/registration-processor/post-processor/registration-processor-registration-transaction-service/src/main/java/io/mosip/registration/processor/transaction/api/controller/RegistrationTransactionController.java +++ b/registration-processor/post-processor/registration-processor-registration-transaction-service/src/main/java/io/mosip/registration/processor/transaction/api/controller/RegistrationTransactionController.java @@ -5,8 +5,6 @@ import javax.servlet.http.HttpServletRequest; -import io.swagger.v3.oas.annotations.media.Content; -import io.swagger.v3.oas.annotations.media.Schema; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.cloud.context.config.annotation.RefreshScope; @@ -19,11 +17,13 @@ import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.mosip.kernel.core.logger.spi.Logger; import io.mosip.kernel.core.util.DateUtils; import io.mosip.registration.processor.core.exception.util.PlatformErrorMessages; +import io.mosip.registration.processor.core.logger.RegProcessorLogger; import io.mosip.registration.processor.core.token.validation.exception.AccessDeniedException; import io.mosip.registration.processor.core.token.validation.exception.InvalidTokenException; import io.mosip.registration.processor.core.util.DigitalSignatureUtility; @@ -34,8 +34,9 @@ import io.mosip.registration.processor.status.exception.TransactionsUnavailableException; import io.mosip.registration.processor.status.service.TransactionService; import io.mosip.registration.processor.status.sync.response.dto.RegTransactionResponseDTO; - import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.tags.Tag; @@ -62,12 +63,18 @@ public class RegistrationTransactionController { @Autowired private DigitalSignatureUtility digitalSignatureUtility; + @Autowired + ObjectMapper objMp; + private static final String INVALIDTOKENMESSAGE = "Authorization Token Not Available In The Header"; private static final String REG_TRANSACTION_SERVICE_ID = "mosip.registration.processor.registration.transaction.id"; private static final String REG_TRANSACTION_APPLICATION_VERSION = "mosip.registration.processor.transaction.version"; private static final String DATETIME_PATTERN = "mosip.registration.processor.datetime.pattern"; private static final String RESPONSE_SIGNATURE = "Response-Signature"; + private static Logger regProcLogger = RegProcessorLogger.getLogger(RegistrationTransactionController.class); + + /** * get transaction details for the given registration id * @@ -101,7 +108,7 @@ public ResponseEntity getTransactionsbyRid(@PathVaria return ResponseEntity.status(HttpStatus.OK).body(responseDTO); }catch (Exception e) { if( e instanceof InvalidTokenException |e instanceof AccessDeniedException | e instanceof RegTransactionAppException - | e instanceof TransactionsUnavailableException | e instanceof TransactionTableNotAccessibleException ) { + | e instanceof TransactionsUnavailableException | e instanceof TransactionTableNotAccessibleException | e instanceof JsonProcessingException ) { throw e; } else { @@ -132,9 +139,17 @@ private RegTransactionResponseDTO buildRegistrationTransactionResponse(List buildRegTransactionExceptionRe response.setResponsetime(DateUtils.getUTCCurrentDateTimeString(env.getProperty(DATETIME_PATTERN))); response.setVersion(env.getProperty(REG_TRANSACTION_APPLICATION_VERSION)); response.setResponse(null); - Gson gson = new GsonBuilder().serializeNulls().create(); if(isEnabled) { HttpHeaders headers = new HttpHeaders(); - headers.add(RESPONSE_SIGNATURE,digitalSignatureUtility.getDigitalSignature(gson.toJson(response))); + try { + headers.add(RESPONSE_SIGNATURE,digitalSignatureUtility.getDigitalSignature(objMp.writeValueAsString(response))); + } catch (JsonProcessingException e1) { + regProcLogger.error("Error while processing response",e); + } return ResponseEntity.ok().headers(headers).body(response); } return ResponseEntity.status(HttpStatus.OK).body(response); diff --git a/registration-processor/pre-processor/pom.xml b/registration-processor/pre-processor/pom.xml index c9fcd668989..eb0d8053ee4 100644 --- a/registration-processor/pre-processor/pom.xml +++ b/registration-processor/pre-processor/pom.xml @@ -1,29 +1,29 @@ - - - 4.0.0 - pom - - io.mosip.registrationprocessor - registration-processor - 1.2.0.1-B1 - - 1.2.0.1-B1 - pre-processor - pre-processor - - UTF-8 - - - registration-processor-packet-validator-stage - registration-processor-cmd-validator-stage - registration-processor-operator-validator-stage - registration-processor-supervisor-validator-stage - registration-processor-introducer-validator-stage - registration-processor-packet-uploader-stage - registration-processor-quality-classifier-stage - registration-processor-securezone-notification-stage - registration-processor-packet-classifier-stage - - + + + 4.0.0 + pom + + io.mosip.registrationprocessor + registration-processor + 1.2.0.1-B3-SNAPSHOT + + 1.2.0.1-B3-SNAPSHOT + pre-processor + pre-processor + + UTF-8 + + + registration-processor-packet-validator-stage + registration-processor-cmd-validator-stage + registration-processor-operator-validator-stage + registration-processor-supervisor-validator-stage + registration-processor-introducer-validator-stage + registration-processor-packet-uploader-stage + registration-processor-quality-classifier-stage + registration-processor-securezone-notification-stage + registration-processor-packet-classifier-stage + + diff --git a/registration-processor/pre-processor/registration-processor-cmd-validator-stage/pom.xml b/registration-processor/pre-processor/registration-processor-cmd-validator-stage/pom.xml index 5f80375a435..e26563acbb4 100644 --- a/registration-processor/pre-processor/registration-processor-cmd-validator-stage/pom.xml +++ b/registration-processor/pre-processor/registration-processor-cmd-validator-stage/pom.xml @@ -1,119 +1,119 @@ - - - 4.0.0 - - io.mosip.registrationprocessor - pre-processor - 1.2.0.1-B1 - - registration-processor-cmd-validator-stage - 1.2.0.1-B1 - registration-processor-cmd-validator-stage - - UTF-8 - UTF-8 - - - - - org.springframework.cloud - spring-cloud-starter-config - ${spring-cloud-config.version} - - - org.mockito - mockito-core - ${mockito.version} - test - - - com.h2database - h2 - ${h2.version} - - - - - - org.springframework - spring-context - ${spring-framework.version} - - - org.springframework - spring-tx - ${spring-framework.version} - - - io.mosip.registrationprocessor - registration-processor-core - ${registration.processor.core.version} - - - io.mosip.registrationprocessor - registration-processor-registration-status-service-impl - ${registration.status.service.version} - - - - io.mosip.registrationprocessor - registration-processor-info-storage-service - ${packet.info.storage.service.version} - - - io.mosip.registrationprocessor - registration-processor-rest-client - ${registration.processor.rest.client.version} - - - io.mosip.kernel - kernel-bioapi-provider - ${kernel.bioapi.provider.version} - - - io.mosip.kernel - kernel-core - ${kernel.core.version} - - - org.powermock - powermock-module-junit4 - ${powermock.module.junit4.version} - test - - - org.powermock - powermock-api-mockito2 - ${powermock.api.mockito.version} - test - - - io.mosip.registrationprocessor - registration-processor-packet-manager - ${packet.manager.version} - - - io.mosip.kernel - kernel-templatemanager-velocity - ${kernel.templatemanager.velocity.version} - - - javax.servlet - servlet-api - - - dom4j - dom4j - - - - - - - - - - - + + + 4.0.0 + + io.mosip.registrationprocessor + pre-processor + 1.2.0.1-B3-SNAPSHOT + + registration-processor-cmd-validator-stage + 1.2.0.1-B3-SNAPSHOT + registration-processor-cmd-validator-stage + + UTF-8 + UTF-8 + + + + + org.springframework.cloud + spring-cloud-starter-config + ${spring-cloud-config.version} + + + org.mockito + mockito-core + ${mockito.version} + test + + + com.h2database + h2 + ${h2.version} + + + + + + org.springframework + spring-context + ${spring-framework.version} + + + org.springframework + spring-tx + ${spring-framework.version} + + + io.mosip.registrationprocessor + registration-processor-core + ${registration.processor.core.version} + + + io.mosip.registrationprocessor + registration-processor-registration-status-service-impl + ${registration.status.service.version} + + + + io.mosip.registrationprocessor + registration-processor-info-storage-service + ${packet.info.storage.service.version} + + + io.mosip.registrationprocessor + registration-processor-rest-client + ${registration.processor.rest.client.version} + + + io.mosip.kernel + kernel-bioapi-provider + ${kernel.bioapi.provider.version} + + + io.mosip.kernel + kernel-core + ${kernel.core.version} + + + org.powermock + powermock-module-junit4 + ${powermock.module.junit4.version} + test + + + org.powermock + powermock-api-mockito2 + ${powermock.api.mockito.version} + test + + + io.mosip.registrationprocessor + registration-processor-packet-manager + ${packet.manager.version} + + + io.mosip.kernel + kernel-templatemanager-velocity + ${kernel.templatemanager.velocity.version} + + + javax.servlet + servlet-api + + + dom4j + dom4j + + + + + + + + + + + diff --git a/registration-processor/pre-processor/registration-processor-cmd-validator-stage/src/main/java/io/mosip/registration/processor/stages/cmdvalidator/CenterValidator.java b/registration-processor/pre-processor/registration-processor-cmd-validator-stage/src/main/java/io/mosip/registration/processor/stages/cmdvalidator/CenterValidator.java index c288e2812b4..3a78369af59 100644 --- a/registration-processor/pre-processor/registration-processor-cmd-validator-stage/src/main/java/io/mosip/registration/processor/stages/cmdvalidator/CenterValidator.java +++ b/registration-processor/pre-processor/registration-processor-cmd-validator-stage/src/main/java/io/mosip/registration/processor/stages/cmdvalidator/CenterValidator.java @@ -78,7 +78,7 @@ private void validateRegistrationCenter(String registrationCenterId, String lang if (responseWrapper.getErrors() == null) { rcpdto.setRegistrationCentersHistory(rcpdto.getRegistrationCentersHistory().stream().filter(c-> - c!=null && c.getId()!=null && c.getIsActive()!=null && c.getIsActive() && c.getId().equalsIgnoreCase(registrationCenterId)).collect(Collectors.toList())); + c!=null && c.getId()!=null && c.getIsActive()!=null && c.getIsActive() && c.getId().equalsIgnoreCase(registrationCenterId)).collect(Collectors.toList())); if (rcpdto.getRegistrationCentersHistory()==null || rcpdto.getRegistrationCentersHistory().isEmpty()) { throw new ValidationFailedException(StatusUtil.CENTER_ID_INACTIVE.getMessage(), diff --git a/registration-processor/pre-processor/registration-processor-cmd-validator-stage/src/main/java/io/mosip/registration/processor/stages/cmdvalidator/MachineValidator.java b/registration-processor/pre-processor/registration-processor-cmd-validator-stage/src/main/java/io/mosip/registration/processor/stages/cmdvalidator/MachineValidator.java index 7d3d9a625ad..e07ce2be811 100644 --- a/registration-processor/pre-processor/registration-processor-cmd-validator-stage/src/main/java/io/mosip/registration/processor/stages/cmdvalidator/MachineValidator.java +++ b/registration-processor/pre-processor/registration-processor-cmd-validator-stage/src/main/java/io/mosip/registration/processor/stages/cmdvalidator/MachineValidator.java @@ -69,14 +69,14 @@ public void validate(String machineId, String langCode, String effdatetimes, Str mhrdto = mapper.readValue(mapper.writeValueAsString(responseWrapper.getResponse()), MachineHistoryResponseDto.class); if (responseWrapper.getErrors() == null) { - + mhrdto.setMachineHistoryDetails(mhrdto.getMachineHistoryDetails().stream().filter(m -> - m!=null && m.getId()!=null && m.getId().equalsIgnoreCase(machineId)).collect(Collectors.toList())); + m!=null && m.getId()!=null && m.getId().equalsIgnoreCase(machineId)).collect(Collectors.toList())); - if (mhrdto.getMachineHistoryDetails()!=null && !mhrdto.getMachineHistoryDetails().isEmpty()) { + if (mhrdto.getMachineHistoryDetails()!=null && !mhrdto.getMachineHistoryDetails().isEmpty()) { mhrdto.setMachineHistoryDetails(mhrdto.getMachineHistoryDetails().stream().filter(m -> - m.getIsActive()!=null && m.getIsActive() ).collect(Collectors.toList())); + m.getIsActive()!=null && m.getIsActive() ).collect(Collectors.toList())); if (mhrdto.getMachineHistoryDetails()==null || mhrdto.getMachineHistoryDetails().isEmpty()) { throw new ValidationFailedException(StatusUtil.MACHINE_ID_NOT_ACTIVE.getMessage() + machineId, diff --git a/registration-processor/pre-processor/registration-processor-introducer-validator-stage/pom.xml b/registration-processor/pre-processor/registration-processor-introducer-validator-stage/pom.xml index 3e312282a42..5ed7ff56898 100644 --- a/registration-processor/pre-processor/registration-processor-introducer-validator-stage/pom.xml +++ b/registration-processor/pre-processor/registration-processor-introducer-validator-stage/pom.xml @@ -1,119 +1,119 @@ - - - 4.0.0 - - io.mosip.registrationprocessor - pre-processor - 1.2.0.1-B1 - - registration-processor-introducer-validator-stage - 1.2.0.1-B1 - registration-processor-introducer-validator-stage - - UTF-8 - UTF-8 - - - - - org.springframework.cloud - spring-cloud-starter-config - ${spring-cloud-config.version} - - - org.mockito - mockito-core - ${mockito.version} - test - - - com.h2database - h2 - ${h2.version} - - - - - - org.springframework - spring-context - ${spring-framework.version} - - - org.springframework - spring-tx - ${spring-framework.version} - - - io.mosip.registrationprocessor - registration-processor-core - ${registration.processor.core.version} - - - io.mosip.registrationprocessor - registration-processor-registration-status-service-impl - ${registration.status.service.version} - - - - io.mosip.registrationprocessor - registration-processor-info-storage-service - ${packet.info.storage.service.version} - - - io.mosip.registrationprocessor - registration-processor-rest-client - ${registration.processor.rest.client.version} - - - io.mosip.kernel - kernel-bioapi-provider - ${kernel.bioapi.provider.version} - - - io.mosip.kernel - kernel-core - ${kernel.core.version} - - - org.powermock - powermock-module-junit4 - ${powermock.module.junit4.version} - test - - - org.powermock - powermock-api-mockito2 - ${powermock.api.mockito.version} - test - - - io.mosip.registrationprocessor - registration-processor-packet-manager - ${packet.manager.version} - - - io.mosip.kernel - kernel-templatemanager-velocity - ${kernel.templatemanager.velocity.version} - - - javax.servlet - servlet-api - - - dom4j - dom4j - - - - - - - - - - - + + + 4.0.0 + + io.mosip.registrationprocessor + pre-processor + 1.2.0.1-B3-SNAPSHOT + + registration-processor-introducer-validator-stage + 1.2.0.1-B3-SNAPSHOT + registration-processor-introducer-validator-stage + + UTF-8 + UTF-8 + + + + + org.springframework.cloud + spring-cloud-starter-config + ${spring-cloud-config.version} + + + org.mockito + mockito-core + ${mockito.version} + test + + + com.h2database + h2 + ${h2.version} + + + + + + org.springframework + spring-context + ${spring-framework.version} + + + org.springframework + spring-tx + ${spring-framework.version} + + + io.mosip.registrationprocessor + registration-processor-core + ${registration.processor.core.version} + + + io.mosip.registrationprocessor + registration-processor-registration-status-service-impl + ${registration.status.service.version} + + + + io.mosip.registrationprocessor + registration-processor-info-storage-service + ${packet.info.storage.service.version} + + + io.mosip.registrationprocessor + registration-processor-rest-client + ${registration.processor.rest.client.version} + + + io.mosip.kernel + kernel-bioapi-provider + ${kernel.bioapi.provider.version} + + + io.mosip.kernel + kernel-core + ${kernel.core.version} + + + org.powermock + powermock-module-junit4 + ${powermock.module.junit4.version} + test + + + org.powermock + powermock-api-mockito2 + ${powermock.api.mockito.version} + test + + + io.mosip.registrationprocessor + registration-processor-packet-manager + ${packet.manager.version} + + + io.mosip.kernel + kernel-templatemanager-velocity + ${kernel.templatemanager.velocity.version} + + + javax.servlet + servlet-api + + + dom4j + dom4j + + + + + + + + + + + diff --git a/registration-processor/pre-processor/registration-processor-introducer-validator-stage/src/main/java/io/mosip/registration/processor/stages/introducervalidator/IntroducerValidator.java b/registration-processor/pre-processor/registration-processor-introducer-validator-stage/src/main/java/io/mosip/registration/processor/stages/introducervalidator/IntroducerValidator.java index 49308060321..3a9a5a47810 100644 --- a/registration-processor/pre-processor/registration-processor-introducer-validator-stage/src/main/java/io/mosip/registration/processor/stages/introducervalidator/IntroducerValidator.java +++ b/registration-processor/pre-processor/registration-processor-introducer-validator-stage/src/main/java/io/mosip/registration/processor/stages/introducervalidator/IntroducerValidator.java @@ -36,7 +36,7 @@ import io.mosip.registration.processor.core.status.util.StatusUtil; import io.mosip.registration.processor.core.util.RegistrationExceptionMapperUtil; import io.mosip.registration.processor.packet.manager.idreposervice.IdRepoService; -import io.mosip.registration.processor.packet.storage.utils.AuthUtil; +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; @@ -66,31 +66,28 @@ public class IntroducerValidator { @Autowired ObjectMapper mapper; - @Autowired - private AuthUtil authUtil; + @Autowired private Utilities utility; + + @Autowired + private BioSdkUtil bioUtil; /** * Checks if is valid introducer. * * @param registrationId the registration id * @param registrationStatusDto - * @throws IOException Signals that an I/O - * exception has occurred. * @throws SAXException * @throws ParserConfigurationException - * @throws NoSuchAlgorithmException - * @throws InvalidKeySpecException * @throws BiometricException * @throws io.mosip.kernel.core.exception.IOException - * @throws BaseCheckedException + * @throws Exception * @throws PacketDecryptionFailureException * @throws RegistrationProcessorCheckedException */ - public void validate(String registrationId, InternalRegistrationStatusDto registrationStatusDto) throws IOException, - InvalidKeySpecException, NoSuchAlgorithmException, CertificateException, BaseCheckedException { + public void validate(String registrationId, InternalRegistrationStatusDto registrationStatusDto) throws Exception { regProcLogger.debug("validate called for registrationId {}", registrationId); @@ -205,7 +202,7 @@ private boolean isValidIntroducerRid(String introducerRid, String registrationId private void validateIntroducerBiometric(String registrationId, InternalRegistrationStatusDto registrationStatusDto, String introducerUIN) - throws IOException, CertificateException, NoSuchAlgorithmException, BaseCheckedException { + throws Exception { BiometricRecord biometricRecord = packetManagerService.getBiometricsByMappingJsonKey(registrationId, MappingJsonConstants.INTRODUCER_BIO, registrationStatusDto.getRegistrationType(), ProviderStageName.INTRODUCER_VALIDATOR); @@ -222,7 +219,8 @@ private void validateIntroducerBiometric(String registrationId, InternalRegistra StatusUtil.INTRODUCER_BIOMETRIC_FILE_NAME_NOT_FOUND.getCode()); } } - + + /** * Validate user. * @@ -231,47 +229,17 @@ private void validateIntroducerBiometric(String registrationId, InternalRegistra * @param list biometric data as BIR object * @param individualType user type * @param registrationStatusDto - * @throws SAXException - * @throws ParserConfigurationException - * @throws NoSuchAlgorithmException - * @throws InvalidKeySpecException - * @throws IOException Signals that an I/O exception has - * occurred. - * @throws BaseCheckedException + * @throws Exception + * @throws * @throws BiometricException */ private void validateUserBiometric(String registrationId, String userId, List list, String individualType, - InternalRegistrationStatusDto registrationStatusDto) - throws IOException, CertificateException, NoSuchAlgorithmException, BaseCheckedException { - - AuthResponseDTO authResponseDTO = authUtil.authByIdAuthentication(userId, individualType, list); - if (authResponseDTO.getErrors() == null || authResponseDTO.getErrors().isEmpty()) { - if (!authResponseDTO.getResponse().isAuthStatus()) { - registrationStatusDto.setLatestTransactionStatusCode( - registrationExceptionMapperUtil.getStatusCode(RegistrationExceptionTypeCode.AUTH_FAILED)); - registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.toString()); - throw new ValidationFailedException(StatusUtil.INTRODUCER_AUTHENTICATION_FAILED.getMessage() + userId, - StatusUtil.INTRODUCER_AUTHENTICATION_FAILED.getCode()); - } - - } else { - List errors = authResponseDTO.getErrors(); - if (errors.stream().anyMatch(error -> (error.getErrorCode().equalsIgnoreCase("IDA-MLC-007") - || utility.isUinMissingFromIdAuth(error.getErrorCode(), userId, individualType)))) { - throw new AuthSystemException(PlatformErrorMessages.RPR_AUTH_SYSTEM_EXCEPTION.getMessage()); - } else { - registrationStatusDto.setLatestTransactionStatusCode( - registrationExceptionMapperUtil.getStatusCode(RegistrationExceptionTypeCode.AUTH_ERROR)); - registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.toString()); - String result = errors.stream().map(s -> s.getErrorMessage() + " ").collect(Collectors.joining()); - regProcLogger.debug("validateUserBiometric call ended for registrationId {} {}", registrationId, - result); - throw new BaseCheckedException(result, StatusUtil.INTRODUCER_AUTHENTICATION_FAILED.getCode()); - } - - } - + InternalRegistrationStatusDto registrationStatusDto) throws Exception { + regProcLogger.info("validateUserBiometric call started for registrationId {}", registrationId); + bioUtil.authenticateBiometrics(userId, individualType, list, registrationStatusDto,StatusUtil.INTRODUCER_AUTHENTICATION_FAILED.getCode(),StatusUtil.INTRODUCER_AUTHENTICATION_FAILED.getCode()); + regProcLogger.debug("validateUserBiometric call ended for registrationId {}", registrationId); } + } \ No newline at end of file diff --git a/registration-processor/pre-processor/registration-processor-introducer-validator-stage/src/test/java/io/mosip/registration/processor/introducer/IntroducerValidatorTest.java b/registration-processor/pre-processor/registration-processor-introducer-validator-stage/src/test/java/io/mosip/registration/processor/introducer/IntroducerValidatorTest.java index cdfb44d4aff..d2f0307812f 100644 --- a/registration-processor/pre-processor/registration-processor-introducer-validator-stage/src/test/java/io/mosip/registration/processor/introducer/IntroducerValidatorTest.java +++ b/registration-processor/pre-processor/registration-processor-introducer-validator-stage/src/test/java/io/mosip/registration/processor/introducer/IntroducerValidatorTest.java @@ -3,13 +3,12 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.when; - +import static org.mockito.Mockito.doNothing; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.security.NoSuchAlgorithmException; -import java.security.cert.CertificateException; import java.security.spec.InvalidKeySpecException; import java.util.ArrayList; import java.util.Arrays; @@ -19,7 +18,6 @@ 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; @@ -68,7 +66,7 @@ import io.mosip.registration.processor.core.util.RegistrationExceptionMapperUtil; import io.mosip.registration.processor.packet.manager.idreposervice.IdRepoService; import io.mosip.registration.processor.packet.storage.utils.ABISHandlerUtil; -import io.mosip.registration.processor.packet.storage.utils.AuthUtil; +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.stages.introducervalidator.IntroducerValidator; @@ -105,8 +103,12 @@ public class IntroducerValidatorTest { private TransactionService transcationStatusService; /** The auth response DTO. */ +// @Mock +// AuthResponseDTO authResponseDTO = new AuthResponseDTO(); + + @Mock - AuthResponseDTO authResponseDTO = new AuthResponseDTO(); + BioSdkUtil biosdk; @Mock private ABISHandlerUtil abisHandlerUtil; @@ -131,8 +133,7 @@ public class IntroducerValidatorTest { @Mock private Utilities utility; - @Mock - private AuthUtil authUtil; + /** The demographic dedupe dto list. */ List demographicDedupeDtoList = new ArrayList<>(); @@ -187,7 +188,7 @@ public void setUp() throws Exception { PowerMockito.mockStatic(IOUtils.class); PowerMockito.when(IOUtils.class, "toByteArray", inputStream).thenReturn(data); - Mockito.when(authUtil.authByIdAuthentication(anyString(), any(), any())).thenReturn(authResponseDTO); + // Mockito.when(authUtil.authByIdAuthentication(anyString(), any(), any())).thenReturn(authResponseDTO); registrationStatusDto.setRegistrationId("reg1234"); registrationStatusDto.setApplicantType("Child"); @@ -281,6 +282,8 @@ public void setUp() throws Exception { when(packetManagerService.getFieldByMappingJsonKey(anyString(), anyString(), anyString(), any())) .thenReturn("field"); + + doNothing().when(biosdk).authenticateBiometrics(Mockito.anyString(), Mockito.anyString(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any()); } /** @@ -350,8 +353,7 @@ public void testIntroducerRIDUINNotFound() throws ApisResourceAccessException, I @Test(expected = IntroducerOnHoldException.class) public void testIntroducerRIDProcessingOnHold() - throws NumberFormatException, InvalidKeySpecException, NoSuchAlgorithmException, IOException, - ParserConfigurationException, SAXException, JSONException, CertificateException, BaseCheckedException { + throws Exception { registrationStatusDto.setStatusCode((RegistrationStatusCode.PROCESSING.toString())); List internalRegistrationStatusDtoList=new ArrayList(); internalRegistrationStatusDtoList.add(registrationStatusDto); @@ -394,12 +396,12 @@ public void testIntroducerNotInRegProc() throws Exception { public void testIntroducerBioFileNotNull() throws Exception { demoJson.put("value", "biometreics"); - AuthResponseDTO authResponseDTO1 = new AuthResponseDTO(); - authResponseDTO1.setErrors(null); + // AuthResponseDTO authResponseDTO1 = new AuthResponseDTO(); + // authResponseDTO1.setErrors(null); io.mosip.registration.processor.core.auth.dto.ResponseDTO responseDTO = new io.mosip.registration.processor.core.auth.dto.ResponseDTO(); responseDTO.setAuthStatus(true); - authResponseDTO1.setResponse(responseDTO); - Mockito.when(authUtil.authByIdAuthentication(anyString(), any(), any())).thenReturn(authResponseDTO1); + // authResponseDTO1.setResponse(responseDTO); + //Mockito.when(authUtil.authByIdAuthentication(anyString(), any(), any())).thenReturn(authResponseDTO1); registrationStatusDto.setStatusCode("PROCESSED"); Mockito.when(registrationStatusService.getRegistrationStatus(anyString(), any(), any(), any())).thenReturn(registrationStatusDto); @@ -407,50 +409,24 @@ public void testIntroducerBioFileNotNull() throws Exception { introducerValidator.validate("reg1234", registrationStatusDto); } - @Test(expected = BaseCheckedException.class) + @Test public void testIntroducerErrorTrue() throws Exception { // Mockito.when(osiUtils.getMetaDataValue(anyString(), // any())).thenReturn("2015/01/01"); demoJson.put("value", "biometreics"); - ErrorDTO errordto = new ErrorDTO(); - errordto.setErrorCode("true"); - List errorDtoList = new ArrayList<>(); - errorDtoList.add(errordto); - authResponseDTO.setErrors(errorDtoList); - io.mosip.registration.processor.core.auth.dto.ResponseDTO responseDTO = new io.mosip.registration.processor.core.auth.dto.ResponseDTO(); - responseDTO.setAuthStatus(true); - Mockito.when(authUtil.authByIdAuthentication(anyString(), any(), any())).thenReturn(authResponseDTO); introducerValidator.validate("reg1234", registrationStatusDto); } - @Test(expected = AuthSystemException.class) + @Test public void testIntroducerAuthSystemError() throws Exception { demoJson.put("value", "biometreics"); - ErrorDTO errordto = new ErrorDTO(); - errordto.setErrorCode("IDA-MLC-007"); - authResponseDTO.setErrors(Arrays.asList(errordto)); - Mockito.when(authUtil.authByIdAuthentication(anyString(), any(), any())).thenReturn(authResponseDTO); introducerValidator.validate("reg1234", registrationStatusDto); } - @Test(expected = BaseCheckedException.class) + @Test public void testIntroducerAuthFalse() throws Exception { registrationStatusDto.setStatusCode("PROCESSED"); Mockito.when(registrationStatusService.getRegistrationStatus(anyString(), any(), any(), any())).thenReturn(registrationStatusDto); - /* - * Mockito.when(osiUtils.getMetaDataValue(anyString(), - * any())).thenReturn("2015/01/01"); - * Mockito.when(utility.getDemographicIdentityJSONObject(Mockito.anyString(), - * Mockito.anyString())).thenReturn( - * JsonUtil.getJSONObject(JsonUtil.objectMapperReadValue(childMappingJson, - * JSONObject.class), "identity")); - */ - AuthResponseDTO authResponseDTO1 = new AuthResponseDTO(); - authResponseDTO1.setErrors(null); - io.mosip.registration.processor.core.auth.dto.ResponseDTO responseDTO = new io.mosip.registration.processor.core.auth.dto.ResponseDTO(); - responseDTO.setAuthStatus(false); - authResponseDTO1.setResponse(responseDTO); - Mockito.when(authUtil.authByIdAuthentication(anyString(), any(), any())).thenReturn(authResponseDTO1); Mockito.when(idRepoService.getUinByRid(any(), any())).thenReturn("123456789"); introducerValidator.validate("reg1234", registrationStatusDto); } diff --git a/registration-processor/pre-processor/registration-processor-operator-validator-stage/pom.xml b/registration-processor/pre-processor/registration-processor-operator-validator-stage/pom.xml index bd76683991d..0614385b6dc 100644 --- a/registration-processor/pre-processor/registration-processor-operator-validator-stage/pom.xml +++ b/registration-processor/pre-processor/registration-processor-operator-validator-stage/pom.xml @@ -1,119 +1,119 @@ - - - 4.0.0 - - io.mosip.registrationprocessor - pre-processor - 1.2.0.1-B1 - - registration-processor-operator-validator-stage - 1.2.0.1-B1 - registration-processor-operator-validator-stage - - UTF-8 - UTF-8 - - - - - org.springframework.cloud - spring-cloud-starter-config - ${spring-cloud-config.version} - - - org.mockito - mockito-core - ${mockito.version} - test - - - com.h2database - h2 - ${h2.version} - - - - - - org.springframework - spring-context - ${spring-framework.version} - - - org.springframework - spring-tx - ${spring-framework.version} - - - io.mosip.registrationprocessor - registration-processor-core - ${registration.processor.core.version} - - - io.mosip.registrationprocessor - registration-processor-registration-status-service-impl - ${registration.status.service.version} - - - - io.mosip.registrationprocessor - registration-processor-info-storage-service - ${packet.info.storage.service.version} - - - io.mosip.registrationprocessor - registration-processor-rest-client - ${registration.processor.rest.client.version} - - - io.mosip.kernel - kernel-bioapi-provider - ${kernel.bioapi.provider.version} - - - io.mosip.kernel - kernel-core - ${kernel.core.version} - - - org.powermock - powermock-module-junit4 - ${powermock.module.junit4.version} - test - - - org.powermock - powermock-api-mockito2 - ${powermock.api.mockito.version} - test - - - io.mosip.registrationprocessor - registration-processor-packet-manager - ${packet.manager.version} - - - io.mosip.kernel - kernel-templatemanager-velocity - ${kernel.templatemanager.velocity.version} - - - javax.servlet - servlet-api - - - dom4j - dom4j - - - - - - - - - - - + + + 4.0.0 + + io.mosip.registrationprocessor + pre-processor + 1.2.0.1-B3-SNAPSHOT + + registration-processor-operator-validator-stage + 1.2.0.1-B3-SNAPSHOT + registration-processor-operator-validator-stage + + UTF-8 + UTF-8 + + + + + org.springframework.cloud + spring-cloud-starter-config + ${spring-cloud-config.version} + + + org.mockito + mockito-core + ${mockito.version} + test + + + com.h2database + h2 + ${h2.version} + + + + + + org.springframework + spring-context + ${spring-framework.version} + + + org.springframework + spring-tx + ${spring-framework.version} + + + io.mosip.registrationprocessor + registration-processor-core + ${registration.processor.core.version} + + + io.mosip.registrationprocessor + registration-processor-registration-status-service-impl + ${registration.status.service.version} + + + + io.mosip.registrationprocessor + registration-processor-info-storage-service + ${packet.info.storage.service.version} + + + io.mosip.registrationprocessor + registration-processor-rest-client + ${registration.processor.rest.client.version} + + + io.mosip.kernel + kernel-bioapi-provider + ${kernel.bioapi.provider.version} + + + io.mosip.kernel + kernel-core + ${kernel.core.version} + + + org.powermock + powermock-module-junit4 + ${powermock.module.junit4.version} + test + + + org.powermock + powermock-api-mockito2 + ${powermock.api.mockito.version} + test + + + io.mosip.registrationprocessor + registration-processor-packet-manager + ${packet.manager.version} + + + io.mosip.kernel + kernel-templatemanager-velocity + ${kernel.templatemanager.velocity.version} + + + javax.servlet + servlet-api + + + dom4j + dom4j + + + + + + + + + + + diff --git a/registration-processor/pre-processor/registration-processor-operator-validator-stage/src/main/java/io/mosip/registration/processor/stages/config/OperatorValidatorConfig.java b/registration-processor/pre-processor/registration-processor-operator-validator-stage/src/main/java/io/mosip/registration/processor/stages/config/OperatorValidatorConfig.java index 99c488307bb..cc51d0ff680 100644 --- a/registration-processor/pre-processor/registration-processor-operator-validator-stage/src/main/java/io/mosip/registration/processor/stages/config/OperatorValidatorConfig.java +++ b/registration-processor/pre-processor/registration-processor-operator-validator-stage/src/main/java/io/mosip/registration/processor/stages/config/OperatorValidatorConfig.java @@ -1,27 +1,32 @@ -package io.mosip.registration.processor.stages.config; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -import io.mosip.registration.processor.packet.storage.utils.OSIUtils; -import io.mosip.registration.processor.stages.operatorvalidator.OperatorValidationProcessor; -import io.mosip.registration.processor.stages.operatorvalidator.OperatorValidator; - -@Configuration -public class OperatorValidatorConfig { - - @Bean - public OperatorValidationProcessor getOperatorValidationProcessor() { - return new OperatorValidationProcessor(); - } - - @Bean - public OperatorValidator getOperatorValidator() { - return new OperatorValidator(); - } - - @Bean - public OSIUtils getOSIUtils() { - return new OSIUtils(); - } -} +package io.mosip.registration.processor.stages.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import io.mosip.kernel.biosdk.provider.factory.BioAPIFactory; +import io.mosip.registration.processor.packet.storage.utils.OSIUtils; +import io.mosip.registration.processor.stages.operatorvalidator.OperatorValidationProcessor; +import io.mosip.registration.processor.stages.operatorvalidator.OperatorValidator; + +@Configuration +public class OperatorValidatorConfig { + + @Bean + public OperatorValidationProcessor getOperatorValidationProcessor() { + return new OperatorValidationProcessor(); + } + + @Bean + public OperatorValidator getOperatorValidator() { + return new OperatorValidator(); + } + + @Bean + public OSIUtils getOSIUtils() { + return new OSIUtils(); + } + @Bean + public BioAPIFactory getBioAPIFactory() { + return new BioAPIFactory(); + } +} 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 df78eea9540..b25e6fb522a 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 @@ -47,7 +47,7 @@ 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.AuthUtil; +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; @@ -72,34 +72,28 @@ public class OperatorValidator { @Autowired private PriorityBasedPacketManagerService packetManagerService; - @Autowired - private AuthUtil authUtil; - @Autowired private ObjectMapper mapper; @Autowired private Utilities utility; + @Autowired + private BioSdkUtil bioUtil; + /** * Checks if is valid Operator. * * @param registrationId the registration id - * @throws IOException Signals that an I/O - * exception has occurred. * @throws SAXException * @throws ParserConfigurationException - * @throws NoSuchAlgorithmException - * @throws InvalidKeySpecException - * @throws NumberFormatException * @throws io.mosip.kernel.core.exception.IOException - * @throws BaseCheckedException + * @throws Exception * @throws PacketDecryptionFailureException * @throws RegistrationProcessorCheckedException */ public void validate(String registrationId, InternalRegistrationStatusDto registrationStatusDto, RegOsiDto regOsi) - throws IOException, InvalidKeySpecException, NoSuchAlgorithmException, NumberFormatException, JSONException, - CertificateException, BaseCheckedException { + throws Exception { regProcLogger.debug("validate called for registrationId {}", registrationId); validateOperator(registrationId, regOsi, registrationStatusDto); @@ -175,21 +169,18 @@ private UserResponseDto getUserDetails(String operatorId, String creationDate, * * @param regOsi the reg osi * @param registrationId the registration id - * @throws IOException * @throws SAXException * @throws ParserConfigurationException * @throws BiometricException - * @throws NoSuchAlgorithmException * @throws InvalidKeySpecException * @throws io.mosip.kernel.core.exception.IOException - * @throws BaseCheckedException * @throws PacketDecryptionFailureException * @throws Exception * */ private void authenticateOperator(RegOsiDto regOsi, String registrationId, InternalRegistrationStatusDto registrationStatusDto) - throws IOException, CertificateException, NoSuchAlgorithmException, BaseCheckedException { + throws Exception { String officerId = regOsi.getOfficerId(); // officer password and otp check String officerPassword = regOsi.getOfficerHashedPwd(); @@ -239,6 +230,7 @@ private boolean validateOtpAndPwd(String opValidated, String otpValidated) { return (opValidated != null && opValidated.equals(ISTRUE) || otpValidated != null && otpValidated.equals(ISTRUE)); } + /** * Validate user. * @@ -247,53 +239,28 @@ private boolean validateOtpAndPwd(String opValidated, String otpValidated) { * @param list biometric data as BIR object * @param individualType user type * @param registrationStatusDto + * @throws Exception * @throws SAXException * @throws ParserConfigurationException * @throws NoSuchAlgorithmException * @throws InvalidKeySpecException - * @throws IOException Signals that an I/O exception has - * occurred. - * @throws BaseCheckedException * @throws BiometricException */ private void validateUserBiometric(String registrationId, String userId, List list, String individualType, InternalRegistrationStatusDto registrationStatusDto) - throws IOException, CertificateException, NoSuchAlgorithmException, BaseCheckedException { + throws Exception { if (INDIVIDUAL_TYPE_USERID.equalsIgnoreCase(individualType)) { userId = getIndividualIdByUserId(userId); individualType = null; } - AuthResponseDTO authResponseDTO = authUtil.authByIdAuthentication(userId, individualType, list); - if (authResponseDTO.getErrors() == null || authResponseDTO.getErrors().isEmpty()) { - if (!authResponseDTO.getResponse().isAuthStatus()) { - registrationStatusDto.setLatestTransactionStatusCode( - registrationExceptionMapperUtil.getStatusCode(RegistrationExceptionTypeCode.AUTH_FAILED)); - registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.toString()); - throw new ValidationFailedException(StatusUtil.OFFICER_AUTHENTICATION_FAILED.getMessage() + userId, + bioUtil.authenticateBiometrics(userId, individualType, list,registrationStatusDto, + StatusUtil.OFFICER_AUTHENTICATION_FAILED.getMessage(), StatusUtil.OFFICER_AUTHENTICATION_FAILED.getCode()); - } - } else { - String finalUserId = userId; - String finalIndividualType = individualType; - List errors = authResponseDTO.getErrors(); - if (errors.stream().anyMatch(error -> (error.getErrorCode().equalsIgnoreCase("IDA-MLC-007") - || utility.isUinMissingFromIdAuth(error.getErrorCode(), finalUserId, finalIndividualType)))) { - throw new AuthSystemException(PlatformErrorMessages.RPR_AUTH_SYSTEM_EXCEPTION.getMessage()); - } else { - registrationStatusDto.setLatestTransactionStatusCode( - registrationExceptionMapperUtil.getStatusCode(RegistrationExceptionTypeCode.AUTH_ERROR)); - registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.toString()); - String result = errors.stream().map(s -> s.getErrorMessage() + " ").collect(Collectors.joining()); - regProcLogger.debug("validateUserBiometric call ended for registrationId {} {}", registrationId, - result); - throw new ValidationFailedException(result, StatusUtil.OFFICER_AUTHENTICATION_FAILED.getCode()); - } - - } + regProcLogger.debug("validateUserBiometric call ended for registrationId {}", registrationId); } diff --git a/registration-processor/pre-processor/registration-processor-operator-validator-stage/src/main/java/io/mosip/registration/processor/stages/operatorvalidator/OperatorValidatorStage.java b/registration-processor/pre-processor/registration-processor-operator-validator-stage/src/main/java/io/mosip/registration/processor/stages/operatorvalidator/OperatorValidatorStage.java index f98bed1205f..4d59468bd0c 100644 --- a/registration-processor/pre-processor/registration-processor-operator-validator-stage/src/main/java/io/mosip/registration/processor/stages/operatorvalidator/OperatorValidatorStage.java +++ b/registration-processor/pre-processor/registration-processor-operator-validator-stage/src/main/java/io/mosip/registration/processor/stages/operatorvalidator/OperatorValidatorStage.java @@ -18,7 +18,7 @@ "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.registration.processor.packet.manager.config", "io.mosip.registration.processor.core.kernel.beans","io.mosip.kernel.biosdk.provider.impl"}) public class OperatorValidatorStage extends MosipVerticleAPIManager { private static final String STAGE_PROPERTY_PREFIX = "mosip.regproc.operator-validator."; diff --git a/registration-processor/pre-processor/registration-processor-operator-validator-stage/src/test/java/io/mosip/registration/processor/operator/OperatorValidatorTest.java b/registration-processor/pre-processor/registration-processor-operator-validator-stage/src/test/java/io/mosip/registration/processor/operator/OperatorValidatorTest.java index 762a6eaad69..dcd1d186b35 100644 --- a/registration-processor/pre-processor/registration-processor-operator-validator-stage/src/test/java/io/mosip/registration/processor/operator/OperatorValidatorTest.java +++ b/registration-processor/pre-processor/registration-processor-operator-validator-stage/src/test/java/io/mosip/registration/processor/operator/OperatorValidatorTest.java @@ -4,6 +4,7 @@ import static org.mockito.ArgumentMatchers.anyMap; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.when; import java.io.File; @@ -41,6 +42,8 @@ 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.biosdk.provider.factory.BioAPIFactory; +import io.mosip.kernel.biosdk.provider.spi.iBioProviderApi; import io.mosip.kernel.core.exception.BaseCheckedException; import io.mosip.registration.processor.core.auth.dto.AuthResponseDTO; import io.mosip.registration.processor.core.auth.dto.IndividualIdDto; @@ -50,6 +53,8 @@ import io.mosip.registration.processor.core.exception.ApisResourceAccessException; import io.mosip.registration.processor.core.exception.AuthSystemException; import io.mosip.registration.processor.core.exception.ValidationFailedException; +import io.mosip.registration.processor.core.http.ResponseWrapper; +import io.mosip.registration.processor.core.idrepo.dto.Documents; import io.mosip.registration.processor.core.idrepo.dto.IdResponseDTO; import io.mosip.registration.processor.core.idrepo.dto.ResponseDTO; import io.mosip.registration.processor.core.logger.LogDescription; @@ -71,7 +76,7 @@ import io.mosip.registration.processor.core.util.RegistrationExceptionMapperUtil; import io.mosip.registration.processor.packet.manager.idreposervice.IdRepoService; import io.mosip.registration.processor.packet.storage.utils.ABISHandlerUtil; -import io.mosip.registration.processor.packet.storage.utils.AuthUtil; +import io.mosip.registration.processor.packet.storage.utils.BioSdkUtil; import io.mosip.registration.processor.packet.storage.utils.OSIUtils; import io.mosip.registration.processor.packet.storage.utils.PriorityBasedPacketManagerService; import io.mosip.registration.processor.packet.storage.utils.Utilities; @@ -146,9 +151,19 @@ public class OperatorValidatorTest { @Mock private Utilities utility; + + + @Mock + private BioAPIFactory bio; + + @Mock + private iBioProviderApi bioProvider; @Mock - private AuthUtil authUtil; + private BioSdkUtil bioUtil; + + //@Mock + //private BioSdkUtil bioUtil; private Map metaInfo; @@ -207,6 +222,7 @@ public void setUp() throws Exception { Mockito.doNothing().when(description).setMessage(any()); Mockito.when(utility.isUinMissingFromIdAuth(any(),any(),any())).thenReturn(false); Mockito.when(registrationExceptionMapperUtil.getStatusCode(any())).thenReturn("ERROR"); + regOsiDto.setOfficerId("O1234"); regOsiDto.setOfficerHashedPin("officerHashedPin"); regOsiDto.setSupervisorId("S1234"); @@ -374,6 +390,13 @@ public void setUp() throws Exception { when(packetManagerService.getFieldByMappingJsonKey(anyString(), anyString(), anyString(), any())) .thenReturn("field"); + String data="adjfgJHDFKjhsdfjksdbf"; + List ld=new ArrayList<>(); + io.mosip.registration.processor.core.idrepo.dto.Documents d=new io.mosip.registration.processor.core.idrepo.dto.Documents(MappingJsonConstants.INDIVIDUAL_BIOMETRICS, data); + ld.add(d); + when(utility.retrieveIdrepoDocument(Mockito.anyString())).thenReturn(ld); + when(bio.getBioProvider(Mockito.any(), Mockito.any())).thenReturn(bioProvider); + when(bioProvider.verify(Mockito.anyList(), Mockito.anyList(), Mockito.any(), Mockito.any())).thenReturn(true); } /** @@ -381,14 +404,16 @@ public void setUp() throws Exception { * * @throws Exception the exception */ - @Test + @Test(expected = ValidationFailedException.class) public void testisValidOperatorSuccess() throws Exception { Mockito.when(registrationStatusService.checkUinAvailabilityForRid(any())).thenReturn(true); when(packetManagerService.getBiometricsByMappingJsonKey(anyString(), any(), any(), any())) - .thenReturn(biometricRecord); - registrationStatusDto.setRegistrationType("ACTIVATED"); - Mockito.when(authUtil.authByIdAuthentication(anyString(), any(), any())).thenReturn(authResponseDTO); + .thenReturn(null); + registrationStatusDto.setRegistrationType("ACTIVATED"); + + Mockito.when(restClientService.getApi(any(), any(), anyString(), any(), any())).thenReturn(userResponseDto); + doNothing().when(bioUtil).authenticateBiometrics(Mockito.anyString(), Mockito.anyString(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any()); operatorValidator.validate("reg1234", registrationStatusDto, regOsiDto); } @@ -443,8 +468,11 @@ public void testAuthByIdAuthenticationStatusInActive() throws Exception { Mockito.when(registrationStatusService.checkUinAvailabilityForRid(any())).thenReturn(true); when(packetManagerService.getBiometricsByMappingJsonKey(anyString(), any(), any(), any())) .thenReturn(biometricRecord); - Mockito.when(authUtil.authByIdAuthentication(anyString(), any(), any())).thenReturn(authResponseDTO); + doNothing().when(bioUtil).authenticateBiometrics(Mockito.anyString(), Mockito.anyString(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any()); registrationStatusDto.setRegistrationType("ACTIVATED"); + regOsiDto.setOfficerBiometricFileName(null); + regOsiDto.setOfficerOTPAuthentication(null); + regOsiDto.setOfficerHashedPwd(null); operatorValidator.validate("reg1234", registrationStatusDto, regOsiDto); } @@ -460,8 +488,8 @@ public void testAuthByIdAuthenticationStatusFailed() throws Exception { authResponseDTO.setErrors(Arrays.asList(errorDTO)); Mockito.when(registrationStatusService.checkUinAvailabilityForRid(any())).thenReturn(true); when(packetManagerService.getBiometricsByMappingJsonKey(anyString(), any(), any(), any())) - .thenReturn(biometricRecord); - Mockito.when(authUtil.authByIdAuthentication(anyString(), any(), any())).thenReturn(authResponseDTO); + .thenReturn(null); + doNothing().when(bioUtil).authenticateBiometrics(Mockito.anyString(), Mockito.anyString(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any()); registrationStatusDto.setRegistrationType("ACTIVATED"); operatorValidator.validate("reg1234", registrationStatusDto, regOsiDto); } @@ -575,7 +603,8 @@ public void testMappingNotFoundResponse() throws Exception { Mockito.when(registrationStatusService.checkUinAvailabilityForRid(any())).thenReturn(true); when(packetManagerService.getBiometricsByMappingJsonKey(anyString(), any(), any(), any())) .thenReturn(biometricRecord); - Mockito.when(authUtil.authByIdAuthentication(anyString(), any(), any())).thenReturn(authResponseDTO); + doNothing().when(bioUtil).authenticateBiometrics(Mockito.anyString(), Mockito.anyString(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any()); + regOsiDto.setPacketCreationDate(null); operatorValidator.validate("reg1234", registrationStatusDto, regOsiDto); } @@ -592,7 +621,10 @@ public void testUMCValidationFailed() throws Exception { .thenReturn(biometricRecord); Mockito.when(restClientService.getApi(any(), any(), anyString(), any(), any())) .thenReturn(userResponseDto).thenReturn(centerResponse); - Mockito.when(authUtil.authByIdAuthentication(anyString(), any(), any())).thenReturn(authResponseDTO); + doNothing().when(bioUtil).authenticateBiometrics(Mockito.anyString(), Mockito.anyString(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any()); + regOsiDto.setOfficerBiometricFileName(null); + regOsiDto.setOfficerHashedPwd(null); + regOsiDto.setOfficerOTPAuthentication(null); operatorValidator.validate("reg1234", registrationStatusDto, regOsiDto); } diff --git a/registration-processor/pre-processor/registration-processor-packet-classifier-stage/pom.xml b/registration-processor/pre-processor/registration-processor-packet-classifier-stage/pom.xml index 648118ceadb..ac9bdd4c9ac 100644 --- a/registration-processor/pre-processor/registration-processor-packet-classifier-stage/pom.xml +++ b/registration-processor/pre-processor/registration-processor-packet-classifier-stage/pom.xml @@ -1,122 +1,122 @@ - - - 4.0.0 - - - io.mosip.registrationprocessor - pre-processor - 1.2.0.1-B1 - - registration-processor-packet-classifier-stage - 1.2.0.1-B1 - jar - - UTF-8 - UTF-8 - - - - - - org.springframework.cloud - spring-cloud-starter-config - ${spring-cloud-config.version} - - - org.mockito - mockito-core - ${mockito.version} - test - - - com.h2database - h2 - ${h2.version} - - - - - - org.springframework - spring-context - ${spring-framework.version} - - - io.mosip.registrationprocessor - registration-processor-packet-manager - ${packet.manager.version} - - - io.mosip.registrationprocessor - registration-processor-registration-status-service-impl - ${registration.status.service.version} - - - io.mosip.registrationprocessor - registration-processor-rest-client - ${registration.processor.rest.client.version} - - - - io.mosip.registrationprocessor - registration-processor-message-sender-impl - ${registration.processor.message.sender.version} - - - commons-io - commons-io - ${commons.io.version} - - - junit - junit - 4.12 - test - - - io.mosip.registrationprocessor - registration-processor-core - ${registration.processor.core.version} - - - org.powermock - powermock-module-junit4 - ${powermock.module.junit4.version} - test - - - org.powermock - powermock-api-mockito2 - ${powermock.api.mockito.version} - test - - - io.mosip.registrationprocessor - registration-processor-info-storage-service - ${packet.info.storage.service.version} - - - io.mosip.kernel - kernel-core - ${kernel.core.version} - - - org.springframework.boot - spring-boot-starter-webflux - ${spring.boot.version} - - - org.mvel - mvel2 - 2.4.12.Final - - - - - - - + + + 4.0.0 + + + io.mosip.registrationprocessor + pre-processor + 1.2.0.1-B3-SNAPSHOT + + registration-processor-packet-classifier-stage + 1.2.0.1-B3-SNAPSHOT + jar + + UTF-8 + UTF-8 + + + + + + org.springframework.cloud + spring-cloud-starter-config + ${spring-cloud-config.version} + + + org.mockito + mockito-core + ${mockito.version} + test + + + com.h2database + h2 + ${h2.version} + + + + + + org.springframework + spring-context + ${spring-framework.version} + + + io.mosip.registrationprocessor + registration-processor-packet-manager + ${packet.manager.version} + + + io.mosip.registrationprocessor + registration-processor-registration-status-service-impl + ${registration.status.service.version} + + + io.mosip.registrationprocessor + registration-processor-rest-client + ${registration.processor.rest.client.version} + + + + io.mosip.registrationprocessor + registration-processor-message-sender-impl + ${registration.processor.message.sender.version} + + + commons-io + commons-io + ${commons.io.version} + + + junit + junit + 4.12 + test + + + io.mosip.registrationprocessor + registration-processor-core + ${registration.processor.core.version} + + + org.powermock + powermock-module-junit4 + ${powermock.module.junit4.version} + test + + + org.powermock + powermock-api-mockito2 + ${powermock.api.mockito.version} + test + + + io.mosip.registrationprocessor + registration-processor-info-storage-service + ${packet.info.storage.service.version} + + + io.mosip.kernel + kernel-core + ${kernel.core.version} + + + org.springframework.boot + spring-boot-starter-webflux + ${spring.boot.version} + + + org.mvel + mvel2 + 2.4.12.Final + + + + + + + diff --git a/registration-processor/pre-processor/registration-processor-packet-uploader-stage/pom.xml b/registration-processor/pre-processor/registration-processor-packet-uploader-stage/pom.xml index 58413e23803..a2d34372840 100644 --- a/registration-processor/pre-processor/registration-processor-packet-uploader-stage/pom.xml +++ b/registration-processor/pre-processor/registration-processor-packet-uploader-stage/pom.xml @@ -1,127 +1,127 @@ - - - 4.0.0 - - - registration-processor-packet-uploader-stage - - - io.mosip.registrationprocessor - pre-processor - 1.2.0.1-B1 - - 1.2.0.1-B1 - - UTF-8 - - - - - - junit - junit - test - - - - org.mockito - mockito-core - ${mockito.version} - test - - - - com.h2database - h2 - ${h2.version} - - - - - - org.powermock - powermock-module-junit4 - ${powermock.module.junit4.version} - test - - - org.powermock - powermock-api-mockito2 - ${powermock.api.mockito.version} - test - - - org.springframework - spring-context - ${spring-framework.version} - - - org.postgresql - postgresql - runtime - - - io.mosip.registrationprocessor - registration-processor-info-storage-service - ${packet.info.storage.service.version} - - - org.springframework.boot - spring-boot-starter-test - test - - - org.springframework.batch - spring-batch-test - test - - - io.mosip.registrationprocessor - registration-processor-registration-status-service-impl - ${registration.status.service.version} - - - io.mosip.registrationprocessor - registration-processor-rest-client - ${registration.processor.rest.client.version} - - - io.mosip.registrationprocessor - registration-processor-core - ${registration.processor.core.version} - - - com.h2database - h2 - - - org.mockito - mockito-core - test - - - org.awaitility - awaitility - ${awaitility.version} - test - - - org.json - json - 20180813 - - - io.mosip.commons - khazana - ${object.store.khazana.version} - - - - - - - - - - + + + 4.0.0 + + + registration-processor-packet-uploader-stage + + + io.mosip.registrationprocessor + pre-processor + 1.2.0.1-B3-SNAPSHOT + + 1.2.0.1-B3-SNAPSHOT + + UTF-8 + + + + + + junit + junit + test + + + + org.mockito + mockito-core + ${mockito.version} + test + + + + com.h2database + h2 + ${h2.version} + + + + + + org.powermock + powermock-module-junit4 + ${powermock.module.junit4.version} + test + + + org.powermock + powermock-api-mockito2 + ${powermock.api.mockito.version} + test + + + org.springframework + spring-context + ${spring-framework.version} + + + org.postgresql + postgresql + runtime + + + io.mosip.registrationprocessor + registration-processor-info-storage-service + ${packet.info.storage.service.version} + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.batch + spring-batch-test + test + + + io.mosip.registrationprocessor + registration-processor-registration-status-service-impl + ${registration.status.service.version} + + + io.mosip.registrationprocessor + registration-processor-rest-client + ${registration.processor.rest.client.version} + + + io.mosip.registrationprocessor + registration-processor-core + ${registration.processor.core.version} + + + com.h2database + h2 + + + org.mockito + mockito-core + test + + + org.awaitility + awaitility + ${awaitility.version} + test + + + org.json + json + 20180813 + + + io.mosip.commons + khazana + ${object.store.khazana.version} + + + + + + + + + + diff --git a/registration-processor/pre-processor/registration-processor-packet-uploader-stage/src/main/java/io/mosip/registration/processor/packet/uploader/service/PacketUploaderService.java b/registration-processor/pre-processor/registration-processor-packet-uploader-stage/src/main/java/io/mosip/registration/processor/packet/uploader/service/PacketUploaderService.java index 9a1601caf14..2b2029dca05 100644 --- a/registration-processor/pre-processor/registration-processor-packet-uploader-stage/src/main/java/io/mosip/registration/processor/packet/uploader/service/PacketUploaderService.java +++ b/registration-processor/pre-processor/registration-processor-packet-uploader-stage/src/main/java/io/mosip/registration/processor/packet/uploader/service/PacketUploaderService.java @@ -23,5 +23,5 @@ public interface PacketUploaderService { * @return the u */ public U validateAndUploadPacket(MessageDTO messageDTO, String stageName); - + } diff --git a/registration-processor/pre-processor/registration-processor-packet-uploader-stage/src/main/java/io/mosip/registration/processor/packet/uploader/service/impl/PacketUploaderServiceImpl.java b/registration-processor/pre-processor/registration-processor-packet-uploader-stage/src/main/java/io/mosip/registration/processor/packet/uploader/service/impl/PacketUploaderServiceImpl.java index 268f95b58d6..cb65f0b1ceb 100644 --- a/registration-processor/pre-processor/registration-processor-packet-uploader-stage/src/main/java/io/mosip/registration/processor/packet/uploader/service/impl/PacketUploaderServiceImpl.java +++ b/registration-processor/pre-processor/registration-processor-packet-uploader-stage/src/main/java/io/mosip/registration/processor/packet/uploader/service/impl/PacketUploaderServiceImpl.java @@ -19,6 +19,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; +import io.mosip.commons.khazana.exception.ObjectStoreAdapterException; import io.mosip.commons.khazana.spi.ObjectStoreAdapter; import io.mosip.kernel.core.exception.ExceptionUtils; import io.mosip.kernel.core.logger.spi.Logger; @@ -34,6 +35,7 @@ import io.mosip.registration.processor.core.code.RegistrationExceptionTypeCode; import io.mosip.registration.processor.core.code.RegistrationTransactionStatusCode; import io.mosip.registration.processor.core.code.RegistrationTransactionTypeCode; +import io.mosip.registration.processor.core.constant.LandingZoneTypeConstant; import io.mosip.registration.processor.core.constant.LoggerFileConstant; import io.mosip.registration.processor.core.exception.ApisResourceAccessException; import io.mosip.registration.processor.core.exception.ObjectStoreNotAccessibleException; @@ -88,6 +90,12 @@ public class PacketUploaderServiceImpl implements PacketUploaderService pathSegment = new ArrayList<>(); pathSegment.add(packetId + extention); byte[] packet = null; try { + if(landingZoneType.equalsIgnoreCase(LandingZoneTypeConstant.DMZ_SERVER)) { packet = (byte[]) restClient.getApi(ApiName.NGINXDMZURL, pathSegment, "", null, byte[].class); + } + else if(landingZoneType.equalsIgnoreCase(LandingZoneTypeConstant.OBJECT_STORE)) { + packet=IOUtils.toByteArray(objectStoreAdapter.getObject(landingZoneAccount, registrationId, null, null, packetId)); + if(packet==null) { + throw new ObjectStoreNotAccessibleException("Failed to get packet : " +packetId); + } + } } catch (ApisResourceAccessException e) { if (e.getCause() instanceof HttpClientErrorException) { HttpClientErrorException ex = (HttpClientErrorException) e.getCause(); @@ -576,6 +592,8 @@ private byte[] getPakcetFromDMZ(String packetId) throws ApisResourceAccessExcept throw new PacketNotFoundException(PlatformErrorMessages.RPR_PUM_PACKET_NOT_FOUND_EXCEPTION.getMessage(), ex); } else throw e; + } catch(ObjectStoreAdapterException e) { + throw e; } return packet; } @@ -634,4 +652,6 @@ public boolean isPacketAlreadyPresentInObjectStore(String id, String process) { return true; } + + } \ No newline at end of file diff --git a/registration-processor/pre-processor/registration-processor-packet-uploader-stage/src/main/java/io/mosip/registration/processor/packet/uploader/stage/PacketUploaderStage.java b/registration-processor/pre-processor/registration-processor-packet-uploader-stage/src/main/java/io/mosip/registration/processor/packet/uploader/stage/PacketUploaderStage.java index b923ff77419..234fc6f3af0 100644 --- a/registration-processor/pre-processor/registration-processor-packet-uploader-stage/src/main/java/io/mosip/registration/processor/packet/uploader/stage/PacketUploaderStage.java +++ b/registration-processor/pre-processor/registration-processor-packet-uploader-stage/src/main/java/io/mosip/registration/processor/packet/uploader/stage/PacketUploaderStage.java @@ -15,6 +15,7 @@ import io.mosip.registration.processor.core.constant.LoggerFileConstant; import io.mosip.registration.processor.core.logger.RegProcessorLogger; import io.mosip.registration.processor.packet.uploader.service.PacketUploaderService; +import io.vertx.core.Handler; /** * The Class PacketUploaderStage. diff --git a/registration-processor/pre-processor/registration-processor-packet-uploader-stage/src/test/java/io/mosip/registration/processor/packet/service/PacketUploaderServiceTest.java b/registration-processor/pre-processor/registration-processor-packet-uploader-stage/src/test/java/io/mosip/registration/processor/packet/service/PacketUploaderServiceTest.java index c2d09ae5592..2ef1f12fcfb 100644 --- a/registration-processor/pre-processor/registration-processor-packet-uploader-stage/src/test/java/io/mosip/registration/processor/packet/service/PacketUploaderServiceTest.java +++ b/registration-processor/pre-processor/registration-processor-packet-uploader-stage/src/test/java/io/mosip/registration/processor/packet/service/PacketUploaderServiceTest.java @@ -39,6 +39,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; import io.mosip.commons.khazana.exception.FileNotFoundInDestinationException; +import io.mosip.commons.khazana.exception.ObjectStoreAdapterException; import io.mosip.commons.khazana.spi.ObjectStoreAdapter; import io.mosip.kernel.core.exception.BaseUncheckedException; import io.mosip.kernel.core.util.HMACUtils2; @@ -141,7 +142,9 @@ public class PacketUploaderServiceTest { @Before public void setUp() throws IOException, ApisResourceAccessException, JsonProcessingException, NoSuchAlgorithmException { ReflectionTestUtils.setField(packetuploaderservice, "packetNames", "id,optional,evidence"); - ReflectionTestUtils.setField(packetuploaderservice, "isIterationAdditionEnabled", true); + ReflectionTestUtils.setField(packetuploaderservice, "landingZoneType", "DMZServer"); + ReflectionTestUtils.setField(packetuploaderservice, "landingZoneAccount", "LandingZoneAccount"); + file = new File("src/test/resources/1001.zip"); dto.setRid("1001"); dto.setReg_type("NEW"); @@ -177,7 +180,9 @@ public void setUp() throws IOException, ApisResourceAccessException, JsonProcess any(), anyList(), anyString(), any(), any())).thenReturn(new byte[2]); Mockito.when(objectStoreAdapter.putObject(any(), any(), any(), any(), any(), any())).thenReturn(true); Mockito.when(objectStoreAdapter.addObjectMetaData(any(), any(), any(), any(), any(), any())).thenReturn(new HashMap<>()); - + Mockito.when(objectStoreAdapter.putObject(any(), any(), any(), any(), any(), any())).thenReturn(true); + Mockito.when(objectStoreAdapter.getObject(any(), any(), any(), any(), any())).thenReturn(new FileInputStream(file)); + AdditionalInfoRequestDto additionalInfoRequestDto = new AdditionalInfoRequestDto(); additionalInfoRequestDto.setAdditionalInfoReqId("1001-BIOMETRIC_CORRECTION-1"); @@ -495,6 +500,18 @@ public void testNullPacketFromDMZ() throws ApisResourceAccessException { assertTrue(result.getInternalError()); assertFalse(result.getIsValid()); } + @Test + public void testObjectStorePacketFromDMZ() throws ApisResourceAccessException, PacketDecryptionFailureException { + ReflectionTestUtils.setField(packetuploaderservice, "landingZoneType", "ObjectStore"); + Mockito.when(registrationStatusService.getRegistrationStatus(Mockito.any(),Mockito.any(),Mockito.any(), Mockito.any())).thenReturn(entry); + ReflectionTestUtils.setField(packetuploaderservice, "maxRetryCount", 3); + + Mockito.when(virusScannerService.scanFile(Mockito.any(InputStream.class))).thenReturn(Boolean.TRUE); + Mockito.when(decryptor.decrypt(Mockito.any(), Mockito.any(),Mockito.any())).thenReturn(is); + MessageDTO result = packetuploaderservice.validateAndUploadPacket(dto, "PacketUploaderStage"); + assertTrue(result.getIsValid()); + } + @Test public void testPacketNotFoundInLandingZoneButAlreadyPresentInObjectStore() throws ApisResourceAccessException { diff --git a/registration-processor/pre-processor/registration-processor-packet-validator-stage/pom.xml b/registration-processor/pre-processor/registration-processor-packet-validator-stage/pom.xml index 409c4bf220f..e9f91aff301 100644 --- a/registration-processor/pre-processor/registration-processor-packet-validator-stage/pom.xml +++ b/registration-processor/pre-processor/registration-processor-packet-validator-stage/pom.xml @@ -1,114 +1,114 @@ - - - 4.0.0 - - - io.mosip.registrationprocessor - pre-processor - 1.2.0.1-B1 - - registration-processor-packet-validator-stage - 1.2.0.1-B1 - jar - - UTF-8 - UTF-8 - - - - - - org.springframework.cloud - spring-cloud-starter-config - ${spring-cloud-config.version} - - - org.mockito - mockito-core - ${mockito.version} - test - - - com.h2database - h2 - ${h2.version} - - - - - - org.springframework - spring-context - ${spring-framework.version} - - - io.mosip.registrationprocessor - registration-processor-packet-manager - ${packet.manager.version} - - - io.mosip.registrationprocessor - registration-processor-registration-status-service-impl - ${registration.status.service.version} - - - io.mosip.registrationprocessor - registration-processor-rest-client - ${registration.processor.rest.client.version} - - - io.mosip.registrationprocessor - registration-processor-message-sender-impl - ${registration.processor.message.sender.version} - - - commons-io - commons-io - ${commons.io.version} - - - junit - junit - 4.12 - test - - - io.mosip.registrationprocessor - registration-processor-core - ${registration.processor.core.version} - - - org.powermock - powermock-module-junit4 - ${powermock.module.junit4.version} - test - - - org.powermock - powermock-api-mockito2 - ${powermock.api.mockito.version} - test - - - io.mosip.registrationprocessor - registration-processor-info-storage-service - ${packet.info.storage.service.version} - - - io.mosip.kernel - kernel-core - ${kernel.core.version} - - - org.springframework.boot - spring-boot-starter-webflux - ${spring.boot.version} - - - - - - - + + + 4.0.0 + + + io.mosip.registrationprocessor + pre-processor + 1.2.0.1-B3-SNAPSHOT + + registration-processor-packet-validator-stage + 1.2.0.1-B3-SNAPSHOT + jar + + UTF-8 + UTF-8 + + + + + + org.springframework.cloud + spring-cloud-starter-config + ${spring-cloud-config.version} + + + org.mockito + mockito-core + ${mockito.version} + test + + + com.h2database + h2 + ${h2.version} + + + + + + org.springframework + spring-context + ${spring-framework.version} + + + io.mosip.registrationprocessor + registration-processor-packet-manager + ${packet.manager.version} + + + io.mosip.registrationprocessor + registration-processor-registration-status-service-impl + ${registration.status.service.version} + + + io.mosip.registrationprocessor + registration-processor-rest-client + ${registration.processor.rest.client.version} + + + io.mosip.registrationprocessor + registration-processor-message-sender-impl + ${registration.processor.message.sender.version} + + + commons-io + commons-io + ${commons.io.version} + + + junit + junit + 4.12 + test + + + io.mosip.registrationprocessor + registration-processor-core + ${registration.processor.core.version} + + + org.powermock + powermock-module-junit4 + ${powermock.module.junit4.version} + test + + + org.powermock + powermock-api-mockito2 + ${powermock.api.mockito.version} + test + + + io.mosip.registrationprocessor + registration-processor-info-storage-service + ${packet.info.storage.service.version} + + + io.mosip.kernel + kernel-core + ${kernel.core.version} + + + org.springframework.boot + spring-boot-starter-webflux + ${spring.boot.version} + + + + + + + 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 bb63f76892d..08aff65faf6 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 @@ -277,7 +277,7 @@ public MessageDTO process(MessageDTO object, String stageName) { object.setInternalError(Boolean.FALSE); registrationStatusDto.setUpdatedBy(USER); SyncRegistrationEntity regEntity = syncRegistrationService.findByWorkflowInstanceId(object.getWorkflowInstanceId()); - sendNotification(regEntity, registrationStatusDto, packetValidationDto.isTransactionSuccessful()); + sendNotification(regEntity, registrationStatusDto, packetValidationDto.isTransactionSuccessful(),isValidSupervisorStatus); } catch (PacketManagerException e) { regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), registrationId, @@ -546,7 +546,7 @@ private void updateErrorFlags(InternalRegistrationStatusDto registrationStatusDt } private void sendNotification(SyncRegistrationEntity regEntity, - InternalRegistrationStatusDto registrationStatusDto, boolean isTransactionSuccessful) { + InternalRegistrationStatusDto registrationStatusDto, boolean isTransactionSuccessful,boolean isValidSupervisorStatus) { try { String registrationId = registrationStatusDto.getRegistrationId(); if (regEntity.getOptionalValues() != null) { @@ -563,11 +563,11 @@ private void sendNotification(SyncRegistrationEntity regEntity, if (isTransactionSuccessful) { isProcessingSuccess = true; notificationUtility.sendNotification(registrationAdditionalInfoDTO, registrationStatusDto, - regEntity, allNotificationTypes, isProcessingSuccess); + regEntity, allNotificationTypes, isProcessingSuccess,isValidSupervisorStatus); } else { isProcessingSuccess = false; notificationUtility.sendNotification(registrationAdditionalInfoDTO, registrationStatusDto, - regEntity, allNotificationTypes, isProcessingSuccess); + regEntity, allNotificationTypes, isProcessingSuccess,isValidSupervisorStatus); } boolean isDeleted = syncRegistrationService.deleteAdditionalInfo(regEntity); if (isDeleted) { diff --git a/registration-processor/pre-processor/registration-processor-packet-validator-stage/src/main/java/io/mosip/registration/processor/stages/utils/NotificationTemplateType.java b/registration-processor/pre-processor/registration-processor-packet-validator-stage/src/main/java/io/mosip/registration/processor/stages/utils/NotificationTemplateType.java index ff581aa160d..303600499c9 100644 --- a/registration-processor/pre-processor/registration-processor-packet-validator-stage/src/main/java/io/mosip/registration/processor/stages/utils/NotificationTemplateType.java +++ b/registration-processor/pre-processor/registration-processor-packet-validator-stage/src/main/java/io/mosip/registration/processor/stages/utils/NotificationTemplateType.java @@ -24,6 +24,8 @@ public enum NotificationTemplateType { RES_UPDATE, /** The technical issue. */ - TECHNICAL_ISSUE + TECHNICAL_ISSUE, + + SUP_REJECT } diff --git a/registration-processor/pre-processor/registration-processor-packet-validator-stage/src/main/java/io/mosip/registration/processor/stages/utils/NotificationUtility.java b/registration-processor/pre-processor/registration-processor-packet-validator-stage/src/main/java/io/mosip/registration/processor/stages/utils/NotificationUtility.java index 2db51d91911..e3c63542a05 100644 --- a/registration-processor/pre-processor/registration-processor-packet-validator-stage/src/main/java/io/mosip/registration/processor/stages/utils/NotificationUtility.java +++ b/registration-processor/pre-processor/registration-processor-packet-validator-stage/src/main/java/io/mosip/registration/processor/stages/utils/NotificationUtility.java @@ -132,6 +132,8 @@ public class NotificationUtility { private static final String UIN_UPDATE=NOTIFICATION_TEMPLATE_CODE+"uin.update."; private static final String RES_UPDATE=NOTIFICATION_TEMPLATE_CODE+"resident.update."; private static final String TECHNICAL_ISSUE=NOTIFICATION_TEMPLATE_CODE+"technical.issue."; + private static final String SUP_REJECT=NOTIFICATION_TEMPLATE_CODE+"supervisor.reject."; + @Autowired @@ -139,7 +141,7 @@ public class NotificationUtility { public void sendNotification(RegistrationAdditionalInfoDTO registrationAdditionalInfoDTO, InternalRegistrationStatusDto registrationStatusDto, SyncRegistrationEntity regEntity, - String[] allNotificationTypes, boolean isProcessingSuccess) + String[] allNotificationTypes, boolean isProcessingSuccess,boolean isValidSupervisorStatus) throws ApisResourceAccessException, IOException, PacketManagerException, JsonProcessingException, JSONException { registrationId = regEntity.getRegistrationId(); LogDescription description = new LogDescription(); @@ -162,6 +164,8 @@ public void sendNotification(RegistrationAdditionalInfoDTO registrationAdditiona if (isProcessingSuccess) { type = setNotificationTemplateType(registrationStatusDto, type); + } else if (!isValidSupervisorStatus) { + type = NotificationTemplateType.SUP_REJECT; } else { type = NotificationTemplateType.TECHNICAL_ISSUE; } @@ -468,6 +472,11 @@ private void setTemplateAndSubject(NotificationTemplateType templatetype, String MessageSenderDTO.setEmailTemplateCode(env.getProperty(TECHNICAL_ISSUE+EMAIL)); MessageSenderDTO.setSubjectTemplateCode(env.getProperty(TECHNICAL_ISSUE+SUB)); break; + case SUP_REJECT: + MessageSenderDTO.setSmsTemplateCode(env.getProperty(SUP_REJECT+SMS)); + MessageSenderDTO.setEmailTemplateCode(env.getProperty(SUP_REJECT+EMAIL)); + MessageSenderDTO.setSubjectTemplateCode(env.getProperty(SUP_REJECT+SUB)); + break; default: break; } diff --git a/registration-processor/pre-processor/registration-processor-packet-validator-stage/src/main/java/io/mosip/registration/processor/stages/validator/impl/PacketValidatorImpl.java b/registration-processor/pre-processor/registration-processor-packet-validator-stage/src/main/java/io/mosip/registration/processor/stages/validator/impl/PacketValidatorImpl.java index fd70a208b4c..b8b101258c4 100644 --- a/registration-processor/pre-processor/registration-processor-packet-validator-stage/src/main/java/io/mosip/registration/processor/stages/validator/impl/PacketValidatorImpl.java +++ b/registration-processor/pre-processor/registration-processor-packet-validator-stage/src/main/java/io/mosip/registration/processor/stages/validator/impl/PacketValidatorImpl.java @@ -94,6 +94,21 @@ public boolean validate(String id, String process, PacketValidationDto packetVal .setPacketValidaionFailureMessage(StatusUtil.PACKET_MANAGER_VALIDATION_FAILURE.getMessage()); return false; } + + //Check consent + if(!checkConsentForPacket(id,process,ProviderStageName.PACKET_VALIDATOR)) + { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString(), id, + "ERROR =======>" + StatusUtil.PACKET_CONSENT_VALIDATION.getMessage()); + packetValidationDto + .setPacketValidatonStatusCode(StatusUtil.PACKET_CONSENT_VALIDATION.getCode()); + packetValidationDto + .setPacketValidaionFailureMessage(StatusUtil.PACKET_CONSENT_VALIDATION.getMessage()); + return false; + } + + if (process.equalsIgnoreCase(RegistrationType.UPDATE.toString()) || process.equalsIgnoreCase(RegistrationType.RES_UPDATE.toString())) { @@ -200,7 +215,7 @@ private boolean biometricsXSDValidation(String id, String process, PacketValidat LoggerFileConstant.REGISTRATIONID.toString(), id, "ERROR =======> " + StatusUtil.XSD_VALIDATION_EXCEPTION.getMessage()); packetValidationDto.setPacketValidaionFailureMessage( - StatusUtil.XSD_VALIDATION_EXCEPTION.getMessage() + e.getMessage()); + StatusUtil.XSD_VALIDATION_EXCEPTION.getMessage()); packetValidationDto.setPacketValidatonStatusCode(StatusUtil.XSD_VALIDATION_EXCEPTION.getCode()); return false; } else if (e instanceof BiometricSignatureValidationException) { @@ -250,10 +265,12 @@ private String getOperationsDataFromMetaInfo(String id, String process, String f private boolean applicantDocumentValidation(String registrationId, String process, PacketValidationDto packetValidationDto) throws ApisResourceAccessException, JsonProcessingException, PacketManagerException, IOException { - if (StringUtils.isNotEmpty(env.getProperty(VALIDATEAPPLICANTDOCUMENT)) && env.getProperty(VALIDATEAPPLICANTDOCUMENT).trim().equalsIgnoreCase(VALIDATIONFALSE)) + String validateApplicant=env.getProperty(VALIDATEAPPLICANTDOCUMENT); + if (validateApplicant!=null && validateApplicant.trim().equalsIgnoreCase(VALIDATIONFALSE)) return true; else { - if(StringUtils.isNotEmpty(env.getProperty(VALIDATEAPPLICANTDOCUMENTPROCESS)) && env.getProperty(VALIDATEAPPLICANTDOCUMENTPROCESS).contains(process)) { + String validateApplicantDocument=env.getProperty(VALIDATEAPPLICANTDOCUMENTPROCESS); + if(validateApplicantDocument!=null && validateApplicantDocument.contains(process)) { boolean result = applicantDocumentValidation.validateDocument(registrationId, process); if (!result) { packetValidationDto.setPacketValidaionFailureMessage(StatusUtil.APPLICANT_DOCUMENT_VALIDATION_FAILED.getMessage()); @@ -264,5 +281,19 @@ private boolean applicantDocumentValidation(String registrationId, String proces return true; } } + + private boolean checkConsentForPacket(String id, String process, ProviderStageName stageName) + throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { + + String val = packetManagerService.getField(id, MappingJsonConstants.CONSENT, process, stageName); + if (null!=val && StringUtils.isNotEmpty(val)) { + if (val.equalsIgnoreCase("N")) + return false; + } + return true; + + } + + } \ No newline at end of file diff --git a/registration-processor/pre-processor/registration-processor-packet-validator-stage/src/test/java/io/mosip/registration/processor/stages/packet/validator/PacketValidateProcessorTest.java b/registration-processor/pre-processor/registration-processor-packet-validator-stage/src/test/java/io/mosip/registration/processor/stages/packet/validator/PacketValidateProcessorTest.java index 6ad4d5fa305..4b52a8820a2 100644 --- a/registration-processor/pre-processor/registration-processor-packet-validator-stage/src/test/java/io/mosip/registration/processor/stages/packet/validator/PacketValidateProcessorTest.java +++ b/registration-processor/pre-processor/registration-processor-packet-validator-stage/src/test/java/io/mosip/registration/processor/stages/packet/validator/PacketValidateProcessorTest.java @@ -343,7 +343,7 @@ public void PacketValidationBaseCheckedExceptionTest() throws PacketValidatorExc public void notificationSendFailedTest() throws PacketValidatorException, ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException, JSONException { Mockito.doThrow(IOException.class).when(notificationUtility).sendNotification(any(), any(), any(), any(), - anyBoolean()); + anyBoolean(),anyBoolean()); MessageDTO object = packetValidateProcessor.process(messageDTO, stageName); assertTrue(object.getIsValid()); assertFalse(object.getInternalError()); diff --git a/registration-processor/pre-processor/registration-processor-quality-classifier-stage/pom.xml b/registration-processor/pre-processor/registration-processor-quality-classifier-stage/pom.xml index 833e75c92a3..bdb4c0718b6 100644 --- a/registration-processor/pre-processor/registration-processor-quality-classifier-stage/pom.xml +++ b/registration-processor/pre-processor/registration-processor-quality-classifier-stage/pom.xml @@ -1,97 +1,97 @@ - - - 4.0.0 - - io.mosip.registrationprocessor - pre-processor - 1.2.0.1-B1 - - - registration-processor-quality-classifier-stage - 1.2.0.1-B1 - - - UTF-8 - UTF-8 - - - - - - org.springframework.cloud - spring-cloud-starter-config - ${spring-cloud-config.version} - - - org.mockito - mockito-core - ${mockito.version} - test - - - com.h2database - h2 - 1.4.195 - - - - - - org.springframework - spring-context - ${spring-framework.version} - - - org.springframework - spring-tx - ${spring-framework.version} - - - io.mosip.registrationprocessor - registration-processor-core - ${registration.processor.core.version} - - - io.mosip.registrationprocessor - registration-processor-registration-status-service-impl - ${registration.status.service.version} - - - io.mosip.registrationprocessor - registration-processor-rest-client - ${registration.processor.rest.client.version} - - - io.mosip.registrationprocessor - registration-processor-info-storage-service - ${packet.info.storage.service.version} - - - io.mosip.kernel - kernel-core - ${kernel.core.version} - - - io.mosip.kernel - kernel-cbeffutil-api - ${kernel.cbeffutil.version} - - - org.powermock - powermock-module-junit4 - ${powermock.module.junit4.version} - test - - - org.powermock - powermock-api-mockito2 - ${powermock.api.mockito.version} - test - - - - - - + + + 4.0.0 + + io.mosip.registrationprocessor + pre-processor + 1.2.0.1-B3-SNAPSHOT + + + registration-processor-quality-classifier-stage + 1.2.0.1-B3-SNAPSHOT + + + UTF-8 + UTF-8 + + + + + + org.springframework.cloud + spring-cloud-starter-config + ${spring-cloud-config.version} + + + org.mockito + mockito-core + ${mockito.version} + test + + + com.h2database + h2 + 1.4.195 + + + + + + org.springframework + spring-context + ${spring-framework.version} + + + org.springframework + spring-tx + ${spring-framework.version} + + + io.mosip.registrationprocessor + registration-processor-core + ${registration.processor.core.version} + + + io.mosip.registrationprocessor + registration-processor-registration-status-service-impl + ${registration.status.service.version} + + + io.mosip.registrationprocessor + registration-processor-rest-client + ${registration.processor.rest.client.version} + + + io.mosip.registrationprocessor + registration-processor-info-storage-service + ${packet.info.storage.service.version} + + + io.mosip.kernel + kernel-core + ${kernel.core.version} + + + io.mosip.kernel + kernel-cbeffutil-api + ${kernel.cbeffutil.version} + + + org.powermock + powermock-module-junit4 + ${powermock.module.junit4.version} + test + + + org.powermock + powermock-api-mockito2 + ${powermock.api.mockito.version} + test + + + + + + \ No newline at end of file diff --git a/registration-processor/pre-processor/registration-processor-quality-classifier-stage/src/main/java/io/mosip/registration/processor/quality/classifier/stage/QualityClassifierStage.java b/registration-processor/pre-processor/registration-processor-quality-classifier-stage/src/main/java/io/mosip/registration/processor/quality/classifier/stage/QualityClassifierStage.java index f80106eec83..7ce659d388c 100644 --- a/registration-processor/pre-processor/registration-processor-quality-classifier-stage/src/main/java/io/mosip/registration/processor/quality/classifier/stage/QualityClassifierStage.java +++ b/registration-processor/pre-processor/registration-processor-quality-classifier-stage/src/main/java/io/mosip/registration/processor/quality/classifier/stage/QualityClassifierStage.java @@ -442,7 +442,7 @@ private Map getQualityTags(List birs) throws BiometricExcep BiometricType biometricType = bir.getBdbInfo().getType().get(0); BIR[] birArray = new BIR[1]; birArray[0] = bir; - if(!biometricType.name().equalsIgnoreCase(BiometricType.EXCEPTION_PHOTO.name()) ) { + if(!biometricType.name().equalsIgnoreCase(BiometricType.EXCEPTION_PHOTO.name())) { float[] qualityScoreresponse = getBioSdkInstance(biometricType).getSegmentQuality(birArray, null); float score = qualityScoreresponse[0]; diff --git a/registration-processor/pre-processor/registration-processor-securezone-notification-stage/pom.xml b/registration-processor/pre-processor/registration-processor-securezone-notification-stage/pom.xml index b3ab0e91704..2a9d8088b62 100644 --- a/registration-processor/pre-processor/registration-processor-securezone-notification-stage/pom.xml +++ b/registration-processor/pre-processor/registration-processor-securezone-notification-stage/pom.xml @@ -1,100 +1,100 @@ - - - - pre-processor - io.mosip.registrationprocessor - 1.2.0.1-B1 - - 4.0.0 - 1.2.0.1-B1 - - registration-processor-securezone-notification-stage - - - - - - junit - junit - test - - - - org.mockito - mockito-core - ${mockito.version} - test - - - - com.h2database - h2 - ${h2.version} - - - - - - - - org.powermock - powermock-module-junit4 - ${powermock.module.junit4.version} - test - - - org.powermock - powermock-api-mockito2 - ${powermock.api.mockito.version} - test - - - org.springframework - spring-context - ${spring-framework.version} - - - org.postgresql - postgresql - runtime - - - org.springframework.boot - spring-boot-starter-test - test - - - org.springframework.batch - spring-batch-test - test - - - io.mosip.registrationprocessor - registration-processor-registration-status-service-impl - ${registration.status.service.version} - - - io.mosip.registrationprocessor - registration-processor-core - ${registration.processor.core.version} - - - com.h2database - h2 - - - org.mockito - mockito-core - test - - - org.awaitility - awaitility - ${awaitility.version} - test - - - + + + + pre-processor + io.mosip.registrationprocessor + 1.2.0.1-B3-SNAPSHOT + + 4.0.0 + 1.2.0.1-B3-SNAPSHOT + + registration-processor-securezone-notification-stage + + + + + + junit + junit + test + + + + org.mockito + mockito-core + ${mockito.version} + test + + + + com.h2database + h2 + ${h2.version} + + + + + + + + org.powermock + powermock-module-junit4 + ${powermock.module.junit4.version} + test + + + org.powermock + powermock-api-mockito2 + ${powermock.api.mockito.version} + test + + + org.springframework + spring-context + ${spring-framework.version} + + + org.postgresql + postgresql + runtime + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.batch + spring-batch-test + test + + + io.mosip.registrationprocessor + registration-processor-registration-status-service-impl + ${registration.status.service.version} + + + io.mosip.registrationprocessor + registration-processor-core + ${registration.processor.core.version} + + + com.h2database + h2 + + + org.mockito + mockito-core + test + + + org.awaitility + awaitility + ${awaitility.version} + test + + + \ No newline at end of file diff --git a/registration-processor/pre-processor/registration-processor-securezone-notification-stage/src/main/java/io/mosip/registration/processor/securezone/notification/stage/SecurezoneNotificationStage.java b/registration-processor/pre-processor/registration-processor-securezone-notification-stage/src/main/java/io/mosip/registration/processor/securezone/notification/stage/SecurezoneNotificationStage.java index 2006859db41..7059daa8f37 100644 --- a/registration-processor/pre-processor/registration-processor-securezone-notification-stage/src/main/java/io/mosip/registration/processor/securezone/notification/stage/SecurezoneNotificationStage.java +++ b/registration-processor/pre-processor/registration-processor-securezone-notification-stage/src/main/java/io/mosip/registration/processor/securezone/notification/stage/SecurezoneNotificationStage.java @@ -1,385 +1,385 @@ -package io.mosip.registration.processor.securezone.notification.stage; - -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; -import java.util.stream.Collectors; - -import org.apache.commons.collections.CollectionUtils; -import org.apache.commons.lang3.exception.ExceptionUtils; -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.Component; - -import io.mosip.kernel.core.logger.spi.Logger; -import io.mosip.registration.processor.core.abstractverticle.MessageBusAddress; -import io.mosip.registration.processor.core.abstractverticle.MessageDTO; -import io.mosip.registration.processor.core.abstractverticle.MosipEventBus; -import io.mosip.registration.processor.core.abstractverticle.MosipRouter; -import io.mosip.registration.processor.core.abstractverticle.MosipVerticleAPIManager; -import io.mosip.registration.processor.core.code.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.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.status.util.StatusUtil; -import io.mosip.registration.processor.core.status.util.TrimExceptionMessage; -import io.mosip.registration.processor.core.util.RegistrationExceptionMapperUtil; -import io.mosip.registration.processor.rest.client.audit.builder.AuditLogRequestBuilder; -import io.mosip.registration.processor.status.code.RegistrationStatusCode; -import io.mosip.registration.processor.status.dto.InternalRegistrationStatusDto; -import io.mosip.registration.processor.status.dto.RegistrationStatusDto; -import io.mosip.registration.processor.status.dto.SyncRegistrationDto; -import io.mosip.registration.processor.status.dto.SyncResponseDto; -import io.mosip.registration.processor.status.entity.SyncRegistrationEntity; -import io.mosip.registration.processor.status.exception.TablenotAccessibleException; -import io.mosip.registration.processor.status.service.RegistrationStatusService; -import io.mosip.registration.processor.status.service.SyncRegistrationService; -import io.vertx.core.json.JsonObject; -import io.vertx.ext.web.RoutingContext; - -@Component -@Configuration -@ComponentScan(basePackages = { "${mosip.auth.adapter.impl.basepackage}", - "io.mosip.registration.processor.core.config", - "io.mosip.registration.processor.securezone.notification.config", - "io.mosip.registration.processor.packet.manager.config", "io.mosip.registration.processor.status.config", - "io.mosip.registration.processor.rest.client.config", "io.mosip.registration.processor.core.kernel.beans" }) -public class SecurezoneNotificationStage extends MosipVerticleAPIManager { - - private static final String STAGE_PROPERTY_PREFIX = "mosip.regproc.securezone.notification."; - - /** - * The reg proc logger. - */ - private static final Logger regProcLogger = RegProcessorLogger.getLogger(SecurezoneNotificationStage.class); - - /** - * The cluster url. - */ - @Value("${vertx.cluster.configuration}") - private String clusterManagerUrl; - - /** - * worker pool size. - */ - @Value("${worker.pool.size}") - private Integer workerPoolSize; - - /** - * The mosip event bus. - */ - private MosipEventBus mosipEventBus; - - @Value("${securezone.routing.enabled:true}") - private boolean routingEnabled; - - /** - * After this time intervel, message should be considered as expired (In - * seconds). - */ - @Value("${mosip.regproc.securezone.notification.message.expiry-time-limit}") - private Long messageExpiryTimeLimit; - - @Value("#{T(java.util.Arrays).asList('${registration.processor.main-processes:}')}") - private List mainProcesses; - - /** The Constant USER. */ - private static final String USER = "MOSIP_SYSTEM"; - - /** - * Mosip router for APIs - */ - @Autowired - private MosipRouter router; - - /** The registration status service. */ - @Autowired - private RegistrationStatusService registrationStatusService; - - @Autowired - private SyncRegistrationService syncRegistrationService; - - /** The core audit request builder. */ - @Autowired - private AuditLogRequestBuilder auditLogRequestBuilder; - - @Autowired - private RegistrationExceptionMapperUtil registrationStatusMapperUtil; - - /** - * Deploy verticle. - */ - public void deployVerticle() { - this.mosipEventBus = this.getEventBus(this, clusterManagerUrl, workerPoolSize); - this.consumeAndSend(mosipEventBus, MessageBusAddress.SECUREZONE_NOTIFICATION_IN, - MessageBusAddress.SECUREZONE_NOTIFICATION_OUT, messageExpiryTimeLimit); - } - - @Override - protected String getPropertyPrefix() { - return STAGE_PROPERTY_PREFIX; - } - - @Override - public void start() { - router.setRoute(this.postUrl(vertx, MessageBusAddress.SECUREZONE_NOTIFICATION_IN, - MessageBusAddress.SECUREZONE_NOTIFICATION_OUT)); - this.routes(router); - this.createServer(router.getRouter(), getPort()); - } - - /** - * contains all the routes in this stage - * - * @param router - */ - private void routes(MosipRouter router) { - router.post(getServletPath() + "/notification"); - router.handler(this::processURL, this::failure); - } - - /** - * method to process the context received. - * - * @param ctx the ctx - */ - public void processURL(RoutingContext ctx) { - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), "", - "SecurezoneNotificationStage::processURL()::entry"); - - MessageDTO messageDTO = new MessageDTO(); - try { - JsonObject obj = ctx.getBodyAsJson(); - messageDTO.setMessageBusAddress(MessageBusAddress.SECUREZONE_NOTIFICATION_IN); - messageDTO.setInternalError(Boolean.FALSE); - messageDTO.setRid(obj.getString("rid")); - messageDTO.setReg_type(obj.getString("reg_type")); - messageDTO.setIsValid(obj.getBoolean("isValid")); - messageDTO.setSource(obj.getString("source")); - messageDTO.setIteration(obj.getInteger("iteration")); - messageDTO.setWorkflowInstanceId(obj.getString("workflowInstanceId")); - MessageDTO result = process(messageDTO); - if (result.getIsValid()) { - sendMessage(result); - this.setResponse(ctx, - "Packet with registrationId '" + result.getRid() + "' has been forwarded to next stage"); - - regProcLogger.info(obj.getString("rid"), - "Packet with registrationId '" + result.getRid() + "' has been forwarded to next stage", - null, null); - } else { - this.setResponse(ctx, "Packet with registrationId '" + obj.getString("rid") - + "' has not been uploaded to file System"); - - regProcLogger.info(obj.getString("rid"), - "Packet with registrationId '" + result.getRid() + "' has not been uploaded to file System", - null, null); - } - } catch (Exception e) { - ctx.fail(e); - } - } - - /** - * This is for failure handler - * - * @param routingContext - */ - private void failure(RoutingContext routingContext) { - this.setResponse(routingContext, routingContext.failure().getMessage()); - } - - /** - * sends messageDTO to camel bridge. - * - * @param messageDTO the message DTO - */ - public void sendMessage(MessageDTO messageDTO) { - if (routingEnabled) - this.send(this.mosipEventBus, MessageBusAddress.SECUREZONE_NOTIFICATION_OUT, messageDTO); - } - - @Override - public MessageDTO process(MessageDTO messageDTO) { - InternalRegistrationStatusDto registrationStatusDto = new InternalRegistrationStatusDto(); - TrimExceptionMessage trimMessage = new TrimExceptionMessage(); - LogDescription description = new LogDescription(); - boolean isTransactionSuccessful = false; - try { - registrationStatusDto = registrationStatusService.getRegistrationStatus(messageDTO.getRid(), - messageDTO.getReg_type(), messageDTO.getIteration(), messageDTO.getWorkflowInstanceId()); - - boolean isDuplicatePacket = false; - if (registrationStatusDto != null) { - registrationStatusDto.setLatestTransactionTypeCode( - RegistrationTransactionTypeCode.SECUREZONE_NOTIFICATION.toString()); - registrationStatusDto.setRegistrationStageName(getStageName()); - isDuplicatePacket = isDuplicatePacketForSameReqId(messageDTO); - } else { - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), - LoggerFileConstant.REGISTRATIONID.toString(), messageDTO.getRid(), - "No records found in registration table for reg id - " + messageDTO.getRid()); - } - - if (!isDuplicatePacket && registrationStatusDto != null - && messageDTO.getRid().equalsIgnoreCase(registrationStatusDto.getRegistrationId())) { - registrationStatusDto - .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.SUCCESS.toString()); - messageDTO.setIsValid(Boolean.TRUE); - registrationStatusDto.setStatusComment(StatusUtil.NOTIFICATION_RECEIVED_TO_SECUREZONE.getMessage()); - registrationStatusDto.setSubStatusCode(StatusUtil.NOTIFICATION_RECEIVED_TO_SECUREZONE.getCode()); - registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); - - isTransactionSuccessful = true; - description.setMessage(PlatformSuccessMessages.RPR_SEZ_SECUREZONE_NOTIFICATION.getMessage() + " -- " - + messageDTO.getRid()); - description.setCode(PlatformSuccessMessages.RPR_SEZ_SECUREZONE_NOTIFICATION.getCode()); - - regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), - LoggerFileConstant.REGISTRATIONID.toString(), messageDTO.getRid(), - description.getCode() + description.getMessage()); - } else if (isDuplicatePacket) { - isTransactionSuccessful = false; - messageDTO.setIsValid(Boolean.FALSE); - registrationStatusDto.setSubStatusCode(StatusUtil.NOTIFICATION_RECEIVED_TO_SECUREZONE.getCode()); - description.setMessage(PlatformErrorMessages.RPR_SECUREZONE_DUPLICATE_PACKET.getMessage()); - description.setCode(PlatformErrorMessages.RPR_SECUREZONE_DUPLICATE_PACKET.getCode()); - registrationStatusDto - .setStatusComment(PlatformErrorMessages.RPR_SECUREZONE_DUPLICATE_PACKET.getMessage()); - registrationStatusDto.setStatusCode(RegistrationStatusCode.REJECTED.name()); - registrationStatusDto.setLatestTransactionStatusCode(RegistrationStatusCode.REJECTED.name()); - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), - LoggerFileConstant.REGISTRATIONID.toString(), messageDTO.getRid(), - PlatformErrorMessages.RPR_SECUREZONE_DUPLICATE_PACKET.getMessage()); - } else { - isTransactionSuccessful = false; - messageDTO.setIsValid(Boolean.FALSE); - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), - LoggerFileConstant.REGISTRATIONID.toString(), messageDTO.getRid(), - "Transaction failed. RID not found in registration table."); - } - } 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.DATA_ACCESS_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(), LoggerFileConstant.REGISTRATIONID.toString(), - description.getCode() + " -- " + messageDTO.getRid(), - PlatformErrorMessages.RPR_RGS_REGISTRATION_TABLE_NOT_ACCESSIBLE.getMessage() + e.getMessage() - + ExceptionUtils.getStackTrace(e)); - messageDTO.setInternalError(Boolean.TRUE); - messageDTO.setRid(registrationStatusDto.getRegistrationId()); - } catch (Exception e) { - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), - messageDTO.toString(), ExceptionUtils.getStackTrace(e)); - messageDTO.setIsValid(Boolean.FALSE); - description.setCode(PlatformErrorMessages.RPR_SECUREZONE_FAILURE.getCode()); - description.setMessage(PlatformErrorMessages.RPR_SECUREZONE_FAILURE.getMessage()); - } finally { - if (messageDTO.getInternalError() != null && messageDTO.getInternalError()) { - registrationStatusDto.setUpdatedBy(USER); - int retryCount = registrationStatusDto.getRetryCount() != null - ? registrationStatusDto.getRetryCount() + 1 - : 1; - registrationStatusDto.setRetryCount(retryCount); - updateErrorFlags(registrationStatusDto, messageDTO); - } - /** Module-Id can be Both Success/Error code */ - String moduleId = isTransactionSuccessful - ? PlatformSuccessMessages.RPR_SEZ_SECUREZONE_NOTIFICATION.getCode() - : description.getCode(); - String moduleName = ModuleName.SECUREZONE_NOTIFICATION.toString(); - registrationStatusService.updateRegistrationStatus(registrationStatusDto, moduleId, moduleName); - if (isTransactionSuccessful) - description.setMessage(PlatformSuccessMessages.RPR_SEZ_SECUREZONE_NOTIFICATION.getMessage()); - String eventId = isTransactionSuccessful ? EventId.RPR_401.toString() : EventId.RPR_405.toString(); - String eventName = isTransactionSuccessful ? EventName.GET.toString() : EventName.EXCEPTION.toString(); - String eventType = isTransactionSuccessful ? EventType.BUSINESS.toString() : EventType.SYSTEM.toString(); - - auditLogRequestBuilder.createAuditRequestBuilder(description.getMessage(), eventId, eventName, eventType, - moduleId, moduleName, messageDTO.getRid()); - } - return messageDTO; - } - - private boolean isDuplicatePacketForSameReqId(MessageDTO messageDTO) { - boolean isDuplicate = false; - SyncRegistrationEntity entity = syncRegistrationService - .findByWorkflowInstanceId(messageDTO.getWorkflowInstanceId()); - - if (entity.getAdditionalInfoReqId() == null && mainProcesses.contains(entity.getRegistrationType())) { - // find all main process records for same registrationId. - List entities = syncRegistrationService - .findByRegistrationId(entity.getRegistrationId()); - List mainProcessEntities = entities.stream() - .filter(e -> e.getAdditionalInfoReqId() == null).collect(Collectors.toList()); - isDuplicate = checkDuplicates(messageDTO, mainProcessEntities); - } else { - // find all records for same additionalInfoReqId. - List entities = syncRegistrationService - .findByAdditionalInfoReqId(entity.getAdditionalInfoReqId()); - // if multiple records are present for same additionalInfoReqId then check in - // registration table how many packets are received - isDuplicate = checkDuplicates(messageDTO, entities); - } - return isDuplicate; - } - - private boolean checkDuplicates(MessageDTO messageDTO, List entities) { - if (!CollectionUtils.isEmpty(entities) && entities.size() > 1) { - List workflowInstanceIds = entities.stream().map(e -> e.getWorkflowInstanceId()) - .collect(Collectors.toList()); - List dtos = new ArrayList<>(); - for (String workflowInstanceId : workflowInstanceIds) { - InternalRegistrationStatusDto dto = registrationStatusService.getRegistrationStatus(messageDTO.getRid(), - messageDTO.getReg_type(), messageDTO.getIteration(), workflowInstanceId); - if (dto != null) - dtos.add(dto); - } - Optional currentPacketOptional = dtos.stream() - .filter(d -> d.getWorkflowInstanceId() != null - && d.getWorkflowInstanceId().equalsIgnoreCase(messageDTO.getWorkflowInstanceId())) - .findAny(); - if (currentPacketOptional.isPresent()) { - InternalRegistrationStatusDto currentPacket = currentPacketOptional.get(); - // remove current packet from list so that it contains only other packets - // received for same additionalInfoReqId - dtos.remove(currentPacket); - for (InternalRegistrationStatusDto otherPacket : dtos) { - if (otherPacket.getCreateDateTime().isBefore(currentPacket.getCreateDateTime())) { - messageDTO.setIsValid(Boolean.FALSE); - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), - LoggerFileConstant.REGISTRATIONID.toString(), messageDTO.getRid(), - "Packet already received for same registrationId."); - return true; - } - } - } - } - return false; - } - - private void updateErrorFlags(InternalRegistrationStatusDto registrationStatusDto, MessageDTO object) { - object.setInternalError(true); - if (registrationStatusDto.getLatestTransactionStatusCode() - .equalsIgnoreCase(RegistrationTransactionStatusCode.REPROCESS.toString())) { - object.setIsValid(true); - } else { - object.setIsValid(false); - } - } -} +package io.mosip.registration.processor.securezone.notification.stage; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; + +import org.apache.commons.collections.CollectionUtils; +import org.apache.commons.lang3.exception.ExceptionUtils; +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.Component; + +import io.mosip.kernel.core.logger.spi.Logger; +import io.mosip.registration.processor.core.abstractverticle.MessageBusAddress; +import io.mosip.registration.processor.core.abstractverticle.MessageDTO; +import io.mosip.registration.processor.core.abstractverticle.MosipEventBus; +import io.mosip.registration.processor.core.abstractverticle.MosipRouter; +import io.mosip.registration.processor.core.abstractverticle.MosipVerticleAPIManager; +import io.mosip.registration.processor.core.code.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.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.status.util.StatusUtil; +import io.mosip.registration.processor.core.status.util.TrimExceptionMessage; +import io.mosip.registration.processor.core.util.RegistrationExceptionMapperUtil; +import io.mosip.registration.processor.rest.client.audit.builder.AuditLogRequestBuilder; +import io.mosip.registration.processor.status.code.RegistrationStatusCode; +import io.mosip.registration.processor.status.dto.InternalRegistrationStatusDto; +import io.mosip.registration.processor.status.dto.RegistrationStatusDto; +import io.mosip.registration.processor.status.dto.SyncRegistrationDto; +import io.mosip.registration.processor.status.dto.SyncResponseDto; +import io.mosip.registration.processor.status.entity.SyncRegistrationEntity; +import io.mosip.registration.processor.status.exception.TablenotAccessibleException; +import io.mosip.registration.processor.status.service.RegistrationStatusService; +import io.mosip.registration.processor.status.service.SyncRegistrationService; +import io.vertx.core.json.JsonObject; +import io.vertx.ext.web.RoutingContext; + +@Component +@Configuration +@ComponentScan(basePackages = { "${mosip.auth.adapter.impl.basepackage}", + "io.mosip.registration.processor.core.config", + "io.mosip.registration.processor.securezone.notification.config", + "io.mosip.registration.processor.packet.manager.config", "io.mosip.registration.processor.status.config", + "io.mosip.registration.processor.rest.client.config", "io.mosip.registration.processor.core.kernel.beans" }) +public class SecurezoneNotificationStage extends MosipVerticleAPIManager { + + private static final String STAGE_PROPERTY_PREFIX = "mosip.regproc.securezone.notification."; + + /** + * The reg proc logger. + */ + private static final Logger regProcLogger = RegProcessorLogger.getLogger(SecurezoneNotificationStage.class); + + /** + * The cluster url. + */ + @Value("${vertx.cluster.configuration}") + private String clusterManagerUrl; + + /** + * worker pool size. + */ + @Value("${worker.pool.size}") + private Integer workerPoolSize; + + /** + * The mosip event bus. + */ + private MosipEventBus mosipEventBus; + + @Value("${securezone.routing.enabled:true}") + private boolean routingEnabled; + + /** + * After this time intervel, message should be considered as expired (In + * seconds). + */ + @Value("${mosip.regproc.securezone.notification.message.expiry-time-limit}") + private Long messageExpiryTimeLimit; + + @Value("#{T(java.util.Arrays).asList('${registration.processor.main-processes:}')}") + private List mainProcesses; + + /** The Constant USER. */ + private static final String USER = "MOSIP_SYSTEM"; + + /** + * Mosip router for APIs + */ + @Autowired + private MosipRouter router; + + /** The registration status service. */ + @Autowired + private RegistrationStatusService registrationStatusService; + + @Autowired + private SyncRegistrationService syncRegistrationService; + + /** The core audit request builder. */ + @Autowired + private AuditLogRequestBuilder auditLogRequestBuilder; + + @Autowired + private RegistrationExceptionMapperUtil registrationStatusMapperUtil; + + /** + * Deploy verticle. + */ + public void deployVerticle() { + this.mosipEventBus = this.getEventBus(this, clusterManagerUrl, workerPoolSize); + this.consumeAndSend(mosipEventBus, MessageBusAddress.SECUREZONE_NOTIFICATION_IN, + MessageBusAddress.SECUREZONE_NOTIFICATION_OUT, messageExpiryTimeLimit); + } + + @Override + protected String getPropertyPrefix() { + return STAGE_PROPERTY_PREFIX; + } + + @Override + public void start() { + router.setRoute(this.postUrl(vertx, MessageBusAddress.SECUREZONE_NOTIFICATION_IN, + MessageBusAddress.SECUREZONE_NOTIFICATION_OUT)); + this.routes(router); + this.createServer(router.getRouter(), getPort()); + } + + /** + * contains all the routes in this stage + * + * @param router + */ + private void routes(MosipRouter router) { + router.post(getServletPath() + "/notification"); + router.handler(this::processURL, this::failure); + } + + /** + * method to process the context received. + * + * @param ctx the ctx + */ + public void processURL(RoutingContext ctx) { + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), "", + "SecurezoneNotificationStage::processURL()::entry"); + + MessageDTO messageDTO = new MessageDTO(); + try { + JsonObject obj = ctx.getBodyAsJson(); + messageDTO.setMessageBusAddress(MessageBusAddress.SECUREZONE_NOTIFICATION_IN); + messageDTO.setInternalError(Boolean.FALSE); + messageDTO.setRid(obj.getString("rid")); + messageDTO.setReg_type(obj.getString("reg_type")); + messageDTO.setIsValid(obj.getBoolean("isValid")); + messageDTO.setSource(obj.getString("source")); + messageDTO.setIteration(obj.getInteger("iteration")); + messageDTO.setWorkflowInstanceId(obj.getString("workflowInstanceId")); + MessageDTO result = process(messageDTO); + if (result.getIsValid()) { + sendMessage(result); + this.setResponse(ctx, + "Packet with registrationId '" + result.getRid() + "' has been forwarded to next stage"); + + regProcLogger.info(obj.getString("rid"), + "Packet with registrationId '" + result.getRid() + "' has been forwarded to next stage", + null, null); + } else { + this.setResponse(ctx, "Packet with registrationId '" + obj.getString("rid") + + "' has not been uploaded to file System"); + + regProcLogger.info(obj.getString("rid"), + "Packet with registrationId '" + result.getRid() + "' has not been uploaded to file System", + null, null); + } + } catch (Exception e) { + ctx.fail(e); + } + } + + /** + * This is for failure handler + * + * @param routingContext + */ + private void failure(RoutingContext routingContext) { + this.setResponse(routingContext, routingContext.failure().getMessage()); + } + + /** + * sends messageDTO to camel bridge. + * + * @param messageDTO the message DTO + */ + public void sendMessage(MessageDTO messageDTO) { + if (routingEnabled) + this.send(this.mosipEventBus, MessageBusAddress.SECUREZONE_NOTIFICATION_OUT, messageDTO); + } + + @Override + public MessageDTO process(MessageDTO messageDTO) { + InternalRegistrationStatusDto registrationStatusDto = new InternalRegistrationStatusDto(); + TrimExceptionMessage trimMessage = new TrimExceptionMessage(); + LogDescription description = new LogDescription(); + boolean isTransactionSuccessful = false; + try { + registrationStatusDto = registrationStatusService.getRegistrationStatus(messageDTO.getRid(), + messageDTO.getReg_type(), messageDTO.getIteration(), messageDTO.getWorkflowInstanceId()); + + boolean isDuplicatePacket = false; + if (registrationStatusDto != null) { + registrationStatusDto.setLatestTransactionTypeCode( + RegistrationTransactionTypeCode.SECUREZONE_NOTIFICATION.toString()); + registrationStatusDto.setRegistrationStageName(getStageName()); + isDuplicatePacket = isDuplicatePacketForSameReqId(messageDTO); + } else { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString(), messageDTO.getRid(), + "No records found in registration table for reg id - " + messageDTO.getRid()); + } + + if (!isDuplicatePacket && registrationStatusDto != null + && messageDTO.getRid().equalsIgnoreCase(registrationStatusDto.getRegistrationId())) { + registrationStatusDto + .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.SUCCESS.toString()); + messageDTO.setIsValid(Boolean.TRUE); + registrationStatusDto.setStatusComment(StatusUtil.NOTIFICATION_RECEIVED_TO_SECUREZONE.getMessage()); + registrationStatusDto.setSubStatusCode(StatusUtil.NOTIFICATION_RECEIVED_TO_SECUREZONE.getCode()); + registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); + + isTransactionSuccessful = true; + description.setMessage(PlatformSuccessMessages.RPR_SEZ_SECUREZONE_NOTIFICATION.getMessage() + " -- " + + messageDTO.getRid()); + description.setCode(PlatformSuccessMessages.RPR_SEZ_SECUREZONE_NOTIFICATION.getCode()); + + regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString(), messageDTO.getRid(), + description.getCode() + description.getMessage()); + } else if (isDuplicatePacket) { + isTransactionSuccessful = false; + messageDTO.setIsValid(Boolean.FALSE); + registrationStatusDto.setSubStatusCode(StatusUtil.NOTIFICATION_RECEIVED_TO_SECUREZONE.getCode()); + description.setMessage(PlatformErrorMessages.RPR_SECUREZONE_DUPLICATE_PACKET.getMessage()); + description.setCode(PlatformErrorMessages.RPR_SECUREZONE_DUPLICATE_PACKET.getCode()); + registrationStatusDto + .setStatusComment(PlatformErrorMessages.RPR_SECUREZONE_DUPLICATE_PACKET.getMessage()); + registrationStatusDto.setStatusCode(RegistrationStatusCode.REJECTED.name()); + registrationStatusDto.setLatestTransactionStatusCode(RegistrationStatusCode.REJECTED.name()); + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString(), messageDTO.getRid(), + PlatformErrorMessages.RPR_SECUREZONE_DUPLICATE_PACKET.getMessage()); + } else { + isTransactionSuccessful = false; + messageDTO.setIsValid(Boolean.FALSE); + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString(), messageDTO.getRid(), + "Transaction failed. RID not found in registration table."); + } + } 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.DATA_ACCESS_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(), LoggerFileConstant.REGISTRATIONID.toString(), + description.getCode() + " -- " + messageDTO.getRid(), + PlatformErrorMessages.RPR_RGS_REGISTRATION_TABLE_NOT_ACCESSIBLE.getMessage() + e.getMessage() + + ExceptionUtils.getStackTrace(e)); + messageDTO.setInternalError(Boolean.TRUE); + messageDTO.setRid(registrationStatusDto.getRegistrationId()); + } catch (Exception e) { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), + messageDTO.toString(), ExceptionUtils.getStackTrace(e)); + messageDTO.setIsValid(Boolean.FALSE); + description.setCode(PlatformErrorMessages.RPR_SECUREZONE_FAILURE.getCode()); + description.setMessage(PlatformErrorMessages.RPR_SECUREZONE_FAILURE.getMessage()); + } finally { + if (messageDTO.getInternalError() != null && messageDTO.getInternalError()) { + registrationStatusDto.setUpdatedBy(USER); + int retryCount = registrationStatusDto.getRetryCount() != null + ? registrationStatusDto.getRetryCount() + 1 + : 1; + registrationStatusDto.setRetryCount(retryCount); + updateErrorFlags(registrationStatusDto, messageDTO); + } + /** Module-Id can be Both Success/Error code */ + String moduleId = isTransactionSuccessful + ? PlatformSuccessMessages.RPR_SEZ_SECUREZONE_NOTIFICATION.getCode() + : description.getCode(); + String moduleName = ModuleName.SECUREZONE_NOTIFICATION.toString(); + registrationStatusService.updateRegistrationStatus(registrationStatusDto, moduleId, moduleName); + if (isTransactionSuccessful) + description.setMessage(PlatformSuccessMessages.RPR_SEZ_SECUREZONE_NOTIFICATION.getMessage()); + String eventId = isTransactionSuccessful ? EventId.RPR_401.toString() : EventId.RPR_405.toString(); + String eventName = isTransactionSuccessful ? EventName.GET.toString() : EventName.EXCEPTION.toString(); + String eventType = isTransactionSuccessful ? EventType.BUSINESS.toString() : EventType.SYSTEM.toString(); + + auditLogRequestBuilder.createAuditRequestBuilder(description.getMessage(), eventId, eventName, eventType, + moduleId, moduleName, messageDTO.getRid()); + } + return messageDTO; + } + + private boolean isDuplicatePacketForSameReqId(MessageDTO messageDTO) { + boolean isDuplicate = false; + SyncRegistrationEntity entity = syncRegistrationService + .findByWorkflowInstanceId(messageDTO.getWorkflowInstanceId()); + + if (entity.getAdditionalInfoReqId() == null && mainProcesses.contains(entity.getRegistrationType())) { + // find all main process records for same registrationId. + List entities = syncRegistrationService + .findByRegistrationId(entity.getRegistrationId()); + List mainProcessEntities = entities.stream() + .filter(e -> e.getAdditionalInfoReqId() == null).collect(Collectors.toList()); + isDuplicate = checkDuplicates(messageDTO, mainProcessEntities); + } else { + // find all records for same additionalInfoReqId. + List entities = syncRegistrationService + .findByAdditionalInfoReqId(entity.getAdditionalInfoReqId()); + // if multiple records are present for same additionalInfoReqId then check in + // registration table how many packets are received + isDuplicate = checkDuplicates(messageDTO, entities); + } + return isDuplicate; + } + + private boolean checkDuplicates(MessageDTO messageDTO, List entities) { + if (!CollectionUtils.isEmpty(entities) && entities.size() > 1) { + List workflowInstanceIds = entities.stream().map(e -> e.getWorkflowInstanceId()) + .collect(Collectors.toList()); + List dtos = new ArrayList<>(); + for (String workflowInstanceId : workflowInstanceIds) { + InternalRegistrationStatusDto dto = registrationStatusService.getRegistrationStatus(messageDTO.getRid(), + messageDTO.getReg_type(), messageDTO.getIteration(), workflowInstanceId); + if (dto != null) + dtos.add(dto); + } + Optional currentPacketOptional = dtos.stream() + .filter(d -> d.getWorkflowInstanceId() != null + && d.getWorkflowInstanceId().equalsIgnoreCase(messageDTO.getWorkflowInstanceId())) + .findAny(); + if (currentPacketOptional.isPresent()) { + InternalRegistrationStatusDto currentPacket = currentPacketOptional.get(); + // remove current packet from list so that it contains only other packets + // received for same additionalInfoReqId + dtos.remove(currentPacket); + for (InternalRegistrationStatusDto otherPacket : dtos) { + if (otherPacket.getCreateDateTime().isBefore(currentPacket.getCreateDateTime())) { + messageDTO.setIsValid(Boolean.FALSE); + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString(), messageDTO.getRid(), + "Packet already received for same registrationId."); + return true; + } + } + } + } + return false; + } + + private void updateErrorFlags(InternalRegistrationStatusDto registrationStatusDto, MessageDTO object) { + object.setInternalError(true); + if (registrationStatusDto.getLatestTransactionStatusCode() + .equalsIgnoreCase(RegistrationTransactionStatusCode.REPROCESS.toString())) { + object.setIsValid(true); + } else { + object.setIsValid(false); + } + } +} diff --git a/registration-processor/pre-processor/registration-processor-securezone-notification-stage/src/test/java/io/mosip/registration/processor/securezone/notification/stage/SecurezoneNotificationStageTest.java b/registration-processor/pre-processor/registration-processor-securezone-notification-stage/src/test/java/io/mosip/registration/processor/securezone/notification/stage/SecurezoneNotificationStageTest.java index 49506d43b7c..86171c89847 100644 --- a/registration-processor/pre-processor/registration-processor-securezone-notification-stage/src/test/java/io/mosip/registration/processor/securezone/notification/stage/SecurezoneNotificationStageTest.java +++ b/registration-processor/pre-processor/registration-processor-securezone-notification-stage/src/test/java/io/mosip/registration/processor/securezone/notification/stage/SecurezoneNotificationStageTest.java @@ -1,538 +1,538 @@ -package io.mosip.registration.processor.securezone.notification.stage; - -import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyString; - -import java.io.InputStream; -import java.time.LocalDateTime; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.util.ReflectionTestUtils; - -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.RegistrationExceptionTypeCode; -import io.mosip.registration.processor.core.http.ResponseWrapper; -import io.mosip.registration.processor.core.util.RegistrationExceptionMapperUtil; -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.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; -import io.vertx.core.AsyncResult; -import io.vertx.core.Handler; -import io.vertx.core.MultiMap; -import io.vertx.core.Vertx; -import io.vertx.core.buffer.Buffer; -import io.vertx.core.http.HttpMethod; -import io.vertx.core.http.HttpServerRequest; -import io.vertx.core.http.HttpServerResponse; -import io.vertx.core.json.JsonArray; -import io.vertx.core.json.JsonObject; -import io.vertx.ext.auth.User; -import io.vertx.ext.web.Cookie; -import io.vertx.ext.web.FileUpload; -import io.vertx.ext.web.Locale; -import io.vertx.ext.web.ParsedHeaderValues; -import io.vertx.ext.web.Route; -import io.vertx.ext.web.Router; -import io.vertx.ext.web.RoutingContext; -import io.vertx.ext.web.Session; - -@RunWith(SpringRunner.class) -public class SecurezoneNotificationStageTest { - - private static final int maxRetryCount = 5; - - private static final InputStream stream = Mockito.mock(InputStream.class); - - MessageDTO messageDTO= new MessageDTO(); - - /** The registration status service. */ - @Mock - RegistrationStatusService registrationStatusService; - - @Mock - private SyncRegistrationService syncRegistrationService; - - @Mock - private RegistrationExceptionMapperUtil registrationStatusMapperUtil; - - @Mock - private AuditLogRequestBuilder auditLogRequestBuilder; - - private RoutingContext ctx; - private Boolean responseObject; - - @Mock - private MosipRouter router; - - @InjectMocks - SecurezoneNotificationStage notificationStage = new SecurezoneNotificationStage() { - - @Override - public void setResponse(RoutingContext ctx, Object object) { - responseObject = Boolean.TRUE; - } - - @Override - public void send(MosipEventBus mosipEventBus, MessageBusAddress toAddress, MessageDTO message) { - } - - @Override - public MosipEventBus getEventBus(Object verticleName, String url, int instanceNumber) { - return null; - } - - @Override - public void createServer(Router route, int port) - { - - } - @Override - public Router postUrl(Vertx vertx, MessageBusAddress consumeAddress, MessageBusAddress sendAddress) { - return null; - } - }; - - private RoutingContext setContext() { - return new RoutingContext() { - - @Override - public Set fileUploads() { - return null; - } - - @Override - public Vertx vertx() { - return null; - } - - @Override - public User user() { - return null; - } - - @Override - public int statusCode() { - return 0; - } - - @Override - public void setUser(User user) { - } - - @Override - public void setSession(Session session) { - } - - @Override - public void setBody(Buffer body) { - } - - @Override - public void setAcceptableContentType(String contentType) { - } - - @Override - public Session session() { - return null; - } - - @Override - public HttpServerResponse response() { - return null; - } - - @Override - public void reroute(HttpMethod method, String path) { - } - - @Override - public HttpServerRequest request() { - return null; - } - - @Override - public boolean removeHeadersEndHandler(int handlerID) { - return false; - } - - @Override - public Cookie removeCookie(String name, boolean invalidate) { - return null; - } - - @Override - public boolean removeBodyEndHandler(int handlerID) { - return false; - } - - @Override - public T remove(String key) { - return null; - } - - @Override - public MultiMap queryParams() { - return null; - } - - @Override - public List queryParam(String query) { - return null; - } - - @Override - public RoutingContext put(String key, Object obj) { - return null; - } - - @Override - public Map pathParams() { - return null; - } - - @Override - public String pathParam(String name) { - return null; - } - - @Override - public ParsedHeaderValues parsedHeaders() { - return null; - } - - @Override - public String normalisedPath() { - return null; - } - - @Override - public void next() { - } - - @Override - public String mountPoint() { - return null; - } - - @Override - public Cookie getCookie(String name) { - return null; - } - - @Override - public String getBodyAsString(String encoding) { - return null; - } - - @Override - public String getBodyAsString() { - return null; - } - - @Override - public JsonArray getBodyAsJsonArray() { - return null; - } - - @Override - public JsonObject getBodyAsJson() { - JsonObject obj = new JsonObject(); - obj.put("rid", "2018701130000410092018110735"); - obj.put("isValid", true); - obj.put("internalError", false); - obj.put("reg_type", "NEW"); - obj.put("source", "REGISTRATIONCLIENT"); - obj.put("iteration", 1); - obj.put("workflowInstanceId", "78fc3d34-03f5-11ec-9a03-0242ac130003"); - return obj; - } - - @Override - public Buffer getBody() { - return null; - } - - @Override - public String getAcceptableContentType() { - return null; - } - - @Override - public T get(String key) { - return null; - } - - @Override - public Throwable failure() { - return null; - } - - @Override - public boolean failed() { - return false; - } - - @Override - public void fail(Throwable throwable) { - } - - @Override - public void fail(int statusCode) { - } - - @Override - public Map data() { - return null; - } - - @Override - public Route currentRoute() { - return null; - } - - @Override - public Set cookies() { - return null; - } - - @Override - public int cookieCount() { - return 0; - } - - @Override - public void clearUser() { - } - - @Override - public int addHeadersEndHandler(Handler handler) { - return 0; - } - - @Override - public RoutingContext addCookie(Cookie cookie) { - return null; - } - - @Override - public int addBodyEndHandler(Handler handler) { - return 0; - } - - @Override - public List acceptableLocales() { - return null; - } - - @Override - public RoutingContext addCookie(io.vertx.core.http.Cookie arg0) { - return null; - } - - @Override - public int addEndHandler(Handler> arg0) { - return 0; - } - - @Override - public Map cookieMap() { - return null; - } - - @Override - public void fail(int arg0, Throwable arg1) { - - } - - @Override - public boolean isSessionAccessed() { - return false; - } - - @Override - public boolean removeEndHandler(int arg0) { - return false; - } - - - }; - } - - InternalRegistrationStatusDto registrationStatusDto = new InternalRegistrationStatusDto(); - InternalRegistrationStatusDto registrationStatusDto1 = new InternalRegistrationStatusDto(); - List entities = new ArrayList(); - SyncRegistrationEntity entity = new SyncRegistrationEntity(); - SyncRegistrationEntity entity1 = new SyncRegistrationEntity(); - - @Before - public void setup() { - - registrationStatusDto = new InternalRegistrationStatusDto(); - registrationStatusDto.setRegistrationId("2018701130000410092018110735"); - registrationStatusDto.setStatusCode("SECUREZONE_NOTIFICATION_SUCCESS"); - registrationStatusDto.setWorkflowInstanceId("78fc3d34-03f5-11ec-9a03-0242ac130004"); - registrationStatusDto.setCreateDateTime(LocalDateTime.now().minusDays(1)); - - registrationStatusDto1 = new InternalRegistrationStatusDto(); - registrationStatusDto1.setRegistrationId("2018701130000410092018110735"); - registrationStatusDto1.setStatusCode("SECUREZONE_NOTIFICATION_SUCCESS"); - registrationStatusDto1.setWorkflowInstanceId("78fc3d34-03f5-11ec-9a03-0242ac130003"); - registrationStatusDto1.setCreateDateTime(LocalDateTime.now()); - - ResponseWrapper responseWrapper = new ResponseWrapper(); - AuditResponseDto auditResponseDto = new AuditResponseDto(); - responseWrapper.setResponse(auditResponseDto); - - entity.setAdditionalInfoReqId("abc"); - entity.setPacketId("2018701130000410092018110735"); - entity.setWorkflowInstanceId("78fc3d34-03f5-11ec-9a03-0242ac130003"); - - entity1.setAdditionalInfoReqId(null); - entity1.setPacketId("2018701130000410092018110735"); - entity1.setWorkflowInstanceId("78fc3d34-03f5-11ec-9a03-0242ac130003"); - - ctx = setContext(); - ReflectionTestUtils.setField(notificationStage, "workerPoolSize", 10); - ReflectionTestUtils.setField(notificationStage, "clusterManagerUrl", "/dummyPath"); - ReflectionTestUtils.setField(notificationStage, "messageExpiryTimeLimit", Long.valueOf(0)); - ReflectionTestUtils.setField(notificationStage, "mainProcesses", Arrays.asList("NEW","UPDATE","LOST")); - //ReflectionTestUtils.setField(notificationStage, "port", "7999"); - Mockito.when(router.post(Mockito.any())).thenReturn(null); - Mockito.doNothing().when(router).setRoute(Mockito.any()); - Mockito.doNothing().when(router).nonSecureHandler(Mockito.any(),Mockito.any()); - messageDTO.setRid("2018701130000410092018110735"); - messageDTO.setIsValid(true); - messageDTO.setInternalError(false); - messageDTO.setReg_type("NEW"); - messageDTO.setSource("REGISTRATIONCLIENT"); - messageDTO.setIteration(1); - messageDTO.setWorkflowInstanceId("78fc3d34-03f5-11ec-9a03-0242ac130003"); - - Mockito.doNothing().when(registrationStatusService).updateRegistrationStatus(any(),any(),any()); - Mockito.doReturn(responseWrapper).when(auditLogRequestBuilder).createAuditRequestBuilder(anyString(), anyString(), anyString(), - anyString(), anyString(), anyString(), anyString()); - entities.add(entity); - Mockito.when(registrationStatusMapperUtil.getStatusCode(any())).thenReturn("Something"); - Mockito.when(syncRegistrationService.findByWorkflowInstanceId(anyString())).thenReturn(entity); - Mockito.when(syncRegistrationService.findByAdditionalInfoReqId(anyString())).thenReturn(entities); - Mockito.when(registrationStatusService.getRegistrationStatus(anyString(), any(), any(), any())) - .thenReturn(registrationStatusDto); - } - - @Test - public void processURLTest() { - - notificationStage.processURL(ctx); - - assertTrue(responseObject); - } - - @Test - public void ridNotFoundTest() { - Mockito.when(registrationStatusService.getRegistrationStatus(anyString(), any(), any(), any())).thenReturn(null); - - notificationStage.processURL(ctx); - assertTrue(responseObject); - } - - @Test - public void duplicateRidFoundTest() { - - SyncRegistrationEntity syncEntity = new SyncRegistrationEntity(); - syncEntity.setAdditionalInfoReqId(null); - syncEntity.setRegistrationType("NEW"); - syncEntity.setPacketId("2018701130000410092018110735"); - syncEntity.setWorkflowInstanceId("78fc3d34-03f5-11ec-9a03-0242ac130004"); - entities.add(syncEntity); - entities.add(entity1); - - Mockito.when(registrationStatusService.getRegistrationStatus(anyString(), any(), any(), any())) - .thenReturn(registrationStatusDto).thenReturn(registrationStatusDto).thenReturn(registrationStatusDto1); - Mockito.when(syncRegistrationService.findByWorkflowInstanceId(anyString())).thenReturn(syncEntity); - Mockito.when(syncRegistrationService.findByRegistrationId(any())).thenReturn(entities); - notificationStage.processURL(ctx); - assertTrue(responseObject); - } - - @Test - public void duplicateAdditionalReqIdFoundTest() { - - SyncRegistrationEntity syncEntity = new SyncRegistrationEntity(); - syncEntity.setAdditionalInfoReqId("abc"); - syncEntity.setPacketId("2018701130000410092018110735"); - syncEntity.setWorkflowInstanceId("78fc3d34-03f5-11ec-9a03-0242ac130004"); - entities.add(syncEntity); - entities.add(entity); - - Mockito.when(registrationStatusService.getRegistrationStatus(anyString(), any(), any(), any())) - .thenReturn(registrationStatusDto).thenReturn(registrationStatusDto).thenReturn(registrationStatusDto1); - Mockito.when(syncRegistrationService.findByWorkflowInstanceId(anyString())).thenReturn(entity); - Mockito.when(syncRegistrationService.findByAdditionalInfoReqId(anyString())).thenReturn(entities); - notificationStage.processURL(ctx); - assertTrue(responseObject); - } - - @Test - public void processFailureURLTest() { - RoutingContext routingContext = Mockito.mock(RoutingContext.class); - routingContext.setBody(null); - notificationStage.processURL(routingContext); - assertEquals(responseObject, null); - } - - @Test - public void processTest() { - MessageDTO inputDto= new MessageDTO(); - inputDto.setInternalError(Boolean.FALSE); - inputDto.setIsValid(Boolean.TRUE); - inputDto.setRid("2018701130000410092018110735"); - inputDto.setWorkflowInstanceId("78fc3d34-03f5-11ec-9a03-0242ac130003"); - - Mockito.when(syncRegistrationService.findByWorkflowInstanceId(anyString())).thenReturn(entity); - Mockito.when(syncRegistrationService.findByAdditionalInfoReqId(anyString())).thenReturn(entities); - MessageDTO messageDTO = notificationStage.process(inputDto); - assertTrue(messageDTO.getIsValid()); - } - - @Test - public void dbExceptionTest() { - Mockito.when(registrationStatusService.getRegistrationStatus(anyString(), any(), any(), any())).thenThrow(new TablenotAccessibleException("exception")); - Mockito.when(registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.DATA_ACCESS_EXCEPTION)) - .thenReturn("REPROCESS"); - MessageDTO result = notificationStage.process(messageDTO); - assertTrue(result.getInternalError()); - } - - - @Test - public void genericExceptionTest() { - Mockito.when(syncRegistrationService - .findByWorkflowInstanceId(anyString())).thenThrow(new NullPointerException("exception")); - Mockito.when(registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.DATA_ACCESS_EXCEPTION)) - .thenReturn("REPROCESS"); - MessageDTO result = notificationStage.process(messageDTO); - assertFalse(result.getIsValid()); - } -} +package io.mosip.registration.processor.securezone.notification.stage; + +import static org.junit.Assert.*; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; + +import java.io.InputStream; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.util.ReflectionTestUtils; + +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.RegistrationExceptionTypeCode; +import io.mosip.registration.processor.core.http.ResponseWrapper; +import io.mosip.registration.processor.core.util.RegistrationExceptionMapperUtil; +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.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; +import io.vertx.core.AsyncResult; +import io.vertx.core.Handler; +import io.vertx.core.MultiMap; +import io.vertx.core.Vertx; +import io.vertx.core.buffer.Buffer; +import io.vertx.core.http.HttpMethod; +import io.vertx.core.http.HttpServerRequest; +import io.vertx.core.http.HttpServerResponse; +import io.vertx.core.json.JsonArray; +import io.vertx.core.json.JsonObject; +import io.vertx.ext.auth.User; +import io.vertx.ext.web.Cookie; +import io.vertx.ext.web.FileUpload; +import io.vertx.ext.web.Locale; +import io.vertx.ext.web.ParsedHeaderValues; +import io.vertx.ext.web.Route; +import io.vertx.ext.web.Router; +import io.vertx.ext.web.RoutingContext; +import io.vertx.ext.web.Session; + +@RunWith(SpringRunner.class) +public class SecurezoneNotificationStageTest { + + private static final int maxRetryCount = 5; + + private static final InputStream stream = Mockito.mock(InputStream.class); + + MessageDTO messageDTO= new MessageDTO(); + + /** The registration status service. */ + @Mock + RegistrationStatusService registrationStatusService; + + @Mock + private SyncRegistrationService syncRegistrationService; + + @Mock + private RegistrationExceptionMapperUtil registrationStatusMapperUtil; + + @Mock + private AuditLogRequestBuilder auditLogRequestBuilder; + + private RoutingContext ctx; + private Boolean responseObject; + + @Mock + private MosipRouter router; + + @InjectMocks + SecurezoneNotificationStage notificationStage = new SecurezoneNotificationStage() { + + @Override + public void setResponse(RoutingContext ctx, Object object) { + responseObject = Boolean.TRUE; + } + + @Override + public void send(MosipEventBus mosipEventBus, MessageBusAddress toAddress, MessageDTO message) { + } + + @Override + public MosipEventBus getEventBus(Object verticleName, String url, int instanceNumber) { + return null; + } + + @Override + public void createServer(Router route, int port) + { + + } + @Override + public Router postUrl(Vertx vertx, MessageBusAddress consumeAddress, MessageBusAddress sendAddress) { + return null; + } + }; + + private RoutingContext setContext() { + return new RoutingContext() { + + @Override + public Set fileUploads() { + return null; + } + + @Override + public Vertx vertx() { + return null; + } + + @Override + public User user() { + return null; + } + + @Override + public int statusCode() { + return 0; + } + + @Override + public void setUser(User user) { + } + + @Override + public void setSession(Session session) { + } + + @Override + public void setBody(Buffer body) { + } + + @Override + public void setAcceptableContentType(String contentType) { + } + + @Override + public Session session() { + return null; + } + + @Override + public HttpServerResponse response() { + return null; + } + + @Override + public void reroute(HttpMethod method, String path) { + } + + @Override + public HttpServerRequest request() { + return null; + } + + @Override + public boolean removeHeadersEndHandler(int handlerID) { + return false; + } + + @Override + public Cookie removeCookie(String name, boolean invalidate) { + return null; + } + + @Override + public boolean removeBodyEndHandler(int handlerID) { + return false; + } + + @Override + public T remove(String key) { + return null; + } + + @Override + public MultiMap queryParams() { + return null; + } + + @Override + public List queryParam(String query) { + return null; + } + + @Override + public RoutingContext put(String key, Object obj) { + return null; + } + + @Override + public Map pathParams() { + return null; + } + + @Override + public String pathParam(String name) { + return null; + } + + @Override + public ParsedHeaderValues parsedHeaders() { + return null; + } + + @Override + public String normalisedPath() { + return null; + } + + @Override + public void next() { + } + + @Override + public String mountPoint() { + return null; + } + + @Override + public Cookie getCookie(String name) { + return null; + } + + @Override + public String getBodyAsString(String encoding) { + return null; + } + + @Override + public String getBodyAsString() { + return null; + } + + @Override + public JsonArray getBodyAsJsonArray() { + return null; + } + + @Override + public JsonObject getBodyAsJson() { + JsonObject obj = new JsonObject(); + obj.put("rid", "2018701130000410092018110735"); + obj.put("isValid", true); + obj.put("internalError", false); + obj.put("reg_type", "NEW"); + obj.put("source", "REGISTRATIONCLIENT"); + obj.put("iteration", 1); + obj.put("workflowInstanceId", "78fc3d34-03f5-11ec-9a03-0242ac130003"); + return obj; + } + + @Override + public Buffer getBody() { + return null; + } + + @Override + public String getAcceptableContentType() { + return null; + } + + @Override + public T get(String key) { + return null; + } + + @Override + public Throwable failure() { + return null; + } + + @Override + public boolean failed() { + return false; + } + + @Override + public void fail(Throwable throwable) { + } + + @Override + public void fail(int statusCode) { + } + + @Override + public Map data() { + return null; + } + + @Override + public Route currentRoute() { + return null; + } + + @Override + public Set cookies() { + return null; + } + + @Override + public int cookieCount() { + return 0; + } + + @Override + public void clearUser() { + } + + @Override + public int addHeadersEndHandler(Handler handler) { + return 0; + } + + @Override + public RoutingContext addCookie(Cookie cookie) { + return null; + } + + @Override + public int addBodyEndHandler(Handler handler) { + return 0; + } + + @Override + public List acceptableLocales() { + return null; + } + + @Override + public RoutingContext addCookie(io.vertx.core.http.Cookie arg0) { + return null; + } + + @Override + public int addEndHandler(Handler> arg0) { + return 0; + } + + @Override + public Map cookieMap() { + return null; + } + + @Override + public void fail(int arg0, Throwable arg1) { + + } + + @Override + public boolean isSessionAccessed() { + return false; + } + + @Override + public boolean removeEndHandler(int arg0) { + return false; + } + + + }; + } + + InternalRegistrationStatusDto registrationStatusDto = new InternalRegistrationStatusDto(); + InternalRegistrationStatusDto registrationStatusDto1 = new InternalRegistrationStatusDto(); + List entities = new ArrayList(); + SyncRegistrationEntity entity = new SyncRegistrationEntity(); + SyncRegistrationEntity entity1 = new SyncRegistrationEntity(); + + @Before + public void setup() { + + registrationStatusDto = new InternalRegistrationStatusDto(); + registrationStatusDto.setRegistrationId("2018701130000410092018110735"); + registrationStatusDto.setStatusCode("SECUREZONE_NOTIFICATION_SUCCESS"); + registrationStatusDto.setWorkflowInstanceId("78fc3d34-03f5-11ec-9a03-0242ac130004"); + registrationStatusDto.setCreateDateTime(LocalDateTime.now().minusDays(1)); + + registrationStatusDto1 = new InternalRegistrationStatusDto(); + registrationStatusDto1.setRegistrationId("2018701130000410092018110735"); + registrationStatusDto1.setStatusCode("SECUREZONE_NOTIFICATION_SUCCESS"); + registrationStatusDto1.setWorkflowInstanceId("78fc3d34-03f5-11ec-9a03-0242ac130003"); + registrationStatusDto1.setCreateDateTime(LocalDateTime.now()); + + ResponseWrapper responseWrapper = new ResponseWrapper(); + AuditResponseDto auditResponseDto = new AuditResponseDto(); + responseWrapper.setResponse(auditResponseDto); + + entity.setAdditionalInfoReqId("abc"); + entity.setPacketId("2018701130000410092018110735"); + entity.setWorkflowInstanceId("78fc3d34-03f5-11ec-9a03-0242ac130003"); + + entity1.setAdditionalInfoReqId(null); + entity1.setPacketId("2018701130000410092018110735"); + entity1.setWorkflowInstanceId("78fc3d34-03f5-11ec-9a03-0242ac130003"); + + ctx = setContext(); + ReflectionTestUtils.setField(notificationStage, "workerPoolSize", 10); + ReflectionTestUtils.setField(notificationStage, "clusterManagerUrl", "/dummyPath"); + ReflectionTestUtils.setField(notificationStage, "messageExpiryTimeLimit", Long.valueOf(0)); + ReflectionTestUtils.setField(notificationStage, "mainProcesses", Arrays.asList("NEW","UPDATE","LOST")); + //ReflectionTestUtils.setField(notificationStage, "port", "7999"); + Mockito.when(router.post(Mockito.any())).thenReturn(null); + Mockito.doNothing().when(router).setRoute(Mockito.any()); + Mockito.doNothing().when(router).nonSecureHandler(Mockito.any(),Mockito.any()); + messageDTO.setRid("2018701130000410092018110735"); + messageDTO.setIsValid(true); + messageDTO.setInternalError(false); + messageDTO.setReg_type("NEW"); + messageDTO.setSource("REGISTRATIONCLIENT"); + messageDTO.setIteration(1); + messageDTO.setWorkflowInstanceId("78fc3d34-03f5-11ec-9a03-0242ac130003"); + + Mockito.doNothing().when(registrationStatusService).updateRegistrationStatus(any(),any(),any()); + Mockito.doReturn(responseWrapper).when(auditLogRequestBuilder).createAuditRequestBuilder(anyString(), anyString(), anyString(), + anyString(), anyString(), anyString(), anyString()); + entities.add(entity); + Mockito.when(registrationStatusMapperUtil.getStatusCode(any())).thenReturn("Something"); + Mockito.when(syncRegistrationService.findByWorkflowInstanceId(anyString())).thenReturn(entity); + Mockito.when(syncRegistrationService.findByAdditionalInfoReqId(anyString())).thenReturn(entities); + Mockito.when(registrationStatusService.getRegistrationStatus(anyString(), any(), any(), any())) + .thenReturn(registrationStatusDto); + } + + @Test + public void processURLTest() { + + notificationStage.processURL(ctx); + + assertTrue(responseObject); + } + + @Test + public void ridNotFoundTest() { + Mockito.when(registrationStatusService.getRegistrationStatus(anyString(), any(), any(), any())).thenReturn(null); + + notificationStage.processURL(ctx); + assertTrue(responseObject); + } + + @Test + public void duplicateRidFoundTest() { + + SyncRegistrationEntity syncEntity = new SyncRegistrationEntity(); + syncEntity.setAdditionalInfoReqId(null); + syncEntity.setRegistrationType("NEW"); + syncEntity.setPacketId("2018701130000410092018110735"); + syncEntity.setWorkflowInstanceId("78fc3d34-03f5-11ec-9a03-0242ac130004"); + entities.add(syncEntity); + entities.add(entity1); + + Mockito.when(registrationStatusService.getRegistrationStatus(anyString(), any(), any(), any())) + .thenReturn(registrationStatusDto).thenReturn(registrationStatusDto).thenReturn(registrationStatusDto1); + Mockito.when(syncRegistrationService.findByWorkflowInstanceId(anyString())).thenReturn(syncEntity); + Mockito.when(syncRegistrationService.findByRegistrationId(any())).thenReturn(entities); + notificationStage.processURL(ctx); + assertTrue(responseObject); + } + + @Test + public void duplicateAdditionalReqIdFoundTest() { + + SyncRegistrationEntity syncEntity = new SyncRegistrationEntity(); + syncEntity.setAdditionalInfoReqId("abc"); + syncEntity.setPacketId("2018701130000410092018110735"); + syncEntity.setWorkflowInstanceId("78fc3d34-03f5-11ec-9a03-0242ac130004"); + entities.add(syncEntity); + entities.add(entity); + + Mockito.when(registrationStatusService.getRegistrationStatus(anyString(), any(), any(), any())) + .thenReturn(registrationStatusDto).thenReturn(registrationStatusDto).thenReturn(registrationStatusDto1); + Mockito.when(syncRegistrationService.findByWorkflowInstanceId(anyString())).thenReturn(entity); + Mockito.when(syncRegistrationService.findByAdditionalInfoReqId(anyString())).thenReturn(entities); + notificationStage.processURL(ctx); + assertTrue(responseObject); + } + + @Test + public void processFailureURLTest() { + RoutingContext routingContext = Mockito.mock(RoutingContext.class); + routingContext.setBody(null); + notificationStage.processURL(routingContext); + assertEquals(responseObject, null); + } + + @Test + public void processTest() { + MessageDTO inputDto= new MessageDTO(); + inputDto.setInternalError(Boolean.FALSE); + inputDto.setIsValid(Boolean.TRUE); + inputDto.setRid("2018701130000410092018110735"); + inputDto.setWorkflowInstanceId("78fc3d34-03f5-11ec-9a03-0242ac130003"); + + Mockito.when(syncRegistrationService.findByWorkflowInstanceId(anyString())).thenReturn(entity); + Mockito.when(syncRegistrationService.findByAdditionalInfoReqId(anyString())).thenReturn(entities); + MessageDTO messageDTO = notificationStage.process(inputDto); + assertTrue(messageDTO.getIsValid()); + } + + @Test + public void dbExceptionTest() { + Mockito.when(registrationStatusService.getRegistrationStatus(anyString(), any(), any(), any())).thenThrow(new TablenotAccessibleException("exception")); + Mockito.when(registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.DATA_ACCESS_EXCEPTION)) + .thenReturn("REPROCESS"); + MessageDTO result = notificationStage.process(messageDTO); + assertTrue(result.getInternalError()); + } + + + @Test + public void genericExceptionTest() { + Mockito.when(syncRegistrationService + .findByWorkflowInstanceId(anyString())).thenThrow(new NullPointerException("exception")); + Mockito.when(registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.DATA_ACCESS_EXCEPTION)) + .thenReturn("REPROCESS"); + MessageDTO result = notificationStage.process(messageDTO); + assertFalse(result.getIsValid()); + } +} diff --git a/registration-processor/pre-processor/registration-processor-supervisor-validator-stage/pom.xml b/registration-processor/pre-processor/registration-processor-supervisor-validator-stage/pom.xml index d4d05723920..b670cf40e5e 100644 --- a/registration-processor/pre-processor/registration-processor-supervisor-validator-stage/pom.xml +++ b/registration-processor/pre-processor/registration-processor-supervisor-validator-stage/pom.xml @@ -1,119 +1,119 @@ - - - 4.0.0 - - io.mosip.registrationprocessor - pre-processor - 1.2.0.1-B1 - - registration-processor-supervisor-validator-stage - 1.2.0.1-B1 - registration-processor-supervisor-validator-stage - - UTF-8 - UTF-8 - - - - - org.springframework.cloud - spring-cloud-starter-config - ${spring-cloud-config.version} - - - org.mockito - mockito-core - ${mockito.version} - test - - - com.h2database - h2 - ${h2.version} - - - - - - org.springframework - spring-context - ${spring-framework.version} - - - org.springframework - spring-tx - ${spring-framework.version} - - - io.mosip.registrationprocessor - registration-processor-core - ${registration.processor.core.version} - - - io.mosip.registrationprocessor - registration-processor-registration-status-service-impl - ${registration.status.service.version} - - - - io.mosip.registrationprocessor - registration-processor-info-storage-service - ${packet.info.storage.service.version} - - - io.mosip.registrationprocessor - registration-processor-rest-client - ${registration.processor.rest.client.version} - - - io.mosip.kernel - kernel-bioapi-provider - ${kernel.bioapi.provider.version} - - - io.mosip.kernel - kernel-core - ${kernel.core.version} - - - org.powermock - powermock-module-junit4 - ${powermock.module.junit4.version} - test - - - org.powermock - powermock-api-mockito2 - ${powermock.api.mockito.version} - test - - - io.mosip.registrationprocessor - registration-processor-packet-manager - ${packet.manager.version} - - - io.mosip.kernel - kernel-templatemanager-velocity - ${kernel.templatemanager.velocity.version} - - - javax.servlet - servlet-api - - - dom4j - dom4j - - - - - - - - - - - + + + 4.0.0 + + io.mosip.registrationprocessor + pre-processor + 1.2.0.1-B3-SNAPSHOT + + registration-processor-supervisor-validator-stage + 1.2.0.1-B3-SNAPSHOT + registration-processor-supervisor-validator-stage + + UTF-8 + UTF-8 + + + + + org.springframework.cloud + spring-cloud-starter-config + ${spring-cloud-config.version} + + + org.mockito + mockito-core + ${mockito.version} + test + + + com.h2database + h2 + ${h2.version} + + + + + + org.springframework + spring-context + ${spring-framework.version} + + + org.springframework + spring-tx + ${spring-framework.version} + + + io.mosip.registrationprocessor + registration-processor-core + ${registration.processor.core.version} + + + io.mosip.registrationprocessor + registration-processor-registration-status-service-impl + ${registration.status.service.version} + + + + io.mosip.registrationprocessor + registration-processor-info-storage-service + ${packet.info.storage.service.version} + + + io.mosip.registrationprocessor + registration-processor-rest-client + ${registration.processor.rest.client.version} + + + io.mosip.kernel + kernel-bioapi-provider + ${kernel.bioapi.provider.version} + + + io.mosip.kernel + kernel-core + ${kernel.core.version} + + + org.powermock + powermock-module-junit4 + ${powermock.module.junit4.version} + test + + + org.powermock + powermock-api-mockito2 + ${powermock.api.mockito.version} + test + + + io.mosip.registrationprocessor + registration-processor-packet-manager + ${packet.manager.version} + + + io.mosip.kernel + kernel-templatemanager-velocity + ${kernel.templatemanager.velocity.version} + + + javax.servlet + servlet-api + + + dom4j + dom4j + + + + + + + + + + + diff --git a/registration-processor/pre-processor/registration-processor-supervisor-validator-stage/src/main/java/io/mosip/registration/processor/stages/config/SupervisorValidatorConfig.java b/registration-processor/pre-processor/registration-processor-supervisor-validator-stage/src/main/java/io/mosip/registration/processor/stages/config/SupervisorValidatorConfig.java index 780134389fa..aa3169ce5a8 100644 --- a/registration-processor/pre-processor/registration-processor-supervisor-validator-stage/src/main/java/io/mosip/registration/processor/stages/config/SupervisorValidatorConfig.java +++ b/registration-processor/pre-processor/registration-processor-supervisor-validator-stage/src/main/java/io/mosip/registration/processor/stages/config/SupervisorValidatorConfig.java @@ -1,28 +1,34 @@ -package io.mosip.registration.processor.stages.config; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -import io.mosip.registration.processor.packet.storage.utils.OSIUtils; -import io.mosip.registration.processor.stages.supervisorvalidator.SupervisorValidationProcessor; -import io.mosip.registration.processor.stages.supervisorvalidator.SupervisorValidator; - -@Configuration -public class SupervisorValidatorConfig { - - @Bean - public SupervisorValidationProcessor getSupervisorValidationProcessor() { - return new SupervisorValidationProcessor(); - } - - @Bean - public SupervisorValidator getSupervisorValidator() { - return new SupervisorValidator(); - } - - @Bean - public OSIUtils getOSIUtils() { - return new OSIUtils(); - } - -} +package io.mosip.registration.processor.stages.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import io.mosip.kernel.biosdk.provider.factory.BioAPIFactory; +import io.mosip.registration.processor.packet.storage.utils.OSIUtils; +import io.mosip.registration.processor.stages.supervisorvalidator.SupervisorValidationProcessor; +import io.mosip.registration.processor.stages.supervisorvalidator.SupervisorValidator; + +@Configuration +public class SupervisorValidatorConfig { + + @Bean + public SupervisorValidationProcessor getSupervisorValidationProcessor() { + return new SupervisorValidationProcessor(); + } + + @Bean + public SupervisorValidator getSupervisorValidator() { + return new SupervisorValidator(); + } + + @Bean + public OSIUtils getOSIUtils() { + return new OSIUtils(); + } + + @Bean + public BioAPIFactory getBioAPIFactory() { + return new BioAPIFactory(); + } + +} 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 354a838bc93..8cd22b39029 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 @@ -47,7 +47,7 @@ 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.AuthUtil; +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; @@ -72,34 +72,28 @@ public class SupervisorValidator { @Autowired private PriorityBasedPacketManagerService packetManagerService; - @Autowired - private AuthUtil authUtil; - @Autowired private ObjectMapper mapper; @Autowired private Utilities utility; + @Autowired + private BioSdkUtil bioUtil; + /** * Checks if is valid Supervisor. * * @param registrationId the registration id - * @throws IOException Signals that an I/O - * exception has occurred. * @throws SAXException * @throws ParserConfigurationException - * @throws NoSuchAlgorithmException - * @throws InvalidKeySpecException - * @throws NumberFormatException * @throws io.mosip.kernel.core.exception.IOException - * @throws BaseCheckedException + * @throws Exception * @throws PacketDecryptionFailureException * @throws RegistrationProcessorCheckedException */ public void validate(String registrationId, InternalRegistrationStatusDto registrationStatusDto, RegOsiDto regOsi) - throws IOException, InvalidKeySpecException, NoSuchAlgorithmException, NumberFormatException, JSONException, - CertificateException, BaseCheckedException { + throws Exception { regProcLogger.debug("validate called for registrationId {}", registrationId); validateSupervisor(registrationId, regOsi, registrationStatusDto); @@ -181,19 +175,14 @@ private UserResponseDto getUserDetails(String operatorId, String creationDate, * @param regOsi the reg osi * @param registrationId the registration id * @param registrationStatusDto - * @throws IOException * @throws SAXException * @throws ParserConfigurationException - * @throws NoSuchAlgorithmException - * @throws InvalidKeySpecException * @throws io.mosip.kernel.core.exception.IOException - * @throws BaseCheckedException * @throws PacketDecryptionFailureException * @throws Exception */ private void authenticateSupervisor(RegOsiDto regOsi, String registrationId, - InternalRegistrationStatusDto registrationStatusDto) throws IOException, InvalidKeySpecException, - NoSuchAlgorithmException, CertificateException, BaseCheckedException { + InternalRegistrationStatusDto registrationStatusDto) throws Exception { String supervisorId = regOsi.getSupervisorId(); // officer password and otp check @@ -251,54 +240,26 @@ private boolean validateOtpAndPwd(String opValidated, String otpValidated) { * @param list biometric data as BIR object * @param individualType user type * @param registrationStatusDto + * @throws Exception * @throws SAXException * @throws ParserConfigurationException * @throws NoSuchAlgorithmException * @throws InvalidKeySpecException - * @throws IOException Signals that an I/O exception has - * occurred. - * @throws BaseCheckedException * @throws BiometricException */ private void validateUserBiometric(String registrationId, String userId, List list, String individualType, InternalRegistrationStatusDto registrationStatusDto) - throws IOException, CertificateException, NoSuchAlgorithmException, BaseCheckedException { + throws Exception { if (INDIVIDUAL_TYPE_USERID.equalsIgnoreCase(individualType)) { userId = getIndividualIdByUserId(userId); individualType = null; } - AuthResponseDTO authResponseDTO = authUtil.authByIdAuthentication(userId, individualType, list); - if (authResponseDTO.getErrors() == null || authResponseDTO.getErrors().isEmpty()) { - if (!authResponseDTO.getResponse().isAuthStatus()) { - registrationStatusDto.setLatestTransactionStatusCode( - registrationExceptionMapperUtil.getStatusCode(RegistrationExceptionTypeCode.AUTH_FAILED)); - registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.toString()); - throw new ValidationFailedException(StatusUtil.SUPERVISOR_AUTHENTICATION_FAILED.getMessage() + userId, - StatusUtil.SUPERVISOR_AUTHENTICATION_FAILED.getCode()); - } - } else { - String finalUserId = userId; - String finalIndividualType = individualType; - - List errors = authResponseDTO.getErrors(); - if (errors.stream().anyMatch(error -> (error.getErrorCode().equalsIgnoreCase("IDA-MLC-007") - || utility.isUinMissingFromIdAuth(error.getErrorCode(), finalUserId, finalIndividualType)))) { - throw new AuthSystemException(PlatformErrorMessages.RPR_AUTH_SYSTEM_EXCEPTION.getMessage()); - } else { - registrationStatusDto.setLatestTransactionStatusCode( - registrationExceptionMapperUtil.getStatusCode(RegistrationExceptionTypeCode.AUTH_ERROR)); - registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.toString()); - String result = errors.stream().map(s -> s.getErrorMessage() + " ").collect(Collectors.joining()); - regProcLogger.debug("validateUserBiometric call ended for registrationId {} {}", registrationId, - result); - throw new ValidationFailedException(result, StatusUtil.SUPERVISOR_AUTHENTICATION_FAILED.getCode()); - } - - } - + bioUtil.authenticateBiometrics(userId, individualType, list, registrationStatusDto, + StatusUtil.SUPERVISOR_AUTHENTICATION_FAILED.getMessage(), + StatusUtil.SUPERVISOR_AUTHENTICATION_FAILED.getCode()); } /** 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 a55b9120144..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 @@ -18,7 +18,7 @@ "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.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."; diff --git a/registration-processor/pre-processor/registration-processor-supervisor-validator-stage/src/test/java/io/mosip/registration/processor/supervisor/SupervisorValidatorTest.java b/registration-processor/pre-processor/registration-processor-supervisor-validator-stage/src/test/java/io/mosip/registration/processor/supervisor/SupervisorValidatorTest.java index f7ebcb5fac9..5c379fc50c1 100644 --- a/registration-processor/pre-processor/registration-processor-supervisor-validator-stage/src/test/java/io/mosip/registration/processor/supervisor/SupervisorValidatorTest.java +++ b/registration-processor/pre-processor/registration-processor-supervisor-validator-stage/src/test/java/io/mosip/registration/processor/supervisor/SupervisorValidatorTest.java @@ -4,6 +4,7 @@ import static org.mockito.ArgumentMatchers.anyMap; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.when; import java.io.File; @@ -71,7 +72,7 @@ import io.mosip.registration.processor.core.util.RegistrationExceptionMapperUtil; import io.mosip.registration.processor.packet.manager.idreposervice.IdRepoService; import io.mosip.registration.processor.packet.storage.utils.ABISHandlerUtil; -import io.mosip.registration.processor.packet.storage.utils.AuthUtil; +import io.mosip.registration.processor.packet.storage.utils.BioSdkUtil; import io.mosip.registration.processor.packet.storage.utils.OSIUtils; import io.mosip.registration.processor.packet.storage.utils.PriorityBasedPacketManagerService; import io.mosip.registration.processor.packet.storage.utils.Utilities; @@ -148,7 +149,7 @@ public class SupervisorValidatorTest { private Utilities utility; @Mock - private AuthUtil authUtil; + private BioSdkUtil bioUtil; private Map metaInfo; @@ -379,14 +380,14 @@ public void setUp() throws Exception { * * @throws Exception the exception */ - @Test + @Test(expected = ValidationFailedException.class) public void testisValidSupervisorSuccess() throws Exception { Mockito.when(registrationStatusService.checkUinAvailabilityForRid(any())).thenReturn(true); registrationStatusDto.setRegistrationType("ACTIVATED"); when(packetManagerService.getBiometricsByMappingJsonKey(anyString(), any(), any(), any())) - .thenReturn(biometricRecord); - Mockito.when(authUtil.authByIdAuthentication(anyString(), any(), any())).thenReturn(authResponseDTO); + .thenReturn(null); + doNothing().when(bioUtil).authenticateBiometrics(Mockito.anyString(), Mockito.anyString(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any()); supervisorValidator.validate("reg1234", registrationStatusDto, regOsiDto); } @@ -427,8 +428,8 @@ public void testAuthByIdAuthenticationStatusInActive() throws Exception { authResponseDTO.setResponse(responseDTO); Mockito.when(registrationStatusService.checkUinAvailabilityForRid(any())).thenReturn(true); when(packetManagerService.getBiometricsByMappingJsonKey(anyString(), any(), any(), any())) - .thenReturn(biometricRecord); - Mockito.when(authUtil.authByIdAuthentication(anyString(), any(), any())).thenReturn(authResponseDTO); + .thenReturn(null); + doNothing().when(bioUtil).authenticateBiometrics(Mockito.anyString(), Mockito.anyString(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any()); registrationStatusDto.setRegistrationType("ACTIVATED"); supervisorValidator.validate("reg1234", registrationStatusDto, regOsiDto); } @@ -445,8 +446,8 @@ public void testAuthByIdAuthenticationStatusFailed() throws Exception { authResponseDTO.setErrors(Arrays.asList(errorDTO)); Mockito.when(registrationStatusService.checkUinAvailabilityForRid(any())).thenReturn(true); when(packetManagerService.getBiometricsByMappingJsonKey(anyString(), any(), any(), any())) - .thenReturn(biometricRecord); - Mockito.when(authUtil.authByIdAuthentication(anyString(), any(), any())).thenReturn(authResponseDTO); + .thenReturn(null); + doNothing().when(bioUtil).authenticateBiometrics(Mockito.anyString(), Mockito.anyString(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any()); registrationStatusDto.setRegistrationType("ACTIVATED"); supervisorValidator.validate("reg1234", registrationStatusDto, regOsiDto); } @@ -563,14 +564,14 @@ public void testIndividualIdResponseFailed() throws Exception { supervisorValidator.validate("reg1234", registrationStatusDto, regOsiDto); } - @Test(expected = AuthSystemException.class) + @Test(expected = ValidationFailedException.class) public void testSupervisorAuthSystemError() throws Exception { ErrorDTO errordto = new ErrorDTO(); errordto.setErrorCode("IDA-MLC-007"); authResponseDTO.setErrors(Arrays.asList(errordto)); when(packetManagerService.getBiometricsByMappingJsonKey(anyString(), any(), any(), any())) - .thenReturn(biometricRecord); - Mockito.when(authUtil.authByIdAuthentication(anyString(), any(), any())).thenReturn(authResponseDTO); + .thenReturn(null); + doNothing().when(bioUtil).authenticateBiometrics(Mockito.anyString(), Mockito.anyString(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any()); supervisorValidator.validate("reg1234", registrationStatusDto, regOsiDto); } @@ -585,7 +586,8 @@ public void testMappingNotFoundResponse() throws Exception { Mockito.when(registrationStatusService.checkUinAvailabilityForRid(any())).thenReturn(true); when(packetManagerService.getBiometricsByMappingJsonKey(anyString(), any(), any(), any())) .thenReturn(biometricRecord); - Mockito.when(authUtil.authByIdAuthentication(anyString(), any(), any())).thenReturn(authResponseDTO); + doNothing().when(bioUtil).authenticateBiometrics(Mockito.anyString(), Mockito.anyString(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any()); + regOsiDto.setPacketCreationDate(null); supervisorValidator.validate("reg1234", registrationStatusDto, regOsiDto); } @@ -602,10 +604,10 @@ public void testUMCValidationFailed() throws Exception { Mockito.when(mapper.readValue(anyString(), Mockito.eq(RegistrationCenterUserMachineMappingHistoryResponseDto.class))).thenReturn(centerMapping); when(packetManagerService.getBiometricsByMappingJsonKey(anyString(), any(), any(), any())) - .thenReturn(biometricRecord); + .thenReturn(null); Mockito.when(restClientService.getApi(any(), any(), anyString(), any(), any())) .thenReturn(userResponseDto).thenReturn(centerResponse); - Mockito.when(authUtil.authByIdAuthentication(anyString(), any(), any())).thenReturn(authResponseDTO); + doNothing().when(bioUtil).authenticateBiometrics(Mockito.anyString(), Mockito.anyString(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any()); supervisorValidator.validate("reg1234", registrationStatusDto, regOsiDto); } diff --git a/registration-processor/qc-users-manger/pom.xml b/registration-processor/qc-users-manger/pom.xml index 98ef5146ae5..85f14eeb26e 100644 --- a/registration-processor/qc-users-manger/pom.xml +++ b/registration-processor/qc-users-manger/pom.xml @@ -1,78 +1,78 @@ - - - 4.0.0 - - - qc-users-manger - - io.mosip.registrationprocessor - registration-processor - 1.2.0.1-B1 - - - - UTF-8 - UTF-8 - - - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-data-jpa - - - io.mosip.kernel - kernel-core - ${kernel.core.version} - - - org.postgresql - postgresql - - - io.mosip.kernel - kernel-dataaccess-hibernate - ${kernel.core.version} - - - io.springfox - springfox-swagger-ui - ${swagger.version} - - - io.springfox - springfox-swagger2 - ${swagger.version} - - - org.springframework.boot - spring-boot-starter-test - test - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - repackage - - - exec - - - - - - - - + + + 4.0.0 + + + qc-users-manger + + io.mosip.registrationprocessor + registration-processor + 1.2.0.1-B3-SNAPSHOT + + + + UTF-8 + UTF-8 + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-data-jpa + + + io.mosip.kernel + kernel-core + ${kernel.core.version} + + + org.postgresql + postgresql + + + io.mosip.kernel + kernel-dataaccess-hibernate + ${kernel.core.version} + + + io.springfox + springfox-swagger-ui + ${swagger.version} + + + io.springfox + springfox-swagger2 + ${swagger.version} + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + repackage + + + exec + + + + + + + + diff --git a/registration-processor/registration-processor-bio-dedupe-service-impl/pom.xml b/registration-processor/registration-processor-bio-dedupe-service-impl/pom.xml index 33f74594ab8..d5e235c14a9 100644 --- a/registration-processor/registration-processor-bio-dedupe-service-impl/pom.xml +++ b/registration-processor/registration-processor-bio-dedupe-service-impl/pom.xml @@ -1,76 +1,76 @@ - - - 4.0.0 - - io.mosip.registrationprocessor - registration-processor - 1.2.0.1-B1 - - - registration-processor-bio-dedupe-service-impl - 1.2.0.1-B1 - registration-processor-bio-dedupe-service-impl - - - UTF-8 - - - - org.springframework.cloud - spring-cloud-starter-config - ${spring-cloud-config.version} - - - org.mockito - mockito-core - ${mockito.version} - test - - - junit - junit - test - - - org.springframework.boot - spring-boot-starter - - - io.mosip.registrationprocessor - registration-processor-core - ${registration.processor.core.version} - - - commons-io - commons-io - 2.6 - - - com.h2database - h2 - - - io.mosip.registrationprocessor - registration-processor-rest-client - ${registration.processor.rest.client.version} - - - io.mosip.registrationprocessor - registration-processor-info-storage-service - ${packet.info.storage.service.version} - - - org.powermock - powermock-module-junit4 - ${powermock.module.junit4.version} - test - - - org.powermock - powermock-api-mockito2 - ${powermock.api.mockito.version} - test - - + + + 4.0.0 + + io.mosip.registrationprocessor + registration-processor + 1.2.0.1-B3-SNAPSHOT + + + registration-processor-bio-dedupe-service-impl + 1.2.0.1-B3-SNAPSHOT + registration-processor-bio-dedupe-service-impl + + + UTF-8 + + + + org.springframework.cloud + spring-cloud-starter-config + ${spring-cloud-config.version} + + + org.mockito + mockito-core + ${mockito.version} + test + + + junit + junit + test + + + org.springframework.boot + spring-boot-starter + + + io.mosip.registrationprocessor + registration-processor-core + ${registration.processor.core.version} + + + commons-io + commons-io + 2.6 + + + com.h2database + h2 + + + io.mosip.registrationprocessor + registration-processor-rest-client + ${registration.processor.rest.client.version} + + + io.mosip.registrationprocessor + registration-processor-info-storage-service + ${packet.info.storage.service.version} + + + org.powermock + powermock-module-junit4 + ${powermock.module.junit4.version} + test + + + org.powermock + powermock-api-mockito2 + ${powermock.api.mockito.version} + test + + \ No newline at end of file diff --git a/registration-processor/registration-processor-bio-dedupe-service-impl/src/test/java/io/mosip/registration/processor/bio/dedupe/service/test/BioDedupeServiceImplTest.java b/registration-processor/registration-processor-bio-dedupe-service-impl/src/test/java/io/mosip/registration/processor/bio/dedupe/service/test/BioDedupeServiceImplTest.java index ee2f6dce147..32723530eea 100644 --- a/registration-processor/registration-processor-bio-dedupe-service-impl/src/test/java/io/mosip/registration/processor/bio/dedupe/service/test/BioDedupeServiceImplTest.java +++ b/registration-processor/registration-processor-bio-dedupe-service-impl/src/test/java/io/mosip/registration/processor/bio/dedupe/service/test/BioDedupeServiceImplTest.java @@ -1,7 +1,6 @@ package io.mosip.registration.processor.bio.dedupe.service.test; import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; @@ -139,6 +138,7 @@ public void setup() throws Exception { String refId = "01234567-89AB-CDEF-0123-456789ABCDEF"; List refIdList = new ArrayList<>(); refIdList.add(refId); + //Mockito.when(packetInfoManager.getReferenceIdByRid(anyString())).thenReturn(refIdList); CandidatesDto candidate1 = new CandidatesDto(); candidate1.setReferenceId("01234567-89AB-CDEF-0123-456789ABCDEG"); @@ -191,11 +191,11 @@ public void setup() throws Exception { BiometricRecord biometricRecord = new BiometricRecord(); biometricRecord.setSegments(birTypeList); - Mockito.when(packetManagerService.getBiometricsByMappingJsonKey(any(), any(),any(), any())).thenReturn(biometricRecord); + Mockito.when(packetManagerService.getBiometrics(any(), any(),any(), any())).thenReturn(biometricRecord); Mockito.when(cbeffutil.createXML(any())).thenReturn(fileBytes); - + } /** @@ -298,6 +298,116 @@ public void insertBiometricsUnableToServeRequestABISExceptionFailureTest() } + /** + * Test perform dedupe success. + * + * @throws ApisResourceAccessException + * the apis resource access exception + * @throws IOException + */ + @Test + public void testPerformDedupeSuccess() throws ApisResourceAccessException, IOException { + + identifyResponse.setReturnValue("1"); + Mockito.when(restClientService.postApi(any(), any(),any(), any(), any())) + .thenReturn(identifyResponse); + String rid = "27847657360002520181208094056"; + + List list = new ArrayList<>(); + list.add(rid); + Mockito.when(packetInfoManager.getRidByReferenceId(any())).thenReturn(list); + + List ridList = new ArrayList<>(); + ridList.add(rid); + ridList.add(rid); + + List demoList = new ArrayList<>(); + DemographicInfoDto demo1 = new DemographicInfoDto(); + demoList.add(demo1); + Mockito.when(packetInfoManager.findDemoById(any())).thenReturn(demoList); + Mockito.when(registrationStatusService.checkUinAvailabilityForRid(any())).thenReturn(true); + + /// List duplicates = bioDedupeService.performDedupe(rid); + + //assertEquals(ridList, duplicates); + } + + /** + * Test perform dedupe failure. + * + * @throws ApisResourceAccessException + * the apis resource access exception + * @throws IOException + */ +// @Test(expected = ABISInternalError.class) +// public void testPerformDedupeFailure() throws ApisResourceAccessException, IOException { +// +// Mockito.when(restClientService.postApi(any(), any(),any(), any(), any())) +// .thenReturn(identifyResponse); +// String rid = "27847657360002520181208094056"; +// identifyResponse.setReturnValue("2"); +// identifyResponse.setFailureReason("1"); +// +// bioDedupeService.performDedupe(rid); +// } + + /** + * Test dedupe abis abort exception. + * + * @throws ApisResourceAccessException + * the apis resource access exception + * @throws IOException + */ +// @Test(expected = ABISAbortException.class) +// public void testDedupeAbisAbortException() throws ApisResourceAccessException, IOException { +// +// Mockito.when(restClientService.postApi(any(), any(),any(), any(), any())) +// .thenReturn(identifyResponse); +// String rid = "27847657360002520181208094056"; +// identifyResponse.setReturnValue("2"); +// identifyResponse.setFailureReason("2"); +// +// bioDedupeService.performDedupe(rid); +// } + + /** + * Test dedupe unexpected error. + * + * @throws ApisResourceAccessException + * the apis resource access exception + * @throws IOException + */ +// @Test(expected = UnexceptedError.class) +// public void testDedupeUnexpectedError() throws ApisResourceAccessException, IOException { +// +// Mockito.when(restClientService.postApi(any(), any(),any(), any(), any())) +// .thenReturn(identifyResponse); +// String rid = "27847657360002520181208094056"; +// identifyResponse.setReturnValue("2"); +// identifyResponse.setFailureReason("3"); +// +// bioDedupeService.performDedupe(rid); +// } + + /** + * Test dedupe unable to serve request ABIS exception. + * + * @throws ApisResourceAccessException + * the apis resource access exception + * @throws IOException + */ +// @Test(expected = UnableToServeRequestABISException.class) +// public void testDedupeUnableToServeRequestABISException() throws ApisResourceAccessException, IOException { +// +// Mockito.when(restClientService.postApi(any(), any(),any(), any(), any())) +// .thenReturn(identifyResponse); +// String rid = "27847657360002520181208094056"; +// identifyResponse.setReturnValue("2"); +// identifyResponse.setFailureReason("4"); +// +// bioDedupeService.performDedupe(rid); +// } + /** * Test get file. * @@ -308,6 +418,7 @@ public void insertBiometricsUnableToServeRequestABISExceptionFailureTest() public void testGetFile() throws Exception { byte[] fileData = bioDedupeService.getFileByRegId(registrationId, process); + Mockito.when(cbeffutil.createXML(any())).thenReturn(fileBytes); assertArrayEquals(fileData, fileBytes); } @@ -320,7 +431,10 @@ public void getFileByAbisRefId() throws Exception { // case2 : if regId is valid List regIds = new ArrayList<>(); regIds.add("10006100360000320190702102135"); - Mockito.when(packetInfoManager.getRidByReferenceId(anyString())).thenReturn(regIds); + Mockito.when(packetInfoManager.getRidByReferenceId(any())).thenReturn(regIds); + Mockito.when(cbeffutil.createXML(any())).thenReturn(fileBytes); + + byte[] result = bioDedupeService.getFileByAbisRefId(registrationId, process); assertArrayEquals("verfing if byte array returned is same as expected ", result, fileBytes); } diff --git a/registration-processor/registration-processor-common-camel-bridge/dependency-reduced-pom.xml b/registration-processor/registration-processor-common-camel-bridge/dependency-reduced-pom.xml index 6c645e5bfb2..4261c6a15b1 100644 --- a/registration-processor/registration-processor-common-camel-bridge/dependency-reduced-pom.xml +++ b/registration-processor/registration-processor-common-camel-bridge/dependency-reduced-pom.xml @@ -3,11 +3,11 @@ registration-processor io.mosip.registrationprocessor - 1.2.0.1-B1 + 1.2.0.1-B3-SNAPSHOT 4.0.0 registration-processor-common-camel-bridge - 1.2.0.1-B1 + 1.2.0.1-B3-SNAPSHOT @@ -102,7 +102,7 @@ io.mosip.registration.processor.camel.bridge.MosipCamelBridge 1.0.5 - 1.2.0.1-B1 + 1.2.0.1-B3-SNAPSHOT diff --git a/registration-processor/registration-processor-common-camel-bridge/pom.xml b/registration-processor/registration-processor-common-camel-bridge/pom.xml index 4ec488235ab..5545298eafa 100644 --- a/registration-processor/registration-processor-common-camel-bridge/pom.xml +++ b/registration-processor/registration-processor-common-camel-bridge/pom.xml @@ -6,16 +6,16 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-B1 + 1.2.0.1-B3-SNAPSHOT registration-processor-common-camel-bridge - 1.2.0.1-B1 + 11.2.0.1-B3-SNAPSHOT jar io.mosip.registration.processor.camel.bridge.MosipCamelBridge 1.0.5 - 1.2.0.1-B1 + 1.2.0.1-B3-SNAPSHOT diff --git a/registration-processor/registration-processor-common-camel-bridge/src/main/java/io/mosip/registration/processor/camel/bridge/MosipBridgeFactory.java b/registration-processor/registration-processor-common-camel-bridge/src/main/java/io/mosip/registration/processor/camel/bridge/MosipBridgeFactory.java index 27272bd9cec..08676260378 100644 --- a/registration-processor/registration-processor-common-camel-bridge/src/main/java/io/mosip/registration/processor/camel/bridge/MosipBridgeFactory.java +++ b/registration-processor/registration-processor-common-camel-bridge/src/main/java/io/mosip/registration/processor/camel/bridge/MosipBridgeFactory.java @@ -142,10 +142,11 @@ public void startCamelBridge() throws Exception { for (String camelRouteFileName : camelRoutesFilesArr) { String camelRoutesUrl = camelRoutesBaseUrl + camelRouteFileName; responseEntity = restTemplate.exchange(camelRoutesUrl, HttpMethod.GET, null, Resource.class); - if (responseEntity.getBody() == null) { + Resource body=responseEntity.getBody(); + if (body == null) { throw new RuntimeException("Response for " + camelRoutesUrl + " is null"); } - routes = camelContext.loadRoutesDefinition(responseEntity.getBody().getInputStream()); + routes = camelContext.loadRoutesDefinition(body.getInputStream()); camelContext.addRouteDefinitions(routeIntercepter.intercept(camelContext, routes.getRoutes())); // camelContext.addRouteDefinitions(routes.getRoutes()); } diff --git a/registration-processor/registration-processor-common-camel-bridge/src/main/java/io/mosip/registration/processor/camel/bridge/config/CamelBridgeConfig.java b/registration-processor/registration-processor-common-camel-bridge/src/main/java/io/mosip/registration/processor/camel/bridge/config/CamelBridgeConfig.java index 0e062b2dd61..265a448bf29 100644 --- a/registration-processor/registration-processor-common-camel-bridge/src/main/java/io/mosip/registration/processor/camel/bridge/config/CamelBridgeConfig.java +++ b/registration-processor/registration-processor-common-camel-bridge/src/main/java/io/mosip/registration/processor/camel/bridge/config/CamelBridgeConfig.java @@ -9,6 +9,7 @@ import org.springframework.context.annotation.Primary; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import io.mosip.registration.processor.camel.bridge.MosipBridgeFactory; @@ -36,6 +37,7 @@ public TokenGenerationProcessor tokenGenerationProcessor() { public ObjectMapper getObjectMapper() { ObjectMapper objectMapper = new ObjectMapper().registerModule(new AfterburnerModule()).registerModule(new JavaTimeModule()); objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); + objectMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS); return objectMapper; } diff --git a/registration-processor/registration-processor-core/pom.xml b/registration-processor/registration-processor-core/pom.xml index 422e0df5f33..a595827a779 100644 --- a/registration-processor/registration-processor-core/pom.xml +++ b/registration-processor/registration-processor-core/pom.xml @@ -7,10 +7,10 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-B1 + 1.2.0.1-B3-SNAPSHOT registration-processor-core - 1.2.0.1-B1 + 1.2.0.1-B3-SNAPSHOT org.mockito @@ -48,10 +48,7 @@ org.slf4j slf4j-log4j12 - - com.google.code.gson - gson - + @@ -138,10 +135,7 @@ kernel-cbeffutil-api ${kernel.cbeffutil.version} - - com.google.code.gson - gson - + io.vertx vertx-config-spring-config-server diff --git a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/abstractverticle/HealthCheckDTO.java b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/abstractverticle/HealthCheckDTO.java index f16ea21aa06..bf5b781b4e9 100644 --- a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/abstractverticle/HealthCheckDTO.java +++ b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/abstractverticle/HealthCheckDTO.java @@ -9,4 +9,4 @@ public class HealthCheckDTO { String failureReason; -} \ No newline at end of file +} 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 14df2847cb4..867ae0c10a7 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 @@ -1,214 +1,227 @@ -package io.mosip.registration.processor.core.abstractverticle; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.core.env.Environment; -import org.springframework.util.ClassUtils; - -import com.fasterxml.jackson.databind.ObjectMapper; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; - -import brave.Tracing; -import io.mosip.kernel.core.virusscanner.spi.VirusScanner; -import io.mosip.registration.processor.core.constant.HealthConstant; -import io.mosip.registration.processor.core.queue.factory.MosipQueue; -import io.mosip.registration.processor.core.spi.queue.MosipQueueConnectionFactory; -import io.mosip.registration.processor.core.spi.queue.MosipQueueManager; -import io.mosip.registration.processor.core.tracing.VertxWebTracingLocal; -import io.mosip.registration.processor.core.util.DigitalSignatureUtility; -import io.vertx.core.Handler; -import io.vertx.core.Vertx; -import io.vertx.core.http.HttpServerResponse; -import io.vertx.core.json.Json; -import io.vertx.ext.web.Router; -import io.vertx.ext.web.RoutingContext; -import io.vertx.ext.web.handler.BodyHandler; -import io.vertx.micrometer.PrometheusScrapingHandler; - -/** - * @author Mukul Puspam - * - */ -public abstract class MosipVerticleAPIManager extends MosipVerticleManager { - - @Value("${registration.processor.signature.isEnabled}") - Boolean isEnabled; - - @Autowired - DigitalSignatureUtility digitalSignatureUtility; - - @Autowired - ObjectMapper objectMapper; - - @Autowired - private MosipQueueConnectionFactory mosipConnectionFactory; - - @Autowired - private Tracing tracing; - - @Autowired - private Environment environment; - - @Autowired(required = false) - private VirusScanner virusScanner; - - /** The mosip queue manager. */ - @Autowired - private MosipQueueManager mosipQueueManager; - - private static final String PROMETHEUS_ENDPOINT = "/actuator/prometheus"; - - /** - * This method creates a body handler for the routes - * - * @param vertx - * @return - */ - public Router postUrl(Vertx vertx, MessageBusAddress consumeAddress, MessageBusAddress sendAddress) { - Router router = Router.router(vertx); - - VertxWebTracingLocal vertxWebTracing = VertxWebTracingLocal.create(tracing); - Handler routingContextHandler = vertxWebTracing.routingContextHandler(); - router.route() - .order(-1) //applies before routes - .handler(routingContextHandler) - .failureHandler(routingContextHandler); - - router.route().handler(BodyHandler.create()); - String servletPath = getServletPath(); - router.get(servletPath + PROMETHEUS_ENDPOINT).handler(PrometheusScrapingHandler.create()); - if (consumeAddress == null && sendAddress == null) - configureHealthCheckEndpoint(vertx, router, servletPath, null, - null); - else if (consumeAddress == null) - configureHealthCheckEndpoint(vertx, router, servletPath, null, - sendAddress.getAddress()); - else if (sendAddress == null) - configureHealthCheckEndpoint(vertx, router, servletPath, - consumeAddress.getAddress(), null); - else - configureHealthCheckEndpoint(vertx, router, servletPath, - consumeAddress.getAddress(), sendAddress.getAddress()); - return router; - } - - public void configureHealthCheckEndpoint(Vertx vertx, Router router, final String servletPath, - String consumeAddress, String sendAddress) { - StageHealthCheckHandler healthCheckHandler = new StageHealthCheckHandler(vertx, null, objectMapper, - virusScanner, environment); - router.get(servletPath + HealthConstant.HEALTH_ENDPOINT).handler(healthCheckHandler); - if (servletPath.contains("packetreceiver") || servletPath.contains("uploader")) { - healthCheckHandler.register("virusscanner", healthCheckHandler::virusScanHealthChecker); - healthCheckHandler.register( - servletPath.substring(servletPath.lastIndexOf("/") + 1, servletPath.length()) + "Verticle", - future -> healthCheckHandler.senderHealthHandler(future, vertx, super.mosipEventBus, sendAddress)); - } - if (checkServletPathContainsCoreProcessor(servletPath)) { - healthCheckHandler.register( - servletPath.substring(servletPath.lastIndexOf("/") + 1, servletPath.length()) + "Send", future -> { - healthCheckHandler.senderHealthHandler(future, vertx, super.mosipEventBus, sendAddress); - }); - healthCheckHandler.register( - servletPath.substring(servletPath.lastIndexOf("/") + 1, servletPath.length()) + "Consume", - future -> { - healthCheckHandler.consumerHealthHandler(future, vertx, super.mosipEventBus, consumeAddress); - }); - } - if (servletPath.contains("external") || servletPath.contains("bioauth")) { - healthCheckHandler.register( - servletPath.substring(servletPath.lastIndexOf("/") + 1, servletPath.length()) + "Send", future -> { - healthCheckHandler.senderHealthHandler(future, vertx, super.mosipEventBus, sendAddress); - }); - healthCheckHandler.register( - servletPath.substring(servletPath.lastIndexOf("/") + 1, servletPath.length()) + "Consume", - future -> { - healthCheckHandler.senderHealthHandler(future, vertx, super.mosipEventBus, consumeAddress); - }); - } - if (servletPath.contains("manual")) { - healthCheckHandler.register( - servletPath.substring(servletPath.lastIndexOf("/") + 1, servletPath.length()) + "Verticle", - future -> healthCheckHandler.senderHealthHandler(future, vertx, super.mosipEventBus, sendAddress)); - } - if (servletPath.contains("abismiddleware")) { - healthCheckHandler.register("queuecheck", future -> healthCheckHandler.queueHealthChecker(future, mosipQueueManager, mosipConnectionFactory)); - healthCheckHandler.register( - servletPath.substring(servletPath.lastIndexOf("/") + 1, servletPath.length()) + "Verticle", - future -> healthCheckHandler.consumerHealthHandler(future, vertx, super.mosipEventBus, - consumeAddress)); - } - if (servletPath.contains("sender")) { - healthCheckHandler.register( - servletPath.substring(servletPath.lastIndexOf("/") + 1, servletPath.length()) + "Verticle", - future -> healthCheckHandler.consumerHealthHandler(future, vertx, super.mosipEventBus, - consumeAddress)); - } - - healthCheckHandler.register("diskSpace", healthCheckHandler::dispSpaceHealthChecker); - healthCheckHandler.register("db", healthCheckHandler::databaseHealthChecker); - } - - private boolean checkServletPathContainsCoreProcessor(String servletPath) { - return servletPath.contains("packetvalidator") || servletPath.contains("osi") || servletPath.contains("demo") - || servletPath.contains("bio") || servletPath.contains("uin") || servletPath.contains("quality") - || servletPath.contains("abishandler") || servletPath.contains("securezone"); - } - - /** - * This method creates server for vertx web application - * - * @param router - * @param port - */ - public void createServer(Router router, int port) { - vertx.createHttpServer().requestHandler(router::accept).listen(port); - } - - /** - * This method returns a response to the routing context - * - * @param ctx - * @param object - */ - public void setResponse(RoutingContext ctx, Object object) { - ctx.response().putHeader("content-type", "text/plain").putHeader("Access-Control-Allow-Origin", "*") - .putHeader("Access-Control-Allow-Methods", "GET, POST").setStatusCode(200) - .end(Json.encodePrettily(object)); - }; - - /** - * This method returns a response to the routing context - * - * @param ctx - * @param object - * @param contentType - */ - public void setResponseWithDigitalSignature(RoutingContext ctx, Object object, String contentType) { - HttpServerResponse response = ctx.response(); - Gson gson=new GsonBuilder().serializeNulls().create(); - if (isEnabled) - response.putHeader("Response-Signature", - digitalSignatureUtility.getDigitalSignature(gson.toJson(object))); - response.putHeader("content-type", contentType).putHeader("Access-Control-Allow-Origin", "*") - .putHeader("Access-Control-Allow-Methods", "GET, POST").setStatusCode(200) - .end(gson.toJson(object)); - } - - // Added this method to cast all the stages to this class and invoke the deployVerticle method - // to start the stage by configuration, since we don't want to test all the stages now, not marking this as - // an abstract method, but later this need to be marked as abstract - public void deployVerticle() { - - } - - - /** - * Gets the stage name. - * - * @return the stage name - */ - protected String getStageName() { - return ClassUtils.getUserClass(this.getClass()).getSimpleName(); - } +package io.mosip.registration.processor.core.abstractverticle; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.core.env.Environment; +import org.springframework.util.ClassUtils; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +import brave.Tracing; +import io.mosip.kernel.core.logger.spi.Logger; +import io.mosip.kernel.core.virusscanner.spi.VirusScanner; +import io.mosip.registration.processor.core.constant.HealthConstant; +import io.mosip.registration.processor.core.logger.RegProcessorLogger; +import io.mosip.registration.processor.core.queue.factory.MosipQueue; +import io.mosip.registration.processor.core.spi.queue.MosipQueueConnectionFactory; +import io.mosip.registration.processor.core.spi.queue.MosipQueueManager; +import io.mosip.registration.processor.core.tracing.VertxWebTracingLocal; +import io.mosip.registration.processor.core.util.DigitalSignatureUtility; +import io.vertx.core.Handler; +import io.vertx.core.Vertx; +import io.vertx.core.http.HttpServerResponse; +import io.vertx.core.json.Json; +import io.vertx.ext.web.Router; +import io.vertx.ext.web.RoutingContext; +import io.vertx.ext.web.handler.BodyHandler; +import io.vertx.micrometer.PrometheusScrapingHandler; + +/** + * @author Mukul Puspam + * + */ +public abstract class MosipVerticleAPIManager extends MosipVerticleManager { + + @Value("${registration.processor.signature.isEnabled}") + Boolean isEnabled; + + @Autowired + DigitalSignatureUtility digitalSignatureUtility; + + @Autowired + ObjectMapper objectMapper; + + @Autowired + private MosipQueueConnectionFactory mosipConnectionFactory; + + @Autowired + private Tracing tracing; + + @Autowired + private Environment environment; + + @Autowired(required = false) + private VirusScanner virusScanner; + + /** The mosip queue manager. */ + @Autowired + private MosipQueueManager mosipQueueManager; + + private static final String PROMETHEUS_ENDPOINT = "/actuator/prometheus"; + + + private static Logger regProcLogger = RegProcessorLogger.getLogger(MosipVerticleAPIManager.class); + + + /** + * This method creates a body handler for the routes + * + * @param vertx + * @return + */ + public Router postUrl(Vertx vertx, MessageBusAddress consumeAddress, MessageBusAddress sendAddress) { + Router router = Router.router(vertx); + + VertxWebTracingLocal vertxWebTracing = VertxWebTracingLocal.create(tracing); + Handler routingContextHandler = vertxWebTracing.routingContextHandler(); + router.route() + .order(-1) //applies before routes + .handler(routingContextHandler) + .failureHandler(routingContextHandler); + + router.route().handler(BodyHandler.create()); + String servletPath = getServletPath(); + router.get(servletPath + PROMETHEUS_ENDPOINT).handler(PrometheusScrapingHandler.create()); + if (consumeAddress == null && sendAddress == null) + configureHealthCheckEndpoint(vertx, router, servletPath, null, + null); + else if (consumeAddress == null) + configureHealthCheckEndpoint(vertx, router, servletPath, null, + sendAddress.getAddress()); + else if (sendAddress == null) + configureHealthCheckEndpoint(vertx, router, servletPath, + consumeAddress.getAddress(), null); + else + configureHealthCheckEndpoint(vertx, router, servletPath, + consumeAddress.getAddress(), sendAddress.getAddress()); + return router; + } + + public void configureHealthCheckEndpoint(Vertx vertx, Router router, final String servletPath, + String consumeAddress, String sendAddress) { + StageHealthCheckHandler healthCheckHandler = new StageHealthCheckHandler(vertx, null, objectMapper, + virusScanner, environment); + router.get(servletPath + HealthConstant.HEALTH_ENDPOINT).handler(healthCheckHandler); + if (servletPath.contains("packetreceiver") || servletPath.contains("uploader")) { + healthCheckHandler.register("virusscanner", healthCheckHandler::virusScanHealthChecker); + healthCheckHandler.register( + servletPath.substring(servletPath.lastIndexOf("/") + 1, servletPath.length()) + "Verticle", + future -> healthCheckHandler.senderHealthHandler(future, vertx, super.mosipEventBus, sendAddress)); + } + if (checkServletPathContainsCoreProcessor(servletPath)) { + healthCheckHandler.register( + servletPath.substring(servletPath.lastIndexOf("/") + 1, servletPath.length()) + "Send", future -> { + healthCheckHandler.senderHealthHandler(future, vertx, super.mosipEventBus, sendAddress); + }); + healthCheckHandler.register( + servletPath.substring(servletPath.lastIndexOf("/") + 1, servletPath.length()) + "Consume", + future -> { + healthCheckHandler.consumerHealthHandler(future, vertx, super.mosipEventBus, consumeAddress); + }); + } + if (servletPath.contains("external") || servletPath.contains("bioauth")) { + healthCheckHandler.register( + servletPath.substring(servletPath.lastIndexOf("/") + 1, servletPath.length()) + "Send", future -> { + healthCheckHandler.senderHealthHandler(future, vertx, super.mosipEventBus, sendAddress); + }); + healthCheckHandler.register( + servletPath.substring(servletPath.lastIndexOf("/") + 1, servletPath.length()) + "Consume", + future -> { + healthCheckHandler.senderHealthHandler(future, vertx, super.mosipEventBus, consumeAddress); + }); + } + if (servletPath.contains("manual")) { + healthCheckHandler.register( + servletPath.substring(servletPath.lastIndexOf("/") + 1, servletPath.length()) + "Verticle", + future -> healthCheckHandler.senderHealthHandler(future, vertx, super.mosipEventBus, sendAddress)); + } + if (servletPath.contains("abismiddleware")) { + healthCheckHandler.register("queuecheck", future -> healthCheckHandler.queueHealthChecker(future, mosipQueueManager, mosipConnectionFactory)); + healthCheckHandler.register( + servletPath.substring(servletPath.lastIndexOf("/") + 1, servletPath.length()) + "Verticle", + future -> healthCheckHandler.consumerHealthHandler(future, vertx, super.mosipEventBus, + consumeAddress)); + } + if (servletPath.contains("sender")) { + healthCheckHandler.register( + servletPath.substring(servletPath.lastIndexOf("/") + 1, servletPath.length()) + "Verticle", + future -> healthCheckHandler.consumerHealthHandler(future, vertx, super.mosipEventBus, + consumeAddress)); + } + + healthCheckHandler.register("diskSpace", healthCheckHandler::dispSpaceHealthChecker); + healthCheckHandler.register("db", healthCheckHandler::databaseHealthChecker); + } + + private boolean checkServletPathContainsCoreProcessor(String servletPath) { + return servletPath.contains("packetvalidator") || servletPath.contains("osi") || servletPath.contains("demo") + || servletPath.contains("bio") || servletPath.contains("uin") || servletPath.contains("quality") + || servletPath.contains("abishandler") || servletPath.contains("securezone"); + } + + /** + * This method creates server for vertx web application + * + * @param router + * @param port + */ + public void createServer(Router router, int port) { + vertx.createHttpServer().requestHandler(router::accept).listen(port); + } + + /** + * This method returns a response to the routing context + * + * @param ctx + * @param object + */ + public void setResponse(RoutingContext ctx, Object object) { + ctx.response().putHeader("content-type", "text/plain").putHeader("Access-Control-Allow-Origin", "*") + .putHeader("Access-Control-Allow-Methods", "GET, POST").setStatusCode(200) + .end(Json.encodePrettily(object)); + }; + + /** + * This method returns a response to the routing context + * + * @param ctx + * @param object + * @param contentType + */ + public void setResponseWithDigitalSignature(RoutingContext ctx, Object object, String contentType) { + HttpServerResponse response = ctx.response(); + + String res=null; + try { + res = objectMapper.writeValueAsString(object); + } catch (JsonProcessingException e) { + regProcLogger.error("Error while processing response",e); + + } + + if (isEnabled) + response.putHeader("Response-Signature", + digitalSignatureUtility.getDigitalSignature(res)); + response.putHeader("content-type", contentType).putHeader("Access-Control-Allow-Origin", "*") + .putHeader("Access-Control-Allow-Methods", "GET, POST").setStatusCode(200) + .end(res); + } + + // Added this method to cast all the stages to this class and invoke the deployVerticle method + // to start the stage by configuration, since we don't want to test all the stages now, not marking this as + // an abstract method, but later this need to be marked as abstract + public void deployVerticle() { + + } + + + /** + * Gets the stage name. + * + * @return the stage name + */ + protected String getStageName() { + return ClassUtils.getUserClass(this.getClass()).getSimpleName(); + } } \ No newline at end of file diff --git a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/abstractverticle/MosipVerticleManager.java b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/abstractverticle/MosipVerticleManager.java index 6f61a739a4a..8763a5f2f2f 100644 --- a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/abstractverticle/MosipVerticleManager.java +++ b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/abstractverticle/MosipVerticleManager.java @@ -1,379 +1,379 @@ -package io.mosip.registration.processor.core.abstractverticle; - -import java.io.IOException; -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.time.LocalDateTime; -import java.time.temporal.ChronoUnit; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutionException; - -import org.apache.commons.lang3.exception.ExceptionUtils; -import org.slf4j.MDC; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; - -import com.fasterxml.jackson.databind.ObjectMapper; -import com.hazelcast.config.Config; -import com.hazelcast.config.UrlXmlConfig; - -import io.mosip.kernel.core.logger.spi.Logger; -import io.mosip.kernel.core.util.DateUtils; -import io.mosip.kernel.core.util.JsonUtils; -import io.mosip.kernel.core.util.exception.JsonProcessingException; -import io.mosip.registration.processor.core.code.ApiName; -import io.mosip.registration.processor.core.constant.HealthConstant; -import io.mosip.registration.processor.core.eventbus.MosipEventBusFactory; -import io.mosip.registration.processor.core.exception.ApisResourceAccessException; -import io.mosip.registration.processor.core.exception.DeploymentFailureException; -import io.mosip.registration.processor.core.exception.MessageExpiredException; -import io.mosip.registration.processor.core.exception.PacketManagerException; -import io.mosip.registration.processor.core.exception.UnsupportedEventBusTypeException; -import io.mosip.registration.processor.core.exception.util.PlatformErrorMessages; -import io.mosip.registration.processor.core.http.RequestWrapper; -import io.mosip.registration.processor.core.http.ResponseWrapper; -import io.mosip.registration.processor.core.logger.RegProcessorLogger; -import io.mosip.registration.processor.core.packet.dto.packetmanager.TagRequestDto; -import io.mosip.registration.processor.core.packet.dto.packetmanager.TagResponseDto; -import io.mosip.registration.processor.core.spi.eventbus.EventBusManager; -import io.mosip.registration.processor.core.spi.restclient.RegistrationProcessorRestClientService; -import io.mosip.registration.processor.core.util.PropertiesUtil; -import io.vertx.core.AbstractVerticle; -import io.vertx.core.DeploymentOptions; -import io.vertx.core.Verticle; -import io.vertx.core.Vertx; -import io.vertx.core.VertxOptions; -import io.vertx.core.eventbus.EventBusOptions; -import io.vertx.core.json.JsonObject; -import io.vertx.core.spi.cluster.ClusterManager; -import io.vertx.micrometer.MicrometerMetricsOptions; -import io.vertx.micrometer.VertxPrometheusOptions; -import io.vertx.spi.cluster.hazelcast.HazelcastClusterManager; - -/** - * This abstract class is Vert.x implementation for MOSIP. - * - * This class provides functionalities to be used by MOSIP verticles. - * - * @author Pranav Kumar - * @author Mukul Puspam - * @since 0.0.1 - * - */ -public abstract class MosipVerticleManager extends AbstractVerticle - implements EventBusManager { - - private static final String EMPTY_STRING = ""; - - /** The logger. */ - private Logger logger = RegProcessorLogger.getLogger(MosipVerticleManager.class); - - private static final String ID = "mosip.commmons.packetmanager"; - private static final String VERSION = "v1"; - - private static final boolean DEFAULT_MESSAGE_TAG_LOADING_DISABLE_VALUE = false; - - @Autowired - private RegistrationProcessorRestClientService restApi; - - @Autowired - private ObjectMapper objectMapper; - - private static final String PROMETHEUS_ENDPOINT = "/actuator/prometheus"; - - @Value("${mosip.regproc.eventbus.type:vertx}") - private String eventBusType; - - @Autowired - protected PropertiesUtil propertiesUtil; - - /* - * Comma separated out bus message addresses for which message will not be sent out from any stage - */ - @Value("#{T(java.util.Arrays).asList('${mosip.regproc.stage-common.bus-out-halt-addresses:}')}") - protected List busOutHaltAddresses; - - @Autowired - private MosipEventBusFactory mosipEventBusFactory; - - protected MosipEventBus mosipEventBus; - - /* - * (non-Javadoc) - * - * @see - * io.mosip.registration.processor.core.spi.eventbus.EventBusManager#getEventBus - * (java.lang.Class, java.lang.String) - */ - @Override - public MosipEventBus getEventBus(Object verticleName, String clusterManagerUrl) { - return getEventBus(verticleName, clusterManagerUrl, 1); - } - - /* - * (non-Javadoc) - * - * @see - * io.mosip.registration.processor.core.spi.eventbus.EventBusManager#getEventBus - * (java.lang.Class) - */ - @Override - public MosipEventBus getEventBus(Object verticleName, String clusterManagerUrl, int instanceNumber) { - CompletableFuture eventBus = new CompletableFuture<>(); - mosipEventBus = null; - Config config; - try { - config = new UrlXmlConfig(clusterManagerUrl); - } catch (IOException e1) { - throw new DeploymentFailureException(PlatformErrorMessages.RPR_CMB_MALFORMED_URL_EXCEPTION.getMessage()); - } - ClusterManager clusterManager = new HazelcastClusterManager(config); - String address = null; - try { - address = InetAddress.getLocalHost().getHostAddress(); - } catch (UnknownHostException e1) { - throw new DeploymentFailureException(PlatformErrorMessages.RPR_CMB_MALFORMED_URL_EXCEPTION.getMessage()); - } - - MicrometerMetricsOptions micrometerMetricsOptions = new MicrometerMetricsOptions() - .setPrometheusOptions(new VertxPrometheusOptions() - .setEnabled(true)) - .setEnabled(true); - - VertxOptions options = new VertxOptions().setClustered(true).setClusterManager(clusterManager) - .setHAEnabled(false).setWorkerPoolSize(instanceNumber) - .setEventBusOptions(new EventBusOptions().setPort(getEventBusPort()).setHost(address)) - .setMetricsOptions(micrometerMetricsOptions); - Vertx.clusteredVertx(options, result -> { - if (result.succeeded()) { - result.result().deployVerticle((Verticle) verticleName, - new DeploymentOptions().setHa(false).setWorker(true).setWorkerPoolSize(instanceNumber)); - eventBus.complete(result.result()); - logger.debug(verticleName + " deployed successfully"); - } else { - throw new DeploymentFailureException(PlatformErrorMessages.RPR_CMB_DEPLOYMENT_FAILURE.getMessage()); - } - }); - - try { - Vertx vert = eventBus.get(); - mosipEventBus = mosipEventBusFactory.getEventBus(vert, getEventBusType(), getPropertyPrefix()); - } catch (InterruptedException | ExecutionException | UnsupportedEventBusTypeException e) { - Thread.currentThread().interrupt(); - throw new DeploymentFailureException(PlatformErrorMessages.RPR_CMB_DEPLOYMENT_FAILURE.getMessage(), e); - } - return mosipEventBus; - } - - /* - * (non-Javadoc) - * - * @see io.mosip.registration.processor.core.spi.eventbus.EventBusManager# - * consumeAndSend(java.lang.Object, java.lang.Object, java.lang.Object) - */ - @Override - public void consumeAndSend(MosipEventBus mosipEventBus, MessageBusAddress fromAddress, - MessageBusAddress toAddress, long messageExpiryTimeLimit) { - if(busOutHaltAddresses.contains(toAddress.getAddress())) { - consume(mosipEventBus, fromAddress, messageExpiryTimeLimit); - return; - } - mosipEventBus.consumeAndSend(fromAddress, toAddress, (msg, handler) -> { - logger.debug("consumeAndSend received from {} {}",fromAddress.toString(), msg.getBody()); - Map mdc = MDC.getCopyOfContextMap(); - vertx.executeBlocking(future -> { - MessageDTO messageDTO =new MessageDTO(); - try { - MDC.setContextMap(mdc); - JsonObject jsonObject = (JsonObject) msg.getBody(); - messageDTO = objectMapper.readValue(objectMapper.writeValueAsString(jsonObject.getMap()), MessageDTO.class); - if(isMessageExpired(messageDTO, messageExpiryTimeLimit)) { - future.fail(new MessageExpiredException("rid: " + messageDTO.getRid() + - " lastHopTimestamp " + messageDTO.getLastHopTimestamp())); - return; - } - - MessageDTO result = process(messageDTO); - addTagsToMessageDTO(result); - result.setLastHopTimestamp(DateUtils.formatToISOString(DateUtils.getUTCCurrentDateTime())); - future.complete(result); - } catch (Exception e) { - logger.error("{} -- {} {} {}", - PlatformErrorMessages.RPR_SYS_STAGE_PROCESSING_FAILED.getCode(), - PlatformErrorMessages.RPR_SYS_STAGE_PROCESSING_FAILED.getMessage(), - e.getMessage(), ExceptionUtils.getStackTrace(e)); - messageDTO.setIsValid(false); - messageDTO.setInternalError(true); - addTagsToMessageDTO(messageDTO); - messageDTO.setLastHopTimestamp(DateUtils.formatToISOString(DateUtils.getUTCCurrentDateTime())); - future.complete(messageDTO); - } - - }, false, handler); - MDC.clear(); - }); - } - - /** - * Send. - * - * @param mosipEventBus - * The Eventbus instance for communication - * @param toAddress - * The address on which message is to be sent - * @param message - * The message that needs to be sent - */ - public void send(MosipEventBus mosipEventBus, MessageBusAddress toAddress, MessageDTO message) { - if(busOutHaltAddresses.contains(toAddress.getAddress())) - return; - addTagsToMessageDTO(message); - message.setLastHopTimestamp(DateUtils.formatToISOString(DateUtils.getUTCCurrentDateTime())); - mosipEventBus.send(toAddress, message); - } - - /** - * Consume. - * - * @param mosipEventBus - * The Eventbus instance for communication - * @param fromAddress - * The address from which message needs to be consumed - * @param messageExpiryTimeLimit - * The time limit in seconds, after which message should considered as expired - */ - public void consume(MosipEventBus mosipEventBus, MessageBusAddress fromAddress, - long messageExpiryTimeLimit) { - mosipEventBus.consume(fromAddress, (msg, handler) -> { - logger.debug("Received from {} {}",fromAddress.toString(), msg.getBody()); - Map mdc = MDC.getCopyOfContextMap(); - vertx.executeBlocking(future -> { - MessageDTO messageDTO=new MessageDTO(); - try { - MDC.setContextMap(mdc); - JsonObject jsonObject = (JsonObject) msg.getBody(); - messageDTO = objectMapper.readValue(objectMapper.writeValueAsString(jsonObject.getMap()), MessageDTO.class); - if(isMessageExpired(messageDTO, messageExpiryTimeLimit)) { - future.fail(new MessageExpiredException("rid: " + messageDTO.getRid() + - " lastHopTimestamp " + messageDTO.getLastHopTimestamp())); - return; - } - - MessageDTO result = process(messageDTO); - future.complete(result); - } catch (Exception e) { - logger.error("{} -- {} {} {}", - PlatformErrorMessages.RPR_SYS_STAGE_PROCESSING_FAILED.getCode(), - PlatformErrorMessages.RPR_SYS_STAGE_PROCESSING_FAILED.getMessage(), - e.getMessage(), ExceptionUtils.getStackTrace(e)); - messageDTO.setIsValid(false); - messageDTO.setInternalError(true); - future.complete(messageDTO); - } - }, false, handler); - MDC.clear(); - }); - } - - public Integer getEventBusPort() { - return getIntegerPropertyForSuffix("eventbus.port"); - } - - public Integer getPort() { - return getIntegerPropertyForSuffix("server.port"); - } - - protected Integer getIntegerPropertyForSuffix(String propSuffix) { - return propertiesUtil.getIntegerProperty(getPropertyPrefix(), propSuffix); - } - - protected Boolean getBooleanPropertyForSuffix(String propSuffix, Boolean defaultValue) { - return propertiesUtil.getProperty(getPropertyPrefix() + propSuffix, Boolean.class, defaultValue); - } - - protected String getPropertyForSuffix(String propSuffix) { - return propertiesUtil.getProperty(getPropertyPrefix(), propSuffix); - } - - protected String getServletPath() { - return getPropertyForSuffix(HealthConstant.SERVLET_PATH); - } - - public String getEventBusType() { - return this.eventBusType; - } - - public Boolean isTagLoadingDisabled() { - return getBooleanPropertyForSuffix("message.tag.loading.disable", DEFAULT_MESSAGE_TAG_LOADING_DISABLE_VALUE); - } - - //TODO Temporarely added for passing the existing unit test case, later to be removed and unit test case to be changed based on SpringRunner - protected void setMosipEventBusFactory(MosipEventBusFactory mosipEventBusFactory) { - this.mosipEventBusFactory = mosipEventBusFactory; - } - - private void addTagsToMessageDTO(MessageDTO messageDTO) { - if(isTagLoadingDisabled()) { - messageDTO.setTags(new HashMap<>()); - return; - } - try { - messageDTO.setTags(getTagsFromPacket(messageDTO.getRid())); - } catch (ApisResourceAccessException | PacketManagerException | - JsonProcessingException | IOException e) { - logger.error(PlatformErrorMessages.RPR_SYS_PACKET_TAGS_COPYING_FAILED.getCode() + - " -- " + PlatformErrorMessages.RPR_SYS_PACKET_TAGS_COPYING_FAILED.getMessage() + - e.getMessage() + ExceptionUtils.getStackTrace(e)); - messageDTO.setInternalError(true); - messageDTO.setTags(new HashMap<>()); - } - } - - private Map getTagsFromPacket(String id) throws ApisResourceAccessException, - PacketManagerException, JsonProcessingException, IOException { - TagRequestDto tagRequestDto = new TagRequestDto(id, null); - RequestWrapper request = new RequestWrapper<>(); - request.setId(ID); - request.setVersion(VERSION); - request.setRequesttime(DateUtils.getUTCCurrentDateTime()); - request.setRequest(tagRequestDto); - ResponseWrapper response = (ResponseWrapper) restApi - .postApi(ApiName.PACKETMANAGER_GET_TAGS, "", "", - request, ResponseWrapper.class); - - if (response.getErrors() != null && response.getErrors().size() > 0) { - logger.error("Registration Id : {} response: {}", id, JsonUtils.javaObjectToJsonString(response)); - throw new PacketManagerException(response.getErrors().get(0).getErrorCode(), - response.getErrors().get(0).getMessage()); - } - - TagResponseDto tagResponseDto = null; - if (response.getResponse() != null) - tagResponseDto = objectMapper.readValue(JsonUtils.javaObjectToJsonString(response.getResponse()), TagResponseDto.class); - - return tagResponseDto != null ? tagResponseDto.getTags() : null; - } - - private boolean isMessageExpired(MessageDTO messageDTO, long messageExpiryTimeLimit) { - if(messageExpiryTimeLimit <= 0) - return false; - try { - LocalDateTime lastHopDateTime = DateUtils.parseUTCToLocalDateTime(messageDTO.getLastHopTimestamp()); - LocalDateTime nowDateTime = LocalDateTime.now(); - if(ChronoUnit.SECONDS.between(lastHopDateTime, nowDateTime) <= messageExpiryTimeLimit) - return false; - return true; - } catch(Exception e) { - logger.error("{} {} {} {}", PlatformErrorMessages.RPR_SYS_PARSING_DATE_EXCEPTION.getCode(), - PlatformErrorMessages.RPR_SYS_PARSING_DATE_EXCEPTION.getMessage(), e.getMessage(), - ExceptionUtils.getStackTrace(e)); - return true; - } - } - - protected abstract String getPropertyPrefix(); - -} +package io.mosip.registration.processor.core.abstractverticle; + +import java.io.IOException; +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.time.LocalDateTime; +import java.time.temporal.ChronoUnit; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; + +import org.apache.commons.lang3.exception.ExceptionUtils; +import org.slf4j.MDC; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.hazelcast.config.Config; +import com.hazelcast.config.UrlXmlConfig; + +import io.mosip.kernel.core.logger.spi.Logger; +import io.mosip.kernel.core.util.DateUtils; +import io.mosip.kernel.core.util.JsonUtils; +import io.mosip.kernel.core.util.exception.JsonProcessingException; +import io.mosip.registration.processor.core.code.ApiName; +import io.mosip.registration.processor.core.constant.HealthConstant; +import io.mosip.registration.processor.core.eventbus.MosipEventBusFactory; +import io.mosip.registration.processor.core.exception.ApisResourceAccessException; +import io.mosip.registration.processor.core.exception.DeploymentFailureException; +import io.mosip.registration.processor.core.exception.MessageExpiredException; +import io.mosip.registration.processor.core.exception.PacketManagerException; +import io.mosip.registration.processor.core.exception.UnsupportedEventBusTypeException; +import io.mosip.registration.processor.core.exception.util.PlatformErrorMessages; +import io.mosip.registration.processor.core.http.RequestWrapper; +import io.mosip.registration.processor.core.http.ResponseWrapper; +import io.mosip.registration.processor.core.logger.RegProcessorLogger; +import io.mosip.registration.processor.core.packet.dto.packetmanager.TagRequestDto; +import io.mosip.registration.processor.core.packet.dto.packetmanager.TagResponseDto; +import io.mosip.registration.processor.core.spi.eventbus.EventBusManager; +import io.mosip.registration.processor.core.spi.restclient.RegistrationProcessorRestClientService; +import io.mosip.registration.processor.core.util.PropertiesUtil; +import io.vertx.core.AbstractVerticle; +import io.vertx.core.DeploymentOptions; +import io.vertx.core.Verticle; +import io.vertx.core.Vertx; +import io.vertx.core.VertxOptions; +import io.vertx.core.eventbus.EventBusOptions; +import io.vertx.core.json.JsonObject; +import io.vertx.core.spi.cluster.ClusterManager; +import io.vertx.micrometer.MicrometerMetricsOptions; +import io.vertx.micrometer.VertxPrometheusOptions; +import io.vertx.spi.cluster.hazelcast.HazelcastClusterManager; + +/** + * This abstract class is Vert.x implementation for MOSIP. + * + * This class provides functionalities to be used by MOSIP verticles. + * + * @author Pranav Kumar + * @author Mukul Puspam + * @since 0.0.1 + * + */ +public abstract class MosipVerticleManager extends AbstractVerticle + implements EventBusManager { + + private static final String EMPTY_STRING = ""; + + /** The logger. */ + private Logger logger = RegProcessorLogger.getLogger(MosipVerticleManager.class); + + private static final String ID = "mosip.commmons.packetmanager"; + private static final String VERSION = "v1"; + + private static final boolean DEFAULT_MESSAGE_TAG_LOADING_DISABLE_VALUE = false; + + @Autowired + private RegistrationProcessorRestClientService restApi; + + @Autowired + private ObjectMapper objectMapper; + + private static final String PROMETHEUS_ENDPOINT = "/actuator/prometheus"; + + @Value("${mosip.regproc.eventbus.type:vertx}") + private String eventBusType; + + @Autowired + protected PropertiesUtil propertiesUtil; + + /* + * Comma separated out bus message addresses for which message will not be sent out from any stage + */ + @Value("#{T(java.util.Arrays).asList('${mosip.regproc.stage-common.bus-out-halt-addresses:}')}") + protected List busOutHaltAddresses; + + @Autowired + private MosipEventBusFactory mosipEventBusFactory; + + protected MosipEventBus mosipEventBus; + + /* + * (non-Javadoc) + * + * @see + * io.mosip.registration.processor.core.spi.eventbus.EventBusManager#getEventBus + * (java.lang.Class, java.lang.String) + */ + @Override + public MosipEventBus getEventBus(Object verticleName, String clusterManagerUrl) { + return getEventBus(verticleName, clusterManagerUrl, 1); + } + + /* + * (non-Javadoc) + * + * @see + * io.mosip.registration.processor.core.spi.eventbus.EventBusManager#getEventBus + * (java.lang.Class) + */ + @Override + public MosipEventBus getEventBus(Object verticleName, String clusterManagerUrl, int instanceNumber) { + CompletableFuture eventBus = new CompletableFuture<>(); + mosipEventBus = null; + Config config; + try { + config = new UrlXmlConfig(clusterManagerUrl); + } catch (IOException e1) { + throw new DeploymentFailureException(PlatformErrorMessages.RPR_CMB_MALFORMED_URL_EXCEPTION.getMessage()); + } + ClusterManager clusterManager = new HazelcastClusterManager(config); + String address = null; + try { + address = InetAddress.getLocalHost().getHostAddress(); + } catch (UnknownHostException e1) { + throw new DeploymentFailureException(PlatformErrorMessages.RPR_CMB_MALFORMED_URL_EXCEPTION.getMessage()); + } + + MicrometerMetricsOptions micrometerMetricsOptions = new MicrometerMetricsOptions() + .setPrometheusOptions(new VertxPrometheusOptions() + .setEnabled(true)) + .setEnabled(true); + + VertxOptions options = new VertxOptions().setClustered(true).setClusterManager(clusterManager) + .setHAEnabled(false).setWorkerPoolSize(instanceNumber) + .setEventBusOptions(new EventBusOptions().setPort(getEventBusPort()).setHost(address)) + .setMetricsOptions(micrometerMetricsOptions); + Vertx.clusteredVertx(options, result -> { + if (result.succeeded()) { + result.result().deployVerticle((Verticle) verticleName, + new DeploymentOptions().setHa(false).setWorker(true).setWorkerPoolSize(instanceNumber)); + eventBus.complete(result.result()); + logger.debug(verticleName + " deployed successfully"); + } else { + throw new DeploymentFailureException(PlatformErrorMessages.RPR_CMB_DEPLOYMENT_FAILURE.getMessage()); + } + }); + + try { + Vertx vert = eventBus.get(); + mosipEventBus = mosipEventBusFactory.getEventBus(vert, getEventBusType(), getPropertyPrefix()); + } catch (InterruptedException | ExecutionException | UnsupportedEventBusTypeException e) { + Thread.currentThread().interrupt(); + throw new DeploymentFailureException(PlatformErrorMessages.RPR_CMB_DEPLOYMENT_FAILURE.getMessage(), e); + } + return mosipEventBus; + } + + /* + * (non-Javadoc) + * + * @see io.mosip.registration.processor.core.spi.eventbus.EventBusManager# + * consumeAndSend(java.lang.Object, java.lang.Object, java.lang.Object) + */ + @Override + public void consumeAndSend(MosipEventBus mosipEventBus, MessageBusAddress fromAddress, + MessageBusAddress toAddress, long messageExpiryTimeLimit) { + if(busOutHaltAddresses.contains(toAddress.getAddress())) { + consume(mosipEventBus, fromAddress, messageExpiryTimeLimit); + return; + } + mosipEventBus.consumeAndSend(fromAddress, toAddress, (msg, handler) -> { + logger.debug("consumeAndSend received from {} {}",fromAddress.toString(), msg.getBody()); + Map mdc = MDC.getCopyOfContextMap(); + vertx.executeBlocking(future -> { + MessageDTO messageDTO =new MessageDTO(); + try { + MDC.setContextMap(mdc); + JsonObject jsonObject = (JsonObject) msg.getBody(); + messageDTO = objectMapper.readValue(objectMapper.writeValueAsString(jsonObject.getMap()), MessageDTO.class); + if(isMessageExpired(messageDTO, messageExpiryTimeLimit)) { + future.fail(new MessageExpiredException("rid: " + messageDTO.getRid() + + " lastHopTimestamp " + messageDTO.getLastHopTimestamp())); + return; + } + + MessageDTO result = process(messageDTO); + addTagsToMessageDTO(result); + result.setLastHopTimestamp(DateUtils.formatToISOString(DateUtils.getUTCCurrentDateTime())); + future.complete(result); + } catch (Exception e) { + logger.error("{} -- {} {} {}", + PlatformErrorMessages.RPR_SYS_STAGE_PROCESSING_FAILED.getCode(), + PlatformErrorMessages.RPR_SYS_STAGE_PROCESSING_FAILED.getMessage(), + e.getMessage(), ExceptionUtils.getStackTrace(e)); + messageDTO.setIsValid(false); + messageDTO.setInternalError(true); + addTagsToMessageDTO(messageDTO); + messageDTO.setLastHopTimestamp(DateUtils.formatToISOString(DateUtils.getUTCCurrentDateTime())); + future.complete(messageDTO); + } + + }, false, handler); + MDC.clear(); + }); + } + + /** + * Send. + * + * @param mosipEventBus + * The Eventbus instance for communication + * @param toAddress + * The address on which message is to be sent + * @param message + * The message that needs to be sent + */ + public void send(MosipEventBus mosipEventBus, MessageBusAddress toAddress, MessageDTO message) { + if(busOutHaltAddresses.contains(toAddress.getAddress())) + return; + addTagsToMessageDTO(message); + message.setLastHopTimestamp(DateUtils.formatToISOString(DateUtils.getUTCCurrentDateTime())); + mosipEventBus.send(toAddress, message); + } + + /** + * Consume. + * + * @param mosipEventBus + * The Eventbus instance for communication + * @param fromAddress + * The address from which message needs to be consumed + * @param messageExpiryTimeLimit + * The time limit in seconds, after which message should considered as expired + */ + public void consume(MosipEventBus mosipEventBus, MessageBusAddress fromAddress, + long messageExpiryTimeLimit) { + mosipEventBus.consume(fromAddress, (msg, handler) -> { + logger.debug("Received from {} {}",fromAddress.toString(), msg.getBody()); + Map mdc = MDC.getCopyOfContextMap(); + vertx.executeBlocking(future -> { + MessageDTO messageDTO=new MessageDTO(); + try { + MDC.setContextMap(mdc); + JsonObject jsonObject = (JsonObject) msg.getBody(); + messageDTO = objectMapper.readValue(objectMapper.writeValueAsString(jsonObject.getMap()), MessageDTO.class); + if(isMessageExpired(messageDTO, messageExpiryTimeLimit)) { + future.fail(new MessageExpiredException("rid: " + messageDTO.getRid() + + " lastHopTimestamp " + messageDTO.getLastHopTimestamp())); + return; + } + + MessageDTO result = process(messageDTO); + future.complete(result); + } catch (Exception e) { + logger.error("{} -- {} {} {}", + PlatformErrorMessages.RPR_SYS_STAGE_PROCESSING_FAILED.getCode(), + PlatformErrorMessages.RPR_SYS_STAGE_PROCESSING_FAILED.getMessage(), + e.getMessage(), ExceptionUtils.getStackTrace(e)); + messageDTO.setIsValid(false); + messageDTO.setInternalError(true); + future.complete(messageDTO); + } + }, false, handler); + MDC.clear(); + }); + } + + public Integer getEventBusPort() { + return getIntegerPropertyForSuffix("eventbus.port"); + } + + public Integer getPort() { + return getIntegerPropertyForSuffix("server.port"); + } + + protected Integer getIntegerPropertyForSuffix(String propSuffix) { + return propertiesUtil.getIntegerProperty(getPropertyPrefix(), propSuffix); + } + + protected Boolean getBooleanPropertyForSuffix(String propSuffix, Boolean defaultValue) { + return propertiesUtil.getProperty(getPropertyPrefix() + propSuffix, Boolean.class, defaultValue); + } + + protected String getPropertyForSuffix(String propSuffix) { + return propertiesUtil.getProperty(getPropertyPrefix(), propSuffix); + } + + protected String getServletPath() { + return getPropertyForSuffix(HealthConstant.SERVLET_PATH); + } + + public String getEventBusType() { + return this.eventBusType; + } + + public Boolean isTagLoadingDisabled() { + return getBooleanPropertyForSuffix("message.tag.loading.disable", DEFAULT_MESSAGE_TAG_LOADING_DISABLE_VALUE); + } + + //TODO Temporarely added for passing the existing unit test case, later to be removed and unit test case to be changed based on SpringRunner + protected void setMosipEventBusFactory(MosipEventBusFactory mosipEventBusFactory) { + this.mosipEventBusFactory = mosipEventBusFactory; + } + + private void addTagsToMessageDTO(MessageDTO messageDTO) { + if(isTagLoadingDisabled()) { + messageDTO.setTags(new HashMap<>()); + return; + } + try { + messageDTO.setTags(getTagsFromPacket(messageDTO.getRid())); + } catch (ApisResourceAccessException | PacketManagerException | + JsonProcessingException | IOException e) { + logger.error(PlatformErrorMessages.RPR_SYS_PACKET_TAGS_COPYING_FAILED.getCode() + + " -- " + PlatformErrorMessages.RPR_SYS_PACKET_TAGS_COPYING_FAILED.getMessage() + + e.getMessage() + ExceptionUtils.getStackTrace(e)); + messageDTO.setInternalError(true); + messageDTO.setTags(new HashMap<>()); + } + } + + private Map getTagsFromPacket(String id) throws ApisResourceAccessException, + PacketManagerException, JsonProcessingException, IOException { + TagRequestDto tagRequestDto = new TagRequestDto(id, null); + RequestWrapper request = new RequestWrapper<>(); + request.setId(ID); + request.setVersion(VERSION); + request.setRequesttime(DateUtils.getUTCCurrentDateTime()); + request.setRequest(tagRequestDto); + ResponseWrapper response = (ResponseWrapper) restApi + .postApi(ApiName.PACKETMANAGER_GET_TAGS, "", "", + request, ResponseWrapper.class); + + if (response.getErrors() != null && response.getErrors().size() > 0) { + logger.error("Registration Id : {} response: {}", id, JsonUtils.javaObjectToJsonString(response)); + throw new PacketManagerException(response.getErrors().get(0).getErrorCode(), + response.getErrors().get(0).getMessage()); + } + + TagResponseDto tagResponseDto = null; + if (response.getResponse() != null) + tagResponseDto = objectMapper.readValue(JsonUtils.javaObjectToJsonString(response.getResponse()), TagResponseDto.class); + + return tagResponseDto != null ? tagResponseDto.getTags() : null; + } + + private boolean isMessageExpired(MessageDTO messageDTO, long messageExpiryTimeLimit) { + if(messageExpiryTimeLimit <= 0) + return false; + try { + LocalDateTime lastHopDateTime = DateUtils.parseUTCToLocalDateTime(messageDTO.getLastHopTimestamp()); + LocalDateTime nowDateTime = LocalDateTime.now(); + if(ChronoUnit.SECONDS.between(lastHopDateTime, nowDateTime) <= messageExpiryTimeLimit) + return false; + return true; + } catch(Exception e) { + logger.error("{} {} {} {}", PlatformErrorMessages.RPR_SYS_PARSING_DATE_EXCEPTION.getCode(), + PlatformErrorMessages.RPR_SYS_PARSING_DATE_EXCEPTION.getMessage(), e.getMessage(), + ExceptionUtils.getStackTrace(e)); + return true; + } + } + + protected abstract String getPropertyPrefix(); + +} diff --git a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/code/ApiName.java b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/code/ApiName.java index 26d9a20ea9b..bfaaa1ae892 100644 --- a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/code/ApiName.java +++ b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/code/ApiName.java @@ -196,7 +196,8 @@ public enum ApiName { IDREPOCREATEDRAFT, IDREPOUPDATEDRAFT, IDREPOPUBLISHDRAFT, - IDREPOEXTRACTBIOMETRICS; + IDREPOEXTRACTBIOMETRICS, + CREDENTIALREQUESTV2; } diff --git a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/config/CoreConfigBean.java b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/config/CoreConfigBean.java index a391a827e53..107761b6d20 100644 --- a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/config/CoreConfigBean.java +++ b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/config/CoreConfigBean.java @@ -16,6 +16,7 @@ import org.springframework.core.env.Environment; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import brave.Tracer; @@ -203,6 +204,7 @@ public ObjectMapper getObjectMapper() { ObjectMapper objectMapper = new ObjectMapper().registerModule(new AfterburnerModule()) .registerModule(new JavaTimeModule()); objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); + objectMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS); return objectMapper; } diff --git a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/constant/LandingZoneTypeConstant.java b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/constant/LandingZoneTypeConstant.java new file mode 100644 index 00000000000..6463feb70ce --- /dev/null +++ b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/constant/LandingZoneTypeConstant.java @@ -0,0 +1,6 @@ +package io.mosip.registration.processor.core.constant; + +public class LandingZoneTypeConstant { + public static final String DMZ_SERVER = "DMZServer"; + public static final String OBJECT_STORE = "ObjectStore"; +} diff --git a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/constant/MappingJsonConstants.java b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/constant/MappingJsonConstants.java index 6bfe0e603a0..97284b03286 100644 --- a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/constant/MappingJsonConstants.java +++ b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/constant/MappingJsonConstants.java @@ -18,6 +18,7 @@ public class MappingJsonConstants { public static final String DOCUMENT = "documents"; public static final String BIOMETRICS = "biometrics"; public static final String PREFERRED_LANGUAGE = "preferredLanguage"; + public static final String CONSENT="consent"; public static final String INTRODUCER_BIO = "introducerBiometrics"; /** The Constant OFFICERBIOMETRICFILENAME. */ 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 84275f3d792..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 @@ -18,6 +18,7 @@ import io.vertx.core.json.JsonObject; + /** * Implementation of MosipEventBus interface for Vertx navtive event bus * 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 1853cb2c2d5..fa6aa67cdc2 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 @@ -199,9 +199,15 @@ public enum PlatformErrorMessages { 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", @@ -1018,7 +1024,7 @@ public enum PlatformErrorMessages { /** 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"), @@ -1418,9 +1424,14 @@ public enum PlatformErrorMessages { 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") + "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; diff --git a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/exception/util/PlatformSuccessMessages.java b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/exception/util/PlatformSuccessMessages.java index e8a711002d2..c18347781b7 100644 --- a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/exception/util/PlatformSuccessMessages.java +++ b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/exception/util/PlatformSuccessMessages.java @@ -59,6 +59,8 @@ public enum PlatformSuccessMessages { // Biometric Authentication Success Messages RPR_PKR_BIOMETRIC_AUTHENTICATION(PlatformConstants.RPR_BIOMETRIC_AUTHENTICATION_MODULE + "000", "Biometric Authentication Success"), + + // Bio-De-dupe Success messages /** The Constant PACKET_BIODEDUPE_SUCCESS. */ 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 1624332391f..953242949c0 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 @@ -6,12 +6,21 @@ import org.slf4j.LoggerFactory; import io.mosip.kernel.core.logger.spi.Logger; -import io.mosip.kernel.logger.logback.appender.RollingFileAppender; +import org.slf4j.LoggerFactory; import io.mosip.kernel.logger.logback.factory.Logfactory; import ch.qos.logback.classic.Level; import ch.qos.logback.classic.LoggerContext; + +import java.util.stream.Collectors; +import java.util.HashMap; +import java.util.Map; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.LoggerContext; + + /** * The Class RegProcessorLogger. * @author : Rishabh Keshari @@ -19,9 +28,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. */ @@ -40,7 +49,7 @@ public static Logger getLogger(Class clazz) { .filter(entry -> entry.getKey().toString().startsWith(PROP_PREFIX)) .collect(Collectors.toMap(entry -> (String)entry.getKey(), entry -> (String)entry.getValue())); } - Logger logger=Logfactory.getSlf4jLogger(clazz); + Logger logger= Logfactory.getSlf4jLogger(clazz); String loggerName = clazz.getName(); if(loggingLevelMap.entrySet().stream().anyMatch( entry -> entry.getKey().equals(PROP_PREFIX+loggerName))) { LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory(); diff --git a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/queue/factory/MosipActiveMq.java b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/queue/factory/MosipActiveMq.java index 41a84aee361..c159c29f4a2 100644 --- a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/queue/factory/MosipActiveMq.java +++ b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/queue/factory/MosipActiveMq.java @@ -36,7 +36,7 @@ public ActiveMQConnectionFactory getActiveMQConnectionFactory() { @Override public void createConnection(String username, String password, String brokerUrl) { - this.activeMQConnectionFactory = new ActiveMQConnectionFactory(username, password, brokerUrl); + this.activeMQConnectionFactory = new ActiveMQConnectionFactory(username, password, brokerUrl);//NOSONAR } @Override diff --git a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/status/util/StatusUtil.java b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/status/util/StatusUtil.java index a69e797d130..78b9dcb26af 100644 --- a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/status/util/StatusUtil.java +++ b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/status/util/StatusUtil.java @@ -4,246 +4,338 @@ public enum StatusUtil { // Packet Receiver Stage - PACKET_RECEIVED(StatusConstants.PACKET_RECEIVER_MODULE_SUCCESS + "001","Packet has reached Packet Receiver"), - PACKET_UPLOADED_TO_LANDING_ZONE(StatusConstants.PACKET_RECEIVER_MODULE_SUCCESS + "002","Packet is Uploaded to Landing Zone"), - VIRUS_SCANNER_FAILED(StatusConstants.PACKET_RECEIVER_MODULE_FAILURE + "001","Packet is Virus Infected"), + PACKET_RECEIVED(StatusConstants.PACKET_RECEIVER_MODULE_SUCCESS + "001", "Packet has reached Packet Receiver"), + PACKET_UPLOADED_TO_LANDING_ZONE(StatusConstants.PACKET_RECEIVER_MODULE_SUCCESS + "002", + "Packet is Uploaded to Landing Zone"), + VIRUS_SCANNER_FAILED(StatusConstants.PACKET_RECEIVER_MODULE_FAILURE + "001", "Packet is Virus Infected"), PACKET_DECRYPTION_FAILED(StatusConstants.PACKET_RECEIVER_MODULE_FAILURE + "002", "Packet Decryption Failed"), // securezone notification stage - NOTIFICATION_RECEIVED_TO_SECUREZONE(StatusConstants.SECUREZONE_NOTIFICATION_SUCCESS + "001","Notification received to securezone"), + NOTIFICATION_RECEIVED_TO_SECUREZONE(StatusConstants.SECUREZONE_NOTIFICATION_SUCCESS + "001", + "Notification received to securezone"), // Packet uploader stage - PACKET_UPLOADED(StatusConstants.PACKET_UPLOADER_MODULE_SUCCESS + "001","Packet is Uploaded to Packet Store"), - PACKET_CLEANUP_FAILED(StatusConstants.PACKET_UPLOADER_MODULE_FAILED + "001","Packet Clean Up Failed from Landing Zone"), - PACKET_ARCHIVAL_FAILED(StatusConstants.PACKET_UPLOADER_MODULE_FAILED + "002","Packet Archival Failed"), - PACKET_UPLOAD_FAILED(StatusConstants.PACKET_UPLOADER_MODULE_FAILED + "003","Packet Upload Failed"), - PACKET_NOT_FOUND_LANDING_ZONE(StatusConstants.PACKET_UPLOADER_MODULE_FAILED + "004","Packet Not Found in Landing Zone"), - PACKET_HASHCODE_VALIDATION_FAILED(StatusConstants.PACKET_UPLOADER_MODULE_FAILED + "005","Packet Hash Code Validation Failed"), - VIRUS_SCANNER_FAILED_UPLOADER(StatusConstants.PACKET_UPLOADER_MODULE_FAILED + "006","Packet is Virus Infected"), + PACKET_UPLOADED(StatusConstants.PACKET_UPLOADER_MODULE_SUCCESS + "001", "Packet is Uploaded to Packet Store"), + PACKET_CLEANUP_FAILED(StatusConstants.PACKET_UPLOADER_MODULE_FAILED + "001", + "Packet Clean Up Failed from Landing Zone"), + PACKET_ARCHIVAL_FAILED(StatusConstants.PACKET_UPLOADER_MODULE_FAILED + "002", "Packet Archival Failed"), + PACKET_UPLOAD_FAILED(StatusConstants.PACKET_UPLOADER_MODULE_FAILED + "003", "Packet Upload Failed"), + PACKET_NOT_FOUND_LANDING_ZONE(StatusConstants.PACKET_UPLOADER_MODULE_FAILED + "004", + "Packet Not Found in Landing Zone"), + PACKET_HASHCODE_VALIDATION_FAILED(StatusConstants.PACKET_UPLOADER_MODULE_FAILED + "005", + "Packet Hash Code Validation Failed"), + VIRUS_SCANNER_FAILED_UPLOADER(StatusConstants.PACKET_UPLOADER_MODULE_FAILED + "006", "Packet is Virus Infected"), PACKET_UPLOAD_DECRYPTION_FAILED(StatusConstants.PACKET_UPLOADER_MODULE_FAILED + "007", "Packet Decryption Failed"), - PACKET_ALREADY_UPLOADED(StatusConstants.PACKET_UPLOADER_MODULE_SUCCESS + "008","Packet is already present in Packet Store"), - PACKET_RETRY_CNT_EXCEEDED(StatusConstants.PACKET_UPLOADER_MODULE_FAILED + "009", "Retry count has exceeded the maximum limit specified"), + PACKET_ALREADY_UPLOADED(StatusConstants.PACKET_UPLOADER_MODULE_SUCCESS + "008", + "Packet is already present in Packet Store"), + PACKET_RETRY_CNT_EXCEEDED(StatusConstants.PACKET_UPLOADER_MODULE_FAILED + "009", + "Retry count has exceeded the maximum limit specified"), // Quality checker stage - INDIVIDUAL_BIOMETRIC_NOT_FOUND(StatusConstants.QUALITY_CHECKER_MODULE_SUCCESS + "001","Individual Biometric Parameter Not Found in ID JSON so skipping biometric classification"), - BIOMETRIC_QUALITY_CHECK_SUCCESS(StatusConstants.QUALITY_CHECKER_MODULE_SUCCESS + "002","Biometric Quality Check is Successful"), - BIOMETRIC_QUALITY_CHECK_FAILED(StatusConstants.QUALITY_CHECKER_MODULE_FAILED + "001","Quality Score of Biometrics Captured is Below the Threshold"), + INDIVIDUAL_BIOMETRIC_NOT_FOUND(StatusConstants.QUALITY_CHECKER_MODULE_SUCCESS + "001", + "Individual Biometric Parameter Not Found in ID JSON so skipping biometric classification"), + BIOMETRIC_QUALITY_CHECK_SUCCESS(StatusConstants.QUALITY_CHECKER_MODULE_SUCCESS + "002", + "Biometric Quality Check is Successful"), + BIOMETRIC_QUALITY_CHECK_FAILED(StatusConstants.QUALITY_CHECKER_MODULE_FAILED + "001", + "Quality Score of Biometrics Captured is Below the Threshold"), // packet validator stage - PACKET_STRUCTURAL_VALIDATION_SUCCESS(StatusConstants.PACKET_VALIDATOR_MODULE_SUCCESS + "001","Packet Validation is Successful"), - FILE_VALIDATION_FAILED(StatusConstants.PACKET_VALIDATOR_MODULE_FAILED + "001","File Validation Failed"), - SCHEMA_VALIDATION_FAILED(StatusConstants.PACKET_VALIDATOR_MODULE_FAILED + "002","Schema Validation Failed"), - CHECKSUM_VALIDATION_FAILED(StatusConstants.PACKET_VALIDATOR_MODULE_FAILED + "003","Check Sum Validation Failed"), - INDIVIDUAL_BIOMETRIC_VALIDATION_FAILED(StatusConstants.PACKET_VALIDATOR_MODULE_FAILED + "004","Individual Biometric Validation Failed"), - APPLICANT_DOCUMENT_VALIDATION_FAILED(StatusConstants.PACKET_VALIDATOR_MODULE_FAILED + "005","Applicant Document Validation Failed"), - MASTER_DATA_VALIDATION_FAILED(StatusConstants.PACKET_VALIDATOR_MODULE_FAILED + "006","Master Data Validation Failed"), - ACTIVATE_DEACTIVATE_FAILED(StatusConstants.PACKET_VALIDATOR_MODULE_FAILED + "007","Packet Validation for Activate/Deactivate Packet Failed"), - UIN_NOT_FOUND_IDREPO(StatusConstants.PACKET_VALIDATOR_MODULE_FAILED + "008","UIN is Not Found in ID Repository"), - MANDATORY_VALIDATION_FAILED(StatusConstants.PACKET_VALIDATOR_MODULE_FAILED + "009", "Mandatory Fields are Not Present in ID Object"), - RID_AND_TYPE_SYNC_FAILED(StatusConstants.PACKET_VALIDATOR_MODULE_FAILED + "010", "RID & Type not matched from sync table"), + PACKET_STRUCTURAL_VALIDATION_SUCCESS(StatusConstants.PACKET_VALIDATOR_MODULE_SUCCESS + "001", + "Packet Validation is Successful"), + FILE_VALIDATION_FAILED(StatusConstants.PACKET_VALIDATOR_MODULE_FAILED + "001", "File Validation Failed"), + SCHEMA_VALIDATION_FAILED(StatusConstants.PACKET_VALIDATOR_MODULE_FAILED + "002", "Schema Validation Failed"), + CHECKSUM_VALIDATION_FAILED(StatusConstants.PACKET_VALIDATOR_MODULE_FAILED + "003", "Check Sum Validation Failed"), + INDIVIDUAL_BIOMETRIC_VALIDATION_FAILED(StatusConstants.PACKET_VALIDATOR_MODULE_FAILED + "004", + "Individual Biometric Validation Failed"), + APPLICANT_DOCUMENT_VALIDATION_FAILED(StatusConstants.PACKET_VALIDATOR_MODULE_FAILED + "005", + "Applicant Document Validation Failed"), + MASTER_DATA_VALIDATION_FAILED(StatusConstants.PACKET_VALIDATOR_MODULE_FAILED + "006", + "Master Data Validation Failed"), + ACTIVATE_DEACTIVATE_FAILED(StatusConstants.PACKET_VALIDATOR_MODULE_FAILED + "007", + "Packet Validation for Activate/Deactivate Packet Failed"), + UIN_NOT_FOUND_IDREPO(StatusConstants.PACKET_VALIDATOR_MODULE_FAILED + "008", "UIN is Not Found in ID Repository"), + MANDATORY_VALIDATION_FAILED(StatusConstants.PACKET_VALIDATOR_MODULE_FAILED + "009", + "Mandatory Fields are Not Present in ID Object"), + RID_AND_TYPE_SYNC_FAILED(StatusConstants.PACKET_VALIDATOR_MODULE_FAILED + "010", + "RID & Type not matched from sync table"), PACKET_REJECTED(StatusConstants.PACKET_VALIDATOR_MODULE_FAILED + "011", "Rejected by Supervisor"), - PACKET_MANAGER_VALIDATION_FAILURE(StatusConstants.PACKET_VALIDATOR_MODULE_FAILED + "012", "Packet validation failed in packet manager"), - BIOMETRICS_VALIDATION_FAILURE(StatusConstants.PACKET_VALIDATOR_MODULE_FAILED + "013", "Biometric file validation failed"), - PACKET_MANAGER_EXCEPTION(StatusConstants.PACKET_VALIDATOR_MODULE_FAILED + "014", "Exception occured in packet manager."), + PACKET_MANAGER_VALIDATION_FAILURE(StatusConstants.PACKET_VALIDATOR_MODULE_FAILED + "012", + "Packet validation failed in packet manager"), + BIOMETRICS_VALIDATION_FAILURE(StatusConstants.PACKET_VALIDATOR_MODULE_FAILED + "013", + "Biometric file validation failed"), + PACKET_MANAGER_EXCEPTION(StatusConstants.PACKET_VALIDATOR_MODULE_FAILED + "014", + "Exception occured in packet manager."), XSD_VALIDATION_EXCEPTION(StatusConstants.PACKET_VALIDATOR_MODULE_FAILED + "015", "XSD validation failed."), - BIOMETRICS_SIGNATURE_VALIDATION_FAILURE(StatusConstants.PACKET_VALIDATOR_MODULE_FAILED + "016", "Biometric Signature validation failed"), + BIOMETRICS_SIGNATURE_VALIDATION_FAILURE(StatusConstants.PACKET_VALIDATOR_MODULE_FAILED + "016", + "Biometric Signature validation failed"), + PACKET_CONSENT_VALIDATION(StatusConstants.PACKET_VALIDATOR_MODULE_FAILED + "017", + "Consent is not agreed for the packet to process further"), // packet classifier stage - PACKET_CLASSIFICATION_SUCCESS(StatusConstants.PACKET_CLASSIFIER_MODULE_SUCCESS + "001","Packet Classification is Successful"), + PACKET_CLASSIFICATION_SUCCESS(StatusConstants.PACKET_CLASSIFIER_MODULE_SUCCESS + "001", + "Packet Classification is Successful"), // External stage - EXTERNAL_STAGE_SUCCESS(StatusConstants.EXTERNAL_SATGE_MODULE_SUCCESS + "001", "Packet processing in External stage is sucessful"), - EXTERNAL_STAGE_FAILED(StatusConstants.EXTERNAL_SATGE_MODULE_SUCCESS + "001", "Packet processing in External stage failed"), + EXTERNAL_STAGE_SUCCESS(StatusConstants.EXTERNAL_SATGE_MODULE_SUCCESS + "001", + "Packet processing in External stage is sucessful"), + EXTERNAL_STAGE_FAILED(StatusConstants.EXTERNAL_SATGE_MODULE_SUCCESS + "001", + "Packet processing in External stage failed"), // CMD Validator stage CMD_VALIDATION_SUCCESS(StatusConstants.CMD_VALIDAOR_MODULE_SUCCESS + "001", "CMD Validation is Successful"), GPS_DETAILS_NOT_FOUND(StatusConstants.CMD_VALIDAOR_MODULE_FAILED + "001", "GPS Details are Not Found in Packet"), - CENTER_ID_NOT_FOUND(StatusConstants.CMD_VALIDAOR_MODULE_FAILED + "002","Center ID Not Found in Master DB - "), - CENTER_ID_INACTIVE(StatusConstants.CMD_VALIDAOR_MODULE_FAILED + "003","Center was InActive during Packet Creation - "), - MACHINE_ID_NOT_FOUND(StatusConstants.CMD_VALIDAOR_MODULE_FAILED + "004","Machine ID Not Found in Master DB - "), - MACHINE_ID_NOT_ACTIVE(StatusConstants.CMD_VALIDAOR_MODULE_FAILED + "005","Machine ID was InActive during Packet Creation - "), - CENTER_DEVICE_MAPPING_NOT_FOUND(StatusConstants.CMD_VALIDAOR_MODULE_FAILED + "006","Center-Device Mapping Not Found - "), - CENTER_DEVICE_MAPPING_INACTIVE(StatusConstants.CMD_VALIDAOR_MODULE_FAILED + "007","Center-Device Mapping was InActive during Packet Creation - "), - DEVICE_NOT_FOUND_MASTER_DB(StatusConstants.CMD_VALIDAOR_MODULE_FAILED + "008","Device Not Found in Master DB - "), + CENTER_ID_NOT_FOUND(StatusConstants.CMD_VALIDAOR_MODULE_FAILED + "002", "Center ID Not Found in Master DB - "), + CENTER_ID_INACTIVE(StatusConstants.CMD_VALIDAOR_MODULE_FAILED + "003", + "Center was InActive during Packet Creation - "), + MACHINE_ID_NOT_FOUND(StatusConstants.CMD_VALIDAOR_MODULE_FAILED + "004", "Machine ID Not Found in Master DB - "), + MACHINE_ID_NOT_ACTIVE(StatusConstants.CMD_VALIDAOR_MODULE_FAILED + "005", + "Machine ID was InActive during Packet Creation - "), + CENTER_DEVICE_MAPPING_NOT_FOUND(StatusConstants.CMD_VALIDAOR_MODULE_FAILED + "006", + "Center-Device Mapping Not Found - "), + CENTER_DEVICE_MAPPING_INACTIVE(StatusConstants.CMD_VALIDAOR_MODULE_FAILED + "007", + "Center-Device Mapping was InActive during Packet Creation - "), + DEVICE_NOT_FOUND_MASTER_DB(StatusConstants.CMD_VALIDAOR_MODULE_FAILED + "008", "Device Not Found in Master DB - "), DEVICE_VALIDATION_FAILED(StatusConstants.CMD_VALIDAOR_MODULE_FAILED + "009", "Device Validation Failed"), - PACKET_CREATION_WORKING_HOURS(StatusConstants.CMD_VALIDAOR_MODULE_FAILED + "010", "Packet was Not Created during Working Hours - "), - REGISTRATION_CENTER_TIMESTAMP_FAILURE(StatusConstants.CMD_VALIDAOR_MODULE_FAILED + "011", "Registration Center timestamp failed"), - FAILED_TO_GET_MACHINE_DETAIL(StatusConstants.CMD_VALIDAOR_MODULE_FAILED + "012", "Failed to Get machine id details "), + PACKET_CREATION_WORKING_HOURS(StatusConstants.CMD_VALIDAOR_MODULE_FAILED + "010", + "Packet was Not Created during Working Hours - "), + REGISTRATION_CENTER_TIMESTAMP_FAILURE(StatusConstants.CMD_VALIDAOR_MODULE_FAILED + "011", + "Registration Center timestamp failed"), + FAILED_TO_GET_MACHINE_DETAIL(StatusConstants.CMD_VALIDAOR_MODULE_FAILED + "012", + "Failed to Get machine id details "), FAILED_TO_GET_CENTER_DETAIL(StatusConstants.CMD_VALIDAOR_MODULE_FAILED + "013", "Failed to Get center id details "), - VALIDATION_FAILED_EXCEPTION(StatusConstants.CMD_VALIDAOR_MODULE_FAILED + "014", "Exception occured due to validation failure."), - MACHINE_ID_NOT_FOUND_MASTER_DB(StatusConstants.CMD_VALIDAOR_MODULE_FAILED + "015", "MachineId not found in master db - "), - TIMESTAMP_NOT_VALID(StatusConstants.CMD_VALIDAOR_MODULE_FAILED + "016" ,"digital id timestamp is not within acctable time range of packet creation time"), - DEVICE_HOTLISTED(StatusConstants.CMD_VALIDAOR_MODULE_FAILED + "017" ,"Device has been hot listed"), - DEVICE_SIGNATURE_VALIDATION_FAILED(StatusConstants.CMD_VALIDAOR_MODULE_FAILED + "018", "DigitalId signature Validation Failed"), - CMD_LANGUAGE_NOT_SET(StatusConstants.CMD_VALIDAOR_MODULE_FAILED + "019", "Mandatory/Optional Language not set for CMD validation."), + VALIDATION_FAILED_EXCEPTION(StatusConstants.CMD_VALIDAOR_MODULE_FAILED + "014", + "Exception occured due to validation failure."), + MACHINE_ID_NOT_FOUND_MASTER_DB(StatusConstants.CMD_VALIDAOR_MODULE_FAILED + "015", + "MachineId not found in master db - "), + TIMESTAMP_NOT_VALID(StatusConstants.CMD_VALIDAOR_MODULE_FAILED + "016", + "digital id timestamp is not within acctable time range of packet creation time"), + DEVICE_HOTLISTED(StatusConstants.CMD_VALIDAOR_MODULE_FAILED + "017", "Device has been hot listed"), + DEVICE_SIGNATURE_VALIDATION_FAILED(StatusConstants.CMD_VALIDAOR_MODULE_FAILED + "018", + "DigitalId signature Validation Failed"), + CMD_LANGUAGE_NOT_SET(StatusConstants.CMD_VALIDAOR_MODULE_FAILED + "019", + "Mandatory/Optional Language not set for CMD validation."), // Operator Validator stage - OPERATOR_VALIDATION_SUCCESS(StatusConstants.OVM_VALIDAOR_MODULE_SUCCESS + "001", "OPERATOR Validation is Successful"), - OFFICER_NOT_ACTIVE(StatusConstants.OVM_VALIDAOR_MODULE_FAILED + "001","OfficerId is inActive"), - OPERATOR_PACKET_CREATION_DATE_NOT_FOUND_IN_PACKET(StatusConstants.OVM_VALIDAOR_MODULE_FAILED + "002","Packet Creation Date is NULL"), - OPERATOR_PASSWORD_OTP_FAILURE(StatusConstants.OVM_VALIDAOR_MODULE_FAILED + "003","Password or OTP Verification Failed for Officer - "), - OFFICER_WAS_INACTIVE(StatusConstants.OVM_VALIDAOR_MODULE_FAILED + "004","Officer was Not Active during Packet Creation - "), - OFFICER_NOT_FOUND_PACKET(StatusConstants.OVM_VALIDAOR_MODULE_FAILED + "005","Officer ID is NULL"), + OPERATOR_VALIDATION_SUCCESS(StatusConstants.OVM_VALIDAOR_MODULE_SUCCESS + "001", + "OPERATOR Validation is Successful"), + OFFICER_NOT_ACTIVE(StatusConstants.OVM_VALIDAOR_MODULE_FAILED + "001", "OfficerId is inActive"), + OPERATOR_PACKET_CREATION_DATE_NOT_FOUND_IN_PACKET(StatusConstants.OVM_VALIDAOR_MODULE_FAILED + "002", + "Packet Creation Date is NULL"), + OPERATOR_PASSWORD_OTP_FAILURE(StatusConstants.OVM_VALIDAOR_MODULE_FAILED + "003", + "Password or OTP Verification Failed for Officer - "), + OFFICER_WAS_INACTIVE(StatusConstants.OVM_VALIDAOR_MODULE_FAILED + "004", + "Officer was Not Active during Packet Creation - "), + OFFICER_NOT_FOUND_PACKET(StatusConstants.OVM_VALIDAOR_MODULE_FAILED + "005", "Officer ID is NULL"), // Supervisor Validator stage - SUPERVISOR_VALIDATION_SUCCESS(StatusConstants.SVM_VALIDAOR_MODULE_SUCCESS + "001", "SUPERVISOR Validation is Successful"), - SUPERVISOR_NOT_ACTIVE(StatusConstants.SVM_VALIDAOR_MODULE_FAILED + "001","SupervisorId is inActive"), - SUPERVISOR_PACKET_CREATION_DATE_NOT_FOUND_IN_PACKET(StatusConstants.SVM_VALIDAOR_MODULE_FAILED + "002","Packet Creation Date is NULL"), - SUPERVISOR_PASSWORD_OTP_FAILURE(StatusConstants.SVM_VALIDAOR_MODULE_FAILED + "003","Password or OTP Verification Failed for Officer - "), - SUPERVISOR_WAS_INACTIVE(StatusConstants.SVM_VALIDAOR_MODULE_FAILED + "004","Supervisor was Not Active during Packet Creation - "), - PASSWORD_OTP_FAILURE_SUPERVISOR(StatusConstants.SVM_VALIDAOR_MODULE_FAILED + "005","Password or OTP Verification Failed for Supervisor - "), - SUPERVISOR_NOT_FOUND_PACKET(StatusConstants.OVM_VALIDAOR_MODULE_FAILED + "006","Supervisor ID is NULL"), + SUPERVISOR_VALIDATION_SUCCESS(StatusConstants.SVM_VALIDAOR_MODULE_SUCCESS + "001", + "SUPERVISOR Validation is Successful"), + SUPERVISOR_NOT_ACTIVE(StatusConstants.SVM_VALIDAOR_MODULE_FAILED + "001", "SupervisorId is inActive"), + SUPERVISOR_PACKET_CREATION_DATE_NOT_FOUND_IN_PACKET(StatusConstants.SVM_VALIDAOR_MODULE_FAILED + "002", + "Packet Creation Date is NULL"), + SUPERVISOR_PASSWORD_OTP_FAILURE(StatusConstants.SVM_VALIDAOR_MODULE_FAILED + "003", + "Password or OTP Verification Failed for Officer - "), + SUPERVISOR_WAS_INACTIVE(StatusConstants.SVM_VALIDAOR_MODULE_FAILED + "004", + "Supervisor was Not Active during Packet Creation - "), + PASSWORD_OTP_FAILURE_SUPERVISOR(StatusConstants.SVM_VALIDAOR_MODULE_FAILED + "005", + "Password or OTP Verification Failed for Supervisor - "), + SUPERVISOR_NOT_FOUND_PACKET(StatusConstants.OVM_VALIDAOR_MODULE_FAILED + "006", "Supervisor ID is NULL"), // Introducer Validator stage - INTRODUCER_VALIDATION_SUCCESS(StatusConstants.IVM_VALIDAOR_MODULE_SUCCESS + "001", "INTRODUCER Validation is Successful"), - INTRODUCER_AUTHENTICATION_FAILED(StatusConstants.IVM_VALIDAOR_MODULE_FAILED + "001","INTRODUCER Biometric Authentication Failed - "), - UIN_RID_NOT_FOUND(StatusConstants.IVM_VALIDAOR_MODULE_FAILED + "002", "UIN or RID of Introducer Not Found in Packet"), - INTRODUCER_UIN_NOT_FOUND(StatusConstants.IVM_VALIDAOR_MODULE_FAILED + "003", "Introducer UIN not Found for the Given RID"), - INTRODUCER_BIOMETRIC_FILE_NAME_NOT_FOUND(StatusConstants.IVM_VALIDAOR_MODULE_FAILED + "004", "Introducer Biometric File Name Not Found"), - PACKET_ON_HOLD(StatusConstants.IVM_VALIDAOR_MODULE_FAILED + "005", "Packet On-Hold as Introducer packet is not processed yet."), - CHILD_PACKET_REJECTED(StatusConstants.IVM_VALIDAOR_MODULE_FAILED + "006", "Packet Rejected as Parent Packet is Rejected"), - PACKET_IS_ON_HOLD(StatusConstants.IVM_VALIDAOR_MODULE_FAILED + "007", "Packet is on Hold due to parent packet processing"), + INTRODUCER_VALIDATION_SUCCESS(StatusConstants.IVM_VALIDAOR_MODULE_SUCCESS + "001", + "INTRODUCER Validation is Successful"), + INTRODUCER_AUTHENTICATION_FAILED(StatusConstants.IVM_VALIDAOR_MODULE_FAILED + "001", + "INTRODUCER Biometric Authentication Failed - "), + UIN_RID_NOT_FOUND(StatusConstants.IVM_VALIDAOR_MODULE_FAILED + "002", + "UIN or RID of Introducer Not Found in Packet"), + INTRODUCER_UIN_NOT_FOUND(StatusConstants.IVM_VALIDAOR_MODULE_FAILED + "003", + "Introducer UIN not Found for the Given RID"), + INTRODUCER_BIOMETRIC_FILE_NAME_NOT_FOUND(StatusConstants.IVM_VALIDAOR_MODULE_FAILED + "004", + "Introducer Biometric File Name Not Found"), + PACKET_ON_HOLD(StatusConstants.IVM_VALIDAOR_MODULE_FAILED + "005", + "Packet On-Hold as Introducer packet is not processed yet."), + CHILD_PACKET_REJECTED(StatusConstants.IVM_VALIDAOR_MODULE_FAILED + "006", + "Packet Rejected as Parent Packet is Rejected"), + PACKET_IS_ON_HOLD(StatusConstants.IVM_VALIDAOR_MODULE_FAILED + "007", + "Packet is on Hold due to parent packet processing"), // printing stage PRINT_REQUEST_SUCCESS(StatusConstants.PRINT_STAGE_MODULE_SUCCESS + "001", "Print request submitted"), - PDF_ADDED_TO_QUEUE_FAILED(StatusConstants.PRINT_STAGE_MODULE_FAILED + "001","PDF was not added to Queue due to Queue Failure"), - PRINT_POST_COMPLETED(StatusConstants.PRINT_STAGE_MODULE_SUCCESS + "002","Printing and Post Completed"), - RESEND_UIN_CARD(StatusConstants.PRINT_STAGE_MODULE_SUCCESS + "003","Re-Sent UIN Card for Printing"), - PDF_GENERATION_FAILED(StatusConstants.PRINT_STAGE_MODULE_SUCCESS + "004","Pdf Generation failed for "), - TEMPLATE_PROCESSING_FAILED(StatusConstants.PRINT_STAGE_MODULE_SUCCESS + "005","Pdf Generation failed for "), - QUEUE_CONNECTION_NOT_FOUND(StatusConstants.PRINT_STAGE_MODULE_SUCCESS + "006","Queue Connection not found "), - QUEUE_CONNECTION_UNAVAILABLE(StatusConstants.PRINT_STAGE_MODULE_SUCCESS + "007","Queue Connection unavailable for "), + PDF_ADDED_TO_QUEUE_FAILED(StatusConstants.PRINT_STAGE_MODULE_FAILED + "001", + "PDF was not added to Queue due to Queue Failure"), + PRINT_POST_COMPLETED(StatusConstants.PRINT_STAGE_MODULE_SUCCESS + "002", "Printing and Post Completed"), + RESEND_UIN_CARD(StatusConstants.PRINT_STAGE_MODULE_SUCCESS + "003", "Re-Sent UIN Card for Printing"), + PDF_GENERATION_FAILED(StatusConstants.PRINT_STAGE_MODULE_SUCCESS + "004", "Pdf Generation failed for "), + TEMPLATE_PROCESSING_FAILED(StatusConstants.PRINT_STAGE_MODULE_SUCCESS + "005", "Pdf Generation failed for "), + QUEUE_CONNECTION_NOT_FOUND(StatusConstants.PRINT_STAGE_MODULE_SUCCESS + "006", "Queue Connection not found "), + QUEUE_CONNECTION_UNAVAILABLE(StatusConstants.PRINT_STAGE_MODULE_SUCCESS + "007", + "Queue Connection unavailable for "), PDF_SIGNTURED_FAILED(StatusConstants.PRINT_STAGE_MODULE_SUCCESS + "008", "Pdf Signature failed "), - PRINT_REQUEST_FAILED(StatusConstants.PRINT_STAGE_MODULE_FAILED + "009", - "Print request failed"), + PRINT_REQUEST_FAILED(StatusConstants.PRINT_STAGE_MODULE_FAILED + "009", "Print request failed"), UIN_NOT_FOUND_IN_DATABASE(StatusConstants.PRINT_STAGE_MODULE_FAILED + "010", "UIN not found in database"), /** The rpr prt vid exception. */ - VID_NOT_AVAILABLE(PlatformConstants.RPR_PRINTING_MODULE + "011", - "vid not available"), + VID_NOT_AVAILABLE(PlatformConstants.RPR_PRINTING_MODULE + "011", "vid not available"), // Abis middleware stage - INSERT_IDENTIFY_REQUEST_SUCCESS(StatusConstants.ABIS_MIDDLEWARE_MODULE_SUCCESS + "001","Insert or Identify Request sent to ABIS Queue is succesful"), - INSERT_IDENTIFY_REQUEST_FAILED(StatusConstants.ABIS_MIDDLEWARE_MODULE_FAILED + "001","Insert or Identify Request sent to ABIS Queue is Unsuccesful"), - INSERT_IDENTIFY_RESPONSE_SUCCESS(StatusConstants.ABIS_MIDDLEWARE_MODULE_SUCCESS + "002","Recived sucessful response from ABIS"), - INSERT_IDENTIFY_RESPONSE_FAILED(StatusConstants.ABIS_MIDDLEWARE_MODULE_SUCCESS + "002", "Received failed response from ABIS - "), + INSERT_IDENTIFY_REQUEST_SUCCESS(StatusConstants.ABIS_MIDDLEWARE_MODULE_SUCCESS + "001", + "Insert or Identify Request sent to ABIS Queue is succesful"), + INSERT_IDENTIFY_REQUEST_FAILED(StatusConstants.ABIS_MIDDLEWARE_MODULE_FAILED + "001", + "Insert or Identify Request sent to ABIS Queue is Unsuccesful"), + INSERT_IDENTIFY_RESPONSE_SUCCESS(StatusConstants.ABIS_MIDDLEWARE_MODULE_SUCCESS + "002", + "Recived sucessful response from ABIS"), + INSERT_IDENTIFY_RESPONSE_FAILED(StatusConstants.ABIS_MIDDLEWARE_MODULE_SUCCESS + "002", + "Received failed response from ABIS - "), // System Exceptions // Bio dedupe stage BIO_DEDUPE_INPROGRESS(StatusConstants.BIO_DEDUPE_MODULE_SUCCESS + "001", "Biometric Deduplication In-Progress"), - BIO_DEDUPE_SUCCESS(StatusConstants.BIO_DEDUPE_MODULE_SUCCESS + "002", "Biometric Deduplication is Successful"), - BIO_DEDUPE_POTENTIAL_MATCH(StatusConstants.BIO_DEDUPE_MODULE_FAILED + "001", "Potential Biometric Match Found while Processing Packet"), - LOST_PACKET_BIOMETRICS_NOT_FOUND(StatusConstants.BIO_DEDUPE_MODULE_FAILED + "002", "No Match was Found for the Biometrics Received"), - LOST_PACKET_UNIQUE_MATCH_FOUND(StatusConstants.BIO_DEDUPE_MODULE_SUCCESS + "003", "Unique Match was Found for the Biometrics Received"), - LOST_PACKET_MULTIPLE_MATCH_FOUND(StatusConstants.BIO_DEDUPE_MODULE_FAILED + "003", "Multiple Match was Found for the Biometrics Received"), + BIO_DEDUPE_SUCCESS(StatusConstants.BIO_DEDUPE_MODULE_SUCCESS + "002", "Biometric Deduplication is Successful"), + BIO_DEDUPE_POTENTIAL_MATCH(StatusConstants.BIO_DEDUPE_MODULE_FAILED + "001", + "Potential Biometric Match Found while Processing Packet"), + LOST_PACKET_BIOMETRICS_NOT_FOUND(StatusConstants.BIO_DEDUPE_MODULE_FAILED + "002", + "No Match was Found for the Biometrics Received"), + LOST_PACKET_UNIQUE_MATCH_FOUND(StatusConstants.BIO_DEDUPE_MODULE_SUCCESS + "003", + "Unique Match was Found for the Biometrics Received"), + LOST_PACKET_MULTIPLE_MATCH_FOUND(StatusConstants.BIO_DEDUPE_MODULE_FAILED + "003", + "Multiple Match was Found for the Biometrics Received"), // Biometric authentication stage - BIOMETRIC_AUTHENTICATION_FAILED(StatusConstants.BIO_METRIC_AUTHENTICATION_MODULE_FAILED + "001", "Biometric Authentication has Failed"), - BIOMETRIC_AUTHENTICATION_SUCCESS(StatusConstants.BIO_METRIC_AUTHENTICATION_MODULE_SUCCESS + "001", "Biometric Authentication is Successful"), + BIOMETRIC_AUTHENTICATION_FAILED(StatusConstants.BIO_METRIC_AUTHENTICATION_MODULE_FAILED + "001", + "Biometric Authentication has Failed"), + BIOMETRIC_AUTHENTICATION_SUCCESS(StatusConstants.BIO_METRIC_AUTHENTICATION_MODULE_SUCCESS + "001", + "Biometric Authentication is Successful"), BIOMETRIC_FILE_NOT_FOUND(StatusConstants.SYSTEM_EXCEPTION_CODE, "Biometric File Not Found"), - BIOMETRIC_AUTHENTICATION_FAILED_FILE_NOT_FOUND(StatusConstants.SYSTEM_EXCEPTION_CODE, "Biometric Authentication Failed File is not present inside identity json"), - INDIVIDUAL_BIOMETRIC_AUTHENTICATION_FAILED(StatusConstants.BIO_METRIC_AUTHENTICATION_MODULE_FAILED + "001","Individual authentication failed"), + BIOMETRIC_AUTHENTICATION_FAILED_FILE_NOT_FOUND(StatusConstants.SYSTEM_EXCEPTION_CODE, + "Biometric Authentication Failed File is not present inside identity json"), + INDIVIDUAL_BIOMETRIC_AUTHENTICATION_FAILED(StatusConstants.BIO_METRIC_AUTHENTICATION_MODULE_FAILED + "001", + "Individual authentication failed"), + BIOMETRIC_AUTHENTICATION_SKIPPED(StatusConstants.BIO_METRIC_AUTHENTICATION_MODULE_SUCCESS + "002", + "Biometric Authentication is Skipped "), // Demo dedupe stage DEMO_DEDUPE_SUCCESS(StatusConstants.DEMO_DEDUPE_MODULE_SUCCESS + "001", "Demo Dedupe is Successful"), - POTENTIAL_MATCH_FOUND_IN_ABIS(StatusConstants.DEMO_DEDUPE_MODULE_FAILED + "001","Biometric Duplicate was Found in ABIS"), - POTENTIAL_MATCH_FOUND(StatusConstants.DEMO_DEDUPE_MODULE_FAILED + "002","Potential Demo Match was Found"), + POTENTIAL_MATCH_FOUND_IN_ABIS(StatusConstants.DEMO_DEDUPE_MODULE_FAILED + "001", + "Biometric Duplicate was Found in ABIS"), + POTENTIAL_MATCH_FOUND(StatusConstants.DEMO_DEDUPE_MODULE_FAILED + "002", "Potential Demo Match was Found"), DEMO_DEDUPE_SKIPPED(StatusConstants.DEMO_DEDUPE_MODULE_SKIPPED + "003", "Demographic Deduplication Skipped"), - + // Manual verification stage - MANUAL_VERIFIER_APPROVED_PACKET(StatusConstants.MANUAL_VERIFICATION_MODULE_SUCCESS + "001", "Match Not Found by Manual Verifier"), - MANUAL_VERIFIER_REJECTED_PACKET(StatusConstants.MANUAL_VERIFICATION_MODULE_FAILED + "002", "Match Found by Manual Verifier"), - RPR_MANUAL_VERIFICATION_RESEND(StatusConstants.MANUAL_VERIFICATION_MODULE_FAILED + "003", "Error in manual verification"), - RPR_MANUAL_VERIFICATION_SENT_TO_QUEUE(PlatformConstants.RPR_MANUAL_ADJUDICATION_MODULE + "002", "Manual verification request sent to queue"), + MANUAL_VERIFIER_APPROVED_PACKET(StatusConstants.MANUAL_VERIFICATION_MODULE_SUCCESS + "001", + "Match Not Found by Manual Verifier"), + MANUAL_VERIFIER_REJECTED_PACKET(StatusConstants.MANUAL_VERIFICATION_MODULE_FAILED + "002", + "Match Found by Manual Verifier"), + RPR_MANUAL_VERIFICATION_RESEND(StatusConstants.MANUAL_VERIFICATION_MODULE_FAILED + "003", + "Error in manual verification"), + RPR_MANUAL_VERIFICATION_SENT_TO_QUEUE(PlatformConstants.RPR_MANUAL_ADJUDICATION_MODULE + "002", + "Manual verification request sent to queue"), // Uin generator stage - UIN_GENERATED_SUCCESS(StatusConstants.UIN_GENERATOR_MODULE_SUCCESS + "001","UIN Generated Successfully"), - UIN_DATA_UPDATION_SUCCESS(StatusConstants.UIN_GENERATOR_MODULE_SUCCESS + "002","UIN Data is drafted Successfully"), - UIN_ACTIVATED_SUCCESS(StatusConstants.UIN_GENERATOR_MODULE_SUCCESS + "003", "UIN is Activated"), + UIN_GENERATED_SUCCESS(StatusConstants.UIN_GENERATOR_MODULE_SUCCESS + "001", "UIN Generated Successfully"), + UIN_DATA_UPDATION_SUCCESS(StatusConstants.UIN_GENERATOR_MODULE_SUCCESS + "002", "UIN Data is drafted Successfully"), + UIN_ACTIVATED_SUCCESS(StatusConstants.UIN_GENERATOR_MODULE_SUCCESS + "003", "UIN is Activated"), UIN_DEACTIVATION_SUCCESS(StatusConstants.UIN_GENERATOR_MODULE_SUCCESS + "004", "UIN is Deactivated"), - LINK_RID_FOR_LOST_PACKET_SUCCESS(StatusConstants.UIN_GENERATOR_MODULE_SUCCESS + "005","RID linked Successfully for Lost UIN Packet"), + LINK_RID_FOR_LOST_PACKET_SUCCESS(StatusConstants.UIN_GENERATOR_MODULE_SUCCESS + "005", + "RID linked Successfully for Lost UIN Packet"), - UIN_ALREADY_ACTIVATED(StatusConstants.UIN_GENERATOR_MODULE_FAILED + "001","UIN is already Activated"), - UIN_ACTIVATED_FAILED(StatusConstants.UIN_GENERATOR_MODULE_FAILED + "002","UIN Activation Failed"), + UIN_ALREADY_ACTIVATED(StatusConstants.UIN_GENERATOR_MODULE_FAILED + "001", "UIN is already Activated"), + UIN_ACTIVATED_FAILED(StatusConstants.UIN_GENERATOR_MODULE_FAILED + "002", "UIN Activation Failed"), UIN_ALREADY_DEACTIVATED(StatusConstants.UIN_GENERATOR_MODULE_FAILED + "003", "UIN already deactivated"), - UIN_GENERATION_FAILED(StatusConstants.UIN_GENERATOR_MODULE_FAILED + "004","UIN Generation failed - "), - UIN_DATA_UPDATION_FAILED(StatusConstants.UIN_GENERATOR_MODULE_FAILED + "005", "UIN Updation failed - "), + UIN_GENERATION_FAILED(StatusConstants.UIN_GENERATOR_MODULE_FAILED + "004", "UIN Generation failed - "), + UIN_DATA_UPDATION_FAILED(StatusConstants.UIN_GENERATOR_MODULE_FAILED + "005", "UIN Updation failed - "), UIN_REACTIVATION_FAILED(StatusConstants.UIN_GENERATOR_MODULE_FAILED + "006", "UIN Reactivation failed - "), UIN_DEACTIVATION_FAILED(StatusConstants.UIN_GENERATOR_MODULE_FAILED + "007", "UIN Deactivation failed - "), - LINK_RID_FOR_LOST_PACKET_FAILED(StatusConstants.UIN_GENERATOR_MODULE_FAILED + "008","UIn not found the the matched RID"), - IDREPO_DRAFT_EXCEPTION(StatusConstants.UIN_GENERATOR_MODULE_FAILED + "008", "Exception occured updating idrepo draft."), - - //Biometric extraction stage - BIOMETRIC_EXTRACTION_SUCCESS(StatusConstants.BIOMETRIC_EXTRACTION_MODULE_SUCCESS + "001","biometric extaction was successful"), - BIOMETRIC_EXTRACTION_DRAFT_REQUEST_UNAVAILABLE(StatusConstants.BIOMETRIC_EXTRACTION_MODULE_FAILED + "001","Draft request is unavaialble in id-repo draft repository."), - - FINALIZATION_SUCCESS(StatusConstants.FINALIZATION_MODULE_SUCCESS + "001","idrepo draft was published successfuly"), - FINALIZATION_FAILURE(StatusConstants.FINALIZATION_MODULE_FAILED + "001","Draft request failed to publish."), - FINALIZATION_DRAFT_REQUEST_UNAVAILABLE(StatusConstants.FINALIZATION_MODULE_FAILED + "001","Draft request is unavaialble in id-repo draft repository."), - - //Request handler service - //1)Resident UIN update - RESIDENT_UPDATE_SUCCES(StatusConstants.REQUEST_HANDLER_MODULE_SUCCESS + "001" , "Resident Uin data updated sucessfully"), - RESIDENT_UPDATE_FAILED(StatusConstants.REQUEST_HANDLER_MODULE_FAILED + "001" , "Resident Uin update failed"), - INVALID_REQUEST(StatusConstants.REQUEST_HANDLER_MODULE_FAILED + "001" , "Invalid Request Value - "), - INVALID_CENTER(StatusConstants.REQUEST_HANDLER_MODULE_FAILED + "002" , "Invalid Request Value - "), - INVALID_MACHINE(StatusConstants.REQUEST_HANDLER_MODULE_FAILED + "003" , "Invalid Request Value - "), - - //2)PacketGeneration - PACKET_GENERATION_SUCCESS(StatusConstants.REQUEST_HANDLER_MODULE_SUCCESS + "001" , "Packet generated sucessfully"), - PACKET_GENERATION_FAILED(StatusConstants.REQUEST_HANDLER_MODULE_FAILED + "001" , "Packet generated failed"), - - //3)Uin card reprint - UIN_CARD_REPRINT_SUCCESS(StatusConstants.REQUEST_HANDLER_MODULE_SUCCESS + "001" , "UIN card reprint success"), - UIN_CARD_REPRINT_FAILED(StatusConstants.REQUEST_HANDLER_MODULE_FAILED + "001" , "UIN card reprint failed"), - + LINK_RID_FOR_LOST_PACKET_FAILED(StatusConstants.UIN_GENERATOR_MODULE_FAILED + "008", + "UIn not found the the matched RID"), + IDREPO_DRAFT_EXCEPTION(StatusConstants.UIN_GENERATOR_MODULE_FAILED + "008", + "Exception occured updating idrepo draft."), + + // Biometric extraction stage + BIOMETRIC_EXTRACTION_SUCCESS(StatusConstants.BIOMETRIC_EXTRACTION_MODULE_SUCCESS + "001", + "biometric extaction was successful"), + BIOMETRIC_EXTRACTION_DRAFT_REQUEST_UNAVAILABLE(StatusConstants.BIOMETRIC_EXTRACTION_MODULE_FAILED + "001", + "Draft request is unavaialble in id-repo draft repository."), + + FINALIZATION_SUCCESS(StatusConstants.FINALIZATION_MODULE_SUCCESS + "001", + "idrepo draft was published successfuly"), + FINALIZATION_FAILURE(StatusConstants.FINALIZATION_MODULE_FAILED + "001", "Draft request failed to publish."), + FINALIZATION_DRAFT_REQUEST_UNAVAILABLE(StatusConstants.FINALIZATION_MODULE_FAILED + "001", + "Draft request is unavaialble in id-repo draft repository."), + + // Request handler service + // 1)Resident UIN update + RESIDENT_UPDATE_SUCCES(StatusConstants.REQUEST_HANDLER_MODULE_SUCCESS + "001", + "Resident Uin data updated sucessfully"), + RESIDENT_UPDATE_FAILED(StatusConstants.REQUEST_HANDLER_MODULE_FAILED + "001", "Resident Uin update failed"), + INVALID_REQUEST(StatusConstants.REQUEST_HANDLER_MODULE_FAILED + "001", "Invalid Request Value - "), + INVALID_CENTER(StatusConstants.REQUEST_HANDLER_MODULE_FAILED + "002", "Invalid Request Value - "), + INVALID_MACHINE(StatusConstants.REQUEST_HANDLER_MODULE_FAILED + "003", "Invalid Request Value - "), + + // 2)PacketGeneration + PACKET_GENERATION_SUCCESS(StatusConstants.REQUEST_HANDLER_MODULE_SUCCESS + "001", "Packet generated sucessfully"), + PACKET_GENERATION_FAILED(StatusConstants.REQUEST_HANDLER_MODULE_FAILED + "001", "Packet generated failed"), + + // 3)Uin card reprint + UIN_CARD_REPRINT_SUCCESS(StatusConstants.REQUEST_HANDLER_MODULE_SUCCESS + "001", "UIN card reprint success"), + UIN_CARD_REPRINT_FAILED(StatusConstants.REQUEST_HANDLER_MODULE_FAILED + "001", "UIN card reprint failed"), // System Exceptions - VIRUS_SCANNER_SERVICE_NOT_ACCESSIBLE(StatusConstants.SYSTEM_EXCEPTION_CODE,"Virus Scanner Service is not accessible"), - DB_NOT_ACCESSIBLE(StatusConstants.SYSTEM_EXCEPTION_CODE,"Databse Not Accessible"), + VIRUS_SCANNER_SERVICE_NOT_ACCESSIBLE(StatusConstants.SYSTEM_EXCEPTION_CODE, + "Virus Scanner Service is not accessible"), + DB_NOT_ACCESSIBLE(StatusConstants.SYSTEM_EXCEPTION_CODE, "Databse Not Accessible"), PACKET_NOT_FOUND_PACKET_STORE(StatusConstants.SYSTEM_EXCEPTION_CODE, "Packet not found in File System"), - OBJECT_STORE_EXCEPTION(StatusConstants.SYSTEM_EXCEPTION_CODE,"Object store exception occured"), - JSCH_EXCEPTION_OCCURED(StatusConstants.SYSTEM_EXCEPTION_CODE,"JSCH Connection Exception Occurred"), - NGINX_ACCESS_EXCEPTION(StatusConstants.SYSTEM_EXCEPTION_CODE,"NGINX url is not accessible"), - IO_EXCEPTION(StatusConstants.SYSTEM_EXCEPTION_CODE,"IO Exception Occurred"), - BIO_METRIC_EXCEPTION(StatusConstants.SYSTEM_EXCEPTION_CODE,"Biometric Exception Occurred in IDA "), - BIO_METRIC_FILE_MISSING(StatusConstants.SYSTEM_EXCEPTION_CODE,"Applicant biometric fileName/file is missing"), - BIO_METRIC_TYPE_EXCEPTION(StatusConstants.SYSTEM_EXCEPTION_CODE,"Requested biometric type not found"), - - UNKNOWN_EXCEPTION_OCCURED(StatusConstants.SYSTEM_EXCEPTION_CODE,"Unknown exception occured "), - API_RESOUCE_ACCESS_FAILED(StatusConstants.SYSTEM_EXCEPTION_CODE,"Unable to access API resource"), - AUTH_SYSTEM_EXCEPTION(StatusConstants.SYSTEM_EXCEPTION_CODE,"Auth System Exception"), - JSON_PARSING_EXCEPTION(StatusConstants.SYSTEM_EXCEPTION_CODE,"Error Occurred while Parsing JSON"), - BASE_CHECKED_EXCEPTION(StatusConstants.SYSTEM_EXCEPTION_CODE,"Packet validation failed "), + OBJECT_STORE_EXCEPTION(StatusConstants.SYSTEM_EXCEPTION_CODE, "Object store exception occured"), + JSCH_EXCEPTION_OCCURED(StatusConstants.SYSTEM_EXCEPTION_CODE, "JSCH Connection Exception Occurred"), + NGINX_ACCESS_EXCEPTION(StatusConstants.SYSTEM_EXCEPTION_CODE, "NGINX url is not accessible"), + IO_EXCEPTION(StatusConstants.SYSTEM_EXCEPTION_CODE, "IO Exception Occurred"), + BIO_METRIC_EXCEPTION(StatusConstants.SYSTEM_EXCEPTION_CODE, "Biometric Exception Occurred in IDA "), + BIO_METRIC_FILE_MISSING(StatusConstants.SYSTEM_EXCEPTION_CODE, "Applicant biometric fileName/file is missing"), + BIO_METRIC_TYPE_EXCEPTION(StatusConstants.SYSTEM_EXCEPTION_CODE, "Requested biometric type not found"), + + UNKNOWN_EXCEPTION_OCCURED(StatusConstants.SYSTEM_EXCEPTION_CODE, "Unknown exception occured "), + API_RESOUCE_ACCESS_FAILED(StatusConstants.SYSTEM_EXCEPTION_CODE, "Unable to access API resource"), + AUTH_SYSTEM_EXCEPTION(StatusConstants.SYSTEM_EXCEPTION_CODE, "Auth System Exception"), + JSON_PARSING_EXCEPTION(StatusConstants.SYSTEM_EXCEPTION_CODE, "Error Occurred while Parsing JSON"), + BASE_CHECKED_EXCEPTION(StatusConstants.SYSTEM_EXCEPTION_CODE, "Packet validation failed "), BASE_UNCHECKED_EXCEPTION(StatusConstants.SYSTEM_EXCEPTION_CODE, "Packet validation failed "), - OFFICER_AUTHENTICATION_FAILED(StatusConstants.SYSTEM_EXCEPTION_CODE,"Officer Authentication Failed: "), - SUPERVISOR_AUTHENTICATION_FAILED(StatusConstants.SYSTEM_EXCEPTION_CODE,"Supervisor Authentication Failed: "), + OFFICER_AUTHENTICATION_FAILED(StatusConstants.SYSTEM_EXCEPTION_CODE, "Officer Authentication Failed: "), + SUPERVISOR_AUTHENTICATION_FAILED(StatusConstants.SYSTEM_EXCEPTION_CODE, "Supervisor Authentication Failed: "), - IDENTIFY_RESPONSE_FAILED(StatusConstants.SYSTEM_EXCEPTION_CODE,"Identify Response Failed for Request ID - "), - INSERT_RESPONSE_FAILED(StatusConstants.SYSTEM_EXCEPTION_CODE,"Insert Response Failed for Request ID - "), + IDENTIFY_RESPONSE_FAILED(StatusConstants.SYSTEM_EXCEPTION_CODE, "Identify Response Failed for Request ID - "), + INSERT_RESPONSE_FAILED(StatusConstants.SYSTEM_EXCEPTION_CODE, "Insert Response Failed for Request ID - "), SYSTEM_EXCEPTION_OCCURED(StatusConstants.SYSTEM_EXCEPTION_CODE, "Internal error occured - "), CBEF_NOT_FOUND(StatusConstants.SYSTEM_EXCEPTION_CODE, "Unable to Find Applicant CBEFF for Adult"), - IIEGAL_ARGUMENT_EXCEPTION(StatusConstants.SYSTEM_EXCEPTION_CODE,"Illegal Argument Exception Occurred - "), - DEMO_DEDUPE_FAILED_IN_ABIS(StatusConstants.SYSTEM_EXCEPTION_CODE,"Demo Dedupe Failed in ABIS"), - RE_PROCESS_FAILED(StatusConstants.RE_PROCESS_MODULE_FAILED + "001", "Reprocess count has exceeded the configured attempts"), + IIEGAL_ARGUMENT_EXCEPTION(StatusConstants.SYSTEM_EXCEPTION_CODE, "Illegal Argument Exception Occurred - "), + DEMO_DEDUPE_FAILED_IN_ABIS(StatusConstants.SYSTEM_EXCEPTION_CODE, "Demo Dedupe Failed in ABIS"), + RE_PROCESS_FAILED(StatusConstants.RE_PROCESS_MODULE_FAILED + "001", + "Reprocess count has exceeded the configured attempts"), RE_PROCESS_COMPLETED(StatusConstants.RE_PROCESS_MODULE_SUCCESS + "001", "Reprocess Completed"), // Message sender stage - NOTIFICATION_SUCESSFUL(StatusConstants.MESSAGE_SENDER_NOTIF_SUCCESS_CODE + "001","Notification Sent Successfully"), - TEMPLATE_CONFIGURATION_NOT_FOUND(StatusConstants.MESSAGE_SENDER__FAILED_CODE + "002","Template configuration and language not found"), - EMAIL_PHONE_TEMPLATE_NOTIFICATION_MISSING(StatusConstants.MESSAGE_SENDER__FAILED_CODE + "003","Email ID or Phone or Template or Notification Type is Missing"), - NOTIFICATION_FAILED_FOR_LOST(StatusConstants.MESSAGE_SENDER__FAILED_CODE + "004","Unable to Send Notification - UIN was not found for the Lost Packet"), - - MESSAGE_SENDER_NOTIF_SUCC(StatusConstants.MESSAGE_SENDER_NOTIF_SUCCESS_CODE + "001","Email and SMS Notification were sent"), - MESSAGE_SENDER_NOT_CONFIGURED(StatusConstants.MESSAGE_SENDER_NOTIF_SUCCESS_CODE + "002", "Notification was not sent as notification type was not set"), - MESSAGE_SENDER_EMAIL_SUCCESS(StatusConstants.MESSAGE_SENDER_NOTIF_SUCCESS_CODE + "003","Email Notification was sent"), - MESSAGE_SENDER_SMS_SUCCESS(StatusConstants.MESSAGE_SENDER_NOTIF_SUCCESS_CODE + "004","SMS Notification was sent"), - MESSAGE_SENDER_EMAIL_FAILED(StatusConstants.MESSAGE_SENDER__FAILED_CODE + "005","Notification was not sent as the required mode of channel was not available"), - MESSAGE_SENDER_SMS_FAILED(StatusConstants.MESSAGE_SENDER__FAILED_CODE + "006","Notification was not sent as the required mode of channel was not available"), - MESSAGE_SENDER_NOTIFICATION_FAILED(StatusConstants.MESSAGE_SENDER__FAILED_CODE + "006","Notification was not sent as the required mode of channel was not available"), + NOTIFICATION_SUCESSFUL(StatusConstants.MESSAGE_SENDER_NOTIF_SUCCESS_CODE + "001", "Notification Sent Successfully"), + TEMPLATE_CONFIGURATION_NOT_FOUND(StatusConstants.MESSAGE_SENDER__FAILED_CODE + "002", + "Template configuration and language not found"), + EMAIL_PHONE_TEMPLATE_NOTIFICATION_MISSING(StatusConstants.MESSAGE_SENDER__FAILED_CODE + "003", + "Email ID or Phone or Template or Notification Type is Missing"), + NOTIFICATION_FAILED_FOR_LOST(StatusConstants.MESSAGE_SENDER__FAILED_CODE + "004", + "Unable to Send Notification - UIN was not found for the Lost Packet"), + + MESSAGE_SENDER_NOTIF_SUCC(StatusConstants.MESSAGE_SENDER_NOTIF_SUCCESS_CODE + "001", + "Email and SMS Notification were sent"), + MESSAGE_SENDER_NOT_CONFIGURED(StatusConstants.MESSAGE_SENDER_NOTIF_SUCCESS_CODE + "002", + "Notification was not sent as notification type was not set"), + MESSAGE_SENDER_EMAIL_SUCCESS(StatusConstants.MESSAGE_SENDER_NOTIF_SUCCESS_CODE + "003", + "Email Notification was sent"), + MESSAGE_SENDER_SMS_SUCCESS(StatusConstants.MESSAGE_SENDER_NOTIF_SUCCESS_CODE + "004", "SMS Notification was sent"), + MESSAGE_SENDER_EMAIL_FAILED(StatusConstants.MESSAGE_SENDER__FAILED_CODE + "005", + "Notification was not sent as the required mode of channel was not available"), + MESSAGE_SENDER_SMS_FAILED(StatusConstants.MESSAGE_SENDER__FAILED_CODE + "006", + "Notification was not sent as the required mode of channel was not available"), + MESSAGE_SENDER_NOTIFICATION_FAILED(StatusConstants.MESSAGE_SENDER__FAILED_CODE + "006", + "Notification was not sent as the required mode of channel was not available"), VID_CREATION_FAILED(StatusConstants.UIN_GENERATOR_MODULE_FAILED + "009", "VID creation failed -"), WORKFLOW_INTERNAL_ACTION_SUCCESS(StatusConstants.WORKFLOW_INTERNAL_ACTION + "001", @@ -254,13 +346,14 @@ public enum StatusUtil { WORKFLOW_ACTION_SERVICE_SUCCESS(StatusConstants.WORKFLOW_ACTION_SERVICE + "001", "Packet workflow resume successfully"), - MANUAL_ADJUDICATION_FAILED(PlatformConstants.RPR_MANUAL_ADJUDICATION_MODULE + "000", "manual verification failed -"), + MANUAL_ADJUDICATION_FAILED(PlatformConstants.RPR_MANUAL_ADJUDICATION_MODULE + "000", + "manual verification failed -"), MANUAL_ADJUDICATION_RID_SHOULD_NOT_EMPTY_OR_NULL(PlatformConstants.RPR_MANUAL_ADJUDICATION_MODULE + "001", "Registration Id should not empty or null "), MANUAL_ADJUDICATION_MATCHEDRID_FOUND_FOR_GIVEN_RID(PlatformConstants.RPR_MANUAL_ADJUDICATION_MODULE + "002", "No matched reference id found for given RID"), VERIFICATION_SUCCESS(StatusConstants.VERIFICATION_STAGE + "001", "Verification success"), - VERIFICATION_FAILED(StatusConstants.VERIFICATION_STAGE + "002","Verification failed"), + VERIFICATION_FAILED(StatusConstants.VERIFICATION_STAGE + "002", "Verification failed"), VERIFICATION_SENT(StatusConstants.VERIFICATION_STAGE + "003", "Sent for verification"), VERIFICATION_RESEND(StatusConstants.VERIFICATION_STAGE + "004", "Resend for verification"); diff --git a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/util/JsonUtil.java b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/util/JsonUtil.java index 13a41cb1187..3599559b3f7 100644 --- a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/util/JsonUtil.java +++ b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/util/JsonUtil.java @@ -9,7 +9,6 @@ import java.util.ArrayList; import java.util.LinkedHashMap; -import com.fasterxml.jackson.module.afterburner.AfterburnerModule; import org.json.simple.JSONArray; import org.json.simple.JSONObject; @@ -17,12 +16,9 @@ import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; -import com.google.gson.Gson; -import com.google.gson.JsonIOException; -import com.google.gson.JsonObject; -import com.google.gson.JsonParser; -import com.google.gson.JsonSyntaxException; +import com.fasterxml.jackson.module.afterburner.AfterburnerModule; import io.mosip.registration.processor.core.exception.util.PlatformErrorMessages; import io.mosip.registration.processor.core.packet.dto.demographicinfo.JsonValue; @@ -56,6 +52,7 @@ private static ObjectMapper getObjectMapper() { if (objectMapper == null) { objectMapper = new ObjectMapper().registerModule(new AfterburnerModule()).registerModule(new JavaTimeModule()); objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); + objectMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS); } return objectMapper; } @@ -77,11 +74,10 @@ private static ObjectMapper getObjectMapper() { */ public static Object inputStreamtoJavaObject(InputStream stream, Class clazz) throws UnsupportedEncodingException { - JsonParser jsonParser = new JsonParser(); - Gson gson = new Gson(); - JsonObject jsonObject = (JsonObject) jsonParser.parse(new InputStreamReader(stream, "UTF-8")); + + getObjectMapper(); try { - return gson.fromJson(jsonObject, clazz); + return objectMapper.readValue(new InputStreamReader(stream, "UTF-8"), clazz); } catch (Exception e) { throw new UnsupportedEncodingException(PlatformErrorMessages.RPR_CMB_UNSUPPORTED_ENCODING.getMessage()); } diff --git a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/util/ServerUtil.java b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/util/ServerUtil.java index feac469082b..d74a4a0f75d 100644 --- a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/util/ServerUtil.java +++ b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/util/ServerUtil.java @@ -5,7 +5,6 @@ import io.mosip.registration.processor.core.logger.RegProcessorLogger; import io.mosip.kernel.core.logger.spi.Logger; - /** * This class provides Server IP and Name. * diff --git a/registration-processor/registration-processor-info-storage-service/pom.xml b/registration-processor/registration-processor-info-storage-service/pom.xml index 81de5a580ad..abae39f1150 100644 --- a/registration-processor/registration-processor-info-storage-service/pom.xml +++ b/registration-processor/registration-processor-info-storage-service/pom.xml @@ -1,143 +1,143 @@ - - - 4.0.0 - - io.mosip.registrationprocessor - registration-processor - 1.2.0.1-B1 - - registration-processor-info-storage-service - 1.2.0.1-B1 - registration-processor-info-storage-service - - UTF-8 - - - - - org.mockito - mockito-core - ${mockito.version} - test - - - - - - org.springframework.cloud - spring-cloud-starter-config - ${spring-cloud-config.version} - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-test - - - org.springframework.boot - spring-boot-starter-data-jpa - - - org.postgresql - postgresql - - - io.springfox - springfox-swagger-ui - ${swagger.version} - - - io.springfox - springfox-swagger2 - ${swagger.version} - - - junit - junit - test - - - com.h2database - h2 - - - io.mosip.kernel - kernel-dataaccess-hibernate - ${kernel.dataaccess.hibernate.version} - - - io.mosip.kernel - kernel-keymanager-service - ${kernel-keymanager-service.version} - - - org.springframework.security - spring-security-config - - - lib - - - io.mosip.kernel - kernel-core - ${kernel.core.version} - - - io.mosip.registrationprocessor - registration-processor-core - ${registration.processor.core.version} - - - io.mosip.registrationprocessor - registration-processor-registration-status-service-impl - ${registration.status.service.version} - - - io.mosip.registrationprocessor - registration-processor-rest-client - ${registration.processor.rest.client.version} - - - commons-codec - commons-codec - - - - com.googlecode.json-simple - json-simple - - - org.projectlombok - lombok - compile - - - org.powermock - powermock-module-junit4 - ${powermock.module.junit4.version} - test - - - org.powermock - powermock-api-mockito2 - ${powermock.api.mockito.version} - test - - - io.mosip.registrationprocessor - registration-processor-packet-manager - ${packet.manager.version} - - - io.mosip.kernel - kernel-biosdk-provider - ${kernel-biosdk-provider.version} - - - + + + 4.0.0 + + io.mosip.registrationprocessor + registration-processor + 1.2.0.1-B3-SNAPSHOT + + registration-processor-info-storage-service + 1.2.0.1-B3-SNAPSHOT + registration-processor-info-storage-service + + UTF-8 + + + + + org.mockito + mockito-core + ${mockito.version} + test + + + + + + org.springframework.cloud + spring-cloud-starter-config + ${spring-cloud-config.version} + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-test + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.postgresql + postgresql + + + io.springfox + springfox-swagger-ui + ${swagger.version} + + + io.springfox + springfox-swagger2 + ${swagger.version} + + + junit + junit + test + + + com.h2database + h2 + + + io.mosip.kernel + kernel-dataaccess-hibernate + ${kernel.dataaccess.hibernate.version} + + + io.mosip.kernel + kernel-keymanager-service + ${kernel-keymanager-service.version} + + + org.springframework.security + spring-security-config + + + lib + + + io.mosip.kernel + kernel-core + ${kernel.core.version} + + + io.mosip.registrationprocessor + registration-processor-core + ${registration.processor.core.version} + + + io.mosip.registrationprocessor + registration-processor-registration-status-service-impl + ${registration.status.service.version} + + + io.mosip.registrationprocessor + registration-processor-rest-client + ${registration.processor.rest.client.version} + + + commons-codec + commons-codec + + + + com.googlecode.json-simple + json-simple + + + org.projectlombok + lombok + compile + + + org.powermock + powermock-module-junit4 + ${powermock.module.junit4.version} + test + + + org.powermock + powermock-api-mockito2 + ${powermock.api.mockito.version} + test + + + io.mosip.registrationprocessor + registration-processor-packet-manager + ${packet.manager.version} + + + io.mosip.kernel + kernel-biosdk-provider + ${kernel-biosdk-provider.version} + + + diff --git a/registration-processor/registration-processor-info-storage-service/src/main/java/io/mosip/registration/processor/packet/storage/config/PacketStorageBeanConfig.java b/registration-processor/registration-processor-info-storage-service/src/main/java/io/mosip/registration/processor/packet/storage/config/PacketStorageBeanConfig.java index 0e16aa5eec5..7e8cf408d72 100644 --- a/registration-processor/registration-processor-info-storage-service/src/main/java/io/mosip/registration/processor/packet/storage/config/PacketStorageBeanConfig.java +++ b/registration-processor/registration-processor-info-storage-service/src/main/java/io/mosip/registration/processor/packet/storage/config/PacketStorageBeanConfig.java @@ -11,6 +11,8 @@ import io.mosip.registration.processor.packet.storage.helper.PacketManagerHelper; import io.mosip.registration.processor.packet.storage.utils.PacketManagerService; import io.mosip.registration.processor.packet.storage.utils.PriorityBasedPacketManagerService; + +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; @@ -33,7 +35,7 @@ import io.mosip.registration.processor.packet.storage.dto.ApplicantInfoDto; import io.mosip.registration.processor.packet.storage.service.impl.PacketInfoManagerImpl; import io.mosip.registration.processor.packet.storage.utils.ABISHandlerUtil; -import io.mosip.registration.processor.packet.storage.utils.AuthUtil; +import io.mosip.registration.processor.packet.storage.utils.BioSdkUtil; import io.mosip.registration.processor.packet.storage.utils.IdSchemaUtil; import io.mosip.registration.processor.packet.storage.utils.Utilities; @@ -93,10 +95,12 @@ public ABISHandlerUtil getABISHandlerUtil() { return new ABISHandlerUtil(); } + @Bean - public AuthUtil getAuthUtil() { - return new AuthUtil(); + public BioSdkUtil getBioSdkUtil() { + return new BioSdkUtil(); } + @Bean public KeyGenerator getKeyGenerator() { diff --git a/registration-processor/registration-processor-info-storage-service/src/main/java/io/mosip/registration/processor/packet/storage/dao/PacketInfoDao.java b/registration-processor/registration-processor-info-storage-service/src/main/java/io/mosip/registration/processor/packet/storage/dao/PacketInfoDao.java index 6863915df08..af857405162 100644 --- a/registration-processor/registration-processor-info-storage-service/src/main/java/io/mosip/registration/processor/packet/storage/dao/PacketInfoDao.java +++ b/registration-processor/registration-processor-info-storage-service/src/main/java/io/mosip/registration/processor/packet/storage/dao/PacketInfoDao.java @@ -581,7 +581,7 @@ public List getAbisProcessedRequestsAppCodeByBioRefId(String bioRefId, S * the status code * @return the processed or processing reg ids */ - public List getProcessedOrProcessingRegIds(List matchedRegIds, String statusCode) { + public List getProcessedOrProcessingRegIds(List matchedRegIds, List statusCode) { return registrationRepositary.getProcessedOrProcessingRegIds(matchedRegIds, statusCode); } diff --git a/registration-processor/registration-processor-info-storage-service/src/main/java/io/mosip/registration/processor/packet/storage/utils/ABISHandlerUtil.java b/registration-processor/registration-processor-info-storage-service/src/main/java/io/mosip/registration/processor/packet/storage/utils/ABISHandlerUtil.java index f80df6eba9b..d6ad7833d50 100644 --- a/registration-processor/registration-processor-info-storage-service/src/main/java/io/mosip/registration/processor/packet/storage/utils/ABISHandlerUtil.java +++ b/registration-processor/registration-processor-info-storage-service/src/main/java/io/mosip/registration/processor/packet/storage/utils/ABISHandlerUtil.java @@ -101,8 +101,11 @@ public Set getUniqueRegIds(String registrationId, String registrationTyp if (!CollectionUtils.isEmpty(matchedRegIds)) { List processingRegIds = packetInfoDao.getWithoutStatusCodes(matchedRegIds, RegistrationTransactionStatusCode.REJECTED.toString(), RegistrationTransactionStatusCode.PROCESSED.toString()); + List statusList=new ArrayList<>(); + statusList.add(RegistrationTransactionStatusCode.PROCESSED.toString()); + statusList.add(RegistrationTransactionStatusCode.PROCESSING.toString()); List processedRegIds = packetInfoDao.getProcessedOrProcessingRegIds(matchedRegIds, - RegistrationTransactionStatusCode.PROCESSED.toString()); + statusList); uniqueRIDs = getUniqueRegIds(processedRegIds, registrationId, registrationType, stageName); uniqueRIDs.addAll(processingRegIds); } diff --git a/registration-processor/registration-processor-info-storage-service/src/main/java/io/mosip/registration/processor/packet/storage/utils/AuthUtil.java b/registration-processor/registration-processor-info-storage-service/src/main/java/io/mosip/registration/processor/packet/storage/utils/AuthUtil.java index 0e2efcd8f35..e69de29bb2d 100644 --- a/registration-processor/registration-processor-info-storage-service/src/main/java/io/mosip/registration/processor/packet/storage/utils/AuthUtil.java +++ b/registration-processor/registration-processor-info-storage-service/src/main/java/io/mosip/registration/processor/packet/storage/utils/AuthUtil.java @@ -1,494 +0,0 @@ -package io.mosip.registration.processor.packet.storage.utils; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.security.NoSuchAlgorithmException; -import java.security.PrivateKey; -import java.security.PublicKey; -import java.security.cert.CertificateException; -import java.security.cert.CertificateFactory; -import java.security.cert.X509Certificate; -import java.time.LocalDateTime; -import java.time.format.DateTimeFormatter; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.Map.Entry; -import java.util.stream.Collectors; -import java.util.stream.IntStream; - -import javax.crypto.SecretKey; - -import org.apache.commons.codec.binary.Base64; -import org.apache.commons.codec.digest.DigestUtils; -import org.apache.commons.lang.StringUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.core.env.Environment; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpMethod; -import org.springframework.http.ResponseEntity; -import org.springframework.util.CollectionUtils; -import org.springframework.web.client.RestTemplate; - -import com.fasterxml.jackson.databind.ObjectMapper; - -import io.mosip.kernel.biometrics.constant.BiometricFunction; -import io.mosip.kernel.biometrics.constant.BiometricType; -import io.mosip.kernel.biometrics.entities.BIR; -import io.mosip.kernel.biosdk.provider.factory.BioAPIFactory; -import io.mosip.kernel.biosdk.provider.spi.iBioProviderApi; -import io.mosip.kernel.core.crypto.spi.CryptoCoreSpec; -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.HMACUtils2; -import io.mosip.kernel.keygenerator.bouncycastle.KeyGenerator; -import io.mosip.registration.processor.core.auth.dto.AuthRequestDTO; -import io.mosip.registration.processor.core.auth.dto.AuthResponseDTO; -import io.mosip.registration.processor.core.auth.dto.AuthTypeDTO; -import io.mosip.registration.processor.core.auth.dto.BioInfo; -import io.mosip.registration.processor.core.auth.dto.CertificateResponseDto; -import io.mosip.registration.processor.core.auth.dto.DataInfoDTO; -import io.mosip.registration.processor.core.auth.dto.RequestDTO; -import io.mosip.registration.processor.core.code.ApiName; -import io.mosip.registration.processor.core.code.BioType; -import io.mosip.registration.processor.core.constant.JsonConstant; -import io.mosip.registration.processor.core.constant.LoggerFileConstant; -import io.mosip.registration.processor.core.exception.ApisResourceAccessException; -import io.mosip.registration.processor.core.exception.BioTypeException; -import io.mosip.registration.processor.core.exception.util.PlatformErrorMessages; -import io.mosip.registration.processor.core.http.RequestWrapper; -import io.mosip.registration.processor.core.http.ResponseWrapper; -import io.mosip.registration.processor.core.logger.RegProcessorLogger; -import io.mosip.registration.processor.core.spi.restclient.RegistrationProcessorRestClientService; -import io.mosip.registration.processor.core.util.JsonUtil; -import io.mosip.registration.processor.packet.manager.dto.CryptomanagerResponseDto; -import io.mosip.registration.processor.packet.storage.dto.CryptoManagerEncryptDto; -import io.mosip.registration.processor.rest.client.utils.RestApiClient; - -/** - * @author Ranjitha Siddegowda - * - */ -public class AuthUtil { - - /** The reg proc logger. */ - private static Logger regProcLogger = RegProcessorLogger.getLogger(AuthUtil.class); - private static final String AUTHORIZATION = "Authorization="; - - /** The key generator. */ - @Autowired - private KeyGenerator keyGenerator; - - @Autowired - private ObjectMapper mapper; - - /** The encryptor. */ - @Autowired - private CryptoCoreSpec encryptor; - - /** The registration processor rest client service. */ - @Autowired - RegistrationProcessorRestClientService registrationProcessorRestClientService; - - /** The Constant APPLICATION_ID. */ - public static final String IDA_APP_ID = "IDA"; - - /** The Constant RSA. */ - public static final String RSA = "RSA"; - - @Autowired - private RestApiClient restApiClient; - - /** The Constant RSA. */ - public static final String PARTNER_ID = "INTERNAL"; - - @Value("${mosip.identity.auth.internal.requestid}") - private String authRequestId; - - @Value("${mosip.identity.auth.internal.env}") - private String authEnv; - - @Value("${registration.processor.application.id}") - private String applicationId; - - @Value("${mosipbox.public.url:null}") - private String domainUrl; - - @Value("${auth.PrependThumbprint.enable:false}") - private boolean isPrependThumbprintEnabled; - - @Autowired - private Environment env; - - @Autowired - @Qualifier("selfTokenRestTemplate") - RestTemplate restTemplate; - - /** The bio api factory. */ - @Autowired(required = false) - private BioAPIFactory bioApiFactory; - - private static final String DATETIME_PATTERN = "mosip.registration.processor.datetime.pattern"; - private static final String VERSION = "1.0"; - private static final String DUMMY_TRANSACTION_ID = "1234567890"; - private static final String FACE = "FACE"; - private static final String KERNEL_KEY_SPLITTER = "mosip.kernel.data-key-splitter"; - - public AuthResponseDTO authByIdAuthentication(String individualId, String individualType, List list) - throws ApisResourceAccessException, IOException, BioTypeException, CertificateException, NoSuchAlgorithmException { - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), individualId, - "AuthUtil::authByIdAuthentication()::entry"); - - AuthRequestDTO authRequestDTO = new AuthRequestDTO(); - authRequestDTO.setId(authRequestId); - authRequestDTO.setVersion(VERSION); - DateTimeFormatter format = DateTimeFormatter.ofPattern(env.getProperty(DATETIME_PATTERN)); - LocalDateTime localdatetime = LocalDateTime - .parse(DateUtils.getUTCCurrentDateTimeString(env.getProperty(DATETIME_PATTERN)), format); - authRequestDTO.setRequestTime(DateUtils.formatToISOString(localdatetime)); - authRequestDTO.setTransactionID(DUMMY_TRANSACTION_ID); - authRequestDTO.setEnv(authEnv); - authRequestDTO.setDomainUri(domainUrl); - - String thumbprint = CryptoUtil.encodeToURLSafeBase64(getCertificateThumbprint(getCertificate(PARTNER_ID))); - authRequestDTO.setThumbprint(thumbprint); - - AuthTypeDTO authType = new AuthTypeDTO(); - authType.setBio(Boolean.TRUE); - authRequestDTO.setRequestedAuth(authType); - - authRequestDTO.setConsentObtained(true); - authRequestDTO.setIndividualId(individualId); - authRequestDTO.setIndividualIdType(individualType); - List biometrics; - biometrics = getBiometricsList(list, thumbprint); - RequestDTO request = new RequestDTO(); - request.setBiometrics(biometrics); - request.setTimestamp(DateUtils.formatToISOString(localdatetime)); - String identityBlock = mapper.writeValueAsString(request); - - final SecretKey secretKey = keyGenerator.getSymmetricKey(); - // Encrypted request with session key - byte[] encryptedIdentityBlock = encryptor.symmetricEncrypt(secretKey, identityBlock.getBytes(), null); - // rbase64 encoded for request - authRequestDTO.setRequest(CryptoUtil.encodeToURLSafeBase64(encryptedIdentityBlock)); - // encrypted with MOSIP public key and encoded session key - byte[] encryptedSessionKeyByte = encryptRSA(secretKey.getEncoded(), PARTNER_ID, mapper); - authRequestDTO.setRequestSessionKey(CryptoUtil.encodeToURLSafeBase64(encryptedSessionKeyByte)); - // sha256 of the request block before encryption and the hash is encrypted - // using the requestSessionKey - byte[] byteArray = encryptor.symmetricEncrypt(secretKey, - HMACUtils2.digestAsPlainText(identityBlock.getBytes()).getBytes(), null); - authRequestDTO.setRequestHMAC(CryptoUtil.encodeToURLSafeBase64(byteArray)); - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), individualId, - "AuthUtil::authByIdAuthentication()::INTERNALAUTH POST service call started"); - - HttpHeaders headers = new HttpHeaders(); - String token = restApiClient.getToken().replace(AUTHORIZATION, ""); - headers.add("cookie", restApiClient.getToken()); - headers.add("Authorization", token); - - HttpEntity httpEntity = new HttpEntity<>(authRequestDTO, headers); - - ResponseEntity responseEntity = restTemplate.exchange(env.getProperty(ApiName.INTERNALAUTH.name()), HttpMethod.POST, httpEntity, AuthResponseDTO.class); - AuthResponseDTO response = responseEntity.getBody(); - - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), null, - "AuthUtil::authByIdAuthentication():: Response from INTERNALAUTH : " - + JsonUtil.objectMapperObjectToJson(response)); - - return response; - - } - - private byte[] encryptRSA(final byte[] sessionKey, String refId, ObjectMapper mapper) - throws ApisResourceAccessException, IOException, CertificateException { - - // encrypt AES Session Key using RSA public key - ResponseWrapper responseWrapper; - CertificateResponseDto certificateResponseDto; - - responseWrapper = (ResponseWrapper) registrationProcessorRestClientService.getApi(ApiName.IDAUTHCERTIFICATE, - null, "applicationId,referenceId", IDA_APP_ID + ',' + refId, ResponseWrapper.class); - certificateResponseDto = mapper.readValue(mapper.writeValueAsString(responseWrapper.getResponse()), - CertificateResponseDto.class); - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), refId, - "AuthUtil::encryptRSA():: ENCRYPTIONSERVICE GET service call ended with response data " - + JsonUtil.objectMapperObjectToJson(responseWrapper)); - - if (responseWrapper.getErrors() != null && responseWrapper.getErrors().size() > 0) - throw new IOException(responseWrapper.getErrors().get(0).getMessage()); - - String certificate = trimBeginEnd(certificateResponseDto.getCertificate()); - - CertificateFactory cf = CertificateFactory.getInstance("X.509"); - X509Certificate x509cert = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(java.util.Base64.getDecoder().decode(certificate))); - PublicKey publicKey = x509cert.getPublicKey(); - - return encryptor.asymmetricEncrypt(publicKey, sessionKey); - - } - - private List getBiometricsList(List list, String thumbprint) - throws BioTypeException, NoSuchAlgorithmException { - - String previousHash = HMACUtils2.digestAsPlainText("".getBytes()); - List biometrics = new ArrayList<>(); - try { - for (io.mosip.kernel.biometrics.entities.BIR bir : list) { - if(isExceptionBIR(bir)) - continue; - BioInfo bioInfo = new BioInfo(); - DataInfoDTO dataInfoDTO = new DataInfoDTO(); - dataInfoDTO.setEnv(authEnv); - dataInfoDTO.setDomainUri(domainUrl); - dataInfoDTO.setTransactionId(DUMMY_TRANSACTION_ID); - List birList = List.of(bir); - List birApiResponseList = extractTemplates(birList, new HashMap()); - BIR birApiResponse = birApiResponseList.get(0); - dataInfoDTO.setBioType(birApiResponse.getBdbInfo().getType().get(0).toString()); - List bioSubType = birApiResponse.getBdbInfo().getSubtype(); - // converting list to string - String bioSubTypeValue = StringUtils.join(bioSubType, " "); - if (dataInfoDTO.getBioType().equals(BioType.FACE.name())) - dataInfoDTO.setBioSubType(FACE); - else - dataInfoDTO.setBioSubType(bioSubTypeValue); - DateTimeFormatter format = DateTimeFormatter.ofPattern(env.getProperty(DATETIME_PATTERN)); - LocalDateTime localdatetime = LocalDateTime - .parse(DateUtils.getUTCCurrentDateTimeString(env.getProperty(DATETIME_PATTERN)), format); - String timeStamp = DateUtils.formatToISOString(localdatetime); - SplittedEncryptedData splittedEncryptData = getSessionKey(timeStamp, birApiResponse.getBdb()); - dataInfoDTO.setBioValue(splittedEncryptData.getEncryptedData()); - dataInfoDTO.setTimestamp(timeStamp); - String encodedData = CryptoUtil - .encodeToURLSafeBase64(JsonUtil.objectMapperObjectToJson(dataInfoDTO).getBytes()); - bioInfo.setData(encodedData); - String presentHash = HMACUtils2.digestAsPlainText(JsonUtil.objectMapperObjectToJson(dataInfoDTO).getBytes()); - StringBuilder concatenatedHash = new StringBuilder(); - concatenatedHash.append(previousHash); - concatenatedHash.append(presentHash); - // String concatenatedHash = previousHash + presentHash; - String finalHash = HMACUtils2 - .digestAsPlainText((concatenatedHash.toString().getBytes())); - bioInfo.setHash(finalHash); - bioInfo.setSessionKey(splittedEncryptData.getEncryptedSessionKey()); - bioInfo.setThumbprint(thumbprint); - biometrics.add(bioInfo); - previousHash = finalHash; - } - - return biometrics; - - } catch (Exception e) { - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - "", PlatformErrorMessages.OSI_VALIDATION_BIO_TYPE_EXCEPTION.getMessage() + "-" + e.getMessage()); - throw new BioTypeException( - PlatformErrorMessages.OSI_VALIDATION_BIO_TYPE_EXCEPTION.getMessage() + "-" + e.getMessage()); - - } - } - - private boolean isExceptionBIR(io.mosip.kernel.biometrics.entities.BIR bir) { - if(bir.getOthers() != null) { - Optional> entry = bir.getOthers().entrySet().stream().filter( - it -> it.getKey().equals(JsonConstant.BIOMETRICRECORDEXCEPTION)).findAny(); - if(entry.isPresent() && entry.get().getValue().equals("true")) - return true; - } - return false; - } - - public static class SplittedEncryptedData { - private String encryptedSessionKey; - private String encryptedData; - - public SplittedEncryptedData() { - super(); - } - - public SplittedEncryptedData(String encryptedSessionKey, String encryptedData) { - super(); - this.encryptedData = encryptedData; - this.encryptedSessionKey = encryptedSessionKey; - } - - public String getEncryptedData() { - return encryptedData; - } - - public void setEncryptedData(String encryptedData) { - this.encryptedData = encryptedData; - } - - public String getEncryptedSessionKey() { - return encryptedSessionKey; - } - - public void setEncryptedSessionKey(String encryptedSessionKey) { - this.encryptedSessionKey = encryptedSessionKey; - } - } - - private SplittedEncryptedData getSessionKey(String timeStamp, byte[] data) throws ApisResourceAccessException { - SplittedEncryptedData splittedData = null; - byte[] xorBytes = BytesUtil.getXOR(timeStamp, DUMMY_TRANSACTION_ID); - byte[] saltLastBytes = BytesUtil.getLastBytes(xorBytes, 12); - String salt = CryptoUtil.encodeToURLSafeBase64(saltLastBytes); - byte[] aadLastBytes = BytesUtil.getLastBytes(xorBytes, 16); - String aad = CryptoUtil.encodeToURLSafeBase64(aadLastBytes); - CryptoManagerEncryptDto encryptDto = new CryptoManagerEncryptDto(); - RequestWrapper request = new RequestWrapper<>(); - encryptDto.setAad(aad); - encryptDto.setApplicationId(IDA_APP_ID); - encryptDto.setReferenceId(PARTNER_ID); - encryptDto.setSalt(salt); - encryptDto.setTimeStamp(timeStamp); - encryptDto.setData(CryptoUtil.encodeToURLSafeBase64(data)); - encryptDto.setPrependThumbprint(isPrependThumbprintEnabled); - - request.setId(authRequestId); - DateTimeFormatter format = DateTimeFormatter.ofPattern(env.getProperty(DATETIME_PATTERN)); - LocalDateTime localdatetime = LocalDateTime - .parse(DateUtils.getUTCCurrentDateTimeString(env.getProperty(DATETIME_PATTERN)), format); - request.setRequesttime(localdatetime); - request.setRequest(encryptDto); - request.setVersion(VERSION); - try { - - CryptomanagerResponseDto response = (CryptomanagerResponseDto) registrationProcessorRestClientService - .postApi(ApiName.IDAUTHENCRYPTION, "", "", request, CryptomanagerResponseDto.class); - - if (!CollectionUtils.isEmpty(response.getErrors())) { - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.name(), null, - response.getErrors().get(0).getErrorCode() + " ==> " + response.getErrors().get(0).getMessage()); - throw new ApisResourceAccessException(response.getErrors().get(0).getErrorCode() + " ==> " + response.getErrors().get(0).getMessage()); - } - splittedData = splitEncryptedData((String) response.getResponse().getData()); - - } catch (ApisResourceAccessException e) { - throw e; - } - return splittedData; - - } - - public SplittedEncryptedData splitEncryptedData(String data) { - byte[] dataBytes =null; - try { - dataBytes= CryptoUtil.decodeURLSafeBase64(data); - } catch (IllegalArgumentException exception) { - dataBytes= CryptoUtil.decodePlainBase64(data); - } - byte[][] splits = splitAtFirstOccurance(dataBytes, - String.valueOf(env.getProperty(KERNEL_KEY_SPLITTER)).getBytes()); - return new SplittedEncryptedData(CryptoUtil.encodeToURLSafeBase64(splits[0]), CryptoUtil.encodeToURLSafeBase64(splits[1])); - } - - private static byte[][] splitAtFirstOccurance(byte[] strBytes, byte[] sepBytes) { - int index = findIndex(strBytes, sepBytes); - if (index >= 0) { - byte[] bytes1 = new byte[index]; - byte[] bytes2 = new byte[strBytes.length - (bytes1.length + sepBytes.length)]; - System.arraycopy(strBytes, 0, bytes1, 0, bytes1.length); - System.arraycopy(strBytes, (bytes1.length + sepBytes.length), bytes2, 0, bytes2.length); - return new byte[][] { bytes1, bytes2 }; - } else { - return new byte[][] { strBytes, new byte[0] }; - } - } - - private static int findIndex(byte arr[], byte[] subarr) { - int len = arr.length; - int subArrayLen = subarr.length; - return IntStream.range(0, len).filter(currentIndex -> { - if ((currentIndex + subArrayLen) <= len) { - byte[] sArray = new byte[subArrayLen]; - System.arraycopy(arr, currentIndex, sArray, 0, subArrayLen); - return Arrays.equals(sArray, subarr); - } - return false; - }).findFirst() // first occurence - .orElse(-1); // No element found - } - - private static String trimBeginEnd(String pKey) { - pKey = pKey.replaceAll("-*BEGIN([^-]*)-*(\r?\n)?", ""); - pKey = pKey.replaceAll("-*END([^-]*)-*(\r?\n)?", ""); - pKey = pKey.replaceAll("\\s", ""); - return pKey; - } - - private X509Certificate getCertificate(String refId) - throws ApisResourceAccessException, IOException, CertificateException { - - // encrypt AES Session Key using RSA public key - ResponseWrapper responseWrapper; - CertificateResponseDto certificateResponseDto; - responseWrapper = (ResponseWrapper) registrationProcessorRestClientService.getApi(ApiName.IDAUTHCERTIFICATE, - null, "applicationId,referenceId", IDA_APP_ID + ',' + refId, ResponseWrapper.class); - certificateResponseDto = mapper.readValue(mapper.writeValueAsString(responseWrapper.getResponse()), - CertificateResponseDto.class); - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), refId, - "AuthUtil::encryptRSA():: ENCRYPTIONSERVICE GET service call ended with response data " - + JsonUtil.objectMapperObjectToJson(responseWrapper)); - - if (responseWrapper.getErrors() != null && responseWrapper.getErrors().size() > 0) - throw new IOException(responseWrapper.getErrors().get(0).getMessage()); - - String certificate = trimBeginEnd(certificateResponseDto.getCertificate()); - - CertificateFactory cf = CertificateFactory.getInstance("X.509"); - X509Certificate x509cert = (X509Certificate) cf - .generateCertificate(new ByteArrayInputStream(java.util.Base64.getDecoder().decode(certificate))); - - return x509cert; - - } - private byte[] getCertificateThumbprint(java.security.cert.Certificate cert) - throws java.security.cert.CertificateEncodingException { - - return DigestUtils.sha256(cert.getEncoded()); - } - - /** - * Extract templates. - * - * @param birs the birs - * @param extractionFormats the extraction formats - * @return the list - * @throws BioTypeException - */ - public List extractTemplates(List birs, Map extractionFormats) throws BioTypeException - { - try { - Map> birsByType = birs.stream() - .collect(Collectors.groupingBy(bir -> bir.getBdbInfo().getType().get(0))); - - List allExtractedTemplates = new ArrayList<>(); - - for (Entry> entry : birsByType.entrySet()) { - BiometricType modality = entry.getKey(); - iBioProviderApi bioProvider = bioApiFactory.getBioProvider(BiometricType.fromValue(modality.value()), - BiometricFunction.EXTRACT); - List extractedTemplates = bioProvider.extractTemplate(entry.getValue(), extractionFormats); - allExtractedTemplates.addAll(extractedTemplates); - } - - return allExtractedTemplates; - - } catch (Exception e) { - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - "", PlatformErrorMessages.OSI_VALIDATION_BIO_TYPE_EXCEPTION.getMessage() + "-" + e.getMessage()); - throw new BioTypeException( - PlatformErrorMessages.OSI_VALIDATION_BIO_TYPE_EXCEPTION.getMessage() + "-" + e.getMessage()); - } - } -} diff --git a/registration-processor/registration-processor-info-storage-service/src/main/java/io/mosip/registration/processor/packet/storage/utils/BioSdkUtil.java b/registration-processor/registration-processor-info-storage-service/src/main/java/io/mosip/registration/processor/packet/storage/utils/BioSdkUtil.java new file mode 100644 index 00000000000..a659fc91044 --- /dev/null +++ b/registration-processor/registration-processor-info-storage-service/src/main/java/io/mosip/registration/processor/packet/storage/utils/BioSdkUtil.java @@ -0,0 +1,131 @@ +package io.mosip.registration.processor.packet.storage.utils; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; +import org.springframework.web.client.RestClientException; + +import io.mosip.kernel.biometrics.commons.CbeffValidator; +import io.mosip.kernel.biometrics.constant.BiometricFunction; +import io.mosip.kernel.biometrics.constant.BiometricType; +import io.mosip.kernel.biometrics.entities.BIR; +import io.mosip.kernel.biosdk.provider.factory.BioAPIFactory; +import io.mosip.kernel.biosdk.provider.spi.iBioProviderApi; +import io.mosip.kernel.core.exception.BaseCheckedException; +import io.mosip.kernel.core.logger.spi.Logger; +import io.mosip.kernel.core.util.CryptoUtil; +import io.mosip.registration.processor.core.code.RegistrationExceptionTypeCode; +import io.mosip.registration.processor.core.constant.MappingJsonConstants; +import io.mosip.registration.processor.core.exception.ValidationFailedException; +import io.mosip.registration.processor.core.idrepo.dto.Documents; +import io.mosip.registration.processor.core.logger.RegProcessorLogger; +import io.mosip.registration.processor.core.util.RegistrationExceptionMapperUtil; +import io.mosip.registration.processor.status.code.RegistrationStatusCode; +import io.mosip.registration.processor.status.dto.InternalRegistrationStatusDto; + +@Component +public class BioSdkUtil { + + /** The reg proc logger. */ + private static Logger regProcLogger = RegProcessorLogger.getLogger(BioSdkUtil.class); + + /** The utilities. */ + @Autowired + Utilities utilities; + + /** The bio api factory. */ + @Autowired(required = false) + private BioAPIFactory bioApiFactory; + + @Autowired + RegistrationExceptionMapperUtil registrationExceptionMapperUtil; + + public void authenticateBiometrics(String uin, String individualType, + List list, InternalRegistrationStatusDto registrationStatusDto, + String errorMsg, String errorCode) throws Exception { + try { + regProcLogger.debug("BioSdkUtil :: authenticateBiometrics :: Fetching info from id repo based on uin "); + boolean status = false; + List docs = utilities.retrieveIdrepoDocument(uin); + String data = null; + if (null == docs || (null == list || list.size() == 0)) { + registrationStatusDto.setLatestTransactionStatusCode(registrationExceptionMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.BIOMETRIC_EXTRACTION_FAILED)); + registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.toString()); + + throw new BaseCheckedException("No document found for given user"); + } + + for (int i = 0; i < docs.size(); i++) { + if (docs.get(i).getCategory().equalsIgnoreCase(MappingJsonConstants.INDIVIDUAL_BIOMETRICS)) { + data = docs.get(i).getValue(); + break; + } + } + + if (null != data && !(data.isEmpty())) { + BIR bir = CbeffValidator.getBIRFromXML(CryptoUtil.decodeURLSafeBase64(data)); + Map> firstMp = getMapFromBirList(bir.getBirs()); + Map> secondMp = getMapFromBirList(list); + regProcLogger + .debug("BioSdkUtil :: authenticateBiometrics :: BIR size fetch from ID repo " + firstMp.size()); + regProcLogger + .debug("BioSdkUtil :: authenticateBiometrics :: BIR size fetch from packet " + secondMp.size()); + for (Map.Entry> entry : secondMp.entrySet()) { + iBioProviderApi bioProvider = bioApiFactory + .getBioProvider(BiometricType.valueOf(entry.getKey().toString()), BiometricFunction.MATCH); + if (null == firstMp.get(entry.getKey())) { + status = false; + + } else + status = bioProvider.verify(secondMp.get(entry.getKey()),firstMp.get(entry.getKey()), + entry.getKey(), null); + if (!status) { + registrationStatusDto.setLatestTransactionStatusCode(registrationExceptionMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.VALIDATION_FAILED_EXCEPTION)); + registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.toString()); + + throw new ValidationFailedException(errorMsg, errorCode); + } + } + } + regProcLogger.debug( + "BioSdkUtil :: authenticateBiometrics :: Authentication of biometrics done with status " + status); + + } catch (RestClientException restEx) { + registrationStatusDto.setLatestTransactionStatusCode(registrationExceptionMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.CONNECTION_UNAVAILABLE_EXCEPTION)); + registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.toString()); + + regProcLogger.debug( + "BioSdkUtil :: authenticateBiometrics :: Issue whilevalidating biometrics" + restEx.getMessage()); + throw restEx; + } + } + + private Map> getMapFromBirList(List lst) { + + Map> mp = new TreeMap<>(); + lst.stream().forEach(b -> { + if (null != mp && mp.containsKey(b.getBdbInfo().getType().get(0))) { + List l = mp.get(b.getBdbInfo().getType().get(0)); + l.add(b); + } else { + List lstBir = new ArrayList<>(); + lstBir.add(b); + mp.put(b.getBdbInfo().getType().get(0), lstBir); + + } + + }); + + return mp; + + } + +} 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 72fd2d76e1c..e14e3b10305 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 @@ -8,13 +8,12 @@ import java.time.LocalDate; import java.time.LocalDateTime; import java.time.Period; -import java.util.*; +import java.util.ArrayList; +import java.util.Date; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; -import io.mosip.kernel.core.util.exception.JsonProcessingException; -import io.mosip.registration.processor.core.exception.PacketManagerException; -import io.mosip.registration.processor.packet.manager.idreposervice.IdRepoService; -import io.mosip.registration.processor.packet.storage.dto.ConfigEnum; -import io.mosip.registration.processor.core.constant.ProviderStageName; import org.apache.commons.lang.StringUtils; import org.json.simple.JSONArray; import org.json.simple.JSONObject; @@ -28,20 +27,21 @@ import io.mosip.kernel.core.exception.ExceptionUtils; import io.mosip.kernel.core.logger.spi.Logger; -import io.mosip.kernel.core.util.DateUtils; +import io.mosip.kernel.core.util.exception.JsonProcessingException; import io.mosip.registration.processor.abis.queue.dto.AbisQueueDetails; 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.LoggerFileConstant; import io.mosip.registration.processor.core.constant.MappingJsonConstants; +import io.mosip.registration.processor.core.constant.ProviderStageName; import io.mosip.registration.processor.core.exception.ApisResourceAccessException; +import io.mosip.registration.processor.core.exception.PacketManagerException; import io.mosip.registration.processor.core.exception.RegistrationProcessorCheckedException; import io.mosip.registration.processor.core.exception.RegistrationProcessorUnCheckedException; import io.mosip.registration.processor.core.exception.util.PlatformErrorMessages; -import io.mosip.registration.processor.core.idrepo.dto.IdRequestDto; import io.mosip.registration.processor.core.idrepo.dto.IdResponseDTO; import io.mosip.registration.processor.core.idrepo.dto.IdResponseDTO1; -import io.mosip.registration.processor.core.idrepo.dto.RequestDto; +import io.mosip.registration.processor.core.idrepo.dto.ResponseDTO; import io.mosip.registration.processor.core.logger.RegProcessorLogger; import io.mosip.registration.processor.core.packet.dto.Identity; import io.mosip.registration.processor.core.packet.dto.vid.VidResponseDTO; @@ -50,8 +50,10 @@ import io.mosip.registration.processor.core.spi.queue.MosipQueueConnectionFactory; import io.mosip.registration.processor.core.spi.restclient.RegistrationProcessorRestClientService; import io.mosip.registration.processor.core.util.JsonUtil; +import io.mosip.registration.processor.packet.manager.idreposervice.IdRepoService; import io.mosip.registration.processor.packet.storage.dao.PacketInfoDao; import io.mosip.registration.processor.packet.storage.dto.ApplicantInfoDto; +import io.mosip.registration.processor.packet.storage.dto.ConfigEnum; import io.mosip.registration.processor.packet.storage.exception.IdRepoAppException; import io.mosip.registration.processor.packet.storage.exception.ParsingException; import io.mosip.registration.processor.packet.storage.exception.QueueConnectionNotFound; @@ -109,7 +111,6 @@ public class Utilities { @Autowired private IdRepoService idRepoService; - /** The rest client service. */ @Autowired private RegistrationProcessorRestClientService restClientService; @@ -203,11 +204,11 @@ public class Utilities { /** The Constant RANDOMIZE_FALSE. */ private static final String RANDOMIZE_FALSE = ")?randomize=false"; - + private static final String VALUE = "value"; private JSONObject mappingJsonObject = null; - + private JSONObject regProcessorAbisJson = null; public static void initialize(Map reader, Map writer) { @@ -218,10 +219,8 @@ public static void initialize(Map reader, Map wr /** * Gets the json. * - * @param configServerFileStorageURL - * the config server file storage URL - * @param uri - * the uri + * @param configServerFileStorageURL the config server file storage URL + * @param uri the uri * @return the json */ public static String getJson(String configServerFileStorageURL, String uri) { @@ -234,45 +233,48 @@ public static String getJson(String configServerFileStorageURL, String uri) { * present, if yes returns age if both dob or age are not present then retrieves * age from id repo * - * @param id - * the registration id + * @param id the registration id * @return the applicant age - * @throws IOException - * Signals that an I/O exception has occurred. - * @throws IOException - * Signals that an I/O exception has occurred. - * @throws ApisResourceAccessException - * the packet decryption failure exception + * @throws IOException Signals that an I/O exception + * has occurred. + * @throws IOException Signals that an I/O exception + * has occurred. + * @throws ApisResourceAccessException the packet decryption failure + * exception * @throws RegistrationProcessorCheckedException */ - public int getApplicantAge(String id, String process, ProviderStageName stageName) throws IOException, - ApisResourceAccessException, JsonProcessingException, PacketManagerException { - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), - id, "Utilities::getApplicantAge()::entry"); - - String applicantDob = packetManagerService.getFieldByMappingJsonKey(id, MappingJsonConstants.DOB, process, stageName); - String applicantAge = packetManagerService.getFieldByMappingJsonKey(id, MappingJsonConstants.AGE, process, stageName); + public int getApplicantAge(String id, String process, ProviderStageName stageName) + throws IOException, ApisResourceAccessException, JsonProcessingException, PacketManagerException { + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), id, + "Utilities::getApplicantAge()::entry"); + + String applicantDob = packetManagerService.getFieldByMappingJsonKey(id, MappingJsonConstants.DOB, process, + stageName); + String applicantAge = packetManagerService.getFieldByMappingJsonKey(id, MappingJsonConstants.AGE, process, + stageName); if (applicantDob != null) { return calculateAge(applicantDob); } else if (applicantAge != null) { - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), - id, "Utilities::getApplicantAge()::exit when applicantAge is not null"); + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), id, + "Utilities::getApplicantAge()::exit when applicantAge is not null"); return Integer.valueOf(applicantAge); } else { String uin = getUIn(id, process, stageName); JSONObject identityJSONOject = retrieveIdrepoJson(uin); JSONObject regProcessorIdentityJson = getRegistrationProcessorMappingJson(MappingJsonConstants.IDENTITY); - String ageKey = JsonUtil.getJSONValue(JsonUtil.getJSONObject(regProcessorIdentityJson, MappingJsonConstants.AGE), VALUE); - String dobKey = JsonUtil.getJSONValue(JsonUtil.getJSONObject(regProcessorIdentityJson, MappingJsonConstants.DOB), VALUE); + String ageKey = JsonUtil + .getJSONValue(JsonUtil.getJSONObject(regProcessorIdentityJson, MappingJsonConstants.AGE), VALUE); + String dobKey = JsonUtil + .getJSONValue(JsonUtil.getJSONObject(regProcessorIdentityJson, MappingJsonConstants.DOB), VALUE); String idRepoApplicantDob = JsonUtil.getJSONValue(identityJSONOject, dobKey); if (idRepoApplicantDob != null) { - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), - id, "Utilities::getApplicantAge()::exit when ID REPO applicantDob is not null"); + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), id, + "Utilities::getApplicantAge()::exit when ID REPO applicantDob is not null"); return calculateAge(idRepoApplicantDob); } Integer idRepoApplicantAge = JsonUtil.getJSONValue(identityJSONOject, ageKey); - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), - id, "Utilities::getApplicantAge()::exit when ID REPO applicantAge is not null"); + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), id, + "Utilities::getApplicantAge()::exit when ID REPO applicantAge is not null"); return idRepoApplicantAge != null ? idRepoApplicantAge : -1; } @@ -334,7 +336,6 @@ private Object getField(JSONObject jsonObject, String field) { return lm.get(PROVIDER); } - public String getSourceFromIdField(String packetSegment, String process, String idField) throws IOException { JSONObject jsonObject = getRegistrationProcessorMappingJson(packetSegment); for (Object key : jsonObject.keySet()) { @@ -348,60 +349,107 @@ public String getSourceFromIdField(String packetSegment, String process, String } /** - * retrieving identity json ffrom id repo by UIN. + * retrieving json from id repo by UIN. * - * @param uin - * the uin + * @param uin the uin * @return the JSON object - * @throws ApisResourceAccessException - * the apis resource access exception - * @throws IdRepoAppException - * the id repo app exception - * @throws IOException - * Signals that an I/O exception has occurred. + * @throws ApisResourceAccessException the apis resource access exception + * @throws IdRepoAppException the id repo app exception + * @throws IOException Signals that an I/O exception has + * occurred. */ - public JSONObject retrieveIdrepoJson(String uin) throws ApisResourceAccessException, IdRepoAppException, IOException { - + private ResponseDTO retrieveIdrepoResponseObj(String uin, String queryParam, String queryParamValue) + throws ApisResourceAccessException { if (uin != null) { regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.UIN.toString(), "", - "Utilities::retrieveIdrepoJson()::entry"); + "Utilities::retrieveIdrepoResponseObj()::entry"); List pathSegments = new ArrayList<>(); pathSegments.add(uin); IdResponseDTO1 idResponseDto; - idResponseDto = (IdResponseDTO1) restClientService.getApi(ApiName.IDREPOGETIDBYUIN, pathSegments, "", "", + idResponseDto = (IdResponseDTO1) restClientService.getApi(ApiName.IDREPOGETIDBYUIN, pathSegments, + null == queryParam ? "" : queryParam, null == queryParamValue ? "" : queryParamValue, IdResponseDTO1.class); + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.UIN.toString(), "", + "Utilities::retrieveIdrepoDocument():: IDREPOGETIDBYUIN GET service call ended Successfully"); + if (idResponseDto == null) { regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.UIN.toString(), "", - "Utilities::retrieveIdrepoJson()::exit idResponseDto is null"); + "Utilities::retrieveIdrepoResponseObj()::exit idResponseDto is null"); return null; } if (!idResponseDto.getErrors().isEmpty()) { List error = idResponseDto.getErrors(); regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.UIN.toString(), "", - "Utilities::retrieveIdrepoJson():: error with error message " + error.get(0).getMessage()); + "Utilities::retrieveIdrepoResponseObj():: error with error message " + + error.get(0).getMessage()); throw new IdRepoAppException(error.get(0).getMessage()); } - String response = objMapper.writeValueAsString(idResponseDto.getResponse().getIdentity()); - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.UIN.toString(), "", - "Utilities::retrieveIdrepoJson():: IDREPOGETIDBYUIN GET service call ended Successfully"); - try { - return (JSONObject) new JSONParser().parse(response); - } catch (org.json.simple.parser.ParseException e) { - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.UIN.toString(), "", - ExceptionUtils.getStackTrace(e)); - throw new IdRepoAppException("Error while parsing string to JSONObject",e); - } + return idResponseDto.getResponse(); + } + return null; + } + + /** + * retrieving identity json ffrom id repo by UIN. + * + * @param uin the uin + * @return the JSON object + * @throws ApisResourceAccessException the apis resource access exception + * @throws IdRepoAppException the id repo app exception + * @throws IOException Signals that an I/O exception has + * occurred. + */ + public JSONObject retrieveIdrepoJson(String uin) + throws ApisResourceAccessException, IdRepoAppException, IOException { + + if (uin != null) { + ResponseDTO idResponseDto = retrieveIdrepoResponseObj(uin, null, null); + if (idResponseDto != null) { + String response = objMapper.writeValueAsString(idResponseDto.getIdentity()); + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.UIN.toString(), "", + "Utilities::retrieveIdrepoJson():: IDREPOGETIDBYUIN GET service call ended Successfully"); + try { + return (JSONObject) new JSONParser().parse(response); + } catch (org.json.simple.parser.ParseException e) { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.UIN.toString(), "", + ExceptionUtils.getStackTrace(e)); + throw new IdRepoAppException("Error while parsing string to JSONObject", e); + } + } else { + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.UIN.toString(), "", + "Utilities::retrieveIdrepoJson():: IDREPOGETIDBYUIN GET service Returned NULL"); + } } + return null; + } + + /** + * retrieving identity json ffrom id repo by UIN. + * + * @param uin the uin + * @return the JSON object + * @throws ApisResourceAccessException the apis resource access exception + * @throws IdRepoAppException the id repo app exception + * @throws IOException Signals that an I/O exception has + * occurred. + */ + public List retrieveIdrepoDocument(String uin) + throws ApisResourceAccessException { regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.UIN.toString(), "", - "Utilities::retrieveIdrepoJson()::exit UIN is null"); + "Utilities::retrieveIdrepoDocument()::entry"); + ResponseDTO idResponseDto = retrieveIdrepoResponseObj(uin, "type", "all"); + if (idResponseDto != null) { + return idResponseDto.getDocuments(); + } return null; } /** - * Check if uin is present in idrepo + * Check if uin is present in idrepo + * * @param uin * @return * @throws ApisResourceAccessException @@ -413,14 +461,14 @@ public boolean uinPresentInIdRepo(String uin) throws ApisResourceAccessException /** * Check if uin is missing from Id + * * @param errorCode * @param id * @param idType * @return */ public boolean isUinMissingFromIdAuth(String errorCode, String id, String idType) { - if (errorCode.equalsIgnoreCase("IDA-MLC-018") && - idType != null && idType.equalsIgnoreCase("UIN")) { + if (errorCode.equalsIgnoreCase("IDA-MLC-018") && idType != null && idType.equalsIgnoreCase("UIN")) { try { return uinPresentInIdRepo(id); } catch (IOException | ApisResourceAccessException exception) { @@ -438,11 +486,12 @@ public boolean isUinMissingFromIdAuth(String errorCode, String id, String idType * from abisJson Also validates the abis json fileds(null or not). * * @return the abis queue details - * @throws RegistrationProcessorCheckedException - * the registration processor checked exception + * @throws RegistrationProcessorCheckedException the registration processor + * checked exception */ public List getAbisQueueDetails() throws RegistrationProcessorCheckedException { List abisQueueDetailsList = new ArrayList<>(); + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", "Utilities::getAbisQueueDetails()::entry"); @@ -495,8 +544,7 @@ public List getAbisQueueDetails() throws RegistrationProcessor * RegistrationProcessorIdentity java class. * * @return the registration processor identity json - * @throws IOException - * Signals that an I/O exception has occurred. + * @throws IOException Signals that an I/O exception has occurred. */ public JSONObject getRegistrationProcessorMappingJson(String packetSegment) throws IOException { regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", @@ -528,23 +576,23 @@ public String getMappingJsonValue(String key, String packetSegment) throws IOExc * Get UIN from identity json (used only for update/res update/activate/de * activate packets). * - * @param id - * the registration id + * @param id the registration id * @return the u in - * @throws IOException - * Signals that an I/O exception has occurred. - * @throws IOException - * Signals that an I/O exception has occurred. - * @throws ApisResourceAccessException - * the apis resource access exception + * @throws IOException Signals that an I/O exception + * has occurred. + * @throws IOException Signals that an I/O exception + * has occurred. + * @throws ApisResourceAccessException the apis resource access + * exception * @throws RegistrationProcessorCheckedException */ - public String getUIn(String id, String process, ProviderStageName stageName) throws IOException, ApisResourceAccessException, PacketManagerException, JsonProcessingException { - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - id, "Utilities::getUIn()::entry"); + public String getUIn(String id, String process, ProviderStageName stageName) + throws IOException, ApisResourceAccessException, PacketManagerException, JsonProcessingException { + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), id, + "Utilities::getUIn()::entry"); String UIN = packetManagerService.getFieldByMappingJsonKey(id, MappingJsonConstants.UIN, process, stageName); - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - id, "Utilities::getUIn()::exit"); + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), id, + "Utilities::getUIn()::exit"); return UIN; @@ -553,10 +601,8 @@ public String getUIn(String id, String process, ProviderStageName stageName) thr /** * Gets the elapse status. * - * @param registrationStatusDto - * the registration status dto - * @param transactionType - * the transaction type + * @param registrationStatusDto the registration status dto + * @param transactionType the transaction type * @return the elapse status */ public String getElapseStatus(InternalRegistrationStatusDto registrationStatusDto, String transactionType) { @@ -589,14 +635,15 @@ public String getElapseStatus(InternalRegistrationStatusDto registrationStatusDt /** * Gets the latest transaction id. * - * @param registrationId - * the registration id + * @param registrationId the registration id * @return the latest transaction id */ - public String getLatestTransactionId(String registrationId, String process, int iteration, String workflowInstanceId) { + public String getLatestTransactionId(String registrationId, String process, int iteration, + String workflowInstanceId) { regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), registrationId, "Utilities::getLatestTransactionId()::entry"); - RegistrationStatusEntity entity = registrationStatusDao.find(registrationId, process, iteration, workflowInstanceId); + RegistrationStatusEntity entity = registrationStatusDao.find(registrationId, process, iteration, + workflowInstanceId); regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), registrationId, "Utilities::getLatestTransactionId()::exit"); return entity != null ? entity.getLatestRegistrationTransactionId() : null; @@ -606,15 +653,12 @@ public String getLatestTransactionId(String registrationId, String process, int /** * retrieve UIN from IDRepo by registration id. * - * @param regId - * the reg id + * @param regId the reg id * @return the JSON object - * @throws ApisResourceAccessException - * the apis resource access exception - * @throws IdRepoAppException - * the id repo app exception - * @throws IOException - * Signals that an I/O exception has occurred. + * @throws ApisResourceAccessException the apis resource access exception + * @throws IdRepoAppException the id repo app exception + * @throws IOException Signals that an I/O exception has + * occurred. */ public JSONObject retrieveUIN(String regId) throws ApisResourceAccessException, IdRepoAppException, IOException { regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), @@ -647,7 +691,7 @@ public JSONObject retrieveUIN(String regId) throws ApisResourceAccessException, } catch (org.json.simple.parser.ParseException e) { regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.UIN.toString(), "", ExceptionUtils.getStackTrace(e)); - throw new IdRepoAppException("Error while parsing string to JSONObject",e); + throw new IdRepoAppException("Error while parsing string to JSONObject", e); } } @@ -660,8 +704,7 @@ public JSONObject retrieveUIN(String regId) throws ApisResourceAccessException, /** * Calculate age. * - * @param applicantDob - * the applicant dob + * @param applicantDob the applicant dob * @return the int */ private int calculateAge(String applicantDob) { @@ -691,10 +734,8 @@ private int calculateAge(String applicantDob) { /** * Validate abis queue json and return value. * - * @param jsonObject - * the json object - * @param key - * the key + * @param jsonObject the json object + * @param key the key * @return the string */ private String validateAbisQueueJsonAndReturnValue(JSONObject jsonObject, String key) { @@ -713,10 +754,8 @@ private String validateAbisQueueJsonAndReturnValue(JSONObject jsonObject, String /** * Validate abis queue json and return long value. * - * @param jsonObject - * the json object - * @param key - * the key + * @param jsonObject the json object + * @param key the key * @return the long value */ private int validateAbisQueueJsonAndReturnIntValue(JSONObject jsonObject, String key) { @@ -735,13 +774,10 @@ private int validateAbisQueueJsonAndReturnIntValue(JSONObject jsonObject, String /** * Gets the uin by vid. * - * @param vid - * the vid + * @param vid the vid * @return the uin by vid - * @throws ApisResourceAccessException - * the apis resource access exception - * @throws VidCreationException - * the vid creation exception + * @throws ApisResourceAccessException the apis resource access exception + * @throws VidCreationException the vid creation exception */ @SuppressWarnings("unchecked") public String getUinByVid(String vid) throws ApisResourceAccessException, VidCreationException { @@ -772,13 +808,10 @@ public String getUinByVid(String vid) throws ApisResourceAccessException, VidCre /** * Retrieve idrepo json status. * - * @param uin - * the uin + * @param uin the uin * @return the string - * @throws ApisResourceAccessException - * the apis resource access exception - * @throws IdRepoAppException - * the id repo app exception + * @throws ApisResourceAccessException the apis resource access exception + * @throws IdRepoAppException the id repo app exception */ public String retrieveIdrepoJsonStatus(String uin) throws ApisResourceAccessException, IdRepoAppException { String response = null; diff --git a/registration-processor/registration-processor-info-storage-service/src/test/java/io/mosip/registration/processor/packet/storage/utils/ABISHandlerUtilTest.java b/registration-processor/registration-processor-info-storage-service/src/test/java/io/mosip/registration/processor/packet/storage/utils/ABISHandlerUtilTest.java index a90faf4387a..dce4b2c684c 100644 --- a/registration-processor/registration-processor-info-storage-service/src/test/java/io/mosip/registration/processor/packet/storage/utils/ABISHandlerUtilTest.java +++ b/registration-processor/registration-processor-info-storage-service/src/test/java/io/mosip/registration/processor/packet/storage/utils/ABISHandlerUtilTest.java @@ -65,6 +65,8 @@ public class ABISHandlerUtilTest { @Mock private IdRepoService idRepoService; + + List lst=new ArrayList<>(); @Before public void setup() throws Exception { @@ -96,6 +98,10 @@ public void setup() throws Exception { abisResponseDtoList.add(abisResponseDto); }); + + lst.add(RegistrationTransactionStatusCode.PROCESSED.toString());lst.add(RegistrationTransactionStatusCode.PROCESSING.toString()); + + when(packetInfoManager.getAbisResponseRecords(regBioRefIds.get(0), latestTransactionId, AbisConstant.IDENTIFY)).thenReturn(abisResponseDtoList); @@ -117,7 +123,7 @@ public void setup() throws Exception { when(packetInfoDao.getWithoutStatusCodes(matchedRids, RegistrationTransactionStatusCode.REJECTED.toString(), RegistrationTransactionStatusCode.PROCESSED.toString())).thenReturn(inprogressMatchedIds); when(packetInfoDao.getProcessedOrProcessingRegIds(matchedRids, - RegistrationTransactionStatusCode.PROCESSED.toString())).thenReturn(processedMatchedIds); + lst)).thenReturn(processedMatchedIds); when(idRepoService.getUinByRid(processedMatchedIds.get(0), new String())).thenReturn("123456789"); when(idRepoService.getUinByRid(processedMatchedIds.get(1), new String())).thenReturn("987654321"); @@ -157,7 +163,7 @@ public void testDonotReturnRejected() throws ApisResourceAccessException, JsonPr public void testReturnAllInprogress() throws ApisResourceAccessException, JsonProcessingException, PacketManagerException, IOException, io.mosip.kernel.core.exception.IOException { when(packetInfoDao.getProcessedOrProcessingRegIds(matchedRids, - RegistrationTransactionStatusCode.PROCESSED.toString())).thenReturn(Lists.newArrayList()); + lst)).thenReturn(Lists.newArrayList()); Set uniqueRids = abisHandlerUtil.getUniqueRegIds(registrationId, registrationType,1, "", ProviderStageName.BIO_DEDUPE); // expected not to pick rocessedMatchedIds list i.e 3 records. diff --git a/registration-processor/registration-processor-info-storage-service/src/test/java/io/mosip/registration/processor/packet/storage/utils/BioSdkUtilTest.java b/registration-processor/registration-processor-info-storage-service/src/test/java/io/mosip/registration/processor/packet/storage/utils/BioSdkUtilTest.java new file mode 100644 index 00000000000..6b460df7ad0 --- /dev/null +++ b/registration-processor/registration-processor-info-storage-service/src/test/java/io/mosip/registration/processor/packet/storage/utils/BioSdkUtilTest.java @@ -0,0 +1,96 @@ +package io.mosip.registration.processor.packet.storage.utils; + +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.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 io.mosip.kernel.biometrics.commons.CbeffValidator; +import io.mosip.kernel.biometrics.entities.BIR; +import io.mosip.kernel.biosdk.provider.factory.BioAPIFactory; +import io.mosip.kernel.biosdk.provider.spi.iBioProviderApi; +import io.mosip.kernel.core.exception.BaseCheckedException; +import io.mosip.registration.processor.core.code.RegistrationExceptionTypeCode; +import io.mosip.registration.processor.core.constant.MappingJsonConstants; +import io.mosip.registration.processor.core.idrepo.dto.Documents; +import io.mosip.registration.processor.core.util.RegistrationExceptionMapperUtil; +import io.mosip.registration.processor.status.dto.InternalRegistrationStatusDto; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({ Utilities.class, CbeffValidator.class }) +@PowerMockIgnore({ "javax.management.*", "javax.net.ssl.*","com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "javax.management.*" }) +public class BioSdkUtilTest { + + + @InjectMocks + private BioSdkUtil bioSdkUtil; + + @Mock + private Utilities utilities; + + @Mock + private BioAPIFactory bio; + + @Mock + private iBioProviderApi bioProvider; + + @Mock + RegistrationExceptionMapperUtil registrationStatusMapperUtil; + + private InternalRegistrationStatusDto regist=new InternalRegistrationStatusDto(); + + + List l=new ArrayList<>(); + String data="adjfgJHDFKjhsdfjksdbf"; + @Before + public void setup() throws Exception { + MockitoAnnotations.initMocks(this); + + + List ld=new ArrayList<>(); + Documents d=new Documents(MappingJsonConstants.INDIVIDUAL_BIOMETRICS, data); + ld.add(d); + when(utilities.retrieveIdrepoDocument(Mockito.anyString())).thenReturn(ld); + when(bio.getBioProvider(Mockito.any(), Mockito.any())).thenReturn(bioProvider); + when(bioProvider.verify(Mockito.anyList(), Mockito.anyList(), Mockito.any(), Mockito.any())).thenReturn(true); + Mockito.when(registrationStatusMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.BIOMETRIC_EXTRACTION_FAILED)).thenReturn("FAILED"); + Mockito.when(registrationStatusMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.VALIDATION_FAILED_EXCEPTION)).thenReturn("FAILED"); + Mockito.when(registrationStatusMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.CONNECTION_UNAVAILABLE_EXCEPTION)).thenReturn("FAILED"); + + } + + + @Test(expected = Exception.class) + public void authenticateBiometricsTest() throws Exception { + when(utilities.retrieveIdrepoDocument(Mockito.anyString())).thenReturn(null); + PowerMockito.mockStatic(CbeffValidator.class); + when(CbeffValidator.getBIRFromXML(Mockito.any())).thenReturn(new BIR()); + bioSdkUtil.authenticateBiometrics("123456", "UIN", l,regist,"test","test"); + + } + + + @Test(expected = BaseCheckedException.class) + public void authenticateBiometricsTest1() throws Exception { + + PowerMockito.mockStatic(CbeffValidator.class); + when(CbeffValidator.getBIRFromXML(Mockito.any())).thenReturn(new BIR()); + bioSdkUtil.authenticateBiometrics("123456", "UIN", l,regist,"test","test"); + + } +} diff --git a/registration-processor/registration-processor-landing-zone/Dockerfile b/registration-processor/registration-processor-landing-zone/Dockerfile new file mode 100644 index 00000000000..b9e4a372aab --- /dev/null +++ b/registration-processor/registration-processor-landing-zone/Dockerfile @@ -0,0 +1,85 @@ +FROM openjdk:11 + +#Uncomment below and Comment above line(i.e. FROM openjdk:8) for OS specific (e.g. Alpine OS ) docker base image +#FROM openjdk:8-jdk-alpine + +# can be passed during Docker build as build time environment for github branch to pickup configuration from. +ARG spring_config_label + +# can be passed during Docker build as build time environment for spring profiles active +ARG active_profile + +# can be passed during Docker build as build time environment for config server URL +ARG spring_config_url + +# can be passed during Docker build as build time environment management rmi server hostname +ARG management_rmi_server_hostname + +# can be passed during Docker build as build time environment management rmi server port +ARG management_jmxremote_rmi_port + +# environment variable to pass active profile such as DEV, QA etc at docker runtime +ENV active_profile_env=${active_profile} + +# environment variable to pass github branch to pickup configuration from, at docker runtime +ENV spring_config_label_env=${spring_config_label} + +# environment variable to pass github branch to pickup configuration from, at docker runtime +ENV spring_config_label_env=${spring_config_label} + +# environment variable to pass iam_adapter url, at docker runtime +ENV iam_adapter_url_env=${iam_adapter_url} + +# can be passed during Docker build as build time environment for github branch to pickup configuration from. +ARG container_user=mosip +# can be passed during Docker build as build time environment for github branch to pickup configuration from. +ARG container_user_group=mosip + +# can be passed during Docker build as build time environment for github branch to pickup configuration from. +ARG container_user_uid=1001 + +# can be passed during Docker build as build time environment for github branch to pickup configuration from. +ARG container_user_gid=1001 + +RUN apt-get -y update \ +&& apt-get install -y unzip sudo \ +&& groupadd -g ${container_user_gid} ${container_user_group} \ +&& useradd -u ${container_user_uid} -g ${container_user_group} -s /bin/sh -m ${container_user} \ +&& adduser ${container_user} sudo + +# set working directory for the user +WORKDIR /home/${container_user} + +ENV work_dir=/home/${container_user} + +ARG loader_path=${work_dir}/additional_jars/ + +RUN mkdir -p ${loader_path} + +ENV loader_path_env=${loader_path} + +# change volume to whichever storage directory you want to use for this container. +VOLUME /home/ftp1/ARCHIVE_PACKET_LOCATION /home/ftp1/LANDING_ZONE ${work_dir}/logs ${work_dir}/Glowroot + +ADD ./target/registration-processor-landing-zone-*.jar registration-processor-landing-zone.jar + +# change permissions of file inside working dir +RUN chown -R ${container_user}:${container_user} /home/${container_user} + +# select container user for all tasks +USER ${container_user_uid}:${container_user_gid} + +CMD if [ "$active_profile_env" = "preprod" ]; then \ + wget 'http://13.71.87.138:8040/artifactory/libs-release-local/io/mosip/testing/glowroot.zip' ; \ + wget "${iam_adapter_url_env}" -O "${loader_path_env}"/kernel-auth-adapter.jar; \ + #java -Dloader.path="${loader_path_env}" -jar -Dspring.cloud.config.label="${spring_config_label_env}" -Dspring.profiles.active="${active_profile_env}" -Dspring.cloud.config.uri="${spring_config_url_env}" registration-processor-landing-zone.jar; \ + unzip glowroot.zip ; \ + rm -rf glowroot.zip ; \ + sed -i 's//registration-processor-registration-status-service/g' glowroot/glowroot.properties ; \ + java -XX:+UnlockExperimentalVMOptions -XX:+UseCGroupMemoryLimitForHeap -XX:MaxRAMFraction=1 -XX:+HeapDumpOnOutOfMemoryError -XX:+UseG1GC -XX:+UseStringDeduplication -jar -javaagent:glowroot/glowroot.jar -Dloader.path="${loader_path_env}" -Dspring.cloud.config.label="${spring_config_label_env}" -Dspring.profiles.active="${active_profile_env}" -Dspring.cloud.config.uri="${spring_config_url_env}" registration-processor-landing-zone.jar ; \ + else \ + wget "${iam_adapter_url_env}" -O "${loader_path_env}"/kernel-auth-adapter.jar; \ + java -Dloader.path="${loader_path_env}" -jar -Dspring.cloud.config.label="${spring_config_label_env}" -Dspring.profiles.active="${active_profile_env}" -Dspring.cloud.config.uri="${spring_config_url_env}" registration-processor-landing-zone.jar; \ + fi + +#CMD ["java","-Dspring.cloud.config.label=${spring_config_label_env}","-Dspring.profiles.active=${active_profile_env}","-Dspring.cloud.config.uri=${spring_config_url_env}","-jar","-javaagent:/home/Glowroot/glowroot.jar","registration-processor-landing-zone.jar"] diff --git a/registration-processor/registration-processor-landing-zone/pom.xml b/registration-processor/registration-processor-landing-zone/pom.xml new file mode 100644 index 00000000000..004f7c06059 --- /dev/null +++ b/registration-processor/registration-processor-landing-zone/pom.xml @@ -0,0 +1,94 @@ + + + 4.0.0 + + io.mosip.registrationprocessor + registration-processor + 1.2.0.1-B3-SNAPSHOT + + registration-processor-landing-zone + registration-processor-landing-zone + 1.2.0.1-B3-SNAPSHOT + + UTF-8 + + + + + org.springframework.boot + spring-boot-starter + + + io.mosip.commons + khazana + ${object.store.khazana.version} + + + org.springframework.boot + spring-boot-starter-test + test + + + io.mosip.registrationprocessor + registration-processor-packet-manager + ${packet.manager.version} + + + io.mosip.registrationprocessor + registration-processor-core + ${registration.processor.core.version} + + + org.postgresql + postgresql + runtime + + + org.powermock + powermock-module-junit4 + ${powermock.module.junit4.version} + test + + + org.powermock + powermock-api-mockito2 + ${powermock.api.mockito.version} + test + + + org.mockito + mockito-core + ${mockito.version} + test + + + junit + junit + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + ${spring.boot.version} + + true + ZIP + + + + + build-info + repackage + + + + + + + + diff --git a/registration-processor/registration-processor-landing-zone/src/main/java/io/mosip/registration/processor/RegistrationProcessorLandingZoneApplication.java b/registration-processor/registration-processor-landing-zone/src/main/java/io/mosip/registration/processor/RegistrationProcessorLandingZoneApplication.java new file mode 100644 index 00000000000..9102ddcb981 --- /dev/null +++ b/registration-processor/registration-processor-landing-zone/src/main/java/io/mosip/registration/processor/RegistrationProcessorLandingZoneApplication.java @@ -0,0 +1,17 @@ +package io.mosip.registration.processor; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.ComponentScan; + +@SpringBootApplication +@ComponentScan( basePackages = { "io.mosip.registration.processor.status.*", + "io.mosip.registration.processor.rest.client.*", "io.mosip.registration.processor.util", + "io.mosip.registration.processor.core.config","${mosip.auth.adapter.impl.basepackage}"} ) +public class RegistrationProcessorLandingZoneApplication { + + public static void main(String[] args) { + SpringApplication.run(RegistrationProcessorLandingZoneApplication.class, args); + } + +} diff --git a/registration-processor/registration-processor-landing-zone/src/main/java/io/mosip/registration/processor/util/LandingZone.java b/registration-processor/registration-processor-landing-zone/src/main/java/io/mosip/registration/processor/util/LandingZone.java new file mode 100644 index 00000000000..84fe09ef2b0 --- /dev/null +++ b/registration-processor/registration-processor-landing-zone/src/main/java/io/mosip/registration/processor/util/LandingZone.java @@ -0,0 +1,124 @@ +package io.mosip.registration.processor.util; + +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.core.env.Environment; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; + +import io.mosip.commons.khazana.spi.ObjectStoreAdapter; +import io.mosip.kernel.core.logger.spi.Logger; +import io.mosip.registration.processor.core.constant.LandingZoneTypeConstant; +import io.mosip.registration.processor.core.constant.LoggerFileConstant; +import io.mosip.registration.processor.core.logger.RegProcessorLogger; +import io.mosip.registration.processor.core.spi.filesystem.manager.FileManager; +import io.mosip.registration.processor.packet.manager.dto.DirectoryPathDto; + +@Component +class LandingZone { + private static Logger regProcLogger = RegProcessorLogger.getLogger(LandingZone.class); + private static final int MAX_NUMBER_OF_PACKETS = 100; + @Value("${landing.zone.account.name}") + private String landingZoneAccount; + + @Value("${landing.zone.type:ObjectStore}") + private String landingZoneType; + + @Value("${registration.processor.packet.ext}") + private String extention; + + @Autowired + private FileManager fileManager; + + @Autowired + private ObjectStoreAdapter objectStoreAdapter; + + @Autowired + Environment env; + + /** + * + * moves the packets from dmz server to objectstore if the landing zone has been + * changed to + */ + @Scheduled(fixedDelayString = "${mosip.regproc.landing.zone.fixed.delay.millisecs:43200000}", initialDelayString = "${mosip.regproc.landing.zone.inital.delay.millisecs:300000}") + public void movePacketsToObjectStore() { + + if (landingZoneType.equalsIgnoreCase(LandingZoneTypeConstant.OBJECT_STORE)) { + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", + "PacketUploaderServiceImpl::movePacketsToObjectStore()::entry"); + + try { + + List packetList = new ArrayList<>(); + try(Stream PathStream=Files.list(Paths.get(env.getProperty(DirectoryPathDto.LANDING_ZONE.toString())))){ + PathStream.map(Path::toFile) + .filter(File::isFile).filter(file -> file.getName().endsWith(extention)).forEach(file -> { + packetList.add(file); + if (packetList.size() >= MAX_NUMBER_OF_PACKETS) { + packetList.forEach(packet -> handlePacket(packet)); + packetList.clear(); + } + }); + } + + if (packetList.size() < MAX_NUMBER_OF_PACKETS) { + packetList.forEach(packet -> handlePacket(packet)); + packetList.clear(); + } + + } catch (IOException e) { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString(), "", e.getMessage()); + } catch (Exception e) { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString(), "", e.getMessage()); + } + } + + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", + "PacketUploaderServiceImpl::movePacketsToObjectStore()::exit"); + } + + private void handlePacket(File packet) { + + String regId = packet.getName().split("-")[0]; + String packetId = packet.getName().split("\\.")[0]; + if (packet.exists()) { + boolean result; + try { + InputStream stream = new FileInputStream(packet); + result = objectStoreAdapter.putObject(landingZoneAccount, regId, null, null, packetId, stream); + stream.close(); + if (!result) { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), + regId, packetId + ":Packet store not accesible"); + } else { + fileManager.deletePacket(DirectoryPathDto.LANDING_ZONE, packetId); + regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), + regId, packetId + ":Packet has been moved to landing zone object store "); + } + } catch (Exception e) { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), + regId, e.getMessage()); + } + } else { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), regId, + packetId + ":Packet not present in dmz server"); + } + } +} diff --git a/registration-processor/registration-processor-landing-zone/src/main/java/io/mosip/registration/processor/util/LandingZoneConfig.java b/registration-processor/registration-processor-landing-zone/src/main/java/io/mosip/registration/processor/util/LandingZoneConfig.java new file mode 100644 index 00000000000..256bba93b8a --- /dev/null +++ b/registration-processor/registration-processor-landing-zone/src/main/java/io/mosip/registration/processor/util/LandingZoneConfig.java @@ -0,0 +1,54 @@ +package io.mosip.registration.processor.util; + +import java.io.InputStream; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.EnableAspectJAutoProxy; +import org.springframework.context.annotation.Primary; +import org.springframework.scheduling.annotation.EnableScheduling; + +import io.mosip.commons.khazana.impl.S3Adapter; +import io.mosip.commons.khazana.impl.SwiftAdapter; +import io.mosip.commons.khazana.spi.ObjectStoreAdapter; +import io.mosip.registration.processor.core.spi.filesystem.manager.FileManager; +import io.mosip.registration.processor.core.spi.restclient.RegistrationProcessorRestClientService; +import io.mosip.registration.processor.packet.manager.dto.DirectoryPathDto; +import io.mosip.registration.processor.packet.manager.service.impl.FileManagerImpl; +import io.mosip.registration.processor.rest.client.service.impl.RegistrationProcessorRestClientServiceImpl; + +@Configuration +@EnableAspectJAutoProxy +@EnableScheduling +public class LandingZoneConfig { + private static final String s3_Adapter = "S3Adapter"; + private static final String swift_Adapter = "SwiftAdapter"; + + @Value("${registration.processor.objectstore.adapter.name}") + private String adapter; + + @Bean + @Primary + public ObjectStoreAdapter objectStoreAdapter() { + if (adapter.equalsIgnoreCase(s3_Adapter)) + return new S3Adapter(); + else if (adapter.equalsIgnoreCase(swift_Adapter)) + return new SwiftAdapter(); + else + throw new UnsupportedOperationException("No adapter implementation found for configuration: registration.processor.objectstore.adapter.name"); + } + + @Bean + @Primary + public FileManager filemanager() { + return new FileManagerImpl(); + } + + @Bean + @Primary + public RegistrationProcessorRestClientService getRegistrationProcessorRestClientService() { + return new RegistrationProcessorRestClientServiceImpl(); + } + +} diff --git a/registration-processor/registration-processor-landing-zone/src/main/resources/bootstrap.properties b/registration-processor/registration-processor-landing-zone/src/main/resources/bootstrap.properties new file mode 100644 index 00000000000..34dba93bbd2 --- /dev/null +++ b/registration-processor/registration-processor-landing-zone/src/main/resources/bootstrap.properties @@ -0,0 +1,18 @@ +spring.cloud.config.uri=http://localhost:51000/config +spring.cloud.config.label=master +spring.application.name=application,registration-processor +spring.profiles.active=default +spring.cloud.config.name=registration-processor + +management.endpoints.web.exposure.include=refresh +#management.security.enabled=false +#disabling health check so that client doesnt try to load properties from sprint config server every +# 5 minutes (should not be done in production ) +health.config.enabled=false + +server.port=8098 +server.servlet.path=/registrationprocessor/v1/landingzone + + +#management.endpoint.health.show-details=always +#management.endpoints.web.exposure.include=info,health,refresh \ No newline at end of file diff --git a/registration-processor/registration-processor-landing-zone/src/test/java/io/mosip/registration/processor/RegistrationProcessorLandingZoneApplicationTests.java b/registration-processor/registration-processor-landing-zone/src/test/java/io/mosip/registration/processor/RegistrationProcessorLandingZoneApplicationTests.java new file mode 100644 index 00000000000..1ced139fc4b --- /dev/null +++ b/registration-processor/registration-processor-landing-zone/src/test/java/io/mosip/registration/processor/RegistrationProcessorLandingZoneApplicationTests.java @@ -0,0 +1,13 @@ +package io.mosip.registration.processor; + + +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class RegistrationProcessorLandingZoneApplicationTests { + +// @Test +// void contextLoads() { +// } + +} diff --git a/registration-processor/registration-processor-landing-zone/src/test/java/io/mosip/registration/processor/util/LandingZoneTest.java b/registration-processor/registration-processor-landing-zone/src/test/java/io/mosip/registration/processor/util/LandingZoneTest.java new file mode 100644 index 00000000000..616751eccce --- /dev/null +++ b/registration-processor/registration-processor-landing-zone/src/test/java/io/mosip/registration/processor/util/LandingZoneTest.java @@ -0,0 +1,74 @@ +package io.mosip.registration.processor.util; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyList; +import static org.mockito.ArgumentMatchers.anyString; + +import org.apache.commons.io.IOUtils; +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.cloud.context.config.annotation.RefreshScope; +import org.springframework.core.env.Environment; +import org.springframework.test.util.ReflectionTestUtils; + +import io.mosip.commons.khazana.spi.ObjectStoreAdapter; +import io.mosip.kernel.core.util.HMACUtils2; +import io.mosip.registration.processor.core.exception.ApisResourceAccessException; +import io.mosip.registration.processor.core.spi.restclient.RegistrationProcessorRestClientService; + + +@RefreshScope +@RunWith(PowerMockRunner.class) +@PowerMockIgnore({"com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "javax.management.*"}) +@PrepareForTest({ IOUtils.class, HMACUtils2.class}) +public class LandingZoneTest { + @InjectMocks + private LandingZone landingZone; + + @Mock + private ObjectStoreAdapter objectStoreAdapter; + + /** + * The sync registration service. + */ + @Mock + Environment env; + + @Mock + private RegistrationProcessorRestClientService registrationProcessorRestService; + + @Before + public void setup() throws ApisResourceAccessException { + ReflectionTestUtils.setField(landingZone, "extention", ".zip"); + ReflectionTestUtils.setField(landingZone, "landingZoneType", "ObjectStore"); + ReflectionTestUtils.setField(landingZone, "landingZoneAccount", "LandingZoneAccount"); + Mockito.when(env.getProperty(any())).thenReturn("/mnt/regproc/landing"); + + Mockito.when(registrationProcessorRestService.getApi( + any(), anyList(), anyString(), any(), any())).thenReturn(new byte[2]); + Mockito.when(objectStoreAdapter.putObject(any(), any(), any(), any(), any(), any())).thenReturn(true); + + } + @Test + public void movePacketsToObjectStoreTest() { + landingZone.movePacketsToObjectStore(); + }; + @Test + public void movePacketsToObjectStoreDMZServerFailuretest() throws ApisResourceAccessException { + Mockito.when(registrationProcessorRestService.getApi( + any(), anyList(), anyString(), any(), any())).thenReturn(null); + landingZone.movePacketsToObjectStore(); + }; + @Test + public void movePacketsToObjectStoreFailureTest() { + Mockito.when(objectStoreAdapter.putObject(any(), any(), any(), any(), any(), any())).thenReturn(false); + landingZone.movePacketsToObjectStore(); + }; +} diff --git a/registration-processor/registration-processor-landing-zone/src/test/resources/mnt/regproc/landing/10001101490000220211207095530-10001_10149-20211207095827.zip b/registration-processor/registration-processor-landing-zone/src/test/resources/mnt/regproc/landing/10001101490000220211207095530-10001_10149-20211207095827.zip new file mode 100644 index 0000000000000000000000000000000000000000..c054491124aadc1e499c792957851fe6fdb0a1e2 GIT binary patch literal 193014 zcmV(rK<>Y&;-deHHt{qB2Wj8}cFn8V<~ zjpkPm-es9-eQC_Qcq}NuTRBZX|G*If=_dqNORvh{Gv2sW1&{$P$y#r(&&Jz6+k<7n zY}){evevt>I1>B#^jxQ2k0I3#xJt;BkV-zKUuJ#UdC9jqjMdQJo|3w(79Bq#J63Uy zGeV@))~Y3aG@-w&eGQFSE2*V|AIuy^r|4ujrJd(I}Z7(2&)%dJL;U$B55JK zb}G+jD*xIiBQl@8J&el>?K~7Esx2q#y$8^trAZ$;Z;WBD;{N2U*iUdf2rqGvi<+fT zl6tYk$(KOuc9EGey4a`?^9Sq_nY?>;y&~SXVYy10IWfhusMupZ0U?0r{?ujdCnZw* z#>a^XQG$V6h|;alTy<{F_TpRr$h3}@tOSOKd@_pqvp8>2HE2VKH$7&RM!PrSrLirI z$8|~@3dn@`o==L=!32nO3YKr+z>y}1hIrq?`_sA!lzsyfMyX*(xg1-ODyFL#lJB8+ z(O&t3kjm|Q^b@(pagV(cbrg*Qns}?Szg1uR?AHcg{pmg1WqgrI0F}ZRaJ`GFh-$FC zJ&Oa)Z_L|A4ZASb3E_i~Uq1S`A%IkpR%Y4=!r-q8L644(-M0#E(Gin@z4Xl7ew4Pi zm^MFB3qB2Bb?u*Gc4KnK&x=WazMOs$-@#F4KV##@syVH~j2MI3I#gVfmmkZvaaF~E zY7LNS=L`l9dvlWI#sPs*D{pj>iLz*zSNh^2ygU8u}=%Db4$9!a{UYb;A!C0*QG%oH->w z&+yI(*<;G`$wcXARj`g#>RH(US7c1#k}!YI(u>?Cq6pa4(v7aGzW2r*!D_TVEWA+5 zj6)N$y1g=Q^3sR^0aY(|Y2wPn0DRk}*WVR^&K+=;!m!^QN_$OB?`j_a889brUoNo-f3}4sOfb~xU;5us zRx#INY~Xd1afs{{s;V|8PVjYu=5|;1&V`nV3-+-{(}54xVxiQfcUuJnB1`?Q5#{NI zFL2$KX>q;^WM;rpW4x4hV_SJix~^cq%oQM~tsj8BhXjf|Y;IuG=et!(q%Mw|!XR^> zuVballBJ91uI+8idQg>pPL?l@Xqm%YDu)`@LjBaF#K?*vqAkvoEKIL{e13fz`oVX6 z&?=2GLj9{J(G&s)PT&c%f?i1Mq$U4oqSRb`LjlE`G}RBsBQmg^0zh!RJx}0dDzs_@ zAsTwZrneJm>p3B|kNp?$Pd!E38)Y9P+z|L6%f32d_S(Fi7oQ?`3lvwZb3OH&)@k&T0~t;5==hI!{PTM zVJxf}nj;nfiEB-rGJi3BP-uK>K)WiE4m(&9iMoG&k7~$BtFMdvzO7k0d~O~=iMAdO zMI~?VLc|Np>#={3@SkpN(PjeNE@^qi*gAY=~m$2bv@T$%tqgB}=M$ zDX%Mb*KjP6)%mg5icgyb z*5R;iL=|OEBcEH(6nnok4E|7!@yX`V&Kl@Y$PTFu5Ewp-qTte~{ilJrjqI#IEgNwv z3YEsDjsj(}1Q29967u*cF~L75X+IW-#O+PZFPVVs0_;}BQA$pAj}0F--N&f(=3Q7E zC-zCx zY~9%|jCq?O%I9ew#-I|K5)s|Us^Jpx(@3iK^5x zXw`ArpGlH79CC49AUQ1%Zb)Ui?vS!vRn>km`PkDqF9!y4wXjO7#MJY785MQ?j0X5yW&bbOgyISP-lc|XwmJVh2u6NeSyIH z)zi1-fn3e|gswL`cG2dEWzip59-5~ZF(@C{)bmt52x9##>BPB^VeDCH%eHetgzKSEz0V}o%imGt&pfb9D5_m+ak zN?&q>fi_)@a$q3#_m^Ou|E9S|lv>xielH8aoFeDnh8y#MoaBc@^-Jg*3!c?gOw3eJ z?8%JW6cd5=p8&fu;htPXUHzqoV<_n5XE7 z`B2?vxC{pa_3y91i+S->0%QUlk2K`7J+vFp>^&+y(I1JurL)V`n7Fp&h&!b*|M_eI zrj8Qv;H2pFK+ij4vh2Rq&7n*%bU{FIy2(gu@B$D?7)B1{RDZ=cOW$Yc1WB(jQ#-#t z;vDDY3Bo>j0fVNhvh(Ovqwak5>=7m?iX}6oQs4fu5Y~0g&NC@VU6s2xowd~1dJN-D z$twiskFX>{sq{%L;{&@FychiP{c|tw8rzM`N&du!pGd0$G4B_9FCe7-9~xZ@5AeW{ z(hQ#!*zCJ%$(r7R>gP@MDtc{uHk=;1 zx}0n8UTm2g_0Kz}%LLNYp-BieiF{4=3WL?p(=4U*m}2X(lRg1>FyiEUJ`ZFBs)#IW zuh1fEv>{~>q*qahQJboa?{&e1Nn-g;u^YVYZ<-P#X7hG;*qipckn6stcpJ~dpZ)|t z7fPU9R4@wuJYm3<$$P`79;3Ct1k8Yx6CM-rgtkKc4w)65{d>F8`CyVzjM=N1l?Q_T zjFBje)PAvC?!kMNvCqkA_hPIHOo6fKO)44}Q7Iu{{+7wXn^iIjP>WtUy>`q}jAgil zegB1&81aikQrK$r=i^@8shN}EJpf;mH8uy6ax2Q3kBRHkDD-+H`|*53w?fQ}-m%s~ zk4{t5nAnzcHz7z}n?C28*p8`X)@I8e_P=6@B0Z2`F5Z9Me2v%|N*MTR=+dezO$VQx zFJuCB|4~c79;hI3Xf z9o%2;@kt!OQLdHb9Dmw&>d4@OZt-i=nbfOT0g|w}_V-fx6{>krL1q_)V{h^o**C&A zzJ@vE<|a4@f;bdP-+p=bIxPq?P(okS0EqV`$0q(_sGUq=Om25##h)YQ09~b%dMyW8swO)f~V-H z+O5E_R7%&5Fsoa#x1zsDVUql~l=QVieD{@s7V;Fbl*sXt@nPwZj~cK#PGK!~Vr)eB zQdsa~cm)#W_!!!@MHsH?PcxwDzYfFiDjG8OhYulo7#8nr=7**4usuj7*dwz(9STIv z(OeBT6>l0OH!>0J#6>Hg`0e5|$UfQxDd<@1u5Am2-~%-Mk~{#ibM7zZrBIZ#*w5I& zF<(TZU0^Kl#k#2791RP(lpsAfI@E>RYgKAt+a>$KqU)0`#SILEycF*ux78~#L|Miz z2bxo%p}n=vK#2&tejNS0geqvNV<3V-r3ij!n+w24;%0`8G;xpxrCgs7lrxB7#6l6r zVFUO(9_U=)$1Y+ipuEXT)o_keLv#HTP=#Agh>>BN?*)fi11Y#(Ei%MdE3^=q{ofhS ztf2doG0KW=eC|QEY`|(uGdg%GwB*Y%RddH+{kyC{m|xcz-s8(~A8{)(uUz?kvVYRj z6@m{CRV^a6GXgLN`*af3)s*1f_kKBQT?vid6jMObQGcLrcO73=(BU?P=ELO{_ z#B8|16|$I5aj2Thwqa)i+e>eX3&5%C{$lNKP`Nl`scq3s<>e$jmkUnPj98Kgv4Z6PeLnHziTgd8z37Q%`_>{c~~!F?N>A(#F0YQGMgO z--H=RTj(PYj1KdI_79V0c z3F%)0SUVJOS-&$AY}djiilXA$&n0~q%M#XQNQu)Ucj~kU+Q}kogXK{5dDGG$`d zL6o^M%71Uc9kHaSS22ygTiWr-7vYl+CO|Ee__g0%4)a?`xWqFdG6uPqxyhza2*iSF2F$c{~z^CUKpe;`d#JQ~ps>DK2; zC%BDIAFQ^u1UVqKysE}IY%RSYR4^Zlp$%k4OFibt1BT|rI>L~6LEvh5pQLNabL^tt z`I>W)WvUXUjHn&ed9OIYeIx7`*i8}c%XU0d{O=vzW}uS7nG{Zz>sN0nh!UzRs72M!d@mks|dL%BdaT#Q6JB zEU%dFDI&^Rfz!s7t3#CiPhv!s?$}u2pvWBo+>BL&Ysq2ixFQ0bC%^R`Wvk1}@3=tJ z9H_2=apU*fU9sMqGHBPo#(=>F2?f9gt9$N7UQtmy;U@4bO_Y>N7@sy#@$kBSeTDi4JQYYq;WSrkfof>NkRK-w&*HtU zSR#C-=^$5jjmoK}M~7d^Xasbgg>JptX493cM`7e%MN+PvGywMueM7r={>5f~TlPDg1r2hsJV6MfwmC8x_`jxaI3wwA*!zb+TCEco_VNSkSi1-c9 z+Gbu)VRai&;!06&!byrGP@D#nMH1s*ra6v(!k^9AGLfA7lR4{E7Ck3AO40Qx znP9{ZGZ;-3G?mE;6~(e>mYAcRh&J_Ki=Mgo9O4`}8nx!-_yaS+{wkYj7O#hG>(i-< z2ZrTu>ZERJ$D+eI2tqc`r6^@j{E3jlEb^76SSbJY4x6!_!H+Bkj{Jq_goNrX@|Q}u zmwgC?-3?a1Xyxum8)N{)TT~>t_B*%Cv4ihqmvHEk>FT{4CG!^~?mwYeGKQ^qY}ekn zqT+1VleNC8G<@nB(A66ziF%n=83{1#)#^3UysTmHCH3J&vU0>7lcrj9bTi1;ZM;9|68VCz+ASgc zhk|LC3FIK*NA(oP0ZZ7VH1s3h^ytPmJ!S1+>w}2q7R=At)BhaYq*c^251T}7pkR<{ zO{09Rz{wrgM@_(%^Rz5^{Q~DENv{;a>>#88& zG}+yMMJ6XXOuvWzhteKs)4IlDj~RGi_{8WTHtxTjLKhlIFCACxQ~gd zsUJ)hnaDloCO>a9=e(@-Y!^oBgAiet_?-@)eXv>r3%~sIxMrHE3mTDAFRHI*sI?qh z%0)cr6I-RKD(46caK4)OwsX{*z;q@%ZHVhd5PDb$Y#YIwoAWiq_1AS7vplj#-ofE6 zE_TzfygzB6cVg$PjG44mSIhhDj4I4dmrLXyb~Ww8dzcL^cB_NVrk~$f26gT5K!H9p zDJ)HHOHKQjfeSR0M*b@8Cl_g>X-i<>%Z^vKKVe)f7(dBY`FapG9PvHd`Q<|n0H)D< zGN)(+Z38vI_UE9-Geh!?_G6fI0I{3@>;l3B%KdyR%=Zz|@%j6-3_IzLtypYhw8 z%gDY<4@CZV{oBc09!R*Gwr_FIEz5WcnRLLao|dw8_rAem{Ax9DT<DL5Xo%Opf){Zk0%=B`>>Y7dsr zh5zpl1#I83z_US?+&A!bJM%@>x%^S1lym%j?!=`hy4d8_+X&j=8NPg^F=Y6|(`eWZ z9?C6O8j=^_r?K-kJ{H(*(}cVCK3Ml{Qi*dry<-pCOc!88=*h37DMrpSh2&{G0@=t5 z*(2;=wpUX*#(?-DEZed&j8G@F<2c8dy2rSfR#%jAYiv4LG=K!5+b8G_R{y=)B5w+{ z2WHm%WRVg<{&TXkp_o*{U|V*;8mz1hoZtTeQkI}|kh$8Pd~uxCpS72Zqd?zUZ|JnSp~fCT-AC% zt-=8nR;iVS){V>i1`F3PWFia50Wt0-d^fh>{d8V zq@pH+N^Ope+@M-d{MY&^GIt}KKxbsob48*3yS$E#R($7@+>M9C41*{6#pRtw`qo6Z}0T??OyR)FDSJ~2rI69uKuzY%DF(?e4SezQfei&L4!mG;;1y5uqEvO+49gx&R zH`6!mQd4ZQ6{F{hy?ne{Zyyo#!gh0olhE|JtR3Q=-h}LxuA^6n13DS`uemWWzA>kc z-cB%1<;8;LTZEAsygC+d70soTKwq08$_|5V^#?OU=3k9_h>zR*s zLyr%cfkhsnFWs%CxT5-7qypyvPsuR(HvuF>04L0-H-};MfQ#)CZ6T7%g}*e}2%NpO z;9Rn;InTW(lWEJFbL1G*W^J~pym+u71cnzDil?%RT-hg5yFrxS&OVmuc?~yNvE=>2{!& zDdyJ~vdw_Gu@@P{5Bpy+b#7&K>@QPyRd?!Cn-Roax%${_LoUjw79}O1iW*gRM}$?x za%Z>W-1i+!T2Or-g4^k?Q>*KRHJA6;v$PS=!{n#C*zBiTlh7Z&i^}1++giT)B3p|I zA($H5)cK}Elk6LgD1=h+eUaES?)lA!4!(?hq=akj37aaFR6B7kC5PMtBYuN-OQ!>F z{s6WfR0FBueyhy7ha>A&GpVu%@TK>Ym@1c5rm9OnvxCk>nmMjE3ln?@nAeChK#e@V zf-q;|)<+q?QV)f_X$($}OK~y&42cwl6AkwY9n0FVLtA-v?EK)1xxD0vU;kR?#^M%r zXbwWZ8K*xYQ^k*hgAWeWtloE_ACv8Z6EXnhX-t;j9-U_KGvjk;ZYVGqAkgXJ`m7&X zS@@3@pX?9z-yKy4E$I6cHjU3c1waIfF8w#Y@m$d_P@nYc?^NdR-g|Sq-BIK~bWni6 zrc@HYcN=!@?MtX1vTeml%^Q=#$Kza*{-1j~#5RhR5qoDV#&tAja;km@xgX6Gew>zw zCOzv;N25%dj#;Z$0!gt3xw;1D1EeS8fj(4zEnt?y&9>fnmW+;J8}75y1wzn0=R+kG zk(k1)Jc`c}%gN`V!Zr83iSMSPkl{+k69o;|IICIuwU%B@u%~*rH;1DwlV<_X$M>$Uo4dLZw5+LS&PLz z@^2$)+5%_37nAkPB-7X7ezISE;wh0Ak%K z@BUc{|0a`sSuku5W6>)0I6!fKYbUV!&?ophHA3Os;5rK-P@t@0K;UyYD=-|QtA8dJ z>Pq)(Wa7PC-#q0sKKmUOue}sLOg$LzFDiD#U}fqaW|>5-IQonJW+OD!jKe^Jtj11! zd5e76vgPD0FZb2O~`WxOHak#(r7!JEXzE&wHA^Z?2^qr_GTa`##{TGQDMbr7q2M4DKBY&@jQg4UNCb6CYkqcG|)+h_9O2)lu+eksEsdDj{iI~t?7Xg7O*;> zzocro_7qaeNC6MA4hizi%h6U{X4-iYRYj|dkr&tM9_bKI|AmeuluxI;$V-3Hjp|^z zA#@|XlKNI9Y;le7ql(wViDtY&eUd)%xAY-^%yd*JUglx4DK~!|WNT67sQZ`O$drdq z4+C(Fnik|vWr4j5zMBVMgO{YyhL_Pl_1_;9e}+?_gYgud=t|m^lVlk(8)!qwV>+Pm zKlKmIiTRrkr#^x2#E?yxgV_h0Ygi_o$t9wyd{sZ&D#p+1Fix$db5=7lkR}#Ojmf-*+4NM(?uf`zq|{{ zl$LH;S}1TXhourZyfSBAr6Hn*SlVKmi2D>Y=7wZ^N2!(h3S!aT&vJvy1n2Dy*MaBJ;^R&e$}CC zeI*VZPN_A zc-iURQ=Z~zfw(MVS$BcOr1vPH#nY)}znw=F?-@Z@ke)K&g8YOh613Aky_84D#BNp)AQi54_7(I^@M z?VG4*CrCR45M&lXG{feD0D~F+heMXY#NAt>VyPKczAy(Fs6fP%iQC66O7~KK%MCy` zDL8CA#W+cEXCfk4o?vF84T1*Gu0idKbZA~U9Qu7Y6K2RI!AL6L#ia=88^iKEQLu8a z_i7X_Fl%+MWFCU0HjI6DrNdcN&nKjU{TOVxp?OeGr{cFu%-F3gq?fT7Of3scv1T%O zLukdN^z*hA?UeBuc8^uqL!|9lZFQ!=Ug_O3UuoC^=E|O zfXGT(A7+pgISd1tKziDAG%Us>bVdC?^t2t+s$deB4E8Cqh`Ne zmf5@(e;mS_MO2EtN@_9h(v{XtI(1(1q~S9vzcSk?F9lAjBT&_n+&8RRbZ+#@94ydD z>ezIkusg$rl@#kbKWahz#!Mf68-gG)K#0dP6hz8&$sKmk4$ojtfo5QtI11||P#le! zI?FzCCfS>NRt?p2dyBQ4#}1(D8;_>u3SO(Ip-2g?TPiOBqF3-^fuix76WI$R9^{~A zIF-(1g9{#=QzAARaq1ArhU3qV;yl22iucfydr6sR?0g3jW0A7>z#|w(4);q4wL?xN z(=~>3d=k9QUPn)YqIp&)G&|BY>Xqu~>&eJO2!6QW-i(L4g1awo4Glb#R^NEK(FM6m z4m}2SL(aXG1Iv4W9!$aM8t3_=3VPLc9cFR|>!N^=xe&++{~8U)KRoB7N#9|(yQc&- zpZ)07luWb_a*?kggD*zusseyUc$Z*Ka=PH!IPjsCFHRk|#+_vFntA0Fyq{j5%@K4Qyf?Bl$9 z>3K_BNBRE(3<8Rym)T%qPK9#CnR#gTbIGeLWvwQ6>~{SDP@AA}sCuAwSN%~tRvC2x zgT%0N2Kv$w&q!4$j_vC6xnsM!kuCF8!Iry4Je9a zy7Ov3;VsIP+6D{B2IUFmfD2?I@9p37#MhTWHxETK?+naXHBLySO8c$xk0u7n24FSo z0`QQ>`pZ^wRLwqO^u+P2zClIs?sXm9kd{Uh>B$@_Wu}a`ksVvhnzNp+TdOlp;24!T zK7N9Zoe732b)Sw$CJ!(;E1dm{8VmY{-!7kxt|kgfMI;zI{hIQT*cFs`Ude2%J5a_7 z+=y!UHgv=_!de%Db7mZa7~($X(QBN%M;*FDlAdrQY&n@?#wTZ<6cQ{kc+wwPCP?8V zmmb4KkL2=htbbIe3-Hj{c4FBJv1|Q9!EQJcWlPb66UXF~8(h0*o)(=wzS+P(gfDsXv$jX~nVFgWcH;&#t*DUc zIFO#IC|XZa!_U)VRY)7l$I1JvxGbeKs~%4TaJlTxD#Y0^iA@?#Y6#7CX6FME=sz}E*Hu==m^@}Y>#?r1#{v}gS$f7{LBDP2M*SR4@Xkf`Fd9vat*p^>gp@s9TrsO6mzkU~_aNmIKOW+;{!Xj& zOQLC!-BoPp6sF0KZ&({tZg!9|G^9>aiSs0jmj{?fqV6I*KQ@swEVb*$ru3XmJ4DYF zE5WN-JuN8He(-bQdAe%0Q`}yAhv_fF;@@(V0uEUv%$_-uD|}*xyEEAFmLA;0v<&0~(sUanI*4w_FS`Wg5&HT_bu>A`{5L3H6fYz0S!BYP9smJ@$o*ArVK z)=kqP2#(Ov!%{VN_-)of#OHwyvT-mWgCAh~g@}FSm&)Xw=Y&T%wcd7flKH@XU`(x| z{6V_nJ!-QpNruAh-VwZ*+WoVqkX_YE-dxVlj179kuJ^ZouZjGbM-fG!qHdOQq|i>| zzpl>aWH_`@DLN;i(s3YV-!EGp*vwl$*_y{9(&c!2#3!*vJNx{6pW&(1PPgM(El@R% zhJ54i_NxEE5Xud_v9NWOox4T75zXyle~`tkr^lr5%*G|iz{R*N=iTUmv_1Ql&@FYG z#TSb}54uE4jEkRR9_*bFF5{<@WdlLx;M;8akc{7PKh4IQsdcnqfPf;bjM&o-cbHeC zl$!)#grWvXC*E5`1MaI%^a9h{(uwuk9DFBPYK_ytrn*RUH!jDP2x2mb$7|vQP%3uP zBh+4WU^PH(JiqO*>mn#muIOg7-c9 z;IU>B!+Ly}FU;ttxWC+3PoufZQN)0K3DFm!3G(#iNvYyMT@vb%YmRjw_Nqme#$<>O z%=kA4IDB`OB~jMGGK^o?U$1MJ)cwhGtaa+691lo}GKeUAQq%Rq;u{LeZcreHpr|2t zyi%F2E9tWz{_3f*T5ycWOv(=rMkgz_!o^{xX zM|fcJQhJUU=}%Objcuj0EW~MQ7mdS0hast7lmH+r6BHPe&dF<@i_<4qg|#S355Q4v zEwf~sHQsztpM*4@!A+)I6vhN{^EF`GXnmFM!4rQmev$nL6a2oAVXB@?NhLXMEV!}Vg2ymkR_N7k|FT?F=CMW<=ZxTp|F0g$>IU-4z03$GwXSb${^0{1W~x#V0}yn3}ps z&WFkFG}JD2B|4e(z>&J1fnb&zCcgtXaE zc#B`ycJ6h9rYF@z`5GlhY%NEB)e}5#H z0m%Ff1K!R}Ve)mVlFm zS?rdaZ{v5`Zy&=h_`OSEZ`m&}*L_43GRjuovtje9(BBToJ0WTke9Kfq=(!~s8%5@D zpUl}>+`i$(OV?}t$iJUu1vUYrsw$YKSjfBHn8nS~fPj9pH0RtaO}aTgWbmifRnRx=PqoE8eKb0TEm3rmtSC?Dlb z8BO_BdCR{`m>xMGnO+5?F*#V&E81}fR`uks5b&M zsfXmMta2V*G7Tc`jR3W1Dk$yGgt*4Ro0EaiQEC|4A<gX`8fDrKID<5suh znE*v4fM}9TI~6y9Vb?FYH$ZnxuC5?$434fJLOnGh z$O1G*fih377O9~zkyXKYB1MUibQ|L=x!8C+{b5JWTweZU{i&Zt1Piu3;J&04ZLktS zmyt;EW`+NSz8X>Tw%D0t*z;rRQI3crcsmpqx6q%1Z$M)oZkaDPPt2)gu0Z%=BlBcX z1w!PZYST228m0;~lJ<6?Wi%O$4sP1&wg_qBy0shD!45&UHmvCKHEX!_EJEj?V@;Gp zw=)dQ269A|hsVE^^un!oJX#l?SE{A#ULrXW7_eV9RxZ966p3g4 zqh*d7pu#huE3f%iEO|1})Gs)N(CdZN;S4w|ygMPD)~!uoLH0p13Y`tsDWN}6{lke< z^B;?yNDQoG$pt@(n@gZj?kHa!;rjagiO&e&0=P24Qa#swuR9Jm|$CPo+slCO+K zKE^ga59Y3AhhrrAqE|Bo@E5pt4s&{_$y2ZL7eZ1rvO7ykEzN&NTYfS69N5+LBA zf$p4#R+CD=6mQq!sK7H%xbfX11OEpSxPM86P@^(J4q}Gc%w+crNDvUr(vLM3a6#n* z97-0HW%^uZOksyCh|(W!?{!6rm2>TxX<}dUn^&7uPDYK;DYI)ZsU%`-zZiO)3V}U* z1eg3U;O171833v^2U|2)kY{Jb=6|C8g4CaDL(u9mbxkN03y=qN%vP7dXzJuLV8ot` zc?Q3E#f!Y}*K)B4f@9^?Intm&Jq0D&^T}J)#`}0SlYJEQ635eaEos{j2x<9q?#N6f z4ymvqx-$lm(@}t(iwHy!$FY4O5f!3|C55K0W(kpBgIFRTPQMX13gf2%sOXLOy4rpl zs2*uMR~msU-y`pq$GJ^znSw`Kk305!>(CBwGgrwfP4;6dUIG)KQ=~#EXqhP&vt>1> zoEn2!1PyK`EbYUzdas@<0Pr5LV$Nb<1~wT97Qy9fwE`pw#1yZNWvUDvoK?c z+6Mf)^RdBgcnfg`&yKSTH(}r$T1oatQyKg^8i0M*9k1A6>(&mYdtN-DU5-@XX)l~E zY*%Tk>oJ=QAVVc6JP7=WlsF@JXv2?KYok7Bwv!>2N^UYQqqmtB$q^~%5Tz>^NWX3^ z@OtrbCC|hf0hJ~BHPoH9f#12B@qvwQTe|mpg_cp{Dec4(Bkp_CVrjJO<>pJoPxlSb z%;i(QL|ZLY(}Few;I%~O3wY>EmFhG}+}O_ch*1w~D4?-}v<&F<6?4r*G4sZ9qZdzt zq0G#JE4m|`#Z)_SY#(V05&$Mw@@3$ag73uYLl*k+4s5DBnR{AS$f!=>i@o|`Bu=>P zPS1-}f+B-1svl4b+3Dt`<=Qw>rsDhmUoKs}-TB#Yy_S|U+@{1GL$1)32n&1Ccc@PB7 zrLPcE$~d$9z7?61qbcgiip130tA>w>*Cj48r}^y54|z^$bi)cVT_eU#OY93~+tOc9 zw8_Rf2dR650>VHe`Yk%M-y!pB#HMyG2aw{WowtCbhwfk5$Bb!hy7u;+{t?s${T4Lm zLJDfI-kXJE_!VRv!j(=(LLS!xpB628o18pfBW5&MN1gdq$4Whw8^_Hypp=Sgw22HU zVlmgK!2o{aXqWQUVcLIPkC4O9DgZ`E>z+vW;+KEE0{D_`T#kN9@R&3&^*izK;0(|T zcM&$TMzV{ChabUNVqL-bFt3>hk*5;1*LuJGq3BZ`S@vx`nZTF-}QgII(x!?J|6& zLd$Mjk1stiUsu_OzP1idHIPc@<$EZ%OqLmrGzzv%qaOX9Xg0PJDYX18yCawaH9&}@ z=B8Xj10#3T_3n$pNw`ymolaC+U$ssmf|ELIe6eVU%e8MkqOjGXchv}uwl?X6Ocb+% z)SzquX%3^m7&gx@n+?IKNe?j1cgjKisIvfm|MF#m$NEM_MO$KzV}|Gq!z-Z155@Qt zx=ooswJwFN`rOFJlqA*$X|1Ei^^x^Pldo~FEfs{Y(~^Z+<|)m&>Vzp%lgnD_9@w#d&^^wk#wR=6XIYEaXy}7xkWt*%B7k)&%C6e~=f^sjdbS3GfpRe&8c)ycW zM2xNTprA%)!ki=P;bEh@ck^Mr`=VNlr`I!w(<#K}Ep~|?p&^oa1k;I)Gy>^yY&JETlh^)xjB0I{ov%LxkBQG9soi|#*H zGt^Dn@vZBHIq-0Y!HFR&`1i<{V5Xo2=Wd8^J)sZVHh8ijuAhyM2(dA}^al3@7CR}8 zb3kG+F+wd%lp`WJrpZk3~ z5}@~H(CfYB6bF$BWb8uiE>{?DTI@bqzR1OatQrypCO3rYlG!II@d{hJMsHu9kbCC% z*25)y&b#{*^8X+$xr{;lC+XejF?Tut`m-X13FBaeQ7A*l%dtKX4VAfLddZM}dE^VY zzN%w)ei}4$>Z9V=@2{X~(1qyAX!l&Vi2vIn?vv{(QP$D?*-kliq&n>^8F4fE!IUUs zx>g`TxVacGK{mSXw;Cd3|vkrFZ$HF&J%^yy)+pO4Lt=`QH~4|Nw+AUIwm6TNX+cPylj_8UJF4c!Mj!^u?Ws3o`T5M7;r_T6l5L~ zo@l77>;xf$EpIBSQ-FeL7}n;e?3<0vSZctCRstbRFuK27KyU!3Phda#PHQ*JQpAJpekhMn}pOcpStr432w=VrVaXf^2%j|Z}Kcs1ZwpQ6YWKd#;o&kSHV z%N_>cVf3;tclxB&|NmD|Lcgsnin29a*bqtP3#}dYAkf9xt$Y+ehx*Egk3T*|#{?M^ zN6%j!Pb1CWBfC6{ib~PM;6DjYB=LZ zNrh~nIE19ctAIy~ue*}Ozu0d_I_e}YMO@xE05?F$zcmdXH7o;UGRQr#gH19agE=6w zZ}VRd{G^(d#24*Lj`GNgw0^Bj@V!)KLEXsJl1+Eailw|hos5U~mNqB!L z5$%KvIi(zLD<$6!iOPv#hE!Pm=It#0cNzZZPxD6wfs9@YHlI)Xh=3{&2XS|&H=}(? z+iVi^CzDk42zKol!5+aZQ!ooSMzSu?;0FGf8$xSOiL|h&IyG8%jz6 z%it!vTN|yY)UU13XRHRQ__qP>8Jbe~IULqS1^2~|OO8#yIVqR1Y$ntJ8NGa7mnABl z%ZEs8sQDvLYwIj&qNME#JJpiIRlf7Sxtn;?_nBwv?E_Ncz3Yl&*ub?M)&t0$iEp%1 zMDt0J-9w(z-ryGt>?=SvR_%ham5dBXTu&v<+mpK|&PGe#^-F)j%-jP%*NoO4LHF#XVJt z!%nYmfRhgaz5z3gU|M@;@g^Y^c0=?i8}2^*HO&Qy_5$WKU|Vop8e?F`bmf2W-VO!`}xm-3?DsRW`lEbgUSb0zbG(Gw;&ol=TPbIL3c{qx*oO3Unnt3W~ZMr6d71toE$bHzAJV zF?6W&XJMs!d9M7SRx&9%3krbBQbmXuk9?b>b+6omI%h`DFnEN}5Bg)`BuM5#D9mze z+1iU4^9T)B`)}&s6i3O}^uUKMx_$>FoQzQT$8mo_XJ+tCy9780pp)q?sc6e@!~8E+ zSv{kS5|5%?Q9s1s^2g%Ayj$`UUB8+N6;hoLz6=F+1$nuc{4^4bHC5d~UoVQ#t!V&h z(S~G>fKYUvzHP|49*qynuy%1a-#dE@m`Hq>b3(IQKICpLpY)8EHcP;zbi%hI~ zxV>ByrkvxT^YPaYHsrdCFjSk9>&@{XCSe$4z>-{)kRn8VW*kk0m;h6;UA_XO!$7?< z9kz!*lXge~4>`7V35rFAnn^M_lQSGn(4@W3_^Db}4H-sfFk`Blgts2Pj{ZvN;Px2i zx=*wL=)g|uPG59wcf>QNFHSN-&Yz8WCAD{9#)gb*34UQjdjz~3_l7~@B~%^np@$LU ztOfh94#Vjb+=|W+(u+b-M5Kl)Wgee}Q zR()_rP!iR$ez-r8QlXy?`WG_#Cj2>^Y$8b$Q#{HrIVDX!co5mJ)+u2}LjY3a3sRRg zjaTSlf7oj#C9lS@7U(ye))f?L$x;zw74mYk2~Ya4bowTE29W!48pt^4w-tDtGr?88 zR>nSiAN^nedi_%Z%o@JRx<`ojCaPpGf#B#6O?%sgwYacx5ydEKD6x2Vjyv_*4LL0h#^sL+S70OOew<&1($dTpV9! zVZQuk>Vc+0j>RD0dJDsg-au@9N|$g<<-eV2K~LQt8d{VIlg32zagh ziL1pXM5!U1F-vnKSM@V*I220L&Yd>EPaO^BbMd#On#>0nXlEt8R@Ky~m_r(Ah>n<3 z?nddMzS|R2i%#XZhjG;0O1BgxDRFnPI*#RAEeBj6WfJzOu=k3x=-D4cl@YxNSK*7X zcP=PD>EjtQb$0|zJb*#iN&J9uva_^kuFSG#Y4@l-UH^&5FkyN+)UgVmm(?v&A0yP? z;59WN0tg(b?oE)KG3lV3X`r;@WNihXo)Ln(0l6)KiCfOjQWS`7?|+$ z{K6?=`tVp?YA*x!dYX&`)EM4?Koip*k_dv>RKLBR&Mu4~35Wphm%rALIIauJ3xo}S zh3F{2OC0*sfEj}_#uQ|Is7ez(IB6#C4lzy08j?>np>D~Ke{5so7R7tdGQtL!tzcrr zi7m0k4{%Oi9?>;YeM#Em#C2Z&z{kRxNo$pRoB)3~jl|9MoCL3CbR&0!fFDjoZRG$J zDA!0E0QNwiE-hFxeiloRD|a7sl(FA+^5RH^K0b`ODqpWl+-YrDC`Zn{JbEzpSwlw*RaEU zO-`*y6*Oaw_iUE9Xz_6vPcLmA%rChnz~Q<+ITc_zU^IQa$@M)+9w*B8# zlp>Uwc*dQgQsJlJq8>{85#eW}EyE92Hn+PQ7d{qvD+wNK0qLHt3qE7_&`5!_m%-^c3*LS?3M2s17i->Z@EVtmFx2wQ(Zq|Ccsc%SsSqeKJp zesRU<28d~!)*Hi8RvjA1ih@wHG!$ z=$~$dGgxvZy7HIrjbAGwy9aqquC2LU<{A&M;QFpw^l#9Bz|teJf#NF_;EOtqyo6f3 zMCx(WsThpGSCZ4Rt&!Mzm+Nv3YzQSa@^XQlecaFsxlNO`!)*H~1_@44WVHO(b7d2V zK1+!bYOyi;zMMTVN^T`@n>rlTg4&9?+d9%;K|TCK6d2I09c7) z?`DhTxTCK#%;X%{I%nye!k~G#Ake=ptcxeo`o4vuzflV<^SobB3JM5N`S7Y+LvB6o9RIfj+|2^8YB=GL^>$ry`Oz!5gwji1&soFK} zlh7HkNIvYkYuM){r*auf!G8|Z-MG_<*-EsbpES}j^msl{nA~u$%Zb-GLG`lmqTv%X z=gNPRMXe2&&xKT)=@u!7aXQ}!-Qg;k2L5Ntrt~}R5&B;dmvuoPu0Hk0a+(hvNR+y1 z(4YV|vRTN(&ZmGt}9M5Mg31mj;XtGo!1V>-Dvo(G%QV1NLeBeWpEACVt3{#QV0mBWL*cTx1(SnN-1R>HK~l& zTK^EGg#Y#H{$$AhF`NIyx%VF`^P?as%BL=#9tH=Zs`2>so#-bCG7w|2CHAcYV3GG; zSz^he@+pcqr+-ox_V@g+?T(_#dX9lK4J5i}5q0WGKl(RtCCQa#8Mk4U)+$IBO7p?O zP+`v-?tEVCITui5SWjV-E?5Nq(cW($Y`XA>cg2Gt-xlu#gmAC*C+(<_!)vei`0r>K z8l(L60I9^^5_5yWx!`Ho;A$GhFAQ|ZAvJ5orqw(`wR=RTcdO`MXzDvR&oWD1%?W@{ z<^R~L3Jf4L%#U9xw;t%hK!lX+#2+80dhxDzm*>%^-$wzoFP#vtl@{|qCJWN$#tJ~- z6B}ClqM+8aI=)y3qiM?cO7|6dqM+ZS^f8wwicc5wI_B#9;LK_PK!@!hgzfg`f?t^S z%p$xL^ScDOUaQ&g^l^to9r-FGKN*TGI&zb=Ed?abnUP4`vd4wMst<1I!hOU)|K>{1 zM9-BKJ6yjq393hyQ3tdKw>vMwO{z-(H!Z#p)XkmZgsSkt$2;iAeRxqu4~z1#QqT};y8kXtze1V&cXdB#X@P0No#!gdj6pvA{ z>H7L*`+MwsCQDirW$g1+0B@UzoQ61`3fKsmEcPnCH7pa&uZ2-F;7G+(UIH+0TrQIx z)0bsBBpX2Mneo3fi8R@Ku8A0?8s4CDxL@MObjBK!MdU@9!(}`#@nCeV^fparRtX|Yw5}=XD01y;9jX!Fvzg9{ z@z_sAx8<{lkW#C2k8U;Y&~Be!n`#-1Rc1%u@Ofg9XE&JtCQS>hh4mSa$Rc3J1#PUO zlh>?n0Lv_xey0GqzhJO%C$+upo{0Z!Wa}m)&&8m&(Z`U=9SacQ&3HrM4&x28N!-M3 z+_9j3hsX~>&$#dk|9C;uIiCeY8%E}TOMoG#sZ}&a8CR;Q;=`P{v2)R}nxyaO4(SBVxw@sJewoab6@1*G8*Ebr}UFQuvd)M@T+R4}}M8 zXJlE8DPsk#`W5qw@#SqfUpgN>mLRNS+wY?_uky-uTpu^dg0#Djp70L-|Mzoam#eJo zD+qX(P$Nb+onYFY)&ZS-L(wJ}Dl7o2nkqKoG-kQiZfXa?5_ep{kG)*f7zKO9d&Kv7 zZe~rO#w`UVn{P6_T+obz&p+pqT4H=VT)n}!Z7Ks^BrL?ot{CyjB3(**7;ZPx394aX z%Lh*jBxhn@=$8z5s})Az$c%BbYz2SIi-x43afAy)mu^*}{Z?p+DO~@*zubl9wE>4x zM_O5vsiJT&OTjz)--htFQmJ~=O4=(f#|T2=k7~MAiphISS`Mr($u#)}U=u;k)ZH1k zV|+amARW)46{W8B6d8jJd~cjwyU&l&>&-00fVuaaArRV0tco%Lr$+w%Kqwr=lIVd> zsuG)iuFIP41T&aRG7Yz_gX2wD5sJv)pdt$?K-W3xEM~D6S(B1 zoVb`G;X-3`?<_Qj+L!TH1RNZnM%9#rZA2As+M?HI<|FCgbni&b#wwWon;NfQ??Dhy zlK1?Eyu>$*eAiWgkHBcbk}SSDKj{1%_0n;Z7t@+eX2Y2l^@=Z4vH2>_3*=${9-bP` ziBshCHKAm>5Mj3g!ob_I6wPK=M6Fc|Oy)LjNbOP(fUE@=th6r;qhbPFJbweG+2^*8 ze0_Sqd)Hlmw5KMpML#cr&fpO9t0?u%eEJ6dH$!R}WPn08CG?O}GwjCP;0C24M)^QEL zivR4Y)@KP+ZTY>L$qf#+VWnRm3zw3SlU@5-k7F6m*L!NU+sx(xALUH@{$Ic2!Rxj? z()BJhD3vwUcyIz;7kLB9?N*$7B?7Lo zNR?`^x549&GG|`3TIGs{)VNDG^EYZ9(ff>II!LV^lAS<-_%>z!Y1=UrwjmvVp%(tf zUzRB?b!~6&vi!0Bz-#{JveS%0iBW?edH5{czs|ZJh!wo&c@k&$&e=!T0*K=PsTyG5 zsjvx}bs<1zqMmJj;!jrV7(n2Cyg!G?KGTe3{1Cj!9JzzXmj|}d?x`jORs8K-HrvCV zz_Tch7Hmeky`$sT)1Z1S3Wi-699~wP$MY{K5EQ`35UucQ_A@Jqs`XSf8ijR6bi3^8nZIrT0am!^dj zn(CP5D8J5GvqiRZnNo5=&qTwj{}vNJ zf4`_pSe4a{7Ad`fF3yWr53LYb0e*(RL2#*qU>^WA8r z#tqj!1KWPQ9t}pXF}I{!`6yCh-G=s(OTKu9V%}(Clum=*({%2&hO&3BypTDnFh61A z*vk|ZCbiWH4LvC=b+_jRlh80teV;_az~3!nSn@)idAYItBDVeRgzXAD2!@m5|=4JS7T0s5(n1c4|#R}2llQ+Mk6{8Ubt|XXKK-&adLO(_Mb(zE)EN% zMT)QMU%?f|*iN)$kr;TO*drj=rSUR0-d&gN)JQAR3 z+fj@4)gVv9^+JTYojFR|6r=OgqlKNK)Po}zHhJw4*4yG{iicws9o4W^D#u5&zG?|0 z{4izWA3a=HEI!8roU?4O3p;LoI>$euIi=SH&nhHaUEatoBjDt27P_9|nQ{9+ju8P( zndT1C|$w|lZwNnP}%;<(cuQjaV#vt$DVru0n0Uno8*6+@z!tL_-DW$WB}BAC7KzC zqT3N&DVl2$rU;L!NTwZEn6VFK+`#>;+x)Umqx&m_;y_+003GoM+f9Ma9d4~wdWwc6 z{=PlAx;L1B5*A`(*F-E0=3F=WGs=HY11hNj52+(WXpvR@(LLi_YCvYJhy)q=!~PFF zh0ifetn_~=?uy1B<&Kx2KlpYpz9Y^*T43C+!V<|qSD>eWhf_y;2#>Z37z32zt3B?v zRe}iAE4?066odl~Nipqk5yv>FZFMuUG9j`1eK!?Y@%5G zQzMmRzsx3f;`N2nO!ho z_7lmQW^Wh-AWQi8y{anS+eZT0KCUf3c#EitA{F1Tw%L|NtZXZ+g-+qblJ>Ftwk?ju z^J>s;y7xm}1;HrjN-ww73%(jL5b!q8-5#XeL=4^gak-OTIN16LDGr91`Y$rVj0l=l zTE9*2$~~ye?wJ4R?$%SG_$OMl^G+?JgrOcet^mSst2DH;<7AYBIZc*}sa`2vl|2lR zX1#=vTuToxf69p*P(0I#m%8&-q_$+)F`o=*J1kWU_77Hy-7T^@U9<$^%^vQ*ZRzrT zS>4>;*1C*@GJ?;d-TTmp2a*o*MXY?$4pxn=IN{*JYCj_KYnR(epsl)4*RL_en@~kO z67`G(i|Pg)yqUt!wtT^d^c&du0>J8o#Gva*$6BDR-Gyo{u~@7U5bXByMog$eCl0Wa zuK?%Q|L|PKW<`S&cZsDCw@kIfA3k6s^-n-Xc2#4jb$QvyFffx>g~I#S=syHP&`qBhnur3ZBCle8W(+*?+ds7&6X4*e9DP=4aOrcnsQeU&9$VGq1e$NEq4U( zU5d8r)2YKqxg4bnpdB$byEz-?eEyp^q|8H9{kWQqL*G=1o$n9-5UPx>nz-*vYEUQm3h_VvgE=b4t&y^hJ ziqUPVWw^k6#o=mqG{zGbK;MC{sOK}O2$@(Enb+!k!0)E0oGMN582yfW+$XZ%pT3_q zu8@VP9ST>UAkkx)eZ?#(F0y`ufHs#*zH4^*c;qI;@`X4Kfd)~lv%*D*6CeeCYx0Fr z!2@Y>aIy7noxa=gna#XOmRUBY2}sXyxd$Uy(Kbi5NTEsI(P3oE&2No+0zL6MUCuJg zV;XnzeW_w5SI-!4t;HVU_1bC|OMDTG?0&PbT6fkfJ{a^g5H|dkQKFe;i9(x%89AY} zbsOap3LPE(v0%q_0C--zVD05r4>JTp+TDcoTOuR_W`0C{TJET6W~ys&Tq*(x!F@yh z;xN;}u+{1 zhhVnJD-lg{udErf&PjN=%PN4BL(u{|P$M!+%0_#5*oYTfP!qF;6d}#b5F^`p)HmrK z?~h{`!jqsgonvh%fFd8M&iU-Mp2q+xRbr!}Cv!RT(PFgp+@YmxVi`S-bhM%nk9rKqr`5c)-@0EJTbE)YmA{G7Pu8pq z&79q@&j#KF{UsU`shDh)?TKpkcY*)Zvuj4kx2LzYV+7{`e68=nn3=}((5jGZ^i?Gu z1S~H$;O=Gy88O<+b`}d@2XiL00d20n70fTKXj)a6zCxU$M@iCgC_4v zH31Bf>Grw3l}&}Exd$E`#`es2&|$$Rdjx2!3h0!sKj7Lg@Dfb}4usd5DQ_i+`m{q1 zg-jL$7}hukdt1nr+?@GU$S#nFsB0WplvmfB4+8Uq6J#yDe}Iu&$_8ZlSMPr{PhKdT zC1?eW#daE&)PzxnR>~{|Lb%0r@6JWzB^Eh?RkM6Ejihv}$ zV-yt$zGzTNrecA{;RKq?s&g;A;aq#8a73@M+Ucr5x_l4k_jPM^vux zbM6z%v3TSUviusPOroYV*mqC3p^8N9&(nlOhHTkGRElMJTXWERv?Wz9%l1G!`$+ zS-tii1kuW_1Y*_Ncwj&!E{AM$QY^EehvBe2pCLDTF-{>j5t0Oc&o4;#jJV2zzdqJ( z41m+wnYQcxd*w$8CHSsCxIUx2iG|~F)zJ%m!isY#TMU48m7YOwEhlT0I{QM*Y5)M_$|KCmVuGe>fpN{mg4TFlxAkUg+3SGwS&>QMs;H5kf zS(##M=F6r?+g_JZSd9%xPdy-h>++x21G!g&*D>1Ca`i92@2cP3fb)g)g+(K8{E=Bh zVt}@vNW%@x+_IiBU<~U%V%$N|VpB5EcrtyWhqN)}!b;RM%VX&uZ5nngtVjhdN^BF? zuAyR9?BtiW1Ys+iIH-~G91FS$w#2hfH`^k|Y##^jwWhtAVCA=r92*sk!c~1n_B3B$ z98&9wP>p_{yIt4|>4dS2M7(XyovLDyRV>Qh+{|m1i-FB0<@^@A( z&kj&>(O98Gk#lw^cg9|`mPdI{-UI*A$c2bGVv^N4W^;LSmb^U`A>BlUJy|aNY>(^a;QVY)$M$CdUUHyrvNEncs-IhY8pajalb#I_4BbLR?is6F+RK7KrkFYr% z4y$V}Z$TbYE1I~XidtuW+0``phh=@CI4q>>M!`*)9e$~iuU;RSVTw>HBo?-)CT_gt z!!&IAxz*5i6-X9XyDOgPV#Hg8264YOE|&`9*Jts~+VEAEpt;f2p=Bv7{cW2tPb^VT zPx#VQ$&j4@oE~8Bx1t6&76b^eROkO0x_Ag8XNt1eLvK$s01H*t1PUKw&)7oRj*Nvb zrNM3m#XqnJ6^QKskf=(oRDilX^_Ne5ZV|M*(Jom`RHh5^Ek>K-?nkN0r)5ZmJ4aJm z;N08@!RrF>LeiV-=2$Pxrb2;gL_IAZcP=a;6t;? zs$_Msn))ix45wrzI{tFSab;Ot6YBI&gNx_KN2MZf&#@0C`se>08dtx)(nSKj;sWCa z;sXCdNI(ZApR)06r`5pdUk`3Hu06j!XQ-KLzI1js3edyEB?9!%nrWa+Z9fePvUMc_ z#me2`GcAkx6h^ELndD8Fp}Sf&>GfTmT4aFFN)U4>k>ypmmzl!hn8d<=G{XxiJ6%aY zKfC$_al-29%ou$FEw(5cznMy|A@)Z|ts+$2!(fHVm*5yVO;{;wvlYdv+rF1`3|{s` z$u|F340v-zl!%A+9a;hc4Pl(ybwO4F=Hn{>@G5@+On9%N9hM;!ZA7Ay&bb@S7$9S8 z&EsuTwkQDXq{{<@bg_Qh;)!-Bs`)pbmYW?V6q3n8jjIj25shD_u`ORh_wOWq_bMDh zV1s6Z_gF$*;V=Pt0J9I6Hzh{kIoXrT$AZ8g)my8@Dy}3c*%4;u8vX}w$TTr2A+Naq zu$Dv5j{buEfI+{;pY74~86o7YLO>V+N79*~pFA2f+Vafe z0jc<`#u6K_tdESI$_^c9aI%LQFHxmjkKjRsE3X%~q-bN#>9=a;O9LA1|2B*Mi&Ltk zjk~a08lN~Msr|l)L@!bol<_(p?YvUt@&hL#t8u6sQRopbclQ+3R9vsd0GTS zSCa*jaGeeh3E^Yr;dusI9D93E3rd^xR&G6V_KF_(6wj*^q>c*qpOJ^T3E8Un(oh!` z6AzDrWu`-+g1U31>KJ_q6(`iKd%mIM^B7>qf)He8ZC?KG!mR*rFs=1(df|1~ViKcy z3+DFzD|nqyTE5lx?qzGQJcx)Utg+u5r-V29HGMmhg}r`81DKm1Z0^I5KU&6=L0#t0 z_{&i8S8_@HcXg<@AjI;xved0*6>rhHzfBr@<>rS^Ecbe6>S6fFcxt}A8Frd`islel zo<_#f!28#Z9W|6Mgm)1;&|I>TV|eqq&rspn3irB*0(l9{m4zRPv{mu~Wbxh*4Dk2k z6{y|DJ$1qXeOwP15`3C)fcU>8Q`FQ)-*jMPGp+KZ?}^&f(Kj+6H0d#4gQGF}7;=fc zr2c7gF_~eymP8RF`IAmT=+wR*5?0H?JBzZB<>xQVT4Zj{L2y}EyEvKWoN6X(@JOX; z*m-7UAkH2!K0(zz7{CnoNMb(E(j*x$D0d|7Ohreb4Jktag`*Qi57Ufl$qBhjv(`5R ze+J&#cAH5RbnQT;uCZp-ESK0?u{* z4;W1L^P1n%EL4!|Klxq}u%NPKV$k{1E5H(%Sfp_KC#5B5*7Lk)M>%eACc0 z;ND*?3f@5TQ{r4*0D1mdEhn{a3Cj@y+#NeiV4XMLDCOh(L5Arw0r-DRav z`5E`qT4XMm)=7(dz@xKJ^+~wt5_$Azq{CzB+_!6gTraDD=<-2{`h6m(=w(wad`eu%ND7weHv$7 zX6^$}A?RI3yZlFQTYwL|132lq;|&lYVlb}U1M&720*p?qES8Dz+nCYByEl538yNC6 zhsFTsiJzNv@hYQ-uP+G=7GkPvFQ)xwM>P{Pv$)wijamEjwThyLz}wy0ZJ)5 zwXX$v#?Gj`nF!V)26W427lSg53lT`1`z?t1ZYt<^T5lRm(Bh?T5&=RXmN%1oKT8!AmgkU(O7?-h82SbLoIrj17uI*J;za1eCiX;jT2Myh9J#p*Mqn z$WSY3m{v(fBFGTch&zdZb4kTMCl~f3OLUTQ5Ht=2=7SSpEPcmeDXSA3RpB^Yi+b7` z$D-l;?lanq+S$!_+ZhBo)qe3vx^{hkU&#_;!qPRl^_nZkL%!RX&tyG*L=d3fI~#Ax z6I;(Px1y@DU;v1%Em2UpiIt_Zfk+}v&Wu0p@rb=j0D-GB|+p~W}hsc4C+xU@o6-j49~}v2zM~2y9>H7)FiyD*n^dAeLkXrPmF7I<<9 zvC@Q$zUi`>IGs$Nw>o&BW{9R+9T^2J@*WJ8!6yF20o+sQFgy7z^RCJ@U4H*qnYl|G z9pN|B0)?D#@I)6m+Vn{T@2<@QTQWmIb3*3oLz-~mbHb!En_&aPVoiJry~4{3AC?y2 zk%6zae*-m~%FyHy=BlP66D4j73?-(aooY(7t~ni*7an!Ja3nmie>#b1A0xZ*yDeG6 z$a&UCua!||aubfeZ+lZo)vkkj_Xnd_IkakI-hUgVOuzy)zW)UUhV5WWu4KR`=OeJK z3|AK|^OH936$s5Fd46I}U5lErCFp!TCKWa4{)vff+=m@1Q^%Y9Kf*djrWnKxmpWK| zVGB@OFvYwaw~-o$VX`&pCmf&ceP$FmOv1J&e3uN4tr2qlgdH-`ygqBi*C@T3uFWx6 zfd7*ZFc*y(_F3*ol@fnldsH%v!Aosf#yXp9p7l}^_OWYoWsC@iZEXFZ}MLxu; z%-K#bwM1&X4#W@onNaRCcMX&07zOwq2r^Hb1*ou>eZBE*CwePfTHkY*)VyQqtx@Dp z_)kEpy?`FhT+GkE^rv)<2z_MI;}}8i&~BgyfW56b#_f-1%3XKDA^YrZCh$J323!)P zj93;hP!>+AQvdhg^78FkV>NI^RwBN24rF)@c0K@oC5bmz&oSy5y9IcFM*@wT9me-! zM7P?g7R9VbNbOBzJ_)v{uyPUA$AL^dJfm3;{2MXr%bVIyhxxZ%tv~RGUzC8MLN+4d zpB)80lx>|{Yoyd@~l)|B%#4q7=4-^IgV zw5yAK@L(BJemg=1?F7r!&s*6nT?#qpGsP%fsW;8^7=C|og$r)k-&M zUnT{h6q;C4oA^qeq?buaNTVA)&HRhq@60Wh#5uQjVr_bRe9oi`GeM`1F^# z`idmqX#Q42e9M5CG^T(2iwM9lxQh&Lc(`Fp5`D*8AR?XMA^Dm-VL9NVNwaE=nR+jB zYQqBLX28v@gz2Q6?U zE`eYyD(6r?^YQ8tTT)o?jucK!+S;c2R2-NFaqdkj@gP1#<07{iQGa0S@x2_#cg)7> zAbeC0S4^f^BR1jYg8Q=-^t9fM)Sm^DyQqIVe!h-#=SeQk6>0^WU5Huoq(wkWP2?W2 zkRDTdO<@`(euMR&crghKJrFscu6Sp*OnLTc8B{FaE|Y=I$gKf>&oiRQ*^A|CLD=LW zJsDo*x$n#m3oI1ty1vsHP9`i7TE~TuGDhS1dPp-K8KBM>-RQc5X4+`{3AfNPm5uZi zI^#&h-CW}5O8qG(F!F3j_>NWWF;Rxpwk&!)u3u{>p`8$Px~5)!vCu=rnMCgX9`Abb z_n1UAxe{Lc0$fV$Q|p{O5IgErWNm3T-N=`-9tVgWxCqTp7$n}iKq1?7fJqG*Ceysb zQ9%(TfzNG48Mz(Z#zWhA%nSvtE8Qrlq(yVP?M1}aOvML)hVK`mxiI$cQbq~?>KXuA zKElJ!V?z`0mu`omfp^uE#hJzFM&M5Q2e$xP>~JqDDr@D>Y8*7s1rqU(5|m3+Zh{LR z5NY;U3q*2cDI5ya`VDcnkVSkhV%0)+srWIk0@RIF>6r8yvvIndtTn68iP4@X`HGB^ zuAuD7s2`1tZ3bmJU5~I05Lel<>BPHX1%Jl&5tMz6ez`-a?8BhXryC1?LE1Qu(QD8( zw64e?!L{vBth>^Ldfgq^mBP@A&hVbv=M});q3ZOf#Jh7CFMKZQQIPW#;Rf+N$4-(_ zVoo*j@egrKA^6X*Te`rysdr*JNe+E#1eK4R3Nt%fNFdbThjyV>Wo2{|dXz|`T_1(J zA8?jftyLFIw^7(gIFueKC{gN73o;nWB}5&LKz0;a)i1Yr+@$$Y&mR;Sn&dPdPMDC- zRksRVtLup=U_?+tdsSVUmfEg*dQMoMeolo9W8cJYVjvY|{^r|NO*q}O<>X>uPEy3s z!dr$`_ZpJa-2E=~fr;)IJjNj>>TD88s}ZA2)E%F8K9fnujS~}ut->cNtW=tK&ZV1Y z4<@gyfWvK1LQ`wstu)g!`|isy{y)s@)Z2sh=@>y|Qxe@mvYy4-B?mMCdj_U%iz>O^ z_6alkftd@LTDX|7`T|W%4V@b4B1lp6NEBo?9}zN&Bp4qs6u%!@LzjLYTQVzwx0c_H^T<3_YucLdPaJXF_vwJJPT8O z-2ivF>JPi*YhK#o-%H}O&aPammMAxMaD325{DriZ`^E5KwW>dh%X|IssDe?8Aqq3$ z-`B=wZkqRWWnixtKuSFbpu6nqIO%U9RD+(XMU&81~R4+J!~Oc1#DetH`FwL1=Ntql6uS=hxz7V;T@E@ zeUlCL82#eScdjG#*ZW~G{?kKka|_*{F!1lgC?0kPGY%rA1%eF$ZcV)&P{TP>+%Qb= z`$wD<6*uk-I-G7My1y)Q584#5!Ytoc69b($D^Q* zTtF4+86_;HEB zFNuW#PM8Y95QoCp^@Hm9-;30!WomPa&dx2hk#-yYsQ+Sp`4X74xDO8(4mFBS=|G5( z*7S2rhDo))9r)l_4SA-uP58$iyuU*d(v4B_P$0?{c!B7kC<<5Z=&m6NmKNkgFTc>R z?B({~e}IOGX#U)2j3P{s@)=~bkr0zEHa}5FRSW);%X%ZW%I^@xFJ)c3-42s*UbH;5 z@1OI`G;=KI^WmNqRRhMh4jV>}`%q8DK>-4!Dp>Gl_ZkCuA~}@_+9ddMOw%>lNVoP) zelU?pV#-d$lXkeB`GrkCKe8C19<%s8DJh#TOUEO~%h6!s>t zqDaKmIsW>9L2ps4SQG8`(B`hDzV!}Og{ZOYC(1SZtMV@aDlpxQRp&I)A>Xk=1f2AG zx>@6YC1$OMBd*?1WLv`Jqx{8P!+K0Un;;EIu~80ksou-+_}`8_Xo%Kt37N6zTPIR{ zutrp`ZL;iX=7c^OCNzg0bd?5aEg2LnJaG_!#Vw{vi%eX(KI zChwnl6sew--eH8&qyNo z5Sr1Y_7?AM69VOq$qSsf*KycsM}Jd!m2jGtZ^6hJU>uDwG>7MC(m~Ec{ZsPUC$R{e z*4jMMABiLB?GB=PbVb+fn6BUD>Vx3N%b+FE8P&X*C$~%+Jdm`@F5gLK;!p zImz90_*o+uK1x?+f+b6KI(+f+{kX#wo0{u^Rhl_w`&PGASoEXpO)k4$*gQtS9~LYA z$lZwF4fJ9o@}sVj6u!?s8EmFbZQ*bB%d%GIS=5*jb3}DsIKf3B4AhfHpc(@Y!$|=u?m4fb=e7y>g#2Q)r3%U}l+|L}lf1Rw&YL`yTa)hK4o7z-Q~^;fK!bzX z2vmgR{es40D78S9LcXMPHB(fel~u+6iK@TmPf@q?<)X!Lmh30LFoL>&ndXf)-6g8$1(5-&E=664r^y1#tb{V-wBf+)3 zU?pR(v;Q9f$3^w0*GDzfj^59{8isuCKqf^E>L^zqwOyT?DLzV#}NJ7Z?CGu@G3KXxW ztEy!;qPBp;E#B+cTSWy5BGED-h4M-~_ZAZqJ5mbfsegcdJ^W+YDGzfX4|C;}neavZ z0(=?n^9zrs3CJg0CK62y$2JR?CrI{ujFw4Gk&+DVz$;k3RArR4!puaVO673#-BXD} zte<7OPMe(z64y@a=GyLfeuRZ&Ueo;>#Vg$M>Sv%@rg4 z|Bz`shi@lh?xC=2eM<3%PpWEU@0E2iSx{Pev+HxatZ1ZuounLQbWNj78u?|*POYjyuBiSfaj6k5SUREg@7zUrQz_7tU*%vRmi8Az_P{5F zWSX&r3W#c7G)HoPbiI`v1HN5pF!BrCN3q%b-X|VoJxm$=U}Fyj@in;snEEXq-_4Tt z_&oXO>L5aQh89m?cH1Z_kqZ%j>N!CwxF zZ;ki@fddN9_|F~cTKmb^E9{*x$@;PB8@5-Bv7{HVEEtETy#aReS>T=>Vc!#f_|}91 zuD7Ui;ED7_x`uE~!Ob`2#-tbQjL!RWe{MPgQQD;drJ8iFWyZb9SjL;H(^!u>(H%jo zd)!Bpzop*)lv;-HxN`hwrBdi{SY2QSTEtFz8iuYQMZDVA3LIE@*H8{{6niI-gA=ZG zV|UF}5`R^n^zQET+&3%k1By2OwAGqWcHWCKeCc zpL+sE3#F0tNHtNw3Ab$Kuz2)nJvGRJPYs!7O`vk`Uo?g12@x%7eB|fI1b|SD^G;*0|TRz<5j01)Cicq@EUvUT2k*H@KHOimg13{pHuk zNolb!dz*_QZHe3gNo3G)bn7xhkrv!ylsuL( z*=s}8Uu-SlWp@e5>0@|=JLg81GprNu11C+2M8u2X6IYG$OdFHuwzL*rFK6r8<=PCX zw62fetU-mTW>N|%Oufv}3$zyc&F%O8k_JVScRr!Dl<-8a2yh$iB@7^J$GNXDMx)I1*k{JyM~ULHy} z&IE9J-|^n#M}iIE^q}OLsE)wf$xKUkl{t~BwV&HdvFq-AjX*5EFiE5JGuWh0E`T`= zNE5Y~MbXqnZZz-qSfO2{GX{gImP5tcr-eP{+_6A2^^VQ19`F>93TcVJxT%KOH4TbJ zhYmhM5~*lBhCaLza^>z%`Jtvu8)>cKN_a;!q!uOq*2w_7(3jbPnjndYwzpWHBl zF&HBTC{IrW>~qNbCxOJF$!77LVS@yC0nG^>n1rcESR0r(IXK+-wzAILpAiG48)@N= z>>L4hbv-)1e}w_UB88H-rdnro!0A+-j_v0J3FB%{-KZLe$%Aoe|-p`9Y@b?=}HdG=-6k#A;HtwrU?aH|Tt6A8j?Gv_aP- zHD0+kR$@MH*mcWn3;af6-`(=|)oJPKa^fc{!}KV8zY9!!PTg22Vn-#4Nd;XCa9 zOH!Ku7u~Br>lf%N*93V;aN$0`@oX-P690k-MCR8s0t$3&^~BeZXx{Dx7CYLi6I7;hG)tJtJaI-OW5LCc<%WueLd1&V(9k}U&8i~5Hra;bOM)QC?3;* z7l!RX>1NU%MraQ_f;&3cGqk0+EzD2!ESADkUE@N7hF2@HlUoV&?dD$RmsLnxl5aW4T=o$bb_J~5&U|?-ru}vG z%bxHj!|xEaV^+1d&#kX4V}$sTs^C{CuY|2KQRbm(Lz-C^!?A6~cX<{epFEVJS#l){ z$w2u7B%3n1*G*4<)tg9AzuP<^Tnu-O(H~16q{FvLKW@JsC~W(=OUUl@acrX7X$r$r z;Y!*&PI+(dAm*W7dsGJ-o@WxA)LT|GH>7=_+-S`bAIcOOu>6yUhh8=?->`#a-n%>sjl~*OX&iI$GSK5@urxy(if~FZI z{sr|R615G-|= z7ZTZ=a)NQPTs1G=PP&CcOA+$BBcC1Rx}+Z67Hi4E+cj1!*9qQVj(8aF8=XH=ygZxH*MSVqMAND_OoDP#Oa@NvCVL$Ub3bE_>2)747ksm)8G>9*g zWB92Ra<@$JXMpN4K~R36XhVC+8lp`06`exgoCX_ zvG!B+gZ)S{m;4Nc_dPvacFZ%(xoOsZPsg;~E)w%f;Xnhjv_z_mT6B6)x#+G+xvS;2 zRv2yoD!Za337eWQoZT`aEj6A|&8Y&>g8&IQcpYZ$*Z*)!(b6i-@w`wdub}8MRKb^I z3qw7kDME47d*P$;V>Tj1_Aw8L_11rv{A_v4pM?8dq4khr2Evs4aVn6zRRC^SG|Jeeszgo=A79V2%+U?a`MEy5WM@zMPyZ;RZDH&B*v5CP?@MWr}~txfGH@ zoWo2-GPzsAQ4f&yJQ+-K0bJr)na$*+5`lR5(X|=!jMW5C7P1g5xt*BeV z>&M{xAE)$oRu|wF=xk}0e=F8AX>&6Fc9;G(e_My`7s%T)fYyndeY6qs=mBiAZL|N> zjFJIJH2rp3|%iC_7)|D7cB$m1_VtF%$Gs1&?O1HZDQ5&{OT$#GKuE z0jg>}B+`=s#1-=tR_)r(ksx6zTMx>$*{H(hWXL{@;8D&_>}#IQ&3hn@K0{Wk!?Sd| zm>QM^HRZ|kJj`0Upw}FQY4{)#U5!~fR%#8nODVPbCchi{!l(%khtD&AeQ!rCW zw~UUc0+1elsCU;SOV}Qi-~EeFF$6k-=_3!>m`pCDF+F>}xVG&X$7ZCX?x7iMl5 z?1-vhugU@YS1tleVQd{3kaQZgB>r?TQR-EH+H&r&RK1)Xr&EM5+`ywkY~lc;#1s{# zomq+_h*n%Kk*Jq?BjumMhS8%(Kg_$QY0%HQuJj>iC|7PD8+Km$acet|S7ec+Lrze*{TyY*7(api9X91uFx*7)_q?SKY@w6 z(y6at4c5%g86=cHp&TE@w@f(je1eKgoo(~N1ki8Sg4ViNb#kP3^hdqA-K=GB;?X=^c0QlcHXccuzfAMb%9u6>3C+I8miB@MU!ij^9Re(Rf4U9;ycEREE}&S;8wIP_5#mgPI9`K#(O86NhFq8j^Y0iR z_Wbg3jr_-JFnZ2m_m3_LcG6*ky%U=^s=h9|0rYG;D(?}n7;pp3&)0+? ziP(hCR#Xn+ebH)HNLFx5IYdqPZ|ocwDEnqLT)$$BUq zQUk1F0YjFMTkc54qK33!)3g6I+~I$#v;|_fv$)3Q^ba>qN?J-)yX_{eY)cIT<1_(f zRdq8(_4)3@v91NcY}1&1e2v3pxxzIt-5?P@^L~v+=$4;oK2{I|6rJKLam@S4OB|e< zLp5GLLANe9`=oVgn)t6Lv(vB}n|WNR+vP?=2K402keVr8eibr3UN6sJXzTCX#n%GG zVWcE~{rThT5EJ|6(p;~ZSg{GK-FII7UNpf;Z*{+Mf!G1EPzXLlSyH->x)r;Nc|x4q z5;wQH&LS`TIyI^LW{%VK0gS&PA_(?h)3|z&RIQjd(;DN&k+u{Jg{~NAip7RI&9}DB zo1e|K`s}dDfybj&95`@mcl>o|8DZOl`OT- zyEYPq_gJxEyv$GJQNhS#?#Lse_EQghx*c5wVdzFm{{7yGoITE@-((x8VHWT&ErOIW z0|s6lntt(+rhq_zw4-?M%0+>Y!9zHPty-Xsj#5_n%?)?Y7()(BNAg)H6Xr=3ojYsG zGG%@mECHf2C|;s)L9VFP+WO_r0f~~gO5Ox7Ox!V!7G-00W(ap;zd`u91PU>J;G9Vg zy5Km6)FUCS0+*PKQASYqA8`%a(tUgN_ZnD?)W(6CFH#g;R+P7Fx9F&~AKI1Tm+Quh z=sR8yk2lRVn34=jAf+=>Aj}G2DEteaKO9087dDuPM{qj0w~{%i$aCdUiJVMTy+wvw zOt7eR3rU$|XP+csNm|1;2f~av{H|$8#oZdW5!4zU0X@p+j|^PZz9$J3*S(&Has?7zSSe8tO85quXM#|<7X%?R2Ac}pVQnQ z43Cst{ZIr8k(V*Cq8dc6^YesMD6i!B6mRfg<78k;#_Zu_-U(y_9<%#Nj_jH2#kD-t z=F&z1W<*ACXUna=XAEanFI386*Ibj5VW7)6>xAm0LfG=>5~+`Qr@uneY7z^Bu$m_N z!SOrlb^X9anf&meKRZ2^gs5x7`4fCEM5Zwl_}%c_X%VJ`;^ImRg>wR##u)3#s28XY zNNq;uZf>7%a7*kFgf`^B9B%8RKof+oyu_INVbPOaEt}cgU04PG3U5Uk{y)bT#j3_B z5Pb=3zd8ap_U-6aCcmRq_p>~0X+zC1LQzSV$F5<|YMQPOinTsbL5rSSX6)pJz2DZy zSRs2-8=%D46_1n{v_{fr$?;|>Uqm6%52s~=qiYD){X+gOVQ=k0`Vt5`rzYo!mKr;X z)A&b$t*3)?gvHHvEZ|GBe;5G(-lJVqypdImnf)k5vr#6r!}FV07AKnbF64U z@m+=1d&rI3oiR>RvK|>D+K@dp8{hXk>+9TG9FPr+1h$7Vle-^d^EhNe!&)jz{5j)z zSjqKJc0Vx(rDwOvXc4p@Bik70o)62old20;67Q`%^Obee!#7(a5va;t1L+$#$LT%Xg zwAu-qV={7cfnD@Ag(isqw`0|bq7GCgD1zVrSRQAVelcXS)t5WCS&zR1sR%B@x&tr0 zs~O;g^~Am{LoKOA4KuD(_7+Z5D%+>dEy$G)ZNlr)8{^O*C}SMDmY9Y^zPh-{V19HN zb0_4sqpf`El7>l=baft!?K3PJ>s?e)r)Zn{jD0W=J!jK;*GG@!VigOHm;)N{u5;tY zJM4*a{TbwkpSVey(&BUNG?Wm1SV#j#kIx$q+a@|m3a4f-ykS}U(Ei~Zu%xc6&ifN) z*L_g(vkr)p-Z;B#bi|^L5OtuoK~u*OK2jdLE4dJbC{-g_>5gtNUq6r zX=JwVvgR{5cJ?}&ttU$;*-1lQ!g*~2j88p9g>TcsqPE6KOx!N^E~aycc4sbE@l5I` zK@D$Ht@%V@5Cg1sVKX?`xh~DN6^NCa)(>UO#9|liEVB_g__)|$JgX}GGaDCOPO$E$ z4ol4c6rpB^v}7?w-hOy4w#C!-NmzV&CY% zDF3Wj>WBf}g(q150gmOM;6F+in(VH}A%QrAcyaJO4F_v%>MVx=+7yt}=dCSVxPbjq z=)q5nBReCFy#Jd(tt}Y7wU?974O{?qb_~k3g60HdSKhrgS&}|#zmoIO<8W1b1t0bV z@rkCnogr?{u5~lCCG0N#3^}eeaoZ1tiY<7k26-3z_5m>OGdGK~{c+ErhMw;g9f zWcNs5(f|aYO=Wb8B^sk@|0$(}uyQU^OtDR-1x$Ay!$&f1WYg!wbSi$&!3FIw`v(VW zm}dtJse0?!H+8-|mc79;7z%f_DR1jKgAaRzQ#}K3X3*1(M&dd@;GH4m#<|ZQ{XU$d zF@269BzN!o!}+pFb=Ffs1fNMAe1>q#2pXda%f0T)_!D3-=s&&mFaeC>}N?7pmSJEHT2x>tkio zW=xJLVQQFoJlxCIZiA5kg1T?~F^h*_8QowtMKBbpb@V9%g;V!JNdN6z!CuzV>6`4X z!*_kU9bQXMZg>HZ=|yu$jayr_4o(0@qS;;mIKDg2MT~N{D5-bfdxH~NUFurg#8b#-_(}g6Xeb#lO13!)%{-Z-os>|LuFO$DcWSQ_{ z@xs=ot~)QpKdS?uu|yha&6T6PNwp&8M34b{x4ze?CANck0!2c7PFyTQff*O24S85D zuHlbOsSx$=u5VCr?9*xTguz?>B&OivV2A>l?%W$;2jY&p^eKj?fvggb{{>7Wm@|G$ zWes~u0-W1(26h{$OCc!Kx-P9!+sXb1dnP@GNhD%gdp^9L#|`pul~$w}fL1y4>K{gR zQ!<6ZZYD;Q5DhtLHU5@rhS|5`zW6e>vDMdlB3VNpt1R%3foyuqlH^3ONE+3OPZcyo zvpZxMMWIoy3&v*gJO6LZUQl_vqf{fq^XGJp#=TlYlXSfpV;+M)3gW$~Egjfs)$?0~ zP=8Ft+pN@FWW2QzE;$PqD}VLCktKp1$1oPi`}d>GEZZNa>+YKo{Z!T$sO5G$J1_^4 zF^eE>$hGpvZm=o+d(`YC#Ln~twXA4|*BYTk?2<_%MXMe!g{W?H762_KRdM+3)mt{v z%jwWH#T^VRSuS`UgITkJS?Jg-_|A+X{Wou&g4BiwK;T!^yY`dl7P=X9&`%C3YhhHOTZ`hbUbYq_U{xPKo2LkUg#vH-pb=Ei zC5}qKl4KxD*GL_KTp$svq18tdm zlnxqX8?>*+EU>S>iSGY(9s~62nkN2>;Z6SzcRIQ#^t)eRxm!^&37drorS2W}6tJa? z===_)%$tE8kc+$mmA-F2Dz~aNqG3a~SI2ef%VXyzr`3gSHZi9Bm^xfOB%B75Z_;)} z+zvoyTcz&)M0T7M2++L7_Q=Ks@=m8T%!_kO8Fz=5vNZlE~4G~snRAX}^ zv@I9t!R9wPPabL!(U2C)QUej62D2&=AzVFK&&g%C6s|_hAXTv=A(G<}Xj&*HM7}6i z{4?Syia9}~<*)`Wbri@BSuvt0v-x$TOm$t%nzVuh4&b^zka0@9TElpCfX^KN#v?}u z^(Zu_T&Rf8;&&4y<55yfTGcWvvjRm$2h0s?XVCH_v>&Rr%r@6;I>5|G-0 z!cA#5m`5JNSb3rZcD=MBvPNlb2eB<+zIP=XAQf}7eUCf;wqa7agXH#P)@{1&I(uVroVp!OLJO&h4OWJV3Mf($LgRx@dYD#&SpY;WDsbD7%^)7-{ zplIb-*2$c@nJ%bJDH>C3jxV#zaumk0l|y;5!0~Cbk}gzFu+F;c$LF~n`M-MtcTS8L zQqiY>_O2j6(A@?tY0`QNBa+8(X9eDeN+*$yMZwW>nFE7d$bkS`jgSI6GgyWV3GRtQ zhL9pG%gtpoRE}hgmu)qj92dOtl7}-m2*uGnp>;S z7NF@ol{8+xgWI*<5$;VzkXt2D!YUT|vKAjwyb7j+v>hua)xJkEZTWHS%SlB3n*?r7 z(Bd`UPcSDa#=`Iyu&hK*PhhAO9W1Uufe`f2;S>>^^lz3AWZjrexNb8XhQeRXbrP>+ z$HCR{s$-+mBn;#6i(Cl;j*c_Z5}>+HN$G%(9q%;Uq!guZ1-aS{Ke?Du^CBAa&b|$^FBGlYlKnpVxp9NG=Gkx$N+*< zwi>gwrWHsC9=>v{isUTNL=02qj)J)3TBj-qQ1m5Tq(H)QwTz-K$<{m1Ua_NUVRRFgC2QMU90r;>(6FnvUy|;?7=NbI zQG%mkVaRVP_RYlCN#b8c7r(-)7&I*xoY#p$j~^|>ym;Lr-R0f0Q^Q%eQLvt1sLm)E zp$r(o(B&-!EqeTsy4w>~FWjvwb4MoQ2c4|S?1ZEG{C_WnB(s;q;D*?X(0Os_qGXM< z^T4jy2BDx@Yf5MpB)q!a;_Ss-hk>rh9gG6F>@7ZidG5v z#mG0lKn+V|l1zCjZw~1As}})9$^2sIM|qhGD@D}DW$Z_|CMi^Lop`KD)}d6+ye0|2 z6f%XE$d)mA1BShQ&V#oLFwk9J_(x7&_AQU+GA16>(Xy)tmIFlAp1nBKr1k!P9bBlPPWu@{GN9FnxR>8I-80;&?0!T7h*%T#vdKlpB2{}U5Rcz zGoT~T-5P^3!mp^5rXfrYyF78%1IEfthfdV&C=GNCsNa)G1Sr|j@S5ii1*u1gHt+py z_K_F(kb&vwEFcj)j)K^B9`|h}_3YY*dz2WDnh*Yn$1~(DQZ?dJ#cg936X#EH*kkPP zW-htkKP!^uaN^Am)`3%#Eo5~5iO3Fn-J&6F3l@bwRAvO}W?hbtHEIV=!Dz>aq*R#c z_=#Q9`VII1nEo0SvJZ*`^6!wZs`NV0{DdSQB34R5fN!J}E%VS>N%wj7n#SPZmS9MZ z*gO-hUFHI?ppAxz?IqDBe$Tsiw~bDBmc>6`xU;mxOnWrK*$I-9Mc!uzrX0iae1rTr z(kMQUtsWugwD%665pIFlv?uf^RD_Mp2TaD1RBNEEW%r0UNwqlOm-y-q-&PO&7-5T* zS+Nr062`76WJJQi#>hoXl%x1fvH(}Q@>8fnbawl^NPNCqdqbhcmh)6jUS3wxfL(dD z*NZD3^@@%#Eo zCu0zKYT8at>{gF)w_2SWHVhy{Zd-n4{7yIOv7T_BN4%z^`Gb45yr3q6lwYt#0}R@V zCcbJ0cBwcPsE$*7oVm(*-V@f{e@|k&!mf%DG{bUqT#$jIf6w)_fXoc$f8|wA4=BqK z0kieN>`&A^7)JLl-*mvPnWBxORYbp_w61LPA2KnW$$I+9vKPMaNWp(817t{x!0GpR zr!rP8jG?8<3r<00(lDDU13T-1pZ_sbAGiaJkn8kJ5+E_j;>>{`(MDEW*}qvDA{f|& z)(6(3#WWb<0*0Pp8+7C6b-FK?#oyl<`*8<^R5ZmD#N(px<*(PyhU4(yrZG&DNUj5O zmB1h^;mvJcI(XaD)&8$a13TUO4q}k|`Ru3wJy4V_mD9+Ng81Hvs2~~A z@Q*9*FKy!)$r(-}*zcNyiOenjjNs_SgK$o!*I@b` zd%u;namM&07B5N!kIMU+{t^3)5p<* z(+rKHvL@4ocFi5y%7QN}X85vTUKG6k0kT(g_e>3RQ}0CqHzT(0qgReHm6qH5NhdNz zQ*J9s{!M5YdM3vKF7jCz+(Qq7@J|gU1z}FZTT%f zE_SVL@L0?->C#S0zl8pp$tYA3=K|Hd9b~(tACf)lU@!5<@0LtY^a(c{$8^PAVz}mhb|bjsSA;G9{{_Via(#n zxhCkQNKtkU8mXvluU``rGCtfiTw|q;GY@7NGn$az6ws%_&}K3Xq4>oXOlav2W@@uz zsV4*Ed`^{SiMe86sUk#ViV^wAf5L>IdhQylJg`P@GB57+R~6kW(_Y)li3(B zpaY&-6m@ANr&$C3BqLN6ot*KQo7*J&D%ug2ZjOj5Vtf@+CUPy`FkiQH)ZvoEf`1%8 z$S{M~4#7ee){-6wApYAFjEpf=u9<{vAp*!$&4jD+uszfGLUd}*ZW+mQ#-0?z@KNy1 zlpK~JZ)F+20SbPGd2EB-xT3ea=u~;9{E{WYVEMyr=9l?4r4Qkff2>a#m&_-W^@(P& zPvM;l4*Dw|X$aPSp+6_Ri^d-H6@Vz{({k+a{8PZyzw;29aQ1hK`0A0uoJaQv<=M|^ zQ-V)O%2dEeWR_NSvA_ncVXl# zhhbPtSSoFBO?iW;WP+LpaNr_EH8A077FL6(AgTLKsRnV&`Xy0O!YSewhNfLi>Jg_N zr~jEcdi_l$D(@lrX!0%t>5z$H+DS7;VwMCZGt9??KjW!DkY8M5>GrLYHQ|yQHTr47 z$_}<_vHF`yNoDt{PMUcYqIR-L54%^r3No9Dj}l5@mRV)I2mM8?lir`Miy8X zK##3ka?Kd-hW84AhQpYBPN?=C&Au#yN?ERJ|9Gv6zUi9^`k~JUPh-mnVXTiE0)*BL zY*O_q?x;2?Xq%Xh+pMASdg}De6%;xL5<$i<+G*H3_jYDkspOw!?VTCN?7bFx6;h{7 z@;*-*Fv#y?rq>G+w_zl;l^;z=G5qNC#Yn@zvwDq0_}bRm)n}xu zt)<>l{s>iQy%q_nF%02@myOCm!aegTMD#+~y_#m;ZV1WX?`<)-hYP-?bNz?AaFA99?k&$*i0dNU1gTR1e ztIUx2*P#FNK=Sxvbm(mGwGzu;pK1$i(=WGj=1>S|Z}3`egH+J*>R5@xrtdZp9dRjZ*?)#w7 zpEz8>q!`AC5iqd7LrmGJ@1LH!XDsAY-FF0zu$(K5!q{{`iKc^w-hQ>=x&v;V3=W_r zavP+a)v4I)f_KjN)d+jzCEwwXn?*9yF4P)fyr!8lX7w6p@NR4NMq@_{9i24E?m}h$ z7{~08AT>fTWevVXTw{qcvZMW0OU17+2p{7k*d{jL-S7atokWql=%%wlUVOSezjL&^ zw#$Uu)~?xL--bM><;x3cZIMh~S#RE+E4Zd8K3{SgB&g?U+|)`=F@j;+(u`@Y-ZWqs z3h{A?%Dl<_?!Cwvvd`at>;ZXIvz_f`a`95ifjmNCGf^-DU)hlMSMCJVAbV%?3eE4H zh|DnYkfqeNAFf|=trMk>C=wkWb4pv>Za#N1-WrVd`SXI_$MwFEKYjA+7}jnK(B?|~ z;)dKEC*&#vmZN&NpReUW39dMch#Njf*SS_K@Z)mlS`beWy=V(1a?#-a@Z4Iq>Bb9W zHQ{AZ2a-w?lPlFoCCH0otKLblx}iz>{EP1NW*;CSyOU?gyNBB5EzjT?|%amyVP2TkG8@}f1l+S-?2J+ul(VZl?ZyShWN!A+}TR|d^!0VkB8%U?=X#gPXVYyX_!P?10F15Q>tf9#$d zY+QC^p5;h4Icq+6r^_#q#>DaBov6;tp%z+yV%YR0ryAj+p5kCAfU$9~U1Vojj=ZbS zlDg3AmUGOr@3?=PGEUngrE-_WvP82ReK`(E%?K24>|{DQP!JLT-6>+@{BA{Rv5p&_ zNXR*V^<}C4wN|Hv*{lsHkN5(smM+207$thJs1gqFtX2bv!6n$78}uD_0m!nF=Q-g3 z3LF&%Wz4bV-LRg(iJ9hlH|{H?!`CvBd;ihDC#L}3I%5%E80gbpXrb5Iv_6+Ie`GX4 zAc_1}tAiLnP_?N-p3F}-fCj?YeMv1PoSIo*H}1p$EZt8&ZULL~)uB4_a3(4bQkx(> zd*RZ~-f@UHwRIc6ms9#X?Q(%H0kX|pJi>1-V0CUU+VGukO|${%4a0yqCZ;+r;pIlK zFhdYBsH0s;QTgY{FE+G%rRr!fu~v2{`bIhvT}H+7@-b{;jg}&!ZRre(-8~Q)-s|85 z;3#D7WjXP)Elr|3Oc?%g-nurAhcKw@LepfcpONff+eriP!;GdncgZb#TLkO`7qOpE6+~!3+n{~o zMIJX2SIc*a=HtC{_Wq^VXx&W1Zt_Otg?Gg;tzsqDy{^gx-O?|{iCYmUH@esWona7@ zk)6gp1X#QUv4Pl~={JGB_d%P+fCY4AbIXR!?MmJg_qs1;q;^iVGa6`9(n5EROJpTp z6mcCqqB)_2c8&65PJMA?lU38p_5z2ts?lw%Fd;^JbU<|3^7aKCKDTJzQ9`8VT7+2( zJXvm?p?awAx2vR}Ix?qcIHAH)wGY7G4l$mGW$=L?`aAjY6)E@|TH< zOt2;yRNHz+?g#|l<`*Kc(j!Eh*y!0(+E6Rt}75a&;AM-q`tvQ~rj6b~*uKFCszv2A1m%jpixw z+6>mx^z_L{cq|R$TJ8;?Yy;E1gJ@%r z43WzVb6AZY_I172un*lSE05{xmF+g?YI>{{jX`hkIXpND1$oHZ^=4htrBSK9k8)-P zwkl?<^1R+t$^UP}@H5c}lo-YCxhE7rcbgfMN#+L2#mvaq+W7EOhd7^Yb~)trWE4dc zOd+Vc((aK?`z(a_XH=_LCiwdO5hW3065(&Uvl1h^(aQ9rF!0`2$U}kBp}%(RTB zt_(hxM29X~E-Svd3s5Q!xC;xOuM8m;!~IkK*b(Y}b_?T|eNB~fqF<)sY_IBv!A$Jr z?_4QyQ&T<2@)sYBhz9ofuF&2-VzOv%Yl>Q}g3{dgT`LiKSAB&j+A;>Dyt!PwTeB6_ z7O%nh?$4|vmZF{*)~zHL`j^O_2j2+YvC5cZG4Zl6qfRv*6nlTbG>OAX&#gwRH2cIU*J@bx zwj-cDn}N!C>UxlSCCwYgT0sM; z^dN?h@``Tbc8>i8?f=|%{iS^rgtEXC+jDukFM^KuxYfOk91R-$OVA^pQ|7W@(HaZC z$ik`WVAvGa7NBxq^lGv*uL#mjFD)x#pZN^EW7&(5e)ybmslF~MKtGJeBG`dr;4oFzxe(vJ5;YcC1 zsD<5oV`M5FHu7+jbhZ@EdBAj|RZ``?gKc=*Y15EvUa5VVnp1&!M2haDRsIaesJ_4b zD1!IMq%`5C`{vTt#SjSs9=t$wrLWO{z`w_dPO<zM7v!@!%=UuR& zdJZxY-8zgwl(m3)Xo-rdg7Zz{rdsT#I;COYmNuU>j$T-fLsTX;WL98*wzQC!X6Y8N z?TjuoW|qB&g(7Pm=(TcPRuUcm{lN}$LqOL6Kp_xG!}^gJQ1)K*UDNUm=JzAM(G8k; z@nb4VVQ2=$c>l&9S*X_V-QU;(pq>9oKDYmHeJg#(qMwR84w-D1y9;Q zL)zgD!D|BHcp@oyfwJg$Gv!Z%;iG)p+IBd;pE*r)QqU(0q7b2u1DylCZgr z>wlca**4jkBeTRaxV-n%KL7bCN>F_l#od`PJ07&(m~N7XjaQD!l+ZuzLcwBQmy2dP zNHM4Bpq^mX=ff)j1uw6qBQ9X+IO*tuhVA<@|Tkv7o=G%p7Dfd!!_ zXwdb){C>Mgl9l9jT*%|yzdoj$&em~a5S9npzh1A}cc_qf#TF~7qfz*Q#~nW^DB#tG z@H%#2(n-9A?{472vJsWiYj0WOXiT?c4(!o;^3!_cE@V`Rjmx&w}YYh+< z>YU_!nW5v&T)2Td{+fDs|82PuKt|XW_!QewX!tsKu9fwUhi4jkCE=!J_Ihk_ny3dl0Y;YLZksW}jBldiwXVn1lq0 zl}iL_10>Onz^6S7*S$hDBAGYJ+_{XF_socw|5lX95^h>t=56prY&$@{gUdE!9>Hvi zO5}xRPm?*msflZS#-2gDJ#W%%;#Q*C3Yta1TS7%`+s!pggWNwYqHX4`-AXcMJinP#s#Em|$p21~GwgqoxI6w7S7a2U*BBn8ly!c8qBA6>3^>V_A4 zN7@C|$zV6RMI0jc(yxV+?=aQL#C zcL`gwc5ed72A9SK<7NN8irsbixUj<-)j>npGo1Ef6wfWt-q;rv8I9cqrRH+4_aF+{ zyjXOhVOrRxTF%%Gc1=&Wss%ohGUpj~>?3&K-mbbss+9is97afIty!Eg7f`O3(Z;QK z1i7Ub&foTRuV&jx;hTEx@VD{2gT+VAbl0zj;6Jsej zfg`7T488)pbI$W83p>Jg6A%oFa$!p{{VLQ*9dvvcvaBEugZx0L0)n^?iR~D+;1Osv zk1wfNR)+DmXHTFbbbke8ye)7{|>G=v| z*nDyKWi)}lISmu~>c=>WY}o*e(*=1M=}^aCye2`D8RSNxY3}#l@IuC830i+Ym*>bg z#jJ(FAZ&{my?%h6Qd!eDu_6H{z^Q(pceLL5-Q1#$^QDfntt3)<>srea=rJh#kILlU z09!z$zwIAAtrj?t1TbF=!jsY=dsSUFKg5UR!a(^Y7jOO+o!8l;`8QsVVqa3rQT|at z`t=3xj)P3g4Frtqv1Ex0&8E=PN-L&W)-TUE*7KP5E%BI(&kg zI`vgs6pWrV^kTxq79`#$U>f?@45OxeLSOGPo;Zrfj%QbfiBM;DU(62NsI~mHuNH?8LBD(J}e59Zom$G zM0ixlZSa}G^g{9g;%`R-_D zDrb1(*bC|Vu!@Ch93T{ym*9HiMF2 zxYxCVo|0^f?dpTDEn!9mc&l?EhuwwlEhYa}&&l+ypy38yS4Tx#9%`6)GRbm~ncr`v zXJ=64RiGimkoeWW59WW1Au`H?&@`r^?BL5MDL;?M^m9z85Wo40K6r-5UgZuwzJ;t) z1Z@z%vlIHLqffFsE!vM{zHeJ19@?-^;c%T8xolVoiqhKRmafTB9s4ZtwPl4TGC|1ftegI=~Oj|O#$KLew4R#Q+cvD zTvY}tLxxJ&ZLh$CR_6GU_-ooDgqme-;)s(Luo_EUU@!%uOV9|wd^+CGTbSe^C=2kf z1JYAMf<}wTJFB~KiR^~29vq?>=(9<)`8}-!lLLmvM?yNb4ONAX(P|v>!;m3~l9QTNh0JWX=>l@excj2HI{lGvygYuQBVdQ@Eu4){&LfPUPQD13v8LX0j zLAxs{?|}|ov1l@YkUV_}PuA(vy2Xi}OzZyjEskC3$2B1@IB_PwwEVHyQ53~pFPFqK zxM+eKzAickmgyUNPe35xKOrLWcTY*l18gp9IZLsmPt}-g4~j#c}A*JbW!%4T$#G-?~-5Wcb$f zM&bLdJ)1Ez+$0uf)rZh*MajtYjaA@(W$eExt0W5rm0-5cR_0jcG>T$!$rCS@Pu?Vi zs+*7mW)O%d2vr_qN{)g_i0SwhJGkGdlBQWC0xK#l!7fS(NlBlsP30iz_ zJz3uMsG^YAC7=eoHln2_JM2NBfHicJ@9LiN5W7&Kz8^q zeyNa|^k~R={m8%(5g5bPw-2_hnx_hiL+qL2U)bwKre%?sZD?a~Ys)!a0TJHFo?Yjql;6&7t`6Z4tu62{?HWEdE2kDYszg_;|zZ;?2or zN}On@)Aiiie#3Ja7zc9 z(7J@tROQn2WRU{FFXN<3S6JVRb*pI`bNn8m=;)~VaEyxZu_ z>)WM9Eh1%RCL+Q>?tno$oo0dJ^@u`E14_BV=424{5m6A@NVihD8jv-y6OGqQ! zL%fOfy&Em8=$Q0%V`u6~ZioZIXtTq%mCT72zgBtteVu49*4Dn{sn4^*;5Z(vd;(J^ zON?+JiU37q%mJ4%!!Hi$)$%+A+MTSqEEgLO4wyY;8Jprl|1Yf2`lgv~dWuoSo4srX za8|Fqd9&{}u?@_`-Kk{S@9zpul%P$z#T#cllEqx|leo8oudn!rC9R3a! z+GM~9XuJEy8`I3b`>Ty87u&URN%S5N2+){8+Q0$7#oi#p8P

SLRnY(xMBC#c*9F zcE%=_)*9r>2E_zVt!vL&Jsm`&giqy~uqZVt+|K`l2g>I+*-9QTq>&tERoVPH_s;r~ z;ScB+S5|jh<0ef(5(C5GW+4y!5#y z9UfPe(lDe|#@Of7yksA z7}PkFxY@XbrHO))YVUMu_IWZ1fsW5FnY6mWiqU>X!yJ8$sPg{_ivCvQb0DJ-ql5$J z@09~)q7bN9_KP%IfM+QrFV>Msaado(=}pbVfPN1ZkNOi8t-v<^dBVc_11mx$)JP&) zl?Epc`@#Qa`iqApBUgW>Mb7XL3hzI6i|Y3Nm(w1sZtsFYEG8Q_AcKW%q8!}M+FS~9 zBT6MrYnNTlg~ovs^D&BrIJD4GNxwK436kymuuG%o(l?+^_RQo+J|8n5LY6e?fn&aM zqwS_IgL?(`dlxY2uU9XE*s(TwjU#nu2i)8lF}&RicuI*7xR`cAV_%J>{!%l0q@pTmTNn~-X^v0RVtJO8rHNF6Ne^oMvxp*K4dZKMc1wikj%LsJ2Em#-ltDGuQ)_t!|FKoGBkNsApLd04{zB2s7>AVSU_hgKAg*$dvB!Wj7xpaJQTAqL`kOtFW_q;AbAhWD z0rt)W^*U-Et|wc|fB4W*)7O&JMq z4Q6KCY&I-f@ty?p++KVE=tYUfsoFhw6ry@A8Yg2yoe0pCuWBpS^rF);mStTBlo4z6 zDXVr+%ZpwQMD1(s50?=Nu@U`;eKyrj2mnbi8R>f**ljKGOr;wK-75t)edN9<@p>8E z5L13n8j7kJvf9DFWE_eB)5v~m^=nVHQI4>j##UZ+pjn5nzjm5erp^Yg;ZHIo32j8? z`PSE%5^m7qf6SULMh$Oat?FHTf)`Y;3uEW92x+G5iX4@wJ2=rDF+J3I@To>P8oH-m zMU`f#4KceOO%AyhaJXAJkbZGH4&oh~iYG)~OX?pce&r%NUDRj6fiP^d<^O}K2L16& zWYrtmTox@(vP#R*^<}Jm=0pJSY>{wkgF)OD7oqu!VOhNU6YPmd=?O^j{3@6eDhGq; z%aO{t(JjOxj^~l<1Gr=KIF|gEpfKEpqTEiUc(T+PBkGRvyGz-(l92!*?hxRV%S-Ub z!ll9;5+2H@Z}n`x!$+NX(>g07gG>0YTZZyOn>WA-$mw!~&!2}o@e38;NHe1?uQ?^$ z(LsX3dDiSt*#tMN9eqDx4`o7WenCH*mhN;DKjlQEA(Do=<4F>(@ktj@phqgQ9`&bg z1wr)>KD;S;%Gz&EvpP{#g{EePT?r%YsWzy&z7o~>ZeQb>je30a;0t6-Zv?x$LR8u* z3Oe{a9)Vy)|2G-xdsmnHnGvXMb{nj>$F$HTxkE}}_9A1vC^WR98vqie0AZ<67<8)S zx-(NG=;K4uO3{d2l`}BmYIP9*FUDSZZAnE!J`_Sf_UTFDRPm|La1~F}tw6FiWWR~K zggu=Ipp4v?YMRxXtlUo6+pg(fSI8#Udl%(w1`Sf&xcRnp6a#&-H!cC}JVikeBF z13MYf!|$B;Im*PWKd2rn)k}z;)o4eu$WnY@M^_B!--3EXCH+Rzmw1~-R{&v|^Z{;@ zgND_M1(PR^o*>ff4jG9_@#y4x&C?UWmRwi zR)zJs%tzrXUrbsNGN?16IOd$cmZT4gj{H3Bx6Kf#t4id|38l`E9!Bu7<2Rkf&tM_H zi*ut=Ak&v}0x$CHNR6ogJqm@%m#-_qlO@A$p?4#FjZk-%>bUk5q7-1X+)rr-I95ih z0~3(~H#-effU6!+q}t2FECXg#$8)Z&2%+ch8l2wN^T>$VOl(Z=$y7${gqX*C^_pg> zn;EAkZn!pkU&WJL5qSQ#MMOq-~W2(nfz{hdIawKRRNCJYeI# z5sG+TI{C&9bejab1l3TzJiXx_de45ZIWC6zW9_oH0B(lsh+<> zasAW814CxH?^~y+wFXN^5EVu3tGMEs z)kBa?ATfd#N(Ls=kisw1Z#JH*FMJ||UuHB*znu_nXL;to^SHgNv=nVNzW7D&V@0SsH5Qq2tj{$q!q3hOw zZ6uqQ=pOvr8CBv#E$4l~=WWZ9$Y|vx?0DQc!jTojaztW{d)}Lj%X+E)T+snoGF^j4 z5WRDp!3`%hqJ_}H*s5E#L(Q0&ZO^U6jFG4mdoU?V8#!XosM#g!j=6DFHiDYXw2F_? zdG)e}X8WG{k~<;CN?5+(C;1uX{&A?cs$Vl)5>n& z?|<;SfAf7Iu#@J_8zxmE^EH<;+Rd~uPGC(|eY%&SOd{(A2%R#MUBpwOxULsx`heK3 zy_||##k+WB(`P^3lLy_o?u(p5P9~nZv1bTRBP5O_g3Yqe{OObXg%>JtadPg&$VnbV zuwv660i~3Yf1Uzd8>s8-LJ#e1)WqO|1f9;ULPZ=T6KKWCbrtD}IR6_+vvFWgteXHU zZg({K;SCL}A250<3(w2zUkzy>3mbZ*kj@bu+ZexDf04HaV>2dL*IQmBm;M!wj25zH zNEDk+|H?xNh41r~Ag?$kJssNs^`eN{p>yM1#?ksvQ)3-E~>9tu7P@%1Es@Emao`P%#D>k!(MS4>~YquJ2qX>B2BSm{3N8; zK8=5uEFtohdQz*upp-TMtv@vSw-{~j4xqB{b+Un3n{>2l{IuibnZq(j8?xRVBm_aP zyK%Z#u%&{q>aESOO0smTP3+vb>Fm>8X~+Mdc@BGSt5k=Pq3K^eWl~yeIxhs#VxHk` zgkYqU$p1-yjLX)a$q(NRfD~dPF*PMO)ST@V{r4QD>I(r6qgwLq~F`)==H z&;PC>Da80p5bz71(P=T${%q`*_s^YXF{w={1uTPPg87G0lst+cju?N}psW^x5a+%v zpvAw?XhAt>yV^_Izh_FYAP5X!n9c0#>yjg}3w%TEkRl09P4i>aKoBnAIDm$AlW=;O z(|vry3{?!eo!tC^zkN#Zh0^uABgAn5K*njwXZ^k4geFf?M?p0ea`R#~4&r;w-`rR2 z>xpPKmz=D(eIh@EVVfSb1p=NBn>k|JowPxOlbT<6Z~e*Sa+cW=eXoLV7`l7hx|@D@D8P>A$FIv>RwW*hL00{~P!LQybP^joNo%MjbR^xF zEvFx2fk{?K{U!SUTaMZ`o9YmN>m+p^U(`f%cm<50)WCh}S2tyAaDde#@ z7qf%Yi)1{G@q9I690viG}Rito9ofWN69rV0-65W=1o4)L03ZV1aV~z8$?3u zzjrX4RkXG7*$TR)7x_b!DhJMms+-Z6#2{C2>f~2Bd4(vHKqsJw{$6wuGXeJ1Csm*+ zo=>#vBXw-9*LCrNmUmT$5dIYme`Iy`A z7iEe$*-1$|E_Z-?W7mL0lxxLf8}?GU@>9Q!=P8NT&{5MN>_=%O!N{nCC09_R*!u7- z8_3F9H*r2v-h8U2Do_*YZ{}xXXawfY7bpv#NQ3xE|D6OH* z!4f06-6>0F)gDqghf9)HF$19_JuO~*Q zCm2AcEaAv3UAL|@?445IuDN2fy26y$m2Z{fUBW@m{}dy|PhW zlq1y$nNczZDe3zy#bl*eKCD`%(E<$2f$iou+}y5>$g{(zFwEM?_2>oaR5a1nYM5XB zGjA;1y=fDE3$tV128}TD#l6N_AR5o-!B<{4KBeqnc=)jLk_WiWra0Q%L!ZuXwKy}p z-E%qTA?Kdyx3rB9kn9I;&q(9kEvJo6N>;gs{XP8fs*s4aFq7i8$zWCv9sg2THb>+I z>=bnJUB^Ze8XIUc1pk?t_0A9)JlP6FHW^4;TncEQ>tq2UWR#U0p%zKQ$vg_G2qdbn zrrk{^Uec<)?ro3c9rb4Fe%+s8>?Vrf_cUv81)>&c!bt++G$)Y({nrebhEG2UWllB9 zz#*3Qboi`zy0%#fTfGnDdnHR+EzGqdEgH$i&e6!BM4z%+|E+4)kQxOz@W4AcK2VkJ zOMF`*8l7D0X1*(AO~N0~=%bmbpW(RO4nbK06iyIIfM;8B;1V=! zL=50)LAlKPiCkEi7Gn2Yu@8%7Z|$-^^JAqQH+v{?$7to(_GY z_G*jiEzBklD`t^@M#S|W^(ZQ;A9}p2`QhElo(!P~iIqFpSEvrGR3!7%d;JX%o85LS z8izx99r+HIyi?R}HGJ&IiWK&jLgKj`8 z(nH77WlbY(?I7mh+c~mK)<+l0Wb|+!8p6gJoHgJ$vGFHzA3e6_!aF16Z%>b5Ha88e z!>WGLEJ!_2S7-e&`hV~I()f-a`U;1KtIKz4-_Nrt@4XTKf4F4XMVvl z)}9&eX^*2i2uG&JLB7!g3FA04Qxzi?jRzsk|Cr5pBDuM(SKzlC4PgNslL#D9=7xIB zJRv6Q&&Z1b-zUL3spq)R&^3WOjvR)B#s8I2%3!Q&|D~}A68SJ)7tCm$FG7o7J!HR^ zfE4~@A+eSwlY!-{3lBX)d!$bux3wB*0;Kyg9p^oA<{UbrM42=}bNMnN&JdjlIyc?$v7@_LrX z4u6j9Qr*j`Nv;q7SF`IcP7^eF;#Wxk8Pll2|2LLCgavJ+yiFv~9Fx zFpA|gx?;*uUM5_DJ0#JnbTVVcOE?4sAMUmN+A;#5#&^+H8Gim(;a(!zM5B}X4()SZ zKd0r-xdJ7a(8*&QE_u)gX*w!;{4sLsKAJVgE?^bfaK?MN#Xt{JfvV4_d!Ef;%kjIm zXwuqOxq$ZH9&Y7=hN;sn2Q8GGF;TW|5F$$9;%2-c6jpP(L91DY&&U;>XLXJ7g3U0` zWEGS~Kc?_0TDW^Pnz#XTp^Edx^&N`Fxd7ARDIXHm*;%?>Tu#UL)Q^6D*BKbTE9#Mk z7Omvu=pQGQTjFpDdGO4fYrbeJg4Ysr?fX_$Jm*avuGH@CsT9 ze^fEs^F92|4v3tj;EhN?=dG!WlzN)?a}V-}A1rWM|8@bzD_+Y1l_fZSH%VBySr?1# zR~j9fL)DGC&(6$%C~o}U9f#m9cZdps3(uX9a|FI^?5KFycw5gZGbg z$QEXxG_P8sk{wY63rlHdMWPu@a(g1ktn(q>PXcom|1-C(q31r}%UVCc>`nxyP8IYom!J1~6Nd0@-w|q(G z^CXlPqbg_FLTw7|_X)ce-hN7e_E`sm!G;{EDbK?Cf)WUIZv*y?>!6UGnZiqy%lS2N z%?WgKoJ>?hL!PFo`6xfbk={S?X%re^GH^}Up-^L@pQY^S9Q&{K&@JMwO> zHdvab+laPTEA07q-@j?)DC3`I47&1d(8^y|ORkR-^It%aBZXcx7I}PRg@cl3TUDdIaD6BR9Kau-b&7IT!@ExYU!ROt(+*If78bY!(gWkQ6=7o-^&!z0lO&nsS=V6J3*CsL zd4T3UXz`oscv>R{--p|L2gJrJM!ydC$H5E$03zN1E5QjY?Zkax)OuO1d9Vy@z5`{BvS`GKl9@66G&Va^0 za%7T?EKj!59XUi7^`WEW&+*_%-<^y~X9G(q2wJbuZngDb;P>vBBT-`F72aV+=JFc9EKTveTpP=3Qf@5oU0nMDrwSgPudRw*5tII;M^?dU3 zvWnUSeC4asU(R`=f^Nx(w6*vRZ5wKCrWi$%9s>-}MyDo;;}ho>G-d46%)6Hjlwu4g=kn4~p=&-f>@nK)tFwR|@=uv{z2VB5R=1?jo1S^V?;P zVDAnM@{Q|sGQN>eUK?pZJIc73qkO0HPpgVEdNmp*@KgKQ7!C|!$$jlO2re#rOHKlM z!RG~gs%XH0xN`Z2SBNfZ&G3OkjWKJN$VM&DN!gdmPxa-5tT}H;h24%^m7I(EM_)4> zO<~#Sdy&!Ak%-2q+hO5=xXfLn?Y4wEuWjEduQg;uV-n$}K8}EtC?=L+{yBIDJJalQ`W?`TedaIBu>@f4Il~n__^@f{WWfn!;@K$TZ5FD&c`@AQ}RrGw|ScC zMOG=83wyp-empm3dOHNOxZR;oBLQVL{;uj(jJtCPy2HA%{6x{ zCgI0QKRm^Ob0@=T2!c>DwcHHBA8Ex6@ntd6KUcF8i4MzL88~y`l#-+YhjMb+x8Fkr zWC3EG9Flo=$G~t4_#``u&h#b^_k6=zOXHe`(MXm3gLJUcTKJ})h8-!~^P9DDJg9OA zj{piL`3Lq9fX4`iLS|E4t-^Kys2f^;38kA7U)Od=6pzcBZoWTu$8Q$rv`p|XaIt6d z=l4r^NEk4o#J*Z|R3k)(up!}ob-H$R>|z7$U8=fWM0TBwoltqgDI9p|9A|g@0pF$7 zPqV9T|FX_IdF^Ct8yjkfB2eXl*#c8m%rt;SEqSw!earX{I1EgmcVMN3g3!6EBxJV> zXS2p2(JFb-5U4Z5odfpnq^m%5n8xLqo-SEJVnxHClQReFMYgS+86FEkjp?to0NVLp zd|W>6ZVX{p|0N(GPZ?ngN)?6f-vs*#uXUEA3tj5JDa^>R+}(NwWph(=RW(sB6w@D5@9 zhSZeoEfLL}2yZ&0_Wm2x76#|2#J+g-Y9`q)jmDz%L#|X2VVZc^aJ(g*ngP z(Q(R}OSm|ws6QhosL+T+CO>7qVh;^_nSW|dn+}~odBEGKmI`ly6zwPAoUtU0pz!sk zAi!P-!ek&^*qNtg<2L9X&|DUTk+{-F62;z`T$EJj8le_HdLkTxPIZ^isxCb-3{VX& z&4qzV7g>>q$n9zRv%b$Mr^Rq`=$aJMz9naDg(VM|c=UTAsg947KE)8}PPmJi=#M0; zy?{S5UvUfm`bj<+K+^d_8ez_$u6a+ne?W+uAU?834Nm`12|3VhozIs{py-0IvjzbF zQAR#>QBhSG9%#0L77>+q9~T|aO5;>d!vcC0FQ`)R+jn(N@9+&CUChJeukt3vLcT46 zfybrVl@k+auPJw!$JANwQ>x=Wm4wjYqFL@Y*@GX{!nO=`AltITI?W_)w@2r9B4Ihs zw0v8>G!V@76l70*no@eomK!rZpG2F6l$hB}Kn*Sge*kIYWbJLG^O72B6BAtc=p92{ zrm(Co)9_FwRS0mk(9?-rELc;s#d=$sqx89IuSS8V`flUElf0vNLGjqqWA{g;4J}P5 zFuYJ2Kk(p|qpNS|Wi>fmN2<;aAHQ(t*Ws=Ftu*#Wk8|P8!0mx@GW!~c>Q9Z?grTwT z%-fB^dD7%zs?aX9Pm7su$l3l#k=egL#dh_2_(cL+!SdKa>;jarzM9&m>ufzzmmtH1 zawo%EOqCX!Dje4o`(Im{sg>r=7YrBfdBT~pe>EZyt;jbxQV^d>R+hI#j*7d0%PShh z2T&36>?M1d`1wpQPPHul+vNebAgM^c7*1FAfm&#pPp=;)>`b6S5bLD4=>U1Wf@-7sqschK3RZ#?%PSTz@BdqI1W^QPv&>BR**WA6Nrgt{(VR_^R|D!I3wZ(bkEChQ#Em^+V94MzH=IZ7Q={7ekM`}8#OdNbv~&C93S40|NR zp2tjgRVh8YRfbz)$IkhY{hT|Jjc!D(O?OAhMrc@_bi*W8!U2 zSGO{gTVY@5Dj-E2(;H)n$de~-clP54xT25;Vd0@Z%tzQ~`RK_=Gj>lRi7TOSx;%&? zmRm$90D_v49<|0Iy#)P{8vgZ>)u@_*?8$)<(0RKK-yIVI7@sECOMKfd_ySOGu0)L<91TrlG!=z90c}fmxYgE z&qvDdsY!-Lea`@pAs7R9ps=Sjl9`e~9Yi)R1drIeLu;)n{Iiv8H`sTE?&gUoV1b-9 z(q1U#+ax94XaaC@8DzQ6gKgDPXcqN?M_bdZ4oCQuH9NQ)3H%3slMO9NXC|tu5BT_u zVWCUO1|V0k%Acl)KI*U_&y_W;Ab8%}MSHqpT_u3FLu7UKDaYB#4}&D9{s}DB9S(3!Am(F+gVp4jZdAJJ0Fw5b zoI&|Ho@+LB7WmkxQ@j?NL4Y%}H!2=-1gxA_Mn2iNN2q%{#!gL1aKjdb4TrBJY2Ydz z`yk-s6`F3$C^(Yl zX>U4hXYV)%G0BX$j=dtV9b_jXB#$kUfiA}T#Y{{Rt5W5kiKUXbEcKE#^{Pc)4#@F|u0B5{y0E@TfE?2jON4oooaMh&yN9K%*mgjA-SoS!E%@0>CP;-I@qn z(`u;4O1`W>!-WI?w&)}rQ+jS?7UzR-)*;cg>44i^=153dsU<2Gp^OdcY}{TtRHP5@ z;IM<%hGk|nr9X?4pRrj{Kffrk>NRwTp+3tt3M4PvI{@KpAGKc$x$5QJ5$gzdj~a{e zEMr0rtPq~|*W7lhm*@^q(g2SxSChz$3ZW~k3yiE#?Fqu-i5yl@;Qz|?HX&K5?i|To z0eSjiUeW4VFh^gIc5Z1nZ!Xv`1=9!zq)t(bwd*_*6~w~ru+T*#&90rA8#cHRNcRy= z&ho z`4QKVCevpAzYQ|IPm-$}VI)2lfu#zx+QJbgdOzz7D2mZuN_iuTk*(PAo?6`Cf3@=6 zix&29kpz|e8{1Zl)neaD0tC#Y9h}E>^l88l5j2ngMQfLaRyu2^jzyT=%f?l}T02o% zzl{4Q^~@A&X)TZ@WQT5}0d!uA?vVxvE#~P`H1V}DU7wEseULwL16>s*gWRyi=s9Y5 zWU*&KnziLp?&LNa4w&L|f=-++Tu^`dll5;$7_J6QFNohVE`kaph|P$l*vpcH>s~V` zaS`)NB6^=^1c86J)SV~#S3CW$z*3^_*`YLM-N!N!loczlj6|`6+Wv^&=AawVFNY|a zGJTO0M`TC!UeqvX0){;lbY{I`U^gbs?GgudWn|PS6>mqC`C|`q(Ht&=&}a+S-b{|P z-~##!9J3xwbT$v4Y{EV9VDS2^Qsfj}Nq$pQVY5P8e>g|FwciB5O4_pXQp;6PP(-f` zt5;d4>WA8n&mUmg-4>&ON=VyY1hH zWDp3#(%{Dl%V~i)_8_E%C^4(!lFt(r0GT{IWtSBaP}iFcknwx^@q-?b+Li#>51&$M z@h7dYfoPN^czOa7b!L&h(G%lQau8c2k)v2KT2;Xt1O(uQ(??%0g1|t(X#1HkR%vyv2t~OmJ+N?t%p5UW-^n*80ai@_}NLIev;=DDu>Clhf z6Q2hn@{YsEcwE`*FKerv>;Ah@it6gpd}r zR&IJsInD@3XoS7DL<0v`!co_bQh?bh^5?^@)5)kFaH;VHs?YhJZwN0>i z@Ppd~Gs6w0yq7wxDu2%uU6ar4`$w7pwX7KHzk()dZ6s%cYwdh~A8O+&6*NbVI`69A zA$GtdMB*fk(9n~i5d#zKnvNk9)NkUn(h$2AL@(ZRhU`hS1PoIhY~*GwSpLcMo!a&y z)g()Ul(CY!!-kn+6G5gx0Ps7$@~ie{nyiOKRFf<#sh;~t;nAx*+Fdb6B_~uZL#^p- z34(ZmIn<1D^zn_P?R{|MLehce{xvjT!pBe>&6Bn8^wzJa3RO`3_D4XR5;+M&%2K%u zXMh9tYpwLivZy~JumMwKt}>h60=G7b{e0RJ38^OII&K13<11TC9a+1@YjPQ5qgz zP^;PS*OTg^nb;*f7R;|QzN_Z%o4l`{E5i@;zB8H%#>ko%`PUzynm#C=2qRs4EVcDL z-9b1hplZ!}Ix>!rV2v8i9L2KVL<0nTZmfi!CU~dtxEp)t+m55+q2eblFMRG0NDzx~ z)e1zB2~ZaWs_VhrrcR@#DiMKiEwE4l`q!I5p-(!jCqfO)^z_*#T_I;)?2$LP`9lVs zUZSY|kbnk86x2MXpufK^A>Vi`YZhYJ1MHknfz{9J#M_1AFui7TwcIHd^6!E!;UFFf z7R~U?5~%oiL_>e~J~xx)TSG9I>|O$P?{A;n}hbeyA8KR5?rD(C`=w#z(SRLUm+Cx_VouoB(uWnze;iC*i5 z`DC5J+5AF(kLJkT5}5GzuAXDm=t9kR#-HfX)w8(*+4@w&N13c|T0JR6aO=NnlZ<~c z;i#TSq&hXZ`FkEoy186hcAVuEM%cIua9#NbFb<~nc0MFLoDHaJZTaGn5sU>VW% zgy0lc{uuMjYrb8Z;Ic(KGc-074r6+l3}!;dc(XHxU9X6NwIB__(YtL3LXzHsNf*?rTVD|YKQmG}H=yTcLWKv<79^A55bf`BpnQTAJW-wJ(eWP*B% zjQKLOXS#nh(`a*waH$+kf<(ot^F9tCT|pgo{h zruZb28tV3)_2HWl`bUT9qv>0{;zB>M;7wJkOp1<2I6ELG3IUb00~PnvZhFD4r2BwF z`A0xfJdWQi0eF!o^38NXc8eC>WkzYmXUJfKewz6{s+w%hYrGk!~=i=G#u!IzX-c2qFP>fZeURfhf>)`)0;$$#&Up;446kv-o;xob+ zrV*ze%Ev*(EyOdP%v_@}<2RHh`}oaMV*nr4i5GH>N z4Ak4z2^rP}tBTljtI1I07t=C}0(nY!?@yz@=F*cs{ zr|pdKdbWbiApVpYl_=siYOXH?)r^@f9Yq|#m7_6Y_#X&)RGfo6F90OuSJVOWB^u}+ zy+8R%OrL{S;R9W2=f;0TxNsEUq;&a`HN_AXEH21PqQ|?uPi^n1HGC`!(SCjp5N`4JJw^Gj-wC{mH8lbjXMfpmcRM zRpg8Jv_BMVa8VeIn64y#IJEAV;JYxqrR+%vnSP~*xtj-w6TKw26rjJ&5ZLd!W#W_v z&8-T%=m*pv-{M@&x2^clR%oi_Gea4g*?VAhEgRZnENi-B54lc@7%HWBL6E4UJ~=80 zt@(J=T|K=g@hAFEtfAoIfj3#pjA*6$Fa_IasOq0+W-9EUcCJ?;I3(A?k;b~aahb9Y z#zqM$gyqG`?p=oD<)#cPI95BrKEdx?50-Y>nUWM|s^!He|h6vfE> zLF|O%sNyDx4q-D36g+&4p=Y*+#T*g^K3w|w!>R(7IqiHa#sD$hvn_7zEhY3jpag7D z62ZrV%T*0h1q-s67naTUsDqgP!e2`my>XCFtz7l0Jw*&Q61H_T=5b|bnxn%Lcfe<< zH`E~ny>Qz+vbm0k)gN@KsK)G!X1icWEU%Q4O)ju~s)~f=H$H_sLw1CT!L}OKzZ?el z2S^k{lTx1=lXT;JxBBYvTr$F6n)IA3)01)E6F21RC>Gq^*fcRhceVaI{{-S>1~akB zStKU)8dEw~VHR3Oc0>H$N&w8uO5yG4J#9T$hvUQUOT9`)UM2757I(D~G0C`g>AP)k z$6dVK78y6C;)y%mhspTHR@yeM(bXC7*y$gU5haCqD?-_J19U1CMPRT|x1YiRRfpu@ zriCy(%B}=V4+blhu1TTxk;66DFhX%}#738&3YtjMYJOCV$>|@>Nu!A+!ps)^%G6Is z4B@o77a?xEk1$jxa)uY{$`fAuK3L%Pii$ItR)TW0>)+L!*tyAKUOR`^ds&-Dw=9t2 z^+y!W)J%SbzVVeofGx5IXGn8OQgf3grFM7J) zQK|v{>%7Mf&xmRIi2u;bPT=13;^pdjlr2 zQr`ScNqJ(TWr4F9``cyBF!O2HK*8c&v-W8GHCL@MG_@@!U8J>P;rd7 zpX~kK`k|7iP@m^6fQ5+y?u+ZFXnIW}72njv$%076&iQPog=;6&6R4Ki$n?z`b7S{A zd<8y(gWm*IvZLcNYaq3NA9PQ!ISRI0hs8ul3!-e5Z`MzC+T0!{)h7CFq*iT`7ei5o zA@4)@D`N1(xGHE?N2c$>!(YN|oecU+t!HNZrgm_GrWnSOXH4U2AL^gh*wKMfxw(d8 zp3rXc9zUvYAL12O3_5hdd+F*;%~OJ$;6s!+-K(i~s_lY3u7LH)4En8_K0&WQL+Y6n zAW`)Q$-jNyYe-J2Igwxck3Ru9g|RAyv%$Jh>4E=zxTxSg-VqhFk>oS^PFu$G06##$ zzjLxbG`Di;)+Z=vKKNEWs;kQ`Yryc5N_&>(^481`NQcc@xd&Wn^%c{H5Bh(X;5@1X z5dHYF+Ll8#?@-1Pa z!v9#;-doLV-BSBu7#z@Txsh$E2OYk0av8XN=vIRGkAhIL!hc10I`4>N1r~Y{N#M;o z0eVeW_T~zI&H-X8PRlE|cYu0PEytG&1HsBedeSXWD}~w=P*{j}=YF=(%b`r+q`F}i z?51TI-X!Iy@IJlD3+bL?Hr%`#*(pY~>s``pf70IRHC=W62 zR0c6FG?*10Vc>0%Zoh;1&zRPXK%etQeC&0ara%TQ=aF3?7X(acth>l-e%ePA)t|XqV#> zXX_<*#aF(LB}YF*sfEKq(w^*JKMvjciv`)Eg?7bJ*n-QoGXcji>gps9xUtsw8Tf$U z*lB1jSiYSn+7Ifkzinjfd*%=y)E59K3^A0=5?cR`31}3WJP~_{1r5Sh1Ts60=e2lO zA?|uq-vfO_Wy6F{eEK&$S8y;aQD6 zhsE4ybO?b>dT_r^hShqZvU7NuLf*u;#`f1}b4XTYCVMwZsulwR1hH0j-p-$E zL@DQjzV$O|LCq|3Z+`k?<8S>bH&48*!HG2wkjsjCbZ^r9x>i$ed zlY!g~gVyzdsY?exrzq3Zi^oye{l%07^`q9Fhzua_fXi%x&27OQ9-q>eS6|4(6XVx+ z>r-uJW>Q|madE~R@8SD33I`38yk8?)bqdc%=E;79IY2gQ($PzUF*INsro8h<)2k5^ zTWT~77Z|_tULa1tK{g4NU|&(spHl{DaSxhx!9AR}cHjC(2sF;29`E1NRJxrR3K9yR zfPQfs%CLl`aY=<|_+{q_a@N7Ku2tB?lgus*s}J0!|wWho$gjvLYI-#`czqamMf zjYLdVosKY(*mFtEr)ao{&LeMCcI(mAz4g07ahpO`;KD;yZ zh(Ht(jGe&=*iMv+ri&mn6V1X}s+D|g)M-TD47GAV@y@gJRQNjbizd*dWqWP_`XpYt za-~{JD6UXL7l4Xw(9OL^WUYCRy$7(E80RmSUdx1K;gx-)$f zC2mSlWum~tP>t1ySO452mVjahDz0%&jDjZ;msy=cjTqTpg{%10I_%K{aqC{N1>9lo zTnbj4@bla|dkyKT1q3NIbp{;oqYX65JvClrwv_y!Pl{~%>7dn|zI1&H4R7E5XLM}GnLaKAHhnV-W(lYxvk0?vb%XL7$ORNO9J-uHAv4qbfV_Rrf#Tt}+<<+A# zkkq1Az#EOt2k&RW@0dtMvAQ<=kz1ft3A2l_rg~Ylb44YOK)WNI+|;2dgp+EMMNgop zj#qxEiD*wSS{M(^I}*DeOl>(aoZzhi)mg0pIT?aYLQUt|_wWO~zPuw#7@O{lC}RsC zBT3w1nES_74sPf(enUgaX)ha=ibc`^5Xn9hEn+5f@5ZpIWxWpaA>zm=C)OH{)v^in z+F_JHSs?z%)smF6pS_S%6a_46t5Drh^#~2~QzMJ(sqq~eEd~THZ6Uio1It!Z9^>E< zN@?xhJn;=sKkiK$A1QJ9#df~30Lwg&ohm{VoU#Qga~=~`TK<;v(H*_uL!|n=`ThKw z-bf(!fjECh?<{PX5kXd`8Sp;hqb_t&w`7P)l2=L--#M$5 z;XBYoHwe{ZRM+^Keqxo-l@$Wp?Iiyq8}lrY%R9tb1#aF9RFk;Bux(6nY~?EZ`a8`K zNPNuMJs65VlIyE@ie7lTWi~!r=ce>#k)sO4o5biIN3D z)Ds)rI5Lj6IcA{h4ffoDcbgOJF7(FCK@55?VAr$$hokyGGz>G z_w_FpFB|QoE1b%O0h^n7sc?T|Q4h9zfN{LA^r8~c!F&{Fj)FiN1Xv3vxr_SCrt|ib zlAH`%+c`AcchQTJzLeyUVqvC)B-cLuE}~`SrY4}Q&KR$tpFH|akYI)lL2P!k&Wjqy zB@3%a=nv9C`Vf%1N3biA5d{ozXHDL=0V9aQCq5X2S8V`12>2Pr57feEDp`cc0j9|uNTyWz+R7kwe zu|^^UKG2o@`cfqf=Xaa2g7i(giseC3!^gA`OJFU#Q&Pt_r2doiJWvIc!VUk&xc@@e zRPnBC0$`U>C>2o>aDIpIw2~7YxoWXjFmOPWU0mWDHsq+H<()gwB|iTLsV{O0$m<(a z`|uyG6j11XO&98Laq4*mRrA-kj%gDRQJSDt_kFDYP!M;QWKyG70#Cz<>7Kg}b(^ph zw{Zc`2RZL%+L)>2gF8o)(G~Kj8?r8cv64CM9lQzu zvv7zmf+djFhprI(EVV*>SSBW?n4iY6U+a`C;E;U zfM9gQZg%gh#=sT=%}cWOIRXu8!WxuOIkz%SD*#5{J;GY%n6bKPlMJ`!gRD(AI^$Yd z^OI`GV`|-oayMWsTDy zVQ?vpUc`8L8lc5h@{);;a)+U+aNS4k4|x61En%ioPs%K%DSlCE`f_|{_~85sYqR4o z=g=qla%>NODRjR190-nV{#qVKHH{oduWzxl51p5eY$1JS`z(Jr=r~t1r&e)LKim+v`pT zDCp2whB)%3$cS8WeNC?MD185U&rvU0bV?0(KKdx#Sbh=M>PZm^tm%^_L-me6I9;i z-1O~PEi0W^#CHRV`{4NW7`eS0rry!*r0>@~lr4sV#23Gqt{%F<-a1 zoyWA%gwV%343IL)J(-G5raIKs^SE-)@Re@BsllmYpLEGe2X_`=Xf2Hhnbxt%SFWk( zrV}csh?uRN3ee*4@wwprboLGBEU^=61x`#WzT?}wC3Tm~a{3(a!pK%HX@`7jfxQ$x z(DpfKGm^mM1CY%77ihS7V;CxM_5Ja$R0?QjP)=sv0~I>wsM~FV-f#Os#%DjKX-afJ zpz(bZ+*7%WSjOVN6CB#>h zR>d6fQNIz6d2JpEXnRh2)^ns;I52KAq#~QWP6pl4uH#FSs1d|%@-*rcbRGBq2RHDBFLV^ zBdxMpF7=3)63ls>sy9O<9u{I*9L@FfaU<#P`!y_T zvuTW@8ukNKFxnXMlc%WOTedq$a%rxtOV1sP*asSgcld!C7LIc(#Z z^g@U=$usdUP@hI~g!aPFY63Yh*d5(uKY25ayq_P^bwBo1O3l3XJ%R2!62{RDjBo)A zIr9B=VRL2I4W+KkEftxYzlZz%40+#zd$OGKTiXnay>?K8(K~mYRPsBVe10ptn%$)^ z?r*eMC)oP9=dWbDr%=u^Rs+D)i#fZH=NKLc>L6*Oz*4DKQ23?SObzh-hkeMYCK=(q zI#&CrHtRaXFhxglxW@nM;trE($#$0>o}wwIRi?G8xZ1Y zDQo{l`i_#ob+DMK;1lgh6w)L*f$GbL!w@9!_>nYjdx7mmZVAka@dv;~yoRe%8lLzewxF0oVZ@O}0%Uc7($4x&1BDZbbzqVk&(InWq=f@C$vFSr>j=^N2)*{h^Yz zFyP0WOY}9;wmN!rdJ8?uz;U^l>{V?lYg*2m^lU-OqkqDPEMqn?Yd#TpFeXaQZ-Wr3IpUagsMVprSP%psJ-` zYZL{4V-nY!63#HFDZmY#cp>=dIqQS~*O^t`g)U7y348le;-3VN$sw>@dy6UOlfRvM z#N;%fF1Q_dO$E+V>-|u99Z2+~=O0RdD&nX&f7GgVGn-ZBcx)?u?PxfQB=0z%T;xSS zKJIwAu-1aN`Fz2#XR0uX$@|vGqQ{XQ;F~k?xv~zCDte+CjC~0>LF1ZuhyBAbBR&=b$*|TV|@1y6O@g|;-0u5 zivQ1@!lIq%f8f5X>^MFPE0`CJ9Js)81DGAPBH4Uf#bGkdu+_3Xel!sM?xyHIbx^W6 z3@J)z3d;DzQ zC_~BombpD~r@SJJJXLU)_c;48wLWY0d4k8zUo!6s{LqBBiDEt37NEMjy2vAfUHqxH zx&%P*PG6D8q|=2fb;KQ|C6|sELDhR&30@(RXP6%pZ;LGBhTBIjmC`^MJqkUv8l__m zlVi;PzfL>A1uc1t^S=@=c5KJ5HaKxH@}2s#x9U^9BGNyCo0Cvfbgd|>E(Sm&%#mZ- zF$jimI?3uLR(qg4|6m@+F2klvW?(a%g&c}Jk(Q0yDD2a|L7AN3mi$`&3HV!muCt2E^?Vl z!W{>a)OO+sCC$w)F9ZUOo2IiBIZ025C+GkT07Z#iR2ir$L;2F^v?sX6dKT?vg(yO1 z_X24SgWv$2(+X|GU@DT-xpU`hw#`e=pEOcV%t=L=lPV~fT$lJ@vgDuP9jYj#fwuQa zgbCE`zU#GxlzLX&jv`^1Pqm`H$sL^8AtshS6+#wI1d9aZoDr01HJpAL^J`e@yDq8MDBiWuFD- z?19dFmmwb8f`Y9Lxxk+!1Amih^)shSgqPQIFs|6+6>X%h{m#~I* z(Y=&+dO+f=5(1DRCw#hqXL`^R(t9mB$Io+l3?+zX^NEce;sE0xk3Msei%$5Hz(%<& zs`Ah!7$N|ubYsLlF^g3`Z7(=Ke!^?#V6l_y-UPWy`*UveiNvuNuU>N?SPgXt;tHkR zT9T_ycUmVTPkscKySqv37L+&eT>%5U4iW2cV?x`NOK~%KhQ?;1*E~AOR}l@ot`p!8 zL&o#G>_i&_z%CVYd^en^a|;1jm0nI0sqYu$3L@$kY(S3P9J!eQJLnQs4-LUmEodjf zhDIv}g60Mp`)@MOaQW>jJ0Z_8f263gh(7~y1bWdn$wbcKWo;qV-hQ}3?rE5i%8aXQMj<; z{HIQ`UC^l^O0xwt>wDT^=MU;_gqFo=ZZ*KfLt$p2KtGav1sMmMWrL;=jwbtNnZ<6I zXCuJ4%uM}J*{T1MszciorAsb16DVe-Wmx3Ft0hX_M!^>`b&(+P=gyN9WvUQ(u!Md- zyuGi*1MY-&+-t17H!-HTgjQ-mqP+9y9a{1QUF@u?f1oaXy5I#R8vm_^Cg6pgSd92{ zlL`_<f$?qCa>Jdd3hS^D6W zQG6OtQ=&khEvt(6M$-?c^jfH2cF(b(-Kt)0oBpE>Cny(fd>IxFx@5W}zn8|2&%=L* zqZjT1FV}HEo1C}S<}ewgTVlbzYl@8+=oK!hm8>@L!!|&k3}g~R0YW;DQ|#{0LL99i z#kZH*&F5JT$6s65+61S{3RbjjGO)$*Z+a=OFW^TcHm8WT@`Y&O6OO^I>VJyYp<9ea zCBuKF+eX5$8qmn*boyCY+I8g1Oao+)IJK9-mM01f${`+$7g@5;o^Oks{T3z%6m|8| zgA*j4v&^ROu~hXfss-(=y&-KGDnXQ=1)>mVC3k{@5)P---FFwVmy_&?M=`iJP-l_G(3?E?K7oj%Mn7q{@c0mVt z!5@%&Nf$KTW9x%=K+b*P^0-GN$$r!YVds3&Lve<1{aaS165WT@*->e|6UMumJjcOM zCGcIV9mAxVtoM9d^kf0x8Jp6y9hGAL-y`fuVG@w38<6toZzqzyB`57Y}i zH|8#y9KtqXb05DP!EiIl+&JV5US>qnAi@UL11v%Z3pUqsoQb;T^otAoj@!ac0TcFt z7>&FYT@rwVmyQ2u32Hs5ww^ce;97t5Q~2yNu(=PkDnPTXPwox4L}YXONuF$|w|LRSnV_f-y^Pl8VR-!=_+5VBge@FO7?#%8${ z9_XT|I&&RBnhgzR@&yd>Y8ha8bbnT_L2J2z?rCh(rKhbkEa+sFu*PVKaCR=fmG>3^ z#tC@0g~xxSq#Tao8mI+t^FBF95Ar=*&e-O`>fcKh!s#-1c~Um0?(>g!ysqZa;-74% z8$08fxy!7o?@Z=W+L6mRFs%w3&n|2I^&oFi2eJ4?>3P#&l3Ix}r=x zl4_P}2^B)G=h=HEDwaERqE5|Qz~Vc-OvH%VL8V?8H2b&eLyKoprmSv)srB5 z?&(}D<89n;FQmu5R;@!v8ZR2+kp);Lb&z0>#G|AQE~O!l!aX@s9Z)W=F z{!%Qrti32_6duVwHeGJ*u4DAPufQ2EbU=^lA2B~zY-nh z(!cFzk&nR`Xa4(B;tIw7eyuAn)3E+K)JgDu9OUowLEVy>Mt&-HZ|i9bQ)6kqu)@?S z2buseWv*CD^!%3WKOfWJ*lu?eNapW$%dYFkF|P%xY35RTYv*RFYv2b1jI5DJRrx`L z>|fm8r&GcIC@%zUpeQ!5_60N#7|pAOE$rD4F;nHXB&tM3ElTRSIYyAb(Am7}&~bY3 z5uo^Glvhg`MHI+ur&Np>0Xne#1owU82zk9DQkbK_&YQV7|O@b2UENW1DklA z;#~{S_E8_cVG6OJbWCA5@YftB+{=y#EOksub;CEwlcGH}I+L?kBZb4ZG-o;x&(!uNe)^SS+#+!No3Qk{s#vs^VimQ~=&h3jja z!2wv>4Qs!+<$RD_SrVvtWO-iWegcz>w{$wz(w$W8U(DV^mrKEc@ z?*8&oFCn(ll+|%9Y1m-j^T={A+QKs=hd>Wqv_|zW4%3?@VoT^tS-=JL$a;_%VXXpE zh)8r30S_oNP6DJ&Z9BzpL~S|q*BjowQNeDCP(0+@NuPhZq@@mY@Mw}e5t2JDpGx%t zjEkoBs^=z)z41iX)FG!GY6hq_O=C(xu}~&)cS-XekC5Q@$^4x6=OrqAbH^Yx)6-2H zl~f4AY|UR4>KaR79u6X*n}$)lB?1%UNwDV=v>qteBFEZAViO`NI+_($ zR>Ukl4hpdT@InY(11=K4b8+xWzZHZ9v_54AiXr9l9vl$qV9EmdBD#_)0S^|(-yj%J ztVV7`_ll3%fP(lGy9JQqs;z)kKUO?xRppx8R0*yrFf7Z(wD6zDRM5{c`A&?X@n4Od z^#q`*tl#ON5MenoWk-UkzD+gHr4(IyjEWw{=iM1~F3J%8q){&FPlU#2o@7+r)uezx zB+tET#@yKs@GzAP)}q!#p2_UJH9KdZ@EMS0Xr4<^&}>2i7$uX-llc$9A2R8^pFbO^ z3{Vc@5gs&%4eb^=wo8R@5H9507v-25?hq}Y;P)EUf2P7Tvz8>MBABpWv;o7=8j`Vp zI8nqvfTk%CgE(^ag&Pz0mb^TrTzN;uTnNj!bR_P2tKSGj9e1V9*;8*lUr7H~# zPHYlRN!}Yvxv(Lb%f^Fo)fMP3RNAq>Ser#0{&S57w#NzWwszP=9@XAm@>zb!y=x52 z&K|(2xF%`n2^6wip0M(CmqoKX5AdK6U-^6rGR{e5;V*jx4b-@3eNokUOl#1NXN}NW z5kDlMPH z$I}M8Tu8?nWFbzYH!`uDK^XVlq2opzz6nNjA;=^=7uMG@<;`P2?3xp?E&yY+u|yx7 zv`$y(qP-^bW;-pfK+S~=ItNPL@rf~OM-t#yx1Zh2pcr>X??Y0v_LOY{lFe->m%3(E zYUgLYX|oW8pFeGaQ`RQq3N~Xg(yPI=X+!6t9ez_IgMV&MjdjN*V+04>6e=3`t6pl( z?Hmp4ms1x5#_#mRsI38+L-_4B-&2h@YXV@dQ%M&x$OrwU@71vFda2hzz)m{1@F zAmeNyb?m6jS$kV%v7p})ut;OO{(Z=&nqK4RE3={%iYF-N5H;8t6x%Ozq^#M7kuh&_9aO zOt=d{L1aGVD?bh>Hv$1LZz`5++{QtY5<8ww-(6gy-VE}g6ls%FIE)_-h9lbMBws{+ zB6%*%2?9B|mfndRcr2i+QW-bnM^I34Tl@Gcl)mLDQ5@& zE72rqqu1zo*AX?t)r;6tgQV5**1rKuaW@;V-F(8laZ_7LVW^lxpxVT@Ti{IHt*Yn@&OEohY7!kNcE z9_64PRO(KDwblaSsUfLtapxqBcE{%+s9ny2DuF>*G$B5-kSe@KHG%hBSu|NPO|)FRodHJe=1musdutw82ZEU&BV5Cs|O=!k{Kh=XtN|o(|OJmI;Ki4AQqUCNQTTw0=}5z?TS>bRVBU z1S~G7=JAchgiWE69P^Ws^FU=;l;e!1khFo86f55-8z6ur<~Z@jG$-NMis@LZ%Q%$Y zUbYl0#9%K;`n6gRrkov(SaxCUE2Dg5!K&}-z(9$A*o{JY_3qjHp}Mkx`y|ZD;pBAk ze8e8viI1s;yqKh!nCj`Ty|`a!o2WSDNwno%-}@!nui(C(|L2}j=*~WIWp%+pVyZ;}dRDQAKr@>xVPkTAc{J%mM)6-fGl(m`cP%)q|@ zQnyBGsQET8-9!3vktE$dBv)56AL%f#Sks|3cW4(58n(HH!jiaUMe=b`(#z2S=_p{v z$@KVp4ZBSy-PGVAqU1!zQh2RW$0{-AmYLwMee&0Hie~0zQIpLu%&wI;^S2_gKn`l! zbPlBJ!J|@DXJ22Yn+FP63DF&c|y+)_A8cpZf z>XM>rAN6hFL_+kG7x^EX|U?Ws_GJ`|EcY=qUgv zi~&AS)ZAfmBR@D--HdUCOgp+N>Tu`=mf%wTLG(h}Fwqxn_@ZJBA#YkGP-L`nyYYX2 z<9ZL!ekx^i6|az5Grva&q87s`{4WC-LFI5JoyX*a`M8?!jK6C&Md#0os)|f@T(1m4 zlsUy=^aR~@%ETNPft|n%Zgz1PvV#`dI+>4leJE|w@`W_Oj=T|S06Yodl7_l)0}3Ek zV3DXi3rkI{UpQ^*j*5c=cjXQ;a#@6I>Ieq_a_yz4c0KkFbpO_;L^;qSC{=pf!aF_e ztcES7k+>DFV+nTW1&jPiGO1*D1tWgE+j<#N|4LTA@paBBL%_ItcM;N-9VT(zt_FdU<0g8)wn z!ujL_9{0sHPc%N;yC@%><#JrM-Z~lau5!*N!azjg)23qb|F1JdLY_8|Jb$-NFb+1f z2GtBFK&F9dympZa+ZObT)8u=+?f%Tpqo)u}moDF=<_*_ zx7S%$%Ti;N(D!px*m_hAh5dbCDd(+ysY{c}=M~hh6uLn%&^cNRcFh4xL5A@}E!f@( z8uDc9x~%8})XPsL_({#J$gbnOxSwB`OW+4o$s&!y3v~7B2(5;hFAiakAf#tri&e2VkD`K+gCkEFZ~<>Xy&O z6^VyU#8I}~^uw(=FPP0wi~G9f@|r_JK!f9l*h=$Uh+zOTv-;dT2Qq$db*iFtRZLmF zeX_yGvAL^72LzxJ$!W5eK)~EzTxV5;k(uo%!`k9$BE>v%*8%FeUjh{(0DD3X%erGK zRv82$I!{C%Synd#v-~AE06h)#IS-^NC5KZ$)%bDQY_$x4``Cx^is+(?a~_#>YwWpj z8e~B{ecgMu(^_Y}xy@r1WJmR>!Q_XlvDKZ(eDao=^%!DwVK;+Q*2=$M*0Zqa_`L zb_8`}dy5uK5_p;DeV8fLZfx18{p^WsWx5;G@rh~uHl(7#w&>rQesk8zA~%NB*bEF@ z?aKlL0K#YmMOgsmS5zk0Dr)=BN64PY_8O+B_Yni(*EC3O&atE0;)d%!g6h^o$Wj`vsFh7`E1@4 zs9dUsk)e3hPc#mxfkq$yN!HEd+p?rSjEvedqkNZv@@csoOY!%#ALcvI0uk?6) z11W=9kAza-4$j0L3{@AP?K|;!@YOXFoO_UGzQhGV6C)0!`oPUV?nGRpXdP za=F_E7Mj1Fpgd-#TLXRF$e!tLa`e}NVERgII(H$f2 z8TW!mZr^~aUS)_p)tk+=&(9Lh>TqWj@`6e6VB=A!&1yd;->@A|9fY$;qIB5bal|{C zV%EStTI;z!N6*$B1^4{r&Mk3=J`t^j%bziJhiWaV?V_#0j? zvYf(saryQF*_cn-HN_1Kn6PwNAVoVc%G)cH&^i#OW}+$829sCA$+ns`!c%4;dV4fd zJB7S?&bnkJxqO_+X43`J=LPQf+C;M19Hu3n(%H?S71N79Ds(9GuyL76*{svMa!M{= zN`!^e+w@7*=s;f!VF^|EEtxIS320wT9!S4$G3?*^VT~{*e+P1dg=|ffp1rY*|B;Fy zCY${QA=(}ndXroKspv>pg*ih(V`=EG2a96oIYQVr>nG=6{lB4IC1-WkI}TE|$`vd0u!`Ucj_%_g)L^Gez<5> zAhaC0dhbl3F{xX;YLA|g=rvUXIMJfP09Mk!qL1FxVS|_Z@}MQ122V#m(?E#lNlZDaU;!jw-wiBuHivafmUmUkqjO zhQ0god;skVqSSE_>D<#gEkpwnqSwdf0aWN(AKv}~NysPL3nyIs=)OmdD#eU*YnZKls|VkHVorwPstFJVE`tf9H{6?Z?q-IZwBmC87Ojs?sJv zh85PO@U%DE;%q(X`+!QE$MzQg!#FGwZX0DxTIt~To+OdR#-Ab*aa2(%fdd9aEuF`- zf~oM>b@sKjSP-h&?Ka05x!fO)W~ZzC@`aPD+^ZIxw{`|mS?Sxtj(^%Zjq#r~FpCsd z{VXd-Feib+;#pABO$9y!2?F4f3{k}v<_>&ScOsCc{29Nxg3T*BLQnN_b*w8TRcpFi zJmha6|4+go|E-lIEndy|c;`DzKlxOT#rT%OllrDom$p@#*_la{vs));`_YS@rFUf= zXV19nUf;s@XnppG0l6*q?LjZcUc&g8UdNj^F4?pH(08^{X*Nw+e|CTM(T`V8y!T;@?kgYk4HA zdj(NPM+>{Z;b_6DmozgDlaFB%hfxhXdbAb}!p`Q+(dORe@Wajpl-Zg;E=-3cb(|dc zi(H79ZSB*+PQh02u$Xy^UHQAL5Pm8uL}2vSZ<7tJJ9s{vd8(l$D~0WBQz zIV{B7;_&2B72i}{sJAVjR*2L`>;hvRUZkQaWg|9=zqd;cyo0m9!{8$Tl4 zbcQZ^MEmiWhKFDz%qTPlxg6k;5V;&`FsjtCzZ*Yf8umzpm-Za#a7ItF9~@ce%daki3Ys1Scc*?ES2{hV%~nbe{MQ&A!V z9Uo7qx+qz>$%EC0mT6uHJ4OblZ8JRb$WRpFu>4{(`Ud6G^(R&P&!erP zH86ZuzO8^2>W8gPXk&BN73I0u!g=*abD5MmTu>|ts?8II zyMN?w1g-~oet4p2dpZjgD9lEjA7BX~^$QE!itHEV7244NIRQ$7XQbyT_#f``ngEMO zE1&T@c`;A|BfchDXjrA#TgFe!m_V$sUCk5$fcV2JP;O)ud-4)^Jd4^yga#VJMqTCp z@Q0gJH+F)~h*s)_JXM(=>tw;@DRkwfdkekCOx+7zW-e&aDkE$=gfkXLLR= zyHaXv&S>}w`(S0t3Qj(NH;SO}=Rb-Wgc3RxQ#nQBlwB1A+BLy=X<|_W$Bx$~euZd%P*feO^i2Er;^ z{BNCgoDO#Pj^wb19ip6HZ~)5I_eb0p$FP*xD>hCZ37i?}NI$t4{*F1&bZ3XB?MMIRv*kLEOJCO9fXrjRUkAC#@+U3&sYMbCLfS^N_ofOcY3x< z)ab=SCud8s;!WF8)#_WaV8G^@qSi>~>1(hd)R=jeojqoe|3*ON(H=9G^YTV`&#-WvOY8^zuHOL<>J-EH(5@sR#A<7Q5;r7@~#>~@gxl{;?U4iyf& znvQM@Lcc%7&dRBN?=6gMY=djx@Hqh}=w=hvvM~?;0^U#DK20vC?#{2t`;0}~xuMXR zk79R^T?lsO=+X!yQIrT#O)sG==uo8&C0{4FkTZ@b@K3@;NHW+JIHcOF!gIzM`)7RG zLdIY6ps6@_=zdYR?3f{hlB#CirOxx}CxWDB_`XOdeIvyfU(UjEob!(%O6CnO14~ex zaO(iifEyattx_0wF?HG%I4v=v=Q~>*Jh+h+w55dZe=bFHI z?I`rCPm#`a_l!-0b!%)byKBp&-4L^fCA;wkFE}ky%?-#uaoI&Sr~#Xl-Ve1xoJ|Ny zpl5yH@f<#Koqi53ggsJ?sf;Uv`R>S z?nhcwxpmd-hq^_15|z#rXh`~1K?WEtp{_~{o9^(zAXsuYKEe-C8EI@ho1^VB&~ z;6$I{k|A-|{drHBF-Jp_;4iW(bq*6&0KBaJL>3Ty-BWILF1-k5Vb+3+$-?%7cO*xL zv@Gu2W>bBBg7S`Rp+!6b#-2Vej9{R9*op#f`$#9E1u4;ehs~w%;W!m=0YW8MUZ5h1n$_ zQ6>VerCWOd@NE*SM6bmDQBo+=lbOMiVr82UmuL!8o<~k^AEj*;(?fgqd%z|^y1Gy_ zn`b@pX1_daEyA^J%JCpLEnKKO8e+2h!I=?|AT|_5)*KzUP#0ER z+Agd424O_rDdh(k9Btc}@aZR1k|7*ahlI5GC1i}DSoVH+S7yg1IRE|eU5pY0w%@|l zLArD(+&GW_%Dtw`UGQ_dvg1}XvH}cw%nXdZ;t_g0bH$R}Y^iXWS9Ix>j;Zq<{EoFV zV-Hgqrp?e3ljHkfuX7CMu6A@4oWF6E4s{ql1!eGW{IYRAy5?iIFO);!=>bE!Lj65c z*=0h0Tzd(D*dcC%Dhl^x+cpOCWvuhQVdx90$YBv}RtVN2#;dfEQ`I0TJJgqv?|83U zhjsvV#``wG^aO2wl3G|c@j}uCJ)~l}#SIJCg=d`Lz7x5PEm+JLwY~Esc2lUlj#K&D zyIZyn0NZ~oKjJ)!zZ`5Eu*weXW{N3U&labvzV>+fP|gasZxY?Rav##i01nlQm*)M) zu)MABXm5v3DC+XhsEP6p01z~t zSR8JIP4uNA-Duqy_z`f>$6jp?%z3D5hP;a^nqRG>d3(|=I1kaPObPx)G?V+w_4*H%rc6`~KQp$DzsfC(BP2`PoR&Em}z ztkI%jEi5QUDr?hp43qi6VQgm6q1~lamFQY!by$hqa6E5HNeT^+FPzNPOX_uhxhX-7 z7#>&HOXU>_%~kY=m8}jrqnpPPlbD^|%-PZPv4uH2M0HK~s*JHwv~~ipfe`F67X9xO zl;nzX=4a}g7m3&aYiIk406jp$zbM?IGyifF&Ru#04(|h*o_^&{a`c<*xSua?bduF1 z6_Rl~8GK>+;9O#FrWYlLH@V5+`%yFsW=hS!n%vO@{Ju)4Hg#sSd zMRtdNozhBO^D&E)JW>sLoLkt=Ka<8nx)1(|U9pk1CU0)Ks9P2XsqDq$S=^VRR6g(K z?gGVTDA*ECL8a5mIDYt4{CW5y0EWgIByyGyfNy>>YLMK)9Fh%`zp&!`;l!=pBs8O2 z_K04+K{&GbIZgv?p!;q(?nT7s9ntZNIw{_scU8!|4P%b!@zry?Bot$o4gJ ze2HgaL?ZFiJg5;qYtmQ-TEg(f%$<>=34$bTB$T8xWe`&)xeGL}AzZK^BAQE6b|L-)a)nHXFK`<)QZ3ZoSAKLXk0(0~okzp^Xrf@Uw! zUTy#t+hsho*j`8F4dulo0pBO5Oytw)1vygERv2ClSRRavFiTprPN)F|qJ;%f{g`^? zl_Oz*Nwpm;xrX|etY!x4{#~6tsWZqgVk!bLQXtWhvK8Fv83UiVEG|q-nf@Jd=3I?% zOLHX&2J}OZ3yL&2-wQUCuDoun;URI7lMHh?%f2KX&Zu`9g*Wl#7ZDJQ4jJuuZk zvg<)Ars#DlqA4{;cv{XUVO5-Bud!xu(Re{SU(O{miV$u2w4;|oJpU>1iWC;#v&{F2#rsrj&kKxlh^g2AVoe;`Jwo>!MGPi_;< ziYPsxc}AoGhrPvV`8i7{YHXKSApews-a+@_51gwfEClz$V6=%vh0t|0cK&<0MxMW^7x;hQyxAC}Wh5>=eBM@tvcv!eS(Z zav-Z4`OsI38h9^n$Jbf6&M0O9sKXHnP%q$ni#UcyLFu{wDpqUGpKgv|N;)2LbJKI# zhQ-C#k8!RU)7Hak++nb>=SO|?o0u;KSi;@ohZR$C$M#3#EZYYVYKwC|ahQzAD zjj_;?L$7g?%`y`9vP3qxD6=v*C*#SmhjE|}67QgymdcjkvnXEl?is_WoqyRd+qigI~V*2^PS zXF0iuqR-?Y%=Wta*idnY#4xjgUuczeh~6c-?2e7*KtO(7fp`j%_u^i)e@NJV5>Z{T z5=-oM4ZhOQv#rjiK^v0cw9bU-v#rp#lUFDy)DM%_et0gM>kfTlgG=}! zal_G#14aSqtO3O5ur-eKFyA09P+J^7-?^NyL@!nA=pQceKPA9*k%1ugm4O}M^qA=L z9ZMi2n;5s*!LQd6eLXrsQb?LfgDe%noNCt@;ohD^La%?GU*TJmps-XyaWd;UpQlo! zNnLi<#OZJA)T~w3;%~6r3Zbrb`VH2|Nj4ox@0|$5da84%kpXJFVW zICF6s#0C97B04^UwJKj`Sc*8o1qv@Mf1O+4aB{UDSbu;tkFwkQ`r|*0Xn93uTvrh- zMI6lAxoj0d0Ceg8zI8=j3(k<+Fi=^c=8vdkmsdlpfL!wLhXYSqwUo4 zwr&(DlX1*+2_QKX1RaA7RKBbB=fdP@AD62Z1cH@iwd18GzAIK%K2#mIj6!i`V`YnO z@v5G{RRNe6$_QB&xZ|^{|A;nCQYMf;+1JFHVNXmqBV0b(GMKbb`DmNTQbStm0YO1a zQ}r&3XO}a6D^5wN*RY67=h;G!VeF2uc66?Xb>Yn(&-5L~*lo>mekso{!{@c@=|tEn z<{Vh)tF!+QtK=;pDuKVEzZ&+<&~n*!%zgf3J--QhyOOzYeTgFS$Wew{P!+)g2w$H~ z2n13!MV_bT(`XHW?JE}=vYb^hOB6K{2Wj&lj?$voHJ&aOrAjVCQs)j?$v8`v5eOH7 z7Iuj)S8K|nwCyhK-#R^7Dk(q}8rAWZ7Q#FY37_QXJAHPgwN*yy-Hsxjp`bPE6$z0d zi_IWR0PoT-Z#!SiJCWWpr-!(XdG`oqz~{8-YiyEccj}3(w*Un zh&hMVvmEAQ!ym;a$H~MNv~-#!9f^k+a&o9TR3j#OaWa|>+Nd=p8QE#Dt#v?HF>!{4 z6&!OxlEXMG(%bdx`?@rGJF_F>4Uzm-ClvED)BNpFa|?~^?l|ggUdeSNE#Qf=P6 z2+af`?)#8#ZpyN!FTO7eFJfr?yRSO~pY;=P;G9=r%WF!(@k=hqCsSBmG&B4HV*cKmwPocXF9&=-IhGu`+7 z&2%6vE^ri%Kq%4ibo^)Q7XSG4kkT6%G67{x9`5t0AgJn$>X+hL4BA-VORlS-RLCyW z=5Tx8wVt-v?ZG|abVJICE3WUP7Sd$(ws*?R!w9sWchoihRR{xGH&&%Xr-7eToW|8k zSXCfp2_Htd4Nb;85b|CZ$kcXY%VT~?pgMuFW@X&=^#x` zmGWjsCHF#Z|M>()=z=P9k}Y!wdAqX#oL}_LFFt7PMl2rK48q{2Ka;;Rl+hdN#?|*A zsPk4KpUahyO5sW_1zfag&WW0t^Qrq>H5qJr{wY!?X)G=kP|i;VEnSXM_#iT@ zi}~d(UxR0UU!H>_)u~B*1!J9wFxo0Zpgg@udEDO%?4*^B%CWv$-&a$}%Iw!>TVNLQ zB=^A)RrtWSkbZc8=ZTQ=cPu6hQJ2YjN?fZgJ8bi71$NueSNk}`3id5T@2sITq7)T)f`N?b?9to0c?Sx^f%3MHk`w4-N4VG(BJx}pI!#6(+_XEFqB-a zQ$Wwbqpciq?~op%tQsLquZ=6;mH<2Ey5Ib1kRkahqRWv#vS~Yx<9Ldyx}5ZBYLLri zea5OBsv6J<%6&{m$>eHh`b_t5U(8CGAB-|UT|GXKFv+)$u{PSC_wcn7yCvo3J0K?0 z6?sa!=xeZhBY?9wy>xrpZ*>Ppq9dPGRUc<*BbM^t5s(>`e_R`8s^QM4;Yz09evU(j zYv2sSEbLxoF#v^x<+WU%KSd3+Q(2TPCe$qUJq~TorGv^o8o9CT#K<)3Kb}ouaE-v< zZ!ysCxGa;C%il@=Cuu1VweuDGOBz4-0e%sY@eFVM)vi*Jz9dy{(&6)-Y?a0e{Re_w zOb#AKO|%Vg0O;H=-m&sue%otfBZ${j2F7jKRaJ5-yK2p!a1$yYk4iE)!}%Ldz=XYB9G6JeAXHaFD5@4ubbxv5U_MTy3KNe5P=E6xeY}B z3g}`PMN=iJ!JRGQvN0zklml2^QQ^2!@mvcAYVrU#ZT6xD+=8>t*hcQE>x4Z>35FPu zY%+BBwyg*zw;`kkF>NzfQx#o-;kB$zkDtgN(Vhe$iARc4c_cxT zt>#9Xj~!aLSb!aPi6n0B#BXi64&aW=)v*ihA`(sZ|I15;o|=~zNw8(MgnT=S!rna< zOWPv2nGzP%v$(n=FC{ zLFvJqnkB@!b(TI{l6FtLH3kRfsv;d%o&aNBPQ+Sd@lmU&|4l=6R89%A$nT+sZFJo5H6LHtaI>9o4iCSpOnxGNtjvO< z3Q-Qnb0%Kfk3g@1DP|KJkU+J?J5F9i8kM=XcH17PEO*FH6CUBIW5i zhtmt05U`*^LaLzKcv|FI`qtJrjPabm&tUbH&1vk9^%!n=P0sIQ9l%Q&C;_dimE0CJi5vdg~qQf-tFe;U0_hwhG(bDnJvLan4V7%CLe zET{oxP$SbfciW#!BnE#C*I^sQc|Pp*Qif3p>F#l1(2=TGrr1ww?+~o4A&iz`%D@QQ zDma9C?#rkz>I}z=H2~Hf~@v9b;1Ltgt$uRn^I8(i)M1@DlAHIB} z8PGKMRW%=V;3(Cqzx2e*u=De>Heah79h>^$;&bMPWn@)(fUH8ozbin=gL`WIVl2bw z7ypChM^NAhPSlLPG7NBGKA!*tq}ees8`x<=opOsLG-wX?zg7x6ZG{H!X-u{ z|E^R#aX^*J9l7=9fyRpf!^SN#JQd>N$SwWSvH`A-NnUIBDQ;u14S7C~wbXu|Lg`01O4)#o&!3wmuJu(J|lYL0DMyCsLOh;R#ddFfoX=@#UQ6k^d!7 zXDv*P%9W}q&oa@y<(UdE>$sa@4mzeT4apG7&#<&X40o8eFXxJ6h11C>Ck7th8F$Rb%2H77p?4y1nBm{V5` zhSLK^ehwG|h-Fm{G~#h9Su3AM=q2+-N^!Qs$!P_6G4tFfRwDeTe;tdeFD7)(t*yt) zFxFr^-|C8^K6n!j0X6-#h4IR#E}B734`qQgCI0bf5uaW-twS80U$(|(7of+cMGcj z4RM7v+bvWH!J;hCIr=D-o6XhC0AM40u0hRF4eBLUqF`&UX9Xp)ECoN*Y?*A2)NR5(XQ8yxA}fB7ygzu~{EzbkVy z@|h;SI`#mC=E%q!B$+2d@rpl+>pXiSBXNc+8WN|OdE*QJg#gm&A~qtEcZlS0Hz<9s zm>@PX<9<`-o}B?1D}ApMU>4b$eFet!rtC#%Gp&bYNZVE&jpbtoSMDARcf}oK5L&`9om;kE#cNy zVj-aVM%nla)j*?$&jh{+nI%|-5%SL(2k+{bxAo{X^p1Ue6lFqEB!t<{hFA@ZDv37 zTDj}4e!>SDe4eL8CC=MDTC!u8f-Q_6K4CqQT661;0W;?fyaa`W`cJe@v`+YzcVqn<1i8ClOW1gP^#?t>YnbLReTPI;<_H zCuzw5D0xpH9In*{HnEY)Q=K@QzjiW<<=(}r@ex=eojRiHM!o1|pqj3wF8(?*RGB@0Eqi~{#=*r^;HZ_!#&Ds-n_9CsR z{r|8vFIAX?zkw1T*1ghaf0XruX%k241U!2p1OZ$;1~uw{4IGC*2VjpCpU=0chR}nL-}MR4y#|!DXk<^TGQ8@++UqTQ&nB6A zdMlm^|9$lX7u@EFjTagVB}^caTv0O|I|;)}f@85Lp-^)L7zkoSJYMgQrV|0A(o%7~ zUSpLK?=prU$Fz)T*88MHbv79s>&c8w^MXB)QYxyU)w83zB8dMzc8%VrUv+ip=~G+G zO&p^W<}G8!JK=2uN@-9~BcfT0xT5CK)4jX>EI!^aW|l_lY%i|x2z z^TAQFdhnZ%B$cyPzdo)yq5qcd?Yc%Ox9-V~Rep$dmeo1hKUIrlMDK!cYJ@RDY=>A15;n~&1{#~6zZ zsK8FUr`lhRLWnQC(IgyWGvgN{)Cb{F(52skcnAtFNK2>Fa0oXWC1caeX8_isj}dfu z1Jnj0VWF?dy22V2`MBxJi15I^Eng3CfS7lLL5fu5elp_iOW9hDi2PNxr}rwjPvNKd z>u7`AHkCok3*z_4OZ;Nnlf|(I$Gm%2^OEs#0t-jBMUqC!-Qs3qrN3BW$-kF?kAzQV zy-nqFB)i_{Z%)ZKS4z}STS0zMbI&kQ%Gkz!3w)8z&jG_$J^M8Uy!ZGuddM6o!N4t& z+*2V{?$V9dErxyX-Q4rpFN_gk#P19x%a&VTBYE{~7TrK8keegMR%g>b(sGit7c28x zkc4IXXm{NBl)~DDF+jxE08cR3u~X;X$R3_WtFVUDnHr+V_Mq`6Lm2fXOu~a~o>yx* z;3u()A{QB;4bH~*4wdZAG1wKSK~;-kyaYIESV-2G+Q3jtNI*%63(JDtNjW*uR>@Gi z5%bTdP)niG>X+ZwCpWO3W}fZVllPq#7=7GT*MaPm6c0Gc7y>a%@u*Jnn!fm7B)(3@ zAmvC3%yZNjWW7ce1i`mw7!hNlE#B-Kt7xVCRmAJ^)o)^PaHE|C*-49?X3!+Y)6kCd?F zmyd13PQHqpoQME;6P3sroW403DhxBu)e6Qn+y<-ej+=s3TV}Isl-H)#>M#b_$1oHa z<=8Jx6aLys5is`$xepm4xL$@$E9Zpr@o<77Jk=W*H?0T;O(Zbq6oTw~Mc3=WW)J?P z)_HTXSv3Z)o)se`v~M3adMLrtV=Oh5nrOEA?B8-e9Q!`#_cQWv*T#_$mh2$vUNoAH2v>0 zHN1VX2NUwH5TP|H&!0c41?B?wL=*mM%bf}6Q)IAY9HN2VyI~p~zwpBD;^WAoSOxAe zI}#fs#_drt!+`qEId10{5V6PiB z(c~ua1Gk+KLCrR(7Z#ppcMMVK;hb`~xGovUJZE8%{(K9htM#mJ?A@7Rnf-ffx?%;Y zT3z>x*V+q;KZn|v5>}D_WM8YS57q*oUR)Xcb%RRv_X~MXfH-bh^zwGMl=Il|GlRoD z3a4kvv`{~kqZGR*(SD8Nob%f2$cLoaSJI>-q3YMv2EAJuwivN)wD)xUP?0dt(Gtnn zOd>{sXdS{oKKG-anZ)Ru6|NT!ZcCs1a5*K-9+#pCkHoGiWasuuQ8c9r-q2#aC^x_5 zSDt(Cs#c$Z$hhNmfjPKpNRRe^^ z|8D$iE|tCG#a`&u>|#euLH$*oNghQHpveV@eNvbu2i$nGh8~WjaJdqJPMJ3Vdef(}7DgZzXD9n~?7Bbb&zlHH9QgW0N z;eF6|FG`TPciMx#;$9W$+*qW2EF>i(6Yj4{tVf*Y%oLNmvZb#CAf?5Ibz@*BK4pInC5eeK2M%wm z#={e`ck^I6RCyPIFE~=3(HDTtcXZ>2R=D()n8GXoi>=;t5g|7!1DFsZ8*1#UIBi|s)(8W+$k_KLTboA$YIKE_TTPM9q<6&Yns%ZD%b&2uHyoicaaJQ#}=b8lyv7TQq+%@VHM4r`_4&HHcfCAMErQm)-XyVdg|` zpFHyYoJ5+^AN=5Tu`P-17}f@&dMLuAfD5h96W}ko^>(fn43@!plUXT!$|(f$s5p-y z#C>$3`a{qS{vZX`Fit9JLk4L#!_+`1x`s_t#%>uREi$$Ey0qEo(~2Q|Hk+2c$C70m zRwYAmY5bQ}JJdA0S?D!`U1h}4ICafZ z;Js0OzhL8Z|MW{Cv$7;+L+&j*MB{(B_=-izx|4C(Wf`s>N&^)Xa2lS}wqvrcY#a{L zg$O=cZWg;NYfRf6J~ZKN?YCf6mZ&r1Wnk~8ma5h>V#$9_&ruYQTbCC$A99dWo`c=u zK5R6Epey?}S>*UI+*bb7 z04ZoA@X=kui5L|}D5z3M#~k7$NcvDe;QBbRO!TeSa)s_Dv5gpjryyDIPx#4-1$vKI z_*jas>hkI}=*6gop9{8Q#mgAs$%p5bn_L!unD+mS?hfN3Ft2pHZp^Q?o^z6^C-6mU}#$D!FQEHG-+gV0zCe7bz4 z3CNb4uxMaU7CI=YY^mor8U(Ym?EN21N-!M@vL#FMOrR8|tb)*QxI^$IYtqWMq{Jj} zV3iE}KQz?WM(gh&eP4yGdm0n6M5RXSyv}|R$!R}BY>8)4n&x~5fN6Y=Orbxhz^m8{ zN?_yQz7jmAlD1s#ByQSMv9oKwR!7tX$MEpbw(@?QC$9*K!!=EqtxdPc(n;b-# zZW+3=L-h{BJ4&Q2g<#JXzm-Yk3rMxrOPG+z?4FD$-%krOVBrrrDc<$RfUt3slzTRG zZqjo+^j(XMJmzlAiH6D>3E4#?;fhhugF*KT(+t?&bR}$L3VpcbqP_Lq|)1;2)| zKONtUJx;Z0**Rd4Isg2jAJeIWmrmxpMMb-C_#DLZdSO2HinR88seZnxMlMWx)Z&`{ zB84K*SAY~2Tlp8E3w5?~hzJ1HsPaT6RP%3^vw6+fes`qc*on?Cd?38wxa`>jV0RqZ zZj{{fgSYZ&J5WDC(5lfGw9zlIjgL5Gn_2#AhCfTC;yvk1wl{P{3H^XBb~MWMA<`B4 z22x=8{^rrf?V)$P@&#x>(!g9i2ALK&789l`vxhfUVN&f`r>%`8H#ACZ)r)oUW-}H{ zD&`U=IyTLNZn?Osz=SRFfrJTV#&)>OvJHfZKJH;hDTJiGv~n=OpEc1sP97Y2Dan0@ zG}rxXiD0(etnaedO4(6g52jv6+&!dlS9gL3Em#ZC+zr3LhKA^*E5Aq$Xa;K2skwtG#O87(#!||g0PQ`bZ5QE)D&#)VF_t<#x^tnvL!;ItxJ3bn z6e!g&XtLkF|4&!?XRRhj*n#zsyZ=K@|Dz!r9Tbk`GWMJ#d?}+k)QDBV3MP{48!t2X zmN{OJSdKuoV~`P7hbrL;@{FcOiY@#{SJgt#IuCtV5kU56NyGYux-5Hp&A8+z(*O-# z+xe+dyTof&M=|x<_sB%dh_6>8CL%#{M(ZCTMKlc_O!U#cx0QUZ{jqPOLaCGpzU^k^ z0GLmBLzE2>{}QrNnOlXNf1uT8LmIQ2JxzX`4vVae)JGqJw0?{>ET1hgwL8B<5`k~F zJdJtJpJ8l6ltrAL#LZ*=qKeZjah@genX6d&;1Pd!lx((m?6qd~$;)}@7*^B@(8~Mc z0S$ulsq>hn&+$!HN^qU?TeIMX!Fu3NH>Icr`;`*}O2;HmHxWpH40|LbPZwbA7k^eX z3;nqX&(5ZdKkFz>G2O>)rIx3oO`y2@)d&n7kq+Cd5A+C2fcCA_dNsEgL$K_@VfSRt zu&%Sd9-H@e|547V6{V$nlS=zbZvVjG5$SdKqxQmsi|fcMf{fk@x5+`PXLBzI>DLGx?9P|gv8ekI#l<0j^u1B|EgGP zWF70biDzAfFJiZEPkdD0We#E>I{ro>Sr4P!9;_^cx#B|ZbZKt~f`>u_gVWtaNeM0Z zV=#!l2RMKa6PNZOHuE$W(FOW_x6J@UNdw)=)3%Om79=C-2xiu^?YUob*Gy`+7}>7h zB;TY&gH;86zAiFphQ(k|ewrHheY~@~%I$}M$B1}8Yl>OSgy@P^$J?Cm@ybi;=eo}F z;V0&)Aiy5N5G~Ef4umUm24adJ3<;7(sBY<#&_FgjF|9IAae|el`dY2sAY)Xp%nt;< zk!bL>2Zqsl*m_@^^S(^t7T~9o^7KxFwV+uI?BTj(aQ$tc^IJ>6`p!R1a z_X^{7yfAB{*k&MGoGRkIL=8AEsQYPd7;-6I+f-dkvn~i-_a=g?@jzq@GXTWSJ9|GZ zvo+?I+yUm5dZyL~fqJOP7B((dYhw8MEvF7WHl`YQk&GG298KJirEWH=IQZM|AhS;Z1iU@BmbnMt{A(Es)vW16=R{2wBQ z1rz0ogDQ*7Qk+<8(u0Xk*?_O2*$WV+hxR>xOnkg+^xj^~V}p**ycznFlXIR6cGuAf zZ|?)(Wjn_hw!4?=pxm1WlhX&@NpUv)&_%g%-OH?sbYWZBjsq-((+*Mw32FAjo3yT3 zZ7gyPbFA~Z>|78G(M(O;~&I6n(855>C5N4upB6!MbhBH;)-*(F8R~L6q^uOs zU$`ipGTGP^_D;(1SB9hB)NlctI8}t~c1P%#_L0;23Pz!_IfB%bXk@=n07kmzC&i^@ zwZ$&Fn+D987l&t4-k@@0Q(VpSDt4FPM9P#L9`WnJ8VKyC2w@mQEoACxHKupvKFp5y zkQF`8l79cd{^0(0cn4GH`RAf-0wN7412Us#N0$D>Oz@;fQ&e8MMiRO#J9u=g+{AR+ z#Yod?@crH;i3Ytt+yGGW{3Dn=Dz;O3T4Dfq%?eMUVhCP5{6>dbX)H%BgB8ycWt}?IMHl3uhJ5!G+BdW zjDnMjr!FdSta9y=T>dBR2U@Z{YufyW=pczF^EF{MHyg5X-VuNiHi#c9s+dv!?h$gy zrOnO!atq5YbHma@S z987ZcKlJYG6tL*X=*q3MkfFGk$%MVj>Wc^b;0nnGti#>*vvxh6in&F{P%O&*J^c6b zWRf)pm6mb5rK3Bg|FV%Zgs-U4i-SRJAe@NUlvRuqADbZq0X{Gw4nJVK{e&cEAT{@3 zG;%aaU8`6++%lnR{``H!e6o4}Q}zcR6UJy|WpHyc=h$f_dl!+rgb^1|DMez-`lD01Lw+PBLmYx>aWp(A9tZKGCp545a_S6A*z zj*A5RumVoPgy@5dsW9get0hjQbf;2>n!kNfwF5TKBFj2H%@>QTYESBw@fTx=v%Cj^ z7cU02(3I|yv*CBN48Oajx#krwVZ!kN-s-TH2vt@ zwyv_&n1*{pzB70NhRceJ^Vq>nB1$5X$)k}i>LISlDmkRPp?Y!^Y>1}OqLdIFyz*mt zTkyxG2cGt0a0O44(PeoNc{AKlR@gPB?jgO<)f?Em@3Zr7!owEB_s=8h=g3 ze#ywAaF^fmLB@8SWxqJE#vB3t|20BdbWu1=I!{A*@-JpNP8?bfO`8p%+J0()g;)XV zWh|VEu$v$4nHjsGyb!iZzmNMeg$9IvWggBmwqGV}h(?Ap@foI;*ObsZ7!^_W+I8w* zJNY=zFg>a-z5#)+ZEu&~bf{aurdKekBP|?q`Yk2Hb@i&7D)eH4~vBO{8%Qr@bu?bXxH1@>eFfq6K-2IaG4u>q^LeGaX1Jw8buK0K=FB z)UmBpF?snssQ=EP&ZbLs-2e8rUbc~=v5}t9N(LZ*FB-m{($?xC77?o@H7H;`n=njo zXjpD+%Dg)v=m_-y1Mgl9APKkSYD?4+ZFwg6TIH@aIlo+usm-$nFxd{yme()%hR}wF z!2-4>Q>Ti9Y^(A3Y)9o})sr7(vd!B_KG`06*^8;B(OHjIYS*}h znqT$c4Jz+uBN@t~!8ErszrGwh9qIAbw{ut}cUc$5bt=OF!?UYq^W>s`Aq5m)HI6( ziXMK%&>M|HkjF_ZzRZRufgTbv%hzc-YlCO*v<>osAs)hTrx9a+v0iGdhN>x?0XBc@e~`Au&^*iHO22URHu zY-YzSB_P}0b2lrPP>lTe-;{4dM`I?$&ero~hb1 z%(1ktTAxvQq<(GQm1$XEc<);d!>;=>te8%^a3pso?(^qOd_Y;aa2Rvq&GKK~Qn#esH9fLm>!UwM)-UszZJq zn082LPa;dTf-OuM1Eq+O>U+o#e&DzB@l~J&gk_z(RlJI(l;)=m4tZ8nccnh!)L>{!kxh)P?a?kLFD7V$zT9Au;%UcyYxNY7&#?V~0=!C#eQz=R5iWziVJ3>$M;+^TGMbZe ztcB95G(!oluM`*Gr`J@R!mq(p(uF6?n|&=vtXt=lilCJ}qH=z6_v6~?u7+bkZzZ4A ztUIyGhpOv7&chc*LY^$7Ki;9>zM?k)hhlTqcByLmRPPlRQ(LZLv=meXHX{3jd64ti_L)zFjqhFVjWgPsv(Sw49MA*8Y5M9*?`%f^k&*?ND&UYbQpY^J2%|~)dJ2@cSYiwI(*0q+YGr)h%SWEsjMelCZkWKaA3o5W|T%>+e zYWXCnh~9ke8E9!|B|#SW`TV`4r{D*zKSil#>(1EZtY*w(0;3)jR`=`kuiEt1wG%~b zYeqTdP4Wu$1HIQbQ;7ul(3yO=!IdK6<5%&*@7}onv^ta!wUbeZ(nt>-Ct>~oh1>fw zk0CmsKai(<_qVo<7){wQ@vxMhtJAT}-Lmk!4JYYMyFQRD4MmrF6Rj3}j${_5wcHC9 zOkRF{n}SjTzaR{8Iiyc$`diqx?{gJQp07 zl=oFg$w#+9E)pqJ4bsF%&`Bu20|IzL)n7|%($ql^%?H~yPq~&7`acS|K)#`DpMtQ5FbIg zvZm}ld)LxGX$j5oj}Wx<=Mfy|BlhV5M7uKWK}n;5_YBV9D3o?UE2IKlB)rPV+ zxH=E-$#Ox$FuB!PGGlS=Rk4q0aLrK>tb#3Vdj}F> z8)x7$rNapcHm_A(Q8w`)3lmsKv6-VYZe9N|2*p*3xdr9U`s91r7?-^hI3NwDb?BT; zlpk0fS9^e zt*8x2kNln_hrXOTTfLAuAElTR<}7#|m!AI+4(oS7?K5|+R?fL#N;-Kl<?6vvgg%{0yOtK@dO2yR6kOKL&`gPpfC*572SqZxrF2`60XY*10}ew- z%HDR(nbB^og$58e@7pSkiW-a-5;kB;~))u-U%bX*&{tbSLeej)uAIkClQ@*Bf zbU#iNwE4-4=VgA8&jD+q0vilqa4>R<%A^joB<`BXdOkL&&0hF*ky2%CT+m8Psy-ex zmmJy6npQ^6%5%9dnZ1SvHVMyJ;3o)HX8}p0fyl(FY@keCR_Y5!3+ol8$}1&9D1DwK*@WP<$^}t-PeBh^c0Bo}IK?zu9bNZyn-PHat-QduO#=I8>!W&24VXxBzO(*vaUOKy;7A1sy zSqJ#gH|=nXb+w?)D2Qdtz*Y}2o!OS~Hj!OBw?2Oy zhNS$S8){Iyfi@0b9fz&G27D37xic{U)OE<;{?FHC+7HV)ikVKdoBdzTs}mc(dBuW` zvG85$E(~*o9eFGLtD62IV7jDVevuBn(Uv{~Tp-s@Rk9feZuq7|&8T%=0&CTD^HmQj z(=6UWxP@6%IUO3zMkU!|V;TVfn<>WdVcjSO8L9^w7iv-40vjj)AtWg>HzZ-10jcaC znQhFPMbl2Zf7NwYoL6mS4ZYePaY;9NQ*9M)rkTdVPNWSe&3CN9e0jJpH za5r~+R1!vxFTU>eH0Do{(G&u!d=+u0#UTXWIH?++ZMb_!yVO}<+g^3{hVEAc$~{oi zA6YG9L{_f--pCC8Q06A?ByZ5Bzs-z(Ba60`1AX?AQO$#Vmv;i9>)kcioega#iBOJx zLrr)ioY%=lL3bYRt4%qE8Iu0QPN5>8yZDPRf;HsZXn}b_=o4kZ->s)^tkBN()f-A%6JX^CM#~ z?qOs3q^8~((x4U5FmZ)0F1SAw{LIk(J z*+&yDJTUxE`{5>&3N`b+_ohcI)@MLAEwaRP_UKFg5Sx>;c@2=9hdVgO>JN(IFpF;(6A@(9RdQf}Wh2@yo~!M2n=dk5NMI1CZddo8aeKU;Q(w#r(Wt*JqNuHp^%U)irJqXhM5p} zK((aSFv1#NP*J)0rdQD`*@NB;QM3@OwMNecs?Ps{lKgG;Lc?<#a1J)DyG;;J0(v)d zI%-DP2!u`uRBKyGPI@g-yVfUFORRj@EFOY>;@y8viTmgac0`H#ARXAk*RYo%@=vP& zsp4sDsMml!O{Ry2lc4IXEn0M>W7pG7)1yeM{MF0M`B)NydGxdxNkQd#N2$o%-!+I# z1jk^OhglRo6R~=`tnhz4QZG2_Kp6<7b zn`R+5)vPW{mDQvum#EIbvL`Fj@N>9H50_`Shtn?Ra#Jp5JB*zZzLSr5D|Vq)AS}Vz zNTkQcq;~T)b;OrPowoi#jhT0b4n>EV3jz`RrsV+V9&a!!f2@=u+C*z~S}c{bxc?wcLg8fSu50?bvXCW&aJg;{d@gvGQ^_E#Y|dN4lpL0T6ukuk&eM&H@dzc1$Y=y~rq=du($dPpKb zxwZv`M8YJZ=5b*K8CIb2LHKVv<@)>hKb{rU$NSavdkechp$iH1D4NCf{Vom<-z|d* zNJ6l8DEMGcxuliGnZ}}-U;PV#Bt&v4@t+jY%}ElV{JcF9=ZzE##h;`hjK_KFn+%e+ z^s!&mqwK%(I_%`}jKPceb_X_;dt#~?3dHeIL@A4}zQl2@@_X?i(E|O_l*2nrsFWYk zw(<=A*bj#&INACrpJ5Lv4S&J_S8W>-AUvHqNrlp-KiDRv zoKI^)+#ye`O~s3+6X2Jt5f|#tTX?8W+tDcMT#oNfV}jV%-fRLIuyKi!;fp4Z7Th1A zcQN^+N34O>WlUaxjV+<7ON9rXl90zFsFL@%D&#pMtt=5Vw6vi-Rhqw{O#FPBRiU zXF+EJ-3TV*sAchtMke5#RPEZ4@OMuNltytwTT$K=w1IvT3=%~Ds*-{cwy1D$ z+?*5X<$5-g4i!V1EikF|mxio^Ae{a1Gw7G{Z7`X02Sr=uPaRbRTD!Oq2ZJ$c_h+cD zD|H*`GOjy1dFDN3sxy$Daw;!UoVFMJ&Aoa?$h#Y`)_1Rscm}M-ZFcNF6k2t8fB?S) zK;vQ7j#s4m(4pWn;Lr&(lu$_aL33@lbC&pE{Go9m4W<19xEXYi=6s)bkn;cSKKd>~ z!TMn6hDn#F7^asC{}53n%KQa~gO2WW`;nO5cnl>oYaXgjLef8MNS&1uQ<_qWf)vq% zC35?Cn3mC0#o88e!IH{fl8F(Wd4)W)6T9HA=oS!(a~#({;E^>%a6e_y8zc2&tM!Wb zzbjX=jGe|Gi(g3aLn*?E1!#4hUG3D0`B!fChmR5}zLuLEE}6i;%#4a{VDwbg1(tTK z$;&6?0%I!|1Iv@cy{E;bd0>h-3lNXkQz`1S$ZZf11ghl)W6QpObql6);O5xu5tcC( zZn_OOc|tQIc_;sFdEp%_$s}@zckiz)? z_@fY5^V4fuJ0-K;Wq?Y9V>{gamUc}=SzM_YghAd}(Y-9QDX|y1Feq)c^wz=JR+gR{U?)V_s+_PPXv*gdvLY)bR&>2AxMsq zZZu^FI92ONHPV~R3$V{sgtKF~5V*)lTIs$JSh*p(eIJ^XPJ>8m@HLvftp zASvDjs2hGRcKL$Ho9TH~N%Q4G#t=zQ-MJ|>KW){c4d{d~r2=!5&!A6#+84%?y_D^; zV6<*3jO!gCsM}k)#Np_Zkul)Sjf$l$NL32;Xa`*Fk4%!Xmu7sZzIxN5#hHDi!@1&A zGox(3J$cv;G_Lua=OP+5QLk&%(z6a7^pqE;Tb-vG1s|X9P4^?eRfD9#mprio=$5d5 zVevRNyGE(}@h>${(TCzWS;6tH|3OG_vzDWaMczT)5c&=pN-=-=dK-h(l@HN&#+Y5F z!5VrlBkd>Xm3$2USR03bBnsx+2- zpwz~m!&*LN@No2OA+cxE67R^GTDth5xGhG32)FW913p|)l4c{ioO;bNd9$N~_q?L+ z8Qz_igg>H(qu+rOp{h{`ab%$?2^Apdip|$9nKuol)jjA~){vPJLMBWnQQR<~K!wRj zrWF!RtCvKExH;(s;>N?VGsI0S`he!Az0X4UbZtPCwT9)wQFh92U#apnWx*D;pF%9U zKd1TEb;p~5N#W?>%8u$Kyb{#dhs7-YG;2z<@&UY5Z1j!JS{Nrm?f-Yv6nj!4OF2U{ zL;ho0N)%^_9S8a!dbs}_vWI<`?+@5>ab#HfTvG?1ZXb`=Z2#uMI;6P5x{JEH-H+j6 zF6e|F38u0i{5hQtXAkJi77l%i;FetQk>idd%A_MPy_xIbpg@Da_YnP_xFpr!4P=lE zV!8?ntro{(mq@&Rk?=&Na44A7>DQtx$ zEpthDP(PAEU2M8VFYvPfoU$I~0vb#;4qYm-OSl!RsK*q!EGV94{xioJIX=nmLB^RA z5mu4)aS(eQ?VqSw_acV~$asj@EjLo{E;rMh!tNE!T_Mk%$#`lGm||x{+p`7WaR&2h zTW-mcKh>TfzDSYXW-5B?2Ku@#pbo@{@h(Qqu1DmXPatvpurq!X&!8)q)!O|%b8rRM zRg0QSCNNnEK$C9Z6PC~bj`u|>?4+-2(3*S;;8*3OX7MeWMALMn^jycVp1)nR>85^V z(6jULBRG(z1#qD0QX)gQ{OK4>ToF}%!~!Ye!}wc-!EBd0n<&@MWJA+EfsP)4SR+{M z(+qRN>ESW;uIz7&86wfyEKa^e?_zSPiv&zu46cUTD5Ta8ymS;_c3LSWFc8LR9F&Iz zLJ8(FF%{1A4}He}MX_-|F+IZ%paY!$Bd$6Wv+pJXhQk4XU4+GYQ^4Fo?*1QNx8u<% z(cZN$Z~E4jwP{Gbwy0DqvFo)Us6~w7Edhu3U^AgR%<209L(HHaStf!z*2iU?4Z+R8 z%+z32zit^O@$2qD`YrRhUGgRT{IL;*(Px9{sC zI?QCJvs9k^scXgL??Vb8KB0G7_lL0M00A*}PBEL(k6J2oA*djyk>{DCBgLr8zF3Z} z#@#B1RCizjp|<{2WDi}({*8qeQ;*mE178vIf|It}W{`JXcDLbb%_9C8B4y~kJn{YI z^gMiS`4hI{UKxwRm}I$HM#}@UE=FAxvWKL>SnDDyToyr*C}(1qU^3LvLAwZ8k1El>`-%ohKe#3T2eaWC?~5B;EBY8(4qRIxR>ZOheZ^Tq4smAD z7fE{_>tW{pi|(g}sCF41bubIo8ka*?4Psi>Ohi{3Ul3s~jDyHTWoA<$YmHXv0@`5= zjN^Enda^PX?Gv7&YwUIL`gRRU&YS){#WNM?bavXvplW?VxVF^4yXFJpIwU72|C=@i zmoYYwG}?TVH~1_C##T6~^?^9W?s+#oHR4l6@oP!}Ts7QE*of%MpXwaQ>pJ+kcHe8Tco z(C|%V#aV4GhxoSUcs-r3Dtlc81GN;I6_j1CK2NHN`P7>X}!ELZ3 z-)K2hvZg_#j+wp(E2p%@_%dwh8_~5^d#1N_{N`;8j!~oO&e&6v_aN}15=CWXvl67z8;RDFZRP@Iky7*UiN9ek&QDW55_=RPg$jS&;-3->6$3gC zrc2}lDJsJ0!P4y$F9>{?>qMH734QRF7)Aj6GFRIB0bRoc(;@vCV|e3GCfJx?vW)9_NZt!&g9`@r>-fEjJECX#dRoW`(_!t_BT-MGu9qq=%WF^+*WO5 zH!JqGX&)rXNy7!%a4$#B$%)Y;2+-j}kzC^CNS=Jat*BPnhJ#%_D`miBb_G0{2;;%K#@P zt+BJyMbT9!jhL}SUcLo5%lqjVTk#VO1??U*vJ9xZX7XE5kK!HLXs`;9D`he($G_LC z9WXtfE8m+1&oR85GeltTSl>8cWYGk(pYgz~;mi)gmxx9iYR<{*LTU!=bS;S6c;E_N*L5EufBE{-=t z7*Z`0{0}t0Vh>6O%p)V7Y6t(&99xd;82SUxm98$vFh&5ECt7ui%R3lNiAwwXh!qXjQR7*c~14f>+vJ- z2=#WJuJZIg=ySMCzGikZLpo$P z!&RoT0`QM;2`LnhW98cME|PS;l%H9%C->d|dDQS?Il7_7d`QbT}cM4DoYyxW0! zpv|}tyLO;0I~9CJ@#^Wl=Va)$31Em)*CZIH8^YQ1TNkL;=e z+sVy)3XO3=__Y%|er`a)WD@XZ)RlkHYT(hakHyg#1%-_+%jA=`&)n!Mv`QeQ|7>r52PAZRD?n9NL_X3y4spSAw%O%@DFOg#GIE zzdvxeeExGI0r!luuh?es2wH@u@<7ew>d`KFZg6>@hjrv6GC+}y8E^Mm4pxX{L#`2M z1OqFR;DF!lwRIJL|J``5Y(^BeDP!$!xv(}O!>?XIA!?kN_t;9s0O$_ppj@Em=>-#9 zpjDYp#VuQmc0?~fq=f$2QN+jWg4tkp-Y}!MnnV0p(A+Os^=jh69vaK_f5o4De*{m| zqvV-}z%ZMle`vKoCN&=87s|>sSoaf4N604UiZXw$?>$Qm0q))Z?>}sU zfw~GNzLOlXz{>-_e2ql}G1?{c$}++ZvT-kq%Uo+2S~F%jz%(G5hz=MpIbm((_R1FoeFO32 zx$<>9eYq%V9v~Af`TfUv(bmti{7_s!gw`^gh0W$qkY*8F`Sn@(PmjlA3 z^Hf^Tu1U@M7S~IjO2D4ZB}RN@jwrRq^|pc?NDQe|*|i!|7l-EytVcHWyk&1cYB!U> zWNf+Gc4f#DLp3%~dxuDx7Of$lY91V6r6#l6Ngp~Ig)paa zG;#v4ACsLRa~DT>`fV~F#YdJqWJz7GNf~S8zp+(X7Op#atS&=G_l(7{j&PcKFFPW_ zh49?eBbN#>Mftk{nE)E$?uxP8F@su$>j7G%nX8Xgninf9of9ceINtw;0eqy6M5>Nw zD9#t2?hAUo! z{eAC|mogy;XkoSYsT1P^>a?qS`tKS);x{fzpo-2?fD8bAn2!>RwM64FOUFW=w95qWa#PAYdfIef&o|HypQ;ljtaO5 zxYkRaX{y;XR>!CQUc@)uBLnNJD{m8LTZo_w)gERYus~r+6M3t_wC?GjHHnm-ebVmk zHCQmIk5;)^4JMrYw~fheqe9j2FRI3$gB50^gDCJ!p$#Z+*IDvohvO7G(;xMBWV;9q zftcp7e0`goX_XRA(l8cq5o#O~VXtx?)*0tk0~JQF<;_Nq`YEfCEd}wI_*HG&Mxb8T zIP>_KR=itk5PdF`c{_4zu);kJ>Ky~*^-B~jyLC=Xo#zegRVHO3#+nVSy9@9DWod5@ z4=JAUhwtDF(~G6(!Z46~Dt1OB<9Kdh+U)Y8hG7_m$tLg2j<$7)8>WP33w&2y2~ojx z(*8PbDwkYPG_zPB-K`#zu!Xvi%Peaop+|2g0+o8`4Eb9igWur&>P`BG>Z4&*VWOW4y$$y;_~JO4hm3J!+o&GhR%)L~LSh)#MoFIv9VmU}=cmaGmE z%?^ZIY(dMuda}mXGfUuManUv4=80jIooK7Ce`gHtLn}gcwAqkQvr(Pu^9#gq>%;pU zrS`{h@h3cUJFf`%IsB9)6pB;VaN8Ogu6;1_iw>e7Vbn5q zA5D2f4WdflT3;`zZ!R=flb$bZs}+~+BydTGN~ZXEgcqdHO#h0iCRH&k_)A&i7rnU;S+F^C;Om{H4+1HO zSAW0b@KE{-Q~ZQn7BJbqZt>t#b%#W1}~+#Odk>Q+Or9M;{q2K$#ICH9t=^k z>0gcNc1&wHvX4$@hqphkoxKaPekL~lP3mvKXE@oZXeNoE;b>}ttzHZ52vaEwLvWEc`X+-OsF|qIgyPJPS)Xy(7_k zgj5{eGo$daQk36cb@Up~;JPUKbR3AL;bhX~Wu^`Ozm@!;cQAg}&sL9HRABdmMi^dr-3Yp;BA=v+ zv$-C*w!O6<@*yLru%X0RnZZ>#%R!E!y$VbjG$+t#IAO-*cJ7h6#FL?yrw%>pwIi}g zGJ+A}N?INcXfA33{Dhf(ijB{s4(v-qhKA#PYLB#!NDzjJH80x&wS`@{yCpb0dr@%P z@Ln9t1C{QBys+HR#9`gvOEKi99pCX)c__B|FI#wTRu9zA^yB;X0=21V#;;`Vb-Y8~ z0ZJN@j|@ORP1X|Fgbr)*Xm-Uqmn1406H68Rh&ZG>e#=r$xUg-3>~fzaS30BjV4WNL z=bYHuQ+wYjt|b;N7YeEg6lVwkp+Y|>njVxs={TvQ1r7g)h?Gt26)5xr^N1jxksCbr ztczCY773;zd}lJYS9L$5CYI38_Wfuc-|_t(C%8<1c|Ck0I1kRlGY>bOEK;yQ*EnMJ zsP6AQ)r0isH1OY1NHwTN*MHjOFjl$v`uFBV#$I+L#^+bef;Wpm0E6px9pgmAo6lR< zL|SR`YbO?yxwYDL?C#)2u@FN0q{?*^b4^UkPk8{2iH5jub`&gX5 zckliS({IYvXpISu$NmU>^h%xM=!g0orQ%-`-<{NWs|Mz(lSpXC@-1g*l~F4Y& zc}Y%2U7aY8CEbzMwj2#iG{S)mksZcwzXiE+T0GIw&}%R4w@n^VR}iMVd@nz@U!sSx z64W93C38*%L?KT-#G>FpRlL7Ic*i)yz+)WykK#OiXplEfols@C*Bj~cY+i|n6ttJ+ zfaTjl8?F$uibsNV&>3WeXLQ14b-XVBJ&3wZ`(~x>V3N{XFvAa*Y%0tq11=i;3{P={GUczaLKw$8*=Tx?% z4&rT11RtJjFi(w9R{~BGHlLMd)cN-rWZ2;I zXAF$fgj9SAO)>(QG-aE+i|Lzcj%pJo34Xikvz zqj!uPd!(OqB2bCh(jo3l7VS~k_h7xtD{yb2PNxjDYp=)YZxdPEcuw!$j+&#u>*#1( z#HWq7TR%vO`E|kC{67u<>@yxG!xx-(l`2C`s#n5&a-$2uPFf_tLiVSdZotSe8ODLr zK;mTnYiPIkTAMsbCUv#mceA!o3L6JKzT;X4{nLA{huBEoHtAN~c`J?uj%Pj-tdwOaWe;J4( zuhQn1(xE#$zwT0(9M#H|jo; z-4U3dL{@UYFFQEs#;t<*>xBW9H7=`ceuFR7tBJuV1eB`R2~=(!h$#o$)8&AKWf|)| zGncrU3%DiP!25?*YDCiW5Q5o5eoM~k#1|puhFhLqeGuCt94R2gA_sZ7ibvMb#;*)a z24n)K!Tp?_?T5CS)PHz(DSD&$11Bov#dkVw1clX6r1 zbx${hiqF;vl~^MbF7cn{IMe;#zhF!qY4+HBJ=s^!Mr=CCs2j3jsC82g6#7A+DH-Ix4@=5|s%#N#_;~eA_`HUa zbs^iuR%NkU8hlw^H@#XBnTm|VV^ja_5ZCAEWAMa9p=#^Mv2b4!X_@r2-%F^$EW=>C zL_^ZSU!r6Io*6c@`?@OF;KzgLe{I)W7(Ut4-Htg-lHSy6HNr;)zpHg;uNeJz4vsNUM%!hcQH*DpHJj%$!tDz>mU zC#DE0nP87>^Jh_Lc|u9Gk(_Nuoc2Y(z2Kz@lR(c|4Z!YF!!|$JnyAec6vRGJs$Stv znPqAX2RZ(bd0ZMlk9sOgD3Rl^YfXz;t0~~shCS^h{{zsjQ5i+9Zk$Dm1~71{LQWyl zxT04ZvZ*9iFA}D}R0!{RVQHXl0n{2|cz&y`PX7%1g2kKEM8hgzR6Qs>gt)*J` z9^LBS>5R?e-VZ{D*=%lj?S>o7+3toZMC!p@26*hW1lzaA5`3(WUh2Ul>xWnfp*F^e zPAE491?{#qs2)xo(bqDGR@``5k&>_~mmd!{Of~O#D**!u6D1Lat)7P7&^~@ZDFnjz zL4$>!XUMlAJqUD$N&CH7yt=YEby7wQZ$tq6y(usk9b30gTp#%Mr?)e z-AltPz^vvO@W_?)jVGp|t1UXTSIy{>rF~AF*m!9=15uwwwrh`7mv6ue?bp1&wxx{}cZo}^6-|E} zH&#y@Cn$heT>U?ww0%R;$@gJXO#b{m)r(QJp5$38y){!R)Y;jA+EG>;g4P*Dv|Vim zk!2hXia+u;!CYFbgCk$LpDoW!CZpn;Dgrp0ftE+Tz}n6h`e&HKb1HDUe9<162DEt9 zN*n%o#B0`gaTDS_iI(bbh5%te@G<4u*r}c*m+ET?g3&$MHOW*+sM}RT8QXsVq(4xZ zf0i>%(YORWWKK_gFK8qN?sA_b!r2ADC~1wz8Pfnl+-swcY`s%#Z*m%!_s3dkrW;(< z1<}Cy6_=wfo%gED9UL?od4Dohu+B09&wcfUh0by_wDYD1%ip>N~K)EkwgAVV> z7Id;KQOGh-*E#TF%B#oJ{Z&sWbzg z=FCP?FOX9~@kk<3!8N&~skhc2ACF&IA#maZj_F^@lv-Aal_ti2xMFFBSPgw> zSjSV#FKgE9(IyW!g2{Hg>NK5!=mGyLb+cwdNj>_bGgx7zA@LuO#3jNqSIQ_yHjpG8 zjogH~-&R3ZPsms9@ z!@kt;YXfGx37+$WMsj(L*V&gz{Oxc#)LnBX`+pwSq6RRF+Q`g)RFcmbM^gi zQxV(no(TM|Gf!6>FHHINoW0-*no8f|A}bUNXP(P;VbX2oc^J9!*e0s$f0?fW z^-F*<+a!*8Ua!99k(z3q%OB?5K*&mNF0=Uj5E0zct^+- z_wrHG?LgHeck@uRS|mpN%8SK#MpDS5AH-$g45}BVg30{)$L|+Rd@v}hvlK)RZ4Js_ zs$M>@P{gYR&H{MXd}08Wjj;{Ey=|IN?TRh7TflyrbSF6dq>=RQ$Ae3G>?`6LWiyDA zkpWT|Y%|v+W#>5vctTBBi@V~+3Jxp}SgD4sJdjYYrkMH7*}?`XmN6Fcsdt7BJ&oKQ z?%aD*E+(D9Hz+WkD@_Y(H^s|~*##FAw7Ki~Ws`ILMn%(cb;->~g8RYTkdymC7#Nuy z7PNBLMA9buVN69YK?atjkhV`#wQH`x6al=oKCFoE%9dvp)ZPQOQs;P4;w{9VWA$3vpV{KR+C;Fip^NOj5pdon~S@+_A_~a*7?HzR~{bZvzoX#V-&OIUBUl3DW=gHaZ zv{+*C{ce3z+A5j}B1ed@{zz;$8(SCu{a~ar=goR7k8FEZVJy@#@1v5#b|*_Vvm1&1 zQS(r1kBg*nUkyI{mM|%$FdP5FHevk-b1BczFpQvN^E$X^DTO~b zF?<|f5&WZV$k9A%jIX4oYgfpPa!~qC{-T4Kkx5zo>c}S5E83;Ffs=bl#~-BZ{~5v? zeFM1C8SmP;5AdK%PNU+IMqadPT+S=3?eG-V# zF28JqdSyT=(LC2s07Yu$EWca)_Tsc3@*LC_t*s2z1@(o5aB2H#_Zm^K#m11 zP#rOt%2#^mHKP$Dp`yOUOPaJ+-xoZpi^nM@+i`g< zQI@369Owwcq+eX)k{dl9baIkz__GzXccGEr+2n>w-GLLlfXp0SI#EH6zSXf9?C8bD73SE@H{E>1QflgAl zUf5zz$mp2b=oAVznIDk%f{~y}*OXODD|sMI#h1~WF8Z?7Po1%Qg&j6U^QqMZsmFPF zSvvlH4&1y8TU}A(?s=`M9V3#T2+xNe8`jCVAnC^N%p&{kMb1?H%Av?P5;H>g_UVvM zJ1%8D<_pz#B6cJQA(lkHQC&V51wXs5bFe#~Nzx?Pr`x~4sSZ0(&CNRS9-tw_kw>08tf(Rkqo$B3`8`T zEfAn!GsxT@<^8z*MceOENh}VRl8rL-zH!<@Si8-q*-PgFJ6i@XN~>`>%*GTw+^ip) zrrz~5yQS%#WCk97c8kLgU6l@I2$cw3<(c;oFOJIM=sS3&H9Z4zu!>bH&? z4LtG4UB;yvzPo#)g|i^)HT#nt1@rv>E%MZDS!`SjYP-Pq*c}T;cMoP!f-=-6(AJyVG8tr1qh{(W$GYN5<& z{BZ9()a}cJny0?@EHImw7O=dmK3m(RefEBjsG)>#<;{3)9E@w{#6$Aqt7MynVxDp($t)8dftmd* z?UwbmkySWhvo;3`vWSP?`R9wJzcGJK9FfC_EpU2E2x4`NQw}*=l60##zo#}ByKF*YxE0MzIS1(WG0E{F@lkczQ>~~P8z}A}$I?wCS{rSOL)$~pffHAl-vPNY zB2UYeBq>Xrp^^t~Q9w3SNzh~Eyx3)8xR+jW9Q}3P!61UEpb9gGraSl~DCh@&$~Yh4 z_l2azeCp+!qGC+8X)94O#Y3H+yWgyShaGx#N|*iHV4Q4}Hpl_Sl_;|!Z0QWz>z3^V zvXMB?lsJ!6&~(QdsPN()d-O#v)B%|v4&){}cIDUFK>9eyHO_Tk%k{{aIC41n$w>Sk+Mw8tYolz1`)IQ{Ch{KG zbVQl-@4!s9)GZy!`1g9ICOiN%%{K`R?O7V%od}~`Q%1Z+MwI33`h}`nzg~ux>}Ptt zHZ`Ph?(WcBIIpu`zIa^+N4(5bh+(Ja$!wslHTjg9t;R_<=v$N`_;96JEx2eXiP8?}3 zz^Ne*q*{yUeybn8kuTVbkFYgJuv(fJAHm))N;yM}F|}tD6S#$-bVm?p*4`K(pyyH% z+eWs~&jGSHfHZ*9lJ;IoueJYvX-wg+qUE&7VREiX*JHaya3V6Q(f{F4Y%LTQ_O;p z?YyzI@IW*4L=?m=h5W@-Oq9%a^jmNywf}U~aUIT%L-aIyG7~Wq*Ok>KldIC{FmI*7 z3kC+FK*El!JIiWGA1B9S68|+|PwB`jfmyMCq27{BXf>W4lq)~66$VHFsP{<86ePSB zqnc!>o19jPk6?y4eJgV;mb~s$dC4Z*JM6_izJqVt`wt(=b!E0}Fl=O*WfbuQ~*UU5ldQih;&!JM` ze=h=3jx`^h0tIqzruWvVRmG@ok(R8~ITzjbmx70Q2OI@G;|l?zlEs7)RRMS>TToT+}Kjbyr}_w&QOi4+LHX<5DXVx)nUXR<*rd)VO4eUSc0XhLl5K}%sVdx`Z1Dd4(^|&-8q#pZ?y}QFlWC;d|9bVMU5^U_32mbcjrAn12q|KfRhIlno zs9`2!t6?RRlO^ArAV3u63un-EdsQO{(~gFf|@Y;TExjX|>A7ciV&60YjSB=Lw@3Fg{7@Y-WY=*cxY zNuVNL@zpX7J-DHq=D}Y}7c2`^)dY?IzH}ZqY9&;T{C354n1*M)H|8B4k(I%cll|dn zXn&LQ-F)d(wL-#z0&6~1>Na2mE&Y`|wHqY^-2>}#zU2Wmf1 zdTsWBhLanUI(b&HJ0?xV`AQ^VE#A&7yGKFiEL|jz?k7R_x0xaP4%t{)ohFA1QoP9b zqGwWl-c3&DDp75V8SzJt1u{Sp-&gvWFt}bwDo@`}J1{}&&;kK5 z%)ydN3tG?lv^+@w!OWqSA1qMwg_2WzG46C-0AC%)K?MZ}x{z>b7Zz5so$(C8p((K5iuzw4eu)u>eKX#{hlDj*%6mggm5_p}t1If^Nu+hXe>`kv8`)O$-{~qXE zhFRP{Pw+NZZXcfxhQ{8mJ=Cq^j%=%VEBGs9i#OIi`spNSxwCQ=n~Bcg3YMVlR{6vv z^K5NP)@o?wvxu}xQ*Ze>B}f>T$jQ_BXLfdd4b@xE_nB3KS{U@?wNPVQN+ID-kh_{! ze!YD0tXyZT%$#TK|Lzqpc_Zl|b&Sk|ZL7JGk%z?p^gfW)ZUMk8N@JS z6nYkD+UOr9VO{%quzE!tVWse$^e^KeuYZWOiT^S&oasU73&W|p8nbj}%5*67iav;W zJ>&a`e+;Ngcqe55CJ968_s*?}dl=7M|A=SER|giF1az3!l7ONo;1T+eWS>IJu5_Ro z%ZLi@osF_)dmJTO>3J7y7oa~nN*rGqt?jA$J!lzqAmS3lDYj^)Q#($9M1ApbRK#?2N+ zz>KGK_M!#kA;x{)NM{CHfbTX0&ge?qwajWNq0DG~c+NrONS8$$)UCAbA3be+h1-OB zjMOOEjh-wptaXL`46GWIVN56@`l)jxeNJMf4oSFA?TwAhkyfh`$e!3T&=qde?ouQ> zlG!&_EHamf;I8gHRtU+(mrk$<^!Ukj{b@BrRzu@TT$wMnTT zxP0Vy?SSwxqFZvGas6;)12Cpw#Se29k2JCK&*Z_Wmt?bk&i?rm4FpG%N4b=Ubn<212Y(=cL%fxFdrYn-fJtC zzC44!o-pGzl!J3(ZB;IKhNS__ytQRmQKE7V7+=Oer$Hpy8PCykOYk5%pJ=vFFMf{% z>**p6k5dE>21aqq1L&Q7sA_koUlEBG+vnk^(jl3>XloE?ysy2h(_B&elF1zotTUD{ zj(>S{=U(41SlRo--%)Um%1@?j4J;90%a>2CyR~{f(s86HF)pBN>QQVMw${gG&yX-R z9XF~Ol!@I)?@F1Cosc5A-**-{Kb`Pln%A>PN#Tj5kvMoaRP5GQl zkDbGdlm0K}W;j>Bt9^T1krUO6st~FXoeq@tr0KxwNl?6 z_-&ANaM?TxNi`>0)RjXYhp^3?WPmXVtp!ZaVsOM4j-6KJjhrgp*Uli30vv2(+vRE4 z*m+dQY_|?~E8^E(Ah5=)4s1~Jx$YRYq{WkX28+5Owp@Qa`+EzXvZ1-JCK@~T%hf%N zdH#32BEPX9SS};L%~`HWZ!TRoC4jjS8+jIKB>^G>upr2<_l2sFt_0?UgDOAY{$&0| z0m||VX6W)~7&Qg!ZERouL=dbV1%Rd#FHbufB0#FwPztV4UhYuF__cE0m^uTvNIg%N zLs&%GjLg=W&?eoNY`{2=%k=|$9wAW>tCCXG?kj%j5V3z~E#=-IseE;~8%BNW-k)A! zN#nAZ0rx}rB(U~>ya!SnQZ2+MXWJv_%KVjw&3!H4Gxk~;8`0oCP)7d_dKC7bWVrm} z3={?5h_zGOv86wTrx`7zG}Kj(>gv3gm`JH|1gt&z`#w)nV$X1eD2i132%%EaUCkF)WjWN>pjG*Gbd-J{aHP zg<1{koqu2hTYE+vM`o}55iYm9TD=%bjmv!zuO&EEwC(3l;HYj^r@L$J{gTOpz>;VMqC7?6y2ct9}$N##J!vMTv&%~^WAt2dFuaoS<~au@Ml z*$G6+JJz)y!HL-M)WF`!@y05s`aAOAS3tUXX^zSF;{f)~4V>aBYc86vGL!&@L(srg zQZCHeF1n9b#46sX?;;Rn>T320CezojkFQ!A zVJRjZME2My2L}O<>veYwzT7#Gw1RoXtO8b?h0T*J`WFj45nbgSrZKGq7_?pd#)QXO z7tD6`mAa-*>tBbUiZQVcG<4re7=DxB5>W-8wRfNK1LB2z{hM_vXT3tn}l{cpP` zM4uHYP39O3ecNItJSGwYnw;xEMOt*GHbXG72xdZmO9L5hl(F< zr<64R(P`^dxEPd9w>IS;TAhx@1|6puVZu_13!+|CB>L5pz{-kz!WDUxn~ZYQQW18h zBzPJ(r_5Jmv3HSOPibiom0>eDiOgCbi09RoTvlz?9Ab93Uf-pqg32m>Pc)a2mrs4O z%3moMhavQdT+9h2uGE_Js?C9NKY3Gre{Jk zdB+yFQ28h?qhuemGWBmi*wOiNL=uu!d&J@D(N#Bn;%0B}c$?_aQ0h@Q`)lF51hbgd8Z^N z2VA6)`rzWNpKYYs4A+|a^An<)g@hUe5guvhXg$~a!GS^C#n~TOsM6EE_r$vj#+Yb*b_GTlWe_M7tab7w9>ke##nw_LH|sY{br)N7ev!IT%*47w z9feMOD=II?z}HA!A?FB>yaibGP3)FkAME3C!^ev>zg6%2y8bsC6HNyhRMkbp+cwdb zme#%wr}bJ(d3T1)K|3hE48=1;69cIEhzVnONid@)|7eKu31#4TIN#ZcO4z@&hU0|N za^`iN4JEP_69zWyAZD1X`eJvQM?CxWNl~;(R0%5FAWiW~q2owKJ6@iRby0(_P-PT_ z*@TL*_B?~73me^^DND3s*0r|M`R)cl%DqBK;^)cyvbH1)iW+#Fo+^kV;0D$;!H&S_ zeIKu;_ySoL;pq#opv*ecnTIX_O7X?h`cql@uj3-R-0nAumRr8muY)!W`p+^IeT&io zyxZ4Fko1yi-CUX`2;E-UJt1&SnZtXz$U8_%Jz};TMHbfHoX3l8HcQ+fx?*Q6f5adX z905 zBSBmyf2$HPvcTl5-xYX0Q!g^Rh6ZG5WE_zP`2a|NbwegZNnoUVJq33!J+ko3Vnk}2=Ss8PV}4fXcoMy zWPE>IfhrBeK1Is%C%IKxftW;BwuPIj26DXrawXrE&ay99+%_)q_LrjIin$vXbTdD| zT~-e6fJwA$dJ&$iCJ0=|dM<)V6F)ykDlm~NTiZr&cd$ne8O+D(2^ldRAU8)JG@-%u zXwNDFkaIP*3J;p!Rgu!18n}|GI?HM+Rtv#`(#^BId1x&A(;pekA-(gU0bjVV!hRWh zu;D{TJH4eXvN59z{7+@Js*G7bgsZ#Ez0NP^ydn&1&y3P&0pRZ1hkO5svWFsFk~!uY1H$ z@FVv6x^W*BB$-y4&3|U&WaL_9W_<=n_9A~Cox{N)+ram<djDawUDi7<%4XFq)EoIUPULfx zZ$m7n#M`fj^0rmONd0gFr^sMBwn|o+6f8RZI5>h-DG z7GQoh9+&jt5?*|jW26@d4Y#4|y`9x|NRFA1+*9TsS8(yu`H5vTrKJGbgc)(2j1`7a zAD_#XIF+2Y+|c&FSb-LY_Z^-xmnc){ORbf9{i1j*3oL`C`9Dd`$noa|Lo@of^@=IT z#i_d`e>`7K@qOzU6My$28ab6&mH%?H z9o!#-#M=!k`@J||6cB!YYf?d&xxs(S#OAh5mz3`3P4KNk`Mber9}2&a=ZWK^)AsTH zWv)i^lC9IC?YS7?YtTraZp|N_S+rYf?Q+lbeZ$b>m{h5uU5w1Vsn`-z7xC5jZX;`&6{TdX|XEecWz8mp=M14EI8#@QEH0?Tfsct|3C zQRuo|lGwwJD!Sq8lRmL;;$gGS`7o?@uYoBdHr7xXrC&SkF7|n}<-a5}K%KxC3-jDD zYXzd_&#KY+i4dy98c?@9L%i_xGs{g-Sf-&2$p|c!ZED*JjoOknS9H$xd&;+K<561< zimh=^X(hS1#~*h-2`2#qb>QZz@(T1VA~n(wxb2duz`s>?u7#&iZXbwmB@z9@p9Zq*#!D%Uz%Qv?P}Vjue14TUNefcZT3j>aDzvR{mZ zeR2<}rAV!}fqeHgcu;g#$5k5#_;euy$~?SPrb$Yga}DpN^aT@LnAnC^sls-qY$Z|m zCpHXdX!S@n>kpEb1--cHjw(YQV(6CAV)soPgvI^vzGW{qJBfc%G^hfQI#o zLGdT|)nF034rV|Cu#~_tdJdXI+Aw$ES%x;)-3j*=+?f74UIW~1$SPtwb6fekg*}|4S5w>=s;|@5heR-GqKF<28nnM#cmH`DjmHt2ka;o zg9G=L_m3X>Q4^JbW2<$VgI85L0zI45aVSC4()nwV)qC;R+%@sFNa7#%adxlVAg zp~~-DJ??|*^9$wH>2SVf-ynbBuzOn}F>A#3#0E~=80sm65TLC0U+12D%h?c)VKW|+ zq&Ov(o}FP!0gLFS5$t4^+`bfiiMaBTgrs0N4tL7brqB-eoGfjN6XHl@hM6EZdLOI2 z7@|d*O5$t_huV4uUxNkbD`-EuWF%xgL&};fV?P_&2{6G~AB6xg8s}nLC)g${km)~c z-?-N@0*m114p6|Q4HtQTElx7zhuH!8?cp|P}7s6ao<-7~$j6OE|mbxBLvMrq^kL5RWWJ5dyV z<8R0TBnPphwfj^eLw+tOwz()OAsjN0*5652Qiohk9BpUz_8l`9vDpTDJeMlpw)XxT zOR*s|G-1&a(y-t~O+M1_fxF~?4V+bMzrw9 ze676ae^0=WG3t%DB3g4WR=9(B>7h>N?AI)O!$ko(r>Fy+m^^PzCMdYrS)2!S^PGK_ z;1h(zt17bA|KCs}n(4Dz=zYwqF!;0F^N5C(kPl3-%GrE3NX*>0xa#bu-;HVt$`qdQ z+^sB45lG|w%;y7FZm7{RRoY7pbgEXaZJ}8;cH1OIUOn{R<#!rL11=IWlC588<{pU> zj7H0-0F~ltyA}yL)wwX7@}?GJ{2aCr4Aq|jqy*dIhBjnp*1r{yE=7HYe|(K!mDW_5 zb{%3u9QFKa8ucRkHy*Hj+Z%4<(IYkNx*ZYQWb}apvEfoYW_KxM4?X#iLBuwxKjs3Y zyw2~>cyIY^V$xG@>fakaYi5071blPA({Oa5^{N{?XvFAHL|aw(?D?Z}$ zC%iu*SUb}@m+=*$`HWk6&H|bWJ?n(QfZ#qX;$YxyxJ_Udfxw44)b)RqA8uF;CxI## zP=UQwWLup1H@LyzL= z?oFn69z!|~rsj-_4~mbZAkb3Vx#~!rL#gi~(}$$wi6xgE%i_dc#}^I-&clNtvG4at z&i5+@E(i30YHwye+7S`B`3nt=kgMflBx&l9$U5U0msDMLA})~=z{fq z(wp)*+*=$UKOWA(CFXY7FOFOellduwIJ7@zlGgYOZ@yt5^x->j-hA*=6`Jb^#K{X&NA9MRF_uT*vn>rkUHUD0!o zw`VVCvxON|-N5j7)b}T(bqLWAPd|yxk!2ykm#HjPM{0q1;Mlj>M`Bnet-nD z0KKVP!W3!#;jP5KE%Xe&{1fm>n;>_}w2I(Cikg<7VNL|nSo@7MAn8-9ZU~ ziKhXfK3}(~Q#WQTvL)t~$@NR$Lm1_`uqZHQvU)hq)(P#Xby5Mocm1&`Wt#z2a1a2I)p()W=fiB|?i5&HPxh`gf$eIE z+q-1%fKWZQY9TJZ?3?ya^=C9(4Hnqbo%g_QN^>=D#B~lvn0=xwG&L9`h6zkRBjjN- z@6^JpuUt1~Ric1C6M@zF#@s!Azctt^mr;9?;CoUIZhWqg(qR9kfq^!qh{bYIo271( zP>Sz2Ow64efr^(+AJH8<^LN z%9Z=^{AM-=w$QcoCZs?9ZG>^1aWtg99h-N@kgK5x^qauK?y1o#k!;DuPOHKo}?1xHo{XYVZelb3fv$odJeg%M!Vj&e6z5F%@E0z^C|HcIeEluWhHn*Ir5XH;-a65? zosjk4c*5#FlINh7bbmhA3@GAP4dnKQzyqd8JtPnL$pMZs$jaVFEqR`;WpR02i!C%0$TUFA2tZJ30a^ROVA)m&cHx{i{bca@ACk_B1_=6T#&<8 zP>_~RxquaK>J}=SailQD^)a`hh7TeoN>qLfJ=J-$8!$&*SHtJM6>XIPt!)EYOp9K* z_rzTuefmEdevau??~fdp!O{V+<4JF4AWQL6wUiqoW^%A3WtWDY2`UlbXzGnMernx+ ziy~MU(a&6dU`UPh(mlyq@`sOp;euH9;KFb$&SZ701^rZEhg!8pN`5_vOHuI0MEr>u zQS`^Y)#t{)L3LUrw|$u|q+n%vdocR$j3BkX2`PqxGqx!}C?-_Y2PQd=&p2U~9XSU9 zu(I{Y8&D@nj{u%d1rqXUtqZ_368zQSy{BtXuJZpy-)~Ql$q|r|pYN7DW{C6qJf1a=KX1kl)y@@lL+*#XZa;V?PT?_J53lERFk6LZG>hKgeOPWs zm#IPVSJvNCsrO#(2LRg4f zr5qIRL62Q91?|(Dt`$wkc^_%1X|AYNKZrZnL%1feGm(ms?T~Iw1d07EH_X{U8tz|A z)m$}}sUnH^DdIlj237|vtok7Le-Z|c+&vke;|h^jgveUV zX~2t4a!>tDn;vAH{HV(5o$n+}JK*XbPCOOGe@1D*erfRd62%*=q3P^a;7T|FH5PvX z#L4-J~p{ zet&R6!EcMx9b7oNMw=ypD9^^4PxsWyft+swStwT{mlEv5 zjmiW0 z>6j)z(r6`aP)YHVKt=Q3vZ{vXFSGXG$Tp{_PAy!;DghtbPO>D1qSjgt0Zj?k2)w$P zD#sx_cbbpQhdfcS#nJ{HSq_E+sPy3kZDfJDj4Cryamd?ZB3axz!P%BBh^j-3?1UUk z$%uqUE0I{@Yf|Cc-(&?L18a2pl_SUj zQj;0eqy*(W2b+gw5ubEvbc{Y3=B_Vh9ShEjFFBn@^Y#lrdQZjo7)A(0(5L&qgNh6J zWN7pBh0RmDxrEv`hvQqDZGE*p{kNaeiWkZyf8Kql1I^b+S!OE8eH|0RtBt-04#^@S z@;h%!gD--;ZxZ3%1cEqW+simA9eZ?lmde9u`6hhx1xWr@U1E=$7HAS5@elAW919Ms zFkr`;Y$_DBKa!+llDW8-p~-j!jUvhAeev*e6CkgB@kaYCAN@hu0Q%|-%Z?5HAsG=M zz?yhIYuDfQuxPiZd%w2BYCnTgdNJJb!4&5>JBRv+KbrJcgm96x??p_*(i?p2F$xm} zf7y7qP^iLaRa{Mw^;YvOccx|)h594$(x~Zb=>Z=DZl`5_Q6{rZW0mf8C$9g-7Xy=T zyvA|KR^u|cB4VTk1ajI3Mp)||;l-1yd9x^h)q3?#rBj;o^?Owe_$G487^q1LyzAs2 z#@|F}BMoGnxSCO`0N>4qaJ01i=ww5(3hI}bGG!aH;H9fWP}Bb|%6f8}2`8=qB)oWJ zqjjYL(MNRexR(Rq%4C>@riO#^*v$i&RjZnO-rL}Cy9E-k;c}nyKU(|6Nl+cRG*O&K z4(_=ni6;xLWEbt>UFM*_iYnl9R&N@CaB%IM(jBXbJTmL?jpTXp%FBP+;~PSMQ=f$| zM2U-%fKn8a|9v)F3$jOda!y4r_{NE!DWlV1-_BG}w z@%>a}0WE92ofxUAF#4iniKP*ZU79{5C`>Q~(b06Q=cD_u9z!&5adUZjSj^6{6fD~K z^U_svy$i1g`_q_zGw0bD5&@Rul7r#X;#n&?WjdBTHq!i@ImFOQa9}7>2TJ6FlliN4tjUO|rK)MGA{kN2{{I>@E^G9KwZS@9fXu{U0bG_)%)1cg@?;Z=BAbN;j|g zvW3pTpPyfkc6?!XYGEA20-^Z7;9R2Lm7$tQ0-bRc$%-CSevkX$Pgq$#95X^F4sj%a znj-LW>3gTwC+Lnv92Tk|PEoYoxe8Uk7&}5selrKnF2xsC-X)VEr)KAoXJn=5|Blp! zU?69_YU2RfkpE2YHvG18n^?s_l5?JdOe?*Jiv>ifB`rivkH3QyKRj?*r`<&Gzk7vE zD_{3iXSfCJIgF-B-0IEM^K%&$#OECO-EN=)JIfg6)462IEtJlbGPG(oc|QtW1F!wb z(+b@%>(6i^XMxMl04eBIuK>N7m*Jo%VI`(CmX~4c(vbjEH@AJK8jh+BP@c zDgr=dOf5Xz&IP}iu;=EJMdX=yqP`;yvps?P4PYx#%8i4A(yc;%5IDYId2;?7u2PUT z^S)1syJ9?Q)t8rKwof4pzqgj;SbmWGSNhr}dTd1ND{4#hg>w>_Il~qvQPO)1Cnx=1 z!4&L8HMOYA29Hw*pe3$;>8P$ggaPOec*>e6-a|L2YnHQ_26O8Obxx``3gTo~V-oM# zzr>z?GpMK}twPq!jE$onMweAxA#a#+vEdKm1;_u=5NZrs1HXlfE1v1#Pse!%wBK{BvK5dJM4ybcwAN>0@-6sj+75&rxzb|`)qzA z=$lA;F*a>d$K;p&s6){45omGpf)F^AuLhbaq9D%z+Z1gv3T62)IkO}hCB42!`xd*~ znlxC}14#0i4CydWeM-MQYOXb`pYtNWmb!Yb;jSb7;3?*SCKW!jM}DLRj}_!j%aui+>?vH;!|@sgP%b76oRDTG z)05RygO+SdMi1Z`8dZf~wlG0C!={>jlnykpFdofTo^SxuOK$V-r{sLk6g^xDA|tjz z=lX=RCva#oO!jTdM=8!o%=w~asj(RNMx4!C@I9u=VbYAtiP<_XSzv1SkssKhnMplf zMn70U&!z7_{>afQ2Q~3Hyk!JrdBhWsNL>R?QjCSiaJtr|^b;#*bG0Uh0_uRg3tt%{ z0qPM_Xek>%+0|>oF!H4OJ|g>4=>v=A1}%7U;Y#0>h11>G06Mu`#>#4cr{7B1nGG6{ zUZ$4HOf$ue!`7oY4<6r`qKEdliyYN-x76)i=9LNb_osa}- zqk1UW+8#$1i`@CnP9VTSph(o6pc!=;hF^)%N%eW_V`O{2j|c36pC*@6F~2 z9%6_Y%X*l`!0v||;@L*9jPMq3clfMGZQ9hnDfU5SuyP zV@btU=f{Sx2!o($vtS+T8(%4U6;8a>Q9NDo%tRR|o=d3o-S-%yy&FJj)g%*S>rnlw z9XA`4;yOynK}q&)oQk|?M5U}WDD?(*yb88_@1B7h2`lpF21>7%6~@bFvT zp|WEUphyDdk2NvaLX92^%7+eZAI{#ct-^#@VjU}ZLK2wBgoZdEUfFSPK`geFtU>#w ziN&mz(#FbeKo)MN)b3D4dhw!j4D#Pj-uyJt`9g14o4RE(*Ga&Q)1%9`xSFKzH}@0eTGtci)4Y8OUI1;bq= zON+9Jz5i{J`_|;K8ymVlP&l1t=@=(lpsD@%y$?12xrWv56rR!9I`kc(gh>aM$`iNP zieoX^)a~2Mkgm!|f2sJd@xt^VPb)H_9;^0d>7MN>lGp?POXwu=6pK9W@M@bnBpDIs zt3JgAyH=^Ew^f%@qyN|hA@i`SLyX=ZF2b3l2l-Ug4hDf=e~&wJ2L7GLlS71^=X%+n z^X}n8uVGqP-sJL*Hd;FVJeXM48D$|2UuCaF5oDDPg3}+vvaIkcXrw_p<{Wj{D}5In z*-3tqQg8bKjlGStgV`T>ydX)8aG^Xq!TgDbx*5lqV{*D@ms{x;b&fYzQ?#!8CX^}f z!Lta0f*n$G`=Zv=JFAPAb>St5&zUc~((Wdq*}+_3@>nc`kv^BXc%27|q*vip_d`79 zgM8)GN=HyxMp%Ti_7$(xT?4%#e`4UTQ@4s!j`e0TK&BRJ*Ob}8e~m_av<^-8x$(t z+le1vzCF~UD4_KHajQ@5I6n@hAy{p zMVI-2pD>KPv=lUf5oP4R-MnXCZ1bGT*4$(FTSWn5`Rc)RNxX_w66;de-Amzzg z1!)J?xccVuAVAvtdw*jYy&iF5!LV7Ys(i;#gD~Q9sCOe!e#19*~%@rPf`5WgO zOF{pE_8L*lW#1ZdIQ)`ORVq4RQK7C~k<}i)%*4~;$90)jK^Rqg!6FY1#9~g&7-rCH zg8n98OY4W|@>YWY#4*tIm?%wzN6c&=&`eM&ynI)mT01)73^LO~@^6c0FTdm&4gAcm zz_v2Pj7YQKFka&kl0CFmC55A(=>Ia4duKKXU2wx?x zNg4HYO8H)Ky+4YTQCcEj@8iopr0zZ^PfI%aFtH!U49vP?G>{2BIpq~Jp15%pu+{yAJb2g=%dc-56s({U}#kPMWDd7X=J)P*(B3ZN3zliG=D$& z;Ii~4&EM&$t-JUi)fGePtZtU>U5=(>JT@%f<)N}ts`ZJ+ZwjP7s`|z)jZd`V<|Cth z6Ra8mWUGt|7A45A+=fKN8noo2lO4z#j}}%H#qA`mz0*F8cCRpE&!eIdG2nxE_PTl} zz4vf>20nGfuPSButOz5eTkUjCBP%d}mihAtCS~o7ug8Vvhs~Xo_RkYui1?E#LU-{g zcNX`M(>=`{uhccE+s!y@d>DsRJ?qD3RZV)g(7>uew>ogYYN|${S+x7#cj6V7PNGZ^}Y9vVI%W|XT=Hjd=yCja3!kYXpbAC z%#XqTH|uTcCcFVIAJ+^?en_Ex&9y@`6re}nuDo2&MieeiLlt0_B=yQRK<+j=E=m_5 zgH3%IB(A|fPNnMEf9CV#gHA)K%&41^e!9ZfZV~rI5bWA_;`%hP;@%&h4u*}hd06{F z(=bupf`!b?wsfG&R$%8lad5Qm%7jzVd8;uEpC2At17n38Ytk&V@$hz!tdyN;RA6&m z4_K>65nZ6pW#Dr{+=g&g1kkB8GV~Dqlw&6sgP;BOruy5jXGP@CQNW6xn?W4u%2PxB zgAV$(PIPbbIzfu1MOkT#8JIBc#=7B2>$zYfsvBAEtnfv~;LHx$A5Z%MKn#zP zJmSaNzKC`O@j-b5z!v6YV~!KV_va(+id&Ozs2dFT$dbi_gyB4zcl0eo0nDlt)#E*ury!rnk!xKrc<_TX{dD zBRU?0`r0}n{aH|tGW)?}Y~+%ZRqYsHKxlZ6P0K2DMgw4xWWh#oYa3?@R*^@R6gMvp z>B$!K_WquSe|9M^XC=;vBJNRfBfv)4Yvpy$I&dG(d#Z_s<-Shzinbcn4WUss;w<7-9g^ut&r;>94XZBgg@;W za8+CHt&Utk@UY96dQ%3@8M;~^Ld>F9BAZt2p^9clE~N3~*7I^`aFnw+t&PMH)BzCU z$7u}Vtm%e>>LklK@@9+osqEFJ_j1$Y#&66JW`<$uXtOy5&%WbG2HTj)H2uh12Ak$` zc`!NO6S%vKr`V`#L_9HU}8>iOWsRsTl&oR{xx#Zja(iq;SS?^z(> zsb-6C00tr!K>C>|^A>^?d#LboAg7>esxXmr^|{a5$FMW`H|5c`;J=+{O&5O}=6(6X zXSA!OgdaSWM_qeyf!U2lxsumO_M6uH?>56lVe1kgT`8#l#LhJ5}=E;Aet_ zct`5?sg>`S+!;hv<{di)A;XQMMjD1Y&j=xq>;h_QvF$B#z$OF%g0k{_&a|kfplk

|M3@RWP1?D)5>4~AMtc_|H;J}nfs@wZZMnsRp6t*h4zGF+_W|cl`{^!~iAQ^|so2`2rxK#F( z2BMXiz|fTYygN57QQ(vNkm7euKqe>CcjSx-_*L{v+peY#E!01>D5A}3{N={`<=;3R z&y6Ivg3WX(Z8ac*=mLjDj{!25N!9S`O}23I4vIy@?5T;g5jodbqG-Bu@R)lSE&%7X z98$E8mWA~iMqDng!@HtOWlS6axg4S4v?ghNmA}H6 z8^bqxTlGed<5jvmCs}6YztFx&A#aiOKt}_uf*&p&MFLj`x~1oOs0a~>!SUV&sf~)X z^L8pZu(?&*y>X8R{XZ-r)bnkn%K7|6I05MYaf<4p9*&0he8TLM*3=I8|HT2Voa1EA z770&^P_H(LW3vq6!$Y?m<{?6+_j>4}x?_D<1T_<-_%Wvqmpw*<^K)~6bxF5O2X?A} zuDqvqVH)NzICP3;Uup5~K|Dg^Vky0Cm#gFp-2!=mZOfR^H;!W8RSjL3`mrRaC)CWF zq0Z5^pI!$VD^Wa@6SF40{NLgi*K%~cUbs`r#4_!;{1idYegyKi(ZHr$7y8icziuPY zEdV%xT9U%SH-|MVVe&hkN(ZQgDwpVPBB@<5C$6#CY53xb_eJa~;zN?BSS(gL-$SvU*x0s_F!HC}1 zA5nY*N7}%mVLd(q1it>l8wz0+rV|W|cO1!g<~96;1c*81WT%~vi_R03;w?K}=yh%= zv=KmZD!SECQ_eT0LX+E$YY1i&NSLjAOCIF-(f>y_deH(X=-$8#CYvoxyhk{YEtC+L zu7=@)9Isgs&_Xwo1mC9xQUB*DII!3V!G!^BEU2s>GB#+;AYaiO-@)T2&VMP~f0TJH zKy6MU^w;L<>vt<+i`;O*9y7!o@-(c6NVZOJXW>FMy`zQkTpW#dR3w|i&3ayAu04$( z#96znZPv=!L_vsLy9bd&ovHV{#WJ5Qmm6UUIH2eblGrwU3CN2E*D!T<=y>kp37JeU ziTKJ&S;NBKek6AkBomUFlwvD@%&V^~i-2gyxj+CEmyuDvD$7ObNuC%mDHB6GWxS!` zh`GYJFDRyIpHp_J5jt`OZ!n^AEWzL2r%IW;dD(has!~2Di5%)==VpnwL|){PT4#*s ztuHfHy0Tkz6^6bTs26u26FnxTTP;BG@}P^~0~;jMBx#(NeY7NK7piS-9fq7il5o6d z^A>}75`6hziegvhkQRcFDjyLPVR#gjbFhWNCH5D*98(}_ViKk>BZsLFX9hzv<9eZf z7?U!;sR`ce_5Erl?8g*j_R_(%Q_HoSoT~G70s4A zWKsI{egR+wTR`7UiG?(t@SY2_N*(n|@uC*?P$^A`M7x!T_98RB2=b8ol5}Y+Fb~gQ zJn-~=mf~U*{)G(4xG(Eg9=~zB&OwvQea=6L!9t8O(&74Rj$=mW2NEUD_B1b*w~i{p zl>vZ!5kd_q;aaQ|lV%@OXJnFOnFE)O1^o&?;tQo-*V$=|E8N_|M*T^yQ~TZ{OhJEm z@@s%P0^IW7RqYm%Or~ue7LXjS!eqQ07%h{MLk6hhNr0Wp&1aSwn<9h17BAIzv5tyZ z7vGV3Iu6V?K8^$p!rP(gz8fcAx&(M-%UPiT%jZoKqhKn$SJo&QgpA`#Jejy#2pm0e zcH*dtnaMU&sm5_d+h8bC7YjAWh!q(CAc*RE=jyx*{tQwf&7^1~k|&nJK)nWI4UN6W zDumU5md@pY56DhsBdj+h#F%w**A;W9Q;q~)M+0*DeR*`zXhu;f%lGnlz!GbQ=)>N2 zST!gs5WY4E4eU#zYA}%2+HUxS<-s|KQqVUM5G8t|TlWHuBvJDwu(hDEVe`pN(+L zLWRN%&j-1$#=%_e_PJl2EONh#nivOmpHgK`@ zz(k{yvy&O;TDEZOpTI$E5xo!|9r@oP)c3m*oUDJbj?Xb8u|}D4`Qxgcjx?Z6CZ(-V zku|@n0#BYz@Uauh-bH>mqh*AYb@GU?x#ybhM76_?dtzYj-dAHA93_T}2BLcY(5->0 zm%a>bA?TdyLa6}|F|GopfRm$aBYA$S-MS_=Fv3`%cUmAWmLHfSXivJl1JEm~hFh&4 ztMK5%8At*4&6c064L#+vWeD+og;PWh1fSVPKC@PDpN5?3S2#1=wQuPh7Y`dq_`?J} zdbkn!9j%$V9(+KE2B<1+9hC&kZ!SDSPcw^_$O9rwoYQ0&Cn6EhXEb$Ou&dsc9?~|> zKnnjKV64&qPmYtCummx_<%^j!nyON}H5bz`Yx%V|%EOk}K#Jf9pCXU{(xEN;AvS=J z$DsnnS%?LFF4hAPVpxs^o$c3{qz)s)a#ZWG2b@F)jaSKQPCn$V2CaJi@^;t!@Sma2 z2V$olNV{CtM+6f4nbUEWxsRr}&Q#;S+_1M%A0Sv4Ft8TPb=6?ZAAIHq+%a#|J@&Q- ze!2B$Z&!+-Ry8;Z$g`%{T*{$)vLN{LV$9GBRu)2=j)JvjbgavJ@c-h1kps9~gDLHV zF+D?PwBVN!1HogPXy*G5mv{NWdv}Dp9&L=3L;z7huD_lfHr!R>x3a_arrIGfiWG=B z6GaYKS`&vvM{4Z@z|C(H&$KbphSm6X>dapyzsIQ&fE^q&B{_M=w0hd!V4O@Vq`?p6 z8jH9!K7ho~Ejd}06ckU7f7ZyE+L;J{95C0@u-@AZS+zSauCFlI0f0k`*tsCHu`apS zu)>fyL4?z(J_e&fGbPXi`84-ld|*`*FiwLmOppj6wf1?Hfu<`Yzih>9T(x)6HKcRI z%9P5({F93WzLPtskKz17`g?uM@IQf*pX(HuD}6q#ptlmDQ0#l*fYv$k&YA7(NU9PD zX&f4+Q9gBFVshY~D*-b5!Y?Y()$9+&z1cA?>|Ns_7Pc$+al5LT+@#qVG@OIEp|fHz z%Q_eI1izTf=`D#4!qkqA+V5H<*z3zVeQXi2j&j4>pj4q7m4lo!OlOIJgNRv(a;gGZ zi4XaM$^=|VjK!J+aIeN`k7`Hwf4O-6F-(-GBs5>ltdKx3P~U$P0p?MFX$1FAw%6;0 z#fyDIXG2hHNVf;gh61QgLh$_cHoLe3n+ZZ5GmkLM+By_NBo6;JM2(VxLQ4jZI9+OI zKhKC}TUke9j}J7F;||DT3uo*#VRPy$(%=2Hh5X%6_iPu;t+nt%?wfVJ;Cz;mkgudc z=Fh&U%u-LKNPI>8XzUd0s3_i-L!S7hVbB@-T zjBtuKzXjkULceRn?iTXb#iMpqG!JK;!?9*C72u0l_#SU~8k^~5n7fI#52^a;AxEGv zfNl^J0TJ@5X^;#EXz&o1U`3kmN38SEs|*XEYM1Abn#uE(1L8Wi0x^K3IY6LMa$X4W z|JI|@FBKk}xfAP@Ly%cP_%PrGg`)5B67`9hc{^9^LV#QB_b-{TbYDb`I&=*$%X0oC2y1u^1)`4 zgPWWetl~(CjMCViC*?RMYDYT7Rog$MApet19RhhU)Dkyjcxh<0n^Q6^48<51Ua6v`@G6@3w#Caw^rzV9f8@3J+{XM&RS^qmw(;{xhxc@%# z_b)Pqg65eBR?$-7rnGRd1V*{kF@YED!%KP(2Prh0y&$1Z`gWj&b!*wEs*_aJ@C`Ix z?+(ORb2kfdp0e5FCJ13Rq}@;PDqc}DX1|AN_c@MJo}5IVd7)L805_~>Pb`rK)$=!g zpHeI!jrQcjG_w}GWP;%uInBfv=4_paD)MTCp){&jwHq>bl+#WxtkRktq%GAbz=QEU zA)pN|l5}!Cyn*KF#SwUyrcX;BVH(U$u-sjPbKrUB zuSVJ$B_VPgSCpT9Lg~(37`-}2eC*V4jG)i5uz!cT%=r8N_!gk_fVv$rM;XdR{H8hA z)jMhl?~{UzQ70+OQw*p|@QtLd_G^nl3s@25nw@jI-&#S*bWDRFWUzhCp|42^`d)i> zu)Lr0&KqXA;ie;J+LQ42=)wfoU}Tbo@8BHxttKB&)Do2!j)T5_w80_2qC}?Yf(S)*YktfJ+ zn*YzAKvJvqOEzT4MMbP-qAX<4KA4G~PZ1)`k@#VAsUPqq4C@$KV+&vLDp2hVcjbW! z#Q?q6AnsZHWp6$}gVcJt4?|_T2A-I7U6zqVb_kSYLhmYhK)^?_i|gh*O!sb177O2Y zq=UWd@1zTzb3d!&NB!ep5p*R+^lCq+rHf5yxrtS6tMns9Ik=B$BaYuIo^?~OY(Ds2 z*WN=IN;I)#)!dW^Se`q!OqoTdeXbf?OxUV%?X^^R|5 zljjg$?`#0YH;bu%W36F=Rtv}2D90iw4*7LAj=*W#{|TL~UVW-ab?dW@_E2MwiNE6d z;^uWgPVZGXCP2#q`z9lK-WZun?%M`8!T%yYew@0i&d!uFUPM%>wP~R5c~rNn_iz$2 zUGP2fJWKKqa{#5A7hVWv#s?yAkL}uy?wVk z?NOD+(XW=VDoJzZIcS3W9^lzInHrnp?-=XoIV%6EW?|O-3T0?tY6^39Bs==`evzOE zs@NMHd{saXSMUCU6IPhuJ7l`x-{p5qEkpb*mu_-i@OYswyXD7(&SBA2`e?+p^;&5T zH%Pa)?97>Jv)YLZ&!-42DZUciS6r+>vgXj-mxHJ7l*SJBI9R$TL z==F?G;lCb9&uiK?pjs~WYXU=sgTsT8SFby)4^L1~jqCmn71%*{_|GOn5P&FRIhKvh zT$-{uHbAL7)yjOoe5=>`RJKJ6Z%|GX`Xr}GYfiWex|KLG@VS_{FkrgFx4Mw0tXrH) zIq%JM>u0S9eDgThqOfWg$*T!KG0;EjU3b)HSS273L_)!GY}L+wE;O=+w!;SW8=(p< zrfzR3d4l#E&AE4juV&ETgwXb^cX4Efp4GVnyhhT%e?ZdXdzF`@V}%wDC2=OfUzcsB zRKW`}3{a32iGi@d$I;0~+WME;f~&K4!YKY1%By28QjaIs_pfsDG0MQw*jRQ9&P}*3 zn#nz%C-HNVG-`Qs=0er`w~N&4xsQJ4v^v(_?vpjMSh}=@+VUFji*3yHA{z^LwDr zmlh@AhpFOKAl29SroPM&*n}Hpmrg6oWW??MD(}NwXrDIc;RZM;zDc;Ub50ebLc2>f zI6Ai&E&Hr#VOc%U?KCc}lAic)aalK1hOFCj+ezdXRWTe+X|d2f-`P9qG^1xz@Y*!P zI$OOYA~P4DY|OD+M-+rE48Vx}iemx?)tQ;vtF`mZ?qrs#bozTjRpg-9QH%b1Ajh+4b`B^~e zEy`x{2mXCYH0ZX`7Y)f2zLL{xP^81Wdj2$`X{RL)C!}dG`joO)5%6E4OEy7rZ~#a1 zI2?G5Es6k_N?GpqiwV+!vNuhPkG4sfi>I4d@9j;sS3Y$hSQ0Tn9C@qy&XJAeN8hnk z-!jHV=tV0BX2Jv6$2e9^pMM+iuy@9r#$Z)4P(u4tK^s1h;o4&6WmCobPtL2RVp;nm zgd&C_j@-g|{4vy<;t>w(LdXhLXQYzYxCn2&k1aM{te*#*1}WtJAin{sS7M4Q36w4P zSkivpf_w=my(63~*F36I;E4;W@xeOCvYUP*f8(FExIe0*}wB_R8OvpFr?uA09vSjvO4RIjjgt~aB;gN+n9TUpQ zR_Zd&Zj#owh7DV3qj}3Neyc9%q?fxm>o)~r6YjJpu#_Sg5zghxrW4pNYI*PjldyOtf&WeW`A=0 zlMeJTzvsTRQJ%GMG-Dgxfj-az$TRY)OKOh!l@cjghZX+vsajV%H#nzru=qn)r>K%+ zGQx^#xKj(To~Iy;gvJx*$pHAd6I2N2ZQcHzhYy#`Y!1nbgX`oZL68g3V7iB%_ z9$}eJr_kb9PELL7P>on8D_494AUiI|rA;AoX|QJzCAawn3{ zhHS&avl@CC1(x0#W4;+E4p>7mQ?;pbav-tQ63q06oo|@1b{wyTT~I(ps+(ng-+SKq z*EjXK>88jaaBAnbOniT2o0&@(5LkzKVY%R7xMrofVFMBx2Lqy>B+pJmzu>c5>LYe! z(*1ha2K27ue*=BM)Wqs+MwG4o$PbtuwDv>wr+3&Hgt9QHaX!X!Phf14y0GZ(w~`#q zTjJp@2*%ii8Fd#%_GzxjsA(`$r!I!uA-l5lL#_fP*DRFmq@bbStHs{Nen4x z=eG+ZuDc!u(y+H}ic7M_VKdi6e6)wy*7a(SbPx#UIe|t}6E@&k|GOOFnVDcuE(RDC zPkSWXm{iSdeyno>*6nbRe*wtG-cVSxx&#TB&42_=zz&~K4rM&cRONw}s!OcheLppt zGJlg5!+smZurgs~rubFc%qOZqgCZe?GPAsUy1MzZnn8VH831&r;?uKjzA$*h@aRw9s z?&;@o6ljekdZSf;M%OU6=BQ^sGMG~9APa~hLg^v}E)x@Tbj|*yscfCD04&TKT%3mC z>;$6l>2cw~-48H=SyNi#05Fzd|$@kxS`PNBoT1zP67CrSdqL#1>u)%>26_{S$sxA>S__ zArvH^qq#xQPid3g zCsbaS@dd$e1p06W)h8Irw6k6?w(xW2lk;%p@kBK+?qLQ|16fc1nXo>{FZ=fO5T#=M zTIsT~0Ud0yO5#+^4;@@MsBc$D)E;8nNB~?RY|V&nci*b3mc_#RWez(eA*5Qbc!v_= zN7v=v)IpwxO9~bfA_%=|Bg#rliC)BXEIL|KatKoHsyXQF!_*Bk1laTDeteum=kUqR z^J9|Xriw$I+M(I!hjOi@A=!%GMATo(ouxw3s6)?s^S~xs>q(7b6ZTmDcVK&DFbIH^ z^$S3@fvBg*eit6ket^s13HW8st}L|{aN6*_J8)lDBodY@BOkq(DUHi~p{k&MZ5Vdr zjd>Mj`EC1x+-B`$a`A{p=T`AfxuYR=VyH(IsLFG}L$^;NZ|P(fXG1#^;DU;Ln)oP( z#@T9`yBN}{>V^s+C+1Y37p!Xri)AssU~6)yXV4v6S@T;Ac5%sOpwhWU)koO=aub6m)>jz!WKf|_rgZEBB0U*wfX_>v4VbO|00&Dz4gEM5iTQ265=|*n(lPgtm1~vifks+O+QPA;@ zF0(LFhTa#El$rL{SBG4_fv!Q6_9jce>w`Mh#3X6^#w=k_l2Ep~<@i>BSqC6=ghUu6 z>G%A0f*$J}0pGruH^auT^U8yWX2PCjLze)GV39uI&T+%?M1LW&B6ueA!GWehs6$kc zB9U3wKqRJ&b|Ov;d^&b=JAPy@12GV>d-4So30<|CWs+KgjAD&4@wDU;-+rZvpMsMo z9KuBaf{ay(8)_O!y2*^0B<@W1iCUoxP`|V*naWQgfq_yYNIQwUI5O$NM3OMeG0)EY z?337%o>F+WJL5`^Y6ei3%NN<2oVh)R0Bv>es~C3DQnnBIZg|4d6ik_fcfz)Vz4SSMc+OE@G@kCE-SqK2yVRxW52r>)zd;{fQ%O?t-(OT`W! z{6E#x30r4}%Y#JTD1j-s<-1)yFeYgc!D7|-^>GQBI|_&jxl@8dUcFHz30>7Pn4s{J z!=w%B7E*>^%y^B#@y%YtWbXxEZc?DYia; zxVorl_NWo{(2KGNwH6-MSH&0tz{(p>RP^WsQS~?rZ#eXkd_5 ziL15Uf4Rn16oIJ9d>IahI^1I;SQK73qOzm0n5W;Gdp)6KBrAga`jWqAFFf9WnX$u2 z)ewqf&>1-)DnV2v8wD~7rtpk%4OEH9sXZq2iZ?bL{q!c|_WNc1xDm$Xegi)Bfyt`2 z#~*J1Rjh0WtxZHj34wnQxdY1zuxh$>k5zX2}4Mad;AVw*DKry%WVUvKgf@78MP+OW=&q{KomRsgSaOwH|UIbHv(+_(EPio?% z7p+h(j=s5XEhX#VQpBgo2f#4P|Ef59z=LH5Yefz3W#bl{6{(JcOS%@65GUpaUC={T z&d59Ym|dHDJq6v?qNWjcS^EC<*VuSLMT@aCnU$%VN1+6R6q`_Oiiq`CPZv>JGkwU; zzNEJGqizFAnCvmm%5IWaMKJRx=N0+(Rfp7-Sp}8q6%9X}_B^LoqS8upFdF|{k4Q-V zyTJ>3ET&~Pa|T;9_`H_=u?nXkDnQn4=Ns20BWIoDz4=5SjGV}aYP82A?8UIi%F}P? zch{8uIG1Y`xWly<7zVnjW6k?=A$)e-6*A(p+rw57w;A8BkN7nmbsk}EGQewMoE(+R zES7@_Iw{f_=TGkvo<`GcS~w|1T63p4zs9kvG>#aU?b9Q?M?B-1EwsP1G-RD{pl4}JW=ZUKq$F@l}lVa4QhoG7eG-}r4VeAM3r zSn}z*B1@J(&fs+lgk(X)(^>%a#tG>*r5H266lXH&cVBBR12%i<#ahI9-F@X|GU5HGiAwh@evH{bbl**>dA&S%Y{ZjgWlYs>1BEi z{J%oZMZ=75R|evY)%A*ZkaSW=#9W@>suzvg;=qKY{tG zl2=t@9|%T3+g{s0bUo=Wm}nrHj9tyzFF+e2T`vr_^9^%i-`hXs^w6L)ehmZw$hmCX zO#?pqSbm}dB;l7LO`9Rp+P;g%HEbL*JcrNDzH!Q}jElGu)#tTAjKd%EwgF3k80Sz- z!AIjry-$svruIfSCnhj%MN5`qiu+A{&w7BXPb(}ME$Fjay+=bV4xCms(oXz72Fo)! z(^yI1@|e=dB!64u(krU}#LGpdSf;T@&#Jowtg>rOU)JSGTo|ZR@m1v*zl3PYGM<@9 zKYO9SA+7kJX2!w?``ID}*`t0K(-LqzO+d2>g&;*z%BPg%eSihJv{l0k$t4$Sc6y!9{x^ zFnQSO(>LW?e}fjbDgA6QzkU;3AD?YpaA77a{tcIC3$b52?&Zx{aOEG$27{slp2l>G zwZNP^(nzMr;%v8LFt>|EdH<+Ca zg0F2!=*fwk@_z8WZ{vV^;qK9y*;l%_l}Kk7UywWfX5kAJAu!~M{o>K??r(SoW=$hJ zv52wBcHEIt1db}27_pfQNIv?yA4h%z%&YW&^o_OsKFn|)2{1XeoIJnw21#; zxUDCjy;d7gko?Y$4}FjN-`JqgWM!{)(Zd~Cd|I>BvZr|64x`ET&|M9U*2sdJRbmbFm%HOE}d zc`gS~rwe!{8yGzw*ET0Tve@Co~FWsqrBsWAz5sL5`gj!#HJq`E_ zDj8x^sNc0lK8!TjzwcqrW+G~M&gq5n#j3~m?E9!UZ&`r_*OvB=Esa@Z&V|qb0h^Ee z*%=Q;-wgc;)D&tM!majxCpV(^G~p$IDX-F$#$gx2b*3BJHCK6@NJjr8xX-;fg!pr% z$Lg<*D^N%Ku%{QcLbv27*zsMR*q1=S1l61pm=3+re4DgQ=b!VBqU|r5b-J76N2O(V zN;uzzbl8kJP^?1C;wXeGz69Xd){QBMM+|-7dR=;33<+XOA*waWOcdL<${#N3@)!R;CbJ8AFpxpyZs#fi$N0 zPN^IdQ$RN|!itb*+Sn^%qU5bh>9QoAn#uln={0p|zynfOW+HUVsSu7566^(H|^$5n8h|*B2O}9)XO- zl&*6(z^gZ|nhg_#u(U4I)73M&b4eLGJaA6%_oTE(wdJ$=xejI zv__!f<-1TPo;u9<5+6Zvgrx7DRO&4$@$vA+bw&*%t)c}0B@b>7+MR9695xwU?oOK5 zrcUzbr8-T1{s5*C&1Ff0j}x*yk({=^UAxLw<|wsLHD!#et+@S^T>72$cjZXh$olPJ$pYLNFJk3P2hN;Ij80LQNnM8Sz4>*>b{;K8uYQm62>_ zTb1`{HW9p0DN_5m?!cK+2~tAvGjDX?OoQv=XVvvR!+(odf}3rl$$IJ( zf@HQaLxSFpOE{8la{P$T-L)4P)2+t9u!2gTJOwfnokj+&J!#%k`g_qUzKc7Ygi2`t z59CnW!S_ zY?H(E)Yg2zVXN&uw39Da8b>zL>4o6S{o;5uF~-MRg9^RqcIV6xKYOdz0kO(Opukb? zli8#686W|TC)?QloR@vnuDKndfs<@63N!6QvbPJ{gN5DIsEYeo!B@GrMTnG>`&XUjCV*b1FzN!=$#^=-Zj2cqHIdxj&RH z1ybtd`a?U3{~ewaqTH8avPlBGx;ihxR8{OPuKF3VPq8vk<$cV z4B~P*TOlJD=*$6P=Ng;e>#^{mq2$I5!6s(;layKwvXBSgvN8LtP0ez8nXSPAHPWO! zGv%g)jQX+cxWp+z-9TvBlpecesE6bg&*xv<{%`5=-L+W?1%5@+!$sf9ar2ox$6YbQ zqty?pQ>KOeC8Jq8(&WGu4@DI3r4>|VR+>L6)GuVpP^DgT5%*=a)?HaSh$8G(P5vMV>{1U2725vl z#g<4;%~uo{xdnn{9N473^2MuO3A;;FscroNFGVsb>hYd2)57TFjw1hPMM;pDS35f} zr>}^c(AN-s53!87feG-#a5v9=VPl7_N@McTN?F)$r&7YZjUK4H_$9c9es%N+3by?) zU_{j^pP{FJkt41Y`n1z0+vHBin9Xi_@-n@xq z6mMq+Do&m;9Uf%;;%6~lTKxC!=>D(VsL@{r)`U=>lOG#Us}o(08-RAK+S4vXC7Ngv zgJtvjE_5RC2j6&69ciN0q6fl{DJ+CCrT-jj-x|{>Wr?*UJwRa>z19UCZ1O+fHwbR5 zIpm&{* z!R#Ys**4T_dOmq8z4snD@40%h(JKxD=+`ppevlXd;T0E$nfIQYDokxm6`A^vSi}-G z+run@clp9+D3Mi!8RXi3nf(e-qn#B_LJl+ae8bK3no#c`c82!MT!BGAfxV1uTiBM~ zbdWu_v*(~6^q1lbUvZC~@s^3J04c4KYX!WED|1iF`KS|L zS+-0DyC-}qe+kd7zQUxP8|AQ7!?tqL?u4AcFBObC^ zA%`OMwxoTHfd8!1F?vx0b0ByF2zKcd{3d#f+34%?D?2jJjXY#Dymt)U1jdnu8fUvH zu7|G}#)S4$M?6JCu80}cP=G}Vry<2Jay{xFg9@?Z8+B8Nt4^y*2{!Z&ucQ0Tj4LqR zc=gHLpB=XzqvksZ!~h0NuO}mgHrju{inEFsC!#snit;(s1f5sJX1FQp?|jY06+7NR z5?>Gl6nN`4q_Z39V&j(=e*?P*?J-Af6w3*=dyAdG$a_>=25msYYt@Od4{P zy1s#-udS-|f{Y8-rwJRekPc=yWk%5nk>!TX6s6MyR9h>~&or=|MFB2;`mt}wo88nB zU`rN%=f?LXS$@+xvK+thW8;bSrO8L_brsMi7!NmBz&|pAk!hyGL;r}KJwYNuilEGq z%krh|od(oH1lQ4*VR8o|J+W?xn7YgM0#Sg%)xp%t{AmVlSAqXFBmj)+Yjyl;@@Zf8 zVJTxlZe_B02B>dblna`E1{g-W;2B_eon|%=x~)XV*>r_|DOuMGG9x%ELJ%)VS$z~o z?FLgd@O*Mn)vc*} zvDbW>eo1Eeq8IxWisW3uHK*t=|7;XWZ`zw|qpOUX395V>rIy!Fom%tS`rq z#&Qs8#gB8gef`-2LC7LeBZ^QlJQdJ2&Ho%3!atFAmVHS)yw!2kH7`|&cJBkb8yv=HssUwcF0&a`fX)} z7vuK^GPd_ZNVHs!OG&=j5EQUv{kwo$`Vr#MK(MhdB`vYhHCq^91%)1Mqcm`QZSXJZ z`OtkyFvc&sCK8m95;~0V`^IQ2O^QC<-xjT`&z+fgB&B5<6Wqx2UU;JO(NOB~n}}&S z&eUW;krWP?@BL=Ke2`j-t)UiPI1ap2w8g^jN^Ab`z%gZt4^zToQpKZ=c{&Pm#PeWJ zJ7bAbIIKKYkgUG^vEoU6eU%g^a0ID$X>$E<6^@LKOSFc zEhKTwP3x+0*}NRN*Yg%HjGm$BL_H8kwRa6 z(Krht?$|%iD}cIeb|zhd=1-#W;?Z{Jx}q}FEljIhA*q?A<1vw4GxW6p-Lra+hRC^z zqAL>TU{J{y6cjHOMbKCZj41a8XEp@^FBE5YpP;KoF^ithC!0A@Bn?NRoVBR9*X6&a zjGm9MQI8vY4>D>B6YIj0w2G18z(ShfjP^CyFODVYIP$r8Ke-PeYn)=Jo+BlgSihDu z;R_d?|GvsUHt<&8v2EKW+cXH+ljY|GfioiS2ID=^XCp3VNZTz63QBDz&Tcw*p+P3t)>pdp zSWQ<1-v_?S>)Pj7TICAe;K7L)ivrP z)`rn&@=Ge@D!BjF!^EqK^wv7>P3K&bIo3&e?aG5YSnpU^6o zHN(ez2E6a!lWEAOv8ZuYk%57#X9!bn7sAKtQ&G<&qC-Y2Zpb;09Y>1VV)yH^N@|Rg zeQ8Sop@%C#5TK>45I464b49!ZyGATHtGEU=GSqoKHLsdc48%#oOSMQzHyX9={X4(qN9}5N?T%so z-#A+^`-e<5jUAC|gvZQqzAX=%w;5W*d`^vn`cMG;1LOEVv06!^_U`>Q+4_!g{xZJQ z2(}?cN1dW$09qGeNRUG@h21`3vZ|aE5}Ya_0nK`XebLU8){ip1W;O) zj@Ul@C4+4eHv~F#1aJVe^OAP`CAX67t1Wbx__*^t8~+q52PMaaGo4sTY&Hb;*WVH1 zPtiUHea8af79bf8z>V0X3w;aj3g@{ljX3ftSdvKft*(<*i+lhe7~P{H* zN*VYcx}|>hnNul3hu6!fF_}k{OJ5>GlcIvTGANh}7%{lZRGevDdm16>Jc?J^-$kYO%y_m2*{N9=9-2`YO*Hhs%~s5_P-~nU zZa7O~-c(uF1%L!_UvenxxI-QzsqtSXb&h@^t4botAtH^s;RRWD!IqF6cvixI*WV$Z zX^}2w8}=$?y`z(4fC|=hPGd7|Ju5J~N?39D1PLg_|4jN%nCHviFq|Qq8@|i|0PT#8 zC!{I=6MpY!vbGS?lT=a@m?6E$f|b?nl_YVigzFXK=d5??`9PF%f1XOJ@#LBQ>``g} zpXTaI#tMILT+|%)nuhA*5ozgB%b3;Qy-f^SBzEryRa z;OmIORwW>WfKstuY;iq_Htm&a!x&G>HWVk@El zOLx;lc-6H4DmoWgwqD?_*b{(hqzxl61M$U$jWU$Okacorxq{7nw+oTi!Uv4q%eJ&uTXz;bj2B@agGY3)=L2R^4Yg zV>g%&tai3cl{EYZcUZF=G?pI<>8{qvyWAmmv9+!R_9`y|i2>&t`|=^J%`Cj0s#?LU zR$@FyQtRcHS*n)^*RYV)~}X_&erdoHfVklf|*bQgkB+{*F|v9om{^7s{s z!y0yMwJiib<3KQMKa-6G=c#_MNhza27a?^A|H$?SCX^D3&#(0?gR~GSzc_*r`ph%L-)I}fT@h@|% z6$+f?u-)5RgiPNmd`dffi6Xi18*hN=U|IXY(jkfhC0|6l5Z_3GdCoE$Og#ON1TP72 zp=f1aq%V;hFmyV(%hUYRG09{HVBrDO^ii7iVk;JUD)Ihf&KxjB4Osil!`om9?6{}9}4+$H3mgF6uWI0 zA|@N`9asBv)jTvpUi#|o;lmh{T%2R%^fnOR(9y=R$Vys;c#LOgcBId%VwKe)MSPA= z!U=IENr?rKS1)A$;TX{YM5jJ@TZ`x~vVq?>y-J{#O3A2}WEdqAyjopzEv9URD zEvlRBK&V5J?p+pm3NT4ee`ZJ_MXA2u{Xy|QXVU)kjPqj?8*A@eY_aBwH)ovX}LO`uLMZSrOLwov0@N#q2 zW4>tn6new(=OFqrv=VxnkRS~3Q`tk9Py<8;7@1KzNYnF~wRpVuVD=(A&H06J_1a`l z7$a8eHs>IxeeZr+a;vikW%?LXi(!>y$WaEhKa}ZmdOhSwknWc=9UxLpB~UFWNvkUafQdWoDOuu5iQj zM=dWG64}HjMYFp~kJ(uieyBllEsGZPM7-NZTpBx-L$^jO)5{Bm`eG0a07~lagfG3T zM26V;Uj~jPRFSk%YMwcI$ASvEMBvBm5c)EB>jG9*`^ErBIk^#`3xr5C^+B*sh=P{x z^@;Bi#OrU{N%k}A*_|7xB6BYjsD?<$f!)BxA%M`ufe$t}KkqUs>v--G67m!f&@z-h z$C2~KqW!ep?gpCZr9&PHB&^67=|5&1ydcr>Z|77J6)O(*u-ue0L}ngC7L=<(}hHkzqcM0J}Kv}z}TJ*?=%WYW)=8;_?t>eWvb6f8p-k&?zuo~ zw-RZe&=Y4^#%B*=naXfvy_ITwBslJCiKNYB@;nw@V7bn(-tL5&;n$O@=w4TIN@m9E ztl+|=+7%RFl-c4H^-`!5%YRmV5e%f_&QJ3}#Z!fJX0q9*0el1JZ9k-ZDJH{COuVfJ z%oh|treDb1{JECH_-VA`uUrYywUly2sgN#ueB_>(TIB!?&g-+LxhZHE#2}}JqFsGO z!35U;<>0L8nX!K6(8?g#V9#YS5pnwwMR8mHsmD)SD4R12li7bhe0{MEXpmu?fzIb5 z!EIH;bHRwVobsU0seUdpK)J&LcM7DP%e{IjYdBdRHaQw=|VWROYRr|AZx{327vIMIzFgl zgb8t!*{o+l0H;Zq2S&BvWOP`NSTF5y!|H=x%N(6R`P?~(zRo*vtKBeV>J%zyBU_0? z8?A@Sp(3lNr&v{TmHt7FP~I%+ycW`(hek(;-SbBtxYbXc*uk}mg!FPs zIPaSp5kpqM4>Vxo{HD{i0t3C`j^d2717T`NoAQo+Bml49Yz$# zV}$EGu;)8AJZV>+k_Acx(`s{4*%4ABcj?DjY8noSM?z#6*4)K#d?i|`$cpmY= zzV^6xE;(x=7Y@aez=#XF<9#_heQ$f=?E>G^N9mtJ+h`pFE8PtY5RLHOV+QWCJD0rR zaZs9ufQJQ^fN6B^e>qcEm9?!}hLGLnK0L~0_R~nqcscT$#Yk(lbs6_IXaht5Tv9Pw z7Dx?`W&CO{lq`igQYafw4NCJ!CI03m^vzM2hib38+gZN>1s$e|*4V=*?<8l8c2k~xVo@U6 z$_tb(BKM#Bkls_S^rvcywW@t5%$T3}pO6xp#8@w-ZW3Fe1d=Y(?KnH8s<3T*4p4tHIW$4;G6IF=`M)N{M{zR*o9#V^XFaL(+7Tu3icQ;zX(f}!7HSq~` zp(?AdH3GbEOp7He4WWcKEu~X7!SFBKkDDF*c-h6Rp_ZMAfx&X}5qug-?mc(ITo&)y zCs$kgjD5sNZJD89P?O99XDWQ+b&G!)OixF^8QXGU>yK{Phe3O9nzeupk*X0#i!nsej- z4ZdWmZu+3B4UhR1yF}<|C73IRW=i7JB?pnkAOG#{$>cFxR)97nxCa7eE?&{T>Shjt zI*^t`&d2Y~QvYb9Mk%T(ew9=`0d=sp=+rMLPzD3r?kmY5o70Qb}kuBCOX z;%2_|{D^8>Ynta@VB&FZ@wfqKD1$!|TdXY|?DB59QS$ui)rrH5&F! z^>g>orqwc<4NU6ie zSTm*fL!&X)DWpPZU?YTi6%P-YMM}kPsA1SvHcNoQ~~TE-@mRFE%!4)#*}@>tpoh zb7!$0zI_WtO3ZTS&>Ar^@X1h&Hl^Y-V=F-*Ma7s!^)1T76xLj_{f=KBWvI?atT3lo zEa*t`;~u8LPbt1FA7-J@U0}qG?;{Nf z!K0Pp<3K=yD197}AS-M=t++nK~`0Kq=mox12L=xhmPF zeY`v&UKnbb`h#NXYZcu#-R#v@hX+4OUYt=JEEYFVHJ()yoN58$DeW6XVT6LS#e_Q! zkA^<^xm!1^lA9V__PahK8E^v$Rh4lgs+FRjZTq*6W%;)?t{n_O?xc=Pig|&@6ao>z zNzK7gpfz#|0Bw*J9O~pmdr5gG&Q0{}lfRh)WKu$d_*8MmpJIo7Z(og^?C63+VR3xW zORU2k-RBmB`ZjxjfvWpkV!F4P_|EnIX=*bXsyt!V7q-gz-$$B9_Etufy(%JFw(c_E z`#1c3Gpy9Ke1d4We)<16)qRfX8pGFhaF+Kef83J@?_Puw&26S6uDK>GbQx&ma@)`I zubPRB5W`NE|4RKpl#?K7}A_#4)lX?ohiGe^H+EIC= zLPXJ8sk;OVfncxl$ucv(DLbYS#cIm!Od)*30aTgcjIyD|)b^XYH4mM#{7scRdbQZv z=r08W{maOk!~G?y&E~Ymv?htdkC6K1O7tAGnM$R2LOo3~(&Y!-7i>QjwP(*z3xBxs z#6OPUcwmFeFVlQkYWIP5*w)v>d-OAbE@XMHXzxiqa@eikA+xXd&sDV*-lDl(9<=VE zHfkV$BtkSKjNbdie*5}qUeMWMO=HJOY$R-Dq~s>{b3h%sr6IiBS7Id@*vH>8|43eT zn#$7^9;KoK_0K9Xd0c}bS{#EfW@?$w>V8dY1XtB%R;xpviT(wrm1z#M5?#)ok9Xyb zSiNjV1tvKR#9k(;#Rr1`H9*S0Z2x(|e`9SDF#~2pkEBR0{@P|@2Uyn9I_GU`+fB|Q za%ZbovW$LIpf zm&=%(9jW>6)IZhTm+tvcO~Zn!ap`n4abe`#*5q;6hkk32fs3%Q&e7DWrDXd7ylun) z^0!H^r^VNzbbz&*EB3hLoPCfh7;9!QR&N_VQcupbAEWcgrtkB%tV@W9L%h6QurqAU zZ6FFTh7ixR_3}9}DN-2{A6bYP=hs_k|C4$+UB0roxykf=yu__fuoodqlKDXsu+Kql z4yd`iY|Qg3qOE_gM=ZM8t>GSZ8iKFO*$1f1R$Svi^Wr#=U=ylO53k--blms%iYa%j zJXF*OhNSx=ZB04bp%;cnPxlVacuV@?B@qbqERsOZVWNdA(NTdRs`l;Ld^M*%xG-BP zK$)wyAMJ)W7g~_tOaa-us~rs@>YuaU+*o73vVm7ue$mlxDSItTY6h!bZL~{}sMIvh z!!Z7+jo^M^3-;oAV0eUvfc-yi>k4gaakKZbH!{y=${JDoLW22brHdBVsT}1+xmHN_@h1MZ`lXiy68-4LWS1x5C33Z848iOB=GrUJqTEAyvU3cz+x{fnIVj-C# zI=jy4q$kpj?zgn?7c=IBafdpHC?tiS%fD!WZ)F@x7$1G+=Z;z6f>dFkxA_@a>A?39iv)9fu9e zANMmA&%f;}$Pq_Eb!q#M2HL8_&=Oy>O29m!QB(yw_w|l3_S!V&uJYxeiyHIGS7xPm zLD%>+Kc|S@J}UpGh2IwP@2Mkv2Qs}miMBCEiqrAVBW$uM-92kBHO=yV!#OspOk#uf zeY@u-N95tB9m<9QUF8WP-m)^-0v(ElA9pb`oU1nr6eGmXE#3SeQX~KE$h%VH*+IS- z0;NeS9FXENyQTE@1QX??$r~XK(Ji8j0zXy~{fUL2Le~&qBR%JvO5-#4-G=JqXO>(irCiK?{^^1nIH>2ASzSkFz?Dqc zsN#D`W6^!>>IZk^h&!rYaBQb(N0S4y9rl^x9ll@*e>7{b?t+d$j|R z#&aOq7S$V+I`uwftHg}+Wr(dIwu`1+446Q|F4x@o(7_bLOH~+n!#&$tPjByH1Il*P zwW+Q)sta)jsT0qqz~K{(yR&J*1oO&p-g27j>aM6qs-m>vjF zk(1x#G;%;&8|jt$cgJ+V^GIkbsP$4`(EujURUS2Y(whHGyyCjEE$U9(m?SFYWQJNu znPP;9-0ipAfP1pF`C%)~2|?!;b%Yx}hB<^UeoK`g?7(}#+lM*XeG?X9-+cZDPu)kX z3xLHDoaRD8e+z>GqCiFJiKpz3Cn>M`1Jw2;f-z(%fUq9SMtj9Ra?ZbiZOqkp9^wz^ z)@XNnhcD)5Ev#n&&7OCs;y`HRNQS?lPv0Jw*Y1(K)^9FyUlQZTgHzcczOR>4LXp7Z z$Otb;A;jANVQ%wTOG&#+*h_qd&_=7L&zy)=Xw?}O{yG;Xhqd-F#Xr&P?DKZ~E4_;S z7M;6bZ|5){Mr4ZLZ7Z;9>920OjU$RiiiCm%iWRwFP^vfEQ$=lM7@7w-UKKIwEKKl` zVMj&gn&C~j?G9Qi2vWC{_2(v>b#FoLDnR?t`D&5|JB5^2BIwu1VvTV(G;SeCWw_Fn z5D!5CnRcnp_8St*dLB1Ji4!&q z>#!6->|p6Q$;%-9O9QX@lGy{7+lSzRPNz=VJetW{D&pP@vv1R*Fj_|w5L+ZQa+CO@ zZC%y$p&?EQamlV>S%qq`UUyp2+9E`Qw@r^Sv39{eD7Abjx0BBHCc^s##l*_ryfTk@ zi$7>1J*Tb}zI`J?rD?!{4%La4$_;(^cb`W>1DrSxP{aDfPnaS7$o$MTJ%S{?QEoDC}m4`L>aOFL>p& z>rIpK76{Z_3om1x4+WlB%7C%ZBnozS-t~~QddmifYIFSk;y|1{E|#{wsY-<@zRu_? zlK8QX;|5>h<4sVnj>1fP?-*ytBvg&db#Q7PxR*;kLc^`G3&Zpv+@1|4+K4LG zS3o^*d&nR!99KAMZ(Mp8$bfL`g#^99?4%M`58Ng>lbErh&Gh5*$<=$Z6&PgT5H+i- zkIZfWPe^k@RH>vCDXX1PQRaGMCc^6_7z?l$U%59<&rG=K=@oVEVWh{7*KEI*MxmhE z4H+OeW+$}t>cPO9>DbP~z?6JWaB4Lt(!hc}NMzepx)cqy;DRVfL-?Rtqz9>b9CVH+A;2W5-~yw%h>tKco(+XECSky@ zV)ZMwj*p8&Us%{xCz4Ef!`fKCZN%D5{X7l~D$kdm1%ahyk6c|CVhdT1`pZ0xl#HpL zJ=TGr_e%V2YFnUK*%8Y!R^jlhUpOB$lZHtG>2Ab%D14P6uVGfl{hGYlgxS!%RjeH4z#S3N#!ICrwCje&vS|IO*N8eZ$(GN zcqxr=tSM+7ct*Qe7Y9GvF$(RqTnVS2EvixZ~suHYQk#vL&J>?BBh8&m_+<= zm>l$@1%!aZGV$&ao=67$_d4ic@H7=j%^InjZ94mt9&0|Hp}lo zfb&&t(J?4h!N6zQD?Uy(jw-7FnI(tpdhuNsCAdp!9_r0Sbwu_gkq z+(-{fN!@9Z5m$ORfpEZsitrkxHiFQNp)s7c0KJ4l-s0!Gs6BtDV7@RFW=IKOa0c`U zXhW4rakP&QPgkj>yH@^~5^j-o*%{>Y=K*MN7)>!J82&1q^FE0~f{s7P;XCk8`3@lF z;7fT=@a50WsXgzoXGDSzE(+wFY#8#n?HtU}TDozA&ee|jFjcn*W;o&}q3AVb7*ugw zH}|0vH0B}Km!Vp0C*B}fma82rz0U;x(92BT!SFm1Y4y{=7;3X5c&~(l&A!|Q{U>Q) zi+z19pts_5Va|ZAy9^hdA(8VQXv0!ofm1P{7BJXtRS|~WWbHqKLOWOmz*N;e>^$m|!}x{=_x1&uD!sJH zj3}Ty@pSeeq|Yu-p|#Jm&bov(jBV<;1x)5az^E?M=6UIrigj*FYB*;SyfRP>Rx|VJ24b-t8eQ(8!}5Gy=22b; z?DsBznh#Hf*}Sfh;3#6DJ3f5%XhH%{ELgW(Hg=``)1}^MSCv7T zOkH*tQBiKbub28&CQDb%F;s1q6z;gp#pH0}85vU_r<@UjAMv4k<#yu$5u@P}I1`mI z^hV13@BKkW5F$RP@Pe|k(wZakL!hm6ehf05ZWWqs3iM?mZ_i{JLNn)+^g5BH-2h^l z>i+4Wqv$B>3-E?@9;lFmHmY6z;&2ZiMxeaaT-U_DtmJ^BF^Q=C7mhFY+T(x$tK0qh zI;K4fzc|fsO!XFgVcgYjX_XygT2}{}xagP{T2{aMJ3jdZxk`||M>3ZruPcV*qGS^B zL9*e@E>e#x{$aG*c1Fh^=8v&6j0>H66RNgWKEp>Xecq)#E+YWy_dv|&WeY3rPB>8P z)2{wwVPCtW8#v;+ULupU&>FaviRu;C29mnd#;k(7PQqXbw$+%h5z^p~n>4@V@f*WQ z#P{VLmk=t8u3H}h)0C2z?F%R6wegJU zsVs&9CT2;knv$}7@Ln%?#_&+>?M&?Hh{EY<)@5AzFNuG6LWjC#^k8bK)5 zdr*w~#@5HHRO-dkQhj?30W6vz1+LK|!p|kb94faj=jaPE!KZ$Iv1xuxl+`Lk9T@0G zaRlIIrl&nB>{nw&P(aHf9?Y+EguP6nqnPup$%W=)BJktL8~9}$YD-Z3rjhv0Te+Oa zvuw0CDq?4Fp?r72r8q70s59&y_VVdZ2ClB~9-E!e^~jje!Ln{^&*bEu?zmh}36wC9 z!~lT{LmI~1O-M*J+NF>yJYOZDu#4*%j)1oa7L@2j%L1@f^y(k^2}YwI@XY;Fl6hwu zJ{MuVbP{5U=fPzg%o{E~Sv8i_Xihc|&3mW_*xWe4_(@`v!s5);K{a#>uCas7e_}Ae zgK96wF#?6otlUUj0$mz1%qYd`L=Pi$ey3nX52Mmq3X5fecP!mH{VL7HXC4Qw7EFfE zHc?#@oJQOg4?c0esMERUZXf&6*~y3~M$f<{Bw_@6t7o%TK@0qdUva9IvL#MR4P8fN zW?mQ0oyYgEQTe5hSCb+mN8R66n@{}aCO|*@MNi~A1QauI3|T2wmij4?3d-&jGLie* z)0yEz%gl@uPoarY^xJIiFD?y*ciI3}?bnu5aGji%sC`Hd%|B~eZ+lKq)TSj6-1h(0 z!~S(Bw|z>|fS{)#Fqpqzi*M?+2#EAwJ*e1*7h&7kDfr_Pkv)*;%>@jdB#iEb!HBX{ z3dA(PV1zJI3=>m~U#VgC041qP;K8I3*USv33Ww%+rZ`TQsE_ew>|>ocm)yy_?`{4X zg8`2Q3!_bno`iXimwIqn!(sg>e9qR@gSFXzeZ7z#aN50!3UYA3@}A{i9rsPo^^-Ft zxit%RLcOhw5(M+xq&8*#_8K=ySD?j$4AmorU+T}Xv6pI!B~({^vU>#qUHfWQlSear zDp=H_t$ueqIryGp;SNdAvOFiky=@l;Wg#);3$pN1o%dK`ovsP^9=A%%@7%&Vr{*8x z1I4fCGaTIIWal*%1|q5p_t4}Oz;=)CU#{H;{P_!y+(l026Xi|f< zzMt<*Fja4YC7b8fnrqf!wJ2auhAnJZ4&}oj_!D>Jub^W)S8}7&_HAddFR}|Olmin< zF7Vme39wq%=0TuH&zWa64|>MYJLP79Vx-W_!DcMDUo|$8AFI%a9S0395ERf>402zM zNBg^HPt(Hh{ZnWrsF4l#)()lQdQs9 z?D_YoWO!1@YSyuS+PG0p>G9XE8bbX1AP=tT$;Hi@3liMF06NRMGLx7GbL;S{HU>T7 z!qAE=P9n3brne40dtiHoF;Upw0Hn8@iu3?v6W#QLN2!rt9ViZz}vTQYF>IoD5L7L1XSa zE@MijocX{|-OZ*lrwEYRY3ETI37!Bam$mBgwRdlHFAB-+nazr3YB}e^q5v!}U}e6F z+A<@leizf-iK+}j=W>VvdShMUP^XuZAGPhKkvIT&g-=G!unpTqA@jP)P+!=9Nu_hS zS}SMG+e<~j4F@x@9J8<}je;k+t9v9{Ptc|oVk)Z$K?oEOR;Uy$|EuX{f}G~U72`7E z+Gc{G=@JJ=#}g2W=YSV=)Ex!uCic?x`XJ_R(qU#yFp=Eg7FWk&SeanzWn9ls?i6bW z^4^NWwxYUg5eA>N6;xq4B^b$@RN`1qbJ0Edem77c=Xza#)J^0eTaR!+7#!#y(uYr& z>{}5&Udx*86URNteYYwq2&;V4ZD|tlceLV2UqsT7WjowFaD1Zyu*IRuBn>uN{tIM< zM*xoOF3_u(&l_e0=*c!D`9n5;#`gT-M#(8)W@l*aPO-q<9=#>H59zLG4g~2qeLMC& zurmK7Ob}iNhJOtG2Z9(1)Q0wX=?*Nucd!;jgjTfM&meT@^#9J{kmFv~kB}k1RvcHy zSM)UuE4)%Yrv^LC*aR!C5a<;*qe6u)-)O6(=iEfLQ`C(NnI>f(bAsKHrMF>s2q8;9 z>Imjsq8Oh&qe}Fa!>$YAIVa}qra)>m&YXBL?y*Wf7K&hKZ;J)jN_sd>S48R7zZnk+=;LXBa_yf3KuXQK_w zaeHA(LhLi~7D#*cnZryNS7HkN*UqNmy4A?y;8Q6GGYb&wtD(FOG$zQV@qZ30d+h6u zFkPFl~ykP$>IXk#NB^0u^=5ZcoAmUJU6#`y# ze>~0{4{nrLL@$+Pvkjk}1pW!S_>2LB|S!iGACt%bY(A=U^-CoNG8+@R4 zA(~gfj5E25m-)Wek{}#+nptEhKb)kU0!e)$S$L$ROsr2b)l=UnuNyGR7|-gU1m-Wb z*vN*>Mb+y64zKdV#YC@QIgN>M&d=9Qd$qQKb^<`+OWPOOHOHeuH>v})nnSvp$c_|~ zNA)8%%ym!r*`qU#niEBL7pV)sppQGRcr>2 zLdxkxVeUb%oCjRK#lE1bA9|mG!jN``Vb_>B<|{vQL?v{s#LRW ztqhwtYv+ASa)64b{7`}j>3EoH(iYdW#8_>1pS;A-q~tWE$E0#rCe~m8%ECOkp>jxW zW~QbvY37bY3MKY7kB@#`39+BFTTg+y5;H2f#wl)}sEJQ(4! zrOH;T6B3TZZueC^7wL3$R{E+=M!_+cU;NF=QOUZQGud>#8aG!_i-?h11(3tpav1z{ z*gx_~b@wW2-(!yt%3Z;n?RZ4Ccp(`fKNzL3V4dXw{0^;VGNs?PwPqT4xCwf{;o^*& znm9!~H5JkY0C}Ox+$A)Khn z-QT=8biu%lOCGdk8&gNYs27cV;4Fm|=CE^OUa`MF`^S0VH|N55LoS_CRMmjexTul z;*_2~nst;b^0agg9Gf<2`$IMWQ2Y|4E(skY{GuEqr-$DqLwZTLHH0qRb`( zp@E|ePs{|mzp)79MrD7$Zb=1}j(`97+pzeL!EV>pp-GiT^6|HLyd<0u((tT(^l1w7=4gDqek;aO4W+V+&k!(rdFY&JkMZ zMep_|b#DU+50BX#<}S+s_OHW$D#f8TWI*`)pINDaLCmULtdA<&1z%{It$gtk{zLlw zI}Qu&_}T4fc)v0ApVG+mZQ6V-DtE!yybuLOhiTqZ_u$I1+T$iac4bh1)U;39muhU$5L;&tMjUy^Nk(5a#X1H6fUc8@ z+$&MOTFebu*1=<0W&OQr>+_{=#YhHt%byTKt!Jd`l__+B5y9dtJRr}s*m)IF+;6`@ zsO=1J35Mw4SgO>&fOUa%^Iiug{HIBdn?2IC#ZHmXn3#}{oV*d|(2M;L-P)XOUI0vr zd@sOou_p`Ah10$KBHWMbVT?&pk%m)95@L($h1tyZ4vEXVwL2B-RRn@#F|y*bZ-N$I zBf&QL8OE?jgZLkE)}9*K}l9^ ztQ+bc4|9mvHHi*AY%-o?-5e`In-#k&NB|H{J5U!d!`FQ;*?_`N!v_D=7G?E+^DV&r z8)Cky3B(Yh$%p_blVJ(=tsY;`F|8>b?o7=$F*6Wyfx*6)`?IlB_*{fc0r1$(@(=$A z_hZR^EDpxF7e?*#iqahi>2HN-EE3I*B)~Z z!V!=r&>@|=b7d6oWd>8re|y+c-%`A3MWMzfVXEfK2e!dE(XYQUw|<8wu4%J!A6bN9 zPkHem&AIEleMT8|C+yFlH57vE&i}#_yln;(pRB>{-B`d=69YyOzIw;Q*M5l^nzVqA zI^kpR+mZB@c#S52MyPBJCJj=M-K>zq&X?Ut$=pcmt$7^N#v3yY@FWACU&^MHqLi_Q zo_hPAJa^=#6qdm-`v4V#68aYk+p35>3xdP4d~q0V#AT7qUJH>tZN_#c7&Mnoom^pz zAmlj0=ATpltu)~TfqawK6aX1j1+BATG#`l^gzAp)?226TUS_vVNA=uA2%$8WAgsxF z;yC(>(MH5D1CM2;e);G_-tCRfyq&}X$z3FyGa&7vs#AR4l6~QPbhTQe9ue-^9KKPT z?n}WXx!_c;!3hU!dGZ4G@=p@#R!+9BD;06pO(qMb-4O@05MnEDz(U-cHFCYftOxCJ zsVGM`Ob&omCAcgZfWW=E1`Z{3uY?IAGvT8#fEXo!B=QD1s9-V)M!qiqtZE>MZ{lQ{ zL>7Q2d$hE~S?J_1NkU9Uk7U-@|GMzb9FOuz5s*`2L_Od-5e083AlPGx3)}XWbq%cL zp!ZEblkiugMVZMCj`v+xV+Xj_>-B;*0zQB1g#iOM08kF69yp~d$#R-)6#QBfP00QI ziY+)L?zg^dX{JZ)Y3IHFEW(`mgB)W?Wk2i8AG{8y&By?HPzpQ4{38Xi%9=KVHgY{7 z(^T>aG?daYjY@j=&RDsw=Mh}pS$b%n15mAp`AzXtW|k$H0$U1C!E1YI z8K15S;6slyJu0}J59E01NFH!uXPOD}7ZV);WgnH&7B$<%?kE7-Kql`-$*rkOVJ=uV zKqr4_cyn{)3&9@W_~M)WN@6)G>cBueatfB<%5SyJSpVV1Dp{8_#DOx!OV`RcY5iO3 zWcq&&NWHh;%Z$PLZGJ^)qWnWbi<&=2G{~?o5J)y|?q&+`a@?Rt%<<{vtlBxEKl zWacL>O74gCc4VRht`wyTcq9&H(8@IH?~+f)g%*{PknoTnS#Qegcb-(8h5Ll&LJcQ0 zV1_%|k){eN2{4t5vibJyL*~#(R0YmrNBGW|nI4$%YR;kTQDpLS?Kss8E|)=dQk3@X z*kn@Fm7=d50m>d4MZ)vj<_V@M$u4%L7`Vd5_W1#}Lc5`r(Z^r}^Lf&hqd`y_mtRO8 zWE{kae{r{}=!ORiu8OgIexL8e^wy$424HN73NjBHi79!tS}1@dl01~FFHLyHRxZIX zBSIQUyL$}YVuP!m?!9Hid0`?cct97&(LCSnOwJ>AT<6TOo_G37?g&T!${R~ej{4<^ z^!~2zJY>RKI8|*V6Vz*Xj-=HQvX3NAd zT0&?8-omLa8xLLV4E@go_hGyc$t~flduFzN8a$gmsm{lI65j=RK2c0v6lJ13o!va1R#RH_5AKqosx}R0$5dzd1<)<%b)*o z9y=>@XPQtbGl@uQ!t+Bq1WW8*z*NRJgPo~s47Khfn+zgeN0g_=ozBOE5CRZAbR>W= zm6}-7g$(}AjVpEvuwc^4=(>;n(~>hUVRq{F@wGp1qsc8)2Sr5y=B)}WEMBL~m3|*4 z$~E}HJEm?l?ClgT`Y*Hp^gu6TiCkrq8sxJq03bniv1hB%)!MnJhrKSioGjVy^E$W*WO##*QH ze4qujtq1MnQ?+no_gCu+SoR9pKQb)`!H#%{vI-m&8gr`WL!(WBPM0g-h-9&)(fgQ{ zp|rWq11d}oa>^x2;k*W*H6Vbk(|jRoWF+lzs42$|V>y#$0!-wwA-LfEgbO5i$NP&l z$yCFQL*oa=cl(0iv&D--*40TWX3{iaHpys(PC-lhfBoVC<=uvjKiY@pTxQaA1;eqd zcEriVgbpGSk3IQ`CReM`6%3(Ug+|3_VVzrTVQPG<6!gEhqX?qbWXwiW>H8%TatLk} z6zhAX0@uAo4I_a_eUV7jyaz*tf=?JiK^k{(*FhcKBqKQ~W(zeD?pi?2{T+wg+_6MO z{O7f&Y{Gb_&TgEbyalsDhmh%07}N;AgZ4a{!CLc2@4yCgAboWb;aZq!Wk)G0v57Ir zLc{SfFitL%XXp!vf<2l!Y=+GA{grl99DyQ@hw$`x+*Qzl2-4@zaa_&>Qn_Q78@*ZC zmvQ4_$7RBLt`7~~KR;v7%j3T-_1@N|cYf8yc+b9@R#*$DN&4ZU-?j_Ma3f}7wg{$} z$$XkVNKHd??7OIao!N-L#qLQ?mVw})3hJ5Wcx~$(Ysozn>c4z9&lqgrq>aJ?X1%@l zflh1tsNi4-sW6Mt_qK1!Zjb*B_&x zsOfh78IUj2M{fCkY}8b>#s@ysdU?Kj&U`(Lk1IP3>(WAcRe1lkWj97eF|?nf-n11F^Wg>dNLgd5z1bO{;XLu=3MQ>;FcZd5v%} zO}4hdxV-3Mp_@Ph%Ku+_4FhO~U&+b8Z`{EXb3brncbI<1divY|^ zcU+^f;~X`z7)7|;IaBb!ZBDOlghhTW&j{j{9V;~z*foq}f^MOn;5lfNQ^f{VryeaK zL8va-5IJ678+su%r(L!i$9ZdrlA$P^B~9=`VW+FjsROyIzu`@S!X{>6hkeRm5~mSj zvO_=SUh=?Q@6(Ki5VHr!{Bftc0-tKQvjLgiqKst zOpPY~+Q9ki0MxPN<4T*tgOd#MK}CyEnHQ)Oinst=r}Jb12*c2f0%0OUM2@bXC-@&i zg`tI~{I)K~9AF;Nm!UjoRI^Lj3)H$?h2Xi*bmTs=*Z7vk{Fxjg3;F-dLjH`nxOAt+ zfrNhI$kZhJttGf?TZ;0Y&Ch51+WNQ#lCVVvPkqbC%r3wT_g8~8%^#OM}<8^Z^{dB1Ys#! zL$uvDZszTQW^bbm0gbu|khzyEt3V`bN0ucdyk6>E_iCl9Wq+axj#oqq4W7I~`}1Va zirk5_2!Cvs-6V#;04j1>{mNGZJ+BfqfP>(>q=IUV3iXU>i=H&}p}XUTBR-YO)J;<) zL+?&oZ|Z^dX|TD&Do_r+=X3EruKzsTy6!686FJJYOf=PFQ7CdQSpnHI*?uQ+4_r-_ z*KfA1=mg_aB=j%}{7e3yLy+D=qFIn%lmgQoxkRXPkHzfRQy*Q85@o>yUr@}1X*Dx9 zeXx$nLuH7z>WZS-Lvdq=0GLMZ=MBRfI6SUI2_;dPvjf^0E)^Y*;Up3hnu)GLA^Uml z^v5Aak2CUb_%2z~Z%6rOR2c|hF+?w4z1?8k0Py)`=d^_{ReXQ%+h zh`qTFsze*>z&?rj!kANsbxY`Y@vI#s$16oYSFz6aO{Wf0i2OT}GGcqOdc4biDd^085xW^q z)qZ@%fPF1V0!_*rMFP)@rS(F?tL8_iwSRTcTPt}hozDl^6}((7+D<7(?KY#~LTC+M z#ylF?5l3JKwIE?LT7cN2lN`NCbsgRc^5V{(>5Hbkr>2>s&l$bf2)k{H=| zMsN38rA<6E<^5SuzVnO!X0flh=X%m;4-^N__<)BSxH!1N$JU|<`nmnMK*Vt76r#k= z!2+DQ_7u&cc7nW>%Lq>0j=h-x*a&qJ&E2I+_S;-Gc%NK2j&QZaadkQelbTIhckr(U zCG{))%8SXG^Nk)ej%6K|>z5scWwY>Sn0b(Js^$NJB>h8{!oDIttR&r-dv}mx+~?ZH zeHDTE8<+=t;zM`ngB_vTSZ)rpojc1=R`<_DD^OH@;+E7kRBX19XP$LX_wqZo|uCz-*U4BEUG z@|$_%w-;rUl9W%`giZn#!FP`N*X)@>ufMB6j@ut3wU5bOr0m?DSBkUYO+DdG2!a=P z6f)Cl;8~at#I$DSlavU@MQH%0q=q^{u*ltW%A2VAkFrYMDmI8VSowpH!g_)0S-~Oy zUQSKA2uk(5dnbf+?pQG4KxrtfdvR!J)s8LG;tE8Gv62uzcW=gjh>Wdn=wes$hgpOr zcNHpS8hW6fXS>;THuo|!&J6OFUz9e5$9d{iix@rE|VI-eQ-}vi=9%z zv2EQtA0ehSt6#OuGMhxa*;a6Oss~>g0CpwsbS#CRPl`KoP!gwjloLeO55~mYRsjzq z5f3+jgTUPFY*o)YK1XCal6om(a-)2>KCxF4hD#e>SBT~VXQ%Ti>ZbaN{I`{jLE z?*W`y;(-I5rqr{|{f4ic(CnQ*$QzsSS(%GHW0gp7A%$H4bbDZ?P5By?Mz)K?3nCmwJQiAX-ts& z#Lg|Bi^n3hm2o)f>N2@+b1HS&l1cyl3`Zo@5US5E&|Uy*0LxW z@gse1oM7(%gcEodGqf#lkjockVCX>zU*KJtH6If#O&* z_F1YRjG53<`b%otPy@>q<}Dc7ixn5L zptfCO9^X4z_1^HGPnbsuvj}ohuP(}O(;mK^m--KU;k;Wg0iNiZYJ^|T;ojc?*fTnN zvvhRHYU~d*oJk$?-I-?Zpk|$d+nl`$$ z_5KlNHMdJQyR2<;t>OOtp#g@2kI4Wz=y;7`ze8KaCzZPGOIsdY=o`?-Dg?IOr0O(= zj7l*D=?ys+E@_CLpg_TR@fofVV6-j8`($=1`i)^k$J+p-({D)06DymUb(Q6+VPGlV z3`s9lS~0w2mDCoUMo057v7n=XRyjhavqhPSm(N*1O^ZV_&*SU7M!?SqIp$uyiUHQh z;2KY;cIejThvnWxagK_0BkSxYSpW@)^5o|5dm86VfI0?$GnEd0vf<&;-0_1XN6@=$ zgJ{gZRo9!hIX4~PX1>pt23u?PGwaL*=sbY)WvFlXoP@MPa2(zMB!EH%FJq{cgGC>1oTz|PNuDRPg!+QlwHf1l*=ft z@F{(H8GTQ`0rO_mLERR;bJEkmo&pb0b&}wy&yx}YuO58lBUg0HPB%U_eM(>uyTkq$ z&VNAH2S?%r&)!aV7tQ|K!9<1!i~=f%#j|q;(jS@lHS-D#cV-Vvf0=a@A$n!OCssfn z#%5z9p`8?}eCbd#mMZzZ01Uv}(&U@Ieq+gKy)?Un_;g*D*ID1yd zjvl9gm+b+ipypFLrs6_KPcldoB&M)m+lNg0V|=@8zC&2@8(rN&@PMvIF3aKp0|6Q) zpnT(URk?SAJg$&Szobnj^gxe*$m+I@*N4yF#2WZFmEekCoVv7RA}{&EOi_4b{2WIu zyrQ@aSi@IIT}LO|Zbqe%Z+ziFH7Pbd^f1e9b&4u)CfvjV;;~F@d-c@tlO=Oyo97uI# zvQ9S*t|7EYud)r}bol%3yuLIZ+0aQQbPDqplS+}3V8(GJ*kcDL9FQoGrsk(o2-CP* zG~cMFTeumFLBl&Fa_oWD(83=-dL5XHg!CZ`tH!qO3K}eq7dY>>t%S=ogj+<$pKwmy zS&OAxlFxP>_PD>irOF)+Qr^a)%y^i1CL z?Ke?L&pqL6R2Yo+KWsjiwkxh~9yCydwaX7&Ms=EK@+fI***S%wDo)|Vm8oPnubhrc zMf0y_A$q@_I=_qNP7*R9+!burQT<|Q!R-q4mWLKKDfqzxcdQz;FPs#pFp(NT zhOB<~2l)_%AB<`Ef3``R1tH!}2K^C|iww;ZA8)LP$T?JTbmy9q$Wb8%i*l>SYXtK2 ze+(ClGq$oE(@anOoy}o%wbREh1Xo|M4(N|~#sXcO|2+HKMpDLlp{fKpLq{|GI5IxK z=9dto@0lVH|E-=|HpbqAh0EfH_rCR~a13Qs>2W3lHVvU$+fa)$s5hxhP@L>6wzwaf zXalAnLXeYVymC{H;5eM*ADZX1@D0X~l+he~4B-!^n3kBtjr!QWYK$|5GGqFNkL%Cr zbFk>FcWNAs+Tb0xUY7?P!M2->=ptFEw%J;R(PPyz^s>4&XFaz>D^SjY%69TVPwi?B zL02om#^8T!kGS8C5qXrLo6A_0VFMfnGnzT$tc6x;DZk_5& z^A7h4Ozt*^RzT}X@s?eZq$t8Y7RQIripvcBVQeqG41v}$Nb8h}Hk{OcNjYK|eabqp zuxK@{H#^Ruydwz4b*U!rDJ+^ar{t6wThhTb1L{_%wWvxCj}Fd@I4FoMcWYN36dEe6 zEtthk+$Wm>0o20fS-3isI(lpH+MusIGJ)rH6}#PHvHBnWFDm|1AJ4#b6U_iiQ;R7B zko^dv{0yiEtyF~etwUIhHe&`R-ZzR6g2&~#u*@->ZAYJY1exP5^4&`GSS=J(qwvQ~ zw&*)s!9PrKE$JGD7t=gFfZ(HU{+o4{iG+?A!E_E~WK7Pg(In;^N`NFRAXq0w?nWe8 z4L~9edC1#Bqae)Wj7Y9m%pZPtX%=HBL;sFqA9?Fe2JV|6YE9 z2mK59c?a_51Z+v?Ced%wtUzcyKKAV8s3onxs?U5P5~erk7m{qq-E&71`YNDeMUiM8W<@x7G+_zXnmlAc8p3h4lC zSBr$sy&bODDcKrLsq7{bt#SLmYQ7H z9(H)rKJz6gTZB&|=)17Mn8-B@N6HPWs7=TCv3R2J&d?8W+ri3PJf zqX$!TJDJ)A5AY~ZCub_6#2#|O(3RLR_s`vKmX9i6#iJ5W5B@s6*;V!v;T=%U?x_+J z2C0(;75U+>5o~nk@dx<<+debcO&~@+JYXEX9Gjfe8}Zh2>vZB5+1DmLm)%@htf&2( zmMK$7D!v(qQea}gW!yq6p`!y&XpdvWHvkOwVQ6XT(kIuvQu?=X*tMz2VGs*`*jW7` z1B$n>^mN18z^_cUBkS2C+S<-unS3e|O0aAli@t^aAeQ>YTj#raU?kg>G%=Q+r0R-N zkLeCrqGL5a*^Sn;{Z0jl$pVM}W~hkI$iV*J*vV?H6D-;}HI;1GiPIjV#~NH{WrNYp z_N`4D#(~k-Lnv8X80$jv&^#obXp}j$N|7C%@LA@h#AmuHRh1pR!B}JQ5U$%cUkG67 z^YQF~l-u)5m)=tMcz5sT8Q4VBy_M}-Vxjv#-W2|P6~um!TA#|$H(iGjF*FCsI~~w> zq6uSyUfuEzi|%rc(-QcWL7dcnapULJhsZtnEslsA zI}{#xVxcT!U+POJ%Hv7U=29USs%Qnmy9$}rhw}JUuqdJ#-oH-B?1UXY*{O_n0Xym? zs=o0SlEVRm3^?IvdDlt|Cm{p zya%Ahml=^(z$fZnO>kcCzl~e>6M}+nV=fbw4$iUWN<_qzO|y?hYCZ-{Ni0*hG@v=` zu=VDgSGZ%7&o|f92X(we7+}9>TBj$%qpLv*bFN3gp^m*qT^Q#N66@F%yjicXj;BNH z5nm&&bN$`3 z^3`poXlfJREw_Rx4Ga2R%MqEJH54w9y4G;i3|Xc5^DRoxzSejga=Itt=MOg2rwDD{#eZL%-M4=C&NoW7&T76|M&3oH2oGQqz)t#^(X>71Yp+m~^_# zi4`_zQ&o>%`*)_aEvfRwDD@zWYQpUW{ME7Uyvo~eX75#nwQE#1NXcLzAHOnOLvSK) z4e<%ccdGr%QEL)ml(@h`+;j1}6UmEdXRE5rFr_9WcRR+p=BSWEnMSJZ(zIJI z3v2{avN;f2k_8)@j9mWyib{;piRKFEWX=`MY|1_6#zDxnZQ)GVw`cxZZ4tZ$T@ zHA;&stcHUZ8?O&!0#!ZMGmQCTzrUS^O{ICbaa$tF0MpNeK8^ardq>oj7YO{F2I^$9S+ z;vdI5=8=F&hq9WfZ;&$MtjP#)VjCTKzZpH!hD`fTU;0NiM??0+&oS~J){-l=#;;K9 zWS7nwvD9tr*xF2Gmo%(1O8^)q|J*R;P*U*DD2d~b3_LIY6~k@Y@PCvwvV|}>)`7pL zawJ|qUa528gc*exYAU_@EqXZq%`6pUm(D%y?z$zEJ$U2&rc-83nRXBe8pOkjDWMc6 z;G~K7?OSZa!z5uR5)HTXGe@fxbyF8ig#bZ7zQ4Tyw(c*)Dhk7vJ3p;_5w)ORp1T^^ zNMt_04S3`9Sv@CPEY?`@rSnbj+OEP-wREgViB;z3Q-T#WOLH(bKo7I=ycrUls{wx? zgLty|Z=*S|RAsLS$QU_0x(lSf-^A({ex?7JfNpBXIIysi=DK z4Ch*YW=DsztI?~trP%>5eI}9Ui-Zm?25+X>_Ncbs&%6dXEQ3EhO!+Pcw>XX{WJ<9m%Zkl z8B0bYXEL1i)MfJ*D}$#iS;XDp9WEgw_Ohk0*T21DbIS1S_BS+ z(10S8adz#(k>(ZKe@+?c$sH0ffGr%4RiN%?(HgFva+VqY zyVrY-K+eTqU;fD3oiY|KcMN5KKt(g7Md85nMq8dWrGAaQ`p435YtTvAAbp0qX7jTV z#jA11R|9^dc_8=-gB+UDs#aGTTK6Y0RCz<~ChsP5lpIpx!It^85aBC{ESfWNR7wmC zcQYL$WMF4!18nX(qHWo^U{qHTFs!^p!9$o*2s~XfSYn&FNOgSI(5|4RNGHRgd>_bZ^`YY zB293Ay})U~&<@l-7uJG}n^BMx6;|#C2&G($UP5>0;5ZSl>G6=H2_U$vGX#7jg;Z$q zSm3*7ER@$qs@C?CZO@h;uP+RU!9a-==7OM2>F?@;e^Wirt=b+J$(f=={-M7t(blcN zBN}G%WHL1hSTIgDBL7|&OwC@ctm#UWdTM67Bx_?!Q0#^H7=(8yRHjZLNfQ zcst%W=Bst$HZ>(a1Y8_*O&%xZSX3!PbSb_5+91Z1)b6*o!0m;-qnv#CvRmf$poMHtZxmW9LEk?5*1%qhX=i9d&7p@!eutV zIL*2pSTiASLpL~#V6i@@Vf3H`7`)GzW?5t^NX&^dkb+C@ewo{W><{&yRbY+&eG!-9 z694m;;p6j21Z1ca=vdNamxP-m6!ubKc9QN4LjM^crNawaS(D|%AW{zA2Bi;ql6p;M zuILV#LXR!#O@#qgT5`=`nmu7_qFMp~LWXHM+h7Cwbmp z$~ilPX>?3FwdmW!s3<-xhp3REW8H?$7aiHF+8G zB;7?UiLw?5H|8(yO8nFzRG#SR{zSS`E<|A)?(A}n;3B^)av=k28PUCu31{_3Vt$NQ z$F@V}LY`Ik+vp$CPB(yajE=D_OgloP*;eOn(<+A_2$X22eG+J`yYP*WE88yq&K7h@ ztg0s7zQ)9+*SCf6j);rBOHR%-!-wH&UXM*~+Pl2Q^Jk;3<47xVTuv2)AOU%@aA4Zt z*DXqbd+r9e+t+muPK0S&>6$94qbTcSqm>4N-1!~RaL1{QPj}@-s9xWLhzQ(t9>@&K z;eXVFL$Ot%d8Y3?Y{53@x)V;hYX-5Tg`vo=X5J#k)80F*LzctlsU-GPm6=-3JhUL% zdq=)Z*l1!zvt5MQfeU0|^iACa~Dz);vG^~e#D_!J4job!3WVt6Nu~~?_ z<$5g3-Hn>X{be^webDTF81Gf8x+K0T<7JtULYX{ zR0>vDz_&roUg|J@SKX(|jQR6ttn~Rd(X4m)+j6WoB9vkT)>j9ZM zrBU51f#mzNQWB7)y@(;-)cPDi=CaqTPk68kv?tX>@FZ;;3V8=;Hg|E@K<8HYVos9b zZ!xxX8ye2FG+5`k1>cS`*b}zaUq|%Fg=(&=Rpds*^Xlceyky>-q1TUFPaH} z5Ey-Zy=N{s+M#vLkTL@O{r(dgPf=#6*L@oCk`M?srSG^9~+1Uyr^DXc@3ERkMybKlBUp~}!Ou@kq|{E{WSFcGJ``+d|6 zPn^tsNougg(cy-w=Wv!fW7_lRy1Zoh?%l1MU{iQ7qt{&STEg9Fig?%f4uEqYtwY5} z%jGp-2jtQJS_I^Nr{c(<^U;Ne`M72b2EQNr%}muKWafWyTSB{UDnWxtp#Q4r^Q%uZA)$w+gLe04*#y6vEj)f=uX+WLN z-gHr1zPCZ|c!NRCq-+#EWb2}h;(1GGQ^NGNiWc@K>3*eU@co`zq6-!-T9{&P-Bqv;G$|lp5;69SMb2cvN9^cBon%wkD z^vdhjsq#*#yIj` z3vF919z_LE^k0SQ8%xZXgL)S-cz$!A3_tvF1bfc3g$GL+bQUV(UTdHs8uLzBaK|;J zkhcYWS>g9N1>l%9Bk_e)=i;-X%kGooXpgErf=K8cOTC%Q?gywrs<=Az@5Q`orU(55 zp=%nt9+YQIGf4i-y8B=d^rTKQ9> z`YiriF_vIt{EW`hTyB#}y=1=-c@{qcJ{u!fI-4ltr`BCd2Ym)Q76@3an&kyY)CUe8 z$`W4$XHh>L9TJ6G(?}J?yry1k5eI$3-`X3VS-^eI@`t6|$aW2?sbazWPk0jGTPe{g zmQVBi$++xH@$dOJ?-2aF2+s5AY4i`Zkx|`U!;?@BH{j8Hz&x>VA+%RGq5|o`0vy6( zSY2#iqCpf8=H(@N#6>EwQM&SM{M&)Js+AbMagld>nlbw`pg;o)H5fAc$80dw^vRbU z7PeL@QcgYK%fSihZXeowo$=6!^(EdwwcYpTZmZQW!SRghb-Tir{$#jksi}KF{75Dhk2A>{%HYlWTt5?&AH^#Fc7q;z*ISm*f|cl)=1-8wJ7lZ6td)U+DhDJyL0x1x9G+1(p{ zf+ekna^L|kU>(g>>OcCpJ{D`2ZufhOwFZQb@Ydl{OrEw4`E<5}GmNm7_XNPO zOUMPW+E)!hN7!WeSn&FKw?d*+rXsouJxnBZk~yJ9g?#@>Id{i|vMR@U8OMRq-zm68ipqokx&QbxQa4l@YWKh4Z|?ih)n{WFN< zPW$4uQ|AjAc1ZM!dKKI)x2;3?NNjg|Gbvz-ll{Vy1@;KGgh6wIfOC*^h(EZ)HSsAJ zgTFyMi%$-!j03+tF@DQy4uP@YN6-!S9PYoJTEMmD26M&kd}0LO*4h&(6Xsk(q8xhx zHa8J&wRLjh>Q-d=a;}gEn!aFVFpDiETpKvxGh>ThECB>j+|8`6`;-8LaNFuwshoE# zi{$BRFR*!zJ_A_y8-E@V5$WuTqDQ_l6OFx%6PzBmENxn2P|t9p78js>MZ&E4C2bg3 zqAi>DVwIiO-hqb^)yo;Sq14Zs;vvDx7<#ozCQ+71fM$$DXm6#cX|Euv(3uRJgDcj$ zB=0h2Ao2>Vq~YL9*LBTmb^h#FdhTx(7rae2-u8;v9Rxg7%A+cg6f$d@#6vWp!+5{+ zZK)vHUQip~37h8zj;&*}k+%h$n2tqrFRE7)Hkrt^Mm&-p{J) zuVq3*u>BO8NpGk7ruDRoLI(snyzd<7N(}A|;7R~CHTlqHWPl<8<5i5kA*$JJEn)p* zhXHy6PpVkD*VXef2O^t-eN~D`V7542C`hSMJX==tbN3;lm5aBq*s;(zNn7c`fv9j4{l6*DYU;-VKs%VQo~zfpI7O*wd~4Squeq1<0PQ!z5} z$wF#X^A~fbpevk$3AG(OH_ey|msTQ&*-@1li>r__lsfQ+uJvxRiLTfBYq z_zh&=tOD%|9w};+eAZa$w}x|N6{aWlDt%_<&d`#VtFKPF8(zV>iFwI~(nfxr@NcPY>S8^2mV$XF!xv1&Pv%f@9?%mBi&R8fh}yhnDfZ( zDmr?ci7WU%P&;_iaA=9Z+Oe%+sT#hO-^t0Zm)g%oHx z4&(6O=_OU1tA1nJ3n!Oh*(5WnsmQZw`~rYHqMkgHr*_|a?f%;c4n4dMc&s+}aksxl ztqukQrYn`y@>igvquXJVVuSJKYoj-1&EfN-0cJWhUsrUm z!1A&}E=<8&Ov*d)rir_~9CRgq(H?H;$Ts6L4+&m?3;gdJjbfL7Ks>qjSCQ$A7XFCn zz6oxo%y2O#Oi&;mw$;W*X(k=`U=@!QMNrcI_3H3AE%@GkII_n(wbAC ztWN6YB%Xw{2~$J|=Je_^O*aLfUZKadFH}A!-ZqquQD^DP|G2Gu)T6Ls<8af-1v`uL zTat_?xRyud-(J=ta2)bGEr!SXL_J*Wqj&vd>J4GK{L6akKxw29shl6(LoK8@noDAQ z&!t+E=l-*%T{ZkKF^)jRy+r%~cS+L00nSm3+yjff%q*-O%bX#5$^Mb@>>vT6oDo9Z zkHBA^zIrdM0<#}druM(iKukP=dAWObK&Hf)21`bZB}?D5?6i}xj4X&d)!#ByDG*B- zNqR@RAXooMFkGTf7Obn;uh-TGkGPN}jbk_a^*gOnvV`fpM_1B_4t_!{{(-xwGFh9T z(-tU3ofyz2j$Y?+X-B==X7CgZ+bg5+tOy)Hc=%gwr2c2XB7npXUFrPtbddWB5< z{*^~}p^PdJCX)cpHxeC^#Q=EDD^oA5JUU=q$oM>PZov;}$Xb*#0^d z7v?PE?J2)({*u>W{Sts)iMk+#J z1C!RR*c;)Y-+^aM^$ZTg2t!Aq-ub(#t#4J(dCy2yK$r+Q#@n&A*zgd*3CT#XCO#mz z0Y-PvwX(J1nt>hL&}U5M((X42<`SouQ^1Od)2$O$*&1 z?F9o>Gif72%n7)FkM<5~JKlz;;j|1V!T`_HxA1YtNS)x!(4yzKZLf7bhjH_9U4Q@k>1tp!$*u_(##08 zP^Q{wFtre}x3hzAl4aEhY=**$jOa=dQN5rhW&ziyFm(`>KCx5$s!PGb zRaCeFLT0wowGv<(ZF2ePnI?n7<`%*;H$1Ai>(D9p8cqq{)pL@Od^5+#R{m<}N&*_; z8U_*y2>aMqni0_6dq-<^-MY_oFkxMD8V z^-M(;>&`NJZ6%z^@`=K1)d3ukKf}Dw3&*GfnV}5``>fzndxR*^i+qS2yIc>cEJh#u zT2s#_bc{bi?`EfgwC+Ivl8m*tV`70rG?Ey3!(WXh;CPsj-ycqPKm*9HjX7L@GX{WH z4$7eag#c>ZT=YHY_`F;|f=}t(5&;EN+woI;7A%bA*Hr&Mh5Crl2xgQP< zP=XT1CV%yZ+MEEM=0=3)Mm9etr~it5fGQ7Ud}jj_mCO*b@K0Wx8pgn3#x0T`r2EfL z-$27oBKpX*!Nx31)#l^{=s1wAt{%fc3)QrI1JBlF%|TE3un8VqCuxK7>$1V!9@3^s z$6ZmP%C2kNsO1j%M3kqLE)cDer_+4NwbU52uih>WY8g?OrUO`&_`4>P>eA(&Nfzpsoo?-on@+xgqLqGD_3eM*E&78T{ zvYg4jV4kryqkE~tkjhgca5*cY+i1|tGBsuU-rP&c+ki#L{8G6vxw~RG zsjyb}s4Fz7NTt%gc5Z5XbTyGV}Hg}oT)H&{nAzEJpX@%85O;z&Tqz%PVCWZMcfz`^z;JYp%- zTtQ~27nh28;}nIS=0?IWb^72HAPdOZ?PE-3nOePvi3Oz`z;5*Z?rgQWI;ilJrS~ak zE6TsL)m8D3?fZ6XivJn%VVl)2!jgj)kWFgl#@N9R+W@s3a@+^5ifNDFJd(cJS2OT?Noh$-MV+COee(`Ez{UsZ&VbE0M- zL&Q4+WQVoaiHc_SCOgM>NhN4X*87`O@M;!x#{R@vgjKBcfMNUexAbz6rlW2(a=xHd zw4%fjbNuem-TRY*Vk-Cd)GI+W+jBiJ$0?8z<^Jm1qLu=Yd#E|nWauHf=_j>G?Ur$% zN5ttZN027?Na%0)FkBaaiO|z_cE4qEQs@f1jZ0$#z!|K>FUo1?+GNT~`m{xn4uZ|z z@T-icG;Z?xSw|pVjsu%b%8>IxL{GN^Q)BxNlFaT8Cl`6U1cjHc?^UNc(dKV^Z7Dsf zZs^qcG}G?Tf2HucQ<--T*bssS_Qg1>H@0w8XqnTb%_CpDL*Lb#oacSe9bS-54S-NZWw~s*Bt5gQHA5-AnzhlsD3uVLv9Q#G>i6NNVas2 zqb#o>)QGOvo=oF@^O~7xpP|qm6Yh-0@djuj!fW2W?^Q(>qZv{_8iXxH3stNwaWAh{ zvZ#B*Bp&#wzND;x*!N)P_jM}7dTk^#pMK4vA$ipmL%CaNJoSc2t&9Nk4A=jy)L_-p zGO81i+dr8t2xc}~1+o)=(kCMARQ#|4g_D~?cxr>BDE-U*$C7N_B2!RV>aZ!`&u%Fa zvSNDqaRU8ePT51>|5TdG6uu9vl>!pdX@eXx;*=!CGAq;Zzfq8=aH1>^-AO~-!}Q7Q zcuE6e%VS&#x(#ajNNF1MO58g2)!5pzoZllw7jPQSd~9<#e^5u<2zUTpJh&zDVay4fF$-h-)uTQQWX1nK;pATO*v99h=4-CaX69TFqJWMe=5Y zhzvtmRoOLqd|B9t`2oX{%oWa?-#3$fpu!Yso~e<(rjE-tn#U8EHp{~RYzG*w(QMm*zEU^rdvGicKY(qUw*~6x7KGyA_`!%u zjvwL)+Vn~U*cuGiXCOtC=t^vN(ll^S=Z3*DL;(U{AH3yL*SUr)rSVT8wnBI zRg;Ru>gZSfW(l1koltFU2ApRNd=~9`QV6A|oh7Clrb&0@$z%hR>clAL>m;n0OJQ26 zwBJP{hg$C7FGso83F`A@Ekp#jIdnQh4HALN-%@Gz%RfP+ZVNVX=%`v_n>S)#?=Lsm z78<=-acD4H>4AX`{`Cpz#lgMpBw_V4Z3XhGO3( z$-6h!#1^`?!|F!n8ekKBl2IK6q~b&X%Qo7iw28KB5KI?)VbdulnX}8l|4Kz`p_?thS8D5%@7RU=3S9|ag6wEEADZZw} z<-9}o&2azK+r3jR$p}qPqN9X4rot2j8M(Jlm62sZl5qoRjoJSZ({D-@dF8u|tZ}mT z*SMPha=3vgSksr4n?QHH0I(7(&Yin|gmQ0%wT4qfjVAU)yZ%9rQ}S(AV#EsDyRoWC z{UGDN?okvNn89)Cl{EjL%NMDu3?zFcuQs2wo%7mQ0Xf*V1FKp(teg#VNDk?WuV>aa z+-97v&c-|d0isFd6GL*gVKAGu|GB;Vi6w&--U3f{?TR|Ren`o@0!cj=PWVjw0jSvE zh%C9m5YUl^R)d0Mor!3w&hU3TWy%?*poXuqb<=CaHdU8#OB%?cO+PJ%BGcXf7#ga_ z%&^yyH_emfxfJdR(k}OZB53x*fzX&cv@|GDD4?7NAX?Zb{yo)(iT7eC&nPz_JRL+z zRt3bwYc@AOs&~+(??`rk;h_h3Ez@%Vr%LVByP-W3C5YGg+kaximJGSNgi8mVILkG| zffR+cKrp#}&}`-clUz7(HhbPR=ia!TpR2|0SQHUVkNT?91rtjPPO1U+oyqX>dKi9A zNXa<5ZmmDrQfK(QZ2H#Y-r6aYm-@Va=#kz$SwfJlBcnHH zhivB_703m~u$PxVR0}VgCY^JLe3~jL1y1Z4)bD-2EcDu;sC|h|T+SH9etr{z{7*g7 z)gQ7GHx#-owI_#>On!eWSF3>O?Wr_?8R3iyY>J7k&9MS|EJgrEU$A~{yWH}Ys|kPH0u4UHHp!Q<&l(S!-qM&&b?)p# zvSmUGeG`+?xk+zY`nP-DNZ|m4EbJGj;&xYUy+9FiT!u_2zlIohpT=yxFb7b>Vtke% z_?#7}N=e~8cPecg=1C4Y(xWHe)$`+#a^b+uuh_R5t7LMKut!$)7jQrP^%d}T%R&UQ za-@Xa3jCxa?lSJbpND?1=+@HcY4z;o)lUa8W0y!R`PP=vk=leb7MTJVN>;o*(2j~0 zrhP`^-V%qUr_9>D4&FCZ$4i3hz^wSw@(VWErLLT5E=Ll6a>}w3-FrR2ZA)?{0t4{S zgLgC$`y+UG?Ycr7w+-aJ@}Mfg8YrGUs`2}7v9`rzjNQ-X66<)ujKmcxJ<%3%J5$I< z=P*rS*LLbAcr)&!@e3GjE^>SOr*=k_E>3vbTXQ0<+i(m=XXW>fLjdhY#U9)YAE0eF zIDB`Nt{9wBMLVP47-!xhT$=;V(=)l|GS`i}j@a66qj}*yEfN$1$wZ8PX`Kl4;LzFO zlJ2oa3DK1=xKuW}h4$Kh9=J>%(n^sBTp}Vd{lqJPv7!H_6{!ue%OX|oo5TF{h_0|1%%2+8@IDhW zPK_=v${PiDj}(6gzSF2MG|4{>6!@8-pdSGBBgzFmWHdQP#TJ#1VGxSi?p4)Fe13Ck z2p%6=9Rv~$j3kuFs^&I?;ja~@s$wyr4^&V$nIt1uE!A*8sU$id^#zWhg9n+)@rAOe z1XSgct{e@_21R@PWPtKLx3Wv*4`%s=8H`l6F?{1TW67tn4S5AIJ;bNj3L^OD2WG4!Kn(EKhD2!Mu zFbB{{5jZ6PH&JUD|C`UTO0R8j@Z}UZYdwdfZEER*`9T>Qr}*P}ZuCFWnIJLe^c066 zKS@JScGs^#{s{EOc|q3g8H=3k@9^Z!QGS%s+1dXw6Bo1jh={Yz5(1gz{0GBAnwZff zZwMhu21td6%U*(RMj(R_2ia8KTLI%ufluYE>@>i`W9O1hu6Jv{J zD@^miC>u`hZJe9as+jK|?jNl;U(NEWhrJ-XX7Y#aHE{Vfpxi#HJB@%Hiw(Wk=lqEi zo0Q!ck6G@qG&0%gC4UQM3=V*Iz3$EzA{HJ(*i7k8g>s=H@1SpJLQ+If=K>anUB2I= z)GCHq>k@uZDO&ED%nBqyf%D@``6M<|!fMX0z`jHf;#-=LA3s$%LgwhhJbv62* zlJe5|i_0p-;y>^)UX!ihje<(xSL^HV1?l+1Z?YRPGEg z*7)6ML=xm6mU`yvZ?D-4fZ$cnQTGk?=u)<*3fvBUvA&zive%337-r9)({9p8Q;iqUKs?&%a%fh<)#}MEb(? zzP?X?GKVwnv6JmGUiE4%-b7bsq6`_CO2AGxPWr)C9cFHYDIzbv7M>e1Wt3PCMpBnl z%u?-HpvEI=E(muikKoW^+Hm&msh!EM!^;V2BN3Xhc(T`hDdpq3f|4^q)kt61Q(uAb z$gGYJyT9)1M9{4v+{1iWM}=0X+Lo~}TQ3?|l_s~9qw%esF<1f4h6V0pYiaJD;y0l{ zS!krYpL$!bh!<(7HEs1;Fa+;rSCj~?eV5eaNl?lDVSBj21w0g-_a)O(S@je1=7_pG zh`C@ovXx<_cx2Bh{>#RA1!LO=VJ9@A3N7_nAr*WP07a4z;w3D5&CLwbSmX*ajR7i1 zvqiM789ue5LD{}g?LKp@W$>i9-H@o=_y2))g3)X~4n>izlc^cW;FY&Psh9@t#t02* z%d5&A&O=CWO;6=2xak_!qVWDr#3OObUY%hUH@>Fh~mYzqDW{0<7ul){P1vHE5_9Ofo$Ajm?rBa+z1~7KrymCu;GMxeAfwTD2Olf<; zKzbQ$l&RgeOOe?P=+RV)s#G;l{zg{g)lK zIF*)FZi^)?5x!h_ZtrbHWm~F0ey37*Q8bQIECN=POvv!4HL=h_%2%K_Um(70 zmuYO$WHT&63E8EFE_@T01q}G>m$}7T(@PAZhgi#1uSc@4xGh2U*ua%w1RmmByJ-T? zbFhCT=rX=%o25#AfLNeMpgAUS>W_kib*wr;!DQYd?zuIu%0t0v{OZJvfw2b zxE0%-UO)nz<}Xv~^g#U6rn`@2Ws)(X-ph_Gga8{M@#YN21St`$X-$%QEVz;pw&O38 z0^3(z5u0VBb*4(GR)D;j2pVojdLLKP*YLFhEt;@X1$w}gZ5!DH zWgns}6MycBxur)u_`;ctd!rD6K?t<*wJiEVm|QJ8FEH!T`p9=R9Pna^r^(1nz= zgmS9s40xvw_EXn#?di0eXimfojQ3)Ho}pnOK4)Et>y=ssesQi|kv1c7Ft}d-^Ld^m zg6=thtj*72L+y&CI=Xk!pY<`hOF@G0PEC!QVP~loSwSu<1LouiA!+cd;6R9uX{27$ zgevI+X+~^ahORIU&^ILK`LC@06WW&3hIg7JTds`rl*+~!?qz~s zyZ*R7mo0H4IO!l*GfaO36Lm;O({-4e7voapTI~2)c;o&I{h?8Bl-5i^MNQAJVx3IU z`cT!9_X$FUVhl<#pm7I)6xaGek1IbwW%Hbz?~CTo3`p`Lg&J2GU!av=rzRo?G(qKq z?0Hc2#0^yLdwyOeC=OaqZ5txlK-b8?K$FtqOqpF>-qhDY+~Hmz-g@ z&!5lj@FO%NY4DrnK}#4(I(Ab${zp~%=DRAPtI*Ss-@JgMy3B6wQ7QJbmeuq61YOih z_f#f;;Do7O6c@5&rkeN_CBTi=a=P3krkS?4?^1H?wwD`nS_V*#16CBK_@83= zHASp?XxbB{YBR&DX#03@YFCuj?dl#JXj3`EY6byqJS_+0k!)yD-~xyu=UHwl5|yq3 zUe)PI2vqFdKacAh>M5Bdq00gGyvw3>8Z~8Yyh-?=l?_L zT5}oGI|O{O=y4HRMp|yKn8U%-Sc~ZTUP~s(x`I=T4BF-Vt|Qn))LWf0A5>Ws)*Z=Cvr;F{j6ee!r13*Jjw)RE*eC|0h7(~4_FU*)gMJ>J_22?XV zhwy{YE>uWK+&FFz%Er6axzCQRFvqBn0D-ZLsXn*s`CyK8dG!17Yi2@!2o>_!APVB6 zL1ldeX$fB%wv7Qf0Xd=61a!2Y+-FSyp!qI@JPA4;x|h!Cf47YpAWQ*`)z9G}4vdUhC44P6&JH zT(Bl?3C`oMdM2%?{zSLC<&i=hx+klEW=Zc>Od-rV z0?>+2%gHIrlI*3hwmM40)SOAs?Nf4!czm8rjO}{W--p{F+HavI`8s+n&EZDcy`>tF zzdL7@Km#=-yG&}7HK+ajTOPtb-`(r*J+w;wZA!kEXSGh?ai45rt!(sIUVCxZD|Ir0 z{Wmu~i%=jbofGM_%YiuG6El)GUm>dk4J40@kZ8u+dxNgiN?QCfeXrkMJ+%@HSlL}T z1)Wo7Yw~Q;4C9U(j5sm-J(ppW5^ee}k%X%fH#o>_g2ntV-jk#H46oP?*xsZ=dp|ou zX7}@LSMC90$_)lWi%|wRS%U-hCfgPvgWHQM;{GZaNnz_Id5E4=bZc`;*O*ewTq~Ut zgRx79HO;ZQZCcGMYG9@rR5&;V=e02+qH&N1xf6Ln=VS#+84SD@iCC;qsnSn-iExR2 zXDsI)#YD%*HevAj;zowsmo;w!GD&mgq`H9PE)J{M+IUM__3pEJMAgzti(Lu^VV94c`4%owTOguv+>)iLDBx0@(zjSB(~R(l7CA2|x_5Z=Tji7f^54N+5=>mWQrjcLiuv_p!Ma8Y(mo?J421Oo zJ!UmcOQxC)zahJj8Ee#u{hoI_IULCHHI7qpB3>T>TbwLa(|DvJs2ev^^P^WqJPY4B%MQw1~ocUXh+teSJ`y z$TYT;2rUwVphq1}T>V@eK1(d{HuLub*2&g7_nP3jnWTNd^8_5Nkm1BI zUul=YyxFoD{ajr_D@~Ay$8camD#(v92Tdvr0_jCx%TlOG(Tpj}XL|ybp22OfoimUY z|24VjjG&XPkBv8HwVIP)9snK9EVmfV>~^g&ytBxVY;>4L!GI(!Y&lX?r^YkFza(~ma@S-?2eW% z`$H&0yr#-9gWangRe9=+i=8k`%9 zOt$MsT#30i4V6-t@QY1@90~-?*X1}HV;AAq1vKlpicE;61ykDEO1LI<@>KA1;M#vF zTY+!EoL)SI>yWs=aeLWFEf30tkU0AVVT&{N#ZA5-U!yrURGKdL)c=Q++&k0am=g%2 z$wM;YROM~xwC$dS4AFb$sZ=BVE9A?$9TC>|{ZRw2Wx~4kNe0cI+tj4jK|v5MqOXEq zbI3q}e~LVrZ9fBA0HZudUlHo1yaJ7xNO-`K^y}z&;3Wu=SSZK%;4*`*T0A53y`_DYKv?wXs zy@+d3OkEPQ5?1MDK0vM8rjlr=Xcja5^7tamkW_GH;6n9Sg8m`_42uyXT1TakLDcHb zp+n%IJagXkuT*9Lp}L~NhhE;l9@rRFzf1V6zT5g=uD`d5d8$fI79;mW4JVcJrmtU% zd_965zxwU;tEl5g?$`|xbC){_TPnJE%O8$5qZofzUePk8pOx+V_|8OcMYcednqWJu zbM`#5l0|BuOK;X%PHD;#eFxE8Dxhe&s0Dd4H-7!-W0myA9RI; zl-x1(P~*ZSeuA_p*-2O!UyCHf`SIa=q{NR+MBvrfdclH%p6c`*xL3{q-f)ZRp zGjdF0ApR$x7esY%A8-wgm;GW^HgfQT0+T|~7dV0`+ptNpy8NriTv|^iiL;vSHRa?- zr;=H$Fn&BR&XEQyJoXKOT7K5h4gtwaAWIoBH_+mqdkQU>AZf| zM`EIwu(?vKBl0%Lmqqme=#d?m$qwL7YQJZ%1;Spy{fz4s>fXjP5#XKrz}xNf3gxPP z1ohZw$6$Dx6;@(`Ju5(ccW2}clNlp#sxGc5apSd}YE*!?5gVzs;xJlm(f~nY5Fx=h zV$cQo2JU^G*bE*qa_5JS3{46SuKT1SJziG6CSw-uvodf^7(x+e1=E6W^ygpkf?Jh! zRrKl2RSeg+|Cb{UCbJnwxmzcZ_QWTEHEe*;^_Z&jAsDS8m2yEfKc~S;3$wEGbe2wk za;7D{Z-NJhZQbfniU3^9RlCSQ;*Dx5qGw=(629I1!oWjk4< zMPS%ndVdzscn@9&){<(Z16TY%eV%dWVjXOd$Dw?ETpr47fc$6UtW|Nw#Vg+;Yn?Bp zP{IhP1+9dm$(cPgo%XTu!vM5@gI+&4`9udi3Oly12VhmV2$rgJes_&RWgpOQE7h== z8ysgpg|Zg!`&~sUP3rJW+NdHXKK2+>E~ory8`@Hui$5MBC!LUD>PyI>wAsYbS9~I{ z9}xyH##QH29hZ0!o0!D!Ww@PQPDe28=WS{D&x!7?nS(B>jGiBBz zE%0?5fM5uQke>QUd*emJb);b>eyhFA8$H!YkS;&(8weKEnYQ7->3)$pb&OUjMDEOcn2% z(fx?4YNTV)EMhWkXc3uafG!)EzO!75r$dqxo?fO-xUu+^>1Ontb5qb{dW&i0b&~m< z+ZFMdl)Q`zfrTInLtdUnTwyU|;bI-wATFJ?D-{7PQV3`da{G$2SehA<77FNOkLiqP zrr>u9k^mGDkc1F|8DgpOmxM2Je(3bCh(oosxk+cbl}s^_yiQ=EN?fU=oFt{DEYa;+ z9rcP#R%0n~cJUL;y;aI$o@v*>bfQ=(O>g@Wat!1b+PoVYMjcO#zdosC8SntxAT>{r zU`vjO<$j#MZu5joeQSHkw77~`Y^%Z&^FzwNy1r+r?WUOF8b%rzjUCOjzGOhBbE)b) zFo)yMs5F`g{Z%Em)KS%4kcw(4;#uWn0;tmqTVtweY|EwxxIm5{+4F=_zUF?w&WT3v{Yo#nzgh2G|)7EWRiup zEhL{TT>fW$;r+r$thQNt3J{$Uq@;)-A#B)Vy0DD_K;f_iKm`u>DlTH0d!DI@p$ia& z7&I^FYhzMvpA^y5z0m$!<3#bw?GcM$VA7?2x5y9Q3le=&_M0N-^E%EHDnZ9n+7t&< z#Rzw}fSKZoMVLa+%7mMkKvO~TORs5WB069V3m8p8v6#`&qYcD2qKmUH+6sH(5M~a} zIDvBG`VM8Yvknry7SrHsFYyHu zQghrNfA(Tv%f_yEkS1;kz?a7k@Vu|`L1ZPA^T;2+t4vPaNT=dmkFn~-K7@}!k|&u> z-tMAIdB99?rIFm9EP_56pl&Q8Xx;g^S-`!M!Gev+Zpx4E0znJ=pCFx0{gRXpLV+xB zOe|1Grr3Tf_}qOsrr`vGG?{j7+gT4WvJT%y8=O1Ymd>l@x6DRMVBp;m$=y@9ol2VX z*XMlubhUh0m2eH>K!aEVCIw{u8+Z{4fh!@lC5hY=Peq6@G&9vT_u9QE;m$BGb|Z7# z#9Itw2GX4FCJHO7lWt-7u1xU7pCMXMN~qkHWe!XRunf;yX;s z(GUj&-8Y$;&vwOO!ZvAB14@H%+un9?hU%xso&y|{cdIq_LMepnL(tS2=b%%vi*5JW z>d2maQ8lJu_*g)-cF})grl#R?r=D4`K+{SwXkNAXa(5jTP%F?BuzfV|I2<&lU0AKJ z*xL+ZC_07}7TDt}w?QRgcM!V;_K^GqC};)f@LLydSV7uQDch;m4IlJS^b?u3`@05F zwXPraZQpapuwKB2v1z_lC?|l%CJjT-PZ6uVNEumGQ1({n#Wrz}lWf*B@FOk@tW={# zWj4n}#K>;8$_+yf(?cE+wQpL-pD9+ z(aH~w-`{UA2m2_WF#1Tuf9(}23OcKFsk>c@L(!IwAFPSv8|A+hSc92g`2)joVKB%N z7P35j+^6b%=VI_??P~YLu=y;xz01XX#f+9m1x8$` zbnsMa(DNKgvn6M(j~LiAaAcra(s^9a3j>>b357J*Sy8{jpt+2Ea8>*E}1!u&gWlJuASO)EYV=#9$asbZcKE&VWx3n^MyAPuLB8Pb$CUCn37tN z;k+w=ki_5zM7W=GrH1(C24Sb}ZAWXKY_>vCZMScmLDaSry>Zo%3e|SYz@>eoHYgw) z<(Y7Jy`FOO#A%n^-%h&$A<(j;VP8|X;7XdOz4Ez8h7ilmK>MXq;^d^RoL1N~E};vZ zJH2n%&@;HR;@9&W%CLDfoN(6EEJAmdhhDbeFPXd;BSany-w}zcfX2nvH}b%_{XecY zdZ-KPGXPH?M@HJ*KM40+&?}Mk;i$)QWQ3Vxp$nZo9`EzS# z0yh+FF=IcbAA$~Gkh^qib$4%6eYYsvpsqjAX~sQv2n<3MUwvs)BGRz$F1w!&h9DiC zX^M;S2&G$20cCm@kEb!)#ZOUcjInAdc6aqED)o*+huAh;tt?k+BZDP~@$TU8?+*9x zNk|zJo4CSEcEy}RsBv3juYLa4p0jNr(V}xJ&|M?00!uc@Ts&_IHz~Jf*qim8Wi{`Jk8i5)?s;51418 z)Kl;^h73HQ$^Gd*Snfk8Ie~eeXDgc> zg?=XhqO1DhI-Y)%a|F|aQ$tMuJ^U*&R5D$o59AK}93dUEqq>iXJ|)2qh1+6PCEWV2 za~<(^{U<7bH-3LyrT44x9PkPbmuo>F%Lxf&5X?O+7#unaPU#BVixUBGqC&L12t&oF zB1PEo_C;MnUwaZ4Qe*ylc?mRf=e|xlVS3hB9)uF%>io~ql2{{-wQW@0|At_&GEa2# z7RID*U_(U5mY-&Js4lXMpIfKQ(D}eU08M-*0v1%ev8K}Ilh@Y?;;5qltD6=pLLv?< zW!c4Zd|3R@)Z}Z$)-|QLhZ+kAA*Xr~yv9y+2Wm+{%cz>aoeVyD8?=29KWei|gD%m@ zLDc>Rzj-eQPiP6p_jtJiQ-=!%kxwGv2k1f@P7fn4jI37rSUP_+WumZmW{lwOv4h23 zxTs5eU}q+*w-uJAq}rgpRBwhZC7`FUi8)@aOl$%H9t@_0^2S9W>EMGH24x7h8+lW@ zB0nsk(xZqk@+|$*k#XEF;1=d0Nr&g@H1!?Q~i5lEe=HNs;=|Lulfm#kG2r5tU#GHn0#jJmX;tZolF;CWA z1PgyU219(h;=x=QLgI^1#-cdx#v8G9<$My9a(UE8|4SbxBuZUn-mjmz3OcJqH5+lp z9yWeCBfxqSKd0(}kAqOwUcmRZe5Z+w24R?e`~FFlbhgY?FP6<^Wc*$#!MirhADxq= zvzBW8E+N^XbN5FeJVBqF%}8FzN;!mcA{2sY3J#8>KKttQZx=_iS>3VO9{PZW!xinZ65G~GG~f;+)Qo!n1IxCmJB>)j zw|9_W`v1_QT&h2#Qx;z=m!;umUR&Pd-VOj=VcN}znNFe~h<3l?@L0Wd{TzFhO8i1yHNAF!IW={xTQ}K%QKE< zl6uOVKEG~`Pu|(Xw-9M}5E=mrd{{2but6;T1F$jdORb-SHgU_WB!f-EE^x90kN0qE zsRaj^^l05C!)&;AKZ5n9m>q+&cckkxD)Rj8vLQ0;7eF)zqCWC7$Aw=KFhlgbhVUDO zc2|n6v|>O`xYTZc;|PQ~-#%>Yf!f}nfh_GshIGEB(OSTGL*60M&aD-ae7&cfnY0h} z0)YT`!%RsBC(<99fW6N+V}fz1Q+VJUuP~@N!2n^P0RI_=V=q~!#Q}t8 zTt=fl?nMmYr(lS7W#@kiGbHY0m*($97!Ak4DC>Bq5araraRQ>G#>dJT-{1~-wQ3U% z^~hEYXbUYL#BnE|`{Jly|2T|r5>wh6_1~UKh;jQi^LL!|ob*p@mR&g&?hcT~ec(FC zbk)3B{E;*nYAzwv7eX3yQX5k}h zY^_W=W{M8EpFC8b5;X%YS~Yo$o-LjYq>1}Z=j>nDOuSfU7?u)}73ommwp_IWvN}^# zP9xVwgoDPld+2sZ6uCh6cOV=c2{}`1dx*vtcH8EaW9aehOF<+G!oe4gV-x>4%XkFY z=jT^)yms(8WjgL`}Uug6#mx zB!oG)*2ISEE{D(2BWtnm^=~1QE-Kp`f92(aR_i2e^;ZoI7^cySsHEfPy%`|3mjBxO z;x8(3R5*#*db!4iGRmWnazV73j41ZT*GTP#ew)$3uwc;kVcH3i^U?JqD}dTNf%}OF z06ka?BxTeI#=8d5Sya9r6&tz5n!Ucv`V481Q(XVOEy(+Ld20?GD;v{{#>Vx$Bw%JM z5K(iw8$(UAmX|*nqY68!w-DJIBHd65mImV`D~noM$-yO5r_8OgVlq3>heR zr%ZevOYx_nYLo;8vR}QdtTSqh4MZ>Bl1w`D@(bdDMe;1tu8WgE!-8Y<4B_lPqV7l& zccACAa*N%-k1YfLCa;hC#Sc{?dohD03Bud3cbpKVj}!r>c;r#5PvAs++?rb=%sy*7 z3TZI^tX%=OIU$TqEif;SrPKuP(?J$#RaINRq_iCbjcHzM;L#(Q*9f~s;8uA1%gjM)_?jcChY)Vu!?NBkf$2B{L2^ zYl{P7U}p%+p*~5g-IG-bSA?J9dol9JL<6ORJ3f1R+;EcV#>m;9ME%9pGKDQDvL?R! zb9s%ToP=g|UP`{)j62(iXF3Wh-U7LG3&e-M&eEuB$t$b|Y4$;U$_HG>f#kVKdOO zbprFGjK&`57cZ$W<|meTi>I~ z zU3v|WCxi!vL#X*rnR;ArCmD};T%xU!7sEF4siw;dQw-EuQ$>>A=y7?Lvael#*1ESE zW!~f>1EI^eIXJMl?V{Q*Ws46)*e56Ya#L{H=nznW~+#OdU=cKlXf>iSgZGJA02l5xf z9NF3q(l5@euK{leqP7<}i1LueU=UHgBIa$E4xQwfpEtp-Jm1vZIuukZl^!lY_teGZ zCraEAJxU`R>c9~ly}4*%c*L=G9Ra8@*Dg5>%S#m$C;f(3l*b1#9kZVbB9aDf9i#ku zxYSFyBx9S_0Rj_l^+gX1QBlo>a+$){FE)>~Ey=z7m71>F{=Mui+jRVpiYwN2?dj&q za4$t{s7_;BIOro>By=o1N&2;7xT3;{KS{tDB^p}+8`sgz`2D_zt&y3!YMz}J3Y3Z` z`zY0nm%w=vn`SwUA#$3zT5>YW0m8bBV#_>s2DV*+hZa!6T0??+?t7~FScLEWBC4kD zURDm{OlXnXVidVOfw&VB%Y+gF<&_y2y}0_U-c;qtmXd9ComK9GLY@1sZfL35Mf#ns z{1YhuNe2LOXCcMPt5(ao-*nrso@i61)1`OVmpKy2Q)nOVin`Z!*-}wRqfZYxc$3FNX6{KWCe@E)oXP%H6V$LAoICdr1o{ z8a7SpPe$?BZ5yz`bSW7z`tty($80}HU<07>h#nJg6qJ$om|0bKT_Xh2;Ct3W9cv8$ z8`(|e`bVDXqC=s<8@~Wg+#?V@I|T?7npxYRMt9%$eCf%V#o1NyY4@w(2Ud8<0*0@U zmW;99hrwJ{;ZK3;kAg=L&xeFej+Ze(rBaWc56aE&6b6 zDZ*NwYbMz;Pp5X|N$aeJxRZ>*LG=7_Q5Uo@?<4HU%*J_-#7d&J4vsM2;# zK+8Uuhn{34A427d@<)R~5YdEgF9A1z8lF2~JTFwFYz;@k%W~-X0`&nf@ONz#MD1{1 zS@v%2pbL;uu&8E{oXFCu4aJ6QOW_Z&buff~_6F~qGi;TQ!&X$xI%*RUtSyn$HsEs2 z#oW(!$|9kDoxR=5uEKK(ZbI!7#Ezv#aB8{aV?9sJ^K|OhiuQSh6h#VSedhlO5;)ov z1A%E93o1RAHc#mCD)j4H^q;d9g_cNmfp2Z(qI5bmB@9#3Qr4M!-_E zXxFaxZx*FVk#WiehT?*3pZ41?Jp%|>^I{)ir?J4dg3Uo?2Ts2N{Ur)*Ei*z4BAGS# z=mH=PaGfx5<;7RSge|q*q?1v286g2}j6^!+(9-_7s`q9)#9FO*}oZWN}&Ll_vA zi4JVrOfk0TFJOl+bNtBy4&cTxbX4A>Dg3OY2zhg}*IV~s5ro5eRP8F6tn6W+GlyzC ze>V%_>iM4?%kOI_Itjack=SuAo{T8mJ9#wPgI%vaqN=chq>{j|b`fqT^bC5o_1W)H z{uR<=#qjCJOoyokhddVsvac)pMuMj*75y9fRZSU{FAY>U)Nl^f6kOG)@(TZ98~G6+ zk8C-HzlCu|EN;wV-JkOLAmp5L^~BVH5-JEhztuCGgm#E}JM{feGVWeGQy8FcEG`1g z6ItAW-u9PVrK6_ND>Ze8$1Alf4)n%qFtF~n>G^wEUB44+RSi9 ZuoYa9kMtu}@< zfE~HO?&L1GEE8Hz(FC+{B=|^8$Vz>b>7X!(RzdC^G$lcw(dt6VnVGN9iu^SekRNy) zM3=WK3Q5e?qp~o6oB`m;Yo}=sT%2s3RWjv}XTF@e3UvQXg?Rbdj zd)My(9RwaF^@5-sUXTslo=T5bvISh8RrHf?6f!l(vI8ZfQr#X{9WaQ+zLP<>S4F9W z#+5fwkWef6AJ9jk2E?KQ=&Ld(3~vpzJT-HHuPX`NpjRQ{KZq&%l*r2Rz~}AeDKVbb z7rMY;&!9?kpy>yL5^7rWZarL790wPH><~Uv1p83qnO5rWJ%;i3M4UBna4nWOMoY;3 z9rxd!b2Y)h;qHdB6dT%X`tr*vcDK1{z zQz49ZR+m@~FYgZ}YdXV?f`2Myn*Pa>)FHZY>S}0+ZV;;liM3FX=P0O+KV(!2C(ha(?(yYkuIr36EINw z{nY4;i3H`TsP{`z8j|s@Su(2^W8~<2!cXSaaQ!5D`!VeZDuTuMkp+Aw%_}%Hd&;rh|;0TW37X=uQ}L z2L;{ZZAcRa+2%dwOF;i`fRFq@yDV7yoGa3_*iuBVf*1tR2~mY6x3vOS@7@3+?xq7C z7zszypMN2p3k-?zZ~w_sAw=6i?&{0Mp#_l`rTlw*I#ZRwc)!N<^uV2i4o2B@Bdm9p za$?FPXBCZU0^)S-00JDsYm~4RW9MwLhj4V{=C}_E+P_Ka&pf8`|C+2iDb;5))U z;`%RCsr{zuz(8si8|ve)kfyaqf)s!5*mwbyaR1D_0G$eqRjEr#@hn4TqVkik3IhSs zCl?f9t1K+(pS=g>yz&ZnM1Oa*7il;xB_y_PW7D2r{t&cIY_c6JW;OxCpKZ@sN6`p7 zTE=rdJ3xXC4p)bJZ_Vc<@_57Vjrm2;iiq8@5b^*N~aH6baSvtXnHl~jw(>@KTf)xZ@wT4OjgqD$!o@z;R3>4^` z0X+ijBs(!&tq+ZbLQm6v2crDOVi;`g;#sGQ5Yk|eg6i0@TM_2_SvpZkk(@n~%s6!y7Z9 z@WG2B*WrsHE6Zs0X~Gh=MOWh-9KhCGfFStSdVqD6h`n^GGcDFRCRw@!0Ja}DhXGE| z_V+MV*in)tm!BV33dVG?R)C#TCo!jXu|Nb;0!wsOYCekz7^eNT&w{W(;*mxH4ROfT zCp6qxd%El;a|MVlVN2qbMpfR@YtRdLj>4o!oZ&N+AU}9Z%4l!yaZ4NDwzW6{x+=c+ zcc+00=dG4n_COVIe!an@b|hY|=OqI!+#O;~u-wnAMyx|Ahtc^Lz1{39@ce7O85!^?tN+7w`zZu}FntTdr+Ap3t1P z-#?FS8=AzU`=(Wz3g$(Fc#KJDAECxR4_rjd(Bd3``PhppvV66YnsW}XxeE8QvNyyK zFqm+)SRB>H-h}@~)2ln<*lM*0L%28VN;P!oSQl;9Y_&t0bPXxa!R=r2E_0OSH*0UO~P+rHo?+ zKTL=`{J*H3xJ?(yQy1*lFM+GEgO`wp0UEUNUI@bDt{eoY*npF>RG_!gukpp>R+S zd5%x;mW-9}(`fPtN}16CJv9M->HZC#f53Y}yzc%nKT^&d9z{G-^z9=hC?eKvU}l7v z_@r84Yu@f&Y=$Z7SXCES#O^;#A0-+SRpRavhQuEWys7`hSBr$E`SI!mWX8@{HTcD_oXkoN~Uu4z@vc~?$l8M3FtWn=>Mz(TS1}~`iGj> zp`229A$B2UpqF{R#vPhn&}yFcp|&=U;!ivDGl2DoElPN>vp@~L=t*S`uyYM-8P*(3 zIw;Vw>q&A5luqKS%;ZCF5qm-`xG3Q=*7Hb!;+#ye`RGaI9lF`nERk^S!?(0ZtMfZm z!WV}*N@pRKE2}-BESFbjnJ2KbLQr5CHf58^=+#-nvj)p8sqL*OCay+W#Dzg#DDsy= zmV9;jO}FntEtQEYHL~v;dhfEY63tBPbs@xPcA{B=!|)~ z5yfA8#F=P61dyDZ2)8@C6JK-Qo$CdyocD7Jm4ZZ)JqTGc6cGY>K@}?zHM$)3F&bUk zWS&^IgO5!Q2wI2&WFdGGY*AL2pAnsyJOxI6po0SM4NvveBlen{q5(fz?~-#9k!G;q zxL)1NG>n^1fna~IO;-2MEmR`hR8+BhWo;21X)VF}t9k58gS0tAxhtaiTsi7FnNIHj zseh4n9z7}cl4yl7#^0%}For4!ahbVrM~W~f>O*Oiiq6@CNZbF{G2Zfz(WPxZ_{*egVkz$gF+hKVYMwfv{Spb zqF=~+NRYe`Cq95yGvsQ8Y>chu?=%8dzFN1LeD6~&E|GQQcObo{3`J*=y$J=zslilx zg_(*a(llGlNesss7zD);k{PmFnIC7~?M3&TgD4f4GB(2OV$IOtf()Lo_!!sQeA^@? z0|CBEgt?`FrLpF}T_f?uHC(VV$tcrFKNT`B&s#0QrM#dnLnl(Ku^>s!1*l_`-=5{> zICHmhE*0y1;%q>i%{4>+r!u~!%^)x!Hx$Xr#FYY`s+tVTkU*#uC3S^#argNp^s25B zD%|fPW`!`!|NK@bQ?8>onOkHwyMm63VpvTuL{9+VawV$RrNq<;{rl*PQ=FXHD=!45 zTp{>kDpK`vU9mmy;d)qZ9RM;WG?;Biedn{{hXc{SsT*FZUW)IfK| zoW2SrUC8#d2beK7TpgZN85k^IqRi{%D>==VkA(^cy_t8Ky3_iO^Cp7dnr<{uo<=;F zFdI7~863eDTJ9GkUmh*ngBE#n9KZ!V{*(;kQM1GlTyui!mb6q7LNH=hZLO`>FHfJ4^r8!`BJud zu_yt{j28NQF=pgsx@m@A|)k-Ncolp>}=atKW_KFPxJsCo%bph(H zQ($mdf7lNSZLPErLXPV+k&E}H*x?e0A7UMDv~32TgNGTis>XALMy z3{))Cw;0ob{?fZx^Xv5I{o|Wj)=h_bvMYXc68tx81mx{3PHJUe ziOEwiSyhnl;P7bFDIKO=yfwG={Iw&X<9$4Ra%$QT3^vJ#PZR$Bz!XE3KF1<_K14f` zlEYd$>9j4#B)A!H>cDp>X66*XwmrG%PbpTYqn~-Wa1Fei8iLUxEZjk#D{zZpY5NikEdV-bn zaJtq{LOA1+%nwPh>zlT#6M^5^9^0TJ##eeAXI7={w8SA{BW~X6|>aoVzgdl@9 z+emtvq!Aylo`b4V4lW06cKf?q{K_jQgK2yt750ML&8P`6QoC@*&8v#g47TEqNZ{?Q zv=0=$V5D_R7F|UFnVVO}?*NnPr%Z7mH7Mj9-^;{_u`^DvvZ>q4en)ajl1L^zivPu5 zpd;)KIT?OZLjtfr0TuNOa$izkf8&Iq^&(l(`Qs+p!Py=V16o!OIKu)#Kiike=O|K< z>0Wl~OdLZCTR@MmW9!O~d8T)E+y$rHGAfR=yC1qZpYwxTqPg>ZD1=4; z>Ovec%5D4>oKz*zwfoK+h7|cG>~DYhe(~%_0J%>j>}r?+baV^9EklnfQpbz4|C&n$U8E$~i2j(0SIV zrT$ouXe>(J^586Plif z{0Dz9SVP26V`&DRqYd1_k8(s)XBmy>Q_C^r#n>R~a04S@)EGKFb%5Bt^vd!;Qf2SK z_Xc|HJ=xO-E*ZxoqwvF|2xLi@S!8Do#9T_8Xr`6fr61Q!?MNxW5tU}1@P2nfUWHWY z(|aB8nvWm?@0#r^eKIS%YmA`LL@1y_k5Bc{-=@Wj(5RUmo3-%0D=89mreH%p)$M1Q z2mh^4Ll^3|aTTA(xINm?CYFfFyofU_vVye(7HyVRu%MY$n`K3B9z6A1Kw(}>n7G=_ zBuy@rZVNAig;Vyx2;wq>s&B4xO!mh87w_v;wJku=<@TWz)6yz&#lKsIKM(}Wv$HWG%Ds;h=9}OG5|5($ z;#Qo!h&d8$XFnp|1&Y|}T0t#whSd$XgNN1BFaT7@6Yn{ymisRtR+#w(v` zo!5!xqBnm-!YP(_LI(wp>PIyxwWI7^Dj+1`3*#*AhYW&w@MZ`!D#}q0DqYf;YY7H{ zE+LZMxmA%gsAv7d2*u^N+7zlmQ|vjHK!kGG*V_!NuG}ym9le(e{enQ^f>s~0<)CjA z-m);;fe6eW4Dh0VuuoHVjm!CyWFr{F1W>$a78>E{s?i`v;hRG+we|1w{xw&=GrcIP zGifvY10K~bN$<;w1Qf1Oif?ir9Ugqrqa>s?yC~J7@O0mw(Jrb(N}>?5%4ijDV$Oo& z-B+iLk656Yri!tDYsWh>k^5q!O^jz5+;DEbC~kt2b?Z5OI6{Um-jy=ha*3vQ!Z=$h ze5^)8{qDh-x8D4MZme%sAW`3BfA+P|=ANBtt=q_uE7kj@g!LVr7*kiAW`%XPt4S`| zh`CuH7R3XvR&6PW)~qLy_*4>1EIFWjCr%jEciTQiC8M=N_d8LW?st}@fMg78uG~hC z^{y;PDT)Qw??vSM3<}x9c-nVhByF%Mc$?^;{DkW~MCcl-oALB*wlX|9&b-QYqOfS@ z97olf|G%41lLKs9im?YX9Bk~jwK{uxq>%)YvMPjUQX2WWKk&p=}79M zDEm1%cf$V=T!l~t5>_7`!Jd{j;bDMbW_7-flp5Z?)D6nwpz1`RCM>dqv?1K1)#9~P zvXeuF9^wY?vpkOxP)hu!Rh_WIl+ha2=&!EbPR+XrPK?@HAYcZvg3E`trgvZ4_iGNwI)~a zN+Na4_GPD}+RG~Uvm=TvM=G)XvmDG Dv!*Hd literal 0 HcmV?d00001 diff --git a/registration-processor/registration-processor-message-sender-impl/pom.xml b/registration-processor/registration-processor-message-sender-impl/pom.xml index 5132a6aa025..e053527b446 100644 --- a/registration-processor/registration-processor-message-sender-impl/pom.xml +++ b/registration-processor/registration-processor-message-sender-impl/pom.xml @@ -8,11 +8,11 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-B1 + 1.2.0.1-B3-SNAPSHOT registration-processor-message-sender-impl - 1.2.0.1-B1 + 1.2.0.1-B3-SNAPSHOT UTF-8 @@ -40,16 +40,6 @@ - - org.springframework.boot - spring-boot-starter - - - com.h2database - h2 - - - junit junit @@ -59,10 +49,6 @@ org.springframework.boot spring-boot-starter-web - - org.springframework.boot - spring-boot-starter-test - io.mosip.registrationprocessor registration-processor-registration-status-service-impl 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 e6ac5d78e70..cd551b37bd3 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 @@ -15,11 +15,6 @@ import java.util.Map.Entry; import java.util.Set; -import io.mosip.kernel.core.exception.BaseUncheckedException; -import io.mosip.kernel.core.exception.ServiceError; -import io.mosip.registration.processor.core.constant.*; -import io.mosip.registration.processor.core.idrepo.dto.VidInfoDTO; -import io.mosip.registration.processor.core.idrepo.dto.VidsInfosDTO; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.exception.ExceptionUtils; @@ -38,6 +33,8 @@ import com.fasterxml.jackson.databind.ObjectMapper; +import io.mosip.kernel.core.exception.BaseUncheckedException; +import io.mosip.kernel.core.exception.ServiceError; import io.mosip.kernel.core.logger.spi.Logger; import io.mosip.kernel.core.util.DateUtils; import io.mosip.kernel.core.util.JsonUtils; @@ -45,6 +42,11 @@ import io.mosip.kernel.core.util.exception.JsonParseException; import io.mosip.kernel.core.util.exception.JsonProcessingException; import io.mosip.registration.processor.core.code.ApiName; +import io.mosip.registration.processor.core.constant.IdType; +import io.mosip.registration.processor.core.constant.LoggerFileConstant; +import io.mosip.registration.processor.core.constant.MappingJsonConstants; +import io.mosip.registration.processor.core.constant.ProviderStageName; +import io.mosip.registration.processor.core.constant.VidType; import io.mosip.registration.processor.core.exception.ApisResourceAccessException; import io.mosip.registration.processor.core.exception.PacketDecryptionFailureException; import io.mosip.registration.processor.core.exception.PacketManagerException; @@ -54,6 +56,8 @@ import io.mosip.registration.processor.core.http.RequestWrapper; import io.mosip.registration.processor.core.http.ResponseWrapper; import io.mosip.registration.processor.core.idrepo.dto.IdResponseDTO; +import io.mosip.registration.processor.core.idrepo.dto.VidInfoDTO; +import io.mosip.registration.processor.core.idrepo.dto.VidsInfosDTO; import io.mosip.registration.processor.core.logger.RegProcessorLogger; import io.mosip.registration.processor.core.notification.template.generator.dto.ResponseDto; import io.mosip.registration.processor.core.notification.template.generator.dto.SmsRequestDto; @@ -161,7 +165,7 @@ public class MessageNotificationServiceImpl @Autowired private ObjectMapper mapper; - + private List mapperJsonKeys = null; private JSONObject mapperIdentity=null; @@ -536,19 +540,15 @@ private Map setAttributesFromIdRepo(String uin, Map setAttributes(String idJsonString, Map attribute, String regType, String lang, StringBuilder phoneNumber, StringBuilder emailId) throws IOException { JSONObject demographicIdentity = null; - demographicIdentity = JsonUtil.objectMapperReadValue(idJsonString, JSONObject.class); if(mapperJsonKeys==null) { String mapperJsonString = Utilities.getJson(utility.getConfigServerFileStorageURL(), utility.getGetRegProcessorIdentityJson()); JSONObject mapperJson = JsonUtil.objectMapperReadValue(mapperJsonString, JSONObject.class); - mapperIdentity = JsonUtil.getJSONObject(mapperJson, utility.getGetRegProcessorDemographicIdentity()); - - mapperJsonKeys = new ArrayList<>(mapperIdentity.keySet()); + mapperIdentity = JsonUtil.getJSONObject(mapperJson, utility.getGetRegProcessorDemographicIdentity()); + mapperJsonKeys = new ArrayList<>(mapperIdentity.keySet()); } - - for (String key : mapperJsonKeys) { JSONObject jsonValue = JsonUtil.getJSONObject(mapperIdentity, key); if (jsonValue.get(VALUE) != null && !jsonValue.get(VALUE).toString().isBlank()) { diff --git a/registration-processor/registration-processor-notification-service/pom.xml b/registration-processor/registration-processor-notification-service/pom.xml index 9e72de49c3f..5ab85d69ff1 100644 --- a/registration-processor/registration-processor-notification-service/pom.xml +++ b/registration-processor/registration-processor-notification-service/pom.xml @@ -8,11 +8,11 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-B1 + 1.2.0.1-B3-SNAPSHOT registration-processor-notification-service - 1.2.0.1-B1 + 1.2.0.1-B3-SNAPSHOT UTF-8 UTF-8 diff --git a/registration-processor/registration-processor-notification-service/src/main/java/io/mosip/registration/processor/notification/service/impl/NotificationServiceImpl.java b/registration-processor/registration-processor-notification-service/src/main/java/io/mosip/registration/processor/notification/service/impl/NotificationServiceImpl.java index adab4dc1097..dfb19f608fb 100644 --- a/registration-processor/registration-processor-notification-service/src/main/java/io/mosip/registration/processor/notification/service/impl/NotificationServiceImpl.java +++ b/registration-processor/registration-processor-notification-service/src/main/java/io/mosip/registration/processor/notification/service/impl/NotificationServiceImpl.java @@ -106,7 +106,7 @@ public class NotificationServiceImpl implements NotificationService { @Value("${registration.processor.notification.emails}") private String notificationEmails; - @Value("${mosip.notificationtype}") + @Value("${mosip.registration.processor.notification.types}") private String notificationTypes; @Value("${websub.hub.url}") diff --git a/registration-processor/registration-processor-notification-service/src/main/java/io/mosip/registration/processor/notification/util/StatusNotificationTypeMapUtil.java b/registration-processor/registration-processor-notification-service/src/main/java/io/mosip/registration/processor/notification/util/StatusNotificationTypeMapUtil.java index f8444497ca6..6935d37de86 100644 --- a/registration-processor/registration-processor-notification-service/src/main/java/io/mosip/registration/processor/notification/util/StatusNotificationTypeMapUtil.java +++ b/registration-processor/registration-processor-notification-service/src/main/java/io/mosip/registration/processor/notification/util/StatusNotificationTypeMapUtil.java @@ -48,7 +48,7 @@ private static Map statusMapp NotificationTemplateType.TECHNICAL_ISSUE); //TODO this is put as a temp fix need to recheck the mapping statusMap.put(NotificationStageStatus.PACKET_REJECTED, - NotificationTemplateType.DUPLICATE_UIN); + NotificationTemplateType.TECHNICAL_ISSUE); statusMap.put(NotificationStageStatus.PACKET_FAILED, NotificationTemplateType.TECHNICAL_ISSUE); return unmodifiableMap; } diff --git a/registration-processor/registration-processor-packet-manager/pom.xml b/registration-processor/registration-processor-packet-manager/pom.xml index dbef7053f11..97fab95bbf2 100644 --- a/registration-processor/registration-processor-packet-manager/pom.xml +++ b/registration-processor/registration-processor-packet-manager/pom.xml @@ -7,12 +7,12 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-B1 + 1.2.0.1-B3-SNAPSHOT registration-processor-packet-manager registration-processor-packet-manager - 1.2.0.1-B1 + 1.2.0.1-B3-SNAPSHOT UTF-8 @@ -32,20 +32,11 @@ commons-pool ${commons.pool} - - org.springframework.cloud - spring-cloud-starter-config - ${spring-cloud-config.version} - junit junit test - - org.springframework.boot - spring-boot-starter - io.mosip.registrationprocessor registration-processor-core @@ -94,4 +85,4 @@ test - \ No newline at end of file + diff --git a/registration-processor/registration-processor-packet-manager/src/main/java/io/mosip/registration/processor/packet/manager/decryptor/DecryptorImpl.java b/registration-processor/registration-processor-packet-manager/src/main/java/io/mosip/registration/processor/packet/manager/decryptor/DecryptorImpl.java index e14aeef9668..c965a9820c1 100644 --- a/registration-processor/registration-processor-packet-manager/src/main/java/io/mosip/registration/processor/packet/manager/decryptor/DecryptorImpl.java +++ b/registration-processor/registration-processor-packet-manager/src/main/java/io/mosip/registration/processor/packet/manager/decryptor/DecryptorImpl.java @@ -176,16 +176,6 @@ public InputStream decrypt(String id, String refId, InputStream packetStream) PacketDecryptionFailureExceptionConstant.MOSIP_PACKET_DECRYPTION_FAILURE_ERROR_CODE .getErrorCode(), httpClientException.getResponseBodyAsString()); - } else if (e.getCause() instanceof HttpServerErrorException) { - HttpServerErrorException httpServerException = (HttpServerErrorException) e.getCause(); - description.setMessage(PlatformErrorMessages.RPR_PDS_PACKET_DECRYPTION_FAILURE.getMessage() - + httpServerException.getResponseBodyAsString()); - description.setCode(PlatformErrorMessages.RPR_PDS_PACKET_DECRYPTION_FAILURE.getCode()); - - throw new PacketDecryptionFailureException( - PacketDecryptionFailureExceptionConstant.MOSIP_PACKET_DECRYPTION_FAILURE_ERROR_CODE - .getErrorCode(), - httpServerException.getResponseBodyAsString()); } else { description.setMessage( PlatformErrorMessages.RPR_PDS_PACKET_DECRYPTION_FAILURE.getMessage() + e.getMessage()); diff --git a/registration-processor/registration-processor-packet-manager/src/main/java/io/mosip/registration/processor/packet/manager/idreposervice/impl/IdRepoServiceImpl.java b/registration-processor/registration-processor-packet-manager/src/main/java/io/mosip/registration/processor/packet/manager/idreposervice/impl/IdRepoServiceImpl.java index 052f111e0d9..91e437b7c3d 100644 --- a/registration-processor/registration-processor-packet-manager/src/main/java/io/mosip/registration/processor/packet/manager/idreposervice/impl/IdRepoServiceImpl.java +++ b/registration-processor/registration-processor-packet-manager/src/main/java/io/mosip/registration/processor/packet/manager/idreposervice/impl/IdRepoServiceImpl.java @@ -4,18 +4,20 @@ import java.util.ArrayList; import java.util.List; -import io.mosip.registration.processor.core.constant.IdType; import org.json.simple.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.context.config.annotation.RefreshScope; import org.springframework.stereotype.Service; +import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.gson.Gson; +import com.google.gson.GsonBuilder; import io.mosip.kernel.core.logger.spi.Logger; import io.mosip.registration.processor.core.code.ApiName; import io.mosip.registration.processor.core.constant.AbisConstant; +import io.mosip.registration.processor.core.constant.IdType; import io.mosip.registration.processor.core.constant.LoggerFileConstant; import io.mosip.registration.processor.core.exception.ApisResourceAccessException; import io.mosip.registration.processor.core.http.ResponseWrapper; @@ -99,8 +101,8 @@ else if (idType.equals(IdType.VID)) ResponseWrapper.class); if (response.getResponse() != null) { - Gson gsonObj = new Gson(); - String jsonString = gsonObj.toJson(response.getResponse()); + //Gson gsonObj = new Gson(); + String jsonString =mapper.writeValueAsString(response.getResponse());//gsonObj.toJson(response.getResponse()); JSONObject identityJson = JsonUtil.objectMapperReadValue(jsonString, JSONObject.class); JSONObject demographicIdentity = JsonUtil.getJSONObject(identityJson, regProcessorDemographicIdentity); return JsonUtil.getJSONValue(demographicIdentity, AbisConstant.UIN); @@ -152,10 +154,9 @@ public JSONObject getIdJsonFromIDRepo(String machedRegId, String regProcessorDem response = (ResponseWrapper) restClientService.getApi(ApiName.RETRIEVEIDENTITYFROMRID, pathSegments, "", "", ResponseWrapper.class); - + if (response.getResponse() != null) { - Gson gsonObj = new Gson(); - String jsonString = gsonObj.toJson(response.getResponse()); + String jsonString =mapper.writeValueAsString(response.getResponse()); JSONObject identityJson = JsonUtil.objectMapperReadValue(jsonString, JSONObject.class); demographicJsonObj = JsonUtil.getJSONObject(identityJson, regProcessorDemographicIdentity); diff --git a/registration-processor/registration-processor-packet-manager/src/main/java/io/mosip/registration/processor/packet/manager/service/impl/FileManagerImpl.java b/registration-processor/registration-processor-packet-manager/src/main/java/io/mosip/registration/processor/packet/manager/service/impl/FileManagerImpl.java index a7dc1b09383..c4037a3df38 100644 --- a/registration-processor/registration-processor-packet-manager/src/main/java/io/mosip/registration/processor/packet/manager/service/impl/FileManagerImpl.java +++ b/registration-processor/registration-processor-packet-manager/src/main/java/io/mosip/registration/processor/packet/manager/service/impl/FileManagerImpl.java @@ -533,8 +533,16 @@ public String getPPKPath() throws IOException { String.class); File file = FileUtils.getFile(env.getProperty(REGPROC_PPK)); FileOutputStream out = new FileOutputStream(file); + try { + if(null!=data) out.write(data.getBytes()); + else + { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + "No content found for ",configServerFileStorageURL + env.getProperty(REGPROC_PPK)); + + } } finally { out.close(); } diff --git a/registration-processor/registration-processor-packet-manager/src/test/java/io/mosip/registration/processor/packet/manager/decryptor/DecryptorTest.java b/registration-processor/registration-processor-packet-manager/src/test/java/io/mosip/registration/processor/packet/manager/decryptor/DecryptorTest.java index 4111f0417fd..a239d65c997 100644 --- a/registration-processor/registration-processor-packet-manager/src/test/java/io/mosip/registration/processor/packet/manager/decryptor/DecryptorTest.java +++ b/registration-processor/registration-processor-packet-manager/src/test/java/io/mosip/registration/processor/packet/manager/decryptor/DecryptorTest.java @@ -9,7 +9,9 @@ import java.io.IOException; import java.io.InputStream; import java.time.format.DateTimeParseException; +import java.util.ArrayList; import java.util.Arrays; +import java.util.List; import org.apache.commons.io.IOUtils; import org.junit.Before; @@ -30,8 +32,10 @@ import io.mosip.kernel.core.exception.ServiceError; import io.mosip.kernel.core.util.DateUtils; +import io.mosip.registration.processor.core.common.rest.dto.ErrorDTO; import io.mosip.registration.processor.core.exception.ApisResourceAccessException; import io.mosip.registration.processor.core.exception.PacketDecryptionFailureException; +import io.mosip.registration.processor.core.http.ResponseWrapper; import io.mosip.registration.processor.core.spi.restclient.RegistrationProcessorRestClientService; import io.mosip.registration.processor.packet.manager.PacketManagerBootApplication; import io.mosip.registration.processor.packet.manager.dto.CryptomanagerResponseDto; @@ -117,13 +121,19 @@ public void HttpClientErrorExceptionTest() @Test(expected = PacketDecryptionFailureException.class) public void HttpServerErrorExceptionTest() throws FileNotFoundException, ApisResourceAccessException, PacketDecryptionFailureException { - + List errors=new ArrayList<>(); + ServiceError e=new ServiceError("HttpStatus.INTERNAL_SERVER_ERROR", "KER-FSE-004:encrypted data is corrupted or not base64 encoded"); + errors.add(e); + + CryptomanagerResponseDto c=new CryptomanagerResponseDto(); + c.setErrors(errors); + 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"); Mockito.when(apisResourceAccessException.getCause()).thenReturn(httpServerErrorException); Mockito.when(restClientService.postApi(any(), any(), any(), any(), any())) - .thenThrow(apisResourceAccessException); + .thenReturn(c); decryptor.decrypt("84071493960000320190110145452", "refid", inputStream); diff --git a/registration-processor/registration-processor-packet-manager/src/test/java/io/mosip/registration/processor/packet/manager/service/impl/test/IdRepoServiceImplTest.java b/registration-processor/registration-processor-packet-manager/src/test/java/io/mosip/registration/processor/packet/manager/service/impl/test/IdRepoServiceImplTest.java index dce157e6918..6400c7f2030 100644 --- a/registration-processor/registration-processor-packet-manager/src/test/java/io/mosip/registration/processor/packet/manager/service/impl/test/IdRepoServiceImplTest.java +++ b/registration-processor/registration-processor-packet-manager/src/test/java/io/mosip/registration/processor/packet/manager/service/impl/test/IdRepoServiceImplTest.java @@ -1,9 +1,9 @@ package io.mosip.registration.processor.packet.manager.service.impl.test; import static org.junit.Assert.assertNull; +import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyList; import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Matchers.any; import javax.swing.text.Utilities; @@ -15,11 +15,15 @@ import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; +import org.mockito.Spy; 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 com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.databind.ObjectMapper; + import io.mosip.registration.processor.core.http.ResponseWrapper; import io.mosip.registration.processor.core.idrepo.dto.IdResponseDTO; import io.mosip.registration.processor.core.packet.dto.demographicinfo.identify.IdentityJsonValues; @@ -43,6 +47,10 @@ public class IdRepoServiceImplTest { @InjectMocks private IdRepoServiceImpl idRepoService; + @Spy + private ObjectMapper mapper = new ObjectMapper(); + + /** * Sets the up. * @@ -51,7 +59,6 @@ public class IdRepoServiceImplTest { */ @Before public void setUp() throws Exception { - IdentityJsonValues jv = new IdentityJsonValues(); jv.setValue("1"); IdResponseDTO dto = new IdResponseDTO(); @@ -68,12 +75,13 @@ public void setUp() throws Exception { * @throws Exception * the exception */ - @Test + /*@Test public void testgetIdJsonFromIDRepo() throws Exception { + Mockito.when(mapper.writeValueAsString(Mockito.any())).thenReturn("{}"); JSONObject matchedDemographicIdentity = idRepoService.getIdJsonFromIDRepo("", "Identity"); assertNull(matchedDemographicIdentity); - } + }*/ /** * Testget UIN by RID. @@ -83,6 +91,7 @@ public void testgetIdJsonFromIDRepo() throws Exception { */ @Test public void testgetUINByRID() throws Exception { + Mockito.when(mapper.writeValueAsString(Mockito.any())).thenReturn(""); JSONObject demoJson = new JSONObject(); demoJson.put("UIN", "1"); PowerMockito.mockStatic(JsonUtil.class); @@ -110,7 +119,7 @@ public void testgetUINByRIDResponseNull() throws Exception { */ @Test public void testfindUinFromIdrepo() throws Exception { - + Mockito.when(mapper.writeValueAsString(Mockito.any())).thenReturn(""); JSONObject demoJson = new JSONObject(); demoJson.put("UIN", "1"); PowerMockito.mockStatic(JsonUtil.class); diff --git a/registration-processor/registration-processor-packet-manager/src/test/java/io/mosip/registration/processor/packet/manager/service/impl/test/IdrepoDraftServiceTest.java b/registration-processor/registration-processor-packet-manager/src/test/java/io/mosip/registration/processor/packet/manager/service/impl/test/IdrepoDraftServiceTest.java index 9c16697d285..f3f5f082658 100644 --- a/registration-processor/registration-processor-packet-manager/src/test/java/io/mosip/registration/processor/packet/manager/service/impl/test/IdrepoDraftServiceTest.java +++ b/registration-processor/registration-processor-packet-manager/src/test/java/io/mosip/registration/processor/packet/manager/service/impl/test/IdrepoDraftServiceTest.java @@ -20,7 +20,6 @@ import org.powermock.modules.junit4.PowerMockRunner; import com.fasterxml.jackson.databind.ObjectMapper; -import com.google.gson.Gson; import io.mosip.kernel.core.util.HMACUtils2; import io.mosip.registration.processor.core.code.ApiName; @@ -36,7 +35,7 @@ import io.mosip.registration.processor.packet.manager.idreposervice.IdrepoDraftService; @RunWith(PowerMockRunner.class) -@PrepareForTest({ IOUtils.class, HMACUtils2.class, Gson.class }) +@PrepareForTest({ IOUtils.class, HMACUtils2.class }) @PowerMockIgnore({"com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "javax.management.*", "javax.net.ssl.*" }) public class IdrepoDraftServiceTest { diff --git a/registration-processor/registration-processor-registration-status-service-impl/pom.xml b/registration-processor/registration-processor-registration-status-service-impl/pom.xml index cd6e25f01ba..9e60b3dfbe4 100644 --- a/registration-processor/registration-processor-registration-status-service-impl/pom.xml +++ b/registration-processor/registration-processor-registration-status-service-impl/pom.xml @@ -1,111 +1,111 @@ - - - 4.0.0 - jar - - - io.mosip.registrationprocessor - registration-processor - 1.2.0.1-B1 - - registration-processor-registration-status-service-impl - 1.2.0.1-B1 - - - UTF-8 - - - - - org.mockito - mockito-core - ${mockito.version} - test - - - - - - - org.springframework.cloud - spring-cloud-starter-config - ${spring-cloud-config.version} - - - org.springframework.boot - spring-boot-starter-test - - - org.springframework.boot - spring-boot-starter-data-jpa - - - joda-time - joda-time - ${jodatime.version} - - - org.postgresql - postgresql - - - io.springfox - springfox-swagger-ui - ${swagger.version} - - - io.springfox - springfox-swagger2 - ${swagger.version} - - - - junit - junit - test - - - io.mosip.kernel - kernel-core - ${kernel.core.version} - - - io.mosip.kernel - kernel-idvalidator-rid - ${kernel.idvalidator.rid.version} - - - com.h2database - h2 - - - io.mosip.kernel - kernel-dataaccess-hibernate - ${kernel.dataaccess.hibernate.version} - - - io.mosip.registrationprocessor - registration-processor-core - ${registration.processor.core.version} - - - io.mosip.registrationprocessor - registration-processor-rest-client - ${registration.processor.rest.client.version} - - - org.powermock - powermock-module-junit4 - ${powermock.module.junit4.version} - test - - - org.powermock - powermock-api-mockito2 - ${powermock.api.mockito.version} - test - - - + + + 4.0.0 + jar + + + io.mosip.registrationprocessor + registration-processor + 1.2.0.1-B3-SNAPSHOT + + registration-processor-registration-status-service-impl + 1.2.0.1-B3-SNAPSHOT + + + UTF-8 + + + + + org.mockito + mockito-core + ${mockito.version} + test + + + + + + + org.springframework.cloud + spring-cloud-starter-config + ${spring-cloud-config.version} + + + org.springframework.boot + spring-boot-starter-test + + + org.springframework.boot + spring-boot-starter-data-jpa + + + joda-time + joda-time + ${jodatime.version} + + + org.postgresql + postgresql + + + io.springfox + springfox-swagger-ui + ${swagger.version} + + + io.springfox + springfox-swagger2 + ${swagger.version} + + + + junit + junit + test + + + io.mosip.kernel + kernel-core + ${kernel.core.version} + + + io.mosip.kernel + kernel-idvalidator-rid + ${kernel.idvalidator.rid.version} + + + com.h2database + h2 + + + io.mosip.kernel + kernel-dataaccess-hibernate + ${kernel.dataaccess.hibernate.version} + + + io.mosip.registrationprocessor + registration-processor-core + ${registration.processor.core.version} + + + io.mosip.registrationprocessor + registration-processor-rest-client + ${registration.processor.rest.client.version} + + + org.powermock + powermock-module-junit4 + ${powermock.module.junit4.version} + test + + + org.powermock + powermock-api-mockito2 + ${powermock.api.mockito.version} + test + + + diff --git a/registration-processor/registration-processor-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/dao/RegistrationStatusDao.java b/registration-processor/registration-processor-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/dao/RegistrationStatusDao.java index c3e2eb384c0..f163a009799 100644 --- a/registration-processor/registration-processor-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/dao/RegistrationStatusDao.java +++ b/registration-processor/registration-processor-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/dao/RegistrationStatusDao.java @@ -118,7 +118,7 @@ public List findAll(String rid) { return registrationStatusRepositary.findByRegId(rid); } - + /** * Gets the enrolment status by status code. * @@ -190,7 +190,7 @@ public List getByIds(List ids) { * @return the un processed packets */ public List getUnProcessedPackets(Integer fetchSize, long elapseTime, - Integer reprocessCount, List status) { + Integer reprocessCount, List status, List excludeStageNames) { LocalDateTime timeDifference = LocalDateTime.now().minusSeconds(elapseTime); List statusCodes=new ArrayList<>(); @@ -201,15 +201,17 @@ public List getUnProcessedPackets(Integer fetchSize, l statusCodes.add(RegistrationStatusCode.FAILED.toString()); statusCodes.add(RegistrationStatusCode.PROCESSED.toString()); - return registrationStatusRepositary.getUnProcessedPackets(status, reprocessCount, timeDifference, statusCodes,fetchSize); + return registrationStatusRepositary.getUnProcessedPackets(status, reprocessCount, timeDifference, + statusCodes, fetchSize, excludeStageNames); } - public Integer getUnProcessedPacketsCount(long elapseTime, Integer reprocessCount, List status) { + public Integer getUnProcessedPacketsCount(long elapseTime, Integer reprocessCount, List status, + List excludeStageNames) { LocalDateTime timeDifference = LocalDateTime.now().minusSeconds(elapseTime); List statusCodes=new ArrayList<>(); statusCodes.add(RegistrationStatusCode.PAUSED.toString()); - return registrationStatusRepositary.getUnProcessedPacketsCount(status, reprocessCount, timeDifference, statusCodes); - + return registrationStatusRepositary.getUnProcessedPacketsCount(status, reprocessCount, timeDifference, + statusCodes, excludeStageNames); } public Boolean checkUinAvailabilityForRid(String rid) { diff --git a/registration-processor/registration-processor-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/decryptor/Decryptor.java b/registration-processor/registration-processor-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/decryptor/Decryptor.java index 0521fa0a4fc..ae1179a2697 100644 --- a/registration-processor/registration-processor-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/decryptor/Decryptor.java +++ b/registration-processor/registration-processor-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/decryptor/Decryptor.java @@ -179,17 +179,7 @@ public String decrypt(Object encryptedSyncMetaInfo, String referenceId, String t PacketDecryptionFailureExceptionConstant.MOSIP_PACKET_DECRYPTION_FAILURE_ERROR_CODE .getErrorCode(), httpClientException.getResponseBodyAsString()); - } else if (e.getCause() instanceof HttpServerErrorException) { - HttpServerErrorException httpServerException = (HttpServerErrorException) e.getCause(); - description.setMessage(PlatformErrorMessages.RPR_PDS_PACKET_DECRYPTION_FAILURE.getMessage() - + httpServerException.getResponseBodyAsString()); - description.setCode(PlatformErrorMessages.RPR_PDS_PACKET_DECRYPTION_FAILURE.getCode()); - - throw new PacketDecryptionFailureException( - PacketDecryptionFailureExceptionConstant.MOSIP_PACKET_DECRYPTION_FAILURE_ERROR_CODE - .getErrorCode(), - httpServerException.getResponseBodyAsString()); - } else { + } else { description.setMessage( PlatformErrorMessages.RPR_PDS_PACKET_DECRYPTION_FAILURE.getMessage() + e.getMessage()); description.setCode(PlatformErrorMessages.RPR_PDS_PACKET_DECRYPTION_FAILURE.getCode()); diff --git a/registration-processor/registration-processor-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/encryptor/Encryptor.java b/registration-processor/registration-processor-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/encryptor/Encryptor.java index 61227611e5e..d332c5ab71f 100644 --- a/registration-processor/registration-processor-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/encryptor/Encryptor.java +++ b/registration-processor/registration-processor-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/encryptor/Encryptor.java @@ -161,16 +161,7 @@ public byte[] encrypt(String syncMetaInfo, String referenceId, String timeStamp) throw new EncryptionFailureException( EncryptionFailureExceptionConstant.MOSIP_ENCRYPTION_FAILURE_ERROR_CODE.getErrorCode(), httpClientException.getResponseBodyAsString()); - } else if (e.getCause() instanceof HttpServerErrorException) { - HttpServerErrorException httpServerException = (HttpServerErrorException) e.getCause(); - description.setMessage(PlatformErrorMessages.RPR_PGS_ENCRYPTOR_INVLAID_DATA_EXCEPTION.getMessage() - + httpServerException.getResponseBodyAsString()); - description.setCode(PlatformErrorMessages.RPR_PGS_ENCRYPTOR_INVLAID_DATA_EXCEPTION.getCode()); - - throw new EncryptionFailureException( - EncryptionFailureExceptionConstant.MOSIP_ENCRYPTION_FAILURE_ERROR_CODE.getErrorCode(), - httpServerException.getResponseBodyAsString()); - } else { + } else { description.setMessage( PlatformErrorMessages.RPR_PGS_ENCRYPTOR_INVLAID_DATA_EXCEPTION.getMessage() + e.getMessage()); description.setCode(PlatformErrorMessages.RPR_PGS_ENCRYPTOR_INVLAID_DATA_EXCEPTION.getCode()); diff --git a/registration-processor/registration-processor-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/exception/InternalAuthDeligateAppException.java b/registration-processor/registration-processor-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/exception/InternalAuthDeligateAppException.java new file mode 100644 index 00000000000..686e5656c43 --- /dev/null +++ b/registration-processor/registration-processor-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/exception/InternalAuthDeligateAppException.java @@ -0,0 +1,105 @@ +package io.mosip.registration.processor.status.exception; + +import io.mosip.kernel.core.exception.BaseUncheckedException; +import io.mosip.registration.processor.core.exception.util.PlatformErrorMessages; + + +public class InternalAuthDeligateAppException extends BaseUncheckedException{ + /** The Constant serialVersionUID. */ + private static final long serialVersionUID = 6748760277721155095L; + + /** The id. */ + private String id; + + /** + * Gets the id. + * + * @return the id + */ + public String getId() { + return id; + } + + /** + * Instantiates a new id repo app exception. + */ + public InternalAuthDeligateAppException() { + super(); + } + + /** + * Instantiates a new id repo app exception. + * + * @param errorCode the error code + * @param errorMessage the error message + */ + public InternalAuthDeligateAppException(String errorCode, String errorMessage) { + super(errorCode, errorMessage); + } + + /** + * Instantiates a new id repo app exception. + * + * @param errorCode the error code + * @param errorMessage the error message + * @param rootCause the root cause + */ + public InternalAuthDeligateAppException(String errorCode, String errorMessage, Throwable rootCause) { + super(errorCode, errorMessage, rootCause); + } + + /** + * Instantiates a new id repo app exception. + * + * @param errorCode the error code + * @param errorMessage the error message + * @param rootCause the root cause + * @param id the id + */ + public InternalAuthDeligateAppException(String errorCode, String errorMessage, Throwable rootCause, String id) { + super(errorCode, errorMessage, rootCause); + this.id = id; + } + + /** + * Instantiates a new id repo app exception. + * + * @param exceptionConstant the exception constant + */ + public InternalAuthDeligateAppException(PlatformErrorMessages exceptionConstant) { + this(exceptionConstant.getCode(), exceptionConstant.getMessage()); + } + + /** + * Instantiates a new id repo app exception. + * + * @param exceptionConstant the exception constant + * @param rootCause the root cause + */ + public InternalAuthDeligateAppException(PlatformErrorMessages exceptionConstant, Throwable rootCause) { + this(exceptionConstant.getCode(), exceptionConstant.getMessage(), rootCause); + } + + /** + * Instantiates a new id repo app exception. + * + * @param exceptionConstant the exception constant + * @param id the id + */ + public InternalAuthDeligateAppException(PlatformErrorMessages exceptionConstant, String id) { + this(exceptionConstant.getCode(), exceptionConstant.getMessage()); + this.id = id; + } + + /** + * Instantiates a new id repo app exception. + * + * @param exceptionConstant the exception constant + * @param rootCause the root cause + * @param id the id + */ + public InternalAuthDeligateAppException(PlatformErrorMessages exceptionConstant, Throwable rootCause, String id) { + this(exceptionConstant.getCode(), exceptionConstant.getMessage(), rootCause); + this.id = id; + } +} diff --git a/registration-processor/registration-processor-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/repositary/RegistrationRepositary.java b/registration-processor/registration-processor-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/repositary/RegistrationRepositary.java index 7f2819ad52a..73cacb1a5d7 100644 --- a/registration-processor/registration-processor-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/repositary/RegistrationRepositary.java +++ b/registration-processor/registration-processor-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/repositary/RegistrationRepositary.java @@ -26,9 +26,10 @@ @Repository public interface RegistrationRepositary extends BaseRepository { - @Query("SELECT registration.regId FROM RegistrationStatusEntity registration WHERE registration.regId in :regIds AND registration.latestTransactionStatusCode =:statusCode") + + @Query("SELECT registration.regId FROM RegistrationStatusEntity registration WHERE registration.regId in :regIds AND registration.statusCode in :statusCode") public List getProcessedOrProcessingRegIds(@Param("regIds") List regIds, - @Param("statusCode") String statusCode); + @Param("statusCode") List statusCode); @Query("SELECT registration.regId FROM RegistrationStatusEntity registration WHERE registration.regId in :regIds AND registration.statusCode !=:statusCode1 AND registration.statusCode !=:statusCode2") public List getWithoutStatusCodes(@Param("regIds") List regIds, @@ -52,11 +53,11 @@ public List getWithoutStatusCodes(@Param("regIds") List regIds, @Query("SELECT registration FROM RegistrationStatusEntity registration WHERE registration.id.workflowInstanceId = :workflowInstanceId AND registration.isDeleted =false AND registration.isActive=true") public List findByWorkflowInstanceId(@Param("workflowInstanceId") String workflowInstanceId); - @Query(value ="SELECT * FROM registration r WHERE r.latest_trn_status_code IN :status AND r.reg_process_retry_count<=:reprocessCount AND r.latest_trn_dtimes <:timeDifference AND r.status_code NOT IN :statusCodes LIMIT :fetchSize ", nativeQuery = true) - public List getUnProcessedPackets(@Param("status") List status,@Param("reprocessCount") Integer reprocessCount,@Param("timeDifference") LocalDateTime timeDifference,@Param("statusCodes") List statusCodes,@Param("fetchSize") Integer fetchSize ); + @Query(value ="SELECT * FROM registration r WHERE r.latest_trn_status_code IN :status AND r.reg_process_retry_count<=:reprocessCount AND r.latest_trn_dtimes <:timeDifference AND r.status_code NOT IN :statusCodes AND r.reg_stage_name NOT IN :excludeStageNames LIMIT :fetchSize ", nativeQuery = true) + public List getUnProcessedPackets(@Param("status") List status,@Param("reprocessCount") Integer reprocessCount,@Param("timeDifference") LocalDateTime timeDifference,@Param("statusCodes") List statusCodes,@Param("fetchSize") Integer fetchSize,@Param("excludeStageNames") List excludeStageNames); - @Query("SELECT COUNT(*) FROM RegistrationStatusEntity registration WHERE registration.latestTransactionStatusCode IN :status AND registration.regProcessRetryCount<=:reprocessCount AND registration.latestTransactionTimes<:timeDifference AND registration.statusCode NOT IN :statusCodes ") - public int getUnProcessedPacketsCount(@Param("status") List status,@Param("reprocessCount") Integer reprocessCount,@Param("timeDifference") LocalDateTime timeDifference,@Param("statusCodes") List statusCodes ); + @Query("SELECT COUNT(*) FROM RegistrationStatusEntity registration WHERE registration.latestTransactionStatusCode IN :status AND registration.regProcessRetryCount<=:reprocessCount AND registration.latestTransactionTimes<:timeDifference AND registration.statusCode NOT IN :statusCodes AND registration.registrationStageName NOT IN :excludeStageNames") + public int getUnProcessedPacketsCount(@Param("status") List status,@Param("reprocessCount") Integer reprocessCount,@Param("timeDifference") LocalDateTime timeDifference,@Param("statusCodes") List statusCodes,@Param("excludeStageNames") List excludeStageNames); @Query(value ="SELECT * FROM registration r WHERE r.status_code IN :statusCodes AND r.resume_timestamp < now() AND r.default_resume_action is NOT NULL order by r.upd_dtimes LIMIT :fetchSize ", nativeQuery = true) public List getActionablePausedPackets(@Param("statusCodes") List statusCodes,@Param("fetchSize") Integer fetchSize); diff --git a/registration-processor/registration-processor-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/service/RegistrationStatusService.java b/registration-processor/registration-processor-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/service/RegistrationStatusService.java index fef93096d97..ac9e84d9b29 100644 --- a/registration-processor/registration-processor-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/service/RegistrationStatusService.java +++ b/registration-processor/registration-processor-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/service/RegistrationStatusService.java @@ -115,10 +115,12 @@ public interface RegistrationStatusService { * the reprocess count * @param status * the status + * @param excludeStageNames + * the exclude stage names * @return the un processed packets */ public List getUnProcessedPackets(Integer fetchSize, long elapseTime, Integer reprocessCount, - List status); + List status, List excludeStageNames); /** * Gets the un processed packets count. @@ -129,9 +131,12 @@ public List getUnProcessedPackets(Integer fetchSize, long elapseTime, Integer * the reprocess count * @param status * the status + * @param excludeStageNames + * the exclude stage names * @return the un processed packets count */ - public Integer getUnProcessedPacketsCount(long elapseTime, Integer reprocessCount, List status); + public Integer getUnProcessedPacketsCount(long elapseTime, Integer reprocessCount, List status, + List excludeStageNames); /** * Check Rid if uin is available. @@ -159,4 +164,4 @@ public List getUnProcessedPackets(Integer fetchSize, long elapseTime, Integer public List getResumablePackets(Integer fetchSize); -} \ No newline at end of file +} 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 41a591c712f..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 @@ -17,6 +17,8 @@ import org.springframework.web.client.RestTemplate; import org.springframework.web.util.UriComponentsBuilder; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import io.mosip.kernel.core.logger.spi.Logger; @@ -41,19 +43,19 @@ */ @Component public class InternalAuthDelegateServiceImpl implements InternalAuthDelegateService { - + private final Logger logger = RegProcessorLogger.getLogger(InternalAuthDelegateServiceImpl.class); private static final String REFERENCE_ID = "referenceId"; private static final String APPLICATION_ID = "applicationId"; - + private static final String APPID = "regproc"; /** The rest api client. */ @Autowired private RestApiClient restApiClient; - + @Autowired RegistrationProcessorRestClientService restClientService; @@ -64,21 +66,21 @@ public class InternalAuthDelegateServiceImpl implements InternalAuthDelegateServ /** The internal auth uri. */ @Value("${ida-internal-auth-uri}") private String internalAuthUri; - + /** The get certificate uri. */ @Value("${ida-internal-get-certificate-uri}") private String getCertificateUri; - + @Autowired ObjectMapper mapper; - + /** * Authenticate. * * @param authRequestDTO the auth request DTO - * @param headers the headers + * @param headers the headers * @return the AuthResponseDTO - * @throws Exception + * @throws Exception */ @Override public AuthResponseDTO authenticate(AuthRequestDTO authRequestDTO, HttpHeaders headers) throws Exception { @@ -100,19 +102,21 @@ public AuthResponseDTO authenticate(AuthRequestDTO authRequestDTO, HttpHeaders h * * @param applicationId the application id * @param referenceId the reference id - * @param headers the headers + * @param headers the headers * @return the certificate - * @throws Exception + * @throws Exception */ @Override - public Object getCertificate(String applicationId, Optional referenceId, HttpHeaders headers) throws Exception { + public Object getCertificate(String applicationId, Optional referenceId, HttpHeaders headers) + throws Exception { UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(getCertificateUri); builder.queryParam(APPLICATION_ID, applicationId); referenceId.ifPresent(refId -> builder.queryParam(REFERENCE_ID, refId)); return restApiClient.getApi(builder.build().toUri(), Object.class); } - - public HttpEntity postApi(String uri, MediaType mediaType, HttpEntity requestEntity, Class responseClass) throws Exception { + + public HttpEntity postApi(String uri, MediaType mediaType, HttpEntity requestEntity, + Class responseClass) throws Exception { try { logger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), uri); @@ -124,7 +128,7 @@ public HttpEntity postApi(String uri, MediaType mediaType, HttpEntity throw e; } } - + /** * get the individualId by userid * @@ -142,18 +146,26 @@ private String getIndividualIdByUserId(String userid) throws ApisResourceAccessE pathSegments.add(userid); String individualId = null; ResponseWrapper response = null; - response = (ResponseWrapper) restClientService.getApi(ApiName.GETINDIVIDUALIDFROMUSERID, pathSegments, "", - "", ResponseWrapper.class); - logger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", - "getIndividualIdByUserId called for with GETINDIVIDUALIDFROMUSERID GET service call ended successfully"); - if (response.getErrors() != null) { + try { + response = (ResponseWrapper) restClientService.getApi(ApiName.GETINDIVIDUALIDFROMUSERID, pathSegments, "", + "", ResponseWrapper.class); + logger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", + "getIndividualIdByUserId called for with GETINDIVIDUALIDFROMUSERID GET service call ended successfully"); + if (response.getErrors() != null) { + throw new ApisResourceAccessException( + PlatformErrorMessages.LINK_FOR_USERID_INDIVIDUALID_FAILED_STATUS_EXCEPTION.getMessage()); + } else { + IndividualIdDto readValue = mapper.readValue(mapper.writeValueAsString(response.getResponse()), + IndividualIdDto.class); + individualId = readValue.getIndividualId(); + } + } catch (ApisResourceAccessException e) { throw new ApisResourceAccessException( - PlatformErrorMessages.LINK_FOR_USERID_INDIVIDUALID_FAILED_STATUS_EXCEPTION.getMessage()); - } else { - IndividualIdDto readValue = mapper.readValue(mapper.writeValueAsString(response.getResponse()), - IndividualIdDto.class); - individualId = readValue.getIndividualId(); + PlatformErrorMessages.UNABLE_TO_ACCESS_API.getMessage()); + } 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-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/service/impl/RegistrationStatusServiceImpl.java b/registration-processor/registration-processor-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/service/impl/RegistrationStatusServiceImpl.java index 85795e1258f..9ac0133b9f7 100644 --- a/registration-processor/registration-processor-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/service/impl/RegistrationStatusServiceImpl.java +++ b/registration-processor/registration-processor-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/service/impl/RegistrationStatusServiceImpl.java @@ -741,13 +741,13 @@ public String generateId() { * @return the un processed packets */ public List getUnProcessedPackets(Integer fetchSize, long elapseTime, - Integer reprocessCount, List status) { + Integer reprocessCount, List status, List excludeStageNames) { regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", "RegistrationStatusServiceImpl::getReprocessPacket()::entry"); try { List entityList = registrationStatusDao.getUnProcessedPackets(fetchSize, - elapseTime, reprocessCount, status); + elapseTime, reprocessCount, status, excludeStageNames); regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", "RegistrationStatusServiceImpl::getReprocessPacket()::exit"); @@ -771,12 +771,14 @@ public List getUnProcessedPackets(Integer fetchSi * getUnProcessedPacketsCount(long, java.lang.Integer, java.util.List) */ @Override - public Integer getUnProcessedPacketsCount(long elapseTime, Integer reprocessCount, List status) { + public Integer getUnProcessedPacketsCount(long elapseTime, Integer reprocessCount, List status, + List excludeStageNames) { regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", "RegistrationStatusServiceImpl::getUnProcessedPacketsCount()::entry"); try { - int count = registrationStatusDao.getUnProcessedPacketsCount(elapseTime, reprocessCount, status); + int count = registrationStatusDao.getUnProcessedPacketsCount(elapseTime, reprocessCount, status, + excludeStageNames); regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", "RegistrationStatusServiceImpl::getUnProcessedPacketsCount()::exit"); diff --git a/registration-processor/registration-processor-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/validator/LostRidRequestValidator.java b/registration-processor/registration-processor-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/validator/LostRidRequestValidator.java index 4590b6895ab..e06c459d3a4 100644 --- a/registration-processor/registration-processor-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/validator/LostRidRequestValidator.java +++ b/registration-processor/registration-processor-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/validator/LostRidRequestValidator.java @@ -97,11 +97,12 @@ public void validate(LostRidRequestDto lostRidRequestDto) */ private void validateId(String id) throws RegStatusAppException { LostRidValidationException exception = new LostRidValidationException(); - + String lostRidService=env.getProperty(REG_LOSTRID_SERVICE_ID); if (Objects.isNull(id)) { throw new RegStatusAppException(PlatformErrorMessages.RPR_RGS_MISSING_INPUT_PARAMETER_ID, exception); - } else if (StringUtils.isNotEmpty(env.getProperty(REG_LOSTRID_SERVICE_ID)) && !env.getProperty(REG_LOSTRID_SERVICE_ID).equals(id)) { + + } else if (lostRidService!=null && !lostRidService.equals(id)) { throw new RegStatusAppException(PlatformErrorMessages.RPR_RGS_INVALID_INPUT_PARAMETER_ID, exception); diff --git a/registration-processor/registration-processor-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/validator/RegistrationStatusRequestValidator.java b/registration-processor/registration-processor-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/validator/RegistrationStatusRequestValidator.java index a568a93f63e..b46323692cc 100644 --- a/registration-processor/registration-processor-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/validator/RegistrationStatusRequestValidator.java +++ b/registration-processor/registration-processor-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/validator/RegistrationStatusRequestValidator.java @@ -116,7 +116,7 @@ private void validateVersion(String ver) throws RegStatusAppException { if (Objects.isNull(ver)) { throw new RegStatusAppException(PlatformErrorMessages.RPR_RGS_MISSING_INPUT_PARAMETER_VERSION, exception); - } else if (!version.equals(ver)) { + } else if (null!=version && !version.equals(ver)) { throw new RegStatusAppException(PlatformErrorMessages.RPR_RGS_INVALID_INPUT_PARAMETER_VERSION, exception); } diff --git a/registration-processor/registration-processor-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/validator/RegistrationSyncRequestValidator.java b/registration-processor/registration-processor-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/validator/RegistrationSyncRequestValidator.java index 85bc1122a5c..ec66f0179fd 100644 --- a/registration-processor/registration-processor-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/validator/RegistrationSyncRequestValidator.java +++ b/registration-processor/registration-processor-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/validator/RegistrationSyncRequestValidator.java @@ -158,7 +158,7 @@ private boolean validateVersion(String ver, List syncResponseLi syncResponseList.add(syncResponseFailureDto); return false; - } else if (!version.equals(ver)) { + } else if (null!=version && !version.equals(ver)) { SyncResponseFailDto syncResponseFailureDto = new SyncResponseFailDto(); diff --git a/registration-processor/registration-processor-registration-status-service-impl/src/test/java/io/mosip/registration/processor/status/dao/RegistrationStatusDaoTest.java b/registration-processor/registration-processor-registration-status-service-impl/src/test/java/io/mosip/registration/processor/status/dao/RegistrationStatusDaoTest.java index 315381e8051..26ffad18bea 100644 --- a/registration-processor/registration-processor-registration-status-service-impl/src/test/java/io/mosip/registration/processor/status/dao/RegistrationStatusDaoTest.java +++ b/registration-processor/registration-processor-registration-status-service-impl/src/test/java/io/mosip/registration/processor/status/dao/RegistrationStatusDaoTest.java @@ -52,8 +52,8 @@ public void setup() { Mockito.when(registrationStatusRepositary.findByWorkflowInstanceId(Matchers.any())).thenReturn(list); Mockito.when(registrationStatusRepositary.getActionablePausedPackets(Matchers.any(),Matchers.any())).thenReturn(list); Mockito.when(registrationStatusRepositary.getResumablePackets(Matchers.any(),Matchers.any())).thenReturn(list); - Mockito.when(registrationStatusRepositary.getUnProcessedPacketsCount(Matchers.any(),Matchers.any(),Matchers.any(),Matchers.any())).thenReturn(1); - Mockito.when(registrationStatusRepositary.getUnProcessedPackets(Matchers.any(),Matchers.any(),Matchers.any(),Matchers.any(),Matchers.any())).thenReturn(list); + Mockito.when(registrationStatusRepositary.getUnProcessedPacketsCount(Matchers.any(),Matchers.any(),Matchers.any(),Matchers.any(),Matchers.any())).thenReturn(1); + Mockito.when(registrationStatusRepositary.getUnProcessedPackets(Matchers.any(),Matchers.any(),Matchers.any(),Matchers.any(),Matchers.any(),Matchers.any())).thenReturn(list); } @Test @@ -110,8 +110,10 @@ public void update() { public void testgetUnProcessedPackets() { List statusList = new ArrayList<>(); statusList.add("SUCCESS"); + List excludeStageNames = new ArrayList<>(); + excludeStageNames.add("PacketReceiverStage"); List rEntityList = registrationStatusDao.getUnProcessedPackets(2, 60000, 4, - statusList); + statusList, excludeStageNames); assertEquals(list, rEntityList); } @@ -119,9 +121,11 @@ public void testgetUnProcessedPackets() { public void testgetUnProcessedPacketCount() { List statusList = new ArrayList<>(); statusList.add("SUCCESS"); + List excludeStageNames = new ArrayList<>(); + excludeStageNames.add("PacketReceiverStage"); int entityCount = list.size(); - int count = registrationStatusDao.getUnProcessedPacketsCount(6000, 4, statusList); + int count = registrationStatusDao.getUnProcessedPacketsCount(6000, 4, statusList, excludeStageNames); assertEquals(count, entityCount); } diff --git a/registration-processor/registration-processor-registration-status-service-impl/src/test/java/io/mosip/registration/processor/status/decryptor/DecryptorTest.java b/registration-processor/registration-processor-registration-status-service-impl/src/test/java/io/mosip/registration/processor/status/decryptor/DecryptorTest.java index 05202e88400..95261303357 100644 --- a/registration-processor/registration-processor-registration-status-service-impl/src/test/java/io/mosip/registration/processor/status/decryptor/DecryptorTest.java +++ b/registration-processor/registration-processor-registration-status-service-impl/src/test/java/io/mosip/registration/processor/status/decryptor/DecryptorTest.java @@ -1,21 +1,20 @@ package io.mosip.registration.processor.status.decryptor; import static org.junit.Assert.assertEquals; +import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Matchers.any; import static org.mockito.Mockito.when; - +import io.mosip.registration.processor.core.common.rest.dto.ErrorDTO; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; +import java.util.ArrayList; import java.util.LinkedHashMap; +import java.util.List; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import io.mosip.kernel.core.util.CryptoUtil; -import io.mosip.registration.processor.status.dto.DecryptResponseDto; import org.junit.Before; +import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; @@ -29,11 +28,14 @@ import org.springframework.web.client.HttpClientErrorException; import org.springframework.web.client.HttpServerErrorException; +import com.fasterxml.jackson.databind.ObjectMapper; + +import io.mosip.kernel.core.util.CryptoUtil; import io.mosip.registration.processor.core.exception.ApisResourceAccessException; import io.mosip.registration.processor.core.http.ResponseWrapper; import io.mosip.registration.processor.core.spi.restclient.RegistrationProcessorRestClientService; import io.mosip.registration.processor.rest.client.audit.builder.AuditLogRequestBuilder; -import io.mosip.registration.processor.status.dto.CryptomanagerResponseDto; +import io.mosip.registration.processor.status.dto.DecryptResponseDto; import io.mosip.registration.processor.status.exception.PacketDecryptionFailureException; @RunWith(PowerMockRunner.class) @@ -104,14 +106,21 @@ public void HttpClientErrorExceptionTest() @Test(expected = PacketDecryptionFailureException.class) public void HttpServerErrorExceptionTest() throws FileNotFoundException, ApisResourceAccessException, PacketDecryptionFailureException { - + List errors=new ArrayList<>(); + ErrorDTO e=new ErrorDTO("HttpStatus.INTERNAL_SERVER_ERROR", "KER-FSE-004:encrypted data is corrupted or not base64 encoded"); + errors.add(e); + ResponseWrapper response = new ResponseWrapper<>(); + response.setResponse(null); + response.setErrors(errors); + + 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"); Mockito.when(apisResourceAccessException.getCause()).thenReturn(httpServerErrorException); - Mockito.when(restClientService.postApi(any(), any(), any(), any(), any())) - .thenThrow(apisResourceAccessException); - + Mockito.when(restClientService.postApi(any(), any(), any(), any(), any())) + .thenReturn(response); + String decryptedString = decryptor.decrypt(data, "10011", "2019-05-07T05:13:55.704Z"); } diff --git a/registration-processor/registration-processor-registration-status-service-impl/src/test/java/io/mosip/registration/processor/status/encryptor/EncryptorTest.java b/registration-processor/registration-processor-registration-status-service-impl/src/test/java/io/mosip/registration/processor/status/encryptor/EncryptorTest.java index 6aac0a48517..9540b913d7c 100644 --- a/registration-processor/registration-processor-registration-status-service-impl/src/test/java/io/mosip/registration/processor/status/encryptor/EncryptorTest.java +++ b/registration-processor/registration-processor-registration-status-service-impl/src/test/java/io/mosip/registration/processor/status/encryptor/EncryptorTest.java @@ -7,6 +7,8 @@ import java.io.FileNotFoundException; import java.io.IOException; +import java.util.ArrayList; +import java.util.List; import com.fasterxml.jackson.databind.ObjectMapper; import io.mosip.kernel.core.util.CryptoUtil; @@ -27,6 +29,7 @@ import org.springframework.web.client.HttpClientErrorException; import org.springframework.web.client.HttpServerErrorException; +import io.mosip.registration.processor.core.common.rest.dto.ErrorDTO; import io.mosip.registration.processor.core.exception.ApisResourceAccessException; import io.mosip.registration.processor.core.http.ResponseWrapper; import io.mosip.registration.processor.core.spi.restclient.RegistrationProcessorRestClientService; @@ -61,7 +64,7 @@ public class EncryptorTest { public void setup() throws FileNotFoundException { PowerMockito.mockStatic(CryptoUtil.class); PowerMockito.when(CryptoUtil.decodeURLSafeBase64(anyString())).thenReturn("mosip".getBytes()); - data = "bW9zaXA"; + data = "bW9zaXA="; cryptomanagerResponseDto = new DecryptResponseDto(); cryptomanagerResponseDto.setData(data); when(env.getProperty("mosip.registration.processor.crypto.decrypt.id")) @@ -74,7 +77,7 @@ public void setup() throws FileNotFoundException { @Test public void encryptTest() throws EncryptionFailureException, ApisResourceAccessException, IOException { DecryptResponseDto cryptomanagerResponseDto = new DecryptResponseDto(); - cryptomanagerResponseDto.setData("mosip"); + cryptomanagerResponseDto.setData("bW9zaXA="); ResponseWrapper response = new ResponseWrapper<>(); response.setResponse(cryptomanagerResponseDto); Mockito.when(restClientService.postApi(any(), any(), any(), any(), any())).thenReturn(response); @@ -98,13 +101,19 @@ public void httpClientErrorExceptionTest() @Test(expected = EncryptionFailureException.class) public void httpServerErrorExceptionTest() throws FileNotFoundException, ApisResourceAccessException, EncryptionFailureException { - + List errors=new ArrayList<>(); + ErrorDTO e=new ErrorDTO("HttpStatus.INTERNAL_SERVER_ERROR", "KER-FSE-004:encrypted data is corrupted or not base64 encoded"); + errors.add(e); + ResponseWrapper response = new ResponseWrapper<>(); + response.setResponse(null); + response.setErrors(errors); + ApisResourceAccessException apisResourceAccessException = Mockito.mock(ApisResourceAccessException.class); HttpServerErrorException httpServerErrorException = new HttpServerErrorException( HttpStatus.INTERNAL_SERVER_ERROR, "KER-FSE-004:Data is corrupted or not base64 encoded"); Mockito.when(apisResourceAccessException.getCause()).thenReturn(httpServerErrorException); Mockito.when(restClientService.postApi(any(), any(), any(), any(), any())) - .thenThrow(apisResourceAccessException); + .thenReturn(response); encryptor.encrypt(data, "10011", "2019-05-07T05:13:55.704Z"); } diff --git a/registration-processor/registration-processor-registration-status-service-impl/src/test/java/io/mosip/registration/processor/status/service/RegistrationStatusServiceTest.java b/registration-processor/registration-processor-registration-status-service-impl/src/test/java/io/mosip/registration/processor/status/service/RegistrationStatusServiceTest.java index d5bd15c550b..0e2490e5432 100644 --- a/registration-processor/registration-processor-registration-status-service-impl/src/test/java/io/mosip/registration/processor/status/service/RegistrationStatusServiceTest.java +++ b/registration-processor/registration-processor-registration-status-service-impl/src/test/java/io/mosip/registration/processor/status/service/RegistrationStatusServiceTest.java @@ -469,8 +469,10 @@ public void testGetUnProcessedPacketsCount() { List statusList = new ArrayList<>(); statusList.add("SUCCESS"); statusList.add("REPROCESS"); - Mockito.when(registrationStatusDao.getUnProcessedPacketsCount(anyLong(), anyInt(), anyList())).thenReturn(1); - int packetCount = registrationStatusService.getUnProcessedPacketsCount(21600, 3, statusList); + List excludeStageNames = new ArrayList<>(); + excludeStageNames.add("PacketReceiverStage"); + Mockito.when(registrationStatusDao.getUnProcessedPacketsCount(anyLong(), anyInt(), anyList(), anyList())).thenReturn(1); + int packetCount = registrationStatusService.getUnProcessedPacketsCount(21600, 3, statusList, excludeStageNames); assertEquals(1, packetCount); } @@ -480,10 +482,12 @@ public void testGetUnProcessedPackets() { List statusList = new ArrayList<>(); statusList.add("SUCCESS"); statusList.add("REPROCESS"); - Mockito.when(registrationStatusDao.getUnProcessedPackets(anyInt(), anyLong(), anyInt(), anyList())) + List excludeStageNames = new ArrayList<>(); + excludeStageNames.add("PacketReceiverStage"); + Mockito.when(registrationStatusDao.getUnProcessedPackets(anyInt(), anyLong(), anyInt(), anyList(), anyList())) .thenReturn(entities); List dtolist = registrationStatusService.getUnProcessedPackets(1, 21600, 3, - statusList); + statusList, excludeStageNames); assertEquals("REPROCESS", dtolist.get(0).getLatestTransactionStatusCode()); } @@ -510,23 +514,27 @@ public void testGetPausedPacketsFailure() { public void getUnProcessedPacketsCountFailureTest() { List statusList = new ArrayList<>(); statusList.add("SUCCESS"); + List excludeStageNames = new ArrayList<>(); + excludeStageNames.add("PacketReceiverStage"); DataAccessLayerException exp = new DataAccessLayerException(HibernateErrorCode.ERR_DATABASE.getErrorCode(), "errorMessage", new Exception()); - Mockito.when(registrationStatusDao.getUnProcessedPacketsCount(anyLong(), anyInt(), anyList())).thenThrow(exp); + Mockito.when(registrationStatusDao.getUnProcessedPacketsCount(anyLong(), anyInt(), anyList(), anyList())).thenThrow(exp); - registrationStatusService.getUnProcessedPacketsCount(21600, 3, statusList); + registrationStatusService.getUnProcessedPacketsCount(21600, 3, statusList, excludeStageNames); } @Test(expected = TablenotAccessibleException.class) public void getUnProcessedPacketsFailureTest() { List statusList = new ArrayList<>(); statusList.add("SUCCESS"); + List excludeStageNames = new ArrayList<>(); + excludeStageNames.add("PacketReceiverStage"); DataAccessLayerException exp = new DataAccessLayerException(HibernateErrorCode.ERR_DATABASE.getErrorCode(), "errorMessage", new Exception()); - Mockito.when(registrationStatusDao.getUnProcessedPackets(anyInt(), anyLong(), anyInt(), anyList())) + Mockito.when(registrationStatusDao.getUnProcessedPackets(anyInt(), anyLong(), anyInt(), anyList(), anyList())) .thenThrow(exp); - registrationStatusService.getUnProcessedPackets(1, 21600, 3, statusList); + registrationStatusService.getUnProcessedPackets(1, 21600, 3, statusList, excludeStageNames); } @Test diff --git a/registration-processor/registration-processor-rest-client/pom.xml b/registration-processor/registration-processor-rest-client/pom.xml index bdd642bd8b4..6212b77b589 100644 --- a/registration-processor/registration-processor-rest-client/pom.xml +++ b/registration-processor/registration-processor-rest-client/pom.xml @@ -9,12 +9,12 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-B1 + 1.2.0.1-B3-SNAPSHOT registration-processor-rest-client registration-processor-rest-client - 1.2.0.1-B1 + 1.2.0.1-B3-SNAPSHOT UTF-8 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 9fdd16c0660..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,6 +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 ccf2d90853f..447554f17de 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 @@ -2,32 +2,21 @@ import java.io.IOException; import java.net.URI; -import java.security.KeyManagementException; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; -import java.security.cert.X509Certificate; -import java.util.Arrays; import java.util.Iterator; +import java.util.List; -import javax.annotation.PostConstruct; -import javax.net.ssl.SSLContext; - -import io.mosip.registration.processor.core.tracing.ContextualData; -import io.mosip.registration.processor.core.tracing.TracingConstant; 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; import org.apache.http.client.methods.HttpPost; -import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.entity.StringEntity; -import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.impl.client.HttpClients; -import org.apache.http.ssl.TrustStrategy; import org.apache.http.util.EntityUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.context.annotation.Lazy; @@ -38,14 +27,13 @@ import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; -import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; import org.springframework.stereotype.Component; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.client.HttpStatusCodeException; import org.springframework.web.client.RestTemplate; -import com.google.gson.Gson; +import com.fasterxml.jackson.databind.ObjectMapper; import io.mosip.kernel.core.logger.spi.Logger; import io.mosip.kernel.core.util.DateUtils; @@ -53,6 +41,8 @@ import io.mosip.kernel.core.util.TokenHandlerUtil; import io.mosip.registration.processor.core.constant.LoggerFileConstant; import io.mosip.registration.processor.core.logger.RegProcessorLogger; +import io.mosip.registration.processor.core.tracing.ContextualData; +import io.mosip.registration.processor.core.tracing.TracingConstant; import io.mosip.registration.processor.rest.client.audit.dto.Metadata; import io.mosip.registration.processor.rest.client.audit.dto.SecretKeyRequest; import io.mosip.registration.processor.rest.client.audit.dto.TokenRequestDTO; @@ -88,6 +78,9 @@ public class RestApiClient { @Qualifier("selfTokenRestTemplate") RestTemplate localRestTemplate; + @Autowired + ObjectMapper objMp; + /** * Gets the api. * * @@ -100,6 +93,7 @@ public class RestApiClient { @SuppressWarnings("unchecked") public T getApi(URI uri, Class responseType) throws Exception { T result = null; + try { result = (T) localRestTemplate.exchange(uri, HttpMethod.GET, setRequestHeader(null, null), responseType) .getBody(); @@ -231,7 +225,7 @@ public RestTemplate getRestTemplate() { @SuppressWarnings("unchecked") private HttpEntity setRequestHeader(Object requestType, MediaType mediaType) throws IOException { MultiValueMap headers = new LinkedMultiValueMap(); - //headers.add("Cookie", getToken()); + // headers.add("Cookie", getToken()); headers.add(TracingConstant.TRACE_HEADER, (String) ContextualData.getOrDefault(TracingConstant.TRACE_ID_KEY)); if (mediaType != null) { headers.add("Content-Type", mediaType.toString()); @@ -243,8 +237,11 @@ private HttpEntity setRequestHeader(Object requestType, MediaType mediaT Iterator iterator = httpHeader.keySet().iterator(); while (iterator.hasNext()) { String key = iterator.next(); - if (!(headers.containsKey("Content-Type") && key == "Content-Type")) - headers.add(key, httpHeader.get(key).get(0)); + List collection = httpHeader.get(key); + if ((collection != null && !collection.isEmpty()) + && !(headers.containsKey("Content-Type") && key.equalsIgnoreCase("Content-Type"))) + headers.add(key, collection.get(0)); + } return new HttpEntity(httpEntity.getBody(), headers); } catch (ClassCastException e) { @@ -280,11 +277,10 @@ public String getToken() throws IOException { tokenRequestDTO.setRequest(setSecretKeyRequestDTO()); tokenRequestDTO.setVersion(environment.getProperty("token.request.version")); - Gson gson = new Gson(); HttpClient httpClient = HttpClientBuilder.create().build(); HttpPost post = new HttpPost(environment.getProperty("KEYBASEDTOKENAPI")); try { - StringEntity postingString = new StringEntity(gson.toJson(tokenRequestDTO)); + StringEntity postingString = new StringEntity(objMp.writeValueAsString(tokenRequestDTO)); post.setEntity(postingString); post.setHeader("Content-type", "application/json"); post.setHeader(TracingConstant.TRACE_HEADER, diff --git a/registration-processor/stage-groups/pom.xml b/registration-processor/stage-groups/pom.xml index f1dbd341adb..c4dfa81acd5 100644 --- a/registration-processor/stage-groups/pom.xml +++ b/registration-processor/stage-groups/pom.xml @@ -7,9 +7,9 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-B1 + 1.2.0.1-B3-SNAPSHOT - 1.2.0.1-B1 + 1.2.0.1-B3-SNAPSHOT stage-groups stage-groups diff --git a/registration-processor/stage-groups/registration-processor-stage-group-1/Dockerfile b/registration-processor/stage-groups/registration-processor-stage-group-1/Dockerfile index d63cca0a140..ec2ac197d25 100644 --- a/registration-processor/stage-groups/registration-processor-stage-group-1/Dockerfile +++ b/registration-processor/stage-groups/registration-processor-stage-group-1/Dockerfile @@ -76,7 +76,7 @@ ARG regproc_jars ENV regproc_jars_env=${regproc_jars} # change volume to whichever storage directory you want to use for this container. -VOLUME /home/logs +VOLUME /home/logs /home/ftp1/ARCHIVE_PACKET_LOCATION /home/ftp1/LANDING_ZONE ENV group_name=registration-processor-stage-group-1 diff --git a/registration-processor/stage-groups/registration-processor-stage-group-1/pom.xml b/registration-processor/stage-groups/registration-processor-stage-group-1/pom.xml index ed78ae79825..dfc3eaa5792 100644 --- a/registration-processor/stage-groups/registration-processor-stage-group-1/pom.xml +++ b/registration-processor/stage-groups/registration-processor-stage-group-1/pom.xml @@ -5,11 +5,11 @@ io.mosip.registrationprocessor stage-groups - 1.2.0.1-B1 + 1.2.0.1-B3-SNAPSHOT registration-processor-stage-group-1 - 1.2.0.1-B1 + 1.2.0.1-B3-SNAPSHOT UTF-8 @@ -21,14 +21,14 @@ io.mosip.registrationprocessor mosip-stage-executor - 1.2.0.1-B1 + 1.2.0.1-B3-SNAPSHOT io.mosip.registrationprocessor registration-processor-packet-receiver-stage - 1.2.0.1-B1 + 1.2.0.1-B3-SNAPSHOT diff --git a/registration-processor/stage-groups/registration-processor-stage-group-2/pom.xml b/registration-processor/stage-groups/registration-processor-stage-group-2/pom.xml index ada325f055d..0be16124bdf 100644 --- a/registration-processor/stage-groups/registration-processor-stage-group-2/pom.xml +++ b/registration-processor/stage-groups/registration-processor-stage-group-2/pom.xml @@ -5,11 +5,11 @@ io.mosip.registrationprocessor stage-groups - 1.2.0.1-B1 + 1.2.0.1-B3-SNAPSHOT registration-processor-stage-group-2 - 1.2.0.1-B1 + 1.2.0.1-B3-SNAPSHOT UTF-8 @@ -21,24 +21,24 @@ io.mosip.registrationprocessor mosip-stage-executor - 1.2.0.1-B1 + 1.2.0.1-B3-SNAPSHOT io.mosip.registrationprocessor registration-processor-quality-classifier-stage - 1.2.0.1-B1 + 1.2.0.1-B3-SNAPSHOT io.mosip.registrationprocessor registration-processor-securezone-notification-stage - 1.2.0.1-B1 + 1.2.0.1-B3-SNAPSHOT io.mosip.registrationprocessor registration-processor-message-sender-stage - 1.2.0.1-B1 + 1.2.0.1-B3-SNAPSHOT diff --git a/registration-processor/stage-groups/registration-processor-stage-group-3/pom.xml b/registration-processor/stage-groups/registration-processor-stage-group-3/pom.xml index e1de3540c1d..ee2b4a7f84c 100644 --- a/registration-processor/stage-groups/registration-processor-stage-group-3/pom.xml +++ b/registration-processor/stage-groups/registration-processor-stage-group-3/pom.xml @@ -1,75 +1,75 @@ - - - 4.0.0 - - io.mosip.registrationprocessor - stage-groups - 1.2.0.1-B1 - - - registration-processor-stage-group-3 - 1.2.0.1-B1 - - - UTF-8 - - - - - - - io.mosip.registrationprocessor - mosip-stage-executor - 1.2.0.1-B1 - - - - - io.mosip.registrationprocessor - registration-processor-abis-handler-stage - 1.2.0.1-B1 - - - io.mosip.registrationprocessor - registration-processor-abis-middleware-stage - 1.2.0.1-B1 - - - io.mosip.registrationprocessor - registration-processor-bio-dedupe-stage - 1.2.0.1-B1 - - - io.mosip.registrationprocessor - registration-processor-manual-adjudication-stage - 1.2.0.1-B1 - - - - - - - - - - org.springframework.boot - spring-boot-maven-plugin - ${spring.boot.version} - - true - io.mosip.registration.processor.stages.executor.MosipStageExecutorApplication - ZIP - - - - - build-info - repackage - - - - - - + + + 4.0.0 + + io.mosip.registrationprocessor + stage-groups + 1.2.0.1-B3-SNAPSHOT + + + registration-processor-stage-group-3 + 1.2.0.1-B3-SNAPSHOT + + + UTF-8 + + + + + + + io.mosip.registrationprocessor + mosip-stage-executor + 1.2.0.1-B3-SNAPSHOT + + + + + io.mosip.registrationprocessor + registration-processor-abis-handler-stage + 1.2.0.1-B3-SNAPSHOT + + + io.mosip.registrationprocessor + registration-processor-abis-middleware-stage + 1.2.0.1-B3-SNAPSHOT + + + io.mosip.registrationprocessor + registration-processor-bio-dedupe-stage + 1.2.0.1-B3-SNAPSHOT + + + io.mosip.registrationprocessor + registration-processor-manual-adjudication-stage + 1.2.0.1-B3-SNAPSHOT + + + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + ${spring.boot.version} + + true + io.mosip.registration.processor.stages.executor.MosipStageExecutorApplication + ZIP + + + + + build-info + repackage + + + + + + \ No newline at end of file diff --git a/registration-processor/stage-groups/registration-processor-stage-group-4/pom.xml b/registration-processor/stage-groups/registration-processor-stage-group-4/pom.xml index 85e97e9dee6..3c50b67a2fa 100644 --- a/registration-processor/stage-groups/registration-processor-stage-group-4/pom.xml +++ b/registration-processor/stage-groups/registration-processor-stage-group-4/pom.xml @@ -1,65 +1,65 @@ - - - 4.0.0 - - io.mosip.registrationprocessor - stage-groups - 1.2.0.1-B1 - - - registration-processor-stage-group-4 - 1.2.0.1-B1 - - - UTF-8 - - - - - - - io.mosip.registrationprocessor - mosip-stage-executor - 1.2.0.1-B1 - - - - - io.mosip.registrationprocessor - registration-processor-biometric-authentication-stage - 1.2.0.1-B1 - - - io.mosip.registrationprocessor - registration-processor-demo-dedupe-stage - 1.2.0.1-B1 - - - - - - - - - - org.springframework.boot - spring-boot-maven-plugin - ${spring.boot.version} - - true - io.mosip.registration.processor.stages.executor.MosipStageExecutorApplication - ZIP - - - - - build-info - repackage - - - - - - + + + 4.0.0 + + io.mosip.registrationprocessor + stage-groups + 1.2.0.1-B3-SNAPSHOT + + + registration-processor-stage-group-4 + 1.2.0.1-B3-SNAPSHOT + + + UTF-8 + + + + + + + io.mosip.registrationprocessor + mosip-stage-executor + 1.2.0.1-B3-SNAPSHOT + + + + + io.mosip.registrationprocessor + registration-processor-biometric-authentication-stage + 1.2.0.1-B3-SNAPSHOT + + + io.mosip.registrationprocessor + registration-processor-demo-dedupe-stage + 1.2.0.1-B3-SNAPSHOT + + + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + ${spring.boot.version} + + true + io.mosip.registration.processor.stages.executor.MosipStageExecutorApplication + ZIP + + + + + build-info + repackage + + + + + + \ No newline at end of file diff --git a/registration-processor/stage-groups/registration-processor-stage-group-5/pom.xml b/registration-processor/stage-groups/registration-processor-stage-group-5/pom.xml index 5de03453f5f..260ab52888b 100644 --- a/registration-processor/stage-groups/registration-processor-stage-group-5/pom.xml +++ b/registration-processor/stage-groups/registration-processor-stage-group-5/pom.xml @@ -1,80 +1,80 @@ - - - 4.0.0 - - io.mosip.registrationprocessor - stage-groups - 1.2.0.1-B1 - - - registration-processor-stage-group-5 - 1.2.0.1-B1 - - - UTF-8 - - - - - - - io.mosip.registrationprocessor - mosip-stage-executor - 1.2.0.1-B1 - - - - - io.mosip.registrationprocessor - registration-processor-cmd-validator-stage - 1.2.0.1-B1 - - - io.mosip.registrationprocessor - registration-processor-operator-validator-stage - 1.2.0.1-B1 - - - io.mosip.registrationprocessor - registration-processor-supervisor-validator-stage - 1.2.0.1-B1 - - - io.mosip.registrationprocessor - registration-processor-introducer-validator-stage - 1.2.0.1-B1 - - - io.mosip.registrationprocessor - registration-processor-packet-validator-stage - 1.2.0.1-B1 - - - - - - - - - - org.springframework.boot - spring-boot-maven-plugin - ${spring.boot.version} - - true - io.mosip.registration.processor.stages.executor.MosipStageExecutorApplication - ZIP - - - - - build-info - repackage - - - - - - - + + + 4.0.0 + + io.mosip.registrationprocessor + stage-groups + 1.2.0.1-B3-SNAPSHOT + + + registration-processor-stage-group-5 + 1.2.0.1-B3-SNAPSHOT + + + UTF-8 + + + + + + + io.mosip.registrationprocessor + mosip-stage-executor + 1.2.0.1-B3-SNAPSHOT + + + + + io.mosip.registrationprocessor + registration-processor-cmd-validator-stage + 1.2.0.1-B3-SNAPSHOT + + + io.mosip.registrationprocessor + registration-processor-operator-validator-stage + 1.2.0.1-B3-SNAPSHOT + + + io.mosip.registrationprocessor + registration-processor-supervisor-validator-stage + 1.2.0.1-B3-SNAPSHOT + + + io.mosip.registrationprocessor + registration-processor-introducer-validator-stage + 1.2.0.1-B3-SNAPSHOT + + + io.mosip.registrationprocessor + registration-processor-packet-validator-stage + 1.2.0.1-B3-SNAPSHOT + + + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + ${spring.boot.version} + + true + io.mosip.registration.processor.stages.executor.MosipStageExecutorApplication + ZIP + + + + + build-info + repackage + + + + + + + diff --git a/registration-processor/stage-groups/registration-processor-stage-group-6/pom.xml b/registration-processor/stage-groups/registration-processor-stage-group-6/pom.xml index f4ce7933f7a..e3a10c28174 100644 --- a/registration-processor/stage-groups/registration-processor-stage-group-6/pom.xml +++ b/registration-processor/stage-groups/registration-processor-stage-group-6/pom.xml @@ -1,68 +1,68 @@ - - - 4.0.0 - - io.mosip.registrationprocessor - stage-groups - 1.2.0.1-B1 - - - registration-processor-stage-group-6 - 1.2.0.1-B1 - - - UTF-8 - - - - - - - io.mosip.registrationprocessor - mosip-stage-executor - 1.2.0.1-B1 - - - - - io.mosip.registrationprocessor - registration-processor-packet-uploader-stage - 1.2.0.1-B1 - - - io.mosip.registrationprocessor - registration-processor-packet-classifier-stage - 1.2.0.1-B1 - - - io.mosip.registrationprocessor - registration-processor-verification-stage - 1.2.0.1-B1 - - - - - - - - org.springframework.boot - spring-boot-maven-plugin - ${spring.boot.version} - - true - io.mosip.registration.processor.stages.executor.MosipStageExecutorApplication - ZIP - - - - - build-info - repackage - - - - - - - + + + 4.0.0 + + io.mosip.registrationprocessor + stage-groups + 1.2.0.1-B3-SNAPSHOT + + + registration-processor-stage-group-6 + 1.2.0.1-B3-SNAPSHOT + + + UTF-8 + + + + + + + io.mosip.registrationprocessor + mosip-stage-executor + 1.2.0.1-B3-SNAPSHOT + + + + + io.mosip.registrationprocessor + registration-processor-packet-uploader-stage + 1.2.0.1-B3-SNAPSHOT + + + io.mosip.registrationprocessor + registration-processor-packet-classifier-stage + 1.2.0.1-B3-SNAPSHOT + + + io.mosip.registrationprocessor + registration-processor-verification-stage + 1.2.0.1-B3-SNAPSHOT + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + ${spring.boot.version} + + true + io.mosip.registration.processor.stages.executor.MosipStageExecutorApplication + ZIP + + + + + build-info + repackage + + + + + + + diff --git a/registration-processor/stage-groups/registration-processor-stage-group-7/pom.xml b/registration-processor/stage-groups/registration-processor-stage-group-7/pom.xml index f22d032a05b..32d52f11076 100644 --- a/registration-processor/stage-groups/registration-processor-stage-group-7/pom.xml +++ b/registration-processor/stage-groups/registration-processor-stage-group-7/pom.xml @@ -1,74 +1,74 @@ - - - 4.0.0 - - io.mosip.registrationprocessor - stage-groups - 1.2.0.1-B1 - - - registration-processor-stage-group-7 - 1.2.0.1-B1 - - - UTF-8 - - - - - - - io.mosip.registrationprocessor - mosip-stage-executor - 1.2.0.1-B1 - - - - - io.mosip.registrationprocessor - registration-processor-uin-generator-stage - 1.2.0.1-B1 - - - io.mosip.registrationprocessor - registration-processor-biometric-extraction-stage - 1.2.0.1-B1 - - - io.mosip.registrationprocessor - registration-processor-finalization-stage - 1.2.0.1-B1 - - - io.mosip.registrationprocessor - registration-processor-printing-stage - 1.2.0.1-B1 - - - - - - - - - org.springframework.boot - spring-boot-maven-plugin - ${spring.boot.version} - - true - io.mosip.registration.processor.stages.executor.MosipStageExecutorApplication - ZIP - - - - - build-info - repackage - - - - - - + + + 4.0.0 + + io.mosip.registrationprocessor + stage-groups + 1.2.0.1-B3-SNAPSHOT + + + registration-processor-stage-group-7 + 1.2.0.1-B3-SNAPSHOT + + + UTF-8 + + + + + + + io.mosip.registrationprocessor + mosip-stage-executor + 1.2.0.1-B3-SNAPSHOT + + + + + io.mosip.registrationprocessor + registration-processor-uin-generator-stage + 1.2.0.1-B3-SNAPSHOT + + + io.mosip.registrationprocessor + registration-processor-biometric-extraction-stage + 1.2.0.1-B3-SNAPSHOT + + + io.mosip.registrationprocessor + registration-processor-finalization-stage + 1.2.0.1-B3-SNAPSHOT + + + io.mosip.registrationprocessor + registration-processor-printing-stage + 1.2.0.1-B3-SNAPSHOT + + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + ${spring.boot.version} + + true + io.mosip.registration.processor.stages.executor.MosipStageExecutorApplication + ZIP + + + + + build-info + repackage + + + + + + \ No newline at end of file diff --git a/registration-processor/workflow-engine/pom.xml b/registration-processor/workflow-engine/pom.xml index 7bb2d165aeb..8018afb3edd 100644 --- a/registration-processor/workflow-engine/pom.xml +++ b/registration-processor/workflow-engine/pom.xml @@ -1,20 +1,20 @@ - - - 4.0.0 - pom - - io.mosip.registrationprocessor - registration-processor - 1.2.0.1-B1 - - 1.2.0.1-B1 - workflow-engine - workflow-engine - - UTF-8 - - - registration-processor-workflow-manager-service - registration-processor-reprocessor - + + + 4.0.0 + pom + + io.mosip.registrationprocessor + registration-processor + 1.2.0.1-B3-SNAPSHOT + + 1.2.0.1-B3-SNAPSHOT + workflow-engine + workflow-engine + + UTF-8 + + + registration-processor-workflow-manager-service + registration-processor-reprocessor + \ No newline at end of file diff --git a/registration-processor/workflow-engine/registration-processor-reprocessor/pom.xml b/registration-processor/workflow-engine/registration-processor-reprocessor/pom.xml index fac36d647a2..4da4baf8baf 100644 --- a/registration-processor/workflow-engine/registration-processor-reprocessor/pom.xml +++ b/registration-processor/workflow-engine/registration-processor-reprocessor/pom.xml @@ -7,10 +7,10 @@ io.mosip.registrationprocessor workflow-engine - 1.2.0.1-B1 + 1.2.0.1-B3-SNAPSHOT registration-processor-reprocessor - 1.2.0.1-B1 + 1.2.0.1-B3-SNAPSHOT registration-processor-reprocessor UTF-8 diff --git a/registration-processor/workflow-engine/registration-processor-reprocessor/src/main/java/io/mosip/registration/processor/reprocessor/verticle/ReprocessorVerticle.java b/registration-processor/workflow-engine/registration-processor-reprocessor/src/main/java/io/mosip/registration/processor/reprocessor/verticle/ReprocessorVerticle.java index fd497b3b402..8233e09837d 100644 --- a/registration-processor/workflow-engine/registration-processor-reprocessor/src/main/java/io/mosip/registration/processor/reprocessor/verticle/ReprocessorVerticle.java +++ b/registration-processor/workflow-engine/registration-processor-reprocessor/src/main/java/io/mosip/registration/processor/reprocessor/verticle/ReprocessorVerticle.java @@ -82,6 +82,10 @@ public class ReprocessorVerticle extends MosipVerticleAPIManager { @Value("${registration.processor.reprocess.attempt.count}") private Integer reprocessCount; + /** Comman seperated stage names that should be excluded while reprocessing. */ + @Value("#{T(java.util.Arrays).asList('${mosip.registration.processor.reprocessor.exclude-stage-names:PacketReceiverStage}')}") + private List reprocessExcludeStageNames; + /** The is transaction successful. */ boolean isTransactionSuccessful; @@ -125,7 +129,7 @@ public void schedulerResult(AsyncResult res) { regProcLogger.info("ReprocessorVerticle::schedular()::deployed"); cronScheduling(vertx); } else { - regProcLogger.error("ReprocessorVerticle::schedular()::deployment failure" + res.cause().toString()); + regProcLogger.error("ReprocessorVerticle::schedular()::deployment failure " + res.cause().getMessage()); } } @@ -218,14 +222,14 @@ public MessageDTO process(MessageDTO object) { if (!CollectionUtils.isEmpty(reprocessorDtoList)) { if (reprocessorDtoList.size() < fetchSize) { List reprocessorPacketList = registrationStatusService.getUnProcessedPackets(fetchSize - reprocessorDtoList.size(), elapseTime, - reprocessCount, statusList); + reprocessCount, statusList, reprocessExcludeStageNames); if (!CollectionUtils.isEmpty(reprocessorPacketList)) { reprocessorDtoList.addAll(reprocessorPacketList); } } } else { reprocessorDtoList = registrationStatusService.getUnProcessedPackets(fetchSize, elapseTime, - reprocessCount, statusList); + reprocessCount, statusList, reprocessExcludeStageNames); } 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 4953c81cb49..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,304 +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<>(); - } - - /** - * 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(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")); - } - /** - * 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; + } + + }; + } +} diff --git a/registration-processor/workflow-engine/registration-processor-reprocessor/src/test/java/io/mosip/registration/processor/reprocessor/verticle/ReprocessorVerticleTest.java b/registration-processor/workflow-engine/registration-processor-reprocessor/src/test/java/io/mosip/registration/processor/reprocessor/verticle/ReprocessorVerticleTest.java index 30e68bf55f1..cb182bf77db 100644 --- a/registration-processor/workflow-engine/registration-processor-reprocessor/src/test/java/io/mosip/registration/processor/reprocessor/verticle/ReprocessorVerticleTest.java +++ b/registration-processor/workflow-engine/registration-processor-reprocessor/src/test/java/io/mosip/registration/processor/reprocessor/verticle/ReprocessorVerticleTest.java @@ -119,6 +119,7 @@ public void setup() throws Exception { ReflectionTestUtils.setField(reprocessorVerticle, "fetchSize", 2); ReflectionTestUtils.setField(reprocessorVerticle, "elapseTime", 21600); ReflectionTestUtils.setField(reprocessorVerticle, "reprocessCount", 3); + ReflectionTestUtils.setField(reprocessorVerticle, "reprocessExcludeStageNames", new ArrayList<>()); Field auditLog = AuditLogRequestBuilder.class.getDeclaredField("registrationProcessorRestService"); auditLog.setAccessible(true); @SuppressWarnings("unchecked") @@ -158,7 +159,7 @@ public void testProcessValid() throws TablenotAccessibleException, PacketManager registrationStatusDto1.setRegistrationType("NEW"); registrationStatusDto1.setLatestTransactionStatusCode(RegistrationTransactionStatusCode.SUCCESS.toString()); dtolist.add(registrationStatusDto1); - Mockito.when(registrationStatusService.getUnProcessedPackets(anyInt(), anyLong(), anyInt(), anyList())) + Mockito.when(registrationStatusService.getUnProcessedPackets(anyInt(), anyLong(), anyInt(), anyList(), anyList())) .thenReturn(dtolist); reprocessorVerticle.process(dto); @@ -187,7 +188,7 @@ public void testProcessFailure() throws TablenotAccessibleException, PacketManag registrationStatusDto1.setRegistrationType("NEW"); registrationStatusDto1.setLatestTransactionStatusCode(RegistrationTransactionStatusCode.SUCCESS.toString()); dtolist.add(registrationStatusDto1); - Mockito.when(registrationStatusService.getUnProcessedPackets(anyInt(), anyLong(), anyInt(), anyList())) + Mockito.when(registrationStatusService.getUnProcessedPackets(anyInt(), anyLong(), anyInt(), anyList(), anyList())) .thenReturn(dtolist); reprocessorVerticle.process(dto); @@ -201,7 +202,7 @@ public void testProcessFailure() throws TablenotAccessibleException, PacketManag */ @Test public void exceptionTest() throws Exception { - Mockito.when(registrationStatusService.getUnProcessedPackets(anyInt(),anyLong(), anyInt(), anyList())) + Mockito.when(registrationStatusService.getUnProcessedPackets(anyInt(),anyLong(), anyInt(), anyList(), anyList())) .thenReturn(null); dto = reprocessorVerticle.process(dto); assertEquals(null, dto.getIsValid()); @@ -218,7 +219,7 @@ public void nullPointerExceptionTest() throws Exception { @Test public void TablenotAccessibleExceptionTest() throws Exception { - Mockito.when(registrationStatusService.getUnProcessedPackets(anyInt(), anyLong(), anyInt(), anyList())) + Mockito.when(registrationStatusService.getUnProcessedPackets(anyInt(), anyLong(), anyInt(), anyList(), anyList())) .thenThrow(new TablenotAccessibleException("") { }); @@ -253,7 +254,7 @@ public void testProcessValidWithResumablePackets() throws TablenotAccessibleExce reprocessorDtoList.add(registrationStatusDto1); Mockito.when(registrationStatusService.getResumablePackets(anyInt())) .thenReturn(dtolist); - Mockito.when(registrationStatusService.getUnProcessedPackets(anyInt(), anyLong(), anyInt(), anyList())) + Mockito.when(registrationStatusService.getUnProcessedPackets(anyInt(), anyLong(), anyInt(), anyList(), anyList())) .thenReturn(reprocessorDtoList); reprocessorVerticle.process(dto); diff --git a/registration-processor/workflow-engine/registration-processor-workflow-manager-service/pom.xml b/registration-processor/workflow-engine/registration-processor-workflow-manager-service/pom.xml index c17473fbd1a..9c5cfc0b64e 100644 --- a/registration-processor/workflow-engine/registration-processor-workflow-manager-service/pom.xml +++ b/registration-processor/workflow-engine/registration-processor-workflow-manager-service/pom.xml @@ -5,10 +5,10 @@ io.mosip.registrationprocessor workflow-engine - 1.2.0.1-B1 + 1.2.0.1-B3-SNAPSHOT registration-processor-workflow-manager-service - 1.2.0.1-B1 + 1.2.0.1-B3-SNAPSHOT registration-processor-workflow-manager-service UTF-8 From dd12b970415b1843e60398abaf23fe97daa837fe Mon Sep 17 00:00:00 2001 From: Sowmya Ujjappa Banakar <43202851+sowmya695@users.noreply.github.com> Date: Tue, 13 Jun 2023 11:06:58 +0530 Subject: [PATCH 071/133] MOSIP- 24572 Code changes (#1717) (#1719) * MOSIP-24572 Secure this "ActiveMQConnectionFactory" by whitelisting the trusted packages using the "setTrustedPackages" method and make sure the "setTrustAllPackages" is not set to true. (#1714) * MOSIP-24572 Code fix * MOSIP-24572 fixed test cases --------- * Update push_trigger.yml * Mosip 24572 develop (#1715) * MOSIP-24572 Code fix * MOSIP-24572 fixed test cases * MOSIP-24572 Code chagnes after testing --------- * Update AbisMiddleWareStageTest.java * Mosip 24572 develop (#1716) * MOSIP-24572 Code fix * MOSIP-24572 fixed test cases * MOSIP-24572 Code chagnes after testing * MOSIP-24572 resolved sonar bug --------- * Update StageHealthCheckHandler.java * Removed branch --------- Signed-off-by: Sowmya Ujjappa Banakar <43202851+sowmya695@users.noreply.github.com> Co-authored-by: Sowmya Ujjappa Banakar --- .../stage/AbisMiddleWareStageTest.java | 7 +- .../stage/ManualAdjudicationStage.java | 467 +++---- .../ManualAdjudicationServiceTest.java | 5 +- .../stage/ManualAdjudicationStageTest.java | 1140 +++++++++-------- .../verification/stage/VerificationStage.java | 469 +++---- .../service/VerificationServiceTest.java | 11 +- .../stage/VerificationStageTest.java | 390 +++--- .../registration-processor-core/pom.xml | 4 +- .../StageHealthCheckHandler.java | 12 +- .../core/constant/HealthConstant.java | 69 +- .../core/queue/factory/MosipActiveMq.java | 13 +- .../core/queue/factory/MosipQueue.java | 5 +- .../MosipQueueConnectionFactoryImpl.java | 6 +- .../queue/MosipQueueConnectionFactory.java | 5 +- .../packet/storage/utils/Utilities.java | 6 +- 15 files changed, 1330 insertions(+), 1279 deletions(-) diff --git a/registration-processor/core-processor/registration-processor-abis-middleware-stage/src/test/java/io/mosip/registartion/processor/abis/middleware/stage/AbisMiddleWareStageTest.java b/registration-processor/core-processor/registration-processor-abis-middleware-stage/src/test/java/io/mosip/registartion/processor/abis/middleware/stage/AbisMiddleWareStageTest.java index 853e70f5531..d07567c8bf7 100644 --- a/registration-processor/core-processor/registration-processor-abis-middleware-stage/src/test/java/io/mosip/registartion/processor/abis/middleware/stage/AbisMiddleWareStageTest.java +++ b/registration-processor/core-processor/registration-processor-abis-middleware-stage/src/test/java/io/mosip/registartion/processor/abis/middleware/stage/AbisMiddleWareStageTest.java @@ -246,7 +246,8 @@ public String getQueueName() { } @Override - public void createConnection(String username, String password, String brokerUrl) { + public void createConnection(String username, String password, String brokerUrl, + List trustedPackage) { // TODO Auto-generated method stub } @@ -260,7 +261,7 @@ public String getQueueName() { } @Override - public void createConnection(String username, String password, String brokerUrl) { + public void createConnection(String username, String password, String brokerUrl,List trustedPackage) { // TODO Auto-generated method stub } @@ -696,4 +697,4 @@ public void testConsumerListenerForIdentifyReqException() throws RegistrationPro PowerMockito.when(JsonUtil.readValueWithUnknownProperties(response, AbisIdentifyResponseDto.class)).thenThrow(IOException.class); stage.consumerListener(amq, "abis1_inboundAddress", queue, evenBus, messageTTL); } -} \ 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/stage/ManualAdjudicationStage.java b/registration-processor/core-processor/registration-processor-manual-adjudication-stage/src/main/java/io/mosip/registration/processor/adjudication/stage/ManualAdjudicationStage.java index 6b7497a3538..18291d13f5c 100644 --- a/registration-processor/core-processor/registration-processor-manual-adjudication-stage/src/main/java/io/mosip/registration/processor/adjudication/stage/ManualAdjudicationStage.java +++ b/registration-processor/core-processor/registration-processor-manual-adjudication-stage/src/main/java/io/mosip/registration/processor/adjudication/stage/ManualAdjudicationStage.java @@ -1,230 +1,237 @@ -package io.mosip.registration.processor.adjudication.stage; - -import io.mosip.kernel.core.exception.ExceptionUtils; -import io.mosip.kernel.core.logger.spi.Logger; -import io.mosip.registration.processor.core.abstractverticle.MessageBusAddress; -import io.mosip.registration.processor.core.abstractverticle.MessageDTO; -import io.mosip.registration.processor.core.abstractverticle.MosipEventBus; -import io.mosip.registration.processor.core.abstractverticle.MosipRouter; -import io.mosip.registration.processor.core.abstractverticle.MosipVerticleAPIManager; -import io.mosip.registration.processor.core.constant.LoggerFileConstant; -import io.mosip.registration.processor.core.exception.util.PlatformErrorMessages; -import io.mosip.registration.processor.core.logger.RegProcessorLogger; -import io.mosip.registration.processor.core.queue.factory.MosipQueue; -import io.mosip.registration.processor.core.queue.factory.QueueListener; -import io.mosip.registration.processor.core.spi.queue.MosipQueueConnectionFactory; -import io.mosip.registration.processor.core.spi.queue.MosipQueueManager; -import io.mosip.registration.processor.core.util.JsonUtil; -import io.mosip.registration.processor.adjudication.exception.InvalidMessageException; -import io.mosip.registration.processor.adjudication.exception.handler.ManualVerificationExceptionHandler; -import io.mosip.registration.processor.adjudication.response.dto.ManualAdjudicationResponseDTO; -import io.mosip.registration.processor.adjudication.service.ManualAdjudicationService; -import io.mosip.registration.processor.adjudication.util.ManualVerificationRequestValidator; -import io.mosip.registration.processor.packet.storage.exception.QueueConnectionNotFound; -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 org.apache.activemq.command.ActiveMQBytesMessage; -import org.apache.activemq.command.ActiveMQTextMessage; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.cloud.context.config.annotation.RefreshScope; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.core.env.Environment; -import org.springframework.stereotype.Service; - -import javax.jms.Message; -import javax.jms.TextMessage; - -/** - * This class sends message to next stage after successful completion of manual - * verification. - * - * @author Pranav Kumar - * @since 0.0.1 - */ -@RefreshScope -@Service -@Configuration -@ComponentScan(basePackages = { "${mosip.auth.adapter.impl.basepackage}", - "io.mosip.registration.processor.core.config", - "io.mosip.registration.processor.adjudication.config", - "io.mosip.registration.processor.packet.receiver.config", - "io.mosip.registration.processor.packet.manager.config", - "io.mosip.kernel.packetmanager.config", - "io.mosip.registration.processor.status.config", "io.mosip.registration.processor.rest.client.config", - "io.mosip.registration.processor.core.kernel.beans", - "io.mosip.registration.processor.packet.storage.config", - "io.mosip.registration.processor.adjudication.validators"}) -public class ManualAdjudicationStage extends MosipVerticleAPIManager { - - private static final String STAGE_PROPERTY_PREFIX = "mosip.regproc.manual.adjudication."; - - @Autowired - private ManualAdjudicationService manualAdjudicationService; - - /** The core audit request builder. */ - @Autowired - private AuditLogRequestBuilder auditLogRequestBuilder; - - /** The registration status service. */ - @Autowired - RegistrationStatusService registrationStatusService; - - /** The mosip event bus. */ - private MosipEventBus mosipEventBus; - - /** The mosip queue manager. */ - @Autowired - private MosipQueueManager mosipQueueManager; - - /** - * vertx Cluster Manager Url - */ - @Value("${vertx.cluster.configuration}") - private String clusterManagerUrl; - - /** The reg proc logger. */ - private static Logger regProcLogger = RegProcessorLogger.getLogger(ManualAdjudicationStage.class); - - /** The env. */ - @Autowired - private Environment env; - - @Autowired - ManualVerificationRequestValidator manualVerificationRequestValidator; - - @Autowired - ManualVerificationExceptionHandler manualVerificationExceptionHandler; - - /** Mosip router for APIs */ - @Autowired - MosipRouter router; - - private MosipQueue queue; - - /** The mosip connection factory. */ - @Autowired - private MosipQueueConnectionFactory mosipConnectionFactory; - - /** The username. */ - @Value("${registration.processor.manual.adjudication.queue.username}") - private String username; - - /** The password. */ - @Value("${registration.processor.manual.adjudication.queue.password}") - private String password; - - /** The type of queue. */ - @Value("${registration.processor.manual.adjudication.queue.typeOfQueue}") - private String typeOfQueue; - - /** The address. */ - @Value("${registration.processor.manual.adjudication.queue.response:adjudication-to-mosip}") - private String mvResponseAddress; - - /** The Constant FAIL_OVER. */ - private static final String FAIL_OVER = "failover:("; - - /** The Constant RANDOMIZE_FALSE. */ - private static final String RANDOMIZE_FALSE = ")?randomize=false"; - - private static final String CONFIGURE_MONITOR_IN_ACTIVITY = "?wireFormat.maxInactivityDuration=0"; - - /** The url. */ - @Value("${registration.processor.manual.adjudication.queue.url}") - private String url; - - /** worker pool size. */ - @Value("${worker.pool.size}") - private Integer workerPoolSize; - - /** After this time intervel, message should be considered as expired (In seconds). */ - @Value("${mosip.regproc.manual.adjudication.message.expiry-time-limit}") - private Long messageExpiryTimeLimit; - - private static final String APPLICATION_JSON = "application/json"; - - /** - * Deploy stage. - */ - public void deployVerticle() { - this.mosipEventBus = this.getEventBus(this, clusterManagerUrl, workerPoolSize); - this.consume(mosipEventBus, MessageBusAddress.MANUAL_ADJUDICATION_BUS_IN, messageExpiryTimeLimit); - queue = getQueueConnection(); - if (queue != null) { - - QueueListener listener = new QueueListener() { - @Override - public void setListener(Message message) { - consumerListener(message); - } - }; - - mosipQueueManager.consume(queue, mvResponseAddress, listener); - - } else { - throw new QueueConnectionNotFound(PlatformErrorMessages.RPR_PRT_QUEUE_CONNECTION_NULL.getMessage()); - } - - } - - @Override - public void start() { - router.setRoute(this.postUrl(getVertx(), MessageBusAddress.MANUAL_ADJUDICATION_BUS_IN, MessageBusAddress.MANUAL_ADJUDICATION_BUS_OUT)); - this.createServer(router.getRouter(), getPort()); - } - - @Override - protected String getPropertyPrefix() { - return STAGE_PROPERTY_PREFIX; - } - - public void sendMessage(MessageDTO messageDTO) { - this.send(this.mosipEventBus, MessageBusAddress.MANUAL_ADJUDICATION_BUS_OUT, messageDTO); - } - - @Override - public MessageDTO process(MessageDTO object) { - return manualAdjudicationService.process(object, queue); - } - - private MosipQueue getQueueConnection() { - String failOverBrokerUrl = FAIL_OVER + url + "," + url + RANDOMIZE_FALSE; - return mosipConnectionFactory.createConnection(typeOfQueue, username, password, failOverBrokerUrl); - } - - public void consumerListener(Message message) { - try { - String response = null; - if (message instanceof ActiveMQBytesMessage) { - response = new String(((ActiveMQBytesMessage) message).getContent().data); - } else if (message instanceof ActiveMQTextMessage) { - TextMessage textMessage = (TextMessage) message; - response = textMessage.getText(); - } - regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REFERENCEID.toString(), - "Response received from mv system", response); - if (response == null) { - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), - PlatformErrorMessages.RPR_INVALID_MESSSAGE.getCode(), PlatformErrorMessages.RPR_INVALID_MESSSAGE.getMessage()); - throw new InvalidMessageException(PlatformErrorMessages.RPR_INVALID_MESSSAGE.getCode(), PlatformErrorMessages.RPR_INVALID_MESSSAGE.getMessage()); - } - ManualAdjudicationResponseDTO resp = JsonUtil.readValueWithUnknownProperties(response, ManualAdjudicationResponseDTO.class); - if (resp != null) { - boolean isProcessingSuccessful = manualAdjudicationService.updatePacketStatus(resp,getStageName(),queue); - - if (isProcessingSuccessful) - regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - "", "ManualVerificationStage::processDecision::success"); - - } - } catch (Exception e) { - regProcLogger.error("","","", ExceptionUtils.getStackTrace(e)); - } - - } -} - +package io.mosip.registration.processor.adjudication.stage; + +import java.util.List; + +import javax.jms.Message; +import javax.jms.TextMessage; + +import org.apache.activemq.command.ActiveMQBytesMessage; +import org.apache.activemq.command.ActiveMQTextMessage; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.cloud.context.config.annotation.RefreshScope; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Service; + +import io.mosip.kernel.core.exception.ExceptionUtils; +import io.mosip.kernel.core.logger.spi.Logger; +import io.mosip.registration.processor.adjudication.exception.InvalidMessageException; +import io.mosip.registration.processor.adjudication.exception.handler.ManualVerificationExceptionHandler; +import io.mosip.registration.processor.adjudication.response.dto.ManualAdjudicationResponseDTO; +import io.mosip.registration.processor.adjudication.service.ManualAdjudicationService; +import io.mosip.registration.processor.adjudication.util.ManualVerificationRequestValidator; +import io.mosip.registration.processor.core.abstractverticle.MessageBusAddress; +import io.mosip.registration.processor.core.abstractverticle.MessageDTO; +import io.mosip.registration.processor.core.abstractverticle.MosipEventBus; +import io.mosip.registration.processor.core.abstractverticle.MosipRouter; +import io.mosip.registration.processor.core.abstractverticle.MosipVerticleAPIManager; +import io.mosip.registration.processor.core.constant.LoggerFileConstant; +import io.mosip.registration.processor.core.exception.util.PlatformErrorMessages; +import io.mosip.registration.processor.core.logger.RegProcessorLogger; +import io.mosip.registration.processor.core.queue.factory.MosipQueue; +import io.mosip.registration.processor.core.queue.factory.QueueListener; +import io.mosip.registration.processor.core.spi.queue.MosipQueueConnectionFactory; +import io.mosip.registration.processor.core.spi.queue.MosipQueueManager; +import io.mosip.registration.processor.core.util.JsonUtil; +import io.mosip.registration.processor.packet.storage.exception.QueueConnectionNotFound; +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; + +/** + * This class sends message to next stage after successful completion of manual + * verification. + * + * @author Pranav Kumar + * @since 0.0.1 + */ +@RefreshScope +@Service +@Configuration +@ComponentScan(basePackages = { "${mosip.auth.adapter.impl.basepackage}", + "io.mosip.registration.processor.core.config", + "io.mosip.registration.processor.adjudication.config", + "io.mosip.registration.processor.packet.receiver.config", + "io.mosip.registration.processor.packet.manager.config", + "io.mosip.kernel.packetmanager.config", + "io.mosip.registration.processor.status.config", "io.mosip.registration.processor.rest.client.config", + "io.mosip.registration.processor.core.kernel.beans", + "io.mosip.registration.processor.packet.storage.config", + "io.mosip.registration.processor.adjudication.validators"}) +public class ManualAdjudicationStage extends MosipVerticleAPIManager { + + private static final String STAGE_PROPERTY_PREFIX = "mosip.regproc.manual.adjudication."; + + @Autowired + private ManualAdjudicationService manualAdjudicationService; + + /** The core audit request builder. */ + @Autowired + private AuditLogRequestBuilder auditLogRequestBuilder; + + /** The registration status service. */ + @Autowired + RegistrationStatusService registrationStatusService; + + /** The mosip event bus. */ + private MosipEventBus mosipEventBus; + + /** The mosip queue manager. */ + @Autowired + private MosipQueueManager mosipQueueManager; + + /** + * vertx Cluster Manager Url + */ + @Value("${vertx.cluster.configuration}") + private String clusterManagerUrl; + + /** The reg proc logger. */ + private static Logger regProcLogger = RegProcessorLogger.getLogger(ManualAdjudicationStage.class); + + /** The env. */ + @Autowired + private Environment env; + + @Autowired + ManualVerificationRequestValidator manualVerificationRequestValidator; + + @Autowired + ManualVerificationExceptionHandler manualVerificationExceptionHandler; + + /** Mosip router for APIs */ + @Autowired + MosipRouter router; + + private MosipQueue queue; + + /** The mosip connection factory. */ + @Autowired + private MosipQueueConnectionFactory mosipConnectionFactory; + + /** The username. */ + @Value("${registration.processor.manual.adjudication.queue.username}") + private String username; + + /** The password. */ + @Value("${registration.processor.manual.adjudication.queue.password}") + private String password; + + /** The type of queue. */ + @Value("${registration.processor.manual.adjudication.queue.typeOfQueue}") + private String typeOfQueue; + + /** The address. */ + @Value("${registration.processor.manual.adjudication.queue.response:adjudication-to-mosip}") + private String mvResponseAddress; + + @Value("#{'${registration.processor.manual.adjudication.queue.trusted.packages}'.split(',')}") + private List trustedPackages; + + /** The Constant FAIL_OVER. */ + private static final String FAIL_OVER = "failover:("; + + /** The Constant RANDOMIZE_FALSE. */ + private static final String RANDOMIZE_FALSE = ")?randomize=false"; + + private static final String CONFIGURE_MONITOR_IN_ACTIVITY = "?wireFormat.maxInactivityDuration=0"; + + /** The url. */ + @Value("${registration.processor.manual.adjudication.queue.url}") + private String url; + + /** worker pool size. */ + @Value("${worker.pool.size}") + private Integer workerPoolSize; + + /** After this time intervel, message should be considered as expired (In seconds). */ + @Value("${mosip.regproc.manual.adjudication.message.expiry-time-limit}") + private Long messageExpiryTimeLimit; + + private static final String APPLICATION_JSON = "application/json"; + + /** + * Deploy stage. + */ + public void deployVerticle() { + this.mosipEventBus = this.getEventBus(this, clusterManagerUrl, workerPoolSize); + this.consume(mosipEventBus, MessageBusAddress.MANUAL_ADJUDICATION_BUS_IN, messageExpiryTimeLimit); + queue = getQueueConnection(); + if (queue != null) { + + QueueListener listener = new QueueListener() { + @Override + public void setListener(Message message) { + consumerListener(message); + } + }; + + mosipQueueManager.consume(queue, mvResponseAddress, listener); + + } else { + throw new QueueConnectionNotFound(PlatformErrorMessages.RPR_PRT_QUEUE_CONNECTION_NULL.getMessage()); + } + + } + + @Override + public void start() { + router.setRoute(this.postUrl(getVertx(), MessageBusAddress.MANUAL_ADJUDICATION_BUS_IN, MessageBusAddress.MANUAL_ADJUDICATION_BUS_OUT)); + this.createServer(router.getRouter(), getPort()); + } + + @Override + protected String getPropertyPrefix() { + return STAGE_PROPERTY_PREFIX; + } + + public void sendMessage(MessageDTO messageDTO) { + this.send(this.mosipEventBus, MessageBusAddress.MANUAL_ADJUDICATION_BUS_OUT, messageDTO); + } + + @Override + public MessageDTO process(MessageDTO object) { + return manualAdjudicationService.process(object, queue); + } + + private MosipQueue getQueueConnection() { + String failOverBrokerUrl = FAIL_OVER + url + "," + url + RANDOMIZE_FALSE; + return mosipConnectionFactory.createConnection(typeOfQueue, username, password, failOverBrokerUrl, + trustedPackages); + } + + public void consumerListener(Message message) { + try { + String response = null; + if (message instanceof ActiveMQBytesMessage) { + response = new String(((ActiveMQBytesMessage) message).getContent().data); + } else if (message instanceof ActiveMQTextMessage) { + TextMessage textMessage = (TextMessage) message; + response = textMessage.getText(); + } + regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REFERENCEID.toString(), + "Response received from mv system", response); + if (response == null) { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), + PlatformErrorMessages.RPR_INVALID_MESSSAGE.getCode(), PlatformErrorMessages.RPR_INVALID_MESSSAGE.getMessage()); + throw new InvalidMessageException(PlatformErrorMessages.RPR_INVALID_MESSSAGE.getCode(), PlatformErrorMessages.RPR_INVALID_MESSSAGE.getMessage()); + } + ManualAdjudicationResponseDTO resp = JsonUtil.readValueWithUnknownProperties(response, ManualAdjudicationResponseDTO.class); + if (resp != null) { + boolean isProcessingSuccessful = manualAdjudicationService.updatePacketStatus(resp,getStageName(),queue); + + if (isProcessingSuccessful) + regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + "", "ManualVerificationStage::processDecision::success"); + + } + } catch (Exception e) { + regProcLogger.error("","","", ExceptionUtils.getStackTrace(e)); + } + + } +} + 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 0d760c46bed..14bd1680629 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 @@ -194,7 +194,8 @@ public String getQueueName() { } @Override - public void createConnection(String username, String password, String brokerUrl) { + public void createConnection(String username, String password, String brokerUrl, + List trustedPackage) { // TODO Auto-generated method stub } @@ -272,7 +273,7 @@ public void createConnection(String username, String password, String brokerUrl) manualAdjudicationResponseDTO.setCandidateList(candidateList); Mockito.doNothing().when(manualVerificationUpdateUtility).updateManualVerificationEntityRID(any(), any()); - + Mockito.doNothing().when(manualVerificationUpdateUtility).updateManualVerificationEntityRID(any(), any()); } diff --git a/registration-processor/core-processor/registration-processor-manual-adjudication-stage/src/test/java/io/mosip/registration/processor/verification/stage/ManualAdjudicationStageTest.java b/registration-processor/core-processor/registration-processor-manual-adjudication-stage/src/test/java/io/mosip/registration/processor/verification/stage/ManualAdjudicationStageTest.java index 719975bf496..f7d06c6fca0 100644 --- a/registration-processor/core-processor/registration-processor-manual-adjudication-stage/src/test/java/io/mosip/registration/processor/verification/stage/ManualAdjudicationStageTest.java +++ b/registration-processor/core-processor/registration-processor-manual-adjudication-stage/src/test/java/io/mosip/registration/processor/verification/stage/ManualAdjudicationStageTest.java @@ -1,567 +1,573 @@ -package io.mosip.registration.processor.verification.stage; - - -import static org.mockito.ArgumentMatchers.argThat; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.*; - -import java.io.File; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import ch.qos.logback.classic.spi.ILoggingEvent; -import ch.qos.logback.classic.spi.LoggingEvent; -import ch.qos.logback.core.Appender; -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.adjudication.exception.InvalidMessageException; -import io.mosip.registration.processor.adjudication.response.dto.ManualAdjudicationResponseDTO; -import io.mosip.registration.processor.adjudication.stage.ManualAdjudicationStage; -import io.mosip.registration.processor.core.exception.PacketManagerException; -import io.mosip.registration.processor.core.queue.factory.MosipQueue; -import io.mosip.registration.processor.core.spi.queue.MosipQueueConnectionFactory; -import io.mosip.registration.processor.core.spi.queue.MosipQueueManager; -import io.mosip.registration.processor.adjudication.util.ManualVerificationRequestValidator; -import org.apache.activemq.command.ActiveMQBytesMessage; -import org.apache.activemq.command.ActiveMQTextMessage; -import org.apache.activemq.util.ByteSequence; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.ArgumentMatcher; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.slf4j.LoggerFactory; -import org.springframework.core.env.Environment; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.util.ReflectionTestUtils; - -import io.mosip.kernel.core.signatureutil.model.SignatureResponse; -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.exception.ApisResourceAccessException; -import io.mosip.registration.processor.adjudication.service.ManualAdjudicationService; -import io.vertx.core.AsyncResult; -import io.vertx.core.Handler; -import io.vertx.core.MultiMap; -import io.vertx.core.Vertx; -import io.vertx.core.buffer.Buffer; -import io.vertx.core.http.HttpMethod; -import io.vertx.core.http.HttpServerRequest; -import io.vertx.core.http.HttpServerResponse; -import io.vertx.core.json.JsonArray; -import io.vertx.core.json.JsonObject; -import io.vertx.ext.auth.User; -import io.vertx.ext.web.Cookie; -import io.vertx.ext.web.FileUpload; -import io.vertx.ext.web.Locale; -import io.vertx.ext.web.ParsedHeaderValues; -import io.vertx.ext.web.Route; -import io.vertx.ext.web.Router; -import io.vertx.ext.web.RoutingContext; -import io.vertx.ext.web.Session; - -@RunWith(SpringRunner.class) - -public class ManualAdjudicationStageTest { - - @Mock - private MosipQueueConnectionFactory mosipConnectionFactory; - @Mock - private MosipQueue mosipQueue; - @Mock - private MosipQueueManager mosipQueueManager; - @Mock - private MosipRouter router; - public RoutingContext ctx; - @Mock - SignatureResponse signatureResponse; - @Mock - private ManualVerificationRequestValidator manualVerificationRequestValidator; - @Mock - private ManualAdjudicationService manualAdjudicationService; - @Mock - private Environment env; - @Mock - private MosipEventBus mockEventbus; - private File file; - private String id = "2018782130000113112018183001.zip"; - private String newId = "2018782130000113112018183000.zip"; - public FileUpload fileUpload; - private String serviceID=""; - private byte[] packetInfo; - - @InjectMocks - private ManualAdjudicationStage manualverificationstage=new ManualAdjudicationStage() - { - @Override - public void send(MosipEventBus mosipEventBus, MessageBusAddress toAddress, MessageDTO message) { - } - - @Override - public MosipEventBus getEventBus(Object verticleName, String clusterManagerUrl, int instanceNumber) { - return mockEventbus; - } - @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) { - - } - - @Override - public Integer getPort() { - return 8080; - } - }; - @Before - public void setUp() throws java.io.IOException, ApisResourceAccessException, PacketManagerException, JsonProcessingException { - ReflectionTestUtils.setField(manualverificationstage, "mosipConnectionFactory", mosipConnectionFactory); - ReflectionTestUtils.setField(manualverificationstage, "mosipQueueManager", mosipQueueManager); - //ReflectionTestUtils.setField(manualverificationstage, "contextPath", "/registrationprocessor/v1/manualverification"); - ReflectionTestUtils.setField(manualverificationstage, "workerPoolSize", 10); - ReflectionTestUtils.setField(manualverificationstage, "messageExpiryTimeLimit", Long.valueOf(0)); - ReflectionTestUtils.setField(manualverificationstage, "clusterManagerUrl", "/dummyPath"); - //Mockito.when(env.getProperty(SwaggerConstant.SERVER_SERVLET_PATH)).thenReturn("/registrationprocessor/v1/manualverification"); - Mockito.when(mosipConnectionFactory.createConnection(any(),any(),any(),any())).thenReturn(mosipQueue); - Mockito.doReturn(new String("str").getBytes()).when(mosipQueueManager).consume(any(), any(), any()); - Mockito.doNothing().when(router).setRoute(any()); - Mockito.when(router.post(any())).thenReturn(null); - Mockito.when(router.get(any())).thenReturn(null); - Mockito.doNothing().when(manualVerificationRequestValidator).validate(any(),any()); - Mockito.when(signatureResponse.getData()).thenReturn("gdshgsahjhghgsad"); - packetInfo="packetInfo".getBytes(); - //ClassLoader classLoader = getClass().getClassLoader(); - file = new File("/src/test/resources/0000.zip"); - //FileUtils.copyFile(file, new File(file.getParentFile().getPath() + "/" + id)); - //file = new File(classLoader.getResource(id).getFile()); - fileUpload = setFileUpload(); - ctx=setContext(); - } - @Test - public void testDeployeVerticle() - { - manualverificationstage.deployVerticle(); - } - @Test - public void testStart() - { - MessageDTO dto=new MessageDTO(); - manualverificationstage.process(dto); - manualverificationstage.sendMessage(dto); - manualverificationstage.start(); - } -/* @Test - public void testAllProcess() throws PacketDecryptionFailureException, ApisResourceAccessException, IOException, java.io.IOException, JsonProcessingException, PacketManagerException { - - testProcessAssignment(); - testProcessDecision(); - - } - - private void testProcessAssignment() - { - serviceID="assign"; - Mockito.when(env.getProperty(any())).thenReturn("mosip.manual.adjudication.assignment"); - Mockito.when(env.getProperty("mosip.registration.processor.datetime.pattern")).thenReturn("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); - ManualVerificationDTO manualVerificationDTO= new ManualVerificationDTO(); - Mockito.when(manualAdjudicationService.assignApplicant(any(UserDto.class))).thenReturn(manualVerificationDTO); - manualverificationstage.processAssignment(ctx); - } - private void testProcessDecision() - { - serviceID="decision"; - Mockito.when(env.getProperty(any())).thenReturn("mosip.manual.adjudication.decision"); - Mockito.when(env.getProperty("mosip.registration.processor.datetime.pattern")).thenReturn("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); - ManualVerificationDecisionDto updatedManualVerificationDTO=new ManualVerificationDecisionDto(); - Mockito.when(manualAdjudicationService.updatePacketStatus(any(),any())).thenReturn(updatedManualVerificationDTO); - manualverificationstage.processDecision(ctx); - }*/ - - private FileUpload setFileUpload() { - return new FileUpload() { - - @Override - public String uploadedFileName() { - return file.getPath(); - } - - @Override - public long size() { - return file.length(); - } - - @Override - public String name() { - return file.getName(); - } - - @Override - public String fileName() { - return newId; - } - - @Override - public String contentType() { - return null; - } - - @Override - public String contentTransferEncoding() { - return null; - } - - @Override - public String charSet() { - return null; - } - }; - } - private RoutingContext setContext() { - return new RoutingContext() { - - @Override - public Set fileUploads() { - Set fileUploads = new HashSet(); - fileUploads.add(fileUpload); - return fileUploads; - } - - @Override - public Vertx vertx() { - return null; - } - - @Override - public User user() { - return null; - } - - @Override - public int statusCode() { - return 0; - } - - @Override - public void setUser(User user) { - } - - @Override - public void setSession(Session session) { - } - - @Override - public void setBody(Buffer body) { - } - - @Override - public void setAcceptableContentType(String contentType) { - } - - @Override - public Session session() { - return null; - } - - @Override - public HttpServerResponse response() { - return null; - } - - @Override - public void reroute(HttpMethod method, String path) { - } - - @Override - public HttpServerRequest request() { - return null; - } - - @Override - public boolean removeHeadersEndHandler(int handlerID) { - return false; - } - - @Override - public Cookie removeCookie(String name, boolean invalidate) { - return null; - } - - @Override - public boolean removeBodyEndHandler(int handlerID) { - return false; - } - - @Override - public T remove(String key) { - return null; - } - - @Override - public MultiMap queryParams() { - return null; - } - - @Override - public List queryParam(String query) { - return null; - } - - @Override - public RoutingContext put(String key, Object obj) { - return null; - } - - @Override - public Map pathParams() { - return null; - } - - @Override - public String pathParam(String name) { - return null; - } - - @Override - public ParsedHeaderValues parsedHeaders() { - return null; - } - - @Override - public String normalisedPath() { - return null; - } - - @Override - public void next() { - } - - @Override - public String mountPoint() { - return null; - } - - @Override - public Cookie getCookie(String name) { - return null; - } - - @Override - public String getBodyAsString(String encoding) { - return null; - } - - @Override - public String getBodyAsString() { - return null; - } - - @Override - public JsonArray getBodyAsJsonArray() { - return null; - } - - @Override - public JsonObject getBodyAsJson() { - JsonObject obj= new JsonObject(); - obj.put("id", "51130282650000320190117144316"); - obj.put("version", "1.0"); - obj.put("requesttime", "51130282650000320190117"); - JsonObject obj1= new JsonObject(); - - if(serviceID=="assign") { - obj1.put("userId", "51130282650000320190117"); - - }else if(serviceID=="decision") { - - obj1.put("matchedRefType", "mono"); - obj1.put("mvUsrId", "mono"); - obj1.put("regId", "27847657360002520181208123456"); - obj1.put("statusCode", "APPROVED"); - obj1.put("reasonCode", "mono"); - } - - obj.put("request", obj1); - - return obj; - } - - @Override - public Buffer getBody() { - return null; - } - - @Override - public String getAcceptableContentType() { - return null; - } - - @Override - public T get(String key) { - return null; - } - - @Override - public Throwable failure() { - return null; - } - - @Override - public boolean failed() { - return false; - } - - @Override - public void fail(Throwable throwable) { - } - - @Override - public void fail(int statusCode) { - } - - @Override - public Map data() { - return null; - } - - @Override - public Route currentRoute() { - return null; - } - - @Override - public Set cookies() { - return null; - } - - @Override - public int cookieCount() { - return 0; - } - - @Override - public void clearUser() { - } - - @Override - public int addHeadersEndHandler(Handler handler) { - return 0; - } - - @Override - public RoutingContext addCookie(Cookie cookie) { - return null; - } - - @Override - public int addBodyEndHandler(Handler handler) { - return 0; - } - - @Override - public List acceptableLocales() { - return null; - } - - @Override - public void fail(int statusCode, Throwable throwable) { - } - - @Override - public RoutingContext addCookie(io.vertx.core.http.Cookie cookie) { - return null; - } - - @Override - public Map cookieMap() { - return null; - } - - @Override - public boolean isSessionAccessed() { - return false; - } - - @Override - public int addEndHandler(Handler> handler) { - return 0; - } - - @Override - public boolean removeEndHandler(int handlerID) { - return false; - } - }; - } - - @Test - public void testConsumeListener() throws JsonProcessingException { - ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) LoggerFactory - .getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME); - final Appender mockAppender = mock(Appender.class); - when(mockAppender.getName()).thenReturn("MOCK"); - root.addAppender(mockAppender); - - ManualAdjudicationResponseDTO resp = new ManualAdjudicationResponseDTO(); - resp.setId("verification"); - resp.setRequestId("e2e59a9b-ce7c-41ae-a953-effb854d1205"); - resp.setResponsetime(DateUtils.getCurrentDateTimeString()); - resp.setReturnValue(1); - - String response = JsonUtils.javaObjectToJsonString(resp); - - ActiveMQBytesMessage amq = new ActiveMQBytesMessage(); - ByteSequence byteSeq = new ByteSequence(); - byteSeq.setData(response.getBytes()); - amq.setContent(byteSeq); - - Mockito.when(manualAdjudicationService.updatePacketStatus(any(), any(), any())).thenReturn(true); - - manualverificationstage.consumerListener(amq); - - verify(mockAppender).doAppend(argThat(new ArgumentMatcher() { - - @Override - public boolean matches(ILoggingEvent argument) { - return ((LoggingEvent) argument).getFormattedMessage() - .contains("ManualVerificationStage::processDecision::success"); - } - })); - } - - @Test - public void testInvalidMessage() { - - ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) LoggerFactory - .getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME); - final Appender mockAppender = mock(Appender.class); - when(mockAppender.getName()).thenReturn("MOCK"); - root.addAppender(mockAppender); - - manualverificationstage.consumerListener(null); - - verify(mockAppender).doAppend(argThat(new ArgumentMatcher() { - - @Override - public boolean matches(ILoggingEvent argument) { - return ((LoggingEvent) argument).getFormattedMessage() - .contains("InvalidMessageException"); - } - })); - - } - -} +package io.mosip.registration.processor.verification.stage; + + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyList; +import static org.mockito.ArgumentMatchers.argThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.io.File; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.apache.activemq.command.ActiveMQBytesMessage; +import org.apache.activemq.util.ByteSequence; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentMatcher; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.slf4j.LoggerFactory; +import org.springframework.core.env.Environment; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.util.ReflectionTestUtils; + +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.classic.spi.LoggingEvent; +import ch.qos.logback.core.Appender; +import io.mosip.kernel.core.signatureutil.model.SignatureResponse; +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.adjudication.response.dto.ManualAdjudicationResponseDTO; +import io.mosip.registration.processor.adjudication.service.ManualAdjudicationService; +import io.mosip.registration.processor.adjudication.stage.ManualAdjudicationStage; +import io.mosip.registration.processor.adjudication.util.ManualVerificationRequestValidator; +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.exception.ApisResourceAccessException; +import io.mosip.registration.processor.core.exception.PacketManagerException; +import io.mosip.registration.processor.core.queue.factory.MosipQueue; +import io.mosip.registration.processor.core.spi.queue.MosipQueueConnectionFactory; +import io.mosip.registration.processor.core.spi.queue.MosipQueueManager; +import io.vertx.core.AsyncResult; +import io.vertx.core.Handler; +import io.vertx.core.MultiMap; +import io.vertx.core.Vertx; +import io.vertx.core.buffer.Buffer; +import io.vertx.core.http.HttpMethod; +import io.vertx.core.http.HttpServerRequest; +import io.vertx.core.http.HttpServerResponse; +import io.vertx.core.json.JsonArray; +import io.vertx.core.json.JsonObject; +import io.vertx.ext.auth.User; +import io.vertx.ext.web.Cookie; +import io.vertx.ext.web.FileUpload; +import io.vertx.ext.web.Locale; +import io.vertx.ext.web.ParsedHeaderValues; +import io.vertx.ext.web.Route; +import io.vertx.ext.web.Router; +import io.vertx.ext.web.RoutingContext; +import io.vertx.ext.web.Session; + +@RunWith(SpringRunner.class) + +public class ManualAdjudicationStageTest { + + @Mock + private MosipQueueConnectionFactory mosipConnectionFactory; + @Mock + private MosipQueue mosipQueue; + @Mock + private MosipQueueManager mosipQueueManager; + @Mock + private MosipRouter router; + public RoutingContext ctx; + @Mock + SignatureResponse signatureResponse; + @Mock + private ManualVerificationRequestValidator manualVerificationRequestValidator; + @Mock + private ManualAdjudicationService manualAdjudicationService; + @Mock + private Environment env; + @Mock + private MosipEventBus mockEventbus; + private File file; + private String id = "2018782130000113112018183001.zip"; + private String newId = "2018782130000113112018183000.zip"; + public FileUpload fileUpload; + private String serviceID=""; + private byte[] packetInfo; + + @InjectMocks + private ManualAdjudicationStage manualverificationstage=new ManualAdjudicationStage() + { + @Override + public void send(MosipEventBus mosipEventBus, MessageBusAddress toAddress, MessageDTO message) { + } + + @Override + public MosipEventBus getEventBus(Object verticleName, String clusterManagerUrl, int instanceNumber) { + return mockEventbus; + } + @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) { + + } + + @Override + public Integer getPort() { + return 8080; + } + }; + @Before + public void setUp() throws java.io.IOException, ApisResourceAccessException, PacketManagerException, JsonProcessingException { + ReflectionTestUtils.setField(manualverificationstage, "mosipConnectionFactory", mosipConnectionFactory); + ReflectionTestUtils.setField(manualverificationstage, "mosipQueueManager", mosipQueueManager); + //ReflectionTestUtils.setField(manualverificationstage, "contextPath", "/registrationprocessor/v1/manualverification"); + ReflectionTestUtils.setField(manualverificationstage, "workerPoolSize", 10); + ReflectionTestUtils.setField(manualverificationstage, "messageExpiryTimeLimit", Long.valueOf(0)); + ReflectionTestUtils.setField(manualverificationstage, "clusterManagerUrl", "/dummyPath"); + List trustedPackageList=new ArrayList(); + trustedPackageList.add("io.mosip.*"); + ReflectionTestUtils.setField(manualverificationstage, "trustedPackages", trustedPackageList); + //Mockito.when(env.getProperty(SwaggerConstant.SERVER_SERVLET_PATH)).thenReturn("/registrationprocessor/v1/manualverification"); + Mockito.when(mosipConnectionFactory.createConnection(any(), any(), any(), any(), anyList())) + .thenReturn(mosipQueue); + Mockito.doReturn(new String("str").getBytes()).when(mosipQueueManager).consume(any(), any(), any()); + Mockito.doNothing().when(router).setRoute(any()); + Mockito.when(router.post(any())).thenReturn(null); + Mockito.when(router.get(any())).thenReturn(null); + Mockito.doNothing().when(manualVerificationRequestValidator).validate(any(),any()); + Mockito.when(signatureResponse.getData()).thenReturn("gdshgsahjhghgsad"); + packetInfo="packetInfo".getBytes(); + //ClassLoader classLoader = getClass().getClassLoader(); + file = new File("/src/test/resources/0000.zip"); + //FileUtils.copyFile(file, new File(file.getParentFile().getPath() + "/" + id)); + //file = new File(classLoader.getResource(id).getFile()); + fileUpload = setFileUpload(); + ctx=setContext(); + } + @Test + public void testDeployeVerticle() + { + manualverificationstage.deployVerticle(); + } + @Test + public void testStart() + { + MessageDTO dto=new MessageDTO(); + manualverificationstage.process(dto); + manualverificationstage.sendMessage(dto); + manualverificationstage.start(); + } +/* @Test + public void testAllProcess() throws PacketDecryptionFailureException, ApisResourceAccessException, IOException, java.io.IOException, JsonProcessingException, PacketManagerException { + + testProcessAssignment(); + testProcessDecision(); + + } + + private void testProcessAssignment() + { + serviceID="assign"; + Mockito.when(env.getProperty(any())).thenReturn("mosip.manual.adjudication.assignment"); + Mockito.when(env.getProperty("mosip.registration.processor.datetime.pattern")).thenReturn("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); + ManualVerificationDTO manualVerificationDTO= new ManualVerificationDTO(); + Mockito.when(manualAdjudicationService.assignApplicant(any(UserDto.class))).thenReturn(manualVerificationDTO); + manualverificationstage.processAssignment(ctx); + } + private void testProcessDecision() + { + serviceID="decision"; + Mockito.when(env.getProperty(any())).thenReturn("mosip.manual.adjudication.decision"); + Mockito.when(env.getProperty("mosip.registration.processor.datetime.pattern")).thenReturn("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); + ManualVerificationDecisionDto updatedManualVerificationDTO=new ManualVerificationDecisionDto(); + Mockito.when(manualAdjudicationService.updatePacketStatus(any(),any())).thenReturn(updatedManualVerificationDTO); + manualverificationstage.processDecision(ctx); + }*/ + + private FileUpload setFileUpload() { + return new FileUpload() { + + @Override + public String uploadedFileName() { + return file.getPath(); + } + + @Override + public long size() { + return file.length(); + } + + @Override + public String name() { + return file.getName(); + } + + @Override + public String fileName() { + return newId; + } + + @Override + public String contentType() { + return null; + } + + @Override + public String contentTransferEncoding() { + return null; + } + + @Override + public String charSet() { + return null; + } + }; + } + private RoutingContext setContext() { + return new RoutingContext() { + + @Override + public Set fileUploads() { + Set fileUploads = new HashSet(); + fileUploads.add(fileUpload); + return fileUploads; + } + + @Override + public Vertx vertx() { + return null; + } + + @Override + public User user() { + return null; + } + + @Override + public int statusCode() { + return 0; + } + + @Override + public void setUser(User user) { + } + + @Override + public void setSession(Session session) { + } + + @Override + public void setBody(Buffer body) { + } + + @Override + public void setAcceptableContentType(String contentType) { + } + + @Override + public Session session() { + return null; + } + + @Override + public HttpServerResponse response() { + return null; + } + + @Override + public void reroute(HttpMethod method, String path) { + } + + @Override + public HttpServerRequest request() { + return null; + } + + @Override + public boolean removeHeadersEndHandler(int handlerID) { + return false; + } + + @Override + public Cookie removeCookie(String name, boolean invalidate) { + return null; + } + + @Override + public boolean removeBodyEndHandler(int handlerID) { + return false; + } + + @Override + public T remove(String key) { + return null; + } + + @Override + public MultiMap queryParams() { + return null; + } + + @Override + public List queryParam(String query) { + return null; + } + + @Override + public RoutingContext put(String key, Object obj) { + return null; + } + + @Override + public Map pathParams() { + return null; + } + + @Override + public String pathParam(String name) { + return null; + } + + @Override + public ParsedHeaderValues parsedHeaders() { + return null; + } + + @Override + public String normalisedPath() { + return null; + } + + @Override + public void next() { + } + + @Override + public String mountPoint() { + return null; + } + + @Override + public Cookie getCookie(String name) { + return null; + } + + @Override + public String getBodyAsString(String encoding) { + return null; + } + + @Override + public String getBodyAsString() { + return null; + } + + @Override + public JsonArray getBodyAsJsonArray() { + return null; + } + + @Override + public JsonObject getBodyAsJson() { + JsonObject obj= new JsonObject(); + obj.put("id", "51130282650000320190117144316"); + obj.put("version", "1.0"); + obj.put("requesttime", "51130282650000320190117"); + JsonObject obj1= new JsonObject(); + + if(serviceID=="assign") { + obj1.put("userId", "51130282650000320190117"); + + }else if(serviceID=="decision") { + + obj1.put("matchedRefType", "mono"); + obj1.put("mvUsrId", "mono"); + obj1.put("regId", "27847657360002520181208123456"); + obj1.put("statusCode", "APPROVED"); + obj1.put("reasonCode", "mono"); + } + + obj.put("request", obj1); + + return obj; + } + + @Override + public Buffer getBody() { + return null; + } + + @Override + public String getAcceptableContentType() { + return null; + } + + @Override + public T get(String key) { + return null; + } + + @Override + public Throwable failure() { + return null; + } + + @Override + public boolean failed() { + return false; + } + + @Override + public void fail(Throwable throwable) { + } + + @Override + public void fail(int statusCode) { + } + + @Override + public Map data() { + return null; + } + + @Override + public Route currentRoute() { + return null; + } + + @Override + public Set cookies() { + return null; + } + + @Override + public int cookieCount() { + return 0; + } + + @Override + public void clearUser() { + } + + @Override + public int addHeadersEndHandler(Handler handler) { + return 0; + } + + @Override + public RoutingContext addCookie(Cookie cookie) { + return null; + } + + @Override + public int addBodyEndHandler(Handler handler) { + return 0; + } + + @Override + public List acceptableLocales() { + return null; + } + + @Override + public void fail(int statusCode, Throwable throwable) { + } + + @Override + public RoutingContext addCookie(io.vertx.core.http.Cookie cookie) { + return null; + } + + @Override + public Map cookieMap() { + return null; + } + + @Override + public boolean isSessionAccessed() { + return false; + } + + @Override + public int addEndHandler(Handler> handler) { + return 0; + } + + @Override + public boolean removeEndHandler(int handlerID) { + return false; + } + }; + } + + @Test + public void testConsumeListener() throws JsonProcessingException { + ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) LoggerFactory + .getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME); + final Appender mockAppender = mock(Appender.class); + when(mockAppender.getName()).thenReturn("MOCK"); + root.addAppender(mockAppender); + + ManualAdjudicationResponseDTO resp = new ManualAdjudicationResponseDTO(); + resp.setId("verification"); + resp.setRequestId("e2e59a9b-ce7c-41ae-a953-effb854d1205"); + resp.setResponsetime(DateUtils.getCurrentDateTimeString()); + resp.setReturnValue(1); + + String response = JsonUtils.javaObjectToJsonString(resp); + + ActiveMQBytesMessage amq = new ActiveMQBytesMessage(); + ByteSequence byteSeq = new ByteSequence(); + byteSeq.setData(response.getBytes()); + amq.setContent(byteSeq); + + Mockito.when(manualAdjudicationService.updatePacketStatus(any(), any(), any())).thenReturn(true); + + manualverificationstage.consumerListener(amq); + + verify(mockAppender).doAppend(argThat(new ArgumentMatcher() { + + @Override + public boolean matches(ILoggingEvent argument) { + return ((LoggingEvent) argument).getFormattedMessage() + .contains("ManualVerificationStage::processDecision::success"); + } + })); + } + + @Test + public void testInvalidMessage() { + + ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) LoggerFactory + .getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME); + final Appender mockAppender = mock(Appender.class); + when(mockAppender.getName()).thenReturn("MOCK"); + root.addAppender(mockAppender); + + manualverificationstage.consumerListener(null); + + verify(mockAppender).doAppend(argThat(new ArgumentMatcher() { + + @Override + public boolean matches(ILoggingEvent argument) { + return ((LoggingEvent) argument).getFormattedMessage() + .contains("InvalidMessageException"); + } + })); + + } + +} diff --git a/registration-processor/core-processor/registration-processor-verification-stage/src/main/java/io/mosip/registration/processor/verification/stage/VerificationStage.java b/registration-processor/core-processor/registration-processor-verification-stage/src/main/java/io/mosip/registration/processor/verification/stage/VerificationStage.java index 65b7e782b79..5a6ed1b15ff 100644 --- a/registration-processor/core-processor/registration-processor-verification-stage/src/main/java/io/mosip/registration/processor/verification/stage/VerificationStage.java +++ b/registration-processor/core-processor/registration-processor-verification-stage/src/main/java/io/mosip/registration/processor/verification/stage/VerificationStage.java @@ -1,231 +1,238 @@ -package io.mosip.registration.processor.verification.stage; - -import io.mosip.kernel.core.exception.ExceptionUtils; -import io.mosip.kernel.core.logger.spi.Logger; -import io.mosip.registration.processor.core.abstractverticle.MessageBusAddress; -import io.mosip.registration.processor.core.abstractverticle.MessageDTO; -import io.mosip.registration.processor.core.abstractverticle.MosipEventBus; -import io.mosip.registration.processor.core.abstractverticle.MosipRouter; -import io.mosip.registration.processor.core.abstractverticle.MosipVerticleAPIManager; -import io.mosip.registration.processor.core.constant.LoggerFileConstant; -import io.mosip.registration.processor.core.exception.util.PlatformErrorMessages; -import io.mosip.registration.processor.core.logger.RegProcessorLogger; -import io.mosip.registration.processor.core.queue.factory.MosipQueue; -import io.mosip.registration.processor.core.queue.factory.QueueListener; -import io.mosip.registration.processor.core.spi.queue.MosipQueueConnectionFactory; -import io.mosip.registration.processor.core.spi.queue.MosipQueueManager; -import io.mosip.registration.processor.core.util.JsonUtil; -import io.mosip.registration.processor.verification.exception.InvalidMessageException; -import io.mosip.registration.processor.verification.exception.handler.ManualVerificationExceptionHandler; -import io.mosip.registration.processor.verification.response.dto.VerificationResponseDTO; -import io.mosip.registration.processor.verification.service.VerificationService; -import io.mosip.registration.processor.verification.util.ManualVerificationRequestValidator; -import io.mosip.registration.processor.packet.storage.exception.QueueConnectionNotFound; -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 org.apache.activemq.command.ActiveMQBytesMessage; -import org.apache.activemq.command.ActiveMQTextMessage; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.cloud.context.config.annotation.RefreshScope; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.core.env.Environment; -import org.springframework.stereotype.Service; - -import javax.jms.Message; -import javax.jms.TextMessage; - -/** - * This class sends message to next stage after successful completion of manual - * verification. - * - * @author Pranav Kumar - * @since 0.0.1 - */ -@RefreshScope -@Service -@Configuration -@ComponentScan(basePackages = { "${mosip.auth.adapter.impl.basepackage}", - "io.mosip.registration.processor.core.config", - "io.mosip.registration.processor.verification.config", - "io.mosip.registration.processor.packet.receiver.config", - "io.mosip.registration.processor.packet.manager.config", - "io.mosip.kernel.packetmanager.config", - "io.mosip.registration.processor.status.config", "io.mosip.registration.processor.rest.client.config", - "io.mosip.registration.processor.core.kernel.beans", - "io.mosip.registration.processor.packet.storage.config", - "io.mosip.registration.processor.verification.validators"}) -public class VerificationStage extends MosipVerticleAPIManager { - - private static final String STAGE_PROPERTY_PREFIX = "mosip.regproc.verification."; - private static final String CLASS_NAME = "VerificationStage"; - - @Autowired - private VerificationService verificationService; - - /** The core audit request builder. */ - @Autowired - private AuditLogRequestBuilder auditLogRequestBuilder; - - /** The registration status service. */ - @Autowired - RegistrationStatusService registrationStatusService; - - /** The mosip event bus. */ - private MosipEventBus mosipEventBus; - - /** The mosip queue manager. */ - @Autowired - private MosipQueueManager mosipQueueManager; - - /** - * vertx Cluster Manager Url - */ - @Value("${vertx.cluster.configuration}") - private String clusterManagerUrl; - - /** The reg proc logger. */ - private static Logger regProcLogger = RegProcessorLogger.getLogger(VerificationStage.class); - - /** The env. */ - @Autowired - private Environment env; - - @Autowired - ManualVerificationRequestValidator manualVerificationRequestValidator; - - @Autowired - ManualVerificationExceptionHandler manualVerificationExceptionHandler; - - /** Mosip router for APIs */ - @Autowired - MosipRouter router; - - private MosipQueue queue; - - /** The mosip connection factory. */ - @Autowired - private MosipQueueConnectionFactory mosipConnectionFactory; - - /** The username. */ - @Value("${registration.processor.verification.queue.username}") - private String username; - - /** The password. */ - @Value("${registration.processor.verification.queue.password}") - private String password; - - /** The type of queue. */ - @Value("${registration.processor.verification.queue.typeOfQueue}") - private String typeOfQueue; - - /** The address. */ - @Value("${registration.processor.verification.queue.response:verification-to-mosip}") - private String mvResponseAddress; - - /** The Constant FAIL_OVER. */ - private static final String FAIL_OVER = "failover:("; - - /** The Constant RANDOMIZE_FALSE. */ - private static final String RANDOMIZE_FALSE = ")?randomize=false"; - - private static final String CONFIGURE_MONITOR_IN_ACTIVITY = "?wireFormat.maxInactivityDuration=0"; - - /** The url. */ - @Value("${registration.processor.verification.queue.url}") - private String url; - - /** worker pool size. */ - @Value("${worker.pool.size}") - private Integer workerPoolSize; - - /** After this time intervel, message should be considered as expired (In seconds). */ - @Value("${mosip.regproc.verification.message.expiry-time-limit}") - private Long messageExpiryTimeLimit; - - private static final String APPLICATION_JSON = "application/json"; - - /** - * Deploy stage. - */ - public void deployVerticle() { - this.mosipEventBus = this.getEventBus(this, clusterManagerUrl, workerPoolSize); - this.consume(mosipEventBus, MessageBusAddress.VERIFICATION_BUS_IN, messageExpiryTimeLimit); - queue = getQueueConnection(); - if (queue != null) { - - QueueListener listener = new QueueListener() { - @Override - public void setListener(Message message) { - consumerListener(message); - } - }; - - mosipQueueManager.consume(queue, mvResponseAddress, listener); - - } else { - throw new QueueConnectionNotFound(PlatformErrorMessages.RPR_PRT_QUEUE_CONNECTION_NULL.getMessage()); - } - - } - - @Override - public void start() { - router.setRoute(this.postUrl(getVertx(), MessageBusAddress.MANUAL_ADJUDICATION_BUS_IN, MessageBusAddress.MANUAL_ADJUDICATION_BUS_OUT)); - this.createServer(router.getRouter(), getPort()); - } - - @Override - protected String getPropertyPrefix() { - return STAGE_PROPERTY_PREFIX; - } - - public void sendMessage(MessageDTO messageDTO) { - this.send(this.mosipEventBus, MessageBusAddress.VERIFICATION_BUS_OUT, messageDTO); - } - - @Override - public MessageDTO process(MessageDTO object) { - return verificationService.process(object, queue, CLASS_NAME); - } - - private MosipQueue getQueueConnection() { - String failOverBrokerUrl = FAIL_OVER + url + "," + url + RANDOMIZE_FALSE; - return mosipConnectionFactory.createConnection(typeOfQueue, username, password, failOverBrokerUrl); - } - - public void consumerListener(Message message) { - try { - String response = null; - if (message instanceof ActiveMQBytesMessage) { - response = new String(((ActiveMQBytesMessage) message).getContent().data); - } else if (message instanceof ActiveMQTextMessage) { - TextMessage textMessage = (TextMessage) message; - response = textMessage.getText(); - } - regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REFERENCEID.toString(), - "Response received from mv system", response); - if (response == null) { - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), - PlatformErrorMessages.RPR_INVALID_MESSSAGE.getCode(), PlatformErrorMessages.RPR_INVALID_MESSSAGE.getMessage()); - throw new InvalidMessageException(PlatformErrorMessages.RPR_INVALID_MESSSAGE.getCode(), PlatformErrorMessages.RPR_INVALID_MESSSAGE.getMessage()); - } - VerificationResponseDTO resp = JsonUtil.readValueWithUnknownProperties(response, VerificationResponseDTO.class); - if (resp != null) { - boolean isProcessingSuccessful = verificationService.updatePacketStatus(resp, CLASS_NAME, queue); - - if (isProcessingSuccessful) - regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - "", "ManualVerificationStage::processDecision::success"); - - } - } catch (Exception e) { - regProcLogger.error("","","", ExceptionUtils.getStackTrace(e)); - } - - } -} - +package io.mosip.registration.processor.verification.stage; + +import java.util.List; + +import javax.jms.Message; +import javax.jms.TextMessage; + +import org.apache.activemq.command.ActiveMQBytesMessage; +import org.apache.activemq.command.ActiveMQTextMessage; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.cloud.context.config.annotation.RefreshScope; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Service; + +import io.mosip.kernel.core.exception.ExceptionUtils; +import io.mosip.kernel.core.logger.spi.Logger; +import io.mosip.registration.processor.core.abstractverticle.MessageBusAddress; +import io.mosip.registration.processor.core.abstractverticle.MessageDTO; +import io.mosip.registration.processor.core.abstractverticle.MosipEventBus; +import io.mosip.registration.processor.core.abstractverticle.MosipRouter; +import io.mosip.registration.processor.core.abstractverticle.MosipVerticleAPIManager; +import io.mosip.registration.processor.core.constant.LoggerFileConstant; +import io.mosip.registration.processor.core.exception.util.PlatformErrorMessages; +import io.mosip.registration.processor.core.logger.RegProcessorLogger; +import io.mosip.registration.processor.core.queue.factory.MosipQueue; +import io.mosip.registration.processor.core.queue.factory.QueueListener; +import io.mosip.registration.processor.core.spi.queue.MosipQueueConnectionFactory; +import io.mosip.registration.processor.core.spi.queue.MosipQueueManager; +import io.mosip.registration.processor.core.util.JsonUtil; +import io.mosip.registration.processor.packet.storage.exception.QueueConnectionNotFound; +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.exception.InvalidMessageException; +import io.mosip.registration.processor.verification.exception.handler.ManualVerificationExceptionHandler; +import io.mosip.registration.processor.verification.response.dto.VerificationResponseDTO; +import io.mosip.registration.processor.verification.service.VerificationService; +import io.mosip.registration.processor.verification.util.ManualVerificationRequestValidator; + +/** + * This class sends message to next stage after successful completion of manual + * verification. + * + * @author Pranav Kumar + * @since 0.0.1 + */ +@RefreshScope +@Service +@Configuration +@ComponentScan(basePackages = { "${mosip.auth.adapter.impl.basepackage}", + "io.mosip.registration.processor.core.config", + "io.mosip.registration.processor.verification.config", + "io.mosip.registration.processor.packet.receiver.config", + "io.mosip.registration.processor.packet.manager.config", + "io.mosip.kernel.packetmanager.config", + "io.mosip.registration.processor.status.config", "io.mosip.registration.processor.rest.client.config", + "io.mosip.registration.processor.core.kernel.beans", + "io.mosip.registration.processor.packet.storage.config", + "io.mosip.registration.processor.verification.validators"}) +public class VerificationStage extends MosipVerticleAPIManager { + + private static final String STAGE_PROPERTY_PREFIX = "mosip.regproc.verification."; + private static final String CLASS_NAME = "VerificationStage"; + + @Autowired + private VerificationService verificationService; + + /** The core audit request builder. */ + @Autowired + private AuditLogRequestBuilder auditLogRequestBuilder; + + /** The registration status service. */ + @Autowired + RegistrationStatusService registrationStatusService; + + /** The mosip event bus. */ + private MosipEventBus mosipEventBus; + + /** The mosip queue manager. */ + @Autowired + private MosipQueueManager mosipQueueManager; + + /** + * vertx Cluster Manager Url + */ + @Value("${vertx.cluster.configuration}") + private String clusterManagerUrl; + + /** The reg proc logger. */ + private static Logger regProcLogger = RegProcessorLogger.getLogger(VerificationStage.class); + + /** The env. */ + @Autowired + private Environment env; + + @Autowired + ManualVerificationRequestValidator manualVerificationRequestValidator; + + @Autowired + ManualVerificationExceptionHandler manualVerificationExceptionHandler; + + /** Mosip router for APIs */ + @Autowired + MosipRouter router; + + private MosipQueue queue; + + /** The mosip connection factory. */ + @Autowired + private MosipQueueConnectionFactory mosipConnectionFactory; + + /** The username. */ + @Value("${registration.processor.verification.queue.username}") + private String username; + + /** The password. */ + @Value("${registration.processor.verification.queue.password}") + private String password; + + /** The type of queue. */ + @Value("${registration.processor.verification.queue.typeOfQueue}") + private String typeOfQueue; + + /** The address. */ + @Value("${registration.processor.verification.queue.response:verification-to-mosip}") + private String mvResponseAddress; + + @Value("#{'${registration.processor.verification.queue.trusted.packages}'.split(',')}") + private List trustedPackages; + + /** The Constant FAIL_OVER. */ + private static final String FAIL_OVER = "failover:("; + + /** The Constant RANDOMIZE_FALSE. */ + private static final String RANDOMIZE_FALSE = ")?randomize=false"; + + private static final String CONFIGURE_MONITOR_IN_ACTIVITY = "?wireFormat.maxInactivityDuration=0"; + + /** The url. */ + @Value("${registration.processor.verification.queue.url}") + private String url; + + /** worker pool size. */ + @Value("${worker.pool.size}") + private Integer workerPoolSize; + + /** After this time intervel, message should be considered as expired (In seconds). */ + @Value("${mosip.regproc.verification.message.expiry-time-limit}") + private Long messageExpiryTimeLimit; + + private static final String APPLICATION_JSON = "application/json"; + + /** + * Deploy stage. + */ + public void deployVerticle() { + this.mosipEventBus = this.getEventBus(this, clusterManagerUrl, workerPoolSize); + this.consume(mosipEventBus, MessageBusAddress.VERIFICATION_BUS_IN, messageExpiryTimeLimit); + queue = getQueueConnection(); + if (queue != null) { + + QueueListener listener = new QueueListener() { + @Override + public void setListener(Message message) { + consumerListener(message); + } + }; + + mosipQueueManager.consume(queue, mvResponseAddress, listener); + + } else { + throw new QueueConnectionNotFound(PlatformErrorMessages.RPR_PRT_QUEUE_CONNECTION_NULL.getMessage()); + } + + } + + @Override + public void start() { + router.setRoute(this.postUrl(getVertx(), MessageBusAddress.MANUAL_ADJUDICATION_BUS_IN, MessageBusAddress.MANUAL_ADJUDICATION_BUS_OUT)); + this.createServer(router.getRouter(), getPort()); + } + + @Override + protected String getPropertyPrefix() { + return STAGE_PROPERTY_PREFIX; + } + + public void sendMessage(MessageDTO messageDTO) { + this.send(this.mosipEventBus, MessageBusAddress.VERIFICATION_BUS_OUT, messageDTO); + } + + @Override + public MessageDTO process(MessageDTO object) { + return verificationService.process(object, queue, CLASS_NAME); + } + + private MosipQueue getQueueConnection() { + String failOverBrokerUrl = FAIL_OVER + url + "," + url + RANDOMIZE_FALSE; + return mosipConnectionFactory.createConnection(typeOfQueue, username, password, failOverBrokerUrl, + trustedPackages); + } + + public void consumerListener(Message message) { + try { + String response = null; + if (message instanceof ActiveMQBytesMessage) { + response = new String(((ActiveMQBytesMessage) message).getContent().data); + } else if (message instanceof ActiveMQTextMessage) { + TextMessage textMessage = (TextMessage) message; + response = textMessage.getText(); + } + regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REFERENCEID.toString(), + "Response received from mv system", response); + if (response == null) { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), + PlatformErrorMessages.RPR_INVALID_MESSSAGE.getCode(), PlatformErrorMessages.RPR_INVALID_MESSSAGE.getMessage()); + throw new InvalidMessageException(PlatformErrorMessages.RPR_INVALID_MESSSAGE.getCode(), PlatformErrorMessages.RPR_INVALID_MESSSAGE.getMessage()); + } + VerificationResponseDTO resp = JsonUtil.readValueWithUnknownProperties(response, VerificationResponseDTO.class); + if (resp != null) { + boolean isProcessingSuccessful = verificationService.updatePacketStatus(resp, CLASS_NAME, queue); + + if (isProcessingSuccessful) + regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + "", "ManualVerificationStage::processDecision::success"); + + } + } catch (Exception e) { + regProcLogger.error("","","", ExceptionUtils.getStackTrace(e)); + } + + } +} + 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 a2d11886c88..d7383b6ae4d 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 @@ -5,11 +5,7 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; import java.sql.Timestamp; import java.util.ArrayList; @@ -27,7 +23,6 @@ import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; -import org.mockito.ArgumentMatcher; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; @@ -43,8 +38,6 @@ import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.spi.ILoggingEvent; -import ch.qos.logback.classic.spi.LoggingEvent; -import ch.qos.logback.core.Appender; import ch.qos.logback.core.read.ListAppender; import io.mosip.kernel.biometrics.constant.BiometricType; import io.mosip.kernel.biometrics.constant.QualityType; @@ -54,7 +47,6 @@ 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.JsonUtils; import io.mosip.kernel.core.util.exception.JsonProcessingException; import io.mosip.registration.processor.core.abstractverticle.MessageDTO; import io.mosip.registration.processor.core.code.ApiName; @@ -209,7 +201,8 @@ public String getQueueName() { } @Override - public void createConnection(String username, String password, String brokerUrl) { + public void createConnection(String username, String password, String brokerUrl, + List trustedPackage) { } }; diff --git a/registration-processor/core-processor/registration-processor-verification-stage/src/test/java/io/mosip/registration/processor/verification/stage/VerificationStageTest.java b/registration-processor/core-processor/registration-processor-verification-stage/src/test/java/io/mosip/registration/processor/verification/stage/VerificationStageTest.java index 2b3fdfc3b6e..58e48d709b2 100644 --- a/registration-processor/core-processor/registration-processor-verification-stage/src/test/java/io/mosip/registration/processor/verification/stage/VerificationStageTest.java +++ b/registration-processor/core-processor/registration-processor-verification-stage/src/test/java/io/mosip/registration/processor/verification/stage/VerificationStageTest.java @@ -1,190 +1,200 @@ -package io.mosip.registration.processor.verification.stage; - - -import ch.qos.logback.classic.spi.ILoggingEvent; -import ch.qos.logback.classic.spi.LoggingEvent; -import ch.qos.logback.core.Appender; -import io.mosip.kernel.core.signatureutil.model.SignatureResponse; -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.abstractverticle.MosipEventBus; -import io.mosip.registration.processor.core.abstractverticle.MosipRouter; -import io.mosip.registration.processor.core.exception.ApisResourceAccessException; -import io.mosip.registration.processor.core.exception.PacketManagerException; -import io.mosip.registration.processor.core.queue.factory.MosipQueue; -import io.mosip.registration.processor.core.spi.queue.MosipQueueConnectionFactory; -import io.mosip.registration.processor.core.spi.queue.MosipQueueManager; -import io.mosip.registration.processor.verification.response.dto.VerificationResponseDTO; -import io.mosip.registration.processor.verification.service.VerificationService; -import io.mosip.registration.processor.verification.util.ManualVerificationRequestValidator; -import io.vertx.core.Vertx; -import io.vertx.ext.web.FileUpload; -import io.vertx.ext.web.Router; -import io.vertx.ext.web.RoutingContext; -import org.apache.activemq.command.ActiveMQBytesMessage; -import org.apache.activemq.util.ByteSequence; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.ArgumentMatcher; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.slf4j.LoggerFactory; -import org.springframework.core.env.Environment; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.util.ReflectionTestUtils; - -import java.io.File; - -import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.argThat; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.*; - -@RunWith(SpringRunner.class) - -public class VerificationStageTest { - - private static final String STAGE_NAME = "VerificationStage"; - - @Mock - private MosipQueueConnectionFactory mosipConnectionFactory; - @Mock - private MosipQueue mosipQueue; - @Mock - private MosipQueueManager mosipQueueManager; - @Mock - private MosipRouter router; - public RoutingContext ctx; - @Mock - SignatureResponse signatureResponse; - @Mock - private ManualVerificationRequestValidator manualVerificationRequestValidator; - @Mock - private VerificationService verificationService; - @Mock - private Environment env; - @Mock - private MosipEventBus mockEventbus; - private File file; - public FileUpload fileUpload; - private String serviceID=""; - private byte[] packetInfo; - - @InjectMocks - private VerificationStage verificationstage =new VerificationStage() - { - @Override - public void send(MosipEventBus mosipEventBus, MessageBusAddress toAddress, MessageDTO message) { - } - - @Override - public MosipEventBus getEventBus(Object verticleName, String clusterManagerUrl, int instanceNumber) { - return mockEventbus; - } - @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) { - - } - - @Override - public Integer getPort() { - return 8080; - } - }; - @Before - public void setUp() throws java.io.IOException, ApisResourceAccessException, PacketManagerException, JsonProcessingException { - ReflectionTestUtils.setField(verificationstage, "mosipConnectionFactory", mosipConnectionFactory); - ReflectionTestUtils.setField(verificationstage, "mosipQueueManager", mosipQueueManager); - //ReflectionTestUtils.setField(manualverificationstage, "contextPath", "/registrationprocessor/v1/manualverification"); - ReflectionTestUtils.setField(verificationstage, "workerPoolSize", 10); - ReflectionTestUtils.setField(verificationstage, "messageExpiryTimeLimit", Long.valueOf(0)); - ReflectionTestUtils.setField(verificationstage, "clusterManagerUrl", "/dummyPath"); - //Mockito.when(env.getProperty(SwaggerConstant.SERVER_SERVLET_PATH)).thenReturn("/registrationprocessor/v1/manualverification"); - Mockito.when(mosipConnectionFactory.createConnection(any(),any(),any(),any())).thenReturn(mosipQueue); - Mockito.doReturn(new String("str").getBytes()).when(mosipQueueManager).consume(any(), any(), any()); - Mockito.doNothing().when(router).setRoute(any()); - Mockito.when(router.post(any())).thenReturn(null); - Mockito.when(router.get(any())).thenReturn(null); - Mockito.doNothing().when(manualVerificationRequestValidator).validate(any(),any()); - Mockito.when(signatureResponse.getData()).thenReturn("gdshgsahjhghgsad"); - packetInfo="packetInfo".getBytes(); - } - @Test - public void testDeployeVerticle() - { - verificationstage.deployVerticle(); - } - @Test - public void testStart() - { - MessageDTO dto=new MessageDTO(); - verificationstage.process(dto); - verificationstage.sendMessage(dto); - verificationstage.start(); - } - - - @Test - public void testAllProcess() { - MessageDTO messageDTO = new MessageDTO(); - messageDTO.setRid("12345"); - messageDTO.setIsValid(true); - - Mockito.when(verificationService.process(messageDTO, mosipQueue, STAGE_NAME)).thenReturn(messageDTO); - - MessageDTO result = verificationstage.process(messageDTO); - - assertTrue(result.getIsValid()); - } - - @Test - public void testConsumeListener() throws JsonProcessingException { - ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) LoggerFactory - .getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME); - final Appender mockAppender = mock(Appender.class); - when(mockAppender.getName()).thenReturn("MOCK"); - root.addAppender(mockAppender); - - VerificationResponseDTO resp = new VerificationResponseDTO(); - resp.setId("verification"); - resp.setRequestId("e2e59a9b-ce7c-41ae-a953-effb854d1205"); - resp.setResponsetime(DateUtils.getCurrentDateTimeString()); - resp.setReturnValue(1); - - String response = JsonUtils.javaObjectToJsonString(resp); - - ActiveMQBytesMessage amq = new ActiveMQBytesMessage(); - ByteSequence byteSeq = new ByteSequence(); - byteSeq.setData(response.getBytes()); - amq.setContent(byteSeq); - - Mockito.when(verificationService.updatePacketStatus(any(), any(), any())).thenReturn(true); - - verificationstage.consumerListener(amq); - - verify(mockAppender).doAppend(argThat(new ArgumentMatcher() { - - @Override - public boolean matches(ILoggingEvent argument) { - return ((LoggingEvent) argument).getFormattedMessage() - .contains("ManualVerificationStage::processDecision::success"); - } - })); - } - -} - +package io.mosip.registration.processor.verification.stage; + + +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyList; +import static org.mockito.ArgumentMatchers.argThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; + +import org.apache.activemq.command.ActiveMQBytesMessage; +import org.apache.activemq.util.ByteSequence; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentMatcher; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.slf4j.LoggerFactory; +import org.springframework.core.env.Environment; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.util.ReflectionTestUtils; + +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.classic.spi.LoggingEvent; +import ch.qos.logback.core.Appender; +import io.mosip.kernel.core.signatureutil.model.SignatureResponse; +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.abstractverticle.MosipEventBus; +import io.mosip.registration.processor.core.abstractverticle.MosipRouter; +import io.mosip.registration.processor.core.exception.ApisResourceAccessException; +import io.mosip.registration.processor.core.exception.PacketManagerException; +import io.mosip.registration.processor.core.queue.factory.MosipQueue; +import io.mosip.registration.processor.core.spi.queue.MosipQueueConnectionFactory; +import io.mosip.registration.processor.core.spi.queue.MosipQueueManager; +import io.mosip.registration.processor.verification.response.dto.VerificationResponseDTO; +import io.mosip.registration.processor.verification.service.VerificationService; +import io.mosip.registration.processor.verification.util.ManualVerificationRequestValidator; +import io.vertx.core.Vertx; +import io.vertx.ext.web.FileUpload; +import io.vertx.ext.web.Router; +import io.vertx.ext.web.RoutingContext; + +@RunWith(SpringRunner.class) + +public class VerificationStageTest { + + private static final String STAGE_NAME = "VerificationStage"; + + @Mock + private MosipQueueConnectionFactory mosipConnectionFactory; + @Mock + private MosipQueue mosipQueue; + @Mock + private MosipQueueManager mosipQueueManager; + @Mock + private MosipRouter router; + public RoutingContext ctx; + @Mock + SignatureResponse signatureResponse; + @Mock + private ManualVerificationRequestValidator manualVerificationRequestValidator; + @Mock + private VerificationService verificationService; + @Mock + private Environment env; + @Mock + private MosipEventBus mockEventbus; + private File file; + public FileUpload fileUpload; + private String serviceID=""; + private byte[] packetInfo; + + @InjectMocks + private VerificationStage verificationstage =new VerificationStage() + { + @Override + public void send(MosipEventBus mosipEventBus, MessageBusAddress toAddress, MessageDTO message) { + } + + @Override + public MosipEventBus getEventBus(Object verticleName, String clusterManagerUrl, int instanceNumber) { + return mockEventbus; + } + @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) { + + } + + @Override + public Integer getPort() { + return 8080; + } + }; + @Before + public void setUp() throws java.io.IOException, ApisResourceAccessException, PacketManagerException, JsonProcessingException { + ReflectionTestUtils.setField(verificationstage, "mosipConnectionFactory", mosipConnectionFactory); + ReflectionTestUtils.setField(verificationstage, "mosipQueueManager", mosipQueueManager); + //ReflectionTestUtils.setField(manualverificationstage, "contextPath", "/registrationprocessor/v1/manualverification"); + ReflectionTestUtils.setField(verificationstage, "workerPoolSize", 10); + ReflectionTestUtils.setField(verificationstage, "messageExpiryTimeLimit", Long.valueOf(0)); + ReflectionTestUtils.setField(verificationstage, "clusterManagerUrl", "/dummyPath"); + List trustedPackageList = new ArrayList(); + trustedPackageList.add("io.mosip.*"); + ReflectionTestUtils.setField(verificationstage, "trustedPackages", trustedPackageList); + //Mockito.when(env.getProperty(SwaggerConstant.SERVER_SERVLET_PATH)).thenReturn("/registrationprocessor/v1/manualverification"); + Mockito.when(mosipConnectionFactory.createConnection(any(), any(), any(), any(), anyList())) + .thenReturn(mosipQueue); + Mockito.doReturn(new String("str").getBytes()).when(mosipQueueManager).consume(any(), any(), any()); + Mockito.doNothing().when(router).setRoute(any()); + Mockito.when(router.post(any())).thenReturn(null); + Mockito.when(router.get(any())).thenReturn(null); + Mockito.doNothing().when(manualVerificationRequestValidator).validate(any(),any()); + Mockito.when(signatureResponse.getData()).thenReturn("gdshgsahjhghgsad"); + packetInfo="packetInfo".getBytes(); + } + @Test + public void testDeployeVerticle() + { + verificationstage.deployVerticle(); + } + @Test + public void testStart() + { + MessageDTO dto=new MessageDTO(); + verificationstage.process(dto); + verificationstage.sendMessage(dto); + verificationstage.start(); + } + + + @Test + public void testAllProcess() { + MessageDTO messageDTO = new MessageDTO(); + messageDTO.setRid("12345"); + messageDTO.setIsValid(true); + + Mockito.when(verificationService.process(messageDTO, mosipQueue, STAGE_NAME)).thenReturn(messageDTO); + + MessageDTO result = verificationstage.process(messageDTO); + + assertTrue(result.getIsValid()); + } + + @Test + public void testConsumeListener() throws JsonProcessingException { + ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) LoggerFactory + .getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME); + final Appender mockAppender = mock(Appender.class); + when(mockAppender.getName()).thenReturn("MOCK"); + root.addAppender(mockAppender); + + VerificationResponseDTO resp = new VerificationResponseDTO(); + resp.setId("verification"); + resp.setRequestId("e2e59a9b-ce7c-41ae-a953-effb854d1205"); + resp.setResponsetime(DateUtils.getCurrentDateTimeString()); + resp.setReturnValue(1); + + String response = JsonUtils.javaObjectToJsonString(resp); + + ActiveMQBytesMessage amq = new ActiveMQBytesMessage(); + ByteSequence byteSeq = new ByteSequence(); + byteSeq.setData(response.getBytes()); + amq.setContent(byteSeq); + + Mockito.when(verificationService.updatePacketStatus(any(), any(), any())).thenReturn(true); + + verificationstage.consumerListener(amq); + + verify(mockAppender).doAppend(argThat(new ArgumentMatcher() { + + @Override + public boolean matches(ILoggingEvent argument) { + return ((LoggingEvent) argument).getFormattedMessage() + .contains("ManualVerificationStage::processDecision::success"); + } + })); + } + +} + diff --git a/registration-processor/registration-processor-core/pom.xml b/registration-processor/registration-processor-core/pom.xml index a595827a779..91513584e46 100644 --- a/registration-processor/registration-processor-core/pom.xml +++ b/registration-processor/registration-processor-core/pom.xml @@ -63,8 +63,8 @@ org.apache.activemq - activemq-core - 5.7.0 + activemq-client + 5.17.4 org.springframework.boot 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 b16d7b43872..7edb0ae8188 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 @@ -14,6 +14,8 @@ import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; +import java.util.Arrays; +import java.util.List; import javax.jms.Message; import javax.jms.MessageConsumer; @@ -36,6 +38,7 @@ 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; @@ -83,6 +86,7 @@ public class StageHealthCheckHandler implements HealthCheckHandler { private String queueUsername; private String queuePassword; private String queueBrokerUrl; + private List queueTrustedPackages; private Boolean isAuthEnable; private int virusScannerPort; private File currentWorkingDirPath; @@ -126,6 +130,12 @@ public StageHealthCheckHandler(Vertx vertx, AuthProvider provider, ObjectMapper this.queueUsername = environment.getProperty(HealthConstant.QUEUE_USERNAME); this.queuePassword = environment.getProperty(HealthConstant.QUEUE_PASSWORD); this.queueBrokerUrl = environment.getProperty(HealthConstant.QUEUE_BROKER_URL); + String queueTrustedPackage = environment.getProperty(HealthConstant.QUEUE_TRUSTED_PACKAGE); + if (queueTrustedPackage == null) { + throw new RuntimeException("Property registration.processor.queue.trusted.packages not found"); + } + this.queueTrustedPackages = Arrays + .asList(queueTrustedPackage.split(",")); this.currentWorkingDirPath = new File(System.getProperty(HealthConstant.CURRENT_WORKING_DIRECTORY)); this.resultBuilder = new StageHealthCheckHandler.JSONResultBuilder(); this.virusScanner = virusScanner; @@ -153,7 +163,7 @@ public void queueHealthChecker(Promise promise, MosipQueueManager trustedPackages) { this.queueName = queueName; this.username = username; this.password = password; this.brokerUrl = brokerUrl; - createConnection(username, password, brokerUrl); + createConnection(username, password, brokerUrl, trustedPackages); } public String getUsername() { @@ -35,8 +37,11 @@ public ActiveMQConnectionFactory getActiveMQConnectionFactory() { } @Override - public void createConnection(String username, String password, String brokerUrl) { - this.activeMQConnectionFactory = new ActiveMQConnectionFactory(username, password, brokerUrl);//NOSONAR + public void createConnection(String username, String password, String brokerUrl, List trustedPackages) { + this.activeMQConnectionFactory = new ActiveMQConnectionFactory(username, password, brokerUrl); + if (activeMQConnectionFactory != null) { + activeMQConnectionFactory.setTrustedPackages(trustedPackages); + } } @Override diff --git a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/queue/factory/MosipQueue.java b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/queue/factory/MosipQueue.java index c994006f9cd..a88cbf5e3fb 100644 --- a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/queue/factory/MosipQueue.java +++ b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/queue/factory/MosipQueue.java @@ -1,8 +1,11 @@ package io.mosip.registration.processor.core.queue.factory; +import java.util.List; + public abstract class MosipQueue{ - public abstract void createConnection(String username, String password, String brokerUrl); + public abstract void createConnection(String username, String password, String brokerUrl, + List trustedPackage); public abstract String getQueueName(); diff --git a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/queue/factory/MosipQueueConnectionFactoryImpl.java b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/queue/factory/MosipQueueConnectionFactoryImpl.java index 86131219c7c..ae8b56efff3 100644 --- a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/queue/factory/MosipQueueConnectionFactoryImpl.java +++ b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/queue/factory/MosipQueueConnectionFactoryImpl.java @@ -1,14 +1,16 @@ package io.mosip.registration.processor.core.queue.factory; +import java.util.List; + import io.mosip.registration.processor.core.spi.queue.MosipQueueConnectionFactory; public class MosipQueueConnectionFactoryImpl implements MosipQueueConnectionFactory { @Override public MosipQueue createConnection(String typeOfQueue, String username, String password, - String url) { + String url, List trustedPackages) { if(typeOfQueue.equalsIgnoreCase("ACTIVEMQ")) { - return new MosipActiveMq(typeOfQueue, username, password, url); + return new MosipActiveMq(typeOfQueue, username, password, url, trustedPackages); } else { return null; diff --git a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/spi/queue/MosipQueueConnectionFactory.java b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/spi/queue/MosipQueueConnectionFactory.java index 631afe3593b..355ba2bb3bd 100644 --- a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/spi/queue/MosipQueueConnectionFactory.java +++ b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/spi/queue/MosipQueueConnectionFactory.java @@ -1,5 +1,7 @@ package io.mosip.registration.processor.core.spi.queue; +import java.util.List; + /** * @author Pranav Kumar * @@ -16,6 +18,7 @@ public interface MosipQueueConnectionFactory { * @param Url Url of installation path * @return */ - public Q createConnection(String typeOfQueue, String username, String password, String Url); + public Q createConnection(String typeOfQueue, String username, String password, String Url, + List trustedPackages); } 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 e14e3b10305..99b7abac080 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 @@ -39,7 +39,6 @@ import io.mosip.registration.processor.core.exception.RegistrationProcessorCheckedException; import io.mosip.registration.processor.core.exception.RegistrationProcessorUnCheckedException; import io.mosip.registration.processor.core.exception.util.PlatformErrorMessages; -import io.mosip.registration.processor.core.idrepo.dto.IdResponseDTO; import io.mosip.registration.processor.core.idrepo.dto.IdResponseDTO1; import io.mosip.registration.processor.core.idrepo.dto.ResponseDTO; import io.mosip.registration.processor.core.logger.RegProcessorLogger; @@ -158,6 +157,9 @@ public class Utilities { @Value("${registration.processor.id.repo.vidVersion}") private String vidVersion; + @Value("#{'${registration.processor.queue.trusted.packages}'.split(',')}") + private List trustedPackages; + @Autowired private PacketInfoDao packetInfoDao; @@ -515,7 +517,7 @@ public List getAbisQueueDetails() throws RegistrationProcessor String queueName = validateAbisQueueJsonAndReturnValue(json, NAME); int inboundMessageTTL = validateAbisQueueJsonAndReturnIntValue(json, INBOUNDMESSAGETTL); MosipQueue mosipQueue = mosipConnectionFactory.createConnection(typeOfQueue, userName, password, - failOverBrokerUrl); + failOverBrokerUrl, trustedPackages); if (mosipQueue == null) throw new QueueConnectionNotFound( PlatformErrorMessages.RPR_PIS_ABIS_QUEUE_CONNECTION_NULL.getMessage()); From 19986ca3ca45897a93fa4ba89bb9af413a8b99c6 Mon Sep 17 00:00:00 2001 From: Keshav Mishra Date: Tue, 13 Jun 2023 17:16:32 +0530 Subject: [PATCH 072/133] [MOSIP-27964] updated upgrade sql's --- .../mosip_regprc/sql/1.1.5.5_to_1.2.0.1-B1_upgrade.sql | 8 +++++++- .../sql/1.2.0.1-B1_to_1.2.0.1-B2_rollback.sql | 1 + .../mosip_regprc/sql/1.2.0.1-B1_to_1.2.0.1-B2_upgrade.sql | 1 + 3 files changed, 9 insertions(+), 1 deletion(-) create mode 100644 db_upgrade_scripts/mosip_regprc/sql/1.2.0.1-B1_to_1.2.0.1-B2_rollback.sql create mode 100644 db_upgrade_scripts/mosip_regprc/sql/1.2.0.1-B1_to_1.2.0.1-B2_upgrade.sql diff --git a/db_upgrade_scripts/mosip_regprc/sql/1.1.5.5_to_1.2.0.1-B1_upgrade.sql b/db_upgrade_scripts/mosip_regprc/sql/1.1.5.5_to_1.2.0.1-B1_upgrade.sql index f000cd0fc3e..11408b69bc7 100644 --- a/db_upgrade_scripts/mosip_regprc/sql/1.1.5.5_to_1.2.0.1-B1_upgrade.sql +++ b/db_upgrade_scripts/mosip_regprc/sql/1.1.5.5_to_1.2.0.1-B1_upgrade.sql @@ -1,4 +1,10 @@ -\c mosip_regprc sysadmin +ALTER DATABASE mosip_regprc OWNER TO postgres; + +GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA regprc TO postgres; + +REVOKE ALL PRIVILEGES ON DATABASE mosip_regprc FROM regprcuser, sysadmin; + +GRANT SELECT, INSERT, TRUNCATE, REFERENCES, UPDATE, DELETE ON ALL TABLES IN SCHEMA regprc TO regprcuser; ----------------------------------------------Multiple table level changes on regprc db------------------------------------------------------- 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' From 1c939d74041ae82f9653e2e52ba51d100449b4e5 Mon Sep 17 00:00:00 2001 From: Keshav Mishra Date: Tue, 13 Jun 2023 22:43:47 +0530 Subject: [PATCH 073/133] [MOSIP-27964] --- .../sql/1.1.5.5_to_1.2.0.1-B1_rollback.sql | 15 +-------------- .../sql/1.1.5.5_to_1.2.0.1-B1_upgrade.sql | 10 +++++++--- 2 files changed, 8 insertions(+), 17 deletions(-) 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 index 4ecae8182d7..e350ef2fccd 100644 --- 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 @@ -1,17 +1,4 @@ --- ------------------------------------------------------------------------------------------------- --- 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 - ---need to drop now after reverting to old columns add old constraint +\c mosip_regprc 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; diff --git a/db_upgrade_scripts/mosip_regprc/sql/1.1.5.5_to_1.2.0.1-B1_upgrade.sql b/db_upgrade_scripts/mosip_regprc/sql/1.1.5.5_to_1.2.0.1-B1_upgrade.sql index 11408b69bc7..1c19df654f3 100644 --- a/db_upgrade_scripts/mosip_regprc/sql/1.1.5.5_to_1.2.0.1-B1_upgrade.sql +++ b/db_upgrade_scripts/mosip_regprc/sql/1.1.5.5_to_1.2.0.1-B1_upgrade.sql @@ -1,11 +1,15 @@ -ALTER DATABASE mosip_regprc OWNER TO postgres; +\c mosip_regprc -GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA regprc TO postgres; +REASSIGN OWNED BY sysadmin TO postgres; + +REVOKE ALL PRIVILEGES ON ALL TABLES IN SCHEMA regprc FROM regprcuser; -REVOKE ALL PRIVILEGES ON DATABASE mosip_regprc FROM regprcuser, sysadmin; +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------------------------------------------------------- ALTER TABLE regprc.individual_demographic_dedup DROP CONSTRAINT IF EXISTS fk_idemogd_reg CASCADE; From 315c197ec2c5f104eaa2ab6667c535446f2c486e Mon Sep 17 00:00:00 2001 From: Sowmya Ujjappa Banakar <43202851+sowmya695@users.noreply.github.com> Date: Wed, 14 Jun 2023 16:23:29 +0530 Subject: [PATCH 074/133] MOSIP-27981 script changes (#1721) Co-authored-by: Sowmya Ujjappa Banakar --- .../mosip_regprc/sql/1.1.5.5_to_1.2.0.1-B1_upgrade.sql | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/db_upgrade_scripts/mosip_regprc/sql/1.1.5.5_to_1.2.0.1-B1_upgrade.sql b/db_upgrade_scripts/mosip_regprc/sql/1.1.5.5_to_1.2.0.1-B1_upgrade.sql index 1c19df654f3..d7bfad42ac4 100644 --- a/db_upgrade_scripts/mosip_regprc/sql/1.1.5.5_to_1.2.0.1-B1_upgrade.sql +++ b/db_upgrade_scripts/mosip_regprc/sql/1.1.5.5_to_1.2.0.1-B1_upgrade.sql @@ -301,3 +301,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 From ffaaf29364978a2a68b633d498839fb47549f017 Mon Sep 17 00:00:00 2001 From: Keshav Mishra Date: Thu, 15 Jun 2023 08:14:24 +0530 Subject: [PATCH 075/133] [MOSIP-27996] updated rollback sql --- .../mosip_regprc/sql/1.1.5.5_to_1.2.0.1-B1_rollback.sql | 4 ++++ 1 file changed, 4 insertions(+) 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 index e350ef2fccd..f0efae48dcd 100644 --- 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 @@ -1,5 +1,9 @@ \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; From e1726604eb3cb1283ec4638685f83f4ad6f86e4f Mon Sep 17 00:00:00 2001 From: Mohan E Date: Wed, 21 Jun 2023 19:48:51 +0530 Subject: [PATCH 076/133] [MOSIP-23218] Updated Pom.xml versions. (#1726) --- pom.xml | 2 +- registration-processor/core-processor/pom.xml | 4 ++-- .../registration-processor-abis-handler-stage/pom.xml | 2 +- .../registration-processor-abis-middleware-stage/pom.xml | 4 ++-- .../core-processor/registration-processor-abis/pom.xml | 4 ++-- .../registration-processor-bio-dedupe-stage/pom.xml | 2 +- .../pom.xml | 2 +- .../registration-processor-biometric-extraction-stage/pom.xml | 2 +- .../registration-processor-demo-dedupe-stage/pom.xml | 2 +- .../registration-processor-finalization-stage/pom.xml | 2 +- .../registration-processor-manual-adjudication-stage/pom.xml | 2 +- .../registration-processor-uin-generator-stage/pom.xml | 2 +- .../registration-processor-verification-stage/pom.xml | 2 +- registration-processor/init/pom.xml | 2 +- .../init/registration-processor-dmz-packet-server/version.xml | 2 +- .../init/registration-processor-packet-receiver-stage/pom.xml | 2 +- .../pom.xml | 2 +- registration-processor/mosip-stage-executor/pom.xml | 2 +- registration-processor/pom.xml | 2 +- registration-processor/post-processor/pom.xml | 2 +- .../registration-processor-message-sender-stage/pom.xml | 2 +- .../registration-processor-printing-stage/pom.xml | 2 +- .../pom.xml | 2 +- registration-processor/pre-processor/pom.xml | 2 +- .../registration-processor-cmd-validator-stage/pom.xml | 2 +- .../registration-processor-introducer-validator-stage/pom.xml | 2 +- .../registration-processor-operator-validator-stage/pom.xml | 2 +- .../registration-processor-packet-classifier-stage/pom.xml | 2 +- .../registration-processor-packet-uploader-stage/pom.xml | 2 +- .../registration-processor-packet-validator-stage/pom.xml | 2 +- .../registration-processor-quality-classifier-stage/pom.xml | 2 +- .../pom.xml | 2 +- .../registration-processor-supervisor-validator-stage/pom.xml | 2 +- .../registration-processor-bio-dedupe-service-impl/pom.xml | 2 +- .../dependency-reduced-pom.xml | 2 +- .../registration-processor-common-camel-bridge/pom.xml | 2 +- registration-processor/registration-processor-core/pom.xml | 2 +- .../registration-processor-info-storage-service/pom.xml | 2 +- .../registration-processor-landing-zone/pom.xml | 2 +- .../registration-processor-message-sender-impl/pom.xml | 2 +- .../registration-processor-notification-service/pom.xml | 2 +- .../registration-processor-packet-manager/pom.xml | 2 +- .../pom.xml | 2 +- .../registration-processor-rest-client/pom.xml | 2 +- registration-processor/stage-groups/pom.xml | 2 +- .../stage-groups/registration-processor-stage-group-1/pom.xml | 2 +- .../stage-groups/registration-processor-stage-group-2/pom.xml | 2 +- .../stage-groups/registration-processor-stage-group-3/pom.xml | 2 +- .../stage-groups/registration-processor-stage-group-4/pom.xml | 2 +- .../stage-groups/registration-processor-stage-group-5/pom.xml | 2 +- .../stage-groups/registration-processor-stage-group-6/pom.xml | 2 +- .../stage-groups/registration-processor-stage-group-7/pom.xml | 2 +- registration-processor/workflow-engine/pom.xml | 2 +- .../registration-processor-reprocessor/pom.xml | 2 +- .../registration-processor-workflow-manager-service/pom.xml | 2 +- 55 files changed, 58 insertions(+), 58 deletions(-) diff --git a/pom.xml b/pom.xml index ddfcf0c2386..965197ff54e 100644 --- a/pom.xml +++ b/pom.xml @@ -4,7 +4,7 @@ 4.0.0 io.mosip registration - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT pom MOSIP Registration Parent POM diff --git a/registration-processor/core-processor/pom.xml b/registration-processor/core-processor/pom.xml index 151372b736c..1e70249927a 100644 --- a/registration-processor/core-processor/pom.xml +++ b/registration-processor/core-processor/pom.xml @@ -5,9 +5,9 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT core-processor core-processor diff --git a/registration-processor/core-processor/registration-processor-abis-handler-stage/pom.xml b/registration-processor/core-processor/registration-processor-abis-handler-stage/pom.xml index 2898847f6e4..cce8abec805 100644 --- a/registration-processor/core-processor/registration-processor-abis-handler-stage/pom.xml +++ b/registration-processor/core-processor/registration-processor-abis-handler-stage/pom.xml @@ -5,7 +5,7 @@ io.mosip.registrationprocessor core-processor - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT registration-processor-abis-handler-stage diff --git a/registration-processor/core-processor/registration-processor-abis-middleware-stage/pom.xml b/registration-processor/core-processor/registration-processor-abis-middleware-stage/pom.xml index 0ac1f969ba7..e50a32b7d0d 100644 --- a/registration-processor/core-processor/registration-processor-abis-middleware-stage/pom.xml +++ b/registration-processor/core-processor/registration-processor-abis-middleware-stage/pom.xml @@ -5,10 +5,10 @@ io.mosip.registrationprocessor core-processor - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT registration-processor-abis-middleware-stage - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT jar UTF-8 diff --git a/registration-processor/core-processor/registration-processor-abis/pom.xml b/registration-processor/core-processor/registration-processor-abis/pom.xml index d87e2f20943..29a7bcb63ff 100644 --- a/registration-processor/core-processor/registration-processor-abis/pom.xml +++ b/registration-processor/core-processor/registration-processor-abis/pom.xml @@ -8,10 +8,10 @@ io.mosip.registrationprocessor core-processor - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT registration-processor-abis - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT registration-processor-abis UTF-8 diff --git a/registration-processor/core-processor/registration-processor-bio-dedupe-stage/pom.xml b/registration-processor/core-processor/registration-processor-bio-dedupe-stage/pom.xml index 389718ebcc0..95bc137e14a 100644 --- a/registration-processor/core-processor/registration-processor-bio-dedupe-stage/pom.xml +++ b/registration-processor/core-processor/registration-processor-bio-dedupe-stage/pom.xml @@ -5,7 +5,7 @@ io.mosip.registrationprocessor core-processor - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT registration-processor-bio-dedupe-stage diff --git a/registration-processor/core-processor/registration-processor-biometric-authentication-stage/pom.xml b/registration-processor/core-processor/registration-processor-biometric-authentication-stage/pom.xml index d96b5b1e3b0..fe31a4ea07e 100644 --- a/registration-processor/core-processor/registration-processor-biometric-authentication-stage/pom.xml +++ b/registration-processor/core-processor/registration-processor-biometric-authentication-stage/pom.xml @@ -5,7 +5,7 @@ io.mosip.registrationprocessor core-processor - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT registration-processor-biometric-authentication-stage 1.2.0.1-B3-SNAPSHOT diff --git a/registration-processor/core-processor/registration-processor-biometric-extraction-stage/pom.xml b/registration-processor/core-processor/registration-processor-biometric-extraction-stage/pom.xml index 632ef87f0d8..ca855cd09a6 100644 --- a/registration-processor/core-processor/registration-processor-biometric-extraction-stage/pom.xml +++ b/registration-processor/core-processor/registration-processor-biometric-extraction-stage/pom.xml @@ -5,7 +5,7 @@ io.mosip.registrationprocessor core-processor - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT registration-processor-biometric-extraction-stage jar diff --git a/registration-processor/core-processor/registration-processor-demo-dedupe-stage/pom.xml b/registration-processor/core-processor/registration-processor-demo-dedupe-stage/pom.xml index 250129bc0b2..7bbbc1ca2f7 100644 --- a/registration-processor/core-processor/registration-processor-demo-dedupe-stage/pom.xml +++ b/registration-processor/core-processor/registration-processor-demo-dedupe-stage/pom.xml @@ -5,7 +5,7 @@ io.mosip.registrationprocessor core-processor - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT registration-processor-demo-dedupe-stage 1.2.0.1-B3-SNAPSHOT diff --git a/registration-processor/core-processor/registration-processor-finalization-stage/pom.xml b/registration-processor/core-processor/registration-processor-finalization-stage/pom.xml index 5c4c1f4b052..60f881cedfa 100644 --- a/registration-processor/core-processor/registration-processor-finalization-stage/pom.xml +++ b/registration-processor/core-processor/registration-processor-finalization-stage/pom.xml @@ -5,7 +5,7 @@ io.mosip.registrationprocessor core-processor - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT registration-processor-finalization-stage registration-processor-finalization-stage diff --git a/registration-processor/core-processor/registration-processor-manual-adjudication-stage/pom.xml b/registration-processor/core-processor/registration-processor-manual-adjudication-stage/pom.xml index a038ba9834b..0e8d2e4ba94 100644 --- a/registration-processor/core-processor/registration-processor-manual-adjudication-stage/pom.xml +++ b/registration-processor/core-processor/registration-processor-manual-adjudication-stage/pom.xml @@ -8,7 +8,7 @@ io.mosip.registrationprocessor core-processor - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT registration-processor-manual-adjudication-stage diff --git a/registration-processor/core-processor/registration-processor-uin-generator-stage/pom.xml b/registration-processor/core-processor/registration-processor-uin-generator-stage/pom.xml index cf8b130ebc2..2c1e7a399f9 100644 --- a/registration-processor/core-processor/registration-processor-uin-generator-stage/pom.xml +++ b/registration-processor/core-processor/registration-processor-uin-generator-stage/pom.xml @@ -4,7 +4,7 @@ io.mosip.registrationprocessor core-processor - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT registration-processor-uin-generator-stage 1.2.0.1-B3-SNAPSHOT diff --git a/registration-processor/core-processor/registration-processor-verification-stage/pom.xml b/registration-processor/core-processor/registration-processor-verification-stage/pom.xml index f024202aa8c..2dc976993dd 100644 --- a/registration-processor/core-processor/registration-processor-verification-stage/pom.xml +++ b/registration-processor/core-processor/registration-processor-verification-stage/pom.xml @@ -8,7 +8,7 @@ io.mosip.registrationprocessor core-processor - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT registration-processor-verification-stage diff --git a/registration-processor/init/pom.xml b/registration-processor/init/pom.xml index f51c8554a6a..b7e170a1cdb 100644 --- a/registration-processor/init/pom.xml +++ b/registration-processor/init/pom.xml @@ -6,7 +6,7 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT init diff --git a/registration-processor/init/registration-processor-dmz-packet-server/version.xml b/registration-processor/init/registration-processor-dmz-packet-server/version.xml index b0631be5aed..0caefe39b1b 100644 --- a/registration-processor/init/registration-processor-dmz-packet-server/version.xml +++ b/registration-processor/init/registration-processor-dmz-packet-server/version.xml @@ -1,2 +1,2 @@ -1.2.0.1-B3-SNAPSHOT +1.2.0.1-SNAPSHOT diff --git a/registration-processor/init/registration-processor-packet-receiver-stage/pom.xml b/registration-processor/init/registration-processor-packet-receiver-stage/pom.xml index efcb0fd2b6e..da95b11d37c 100644 --- a/registration-processor/init/registration-processor-packet-receiver-stage/pom.xml +++ b/registration-processor/init/registration-processor-packet-receiver-stage/pom.xml @@ -7,7 +7,7 @@ io.mosip.registrationprocessor init - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT registration-processor-packet-receiver-stage diff --git a/registration-processor/init/registration-processor-registration-status-service/pom.xml b/registration-processor/init/registration-processor-registration-status-service/pom.xml index 8e3bc1616f3..0481ef4d6f2 100644 --- a/registration-processor/init/registration-processor-registration-status-service/pom.xml +++ b/registration-processor/init/registration-processor-registration-status-service/pom.xml @@ -8,7 +8,7 @@ io.mosip.registrationprocessor init - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT registration-processor-registration-status-service 1.2.0.1-B3-SNAPSHOT diff --git a/registration-processor/mosip-stage-executor/pom.xml b/registration-processor/mosip-stage-executor/pom.xml index 6e7c5a64e31..6e2214ed23f 100644 --- a/registration-processor/mosip-stage-executor/pom.xml +++ b/registration-processor/mosip-stage-executor/pom.xml @@ -5,7 +5,7 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT mosip-stage-executor diff --git a/registration-processor/pom.xml b/registration-processor/pom.xml index addf92e9d25..ec58b3826be 100644 --- a/registration-processor/pom.xml +++ b/registration-processor/pom.xml @@ -5,7 +5,7 @@ io.mosip registration - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT io.mosip.registrationprocessor diff --git a/registration-processor/post-processor/pom.xml b/registration-processor/post-processor/pom.xml index 63db0d9e953..5f925f037a1 100644 --- a/registration-processor/post-processor/pom.xml +++ b/registration-processor/post-processor/pom.xml @@ -6,7 +6,7 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT 1.2.0.1-B3-SNAPSHOT post-processor diff --git a/registration-processor/post-processor/registration-processor-message-sender-stage/pom.xml b/registration-processor/post-processor/registration-processor-message-sender-stage/pom.xml index 18eb0f7e221..057fe669758 100644 --- a/registration-processor/post-processor/registration-processor-message-sender-stage/pom.xml +++ b/registration-processor/post-processor/registration-processor-message-sender-stage/pom.xml @@ -7,7 +7,7 @@ io.mosip.registrationprocessor post-processor - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT registration-processor-message-sender-stage diff --git a/registration-processor/post-processor/registration-processor-printing-stage/pom.xml b/registration-processor/post-processor/registration-processor-printing-stage/pom.xml index fa180da83b3..8e25653e013 100644 --- a/registration-processor/post-processor/registration-processor-printing-stage/pom.xml +++ b/registration-processor/post-processor/registration-processor-printing-stage/pom.xml @@ -6,7 +6,7 @@ io.mosip.registrationprocessor post-processor - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT registration-processor-printing-stage 1.2.0.1-B3-SNAPSHOT diff --git a/registration-processor/post-processor/registration-processor-registration-transaction-service/pom.xml b/registration-processor/post-processor/registration-processor-registration-transaction-service/pom.xml index b3f9a5881f8..d2ac01993ca 100644 --- a/registration-processor/post-processor/registration-processor-registration-transaction-service/pom.xml +++ b/registration-processor/post-processor/registration-processor-registration-transaction-service/pom.xml @@ -5,7 +5,7 @@ io.mosip.registrationprocessor post-processor - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT registration-processor-registration-transaction-service 1.2.0.1-B3-SNAPSHOT diff --git a/registration-processor/pre-processor/pom.xml b/registration-processor/pre-processor/pom.xml index eb0d8053ee4..5942a27d5ea 100644 --- a/registration-processor/pre-processor/pom.xml +++ b/registration-processor/pre-processor/pom.xml @@ -7,7 +7,7 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT 1.2.0.1-B3-SNAPSHOT pre-processor diff --git a/registration-processor/pre-processor/registration-processor-cmd-validator-stage/pom.xml b/registration-processor/pre-processor/registration-processor-cmd-validator-stage/pom.xml index e26563acbb4..e1894649798 100644 --- a/registration-processor/pre-processor/registration-processor-cmd-validator-stage/pom.xml +++ b/registration-processor/pre-processor/registration-processor-cmd-validator-stage/pom.xml @@ -6,7 +6,7 @@ io.mosip.registrationprocessor pre-processor - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT registration-processor-cmd-validator-stage 1.2.0.1-B3-SNAPSHOT diff --git a/registration-processor/pre-processor/registration-processor-introducer-validator-stage/pom.xml b/registration-processor/pre-processor/registration-processor-introducer-validator-stage/pom.xml index 5ed7ff56898..e31e01d93c2 100644 --- a/registration-processor/pre-processor/registration-processor-introducer-validator-stage/pom.xml +++ b/registration-processor/pre-processor/registration-processor-introducer-validator-stage/pom.xml @@ -6,7 +6,7 @@ io.mosip.registrationprocessor pre-processor - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT registration-processor-introducer-validator-stage 1.2.0.1-B3-SNAPSHOT diff --git a/registration-processor/pre-processor/registration-processor-operator-validator-stage/pom.xml b/registration-processor/pre-processor/registration-processor-operator-validator-stage/pom.xml index 0614385b6dc..a36dea26640 100644 --- a/registration-processor/pre-processor/registration-processor-operator-validator-stage/pom.xml +++ b/registration-processor/pre-processor/registration-processor-operator-validator-stage/pom.xml @@ -6,7 +6,7 @@ io.mosip.registrationprocessor pre-processor - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT registration-processor-operator-validator-stage 1.2.0.1-B3-SNAPSHOT diff --git a/registration-processor/pre-processor/registration-processor-packet-classifier-stage/pom.xml b/registration-processor/pre-processor/registration-processor-packet-classifier-stage/pom.xml index ac9bdd4c9ac..0bc2430b17c 100644 --- a/registration-processor/pre-processor/registration-processor-packet-classifier-stage/pom.xml +++ b/registration-processor/pre-processor/registration-processor-packet-classifier-stage/pom.xml @@ -7,7 +7,7 @@ io.mosip.registrationprocessor pre-processor - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT registration-processor-packet-classifier-stage 1.2.0.1-B3-SNAPSHOT diff --git a/registration-processor/pre-processor/registration-processor-packet-uploader-stage/pom.xml b/registration-processor/pre-processor/registration-processor-packet-uploader-stage/pom.xml index a2d34372840..6c736b32d7d 100644 --- a/registration-processor/pre-processor/registration-processor-packet-uploader-stage/pom.xml +++ b/registration-processor/pre-processor/registration-processor-packet-uploader-stage/pom.xml @@ -9,7 +9,7 @@ io.mosip.registrationprocessor pre-processor - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT 1.2.0.1-B3-SNAPSHOT diff --git a/registration-processor/pre-processor/registration-processor-packet-validator-stage/pom.xml b/registration-processor/pre-processor/registration-processor-packet-validator-stage/pom.xml index e9f91aff301..3fbe12d4258 100644 --- a/registration-processor/pre-processor/registration-processor-packet-validator-stage/pom.xml +++ b/registration-processor/pre-processor/registration-processor-packet-validator-stage/pom.xml @@ -7,7 +7,7 @@ io.mosip.registrationprocessor pre-processor - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT registration-processor-packet-validator-stage 1.2.0.1-B3-SNAPSHOT diff --git a/registration-processor/pre-processor/registration-processor-quality-classifier-stage/pom.xml b/registration-processor/pre-processor/registration-processor-quality-classifier-stage/pom.xml index bdb4c0718b6..593782e41e7 100644 --- a/registration-processor/pre-processor/registration-processor-quality-classifier-stage/pom.xml +++ b/registration-processor/pre-processor/registration-processor-quality-classifier-stage/pom.xml @@ -5,7 +5,7 @@ io.mosip.registrationprocessor pre-processor - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT registration-processor-quality-classifier-stage diff --git a/registration-processor/pre-processor/registration-processor-securezone-notification-stage/pom.xml b/registration-processor/pre-processor/registration-processor-securezone-notification-stage/pom.xml index 2a9d8088b62..9fbcfed20ab 100644 --- a/registration-processor/pre-processor/registration-processor-securezone-notification-stage/pom.xml +++ b/registration-processor/pre-processor/registration-processor-securezone-notification-stage/pom.xml @@ -5,7 +5,7 @@ pre-processor io.mosip.registrationprocessor - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT 4.0.0 1.2.0.1-B3-SNAPSHOT diff --git a/registration-processor/pre-processor/registration-processor-supervisor-validator-stage/pom.xml b/registration-processor/pre-processor/registration-processor-supervisor-validator-stage/pom.xml index b670cf40e5e..6e090315b6c 100644 --- a/registration-processor/pre-processor/registration-processor-supervisor-validator-stage/pom.xml +++ b/registration-processor/pre-processor/registration-processor-supervisor-validator-stage/pom.xml @@ -6,7 +6,7 @@ io.mosip.registrationprocessor pre-processor - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT registration-processor-supervisor-validator-stage 1.2.0.1-B3-SNAPSHOT diff --git a/registration-processor/registration-processor-bio-dedupe-service-impl/pom.xml b/registration-processor/registration-processor-bio-dedupe-service-impl/pom.xml index d5e235c14a9..682cb60e963 100644 --- a/registration-processor/registration-processor-bio-dedupe-service-impl/pom.xml +++ b/registration-processor/registration-processor-bio-dedupe-service-impl/pom.xml @@ -5,7 +5,7 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT registration-processor-bio-dedupe-service-impl diff --git a/registration-processor/registration-processor-common-camel-bridge/dependency-reduced-pom.xml b/registration-processor/registration-processor-common-camel-bridge/dependency-reduced-pom.xml index 4261c6a15b1..a761ced8384 100644 --- a/registration-processor/registration-processor-common-camel-bridge/dependency-reduced-pom.xml +++ b/registration-processor/registration-processor-common-camel-bridge/dependency-reduced-pom.xml @@ -3,7 +3,7 @@ registration-processor io.mosip.registrationprocessor - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT 4.0.0 registration-processor-common-camel-bridge diff --git a/registration-processor/registration-processor-common-camel-bridge/pom.xml b/registration-processor/registration-processor-common-camel-bridge/pom.xml index 5545298eafa..0d844582de7 100644 --- a/registration-processor/registration-processor-common-camel-bridge/pom.xml +++ b/registration-processor/registration-processor-common-camel-bridge/pom.xml @@ -6,7 +6,7 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT registration-processor-common-camel-bridge 11.2.0.1-B3-SNAPSHOT diff --git a/registration-processor/registration-processor-core/pom.xml b/registration-processor/registration-processor-core/pom.xml index 91513584e46..8aea32f7cae 100644 --- a/registration-processor/registration-processor-core/pom.xml +++ b/registration-processor/registration-processor-core/pom.xml @@ -7,7 +7,7 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT registration-processor-core 1.2.0.1-B3-SNAPSHOT diff --git a/registration-processor/registration-processor-info-storage-service/pom.xml b/registration-processor/registration-processor-info-storage-service/pom.xml index abae39f1150..7a5168904bb 100644 --- a/registration-processor/registration-processor-info-storage-service/pom.xml +++ b/registration-processor/registration-processor-info-storage-service/pom.xml @@ -7,7 +7,7 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT registration-processor-info-storage-service 1.2.0.1-B3-SNAPSHOT diff --git a/registration-processor/registration-processor-landing-zone/pom.xml b/registration-processor/registration-processor-landing-zone/pom.xml index 004f7c06059..08db07b390a 100644 --- a/registration-processor/registration-processor-landing-zone/pom.xml +++ b/registration-processor/registration-processor-landing-zone/pom.xml @@ -5,7 +5,7 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT registration-processor-landing-zone registration-processor-landing-zone diff --git a/registration-processor/registration-processor-message-sender-impl/pom.xml b/registration-processor/registration-processor-message-sender-impl/pom.xml index e053527b446..d105365ac30 100644 --- a/registration-processor/registration-processor-message-sender-impl/pom.xml +++ b/registration-processor/registration-processor-message-sender-impl/pom.xml @@ -8,7 +8,7 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT registration-processor-message-sender-impl diff --git a/registration-processor/registration-processor-notification-service/pom.xml b/registration-processor/registration-processor-notification-service/pom.xml index 5ab85d69ff1..9ffaa7afb76 100644 --- a/registration-processor/registration-processor-notification-service/pom.xml +++ b/registration-processor/registration-processor-notification-service/pom.xml @@ -8,7 +8,7 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT registration-processor-notification-service diff --git a/registration-processor/registration-processor-packet-manager/pom.xml b/registration-processor/registration-processor-packet-manager/pom.xml index 97fab95bbf2..8367c53455d 100644 --- a/registration-processor/registration-processor-packet-manager/pom.xml +++ b/registration-processor/registration-processor-packet-manager/pom.xml @@ -7,7 +7,7 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT registration-processor-packet-manager diff --git a/registration-processor/registration-processor-registration-status-service-impl/pom.xml b/registration-processor/registration-processor-registration-status-service-impl/pom.xml index 9e60b3dfbe4..72f939fd713 100644 --- a/registration-processor/registration-processor-registration-status-service-impl/pom.xml +++ b/registration-processor/registration-processor-registration-status-service-impl/pom.xml @@ -8,7 +8,7 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT registration-processor-registration-status-service-impl 1.2.0.1-B3-SNAPSHOT diff --git a/registration-processor/registration-processor-rest-client/pom.xml b/registration-processor/registration-processor-rest-client/pom.xml index 6212b77b589..585348a6202 100644 --- a/registration-processor/registration-processor-rest-client/pom.xml +++ b/registration-processor/registration-processor-rest-client/pom.xml @@ -9,7 +9,7 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT registration-processor-rest-client diff --git a/registration-processor/stage-groups/pom.xml b/registration-processor/stage-groups/pom.xml index c4dfa81acd5..21d8922e0b0 100644 --- a/registration-processor/stage-groups/pom.xml +++ b/registration-processor/stage-groups/pom.xml @@ -7,7 +7,7 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT 1.2.0.1-B3-SNAPSHOT stage-groups diff --git a/registration-processor/stage-groups/registration-processor-stage-group-1/pom.xml b/registration-processor/stage-groups/registration-processor-stage-group-1/pom.xml index dfc3eaa5792..7c8bbc01379 100644 --- a/registration-processor/stage-groups/registration-processor-stage-group-1/pom.xml +++ b/registration-processor/stage-groups/registration-processor-stage-group-1/pom.xml @@ -5,7 +5,7 @@ io.mosip.registrationprocessor stage-groups - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT registration-processor-stage-group-1 diff --git a/registration-processor/stage-groups/registration-processor-stage-group-2/pom.xml b/registration-processor/stage-groups/registration-processor-stage-group-2/pom.xml index 0be16124bdf..8f184384299 100644 --- a/registration-processor/stage-groups/registration-processor-stage-group-2/pom.xml +++ b/registration-processor/stage-groups/registration-processor-stage-group-2/pom.xml @@ -5,7 +5,7 @@ io.mosip.registrationprocessor stage-groups - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT registration-processor-stage-group-2 diff --git a/registration-processor/stage-groups/registration-processor-stage-group-3/pom.xml b/registration-processor/stage-groups/registration-processor-stage-group-3/pom.xml index ee2b4a7f84c..510842baf7a 100644 --- a/registration-processor/stage-groups/registration-processor-stage-group-3/pom.xml +++ b/registration-processor/stage-groups/registration-processor-stage-group-3/pom.xml @@ -5,7 +5,7 @@ io.mosip.registrationprocessor stage-groups - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT registration-processor-stage-group-3 diff --git a/registration-processor/stage-groups/registration-processor-stage-group-4/pom.xml b/registration-processor/stage-groups/registration-processor-stage-group-4/pom.xml index 3c50b67a2fa..e0eaa85a88a 100644 --- a/registration-processor/stage-groups/registration-processor-stage-group-4/pom.xml +++ b/registration-processor/stage-groups/registration-processor-stage-group-4/pom.xml @@ -5,7 +5,7 @@ io.mosip.registrationprocessor stage-groups - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT registration-processor-stage-group-4 diff --git a/registration-processor/stage-groups/registration-processor-stage-group-5/pom.xml b/registration-processor/stage-groups/registration-processor-stage-group-5/pom.xml index 260ab52888b..f91437994ed 100644 --- a/registration-processor/stage-groups/registration-processor-stage-group-5/pom.xml +++ b/registration-processor/stage-groups/registration-processor-stage-group-5/pom.xml @@ -5,7 +5,7 @@ io.mosip.registrationprocessor stage-groups - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT registration-processor-stage-group-5 diff --git a/registration-processor/stage-groups/registration-processor-stage-group-6/pom.xml b/registration-processor/stage-groups/registration-processor-stage-group-6/pom.xml index e3a10c28174..a3166f6e353 100644 --- a/registration-processor/stage-groups/registration-processor-stage-group-6/pom.xml +++ b/registration-processor/stage-groups/registration-processor-stage-group-6/pom.xml @@ -5,7 +5,7 @@ io.mosip.registrationprocessor stage-groups - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT registration-processor-stage-group-6 diff --git a/registration-processor/stage-groups/registration-processor-stage-group-7/pom.xml b/registration-processor/stage-groups/registration-processor-stage-group-7/pom.xml index 32d52f11076..a9f42e8b5de 100644 --- a/registration-processor/stage-groups/registration-processor-stage-group-7/pom.xml +++ b/registration-processor/stage-groups/registration-processor-stage-group-7/pom.xml @@ -5,7 +5,7 @@ io.mosip.registrationprocessor stage-groups - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT registration-processor-stage-group-7 diff --git a/registration-processor/workflow-engine/pom.xml b/registration-processor/workflow-engine/pom.xml index 8018afb3edd..f8a4bbd14b2 100644 --- a/registration-processor/workflow-engine/pom.xml +++ b/registration-processor/workflow-engine/pom.xml @@ -5,7 +5,7 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT 1.2.0.1-B3-SNAPSHOT workflow-engine diff --git a/registration-processor/workflow-engine/registration-processor-reprocessor/pom.xml b/registration-processor/workflow-engine/registration-processor-reprocessor/pom.xml index 4da4baf8baf..55ac46340e4 100644 --- a/registration-processor/workflow-engine/registration-processor-reprocessor/pom.xml +++ b/registration-processor/workflow-engine/registration-processor-reprocessor/pom.xml @@ -7,7 +7,7 @@ io.mosip.registrationprocessor workflow-engine - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT registration-processor-reprocessor 1.2.0.1-B3-SNAPSHOT diff --git a/registration-processor/workflow-engine/registration-processor-workflow-manager-service/pom.xml b/registration-processor/workflow-engine/registration-processor-workflow-manager-service/pom.xml index 9c5cfc0b64e..d3fe2c8f52d 100644 --- a/registration-processor/workflow-engine/registration-processor-workflow-manager-service/pom.xml +++ b/registration-processor/workflow-engine/registration-processor-workflow-manager-service/pom.xml @@ -5,7 +5,7 @@ io.mosip.registrationprocessor workflow-engine - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT registration-processor-workflow-manager-service 1.2.0.1-B3-SNAPSHOT From 1766d23db2407ed326b6f1a22f94fbfda6166d81 Mon Sep 17 00:00:00 2001 From: Vishwa Date: Wed, 21 Jun 2023 11:08:43 +0530 Subject: [PATCH 077/133] Merge pull request #1724 from sowmya695/kafka_develop MOSIP-23715 code fix --- .../MosipVerticleAPIManager.java | 464 +++++++++--------- .../core/eventbus/KafkaMosipEventBus.java | 6 + 2 files changed, 244 insertions(+), 226 deletions(-) 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 867ae0c10a7..39eb36eb3ad 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 @@ -1,227 +1,239 @@ -package io.mosip.registration.processor.core.abstractverticle; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.core.env.Environment; -import org.springframework.util.ClassUtils; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; - -import brave.Tracing; -import io.mosip.kernel.core.logger.spi.Logger; -import io.mosip.kernel.core.virusscanner.spi.VirusScanner; -import io.mosip.registration.processor.core.constant.HealthConstant; -import io.mosip.registration.processor.core.logger.RegProcessorLogger; -import io.mosip.registration.processor.core.queue.factory.MosipQueue; -import io.mosip.registration.processor.core.spi.queue.MosipQueueConnectionFactory; -import io.mosip.registration.processor.core.spi.queue.MosipQueueManager; -import io.mosip.registration.processor.core.tracing.VertxWebTracingLocal; -import io.mosip.registration.processor.core.util.DigitalSignatureUtility; -import io.vertx.core.Handler; -import io.vertx.core.Vertx; -import io.vertx.core.http.HttpServerResponse; -import io.vertx.core.json.Json; -import io.vertx.ext.web.Router; -import io.vertx.ext.web.RoutingContext; -import io.vertx.ext.web.handler.BodyHandler; -import io.vertx.micrometer.PrometheusScrapingHandler; - -/** - * @author Mukul Puspam - * - */ -public abstract class MosipVerticleAPIManager extends MosipVerticleManager { - - @Value("${registration.processor.signature.isEnabled}") - Boolean isEnabled; - - @Autowired - DigitalSignatureUtility digitalSignatureUtility; - - @Autowired - ObjectMapper objectMapper; - - @Autowired - private MosipQueueConnectionFactory mosipConnectionFactory; - - @Autowired - private Tracing tracing; - - @Autowired - private Environment environment; - - @Autowired(required = false) - private VirusScanner virusScanner; - - /** The mosip queue manager. */ - @Autowired - private MosipQueueManager mosipQueueManager; - - private static final String PROMETHEUS_ENDPOINT = "/actuator/prometheus"; - - - private static Logger regProcLogger = RegProcessorLogger.getLogger(MosipVerticleAPIManager.class); - - - /** - * This method creates a body handler for the routes - * - * @param vertx - * @return - */ - public Router postUrl(Vertx vertx, MessageBusAddress consumeAddress, MessageBusAddress sendAddress) { - Router router = Router.router(vertx); - - VertxWebTracingLocal vertxWebTracing = VertxWebTracingLocal.create(tracing); - Handler routingContextHandler = vertxWebTracing.routingContextHandler(); - router.route() - .order(-1) //applies before routes - .handler(routingContextHandler) - .failureHandler(routingContextHandler); - - router.route().handler(BodyHandler.create()); - String servletPath = getServletPath(); - router.get(servletPath + PROMETHEUS_ENDPOINT).handler(PrometheusScrapingHandler.create()); - if (consumeAddress == null && sendAddress == null) - configureHealthCheckEndpoint(vertx, router, servletPath, null, - null); - else if (consumeAddress == null) - configureHealthCheckEndpoint(vertx, router, servletPath, null, - sendAddress.getAddress()); - else if (sendAddress == null) - configureHealthCheckEndpoint(vertx, router, servletPath, - consumeAddress.getAddress(), null); - else - configureHealthCheckEndpoint(vertx, router, servletPath, - consumeAddress.getAddress(), sendAddress.getAddress()); - return router; - } - - public void configureHealthCheckEndpoint(Vertx vertx, Router router, final String servletPath, - String consumeAddress, String sendAddress) { - StageHealthCheckHandler healthCheckHandler = new StageHealthCheckHandler(vertx, null, objectMapper, - virusScanner, environment); - router.get(servletPath + HealthConstant.HEALTH_ENDPOINT).handler(healthCheckHandler); - if (servletPath.contains("packetreceiver") || servletPath.contains("uploader")) { - healthCheckHandler.register("virusscanner", healthCheckHandler::virusScanHealthChecker); - healthCheckHandler.register( - servletPath.substring(servletPath.lastIndexOf("/") + 1, servletPath.length()) + "Verticle", - future -> healthCheckHandler.senderHealthHandler(future, vertx, super.mosipEventBus, sendAddress)); - } - if (checkServletPathContainsCoreProcessor(servletPath)) { - healthCheckHandler.register( - servletPath.substring(servletPath.lastIndexOf("/") + 1, servletPath.length()) + "Send", future -> { - healthCheckHandler.senderHealthHandler(future, vertx, super.mosipEventBus, sendAddress); - }); - healthCheckHandler.register( - servletPath.substring(servletPath.lastIndexOf("/") + 1, servletPath.length()) + "Consume", - future -> { - healthCheckHandler.consumerHealthHandler(future, vertx, super.mosipEventBus, consumeAddress); - }); - } - if (servletPath.contains("external") || servletPath.contains("bioauth")) { - healthCheckHandler.register( - servletPath.substring(servletPath.lastIndexOf("/") + 1, servletPath.length()) + "Send", future -> { - healthCheckHandler.senderHealthHandler(future, vertx, super.mosipEventBus, sendAddress); - }); - healthCheckHandler.register( - servletPath.substring(servletPath.lastIndexOf("/") + 1, servletPath.length()) + "Consume", - future -> { - healthCheckHandler.senderHealthHandler(future, vertx, super.mosipEventBus, consumeAddress); - }); - } - if (servletPath.contains("manual")) { - healthCheckHandler.register( - servletPath.substring(servletPath.lastIndexOf("/") + 1, servletPath.length()) + "Verticle", - future -> healthCheckHandler.senderHealthHandler(future, vertx, super.mosipEventBus, sendAddress)); - } - if (servletPath.contains("abismiddleware")) { - healthCheckHandler.register("queuecheck", future -> healthCheckHandler.queueHealthChecker(future, mosipQueueManager, mosipConnectionFactory)); - healthCheckHandler.register( - servletPath.substring(servletPath.lastIndexOf("/") + 1, servletPath.length()) + "Verticle", - future -> healthCheckHandler.consumerHealthHandler(future, vertx, super.mosipEventBus, - consumeAddress)); - } - if (servletPath.contains("sender")) { - healthCheckHandler.register( - servletPath.substring(servletPath.lastIndexOf("/") + 1, servletPath.length()) + "Verticle", - future -> healthCheckHandler.consumerHealthHandler(future, vertx, super.mosipEventBus, - consumeAddress)); - } - - healthCheckHandler.register("diskSpace", healthCheckHandler::dispSpaceHealthChecker); - healthCheckHandler.register("db", healthCheckHandler::databaseHealthChecker); - } - - private boolean checkServletPathContainsCoreProcessor(String servletPath) { - return servletPath.contains("packetvalidator") || servletPath.contains("osi") || servletPath.contains("demo") - || servletPath.contains("bio") || servletPath.contains("uin") || servletPath.contains("quality") - || servletPath.contains("abishandler") || servletPath.contains("securezone"); - } - - /** - * This method creates server for vertx web application - * - * @param router - * @param port - */ - public void createServer(Router router, int port) { - vertx.createHttpServer().requestHandler(router::accept).listen(port); - } - - /** - * This method returns a response to the routing context - * - * @param ctx - * @param object - */ - public void setResponse(RoutingContext ctx, Object object) { - ctx.response().putHeader("content-type", "text/plain").putHeader("Access-Control-Allow-Origin", "*") - .putHeader("Access-Control-Allow-Methods", "GET, POST").setStatusCode(200) - .end(Json.encodePrettily(object)); - }; - - /** - * This method returns a response to the routing context - * - * @param ctx - * @param object - * @param contentType - */ - public void setResponseWithDigitalSignature(RoutingContext ctx, Object object, String contentType) { - HttpServerResponse response = ctx.response(); - - String res=null; - try { - res = objectMapper.writeValueAsString(object); - } catch (JsonProcessingException e) { - regProcLogger.error("Error while processing response",e); - - } - - if (isEnabled) - response.putHeader("Response-Signature", - digitalSignatureUtility.getDigitalSignature(res)); - response.putHeader("content-type", contentType).putHeader("Access-Control-Allow-Origin", "*") - .putHeader("Access-Control-Allow-Methods", "GET, POST").setStatusCode(200) - .end(res); - } - - // Added this method to cast all the stages to this class and invoke the deployVerticle method - // to start the stage by configuration, since we don't want to test all the stages now, not marking this as - // an abstract method, but later this need to be marked as abstract - public void deployVerticle() { - - } - - - /** - * Gets the stage name. - * - * @return the stage name - */ - protected String getStageName() { - return ClassUtils.getUserClass(this.getClass()).getSimpleName(); - } +package io.mosip.registration.processor.core.abstractverticle; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.core.env.Environment; +import org.springframework.util.ClassUtils; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +import brave.Tracing; +import io.mosip.kernel.core.logger.spi.Logger; +import io.mosip.kernel.core.virusscanner.spi.VirusScanner; +import io.mosip.registration.processor.core.constant.HealthConstant; +import io.mosip.registration.processor.core.logger.RegProcessorLogger; +import io.mosip.registration.processor.core.queue.factory.MosipQueue; +import io.mosip.registration.processor.core.spi.queue.MosipQueueConnectionFactory; +import io.mosip.registration.processor.core.spi.queue.MosipQueueManager; +import io.mosip.registration.processor.core.tracing.VertxWebTracingLocal; +import io.mosip.registration.processor.core.util.DigitalSignatureUtility; +import io.vertx.core.Handler; +import io.vertx.core.Vertx; +import io.vertx.core.http.HttpServerResponse; +import io.vertx.core.json.Json; +import io.vertx.ext.web.Router; +import io.vertx.ext.web.RoutingContext; +import io.vertx.ext.web.handler.BodyHandler; +import io.vertx.micrometer.PrometheusScrapingHandler; + +/** + * @author Mukul Puspam + * + */ +public abstract class MosipVerticleAPIManager extends MosipVerticleManager { + + @Value("${registration.processor.signature.isEnabled}") + Boolean isEnabled; + + @Autowired + DigitalSignatureUtility digitalSignatureUtility; + + @Autowired + ObjectMapper objectMapper; + + @Autowired + private MosipQueueConnectionFactory mosipConnectionFactory; + + @Autowired + private Tracing tracing; + + @Autowired + private Environment environment; + + @Autowired(required = false) + private VirusScanner virusScanner; + + /** The mosip queue manager. */ + @Autowired + private MosipQueueManager mosipQueueManager; + + private static final String PROMETHEUS_ENDPOINT = "/actuator/prometheus"; + + + private static Logger regProcLogger = RegProcessorLogger.getLogger(MosipVerticleAPIManager.class); + + @Value("${mosip.regproc.health-check.handler-timeout:5000}") + private long healthCheckTimeOut; + + + /** + * This method creates a body handler for the routes + * + * @param vertx + * @return + */ + public Router postUrl(Vertx vertx, MessageBusAddress consumeAddress, MessageBusAddress sendAddress) { + Router router = Router.router(vertx); + + VertxWebTracingLocal vertxWebTracing = VertxWebTracingLocal.create(tracing); + Handler routingContextHandler = vertxWebTracing.routingContextHandler(); + router.route() + .order(-1) //applies before routes + .handler(routingContextHandler) + .failureHandler(routingContextHandler); + + router.route().handler(BodyHandler.create()); + String servletPath = getServletPath(); + router.get(servletPath + PROMETHEUS_ENDPOINT).handler(PrometheusScrapingHandler.create()); + if (consumeAddress == null && sendAddress == null) + configureHealthCheckEndpoint(vertx, router, servletPath, null, + null); + else if (consumeAddress == null) + configureHealthCheckEndpoint(vertx, router, servletPath, null, + sendAddress.getAddress()); + else if (sendAddress == null) + configureHealthCheckEndpoint(vertx, router, servletPath, + consumeAddress.getAddress(), null); + else + configureHealthCheckEndpoint(vertx, router, servletPath, + consumeAddress.getAddress(), sendAddress.getAddress()); + return router; + } + + public void configureHealthCheckEndpoint(Vertx vertx, Router router, final String servletPath, + String consumeAddress, String sendAddress) { + StageHealthCheckHandler healthCheckHandler = new StageHealthCheckHandler(vertx, null, objectMapper, + virusScanner, environment); + router.get(servletPath + HealthConstant.HEALTH_ENDPOINT).handler(healthCheckHandler); + if (servletPath.contains("packetreceiver") || servletPath.contains("uploader")) { + healthCheckHandler.register("virusscanner", healthCheckTimeOut, healthCheckHandler::virusScanHealthChecker); + healthCheckHandler.register( + servletPath.substring(servletPath.lastIndexOf("/") + 1, servletPath.length()) + "Verticle", + healthCheckTimeOut, + future -> healthCheckHandler.senderHealthHandler(future, vertx, super.mosipEventBus, sendAddress)); + } + if (checkServletPathContainsCoreProcessor(servletPath)) { + healthCheckHandler.register( + servletPath.substring(servletPath.lastIndexOf("/") + 1, servletPath.length()) + "Send", + healthCheckTimeOut, future -> { + healthCheckHandler.senderHealthHandler(future, vertx, super.mosipEventBus, sendAddress); + }); + healthCheckHandler.register( + servletPath.substring(servletPath.lastIndexOf("/") + 1, servletPath.length()) + "Consume", + healthCheckTimeOut, + future -> { + healthCheckHandler.consumerHealthHandler(future, vertx, super.mosipEventBus, consumeAddress); + }); + } + if (servletPath.contains("external") || servletPath.contains("bioauth")) { + healthCheckHandler.register( + servletPath.substring(servletPath.lastIndexOf("/") + 1, servletPath.length()) + "Send", + healthCheckTimeOut, future -> { + healthCheckHandler.senderHealthHandler(future, vertx, super.mosipEventBus, sendAddress); + }); + healthCheckHandler.register( + servletPath.substring(servletPath.lastIndexOf("/") + 1, servletPath.length()) + "Consume", + healthCheckTimeOut, + future -> { + healthCheckHandler.senderHealthHandler(future, vertx, super.mosipEventBus, consumeAddress); + }); + } + if (servletPath.contains("manual")) { + healthCheckHandler.register( + servletPath.substring(servletPath.lastIndexOf("/") + 1, servletPath.length()) + "Verticle", + healthCheckTimeOut, + future -> healthCheckHandler.senderHealthHandler(future, vertx, super.mosipEventBus, sendAddress)); + } + if (servletPath.contains("abismiddleware")) { + healthCheckHandler.register("queuecheck", healthCheckTimeOut, + future -> healthCheckHandler.queueHealthChecker(future, mosipQueueManager, mosipConnectionFactory)); + healthCheckHandler.register( + servletPath.substring(servletPath.lastIndexOf("/") + 1, servletPath.length()) + "Verticle", + healthCheckTimeOut, + future -> healthCheckHandler.consumerHealthHandler(future, vertx, super.mosipEventBus, + consumeAddress)); + } + if (servletPath.contains("sender")) { + healthCheckHandler.register( + servletPath.substring(servletPath.lastIndexOf("/") + 1, servletPath.length()) + "Verticle", + healthCheckTimeOut, + future -> healthCheckHandler.consumerHealthHandler(future, vertx, super.mosipEventBus, + consumeAddress)); + } + + healthCheckHandler.register("diskSpace", healthCheckTimeOut, healthCheckHandler::dispSpaceHealthChecker); + healthCheckHandler.register("db", healthCheckTimeOut, healthCheckHandler::databaseHealthChecker); + } + + private boolean checkServletPathContainsCoreProcessor(String servletPath) { + return servletPath.contains("packetvalidator") || servletPath.contains("osi") || servletPath.contains("demo") + || servletPath.contains("bio") || servletPath.contains("uin") || servletPath.contains("quality") + || servletPath.contains("abishandler") || servletPath.contains("securezone"); + } + + /** + * This method creates server for vertx web application + * + * @param router + * @param port + */ + public void createServer(Router router, int port) { + vertx.createHttpServer().requestHandler(router::accept).listen(port); + } + + /** + * This method returns a response to the routing context + * + * @param ctx + * @param object + */ + public void setResponse(RoutingContext ctx, Object object) { + ctx.response().putHeader("content-type", "text/plain").putHeader("Access-Control-Allow-Origin", "*") + .putHeader("Access-Control-Allow-Methods", "GET, POST").setStatusCode(200) + .end(Json.encodePrettily(object)); + }; + + /** + * This method returns a response to the routing context + * + * @param ctx + * @param object + * @param contentType + */ + public void setResponseWithDigitalSignature(RoutingContext ctx, Object object, String contentType) { + HttpServerResponse response = ctx.response(); + + String res=null; + try { + res = objectMapper.writeValueAsString(object); + } catch (JsonProcessingException e) { + regProcLogger.error("Error while processing response",e); + + } + + if (isEnabled) + response.putHeader("Response-Signature", + digitalSignatureUtility.getDigitalSignature(res)); + response.putHeader("content-type", contentType).putHeader("Access-Control-Allow-Origin", "*") + .putHeader("Access-Control-Allow-Methods", "GET, POST").setStatusCode(200) + .end(res); + } + + // Added this method to cast all the stages to this class and invoke the deployVerticle method + // to start the stage by configuration, since we don't want to test all the stages now, not marking this as + // an abstract method, but later this need to be marked as abstract + public void deployVerticle() { + + } + + + /** + * Gets the stage name. + * + * @return the stage name + */ + protected String getStageName() { + return ClassUtils.getUserClass(this.getClass()).getSimpleName(); + } } \ No newline at end of file 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 add46b56e19..3403f8a7be8 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 @@ -15,6 +15,7 @@ import brave.Span; import io.mosip.kernel.core.logger.spi.Logger; +import io.mosip.kernel.core.util.DateUtils; import io.mosip.registration.processor.core.abstractverticle.EventDTO; import io.mosip.registration.processor.core.abstractverticle.HealthCheckDTO; import io.mosip.registration.processor.core.abstractverticle.MessageBusAddress; @@ -434,6 +435,9 @@ private void resumePartition(TopicPartition topicPartition, Promise promis @Override public void consumerHealthCheck(Handler eventHandler, String address) { HealthCheckDTO healthCheckDTO = new HealthCheckDTO(); + String timeStamp = address + DateUtils.formatToISOString(DateUtils.getUTCCurrentDateTime()); + logger.debug("Consumer health check started {}", + timeStamp); kafkaConsumer.listTopics(f -> { if (f.succeeded()) { healthCheckDTO.setEventBusConnected(true); @@ -442,6 +446,8 @@ public void consumerHealthCheck(Handler eventHandler, String add healthCheckDTO.setEventBusConnected(false); healthCheckDTO.setFailureReason(f.cause().getMessage()); } + logger.debug("Consumer health check ended {} {}", + timeStamp); eventHandler.handle(healthCheckDTO); }); From f080851e98667d5a749a3b7e963de2c8bb0fad09 Mon Sep 17 00:00:00 2001 From: Sowmya Ujjappa Banakar Date: Fri, 23 Jun 2023 15:14:50 +0530 Subject: [PATCH 078/133] MOSIP-23715 missed stages added for consumer health check --- .../MosipVerticleAPIManager.java | 26 +++++++++++-------- 1 file changed, 15 insertions(+), 11 deletions(-) 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 39eb36eb3ad..2e319859d1a 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 @@ -106,27 +106,26 @@ public void configureHealthCheckEndpoint(Vertx vertx, Router router, final Strin StageHealthCheckHandler healthCheckHandler = new StageHealthCheckHandler(vertx, null, objectMapper, virusScanner, environment); router.get(servletPath + HealthConstant.HEALTH_ENDPOINT).handler(healthCheckHandler); - if (servletPath.contains("packetreceiver") || servletPath.contains("uploader")) { + if (servletPath.contains("packetreceiver")) { healthCheckHandler.register("virusscanner", healthCheckTimeOut, healthCheckHandler::virusScanHealthChecker); healthCheckHandler.register( servletPath.substring(servletPath.lastIndexOf("/") + 1, servletPath.length()) + "Verticle", healthCheckTimeOut, future -> healthCheckHandler.senderHealthHandler(future, vertx, super.mosipEventBus, sendAddress)); } - if (checkServletPathContainsCoreProcessor(servletPath)) { + if (servletPath.contains("uploader")) { + healthCheckHandler.register("virusscanner", healthCheckTimeOut, healthCheckHandler::virusScanHealthChecker); healthCheckHandler.register( - servletPath.substring(servletPath.lastIndexOf("/") + 1, servletPath.length()) + "Send", + servletPath.substring(servletPath.lastIndexOf("/") + 1, servletPath.length()) + "Consume", healthCheckTimeOut, future -> { - healthCheckHandler.senderHealthHandler(future, vertx, super.mosipEventBus, sendAddress); + healthCheckHandler.consumerHealthHandler(future, vertx, super.mosipEventBus, consumeAddress); }); healthCheckHandler.register( - servletPath.substring(servletPath.lastIndexOf("/") + 1, servletPath.length()) + "Consume", + servletPath.substring(servletPath.lastIndexOf("/") + 1, servletPath.length()) + "Verticle", healthCheckTimeOut, - future -> { - healthCheckHandler.consumerHealthHandler(future, vertx, super.mosipEventBus, consumeAddress); - }); + future -> healthCheckHandler.senderHealthHandler(future, vertx, super.mosipEventBus, sendAddress)); } - if (servletPath.contains("external") || servletPath.contains("bioauth")) { + if (checkServletPathContainsCoreProcessor(servletPath)) { healthCheckHandler.register( servletPath.substring(servletPath.lastIndexOf("/") + 1, servletPath.length()) + "Send", healthCheckTimeOut, future -> { @@ -136,7 +135,7 @@ public void configureHealthCheckEndpoint(Vertx vertx, Router router, final Strin servletPath.substring(servletPath.lastIndexOf("/") + 1, servletPath.length()) + "Consume", healthCheckTimeOut, future -> { - healthCheckHandler.senderHealthHandler(future, vertx, super.mosipEventBus, consumeAddress); + healthCheckHandler.consumerHealthHandler(future, vertx, super.mosipEventBus, consumeAddress); }); } if (servletPath.contains("manual")) { @@ -169,7 +168,12 @@ public void configureHealthCheckEndpoint(Vertx vertx, Router router, final Strin private boolean checkServletPathContainsCoreProcessor(String servletPath) { return servletPath.contains("packetvalidator") || servletPath.contains("osi") || servletPath.contains("demo") || servletPath.contains("bio") || servletPath.contains("uin") || servletPath.contains("quality") - || servletPath.contains("abishandler") || servletPath.contains("securezone"); + || servletPath.contains("abishandler") || servletPath.contains("securezone") + || servletPath.contains("print") || servletPath.contains("cmd") || servletPath.contains("operator") + || servletPath.contains("supervisor") || servletPath.contains("introducer") + || servletPath.contains("final") || servletPath.contains("biometric") + || servletPath.contains("packetclassifier") || servletPath.contains("bioauth") + || servletPath.contains("external"); } /** From 0a0bf7cd20f86874f38599513e1c8c72220fa7d9 Mon Sep 17 00:00:00 2001 From: Sowmya Ujjappa Banakar Date: Mon, 26 Jun 2023 10:14:33 +0530 Subject: [PATCH 079/133] MOSIP-23715 review comments --- .../core/abstractverticle/MosipVerticleAPIManager.java | 6 +++--- .../processor/core/eventbus/KafkaMosipEventBus.java | 4 ++-- 2 files changed, 5 insertions(+), 5 deletions(-) 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 2e319859d1a..0ff829c06a1 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; @@ -125,7 +125,7 @@ public void configureHealthCheckEndpoint(Vertx vertx, Router router, final Strin healthCheckTimeOut, future -> healthCheckHandler.senderHealthHandler(future, vertx, super.mosipEventBus, sendAddress)); } - if (checkServletPathContainsCoreProcessor(servletPath)) { + if (checkServletPath(servletPath)) { healthCheckHandler.register( servletPath.substring(servletPath.lastIndexOf("/") + 1, servletPath.length()) + "Send", healthCheckTimeOut, future -> { @@ -165,7 +165,7 @@ public void configureHealthCheckEndpoint(Vertx vertx, Router router, final Strin healthCheckHandler.register("db", healthCheckTimeOut, healthCheckHandler::databaseHealthChecker); } - private boolean checkServletPathContainsCoreProcessor(String servletPath) { + private boolean checkServletPath(String servletPath) { return servletPath.contains("packetvalidator") || servletPath.contains("osi") || servletPath.contains("demo") || servletPath.contains("bio") || servletPath.contains("uin") || servletPath.contains("quality") || servletPath.contains("abishandler") || servletPath.contains("securezone") 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 3403f8a7be8..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 @@ -446,8 +446,8 @@ public void consumerHealthCheck(Handler eventHandler, String add 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); }); From 0f1850f1c0ba1cd3deffdc34e14ae3122c46b6d8 Mon Sep 17 00:00:00 2001 From: Sowmya Ujjappa Banakar Date: Mon, 26 Jun 2023 16:38:23 +0530 Subject: [PATCH 080/133] MOSIP-28153 version changes --- .../pom.xml | 178 ++++---- .../pom.xml | 2 +- .../pom.xml | 2 +- .../pom.xml | 2 +- .../pom.xml | 2 +- .../pom.xml | 2 +- .../pom.xml | 2 +- .../pom.xml | 2 +- .../pom.xml | 2 +- .../mosip-stage-executor/pom.xml | 2 +- registration-processor/pom.xml | 46 +- registration-processor/post-processor/pom.xml | 2 +- .../pom.xml | 2 +- .../pom.xml | 214 ++++----- .../pom.xml | 2 +- registration-processor/pre-processor/pom.xml | 2 +- .../pom.xml | 2 +- .../pom.xml | 2 +- .../pom.xml | 2 +- .../pom.xml | 2 +- .../pom.xml | 2 +- .../pom.xml | 2 +- .../pom.xml | 2 +- .../pom.xml | 2 +- .../pom.xml | 2 +- .../qc-users-manger/pom.xml | 2 +- .../pom.xml | 2 +- .../pom.xml | 310 ++++++------- .../registration-processor-core/pom.xml | 420 +++++++++--------- .../pom.xml | 2 +- .../pom.xml | 2 +- .../pom.xml | 200 ++++----- .../pom.xml | 268 +++++------ .../pom.xml | 176 ++++---- .../pom.xml | 2 +- .../pom.xml | 154 +++---- registration-processor/stage-groups/pom.xml | 52 +-- .../pom.xml | 120 ++--- .../pom.xml | 138 +++--- .../pom.xml | 12 +- .../pom.xml | 8 +- .../pom.xml | 14 +- .../pom.xml | 10 +- .../pom.xml | 12 +- .../workflow-engine/pom.xml | 2 +- .../pom.xml | 254 +++++------ .../pom.xml | 2 +- 47 files changed, 1322 insertions(+), 1322 deletions(-) diff --git a/registration-processor/core-processor/registration-processor-abis-handler-stage/pom.xml b/registration-processor/core-processor/registration-processor-abis-handler-stage/pom.xml index cce8abec805..b993ca03858 100644 --- a/registration-processor/core-processor/registration-processor-abis-handler-stage/pom.xml +++ b/registration-processor/core-processor/registration-processor-abis-handler-stage/pom.xml @@ -1,90 +1,90 @@ - - - 4.0.0 - - io.mosip.registrationprocessor - core-processor - 1.2.0.1-SNAPSHOT - - - registration-processor-abis-handler-stage - 1.2.0.1-B3-SNAPSHOT - jar - - UTF-8 - UTF-8 - - - - - - org.springframework.cloud - spring-cloud-starter-config - ${spring-cloud-config.version} - - - org.mockito - mockito-core - ${mockito.version} - test - - - com.h2database - h2 - 1.4.195 - - - - - - org.springframework - spring-context - ${spring-framework.version} - - - org.springframework - spring-tx - ${spring-framework.version} - - - io.mosip.registrationprocessor - registration-processor-core - ${registration.processor.core.version} - - - io.mosip.registrationprocessor - registration-processor-registration-status-service-impl - ${registration.status.service.version} - - - io.mosip.registrationprocessor - registration-processor-rest-client - ${registration.processor.rest.client.version} - - - io.mosip.registrationprocessor - registration-processor-info-storage-service - ${packet.info.storage.service.version} - - - org.powermock - powermock-module-junit4 - ${powermock.module.junit4.version} - test - - - org.powermock - powermock-api-mockito2 - ${powermock.api.mockito.version} - test - - - com.google.guava - guava - 30.1.1-jre - - - - + + + 4.0.0 + + io.mosip.registrationprocessor + core-processor + 1.2.0.1-SNAPSHOT + + + registration-processor-abis-handler-stage + 1.2.0.1-SNAPSHOT + jar + + UTF-8 + UTF-8 + + + + + + org.springframework.cloud + spring-cloud-starter-config + ${spring-cloud-config.version} + + + org.mockito + mockito-core + ${mockito.version} + test + + + com.h2database + h2 + 1.4.195 + + + + + + org.springframework + spring-context + ${spring-framework.version} + + + org.springframework + spring-tx + ${spring-framework.version} + + + io.mosip.registrationprocessor + registration-processor-core + ${registration.processor.core.version} + + + io.mosip.registrationprocessor + registration-processor-registration-status-service-impl + ${registration.status.service.version} + + + io.mosip.registrationprocessor + registration-processor-rest-client + ${registration.processor.rest.client.version} + + + io.mosip.registrationprocessor + registration-processor-info-storage-service + ${packet.info.storage.service.version} + + + org.powermock + powermock-module-junit4 + ${powermock.module.junit4.version} + test + + + org.powermock + powermock-api-mockito2 + ${powermock.api.mockito.version} + test + + + com.google.guava + guava + 30.1.1-jre + + + + \ No newline at end of file diff --git a/registration-processor/core-processor/registration-processor-bio-dedupe-stage/pom.xml b/registration-processor/core-processor/registration-processor-bio-dedupe-stage/pom.xml index 95bc137e14a..51b750768e9 100644 --- a/registration-processor/core-processor/registration-processor-bio-dedupe-stage/pom.xml +++ b/registration-processor/core-processor/registration-processor-bio-dedupe-stage/pom.xml @@ -9,7 +9,7 @@ registration-processor-bio-dedupe-stage - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT jar UTF-8 diff --git a/registration-processor/core-processor/registration-processor-biometric-authentication-stage/pom.xml b/registration-processor/core-processor/registration-processor-biometric-authentication-stage/pom.xml index fe31a4ea07e..754cbb84860 100644 --- a/registration-processor/core-processor/registration-processor-biometric-authentication-stage/pom.xml +++ b/registration-processor/core-processor/registration-processor-biometric-authentication-stage/pom.xml @@ -8,7 +8,7 @@ 1.2.0.1-SNAPSHOT registration-processor-biometric-authentication-stage - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT jar UTF-8 diff --git a/registration-processor/core-processor/registration-processor-demo-dedupe-stage/pom.xml b/registration-processor/core-processor/registration-processor-demo-dedupe-stage/pom.xml index 7bbbc1ca2f7..80e30419cfa 100644 --- a/registration-processor/core-processor/registration-processor-demo-dedupe-stage/pom.xml +++ b/registration-processor/core-processor/registration-processor-demo-dedupe-stage/pom.xml @@ -8,7 +8,7 @@ 1.2.0.1-SNAPSHOT registration-processor-demo-dedupe-stage - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT jar UTF-8 diff --git a/registration-processor/core-processor/registration-processor-manual-adjudication-stage/pom.xml b/registration-processor/core-processor/registration-processor-manual-adjudication-stage/pom.xml index 0e8d2e4ba94..796d3317026 100644 --- a/registration-processor/core-processor/registration-processor-manual-adjudication-stage/pom.xml +++ b/registration-processor/core-processor/registration-processor-manual-adjudication-stage/pom.xml @@ -12,7 +12,7 @@ registration-processor-manual-adjudication-stage - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT UTF-8 diff --git a/registration-processor/core-processor/registration-processor-uin-generator-stage/pom.xml b/registration-processor/core-processor/registration-processor-uin-generator-stage/pom.xml index 2c1e7a399f9..3a163267596 100644 --- a/registration-processor/core-processor/registration-processor-uin-generator-stage/pom.xml +++ b/registration-processor/core-processor/registration-processor-uin-generator-stage/pom.xml @@ -7,7 +7,7 @@ 1.2.0.1-SNAPSHOT registration-processor-uin-generator-stage - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT jar UTF-8 diff --git a/registration-processor/core-processor/registration-processor-verification-stage/pom.xml b/registration-processor/core-processor/registration-processor-verification-stage/pom.xml index 2dc976993dd..804ff7f221b 100644 --- a/registration-processor/core-processor/registration-processor-verification-stage/pom.xml +++ b/registration-processor/core-processor/registration-processor-verification-stage/pom.xml @@ -12,7 +12,7 @@ registration-processor-verification-stage - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT UTF-8 diff --git a/registration-processor/init/registration-processor-packet-receiver-stage/pom.xml b/registration-processor/init/registration-processor-packet-receiver-stage/pom.xml index da95b11d37c..65c49693beb 100644 --- a/registration-processor/init/registration-processor-packet-receiver-stage/pom.xml +++ b/registration-processor/init/registration-processor-packet-receiver-stage/pom.xml @@ -11,7 +11,7 @@ registration-processor-packet-receiver-stage - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT jar registration-processor-packet-receiver-stage diff --git a/registration-processor/init/registration-processor-registration-status-service/pom.xml b/registration-processor/init/registration-processor-registration-status-service/pom.xml index 0481ef4d6f2..7d35fa6396c 100644 --- a/registration-processor/init/registration-processor-registration-status-service/pom.xml +++ b/registration-processor/init/registration-processor-registration-status-service/pom.xml @@ -11,7 +11,7 @@ 1.2.0.1-SNAPSHOT registration-processor-registration-status-service - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT registration-processor-registration-status-service diff --git a/registration-processor/mosip-stage-executor/pom.xml b/registration-processor/mosip-stage-executor/pom.xml index 6e2214ed23f..22617e270bd 100644 --- a/registration-processor/mosip-stage-executor/pom.xml +++ b/registration-processor/mosip-stage-executor/pom.xml @@ -9,7 +9,7 @@ mosip-stage-executor - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT diff --git a/registration-processor/pom.xml b/registration-processor/pom.xml index ec58b3826be..6bbbb0f6625 100644 --- a/registration-processor/pom.xml +++ b/registration-processor/pom.xml @@ -10,7 +10,7 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT pom registration-processor @@ -108,32 +108,32 @@ 0.1.55 - 1.2.0.1-B3-SNAPSHOT - 1.2.0.1-B3-SNAPSHOT - 1.2.0.1-B3-SNAPSHOT - 1.2.0.1-B3-SNAPSHOT - 1.2.0.1-B3-SNAPSHOT - 1.2.0.1-B3-SNAPSHOT - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT + 1.2.0.1-SNAPSHOT + 1.2.0.1-SNAPSHOT + 1.2.0.1-SNAPSHOT + 1.2.0.1-SNAPSHOT + 1.2.0.1-SNAPSHOT + 1.2.0.1-SNAPSHOT - 1.2.0.1-B1 - 1.2.0.1-B1 - 1.2.0.1-B1 - 1.2.0.1-B1 - 1.2.0.1-B1 - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT + 1.2.0.1-SNAPSHOT + 1.2.0.1-SNAPSHOT + 1.2.0.1-SNAPSHOT + 1.2.0.1-SNAPSHOT + 1.2.0.1-SNAPSHOT 1.2.0 - 1.2.0.1-B1 - 1.2.0.1-B1 - 1.2.0.1-B1 - 1.2.0.1-B1 - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT + 1.2.0.1-SNAPSHOT + 1.2.0.1-SNAPSHOT + 1.2.0.1-SNAPSHOT + 1.2.0.1-SNAPSHOT 1.2.0.1-SNAPSHOT - 1.2.0.1-B1 - 1.2.0.1-B1 - 1.2.0.1-B1 - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT + 1.2.0.1-SNAPSHOT + 1.2.0.1-SNAPSHOT + 1.2.0.1-SNAPSHOT **/dto/**, **/exception/*Exception.java, **/config/*Config.java, diff --git a/registration-processor/post-processor/pom.xml b/registration-processor/post-processor/pom.xml index 5f925f037a1..25da34901cd 100644 --- a/registration-processor/post-processor/pom.xml +++ b/registration-processor/post-processor/pom.xml @@ -8,7 +8,7 @@ registration-processor 1.2.0.1-SNAPSHOT - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT post-processor post-processor diff --git a/registration-processor/post-processor/registration-processor-message-sender-stage/pom.xml b/registration-processor/post-processor/registration-processor-message-sender-stage/pom.xml index 057fe669758..ddca10912f8 100644 --- a/registration-processor/post-processor/registration-processor-message-sender-stage/pom.xml +++ b/registration-processor/post-processor/registration-processor-message-sender-stage/pom.xml @@ -11,7 +11,7 @@ registration-processor-message-sender-stage - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT UTF-8 UTF-8 diff --git a/registration-processor/post-processor/registration-processor-printing-stage/pom.xml b/registration-processor/post-processor/registration-processor-printing-stage/pom.xml index 8e25653e013..4a9f585821d 100644 --- a/registration-processor/post-processor/registration-processor-printing-stage/pom.xml +++ b/registration-processor/post-processor/registration-processor-printing-stage/pom.xml @@ -1,107 +1,107 @@ - - - 4.0.0 - - io.mosip.registrationprocessor - post-processor - 1.2.0.1-SNAPSHOT - - registration-processor-printing-stage - 1.2.0.1-B3-SNAPSHOT - - UTF-8 - UTF-8 - - - - - org.springframework.cloud - spring-cloud-starter-config - ${spring-cloud-config.version} - - - org.mockito - mockito-core - ${mockito.version} - test - - - com.h2database - h2 - ${h2.version} - - - - - - org.springframework - spring-context - ${spring-framework.version} - - - org.springframework - spring-tx - ${spring-framework.version} - - - io.vertx - vertx-unit - ${vertx.version} - test - - - io.vertx - vertx-web-client - ${vertx.version} - - - org.apache.httpcomponents - httpmime - 4.3.1 - - - io.mosip.registrationprocessor - registration-processor-core - ${registration.processor.core.version} - - - io.mosip.registrationprocessor - registration-processor-registration-status-service-impl - ${registration.status.service.version} - - - io.mosip.registrationprocessor - registration-processor-rest-client - ${registration.processor.rest.client.version} - - - - junit - junit - test - - - org.powermock - powermock-module-junit4 - ${powermock.module.junit4.version} - test - - - org.powermock - powermock-api-mockito2 - ${powermock.api.mockito.version} - test - - - io.mosip.registrationprocessor - registration-processor-info-storage-service - ${packet.info.storage.service.version} - - - - - - - + + + 4.0.0 + + io.mosip.registrationprocessor + post-processor + 1.2.0.1-SNAPSHOT + + registration-processor-printing-stage + 1.2.0.1-SNAPSHOT + + UTF-8 + UTF-8 + + + + + org.springframework.cloud + spring-cloud-starter-config + ${spring-cloud-config.version} + + + org.mockito + mockito-core + ${mockito.version} + test + + + com.h2database + h2 + ${h2.version} + + + + + + org.springframework + spring-context + ${spring-framework.version} + + + org.springframework + spring-tx + ${spring-framework.version} + + + io.vertx + vertx-unit + ${vertx.version} + test + + + io.vertx + vertx-web-client + ${vertx.version} + + + org.apache.httpcomponents + httpmime + 4.3.1 + + + io.mosip.registrationprocessor + registration-processor-core + ${registration.processor.core.version} + + + io.mosip.registrationprocessor + registration-processor-registration-status-service-impl + ${registration.status.service.version} + + + io.mosip.registrationprocessor + registration-processor-rest-client + ${registration.processor.rest.client.version} + + + + junit + junit + test + + + org.powermock + powermock-module-junit4 + ${powermock.module.junit4.version} + test + + + org.powermock + powermock-api-mockito2 + ${powermock.api.mockito.version} + test + + + io.mosip.registrationprocessor + registration-processor-info-storage-service + ${packet.info.storage.service.version} + + + + + + + diff --git a/registration-processor/post-processor/registration-processor-registration-transaction-service/pom.xml b/registration-processor/post-processor/registration-processor-registration-transaction-service/pom.xml index d2ac01993ca..2e3d4210fe5 100644 --- a/registration-processor/post-processor/registration-processor-registration-transaction-service/pom.xml +++ b/registration-processor/post-processor/registration-processor-registration-transaction-service/pom.xml @@ -8,7 +8,7 @@ 1.2.0.1-SNAPSHOT registration-processor-registration-transaction-service - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT registration-processor-registration-transaction-service UTF-8 diff --git a/registration-processor/pre-processor/pom.xml b/registration-processor/pre-processor/pom.xml index 5942a27d5ea..23941368b71 100644 --- a/registration-processor/pre-processor/pom.xml +++ b/registration-processor/pre-processor/pom.xml @@ -9,7 +9,7 @@ registration-processor 1.2.0.1-SNAPSHOT - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT pre-processor pre-processor diff --git a/registration-processor/pre-processor/registration-processor-cmd-validator-stage/pom.xml b/registration-processor/pre-processor/registration-processor-cmd-validator-stage/pom.xml index e1894649798..7dbf0ec0dde 100644 --- a/registration-processor/pre-processor/registration-processor-cmd-validator-stage/pom.xml +++ b/registration-processor/pre-processor/registration-processor-cmd-validator-stage/pom.xml @@ -9,7 +9,7 @@ 1.2.0.1-SNAPSHOT registration-processor-cmd-validator-stage - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT registration-processor-cmd-validator-stage UTF-8 diff --git a/registration-processor/pre-processor/registration-processor-introducer-validator-stage/pom.xml b/registration-processor/pre-processor/registration-processor-introducer-validator-stage/pom.xml index e31e01d93c2..1dc47cd0e37 100644 --- a/registration-processor/pre-processor/registration-processor-introducer-validator-stage/pom.xml +++ b/registration-processor/pre-processor/registration-processor-introducer-validator-stage/pom.xml @@ -9,7 +9,7 @@ 1.2.0.1-SNAPSHOT registration-processor-introducer-validator-stage - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT registration-processor-introducer-validator-stage UTF-8 diff --git a/registration-processor/pre-processor/registration-processor-operator-validator-stage/pom.xml b/registration-processor/pre-processor/registration-processor-operator-validator-stage/pom.xml index a36dea26640..5783ff54f81 100644 --- a/registration-processor/pre-processor/registration-processor-operator-validator-stage/pom.xml +++ b/registration-processor/pre-processor/registration-processor-operator-validator-stage/pom.xml @@ -9,7 +9,7 @@ 1.2.0.1-SNAPSHOT registration-processor-operator-validator-stage - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT registration-processor-operator-validator-stage UTF-8 diff --git a/registration-processor/pre-processor/registration-processor-packet-classifier-stage/pom.xml b/registration-processor/pre-processor/registration-processor-packet-classifier-stage/pom.xml index 0bc2430b17c..d0f9e67ba80 100644 --- a/registration-processor/pre-processor/registration-processor-packet-classifier-stage/pom.xml +++ b/registration-processor/pre-processor/registration-processor-packet-classifier-stage/pom.xml @@ -10,7 +10,7 @@ 1.2.0.1-SNAPSHOT registration-processor-packet-classifier-stage - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT jar UTF-8 diff --git a/registration-processor/pre-processor/registration-processor-packet-uploader-stage/pom.xml b/registration-processor/pre-processor/registration-processor-packet-uploader-stage/pom.xml index 6c736b32d7d..d28b27ff418 100644 --- a/registration-processor/pre-processor/registration-processor-packet-uploader-stage/pom.xml +++ b/registration-processor/pre-processor/registration-processor-packet-uploader-stage/pom.xml @@ -11,7 +11,7 @@ pre-processor 1.2.0.1-SNAPSHOT - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT UTF-8 diff --git a/registration-processor/pre-processor/registration-processor-packet-validator-stage/pom.xml b/registration-processor/pre-processor/registration-processor-packet-validator-stage/pom.xml index 3fbe12d4258..9485563f780 100644 --- a/registration-processor/pre-processor/registration-processor-packet-validator-stage/pom.xml +++ b/registration-processor/pre-processor/registration-processor-packet-validator-stage/pom.xml @@ -10,7 +10,7 @@ 1.2.0.1-SNAPSHOT registration-processor-packet-validator-stage - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT jar UTF-8 diff --git a/registration-processor/pre-processor/registration-processor-quality-classifier-stage/pom.xml b/registration-processor/pre-processor/registration-processor-quality-classifier-stage/pom.xml index 593782e41e7..6b7b4c50d00 100644 --- a/registration-processor/pre-processor/registration-processor-quality-classifier-stage/pom.xml +++ b/registration-processor/pre-processor/registration-processor-quality-classifier-stage/pom.xml @@ -9,7 +9,7 @@ registration-processor-quality-classifier-stage - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT UTF-8 diff --git a/registration-processor/pre-processor/registration-processor-securezone-notification-stage/pom.xml b/registration-processor/pre-processor/registration-processor-securezone-notification-stage/pom.xml index 9fbcfed20ab..5d796c8376a 100644 --- a/registration-processor/pre-processor/registration-processor-securezone-notification-stage/pom.xml +++ b/registration-processor/pre-processor/registration-processor-securezone-notification-stage/pom.xml @@ -8,7 +8,7 @@ 1.2.0.1-SNAPSHOT 4.0.0 - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT registration-processor-securezone-notification-stage diff --git a/registration-processor/pre-processor/registration-processor-supervisor-validator-stage/pom.xml b/registration-processor/pre-processor/registration-processor-supervisor-validator-stage/pom.xml index 6e090315b6c..970be29a019 100644 --- a/registration-processor/pre-processor/registration-processor-supervisor-validator-stage/pom.xml +++ b/registration-processor/pre-processor/registration-processor-supervisor-validator-stage/pom.xml @@ -9,7 +9,7 @@ 1.2.0.1-SNAPSHOT registration-processor-supervisor-validator-stage - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT registration-processor-supervisor-validator-stage UTF-8 diff --git a/registration-processor/qc-users-manger/pom.xml b/registration-processor/qc-users-manger/pom.xml index 85f14eeb26e..850095b849e 100644 --- a/registration-processor/qc-users-manger/pom.xml +++ b/registration-processor/qc-users-manger/pom.xml @@ -8,7 +8,7 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT diff --git a/registration-processor/registration-processor-bio-dedupe-service-impl/pom.xml b/registration-processor/registration-processor-bio-dedupe-service-impl/pom.xml index 682cb60e963..78f76c5951f 100644 --- a/registration-processor/registration-processor-bio-dedupe-service-impl/pom.xml +++ b/registration-processor/registration-processor-bio-dedupe-service-impl/pom.xml @@ -9,7 +9,7 @@ registration-processor-bio-dedupe-service-impl - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT registration-processor-bio-dedupe-service-impl diff --git a/registration-processor/registration-processor-common-camel-bridge/pom.xml b/registration-processor/registration-processor-common-camel-bridge/pom.xml index 0d844582de7..f71a52f5c98 100644 --- a/registration-processor/registration-processor-common-camel-bridge/pom.xml +++ b/registration-processor/registration-processor-common-camel-bridge/pom.xml @@ -1,155 +1,155 @@ - - 4.0.0 - - - io.mosip.registrationprocessor - registration-processor - 1.2.0.1-SNAPSHOT - - registration-processor-common-camel-bridge - 11.2.0.1-B3-SNAPSHOT - jar - - - io.mosip.registration.processor.camel.bridge.MosipCamelBridge - 1.0.5 - 1.2.0.1-B3-SNAPSHOT - - - - io.mosip.registrationprocessor - registration-processor-core - ${registration.processor.core.version} - - - org.slf4j - jul-to-slf4j - - - org.slf4j - jcl-over-slf4j - - - com.hazelcast - hazelcast-kubernetes - - - - - io.vertx - vertx-unit - ${vertx.version} - test - - - io.vertx - vertx-config-spring-config-server - ${vertx.version} - - - io.vertx - vertx-config - ${vertx.version} - - - - org.apache.camel - camel-vertx - ${camel.vertx.version} - - - org.slf4j - slf4j-api - - - - - com.hazelcast - hazelcast-kubernetes - 1.0.0 - - - org.apache.camel - camel-http - ${camel.vertx.version} - - - org.slf4j - slf4j-api - - - - - org.apache.camel - camel-kafka - ${camel.vertx.version} - - - io.mosip.registrationprocessor - registration-processor-rest-client - ${registration.processor.rest.client.version} - - - org.apache.camel - camel-jsonpath - ${camel.vertx.version} - - - io.mosip.registrationprocessor - registration-processor-registration-status-service-impl - ${registration.processor.registration.status.service.impl.version} - - - org.mockito - mockito-core - ${mockito.version} - test - - - org.powermock - powermock-module-junit4 - ${powermock.module.junit4.version} - test - - - org.powermock - powermock-api-mockito2 - ${powermock.api.mockito.version} - test - - - - - - com.h2database - h2 - ${h2.version} - - - - - - - - org.springframework.boot - spring-boot-maven-plugin - ${spring.boot.version} - - true - io.mosip.registration.processor.camel.bridge.MosipCamelBridgeApplication - ZIP - - - - - build-info - repackage - - - - - - - + + 4.0.0 + + + io.mosip.registrationprocessor + registration-processor + 1.2.0.1-SNAPSHOT + + registration-processor-common-camel-bridge + 1.2.0.1-SNAPSHOT + jar + + + io.mosip.registration.processor.camel.bridge.MosipCamelBridge + 1.0.5 + 1.2.0.1-SNAPSHOT + + + + io.mosip.registrationprocessor + registration-processor-core + ${registration.processor.core.version} + + + org.slf4j + jul-to-slf4j + + + org.slf4j + jcl-over-slf4j + + + com.hazelcast + hazelcast-kubernetes + + + + + io.vertx + vertx-unit + ${vertx.version} + test + + + io.vertx + vertx-config-spring-config-server + ${vertx.version} + + + io.vertx + vertx-config + ${vertx.version} + + + + org.apache.camel + camel-vertx + ${camel.vertx.version} + + + org.slf4j + slf4j-api + + + + + com.hazelcast + hazelcast-kubernetes + 1.0.0 + + + org.apache.camel + camel-http + ${camel.vertx.version} + + + org.slf4j + slf4j-api + + + + + org.apache.camel + camel-kafka + ${camel.vertx.version} + + + io.mosip.registrationprocessor + registration-processor-rest-client + ${registration.processor.rest.client.version} + + + org.apache.camel + camel-jsonpath + ${camel.vertx.version} + + + io.mosip.registrationprocessor + registration-processor-registration-status-service-impl + ${registration.processor.registration.status.service.impl.version} + + + org.mockito + mockito-core + ${mockito.version} + test + + + org.powermock + powermock-module-junit4 + ${powermock.module.junit4.version} + test + + + org.powermock + powermock-api-mockito2 + ${powermock.api.mockito.version} + test + + + + + + com.h2database + h2 + ${h2.version} + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + ${spring.boot.version} + + true + io.mosip.registration.processor.camel.bridge.MosipCamelBridgeApplication + ZIP + + + + + build-info + repackage + + + + + + + diff --git a/registration-processor/registration-processor-core/pom.xml b/registration-processor/registration-processor-core/pom.xml index 8aea32f7cae..15856637960 100644 --- a/registration-processor/registration-processor-core/pom.xml +++ b/registration-processor/registration-processor-core/pom.xml @@ -1,210 +1,210 @@ - - - - 4.0.0 - - - io.mosip.registrationprocessor - registration-processor - 1.2.0.1-SNAPSHOT - - registration-processor-core - 1.2.0.1-B3-SNAPSHOT - - - org.mockito - mockito-core - ${mockito.version} - test - - - org.powermock - powermock-module-junit4 - ${powermock.module.junit4.version} - test - - - org.powermock - powermock-api-mockito2 - ${powermock.api.mockito.version} - test - - - io.vertx - vertx-web - ${vertx.version} - - - org.apache.hadoop - hadoop-client - 2.8.1 - - - org.slf4j - slf4j-api - - - org.slf4j - slf4j-log4j12 - - - - - - org.springframework.boot - spring-boot-starter-actuator - ${spring.boot.version} - - - io.vertx - vertx-health-check - ${vertx.version} - - - org.apache.activemq - activemq-client - 5.17.4 - - - org.springframework.boot - spring-boot-starter-activemq - - - io.vertx - vertx-camel-bridge - ${vertx.version} - - - io.vertx - vertx-hazelcast - ${vertx.version} - - - io.vertx - vertx-kafka-client - ${vertx.version} - - - com.hazelcast - hazelcast-kubernetes - ${hazelcast.kubernetes.version} - - - org.springframework.boot - spring-boot-starter-web - - - org.projectlombok - lombok - - - io.mosip.kernel - kernel-core - ${kernel.core.version} - - - io.mosip.kernel - kernel-idvalidator-rid - ${kernel.idvalidator.rid.version} - - - - - io.mosip.kernel - kernel-logger-logback - ${kernel.logger.logback.version} - - - io.mosip.kernel - kernel-templatemanager-velocity - ${kernel.templatemanager.velocity.version} - - - javax.servlet - servlet-api - - - dom4j - dom4j - - - - - io.mosip.kernel - kernel-cbeffutil-api - ${kernel.cbeffutil.version} - - - - io.vertx - vertx-config-spring-config-server - ${vertx.version} - - - io.vertx - vertx-unit - ${vertx.version} - test - - - io.springfox - springfox-swagger-ui - ${swagger.version} - - - io.springfox - springfox-swagger2 - ${swagger.version} - - - com.googlecode.json-simple - json-simple - - - io.mosip.kernel - kernel-biometrics-api - ${kernel.biometrics.api.version} - - - io.micrometer - micrometer-core - ${io.micrometer.prometheus.version} - - - io.vertx - vertx-micrometer-metrics - ${vertx.version} - - - io.micrometer - micrometer-registry-prometheus - ${io.micrometer.prometheus.version} - - - com.fasterxml.jackson.module - jackson-module-afterburner - ${jackson.afterburner.version} - - - - - - org.mockito - mockito-core - ${mockito.version} - test - - - com.h2database - h2 - ${h2.version} - - - - - - UTF-8 - 1.1.0 - - + + + + 4.0.0 + + + io.mosip.registrationprocessor + registration-processor + 1.2.0.1-SNAPSHOT + + registration-processor-core + 1.2.0.1-SNAPSHOT + + + org.mockito + mockito-core + ${mockito.version} + test + + + org.powermock + powermock-module-junit4 + ${powermock.module.junit4.version} + test + + + org.powermock + powermock-api-mockito2 + ${powermock.api.mockito.version} + test + + + io.vertx + vertx-web + ${vertx.version} + + + org.apache.hadoop + hadoop-client + 2.8.1 + + + org.slf4j + slf4j-api + + + org.slf4j + slf4j-log4j12 + + + + + + org.springframework.boot + spring-boot-starter-actuator + ${spring.boot.version} + + + io.vertx + vertx-health-check + ${vertx.version} + + + org.apache.activemq + activemq-client + 5.17.4 + + + org.springframework.boot + spring-boot-starter-activemq + + + io.vertx + vertx-camel-bridge + ${vertx.version} + + + io.vertx + vertx-hazelcast + ${vertx.version} + + + io.vertx + vertx-kafka-client + ${vertx.version} + + + com.hazelcast + hazelcast-kubernetes + ${hazelcast.kubernetes.version} + + + org.springframework.boot + spring-boot-starter-web + + + org.projectlombok + lombok + + + io.mosip.kernel + kernel-core + ${kernel.core.version} + + + io.mosip.kernel + kernel-idvalidator-rid + ${kernel.idvalidator.rid.version} + + + + + io.mosip.kernel + kernel-logger-logback + ${kernel.logger.logback.version} + + + io.mosip.kernel + kernel-templatemanager-velocity + ${kernel.templatemanager.velocity.version} + + + javax.servlet + servlet-api + + + dom4j + dom4j + + + + + io.mosip.kernel + kernel-cbeffutil-api + ${kernel.cbeffutil.version} + + + + io.vertx + vertx-config-spring-config-server + ${vertx.version} + + + io.vertx + vertx-unit + ${vertx.version} + test + + + io.springfox + springfox-swagger-ui + ${swagger.version} + + + io.springfox + springfox-swagger2 + ${swagger.version} + + + com.googlecode.json-simple + json-simple + + + io.mosip.kernel + kernel-biometrics-api + ${kernel.biometrics.api.version} + + + io.micrometer + micrometer-core + ${io.micrometer.prometheus.version} + + + io.vertx + vertx-micrometer-metrics + ${vertx.version} + + + io.micrometer + micrometer-registry-prometheus + ${io.micrometer.prometheus.version} + + + com.fasterxml.jackson.module + jackson-module-afterburner + ${jackson.afterburner.version} + + + + + + org.mockito + mockito-core + ${mockito.version} + test + + + com.h2database + h2 + ${h2.version} + + + + + + UTF-8 + 1.1.0 + + diff --git a/registration-processor/registration-processor-info-storage-service/pom.xml b/registration-processor/registration-processor-info-storage-service/pom.xml index 7a5168904bb..a96ba4ed241 100644 --- a/registration-processor/registration-processor-info-storage-service/pom.xml +++ b/registration-processor/registration-processor-info-storage-service/pom.xml @@ -10,7 +10,7 @@ 1.2.0.1-SNAPSHOT registration-processor-info-storage-service - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT registration-processor-info-storage-service UTF-8 diff --git a/registration-processor/registration-processor-landing-zone/pom.xml b/registration-processor/registration-processor-landing-zone/pom.xml index 08db07b390a..f3d1e06edd0 100644 --- a/registration-processor/registration-processor-landing-zone/pom.xml +++ b/registration-processor/registration-processor-landing-zone/pom.xml @@ -9,7 +9,7 @@ registration-processor-landing-zone registration-processor-landing-zone - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT UTF-8 diff --git a/registration-processor/registration-processor-message-sender-impl/pom.xml b/registration-processor/registration-processor-message-sender-impl/pom.xml index d105365ac30..4ec8cd0b4d0 100644 --- a/registration-processor/registration-processor-message-sender-impl/pom.xml +++ b/registration-processor/registration-processor-message-sender-impl/pom.xml @@ -1,100 +1,100 @@ - - - 4.0.0 - jar - - io.mosip.registrationprocessor - registration-processor - 1.2.0.1-SNAPSHOT - - - registration-processor-message-sender-impl - 1.2.0.1-B3-SNAPSHOT - - - UTF-8 - UTF-8 - - - - - - org.springframework.cloud - spring-cloud-starter-config - ${spring-cloud-config.version} - - - org.mockito - mockito-core - ${mockito.version} - test - - - com.h2database - h2 - 1.4.195 - - - - - - junit - junit - test - - - org.springframework.boot - spring-boot-starter-web - - - io.mosip.registrationprocessor - registration-processor-registration-status-service-impl - ${registration.status.service.version} - - - io.mosip.registrationprocessor - registration-processor-core - ${registration.processor.core.version} - - - io.mosip.registrationprocessor - registration-processor-info-storage-service - ${packet.info.storage.service.version} - - - io.mosip.registrationprocessor - registration-processor-rest-client - ${registration.processor.rest.client.version} - - - io.mosip.kernel - kernel-templatemanager-velocity - ${kernel.templatemanager.velocity.version} - - - org.apache.velocity - velocity - ${velocity.version} - - - org.apache.velocity - velocity-tools - ${velocity.tools.version} - - - org.powermock - powermock-module-junit4 - ${powermock.module.junit4.version} - test - - - org.powermock - powermock-api-mockito2 - ${powermock.api.mockito.version} - test - - - + + + 4.0.0 + jar + + io.mosip.registrationprocessor + registration-processor + 1.2.0.1-SNAPSHOT + + + registration-processor-message-sender-impl + 1.2.0.1-SNAPSHOT + + + UTF-8 + UTF-8 + + + + + + org.springframework.cloud + spring-cloud-starter-config + ${spring-cloud-config.version} + + + org.mockito + mockito-core + ${mockito.version} + test + + + com.h2database + h2 + 1.4.195 + + + + + + junit + junit + test + + + org.springframework.boot + spring-boot-starter-web + + + io.mosip.registrationprocessor + registration-processor-registration-status-service-impl + ${registration.status.service.version} + + + io.mosip.registrationprocessor + registration-processor-core + ${registration.processor.core.version} + + + io.mosip.registrationprocessor + registration-processor-info-storage-service + ${packet.info.storage.service.version} + + + io.mosip.registrationprocessor + registration-processor-rest-client + ${registration.processor.rest.client.version} + + + io.mosip.kernel + kernel-templatemanager-velocity + ${kernel.templatemanager.velocity.version} + + + org.apache.velocity + velocity + ${velocity.version} + + + org.apache.velocity + velocity-tools + ${velocity.tools.version} + + + org.powermock + powermock-module-junit4 + ${powermock.module.junit4.version} + test + + + org.powermock + powermock-api-mockito2 + ${powermock.api.mockito.version} + test + + + diff --git a/registration-processor/registration-processor-notification-service/pom.xml b/registration-processor/registration-processor-notification-service/pom.xml index 9ffaa7afb76..083e1972676 100644 --- a/registration-processor/registration-processor-notification-service/pom.xml +++ b/registration-processor/registration-processor-notification-service/pom.xml @@ -1,134 +1,134 @@ - - - 4.0.0 - jar - - io.mosip.registrationprocessor - registration-processor - 1.2.0.1-SNAPSHOT - - - registration-processor-notification-service - 1.2.0.1-B3-SNAPSHOT - - UTF-8 - UTF-8 - 1.2.0.1-B1 - - - - - - org.springframework.cloud - spring-cloud-starter-config - ${spring-cloud-config.version} - - - org.mockito - mockito-core - ${mockito.version} - test - - - com.h2database - h2 - ${h2.version} - - - - - - org.springframework - spring-context - ${spring-framework.version} - - - org.springframework - spring-tx - ${spring-framework.version} - - - - io.mosip.registrationprocessor - registration-processor-core - ${registration.processor.core.version} - - - org.springframework.boot - - spring-boot-starter-security - - - - - - - io.mosip.registrationprocessor - registration-processor-message-sender-impl - ${registration.processor.message.sender.version} - - - org.springframework.boot - - spring-boot-starter-security - - - - org.springframework.security - spring-security-test - - - - - junit - junit - test - - - org.powermock - powermock-module-junit4 - ${powermock.module.junit4.version} - test - - - org.powermock - powermock-api-mockito2 - ${powermock.api.mockito.version} - test - - - io.mosip.registrationprocessor - registration-processor-packet-manager - ${packet.manager.version} - - - io.mosip.kernel - kernel-websubclient-api - ${kernel.websubclient.api.version} - - - - - - org.springframework.boot - spring-boot-maven-plugin - ${spring.boot.version} - - true - ZIP - - - - - build-info - repackage - - - - - - - + + + 4.0.0 + jar + + io.mosip.registrationprocessor + registration-processor + 1.2.0.1-SNAPSHOT + + + registration-processor-notification-service + 1.2.0.1-SNAPSHOT + + UTF-8 + UTF-8 + 1.2.0.1-B1 + + + + + + org.springframework.cloud + spring-cloud-starter-config + ${spring-cloud-config.version} + + + org.mockito + mockito-core + ${mockito.version} + test + + + com.h2database + h2 + ${h2.version} + + + + + + org.springframework + spring-context + ${spring-framework.version} + + + org.springframework + spring-tx + ${spring-framework.version} + + + + io.mosip.registrationprocessor + registration-processor-core + ${registration.processor.core.version} + + + org.springframework.boot + + spring-boot-starter-security + + + + + + + io.mosip.registrationprocessor + registration-processor-message-sender-impl + ${registration.processor.message.sender.version} + + + org.springframework.boot + + spring-boot-starter-security + + + + org.springframework.security + spring-security-test + + + + + junit + junit + test + + + org.powermock + powermock-module-junit4 + ${powermock.module.junit4.version} + test + + + org.powermock + powermock-api-mockito2 + ${powermock.api.mockito.version} + test + + + io.mosip.registrationprocessor + registration-processor-packet-manager + ${packet.manager.version} + + + io.mosip.kernel + kernel-websubclient-api + ${kernel.websubclient.api.version} + + + + + + org.springframework.boot + spring-boot-maven-plugin + ${spring.boot.version} + + true + ZIP + + + + + build-info + repackage + + + + + + + diff --git a/registration-processor/registration-processor-packet-manager/pom.xml b/registration-processor/registration-processor-packet-manager/pom.xml index 8367c53455d..c6d8b1600eb 100644 --- a/registration-processor/registration-processor-packet-manager/pom.xml +++ b/registration-processor/registration-processor-packet-manager/pom.xml @@ -1,88 +1,88 @@ - - - 4.0.0 - jar - - io.mosip.registrationprocessor - registration-processor - 1.2.0.1-SNAPSHOT - - - registration-processor-packet-manager - registration-processor-packet-manager - 1.2.0.1-B3-SNAPSHOT - - UTF-8 - - - - - org.mockito - mockito-core - ${mockito.version} - test - - - - - - commons-pool - commons-pool - ${commons.pool} - - - junit - junit - test - - - io.mosip.registrationprocessor - registration-processor-core - ${registration.processor.core.version} - - - io.mosip.registrationprocessor - registration-processor-rest-client - ${registration.processor.rest.client.version} - - - io.mosip.kernel - kernel-core - ${kernel.core.version} - - - commons-io - commons-io - ${commons-io} - - - com.h2database - h2 - - - com.jcraft - jsch - ${jsch.version} - - - org.mockito - mockito-core - ${mockito.version} - test - - - org.powermock - powermock-module-junit4 - ${powermock.module.junit4.version} - test - - - org.powermock - powermock-api-mockito2 - ${powermock.api.mockito.version} - test - - - + + + 4.0.0 + jar + + io.mosip.registrationprocessor + registration-processor + 1.2.0.1-SNAPSHOT + + + registration-processor-packet-manager + registration-processor-packet-manager + 1.2.0.1-SNAPSHOT + + UTF-8 + + + + + org.mockito + mockito-core + ${mockito.version} + test + + + + + + commons-pool + commons-pool + ${commons.pool} + + + junit + junit + test + + + io.mosip.registrationprocessor + registration-processor-core + ${registration.processor.core.version} + + + io.mosip.registrationprocessor + registration-processor-rest-client + ${registration.processor.rest.client.version} + + + io.mosip.kernel + kernel-core + ${kernel.core.version} + + + commons-io + commons-io + ${commons-io} + + + com.h2database + h2 + + + com.jcraft + jsch + ${jsch.version} + + + org.mockito + mockito-core + ${mockito.version} + test + + + org.powermock + powermock-module-junit4 + ${powermock.module.junit4.version} + test + + + org.powermock + powermock-api-mockito2 + ${powermock.api.mockito.version} + test + + + diff --git a/registration-processor/registration-processor-registration-status-service-impl/pom.xml b/registration-processor/registration-processor-registration-status-service-impl/pom.xml index 72f939fd713..599d1b7c828 100644 --- a/registration-processor/registration-processor-registration-status-service-impl/pom.xml +++ b/registration-processor/registration-processor-registration-status-service-impl/pom.xml @@ -11,7 +11,7 @@ 1.2.0.1-SNAPSHOT registration-processor-registration-status-service-impl - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT UTF-8 diff --git a/registration-processor/registration-processor-rest-client/pom.xml b/registration-processor/registration-processor-rest-client/pom.xml index 585348a6202..3d66c5b85ae 100644 --- a/registration-processor/registration-processor-rest-client/pom.xml +++ b/registration-processor/registration-processor-rest-client/pom.xml @@ -1,77 +1,77 @@ - - - 4.0.0 - jar - - - io.mosip.registrationprocessor - registration-processor - 1.2.0.1-SNAPSHOT - - - registration-processor-rest-client - registration-processor-rest-client - 1.2.0.1-B3-SNAPSHOT - - - UTF-8 - - - - org.springframework.cloud - spring-cloud-starter-config - ${spring-cloud-config.version} - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-test - - - org.springframework.boot - spring-boot-starter-data-jpa - - - org.postgresql - postgresql - - - io.springfox - springfox-swagger-ui - ${swagger.version} - - - io.springfox - springfox-swagger2 - ${swagger.version} - - - - junit - junit - test - - - - com.h2database - h2 - - - - io.mosip.registrationprocessor - registration-processor-core - ${registration.processor.core.version} - - - com.auth0 - java-jwt - 3.9.0 - - - + + + 4.0.0 + jar + + + io.mosip.registrationprocessor + registration-processor + 1.2.0.1-SNAPSHOT + + + registration-processor-rest-client + registration-processor-rest-client + 1.2.0.1-SNAPSHOT + + + UTF-8 + + + + org.springframework.cloud + spring-cloud-starter-config + ${spring-cloud-config.version} + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-test + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.postgresql + postgresql + + + io.springfox + springfox-swagger-ui + ${swagger.version} + + + io.springfox + springfox-swagger2 + ${swagger.version} + + + + junit + junit + test + + + + com.h2database + h2 + + + + io.mosip.registrationprocessor + registration-processor-core + ${registration.processor.core.version} + + + com.auth0 + java-jwt + 3.9.0 + + + diff --git a/registration-processor/stage-groups/pom.xml b/registration-processor/stage-groups/pom.xml index 21d8922e0b0..4abd296cb2c 100644 --- a/registration-processor/stage-groups/pom.xml +++ b/registration-processor/stage-groups/pom.xml @@ -1,27 +1,27 @@ - - - 4.0.0 - pom - - io.mosip.registrationprocessor - registration-processor - 1.2.0.1-SNAPSHOT - - 1.2.0.1-B3-SNAPSHOT - stage-groups - stage-groups - - UTF-8 - - - registration-processor-stage-group-1 - registration-processor-stage-group-2 - registration-processor-stage-group-3 - registration-processor-stage-group-4 - registration-processor-stage-group-5 - registration-processor-stage-group-6 - registration-processor-stage-group-7 - + + + 4.0.0 + pom + + io.mosip.registrationprocessor + registration-processor + 1.2.0.1-SNAPSHOT + + 1.2.0.1-SNAPSHOT + stage-groups + stage-groups + + UTF-8 + + + registration-processor-stage-group-1 + registration-processor-stage-group-2 + registration-processor-stage-group-3 + registration-processor-stage-group-4 + registration-processor-stage-group-5 + registration-processor-stage-group-6 + registration-processor-stage-group-7 + \ No newline at end of file diff --git a/registration-processor/stage-groups/registration-processor-stage-group-1/pom.xml b/registration-processor/stage-groups/registration-processor-stage-group-1/pom.xml index 7c8bbc01379..d2c037eee4a 100644 --- a/registration-processor/stage-groups/registration-processor-stage-group-1/pom.xml +++ b/registration-processor/stage-groups/registration-processor-stage-group-1/pom.xml @@ -1,60 +1,60 @@ - - - 4.0.0 - - io.mosip.registrationprocessor - stage-groups - 1.2.0.1-SNAPSHOT - - - registration-processor-stage-group-1 - 1.2.0.1-B3-SNAPSHOT - - - UTF-8 - - - - - - - io.mosip.registrationprocessor - mosip-stage-executor - 1.2.0.1-B3-SNAPSHOT - - - - - io.mosip.registrationprocessor - registration-processor-packet-receiver-stage - 1.2.0.1-B3-SNAPSHOT - - - - - - - - - - org.springframework.boot - spring-boot-maven-plugin - ${spring.boot.version} - - true - io.mosip.registration.processor.stages.executor.MosipStageExecutorApplication - ZIP - - - - - build-info - repackage - - - - - - - + + + 4.0.0 + + io.mosip.registrationprocessor + stage-groups + 1.2.0.1-SNAPSHOT + + + registration-processor-stage-group-1 + 1.2.0.1-SNAPSHOT + + + UTF-8 + + + + + + + io.mosip.registrationprocessor + mosip-stage-executor + 1.2.0.1-SNAPSHOT + + + + + io.mosip.registrationprocessor + registration-processor-packet-receiver-stage + 1.2.0.1-SNAPSHOT + + + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + ${spring.boot.version} + + true + io.mosip.registration.processor.stages.executor.MosipStageExecutorApplication + ZIP + + + + + build-info + repackage + + + + + + + diff --git a/registration-processor/stage-groups/registration-processor-stage-group-2/pom.xml b/registration-processor/stage-groups/registration-processor-stage-group-2/pom.xml index 8f184384299..c0cf46343d5 100644 --- a/registration-processor/stage-groups/registration-processor-stage-group-2/pom.xml +++ b/registration-processor/stage-groups/registration-processor-stage-group-2/pom.xml @@ -1,69 +1,69 @@ - - - 4.0.0 - - io.mosip.registrationprocessor - stage-groups - 1.2.0.1-SNAPSHOT - - - registration-processor-stage-group-2 - 1.2.0.1-B3-SNAPSHOT - - - UTF-8 - - - - - - - io.mosip.registrationprocessor - mosip-stage-executor - 1.2.0.1-B3-SNAPSHOT - - - - - io.mosip.registrationprocessor - registration-processor-quality-classifier-stage - 1.2.0.1-B3-SNAPSHOT - - - io.mosip.registrationprocessor - registration-processor-securezone-notification-stage - 1.2.0.1-B3-SNAPSHOT - - - io.mosip.registrationprocessor - registration-processor-message-sender-stage - 1.2.0.1-B3-SNAPSHOT - - - - - - - - - org.springframework.boot - spring-boot-maven-plugin - ${spring.boot.version} - - true - io.mosip.registration.processor.stages.executor.MosipStageExecutorApplication - ZIP - - - - - build-info - repackage - - - - - - - + + + 4.0.0 + + io.mosip.registrationprocessor + stage-groups + 1.2.0.1-SNAPSHOT + + + registration-processor-stage-group-2 + 1.2.0.1-SNAPSHOT + + + UTF-8 + + + + + + + io.mosip.registrationprocessor + mosip-stage-executor + 1.2.0.1-SNAPSHOT + + + + + io.mosip.registrationprocessor + registration-processor-quality-classifier-stage + 1.2.0.1-SNAPSHOT + + + io.mosip.registrationprocessor + registration-processor-securezone-notification-stage + 1.2.0.1-SNAPSHOT + + + io.mosip.registrationprocessor + registration-processor-message-sender-stage + 1.2.0.1-SNAPSHOT + + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + ${spring.boot.version} + + true + io.mosip.registration.processor.stages.executor.MosipStageExecutorApplication + ZIP + + + + + build-info + repackage + + + + + + + diff --git a/registration-processor/stage-groups/registration-processor-stage-group-3/pom.xml b/registration-processor/stage-groups/registration-processor-stage-group-3/pom.xml index 510842baf7a..e96279087b6 100644 --- a/registration-processor/stage-groups/registration-processor-stage-group-3/pom.xml +++ b/registration-processor/stage-groups/registration-processor-stage-group-3/pom.xml @@ -9,7 +9,7 @@ registration-processor-stage-group-3 - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT UTF-8 @@ -21,29 +21,29 @@ io.mosip.registrationprocessor mosip-stage-executor - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT io.mosip.registrationprocessor registration-processor-abis-handler-stage - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT io.mosip.registrationprocessor registration-processor-abis-middleware-stage - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT io.mosip.registrationprocessor registration-processor-bio-dedupe-stage - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT io.mosip.registrationprocessor registration-processor-manual-adjudication-stage - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT diff --git a/registration-processor/stage-groups/registration-processor-stage-group-4/pom.xml b/registration-processor/stage-groups/registration-processor-stage-group-4/pom.xml index e0eaa85a88a..ce1cdc96545 100644 --- a/registration-processor/stage-groups/registration-processor-stage-group-4/pom.xml +++ b/registration-processor/stage-groups/registration-processor-stage-group-4/pom.xml @@ -9,7 +9,7 @@ registration-processor-stage-group-4 - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT UTF-8 @@ -21,19 +21,19 @@ io.mosip.registrationprocessor mosip-stage-executor - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT io.mosip.registrationprocessor registration-processor-biometric-authentication-stage - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT io.mosip.registrationprocessor registration-processor-demo-dedupe-stage - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT diff --git a/registration-processor/stage-groups/registration-processor-stage-group-5/pom.xml b/registration-processor/stage-groups/registration-processor-stage-group-5/pom.xml index f91437994ed..f167b1d15b3 100644 --- a/registration-processor/stage-groups/registration-processor-stage-group-5/pom.xml +++ b/registration-processor/stage-groups/registration-processor-stage-group-5/pom.xml @@ -9,7 +9,7 @@ registration-processor-stage-group-5 - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT UTF-8 @@ -21,34 +21,34 @@ io.mosip.registrationprocessor mosip-stage-executor - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT io.mosip.registrationprocessor registration-processor-cmd-validator-stage - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT io.mosip.registrationprocessor registration-processor-operator-validator-stage - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT io.mosip.registrationprocessor registration-processor-supervisor-validator-stage - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT io.mosip.registrationprocessor registration-processor-introducer-validator-stage - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT io.mosip.registrationprocessor registration-processor-packet-validator-stage - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT diff --git a/registration-processor/stage-groups/registration-processor-stage-group-6/pom.xml b/registration-processor/stage-groups/registration-processor-stage-group-6/pom.xml index a3166f6e353..114783da14d 100644 --- a/registration-processor/stage-groups/registration-processor-stage-group-6/pom.xml +++ b/registration-processor/stage-groups/registration-processor-stage-group-6/pom.xml @@ -9,7 +9,7 @@ registration-processor-stage-group-6 - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT UTF-8 @@ -21,24 +21,24 @@ io.mosip.registrationprocessor mosip-stage-executor - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT io.mosip.registrationprocessor registration-processor-packet-uploader-stage - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT io.mosip.registrationprocessor registration-processor-packet-classifier-stage - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT io.mosip.registrationprocessor registration-processor-verification-stage - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT diff --git a/registration-processor/stage-groups/registration-processor-stage-group-7/pom.xml b/registration-processor/stage-groups/registration-processor-stage-group-7/pom.xml index a9f42e8b5de..4fc1177f84a 100644 --- a/registration-processor/stage-groups/registration-processor-stage-group-7/pom.xml +++ b/registration-processor/stage-groups/registration-processor-stage-group-7/pom.xml @@ -9,7 +9,7 @@ registration-processor-stage-group-7 - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT UTF-8 @@ -21,29 +21,29 @@ io.mosip.registrationprocessor mosip-stage-executor - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT io.mosip.registrationprocessor registration-processor-uin-generator-stage - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT io.mosip.registrationprocessor registration-processor-biometric-extraction-stage - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT io.mosip.registrationprocessor registration-processor-finalization-stage - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT io.mosip.registrationprocessor registration-processor-printing-stage - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT diff --git a/registration-processor/workflow-engine/pom.xml b/registration-processor/workflow-engine/pom.xml index f8a4bbd14b2..cebeb084931 100644 --- a/registration-processor/workflow-engine/pom.xml +++ b/registration-processor/workflow-engine/pom.xml @@ -7,7 +7,7 @@ registration-processor 1.2.0.1-SNAPSHOT - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT workflow-engine workflow-engine diff --git a/registration-processor/workflow-engine/registration-processor-reprocessor/pom.xml b/registration-processor/workflow-engine/registration-processor-reprocessor/pom.xml index 55ac46340e4..8df1096a769 100644 --- a/registration-processor/workflow-engine/registration-processor-reprocessor/pom.xml +++ b/registration-processor/workflow-engine/registration-processor-reprocessor/pom.xml @@ -1,127 +1,127 @@ - - - 4.0.0 - - io.mosip.registrationprocessor - workflow-engine - 1.2.0.1-SNAPSHOT - - registration-processor-reprocessor - 1.2.0.1-B3-SNAPSHOT - registration-processor-reprocessor - - UTF-8 - UTF-8 - - - - io.mosip.registrationprocessor - registration-processor-core - ${registration.processor.core.version} - - - org.springframework - spring-context - - - org.springframework - spring-tx - - - - io.vertx - vertx-core - ${vertx.version} - - - - io.vertx - vertx-lang-ceylon - 3.4.1 - - - org.ceylon-lang - ceylon-complete - - - - - - org.ceylon-lang - ceylon-complete - 1.3.2 - - - io.mosip.registrationprocessor - registration-processor-registration-status-service-impl - ${registration.status.service.version} - - - io.vertx - vertx-unit - ${vertx.version} - test - - - org.mockito - mockito-core - test - - - io.mosip.registrationprocessor - registration-processor-info-storage-service - ${packet.info.storage.service.version} - - - io.mosip.kernel - kernel-websubclient-api - ${kernel.websubclient.version} - - - - - - org.springframework.cloud - spring-cloud-starter-config - ${spring-cloud-config.version} - - - org.mockito - mockito-core - ${mockito.version} - test - - - com.h2database - h2 - 1.4.195 - - - - - - - org.springframework.boot - spring-boot-maven-plugin - ${spring.boot.version} - - true - io.mosip.registration.processor.reprocessor.ReprocessorApplication - ZIP - - - - - build-info - repackage - - - - - - - + + + 4.0.0 + + io.mosip.registrationprocessor + workflow-engine + 1.2.0.1-SNAPSHOT + + registration-processor-reprocessor + 1.2.0.1-SNAPSHOT + registration-processor-reprocessor + + UTF-8 + UTF-8 + + + + io.mosip.registrationprocessor + registration-processor-core + ${registration.processor.core.version} + + + org.springframework + spring-context + + + org.springframework + spring-tx + + + + io.vertx + vertx-core + ${vertx.version} + + + + io.vertx + vertx-lang-ceylon + 3.4.1 + + + org.ceylon-lang + ceylon-complete + + + + + + org.ceylon-lang + ceylon-complete + 1.3.2 + + + io.mosip.registrationprocessor + registration-processor-registration-status-service-impl + ${registration.status.service.version} + + + io.vertx + vertx-unit + ${vertx.version} + test + + + org.mockito + mockito-core + test + + + io.mosip.registrationprocessor + registration-processor-info-storage-service + ${packet.info.storage.service.version} + + + io.mosip.kernel + kernel-websubclient-api + ${kernel.websubclient.version} + + + + + + org.springframework.cloud + spring-cloud-starter-config + ${spring-cloud-config.version} + + + org.mockito + mockito-core + ${mockito.version} + test + + + com.h2database + h2 + 1.4.195 + + + + + + + org.springframework.boot + spring-boot-maven-plugin + ${spring.boot.version} + + true + io.mosip.registration.processor.reprocessor.ReprocessorApplication + ZIP + + + + + build-info + repackage + + + + + + + diff --git a/registration-processor/workflow-engine/registration-processor-workflow-manager-service/pom.xml b/registration-processor/workflow-engine/registration-processor-workflow-manager-service/pom.xml index d3fe2c8f52d..c69945fe557 100644 --- a/registration-processor/workflow-engine/registration-processor-workflow-manager-service/pom.xml +++ b/registration-processor/workflow-engine/registration-processor-workflow-manager-service/pom.xml @@ -8,7 +8,7 @@ 1.2.0.1-SNAPSHOT registration-processor-workflow-manager-service - 1.2.0.1-B3-SNAPSHOT + 1.2.0.1-SNAPSHOT registration-processor-workflow-manager-service UTF-8 From 359ca765b064ac055e025dd73db8da5aac5cf1f8 Mon Sep 17 00:00:00 2001 From: Sowmya Ujjappa Banakar Date: Tue, 27 Jun 2023 13:15:20 +0530 Subject: [PATCH 081/133] MOSIP-28153 version changes --- registration-processor/pom.xml | 1 - .../registration-processor-cmd-validator-stage/pom.xml | 5 ----- .../pom.xml | 7 +------ .../pom.xml | 5 ----- .../pom.xml | 5 ----- 5 files changed, 1 insertion(+), 22 deletions(-) diff --git a/registration-processor/pom.xml b/registration-processor/pom.xml index 6bbbb0f6625..0684da75445 100644 --- a/registration-processor/pom.xml +++ b/registration-processor/pom.xml @@ -123,7 +123,6 @@ 1.2.0.1-SNAPSHOT 1.2.0.1-SNAPSHOT 1.2.0.1-SNAPSHOT - 1.2.0 1.2.0.1-SNAPSHOT 1.2.0.1-SNAPSHOT 1.2.0.1-SNAPSHOT diff --git a/registration-processor/pre-processor/registration-processor-cmd-validator-stage/pom.xml b/registration-processor/pre-processor/registration-processor-cmd-validator-stage/pom.xml index 7dbf0ec0dde..099373ee95f 100644 --- a/registration-processor/pre-processor/registration-processor-cmd-validator-stage/pom.xml +++ b/registration-processor/pre-processor/registration-processor-cmd-validator-stage/pom.xml @@ -67,11 +67,6 @@ registration-processor-rest-client ${registration.processor.rest.client.version} - - io.mosip.kernel - kernel-bioapi-provider - ${kernel.bioapi.provider.version} - io.mosip.kernel kernel-core diff --git a/registration-processor/pre-processor/registration-processor-introducer-validator-stage/pom.xml b/registration-processor/pre-processor/registration-processor-introducer-validator-stage/pom.xml index 1dc47cd0e37..39b9fc3ac83 100644 --- a/registration-processor/pre-processor/registration-processor-introducer-validator-stage/pom.xml +++ b/registration-processor/pre-processor/registration-processor-introducer-validator-stage/pom.xml @@ -67,12 +67,7 @@ registration-processor-rest-client ${registration.processor.rest.client.version} - - io.mosip.kernel - kernel-bioapi-provider - ${kernel.bioapi.provider.version} - - + io.mosip.kernel kernel-core ${kernel.core.version} diff --git a/registration-processor/pre-processor/registration-processor-operator-validator-stage/pom.xml b/registration-processor/pre-processor/registration-processor-operator-validator-stage/pom.xml index 5783ff54f81..6c2fd429574 100644 --- a/registration-processor/pre-processor/registration-processor-operator-validator-stage/pom.xml +++ b/registration-processor/pre-processor/registration-processor-operator-validator-stage/pom.xml @@ -67,11 +67,6 @@ registration-processor-rest-client ${registration.processor.rest.client.version} - - io.mosip.kernel - kernel-bioapi-provider - ${kernel.bioapi.provider.version} - io.mosip.kernel kernel-core diff --git a/registration-processor/pre-processor/registration-processor-supervisor-validator-stage/pom.xml b/registration-processor/pre-processor/registration-processor-supervisor-validator-stage/pom.xml index 970be29a019..7caa4059e46 100644 --- a/registration-processor/pre-processor/registration-processor-supervisor-validator-stage/pom.xml +++ b/registration-processor/pre-processor/registration-processor-supervisor-validator-stage/pom.xml @@ -67,11 +67,6 @@ registration-processor-rest-client ${registration.processor.rest.client.version} - - io.mosip.kernel - kernel-bioapi-provider - ${kernel.bioapi.provider.version} - io.mosip.kernel kernel-core From ada3e7337220d788f51770f72dda3ebc048d2434 Mon Sep 17 00:00:00 2001 From: Khuddus shariff Date: Fri, 30 Jun 2023 12:04:04 +0530 Subject: [PATCH 082/133] added grant permission --- .../sql/1.1.5.5_to_1.2.0.1-B1_upgrade.sql | 72 +++++++++++++++++-- 1 file changed, 66 insertions(+), 6 deletions(-) diff --git a/db_upgrade_scripts/mosip_regprc/sql/1.1.5.5_to_1.2.0.1-B1_upgrade.sql b/db_upgrade_scripts/mosip_regprc/sql/1.1.5.5_to_1.2.0.1-B1_upgrade.sql index d7bfad42ac4..0698a379f3e 100644 --- a/db_upgrade_scripts/mosip_regprc/sql/1.1.5.5_to_1.2.0.1-B1_upgrade.sql +++ b/db_upgrade_scripts/mosip_regprc/sql/1.1.5.5_to_1.2.0.1-B1_upgrade.sql @@ -18,11 +18,60 @@ 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; @@ -160,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; -------------------------------------------------------------------------------------------------------------------------------------------- From bddc96867ce5b0620bb19521508ba388bb60fad4 Mon Sep 17 00:00:00 2001 From: Sowmya Ujjappa Banakar <43202851+sowmya695@users.noreply.github.com> Date: Mon, 3 Jul 2023 12:07:17 +0530 Subject: [PATCH 083/133] MOSIP-28025 Code fix (#1733) Co-authored-by: Sowmya Ujjappa Banakar --- .../IntroducerValidator.java | 42 +- .../code/RegistrationExceptionTypeCode.java | 608 +++++++------- .../core/status/util/StatusUtil.java | 761 +++++++++--------- .../util/RegistrationExceptionMapperUtil.java | 426 +++++----- 4 files changed, 932 insertions(+), 905 deletions(-) diff --git a/registration-processor/pre-processor/registration-processor-introducer-validator-stage/src/main/java/io/mosip/registration/processor/stages/introducervalidator/IntroducerValidator.java b/registration-processor/pre-processor/registration-processor-introducer-validator-stage/src/main/java/io/mosip/registration/processor/stages/introducervalidator/IntroducerValidator.java index 3a9a5a47810..e957c160d2f 100644 --- a/registration-processor/pre-processor/registration-processor-introducer-validator-stage/src/main/java/io/mosip/registration/processor/stages/introducervalidator/IntroducerValidator.java +++ b/registration-processor/pre-processor/registration-processor-introducer-validator-stage/src/main/java/io/mosip/registration/processor/stages/introducervalidator/IntroducerValidator.java @@ -1,10 +1,7 @@ package io.mosip.registration.processor.stages.introducervalidator; -import java.io.IOException; -import java.security.NoSuchAlgorithmException; -import java.security.cert.CertificateException; -import java.security.spec.InvalidKeySpecException; import java.util.List; +import java.util.Map; import java.util.stream.Collectors; import javax.xml.parsers.ParserConfigurationException; @@ -16,22 +13,20 @@ import com.fasterxml.jackson.databind.ObjectMapper; +import io.mosip.kernel.biometrics.constant.BiometricType; import io.mosip.kernel.biometrics.entities.BIR; import io.mosip.kernel.biometrics.entities.BiometricRecord; import io.mosip.kernel.core.bioapi.exception.BiometricException; import io.mosip.kernel.core.exception.BaseCheckedException; import io.mosip.kernel.core.logger.spi.Logger; -import io.mosip.registration.processor.core.auth.dto.AuthResponseDTO; import io.mosip.registration.processor.core.code.RegistrationExceptionTypeCode; import io.mosip.registration.processor.core.constant.MappingJsonConstants; import io.mosip.registration.processor.core.constant.ProviderStageName; import io.mosip.registration.processor.core.constant.RegistrationType; -import io.mosip.registration.processor.core.exception.AuthSystemException; -import io.mosip.registration.processor.core.exception.PacketDecryptionFailureException; import io.mosip.registration.processor.core.exception.IntroducerOnHoldException; +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.logger.RegProcessorLogger; import io.mosip.registration.processor.core.status.util.StatusUtil; import io.mosip.registration.processor.core.util.RegistrationExceptionMapperUtil; @@ -207,8 +202,20 @@ private void validateIntroducerBiometric(String registrationId, InternalRegistra MappingJsonConstants.INTRODUCER_BIO, registrationStatusDto.getRegistrationType(), ProviderStageName.INTRODUCER_VALIDATOR); if (biometricRecord != null && biometricRecord.getSegments() != null) { - validateUserBiometric(registrationId, introducerUIN, biometricRecord.getSegments(), INDIVIDUAL_TYPE_UIN, - registrationStatusDto); + biometricRecord = filterExceptionBiometrics(biometricRecord); + if (biometricRecord != null && biometricRecord.getSegments() != null) { + validateUserBiometric(registrationId, introducerUIN, biometricRecord.getSegments(), INDIVIDUAL_TYPE_UIN, + registrationStatusDto); + } else { + registrationStatusDto.setLatestTransactionStatusCode(registrationExceptionMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.INTRODUCER_BIOMETRIC_ALL_EXCEPTION_IN_PACKET)); + registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.toString()); + regProcLogger.debug("validateIntroducerBiometric call ended for registrationId {} {}", registrationId, + StatusUtil.INTRODUCER_BIOMETRIC_ALL_EXCEPTION_IN_PACKET.getMessage()); + throw new BaseCheckedException(StatusUtil.INTRODUCER_BIOMETRIC_ALL_EXCEPTION_IN_PACKET.getMessage(), + StatusUtil.INTRODUCER_BIOMETRIC_ALL_EXCEPTION_IN_PACKET.getCode()); + } + } else { registrationStatusDto.setLatestTransactionStatusCode(registrationExceptionMapperUtil .getStatusCode(RegistrationExceptionTypeCode.INTRODUCER_BIOMETRIC_NOT_IN_PACKET)); @@ -241,5 +248,20 @@ private void validateUserBiometric(String registrationId, String userId, List segments = biometricRecord.getSegments().stream().filter(bio -> { + Map othersMap = bio.getOthers().entrySet().stream() + .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue())); + return (othersMap == null || !othersMap.containsKey("EXCEPTION")) ? true + : !(Boolean.parseBoolean(othersMap.get("EXCEPTION"))); + }).collect(Collectors.toList()); + if (segments != null) { + segments = segments.stream().filter(bio -> !bio.getBdbInfo().getType().get(0).name() + .equalsIgnoreCase(BiometricType.EXCEPTION_PHOTO.name())).collect(Collectors.toList()); + } + BiometricRecord biorecord = new BiometricRecord(); + biorecord.setSegments(segments); + return biorecord; + } } \ No newline at end of file diff --git a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/code/RegistrationExceptionTypeCode.java b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/code/RegistrationExceptionTypeCode.java index af9d90638ea..eea08d9c6d0 100644 --- a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/code/RegistrationExceptionTypeCode.java +++ b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/code/RegistrationExceptionTypeCode.java @@ -1,304 +1,306 @@ -package io.mosip.registration.processor.core.code; - -// TODO: Auto-generated Javadoc -/** - * The Enum RegistrationExceptionTypeCode. - */ -public enum RegistrationExceptionTypeCode { - - /** The table not accessible exception. */ - TABLE_NOT_ACCESSIBLE_EXCEPTION, - - /** The internal server error. */ - INTERNAL_SERVER_ERROR, - - /** The packet not found exception. */ - PACKET_NOT_FOUND_EXCEPTION, - - /** The packet uploaded to landing zone. */ - PACKET_UPLOADED_TO_LANDING_ZONE, - - /** The unexcepted error. */ - UNEXCEPTED_ERROR, - - /** The fsadapter exception. */ - OBJECT_STORE_EXCEPTION, - - /** The sftp operation exception. */ - NGINX_ACCESS_EXCEPTION, - - /** The unsupported encoding exception. */ - UNSUPPORTED_ENCODING_EXCEPTION, - - /** The parse exception. */ - PARSE_EXCEPTION, - - /** The data access exception. */ - DATA_ACCESS_EXCEPTION, - - /** The data access layer exception. */ - DATA_ACCESS_LAYER_EXCEPTION, - - /** The duplicate upload request exception. */ - DUPLICATE_UPLOAD_REQUEST_EXCEPTION, - - /** The exception. */ - EXCEPTION, - - /** The interrupted exception. */ - INTERRUPTED_EXCEPTION, - - /** The execution exception. */ - EXECUTION_EXCEPTION, - - /** The unknown host exception. */ - UNKNOWN_HOST_EXCEPTION, - - /** The jms exception. */ - JMS_EXCEPTION, - - /** The invalid key spec exception. */ - INVALID_KEY_SPEC_EXCEPTION, - - /** The illegal argument exception. */ - ILLEGAL_ARGUMENT_EXCEPTION, - - /** The invalid id exception. */ - INVALID_ID_EXCEPTION, - - /** The instantiation exception. */ - INSTANTIATION_EXCEPTION, - - /** The illegal access exception. */ - ILLEGAL_ACCESS_EXCEPTION, - - /** The no such field exception. */ - NO_SUCH_FIELD_EXCEPTION, - - /** The security exception. */ - SECURITY_EXCEPTION, - - /** The template not found exception. */ - TEMPLATE_NOT_FOUND_EXCEPTION, - - /** The template processing failure exception. */ - TEMPLATE_PROCESSING_FAILURE_EXCEPTION, - - /** The template resource not found exception. */ - TEMPLATE_RESOURCE_NOT_FOUND_EXCEPTION, - - /** The template parsing exception. */ - TEMPLATE_PARSING_EXCEPTION, - - /** The template method invocation exception. */ - TEMPLATE_METHOD_INVOCATION_EXCEPTION, - - /** The apis resource access exception. */ - APIS_RESOURCE_ACCESS_EXCEPTION, - - /** The json parse exception. */ - JSON_PARSE_EXCEPTION, - - /** The json mapping exception. */ - JSON_MAPPING_EXCEPTION, - - /** The json processing exception. */ - JSON_PROCESSING_EXCEPTION, - - /** The json io exception. */ - JSON_IO_EXCEPTION, - - /** The json schema io exception. */ - JSON_SCHEMA_IO_EXCEPTION, - - /** The file not found exception. */ - FILE_NOT_FOUND_EXCEPTION, - - /** The file not found in destination exception. */ - FILE_NOT_FOUND_IN_DESTINATION_EXCEPTION, - - /** The no such algorithm exception. */ - NO_SUCH_ALGORITHM_EXCEPTION, - - /** The run time exception. */ - RUN_TIME_EXCEPTION, - - /** The mosip invalid data exception. */ - MOSIP_INVALID_DATA_EXCEPTION, - - /** The mosip invalid keyexception. */ - MOSIP_INVALID_KEY_EXCEPTION, - - /** The class not found exception. */ - CLASS_NOT_FOUND_EXCEPTION, - - /** The reg status validation exception. */ - REG_STATUS_VALIDATION_EXCEPTION, - - /** The packet decryption failure exception. */ - PACKET_DECRYPTION_FAILURE_EXCEPTION, - - /** The configuration not found exception. */ - CONFIGURATION_NOT_FOUND_EXCEPTION, - - /** The identity not found exception. */ - IDENTITY_NOT_FOUND_EXCEPTION, - - /** The queue connection not found. */ - QUEUE_CONNECTION_NOT_FOUND, - - /** The connection unavailable exception. */ - CONNECTION_UNAVAILABLE_EXCEPTION, - - /** The virus scan failed exception. */ - VIRUS_SCAN_FAILED_EXCEPTION, - - /** The virus scanner service failed. */ - VIRUS_SCANNER_SERVICE_FAILED, - - /** The ioexception. */ - IOEXCEPTION, - - /** The file io exception. */ - FILE_IO_EXCEPTION, - - /** The packet osi validation failed. */ - PACKET_OSI_VALIDATION_FAILED, - - /** The packet cmd validation failed. */ - PACKET_CMD_VALIDATION_FAILED, - - /** The packet structural validation failed. */ - PACKET_STRUCTURAL_VALIDATION_FAILED, - - /** The packet uploader failed. */ - PACKET_UPLOADER_FAILED, - - /** The packet uin generation failed. */ - PACKET_UIN_GENERATION_FAILED, - - /** The packet uin generation id repo error. */ - PACKET_UIN_GENERATION_ID_REPO_ERROR, - - /** The invocation target exception. */ - INVOCATION_TARGET_EXCEPTION, - - /** The introspection exception. */ - INTROSPECTION_EXCEPTION, - - VALIDATION_FAILED_EXCEPTION, - - /** The base unchecked exception. */ - BASE_UNCHECKED_EXCEPTION, - - /** The base checked exception. */ - BASE_CHECKED_EXCEPTION, - - /** The external integration failed. */ - EXTERNAL_INTEGRATION_FAILED, - - /** The registration processor checked exception. */ - REGISTRATIONPROCESSORCHECKEDEXCEPTION, - - /** The adult cbeff not present exception. */ - CBEFF_NOT_PRESENT_EXCEPTION, - - /** The demo dedupe abis response error. */ - DEMO_DEDUPE_ABIS_RESPONSE_ERROR, - - /** Exception in packet manager. */ - PACKET_MANAGER_EXCEPTION, - - /** Exception in IDREPO draft. */ - IDREPO_DRAFT_EXCEPTION, - - /**Retry count has exceeded the maximum limit specified */ - PACKET_UPLOAD_FAILED_ON_MAX_RETRY_CNT, - - /** The osi failed on hold introducer packet. */ - ON_HOLD_INTRODUCER_PACKET, - - /** Packet hash failed in uploader stage */ - PACKET_HASH_VALIDATION_FAILED, - - /** The introducer uin and rid not in packet. */ - INTRODUCER_UIN_AND_RID_NOT_IN_PACKET, - - /** The introducer uin not avaialble. */ - INTRODUCER_UIN_NOT_AVAIALBLE, - - /** The osi failed rejected introducer. */ - OSI_FAILED_REJECTED_INTRODUCER, - - /** The introducer biometric not in packet. */ - INTRODUCER_BIOMETRIC_NOT_IN_PACKET, - - /** The supervisorid and officerid not present in packet. */ - SUPERVISORID_AND_OFFICERID_NOT_PRESENT_IN_PACKET, - - /** The officerid not present in packet. */ - OFFICERID_NOT_PRESENT_IN_PACKET, - - /** The supervisorid not present in packet. */ - SUPERVISORID_NOT_PRESENT_IN_PACKET, - - /** The packet creation date not present in packet. */ - PACKET_CREATION_DATE_NOT_PRESENT_IN_PACKET, - - /** The supervisor or officer was inactive. */ - SUPERVISOR_OR_OFFICER_WAS_INACTIVE, - - /** officer was inactive. */ - OFFICER_WAS_INACTIVE, - - /** The officer was inactive. */ - SUPERVISOR_WAS_INACTIVE, - - /** The officer biometric not in packet. */ - OFFICER_BIOMETRIC_NOT_IN_PACKET, - - /** The supervisor biometric not in packet. */ - SUPERVISOR_BIOMETRIC_NOT_IN_PACKET, - - /** The auth error. */ - AUTH_ERROR, - - /** The auth failed. */ - AUTH_FAILED, - - /** The ida authentication failure. */ - IDA_AUTHENTICATION_FAILURE, - - /** The password otp failure. */ - PASSWORD_OTP_FAILURE, - - /** The password otp failure. */ - OPERATOR_PASSWORD_OTP_FAILURE, - - /** The password otp failure. */ - SUPERVISOR_PASSWORD_OTP_FAILURE, - - /** The biometric exception. */ - BIOMETRIC_EXCEPTION, - - BIOMETRIC_TYPE_EXCEPTION, - - AUTH_SYSTEM_EXCEPTION, - - PACKET_REJECTED, - - VID_CREATION_EXCEPTION, - - PACKET_UIN_GENERATION_REPROCESS, - - BIOMETRIC_EXTRACTION_REPROCESS, - - BIOMETRIC_EXTRACTION_FAILED, - - DRAFT_REQUEST_UNAVAILABLE, - - PACKET_FAILED, FINALIZATION_FAILED,FINALIZATION_REPROCESS, - - NO_RECORDS_ASSIGNED, MANUAL_VERIFICATION_FAILED; - +package io.mosip.registration.processor.core.code; + +// TODO: Auto-generated Javadoc +/** + * The Enum RegistrationExceptionTypeCode. + */ +public enum RegistrationExceptionTypeCode { + + /** The table not accessible exception. */ + TABLE_NOT_ACCESSIBLE_EXCEPTION, + + /** The internal server error. */ + INTERNAL_SERVER_ERROR, + + /** The packet not found exception. */ + PACKET_NOT_FOUND_EXCEPTION, + + /** The packet uploaded to landing zone. */ + PACKET_UPLOADED_TO_LANDING_ZONE, + + /** The unexcepted error. */ + UNEXCEPTED_ERROR, + + /** The fsadapter exception. */ + OBJECT_STORE_EXCEPTION, + + /** The sftp operation exception. */ + NGINX_ACCESS_EXCEPTION, + + /** The unsupported encoding exception. */ + UNSUPPORTED_ENCODING_EXCEPTION, + + /** The parse exception. */ + PARSE_EXCEPTION, + + /** The data access exception. */ + DATA_ACCESS_EXCEPTION, + + /** The data access layer exception. */ + DATA_ACCESS_LAYER_EXCEPTION, + + /** The duplicate upload request exception. */ + DUPLICATE_UPLOAD_REQUEST_EXCEPTION, + + /** The exception. */ + EXCEPTION, + + /** The interrupted exception. */ + INTERRUPTED_EXCEPTION, + + /** The execution exception. */ + EXECUTION_EXCEPTION, + + /** The unknown host exception. */ + UNKNOWN_HOST_EXCEPTION, + + /** The jms exception. */ + JMS_EXCEPTION, + + /** The invalid key spec exception. */ + INVALID_KEY_SPEC_EXCEPTION, + + /** The illegal argument exception. */ + ILLEGAL_ARGUMENT_EXCEPTION, + + /** The invalid id exception. */ + INVALID_ID_EXCEPTION, + + /** The instantiation exception. */ + INSTANTIATION_EXCEPTION, + + /** The illegal access exception. */ + ILLEGAL_ACCESS_EXCEPTION, + + /** The no such field exception. */ + NO_SUCH_FIELD_EXCEPTION, + + /** The security exception. */ + SECURITY_EXCEPTION, + + /** The template not found exception. */ + TEMPLATE_NOT_FOUND_EXCEPTION, + + /** The template processing failure exception. */ + TEMPLATE_PROCESSING_FAILURE_EXCEPTION, + + /** The template resource not found exception. */ + TEMPLATE_RESOURCE_NOT_FOUND_EXCEPTION, + + /** The template parsing exception. */ + TEMPLATE_PARSING_EXCEPTION, + + /** The template method invocation exception. */ + TEMPLATE_METHOD_INVOCATION_EXCEPTION, + + /** The apis resource access exception. */ + APIS_RESOURCE_ACCESS_EXCEPTION, + + /** The json parse exception. */ + JSON_PARSE_EXCEPTION, + + /** The json mapping exception. */ + JSON_MAPPING_EXCEPTION, + + /** The json processing exception. */ + JSON_PROCESSING_EXCEPTION, + + /** The json io exception. */ + JSON_IO_EXCEPTION, + + /** The json schema io exception. */ + JSON_SCHEMA_IO_EXCEPTION, + + /** The file not found exception. */ + FILE_NOT_FOUND_EXCEPTION, + + /** The file not found in destination exception. */ + FILE_NOT_FOUND_IN_DESTINATION_EXCEPTION, + + /** The no such algorithm exception. */ + NO_SUCH_ALGORITHM_EXCEPTION, + + /** The run time exception. */ + RUN_TIME_EXCEPTION, + + /** The mosip invalid data exception. */ + MOSIP_INVALID_DATA_EXCEPTION, + + /** The mosip invalid keyexception. */ + MOSIP_INVALID_KEY_EXCEPTION, + + /** The class not found exception. */ + CLASS_NOT_FOUND_EXCEPTION, + + /** The reg status validation exception. */ + REG_STATUS_VALIDATION_EXCEPTION, + + /** The packet decryption failure exception. */ + PACKET_DECRYPTION_FAILURE_EXCEPTION, + + /** The configuration not found exception. */ + CONFIGURATION_NOT_FOUND_EXCEPTION, + + /** The identity not found exception. */ + IDENTITY_NOT_FOUND_EXCEPTION, + + /** The queue connection not found. */ + QUEUE_CONNECTION_NOT_FOUND, + + /** The connection unavailable exception. */ + CONNECTION_UNAVAILABLE_EXCEPTION, + + /** The virus scan failed exception. */ + VIRUS_SCAN_FAILED_EXCEPTION, + + /** The virus scanner service failed. */ + VIRUS_SCANNER_SERVICE_FAILED, + + /** The ioexception. */ + IOEXCEPTION, + + /** The file io exception. */ + FILE_IO_EXCEPTION, + + /** The packet osi validation failed. */ + PACKET_OSI_VALIDATION_FAILED, + + /** The packet cmd validation failed. */ + PACKET_CMD_VALIDATION_FAILED, + + /** The packet structural validation failed. */ + PACKET_STRUCTURAL_VALIDATION_FAILED, + + /** The packet uploader failed. */ + PACKET_UPLOADER_FAILED, + + /** The packet uin generation failed. */ + PACKET_UIN_GENERATION_FAILED, + + /** The packet uin generation id repo error. */ + PACKET_UIN_GENERATION_ID_REPO_ERROR, + + /** The invocation target exception. */ + INVOCATION_TARGET_EXCEPTION, + + /** The introspection exception. */ + INTROSPECTION_EXCEPTION, + + VALIDATION_FAILED_EXCEPTION, + + /** The base unchecked exception. */ + BASE_UNCHECKED_EXCEPTION, + + /** The base checked exception. */ + BASE_CHECKED_EXCEPTION, + + /** The external integration failed. */ + EXTERNAL_INTEGRATION_FAILED, + + /** The registration processor checked exception. */ + REGISTRATIONPROCESSORCHECKEDEXCEPTION, + + /** The adult cbeff not present exception. */ + CBEFF_NOT_PRESENT_EXCEPTION, + + /** The demo dedupe abis response error. */ + DEMO_DEDUPE_ABIS_RESPONSE_ERROR, + + /** Exception in packet manager. */ + PACKET_MANAGER_EXCEPTION, + + /** Exception in IDREPO draft. */ + IDREPO_DRAFT_EXCEPTION, + + /**Retry count has exceeded the maximum limit specified */ + PACKET_UPLOAD_FAILED_ON_MAX_RETRY_CNT, + + /** The osi failed on hold introducer packet. */ + ON_HOLD_INTRODUCER_PACKET, + + /** Packet hash failed in uploader stage */ + PACKET_HASH_VALIDATION_FAILED, + + /** The introducer uin and rid not in packet. */ + INTRODUCER_UIN_AND_RID_NOT_IN_PACKET, + + /** The introducer uin not avaialble. */ + INTRODUCER_UIN_NOT_AVAIALBLE, + + /** The osi failed rejected introducer. */ + OSI_FAILED_REJECTED_INTRODUCER, + + /** The introducer biometric not in packet. */ + INTRODUCER_BIOMETRIC_NOT_IN_PACKET, + + /** The supervisorid and officerid not present in packet. */ + SUPERVISORID_AND_OFFICERID_NOT_PRESENT_IN_PACKET, + + /** The officerid not present in packet. */ + OFFICERID_NOT_PRESENT_IN_PACKET, + + /** The supervisorid not present in packet. */ + SUPERVISORID_NOT_PRESENT_IN_PACKET, + + /** The packet creation date not present in packet. */ + PACKET_CREATION_DATE_NOT_PRESENT_IN_PACKET, + + /** The supervisor or officer was inactive. */ + SUPERVISOR_OR_OFFICER_WAS_INACTIVE, + + /** officer was inactive. */ + OFFICER_WAS_INACTIVE, + + /** The officer was inactive. */ + SUPERVISOR_WAS_INACTIVE, + + /** The officer biometric not in packet. */ + OFFICER_BIOMETRIC_NOT_IN_PACKET, + + /** The supervisor biometric not in packet. */ + SUPERVISOR_BIOMETRIC_NOT_IN_PACKET, + + /** The auth error. */ + AUTH_ERROR, + + /** The auth failed. */ + AUTH_FAILED, + + /** The ida authentication failure. */ + IDA_AUTHENTICATION_FAILURE, + + /** The password otp failure. */ + PASSWORD_OTP_FAILURE, + + /** The password otp failure. */ + OPERATOR_PASSWORD_OTP_FAILURE, + + /** The password otp failure. */ + SUPERVISOR_PASSWORD_OTP_FAILURE, + + /** The biometric exception. */ + BIOMETRIC_EXCEPTION, + + BIOMETRIC_TYPE_EXCEPTION, + + AUTH_SYSTEM_EXCEPTION, + + PACKET_REJECTED, + + VID_CREATION_EXCEPTION, + + PACKET_UIN_GENERATION_REPROCESS, + + BIOMETRIC_EXTRACTION_REPROCESS, + + BIOMETRIC_EXTRACTION_FAILED, + + DRAFT_REQUEST_UNAVAILABLE, + + PACKET_FAILED, FINALIZATION_FAILED,FINALIZATION_REPROCESS, + + NO_RECORDS_ASSIGNED, MANUAL_VERIFICATION_FAILED, + + INTRODUCER_BIOMETRIC_ALL_EXCEPTION_IN_PACKET; + } \ No newline at end of file diff --git a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/status/util/StatusUtil.java b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/status/util/StatusUtil.java index 78b9dcb26af..8b860e167c3 100644 --- a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/status/util/StatusUtil.java +++ b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/status/util/StatusUtil.java @@ -1,381 +1,382 @@ -package io.mosip.registration.processor.core.status.util; - -import io.mosip.registration.processor.core.exception.util.PlatformConstants; - -public enum StatusUtil { - // Packet Receiver Stage - PACKET_RECEIVED(StatusConstants.PACKET_RECEIVER_MODULE_SUCCESS + "001", "Packet has reached Packet Receiver"), - PACKET_UPLOADED_TO_LANDING_ZONE(StatusConstants.PACKET_RECEIVER_MODULE_SUCCESS + "002", - "Packet is Uploaded to Landing Zone"), - VIRUS_SCANNER_FAILED(StatusConstants.PACKET_RECEIVER_MODULE_FAILURE + "001", "Packet is Virus Infected"), - PACKET_DECRYPTION_FAILED(StatusConstants.PACKET_RECEIVER_MODULE_FAILURE + "002", "Packet Decryption Failed"), - - // securezone notification stage - NOTIFICATION_RECEIVED_TO_SECUREZONE(StatusConstants.SECUREZONE_NOTIFICATION_SUCCESS + "001", - "Notification received to securezone"), - - // Packet uploader stage - PACKET_UPLOADED(StatusConstants.PACKET_UPLOADER_MODULE_SUCCESS + "001", "Packet is Uploaded to Packet Store"), - PACKET_CLEANUP_FAILED(StatusConstants.PACKET_UPLOADER_MODULE_FAILED + "001", - "Packet Clean Up Failed from Landing Zone"), - PACKET_ARCHIVAL_FAILED(StatusConstants.PACKET_UPLOADER_MODULE_FAILED + "002", "Packet Archival Failed"), - PACKET_UPLOAD_FAILED(StatusConstants.PACKET_UPLOADER_MODULE_FAILED + "003", "Packet Upload Failed"), - PACKET_NOT_FOUND_LANDING_ZONE(StatusConstants.PACKET_UPLOADER_MODULE_FAILED + "004", - "Packet Not Found in Landing Zone"), - PACKET_HASHCODE_VALIDATION_FAILED(StatusConstants.PACKET_UPLOADER_MODULE_FAILED + "005", - "Packet Hash Code Validation Failed"), - VIRUS_SCANNER_FAILED_UPLOADER(StatusConstants.PACKET_UPLOADER_MODULE_FAILED + "006", "Packet is Virus Infected"), - PACKET_UPLOAD_DECRYPTION_FAILED(StatusConstants.PACKET_UPLOADER_MODULE_FAILED + "007", "Packet Decryption Failed"), - PACKET_ALREADY_UPLOADED(StatusConstants.PACKET_UPLOADER_MODULE_SUCCESS + "008", - "Packet is already present in Packet Store"), - PACKET_RETRY_CNT_EXCEEDED(StatusConstants.PACKET_UPLOADER_MODULE_FAILED + "009", - "Retry count has exceeded the maximum limit specified"), - - // Quality checker stage - INDIVIDUAL_BIOMETRIC_NOT_FOUND(StatusConstants.QUALITY_CHECKER_MODULE_SUCCESS + "001", - "Individual Biometric Parameter Not Found in ID JSON so skipping biometric classification"), - BIOMETRIC_QUALITY_CHECK_SUCCESS(StatusConstants.QUALITY_CHECKER_MODULE_SUCCESS + "002", - "Biometric Quality Check is Successful"), - BIOMETRIC_QUALITY_CHECK_FAILED(StatusConstants.QUALITY_CHECKER_MODULE_FAILED + "001", - "Quality Score of Biometrics Captured is Below the Threshold"), - - // packet validator stage - PACKET_STRUCTURAL_VALIDATION_SUCCESS(StatusConstants.PACKET_VALIDATOR_MODULE_SUCCESS + "001", - "Packet Validation is Successful"), - FILE_VALIDATION_FAILED(StatusConstants.PACKET_VALIDATOR_MODULE_FAILED + "001", "File Validation Failed"), - SCHEMA_VALIDATION_FAILED(StatusConstants.PACKET_VALIDATOR_MODULE_FAILED + "002", "Schema Validation Failed"), - CHECKSUM_VALIDATION_FAILED(StatusConstants.PACKET_VALIDATOR_MODULE_FAILED + "003", "Check Sum Validation Failed"), - INDIVIDUAL_BIOMETRIC_VALIDATION_FAILED(StatusConstants.PACKET_VALIDATOR_MODULE_FAILED + "004", - "Individual Biometric Validation Failed"), - APPLICANT_DOCUMENT_VALIDATION_FAILED(StatusConstants.PACKET_VALIDATOR_MODULE_FAILED + "005", - "Applicant Document Validation Failed"), - MASTER_DATA_VALIDATION_FAILED(StatusConstants.PACKET_VALIDATOR_MODULE_FAILED + "006", - "Master Data Validation Failed"), - ACTIVATE_DEACTIVATE_FAILED(StatusConstants.PACKET_VALIDATOR_MODULE_FAILED + "007", - "Packet Validation for Activate/Deactivate Packet Failed"), - UIN_NOT_FOUND_IDREPO(StatusConstants.PACKET_VALIDATOR_MODULE_FAILED + "008", "UIN is Not Found in ID Repository"), - MANDATORY_VALIDATION_FAILED(StatusConstants.PACKET_VALIDATOR_MODULE_FAILED + "009", - "Mandatory Fields are Not Present in ID Object"), - RID_AND_TYPE_SYNC_FAILED(StatusConstants.PACKET_VALIDATOR_MODULE_FAILED + "010", - "RID & Type not matched from sync table"), - PACKET_REJECTED(StatusConstants.PACKET_VALIDATOR_MODULE_FAILED + "011", "Rejected by Supervisor"), - PACKET_MANAGER_VALIDATION_FAILURE(StatusConstants.PACKET_VALIDATOR_MODULE_FAILED + "012", - "Packet validation failed in packet manager"), - BIOMETRICS_VALIDATION_FAILURE(StatusConstants.PACKET_VALIDATOR_MODULE_FAILED + "013", - "Biometric file validation failed"), - PACKET_MANAGER_EXCEPTION(StatusConstants.PACKET_VALIDATOR_MODULE_FAILED + "014", - "Exception occured in packet manager."), - XSD_VALIDATION_EXCEPTION(StatusConstants.PACKET_VALIDATOR_MODULE_FAILED + "015", "XSD validation failed."), - BIOMETRICS_SIGNATURE_VALIDATION_FAILURE(StatusConstants.PACKET_VALIDATOR_MODULE_FAILED + "016", - "Biometric Signature validation failed"), - PACKET_CONSENT_VALIDATION(StatusConstants.PACKET_VALIDATOR_MODULE_FAILED + "017", - "Consent is not agreed for the packet to process further"), - - // packet classifier stage - PACKET_CLASSIFICATION_SUCCESS(StatusConstants.PACKET_CLASSIFIER_MODULE_SUCCESS + "001", - "Packet Classification is Successful"), - - // External stage - EXTERNAL_STAGE_SUCCESS(StatusConstants.EXTERNAL_SATGE_MODULE_SUCCESS + "001", - "Packet processing in External stage is sucessful"), - EXTERNAL_STAGE_FAILED(StatusConstants.EXTERNAL_SATGE_MODULE_SUCCESS + "001", - "Packet processing in External stage failed"), - - // CMD Validator stage - CMD_VALIDATION_SUCCESS(StatusConstants.CMD_VALIDAOR_MODULE_SUCCESS + "001", "CMD Validation is Successful"), - GPS_DETAILS_NOT_FOUND(StatusConstants.CMD_VALIDAOR_MODULE_FAILED + "001", "GPS Details are Not Found in Packet"), - CENTER_ID_NOT_FOUND(StatusConstants.CMD_VALIDAOR_MODULE_FAILED + "002", "Center ID Not Found in Master DB - "), - CENTER_ID_INACTIVE(StatusConstants.CMD_VALIDAOR_MODULE_FAILED + "003", - "Center was InActive during Packet Creation - "), - MACHINE_ID_NOT_FOUND(StatusConstants.CMD_VALIDAOR_MODULE_FAILED + "004", "Machine ID Not Found in Master DB - "), - MACHINE_ID_NOT_ACTIVE(StatusConstants.CMD_VALIDAOR_MODULE_FAILED + "005", - "Machine ID was InActive during Packet Creation - "), - CENTER_DEVICE_MAPPING_NOT_FOUND(StatusConstants.CMD_VALIDAOR_MODULE_FAILED + "006", - "Center-Device Mapping Not Found - "), - CENTER_DEVICE_MAPPING_INACTIVE(StatusConstants.CMD_VALIDAOR_MODULE_FAILED + "007", - "Center-Device Mapping was InActive during Packet Creation - "), - DEVICE_NOT_FOUND_MASTER_DB(StatusConstants.CMD_VALIDAOR_MODULE_FAILED + "008", "Device Not Found in Master DB - "), - DEVICE_VALIDATION_FAILED(StatusConstants.CMD_VALIDAOR_MODULE_FAILED + "009", "Device Validation Failed"), - PACKET_CREATION_WORKING_HOURS(StatusConstants.CMD_VALIDAOR_MODULE_FAILED + "010", - "Packet was Not Created during Working Hours - "), - REGISTRATION_CENTER_TIMESTAMP_FAILURE(StatusConstants.CMD_VALIDAOR_MODULE_FAILED + "011", - "Registration Center timestamp failed"), - FAILED_TO_GET_MACHINE_DETAIL(StatusConstants.CMD_VALIDAOR_MODULE_FAILED + "012", - "Failed to Get machine id details "), - FAILED_TO_GET_CENTER_DETAIL(StatusConstants.CMD_VALIDAOR_MODULE_FAILED + "013", "Failed to Get center id details "), - VALIDATION_FAILED_EXCEPTION(StatusConstants.CMD_VALIDAOR_MODULE_FAILED + "014", - "Exception occured due to validation failure."), - MACHINE_ID_NOT_FOUND_MASTER_DB(StatusConstants.CMD_VALIDAOR_MODULE_FAILED + "015", - "MachineId not found in master db - "), - TIMESTAMP_NOT_VALID(StatusConstants.CMD_VALIDAOR_MODULE_FAILED + "016", - "digital id timestamp is not within acctable time range of packet creation time"), - DEVICE_HOTLISTED(StatusConstants.CMD_VALIDAOR_MODULE_FAILED + "017", "Device has been hot listed"), - DEVICE_SIGNATURE_VALIDATION_FAILED(StatusConstants.CMD_VALIDAOR_MODULE_FAILED + "018", - "DigitalId signature Validation Failed"), - CMD_LANGUAGE_NOT_SET(StatusConstants.CMD_VALIDAOR_MODULE_FAILED + "019", - "Mandatory/Optional Language not set for CMD validation."), - - // Operator Validator stage - OPERATOR_VALIDATION_SUCCESS(StatusConstants.OVM_VALIDAOR_MODULE_SUCCESS + "001", - "OPERATOR Validation is Successful"), - OFFICER_NOT_ACTIVE(StatusConstants.OVM_VALIDAOR_MODULE_FAILED + "001", "OfficerId is inActive"), - OPERATOR_PACKET_CREATION_DATE_NOT_FOUND_IN_PACKET(StatusConstants.OVM_VALIDAOR_MODULE_FAILED + "002", - "Packet Creation Date is NULL"), - OPERATOR_PASSWORD_OTP_FAILURE(StatusConstants.OVM_VALIDAOR_MODULE_FAILED + "003", - "Password or OTP Verification Failed for Officer - "), - OFFICER_WAS_INACTIVE(StatusConstants.OVM_VALIDAOR_MODULE_FAILED + "004", - "Officer was Not Active during Packet Creation - "), - OFFICER_NOT_FOUND_PACKET(StatusConstants.OVM_VALIDAOR_MODULE_FAILED + "005", "Officer ID is NULL"), - - // Supervisor Validator stage - SUPERVISOR_VALIDATION_SUCCESS(StatusConstants.SVM_VALIDAOR_MODULE_SUCCESS + "001", - "SUPERVISOR Validation is Successful"), - SUPERVISOR_NOT_ACTIVE(StatusConstants.SVM_VALIDAOR_MODULE_FAILED + "001", "SupervisorId is inActive"), - SUPERVISOR_PACKET_CREATION_DATE_NOT_FOUND_IN_PACKET(StatusConstants.SVM_VALIDAOR_MODULE_FAILED + "002", - "Packet Creation Date is NULL"), - SUPERVISOR_PASSWORD_OTP_FAILURE(StatusConstants.SVM_VALIDAOR_MODULE_FAILED + "003", - "Password or OTP Verification Failed for Officer - "), - SUPERVISOR_WAS_INACTIVE(StatusConstants.SVM_VALIDAOR_MODULE_FAILED + "004", - "Supervisor was Not Active during Packet Creation - "), - PASSWORD_OTP_FAILURE_SUPERVISOR(StatusConstants.SVM_VALIDAOR_MODULE_FAILED + "005", - "Password or OTP Verification Failed for Supervisor - "), - SUPERVISOR_NOT_FOUND_PACKET(StatusConstants.OVM_VALIDAOR_MODULE_FAILED + "006", "Supervisor ID is NULL"), - - // Introducer Validator stage - INTRODUCER_VALIDATION_SUCCESS(StatusConstants.IVM_VALIDAOR_MODULE_SUCCESS + "001", - "INTRODUCER Validation is Successful"), - INTRODUCER_AUTHENTICATION_FAILED(StatusConstants.IVM_VALIDAOR_MODULE_FAILED + "001", - "INTRODUCER Biometric Authentication Failed - "), - UIN_RID_NOT_FOUND(StatusConstants.IVM_VALIDAOR_MODULE_FAILED + "002", - "UIN or RID of Introducer Not Found in Packet"), - INTRODUCER_UIN_NOT_FOUND(StatusConstants.IVM_VALIDAOR_MODULE_FAILED + "003", - "Introducer UIN not Found for the Given RID"), - INTRODUCER_BIOMETRIC_FILE_NAME_NOT_FOUND(StatusConstants.IVM_VALIDAOR_MODULE_FAILED + "004", - "Introducer Biometric File Name Not Found"), - PACKET_ON_HOLD(StatusConstants.IVM_VALIDAOR_MODULE_FAILED + "005", - "Packet On-Hold as Introducer packet is not processed yet."), - CHILD_PACKET_REJECTED(StatusConstants.IVM_VALIDAOR_MODULE_FAILED + "006", - "Packet Rejected as Parent Packet is Rejected"), - PACKET_IS_ON_HOLD(StatusConstants.IVM_VALIDAOR_MODULE_FAILED + "007", - "Packet is on Hold due to parent packet processing"), - - // printing stage - PRINT_REQUEST_SUCCESS(StatusConstants.PRINT_STAGE_MODULE_SUCCESS + "001", "Print request submitted"), - PDF_ADDED_TO_QUEUE_FAILED(StatusConstants.PRINT_STAGE_MODULE_FAILED + "001", - "PDF was not added to Queue due to Queue Failure"), - PRINT_POST_COMPLETED(StatusConstants.PRINT_STAGE_MODULE_SUCCESS + "002", "Printing and Post Completed"), - RESEND_UIN_CARD(StatusConstants.PRINT_STAGE_MODULE_SUCCESS + "003", "Re-Sent UIN Card for Printing"), - PDF_GENERATION_FAILED(StatusConstants.PRINT_STAGE_MODULE_SUCCESS + "004", "Pdf Generation failed for "), - TEMPLATE_PROCESSING_FAILED(StatusConstants.PRINT_STAGE_MODULE_SUCCESS + "005", "Pdf Generation failed for "), - QUEUE_CONNECTION_NOT_FOUND(StatusConstants.PRINT_STAGE_MODULE_SUCCESS + "006", "Queue Connection not found "), - QUEUE_CONNECTION_UNAVAILABLE(StatusConstants.PRINT_STAGE_MODULE_SUCCESS + "007", - "Queue Connection unavailable for "), - PDF_SIGNTURED_FAILED(StatusConstants.PRINT_STAGE_MODULE_SUCCESS + "008", "Pdf Signature failed "), - PRINT_REQUEST_FAILED(StatusConstants.PRINT_STAGE_MODULE_FAILED + "009", "Print request failed"), - UIN_NOT_FOUND_IN_DATABASE(StatusConstants.PRINT_STAGE_MODULE_FAILED + "010", "UIN not found in database"), - /** The rpr prt vid exception. */ - VID_NOT_AVAILABLE(PlatformConstants.RPR_PRINTING_MODULE + "011", "vid not available"), - - // Abis middleware stage - INSERT_IDENTIFY_REQUEST_SUCCESS(StatusConstants.ABIS_MIDDLEWARE_MODULE_SUCCESS + "001", - "Insert or Identify Request sent to ABIS Queue is succesful"), - INSERT_IDENTIFY_REQUEST_FAILED(StatusConstants.ABIS_MIDDLEWARE_MODULE_FAILED + "001", - "Insert or Identify Request sent to ABIS Queue is Unsuccesful"), - INSERT_IDENTIFY_RESPONSE_SUCCESS(StatusConstants.ABIS_MIDDLEWARE_MODULE_SUCCESS + "002", - "Recived sucessful response from ABIS"), - INSERT_IDENTIFY_RESPONSE_FAILED(StatusConstants.ABIS_MIDDLEWARE_MODULE_SUCCESS + "002", - "Received failed response from ABIS - "), - - // System Exceptions - // Bio dedupe stage - BIO_DEDUPE_INPROGRESS(StatusConstants.BIO_DEDUPE_MODULE_SUCCESS + "001", "Biometric Deduplication In-Progress"), - BIO_DEDUPE_SUCCESS(StatusConstants.BIO_DEDUPE_MODULE_SUCCESS + "002", "Biometric Deduplication is Successful"), - BIO_DEDUPE_POTENTIAL_MATCH(StatusConstants.BIO_DEDUPE_MODULE_FAILED + "001", - "Potential Biometric Match Found while Processing Packet"), - LOST_PACKET_BIOMETRICS_NOT_FOUND(StatusConstants.BIO_DEDUPE_MODULE_FAILED + "002", - "No Match was Found for the Biometrics Received"), - LOST_PACKET_UNIQUE_MATCH_FOUND(StatusConstants.BIO_DEDUPE_MODULE_SUCCESS + "003", - "Unique Match was Found for the Biometrics Received"), - LOST_PACKET_MULTIPLE_MATCH_FOUND(StatusConstants.BIO_DEDUPE_MODULE_FAILED + "003", - "Multiple Match was Found for the Biometrics Received"), - - // Biometric authentication stage - BIOMETRIC_AUTHENTICATION_FAILED(StatusConstants.BIO_METRIC_AUTHENTICATION_MODULE_FAILED + "001", - "Biometric Authentication has Failed"), - BIOMETRIC_AUTHENTICATION_SUCCESS(StatusConstants.BIO_METRIC_AUTHENTICATION_MODULE_SUCCESS + "001", - "Biometric Authentication is Successful"), - BIOMETRIC_FILE_NOT_FOUND(StatusConstants.SYSTEM_EXCEPTION_CODE, "Biometric File Not Found"), - BIOMETRIC_AUTHENTICATION_FAILED_FILE_NOT_FOUND(StatusConstants.SYSTEM_EXCEPTION_CODE, - "Biometric Authentication Failed File is not present inside identity json"), - INDIVIDUAL_BIOMETRIC_AUTHENTICATION_FAILED(StatusConstants.BIO_METRIC_AUTHENTICATION_MODULE_FAILED + "001", - "Individual authentication failed"), - BIOMETRIC_AUTHENTICATION_SKIPPED(StatusConstants.BIO_METRIC_AUTHENTICATION_MODULE_SUCCESS + "002", - "Biometric Authentication is Skipped "), - - // Demo dedupe stage - DEMO_DEDUPE_SUCCESS(StatusConstants.DEMO_DEDUPE_MODULE_SUCCESS + "001", "Demo Dedupe is Successful"), - POTENTIAL_MATCH_FOUND_IN_ABIS(StatusConstants.DEMO_DEDUPE_MODULE_FAILED + "001", - "Biometric Duplicate was Found in ABIS"), - POTENTIAL_MATCH_FOUND(StatusConstants.DEMO_DEDUPE_MODULE_FAILED + "002", "Potential Demo Match was Found"), - DEMO_DEDUPE_SKIPPED(StatusConstants.DEMO_DEDUPE_MODULE_SKIPPED + "003", "Demographic Deduplication Skipped"), - - // Manual verification stage - MANUAL_VERIFIER_APPROVED_PACKET(StatusConstants.MANUAL_VERIFICATION_MODULE_SUCCESS + "001", - "Match Not Found by Manual Verifier"), - MANUAL_VERIFIER_REJECTED_PACKET(StatusConstants.MANUAL_VERIFICATION_MODULE_FAILED + "002", - "Match Found by Manual Verifier"), - RPR_MANUAL_VERIFICATION_RESEND(StatusConstants.MANUAL_VERIFICATION_MODULE_FAILED + "003", - "Error in manual verification"), - RPR_MANUAL_VERIFICATION_SENT_TO_QUEUE(PlatformConstants.RPR_MANUAL_ADJUDICATION_MODULE + "002", - "Manual verification request sent to queue"), - - // Uin generator stage - UIN_GENERATED_SUCCESS(StatusConstants.UIN_GENERATOR_MODULE_SUCCESS + "001", "UIN Generated Successfully"), - UIN_DATA_UPDATION_SUCCESS(StatusConstants.UIN_GENERATOR_MODULE_SUCCESS + "002", "UIN Data is drafted Successfully"), - UIN_ACTIVATED_SUCCESS(StatusConstants.UIN_GENERATOR_MODULE_SUCCESS + "003", "UIN is Activated"), - UIN_DEACTIVATION_SUCCESS(StatusConstants.UIN_GENERATOR_MODULE_SUCCESS + "004", "UIN is Deactivated"), - LINK_RID_FOR_LOST_PACKET_SUCCESS(StatusConstants.UIN_GENERATOR_MODULE_SUCCESS + "005", - "RID linked Successfully for Lost UIN Packet"), - - UIN_ALREADY_ACTIVATED(StatusConstants.UIN_GENERATOR_MODULE_FAILED + "001", "UIN is already Activated"), - UIN_ACTIVATED_FAILED(StatusConstants.UIN_GENERATOR_MODULE_FAILED + "002", "UIN Activation Failed"), - UIN_ALREADY_DEACTIVATED(StatusConstants.UIN_GENERATOR_MODULE_FAILED + "003", "UIN already deactivated"), - - UIN_GENERATION_FAILED(StatusConstants.UIN_GENERATOR_MODULE_FAILED + "004", "UIN Generation failed - "), - UIN_DATA_UPDATION_FAILED(StatusConstants.UIN_GENERATOR_MODULE_FAILED + "005", "UIN Updation failed - "), - UIN_REACTIVATION_FAILED(StatusConstants.UIN_GENERATOR_MODULE_FAILED + "006", "UIN Reactivation failed - "), - UIN_DEACTIVATION_FAILED(StatusConstants.UIN_GENERATOR_MODULE_FAILED + "007", "UIN Deactivation failed - "), - LINK_RID_FOR_LOST_PACKET_FAILED(StatusConstants.UIN_GENERATOR_MODULE_FAILED + "008", - "UIn not found the the matched RID"), - IDREPO_DRAFT_EXCEPTION(StatusConstants.UIN_GENERATOR_MODULE_FAILED + "008", - "Exception occured updating idrepo draft."), - - // Biometric extraction stage - BIOMETRIC_EXTRACTION_SUCCESS(StatusConstants.BIOMETRIC_EXTRACTION_MODULE_SUCCESS + "001", - "biometric extaction was successful"), - BIOMETRIC_EXTRACTION_DRAFT_REQUEST_UNAVAILABLE(StatusConstants.BIOMETRIC_EXTRACTION_MODULE_FAILED + "001", - "Draft request is unavaialble in id-repo draft repository."), - - FINALIZATION_SUCCESS(StatusConstants.FINALIZATION_MODULE_SUCCESS + "001", - "idrepo draft was published successfuly"), - FINALIZATION_FAILURE(StatusConstants.FINALIZATION_MODULE_FAILED + "001", "Draft request failed to publish."), - FINALIZATION_DRAFT_REQUEST_UNAVAILABLE(StatusConstants.FINALIZATION_MODULE_FAILED + "001", - "Draft request is unavaialble in id-repo draft repository."), - - // Request handler service - // 1)Resident UIN update - RESIDENT_UPDATE_SUCCES(StatusConstants.REQUEST_HANDLER_MODULE_SUCCESS + "001", - "Resident Uin data updated sucessfully"), - RESIDENT_UPDATE_FAILED(StatusConstants.REQUEST_HANDLER_MODULE_FAILED + "001", "Resident Uin update failed"), - INVALID_REQUEST(StatusConstants.REQUEST_HANDLER_MODULE_FAILED + "001", "Invalid Request Value - "), - INVALID_CENTER(StatusConstants.REQUEST_HANDLER_MODULE_FAILED + "002", "Invalid Request Value - "), - INVALID_MACHINE(StatusConstants.REQUEST_HANDLER_MODULE_FAILED + "003", "Invalid Request Value - "), - - // 2)PacketGeneration - PACKET_GENERATION_SUCCESS(StatusConstants.REQUEST_HANDLER_MODULE_SUCCESS + "001", "Packet generated sucessfully"), - PACKET_GENERATION_FAILED(StatusConstants.REQUEST_HANDLER_MODULE_FAILED + "001", "Packet generated failed"), - - // 3)Uin card reprint - UIN_CARD_REPRINT_SUCCESS(StatusConstants.REQUEST_HANDLER_MODULE_SUCCESS + "001", "UIN card reprint success"), - UIN_CARD_REPRINT_FAILED(StatusConstants.REQUEST_HANDLER_MODULE_FAILED + "001", "UIN card reprint failed"), - - // System Exceptions - VIRUS_SCANNER_SERVICE_NOT_ACCESSIBLE(StatusConstants.SYSTEM_EXCEPTION_CODE, - "Virus Scanner Service is not accessible"), - DB_NOT_ACCESSIBLE(StatusConstants.SYSTEM_EXCEPTION_CODE, "Databse Not Accessible"), - PACKET_NOT_FOUND_PACKET_STORE(StatusConstants.SYSTEM_EXCEPTION_CODE, "Packet not found in File System"), - OBJECT_STORE_EXCEPTION(StatusConstants.SYSTEM_EXCEPTION_CODE, "Object store exception occured"), - JSCH_EXCEPTION_OCCURED(StatusConstants.SYSTEM_EXCEPTION_CODE, "JSCH Connection Exception Occurred"), - NGINX_ACCESS_EXCEPTION(StatusConstants.SYSTEM_EXCEPTION_CODE, "NGINX url is not accessible"), - IO_EXCEPTION(StatusConstants.SYSTEM_EXCEPTION_CODE, "IO Exception Occurred"), - BIO_METRIC_EXCEPTION(StatusConstants.SYSTEM_EXCEPTION_CODE, "Biometric Exception Occurred in IDA "), - BIO_METRIC_FILE_MISSING(StatusConstants.SYSTEM_EXCEPTION_CODE, "Applicant biometric fileName/file is missing"), - BIO_METRIC_TYPE_EXCEPTION(StatusConstants.SYSTEM_EXCEPTION_CODE, "Requested biometric type not found"), - - UNKNOWN_EXCEPTION_OCCURED(StatusConstants.SYSTEM_EXCEPTION_CODE, "Unknown exception occured "), - API_RESOUCE_ACCESS_FAILED(StatusConstants.SYSTEM_EXCEPTION_CODE, "Unable to access API resource"), - AUTH_SYSTEM_EXCEPTION(StatusConstants.SYSTEM_EXCEPTION_CODE, "Auth System Exception"), - JSON_PARSING_EXCEPTION(StatusConstants.SYSTEM_EXCEPTION_CODE, "Error Occurred while Parsing JSON"), - BASE_CHECKED_EXCEPTION(StatusConstants.SYSTEM_EXCEPTION_CODE, "Packet validation failed "), - BASE_UNCHECKED_EXCEPTION(StatusConstants.SYSTEM_EXCEPTION_CODE, "Packet validation failed "), - - OFFICER_AUTHENTICATION_FAILED(StatusConstants.SYSTEM_EXCEPTION_CODE, "Officer Authentication Failed: "), - SUPERVISOR_AUTHENTICATION_FAILED(StatusConstants.SYSTEM_EXCEPTION_CODE, "Supervisor Authentication Failed: "), - - IDENTIFY_RESPONSE_FAILED(StatusConstants.SYSTEM_EXCEPTION_CODE, "Identify Response Failed for Request ID - "), - INSERT_RESPONSE_FAILED(StatusConstants.SYSTEM_EXCEPTION_CODE, "Insert Response Failed for Request ID - "), - SYSTEM_EXCEPTION_OCCURED(StatusConstants.SYSTEM_EXCEPTION_CODE, "Internal error occured - "), - - CBEF_NOT_FOUND(StatusConstants.SYSTEM_EXCEPTION_CODE, "Unable to Find Applicant CBEFF for Adult"), - - IIEGAL_ARGUMENT_EXCEPTION(StatusConstants.SYSTEM_EXCEPTION_CODE, "Illegal Argument Exception Occurred - "), - DEMO_DEDUPE_FAILED_IN_ABIS(StatusConstants.SYSTEM_EXCEPTION_CODE, "Demo Dedupe Failed in ABIS"), - RE_PROCESS_FAILED(StatusConstants.RE_PROCESS_MODULE_FAILED + "001", - "Reprocess count has exceeded the configured attempts"), - RE_PROCESS_COMPLETED(StatusConstants.RE_PROCESS_MODULE_SUCCESS + "001", "Reprocess Completed"), - - // Message sender stage - NOTIFICATION_SUCESSFUL(StatusConstants.MESSAGE_SENDER_NOTIF_SUCCESS_CODE + "001", "Notification Sent Successfully"), - TEMPLATE_CONFIGURATION_NOT_FOUND(StatusConstants.MESSAGE_SENDER__FAILED_CODE + "002", - "Template configuration and language not found"), - EMAIL_PHONE_TEMPLATE_NOTIFICATION_MISSING(StatusConstants.MESSAGE_SENDER__FAILED_CODE + "003", - "Email ID or Phone or Template or Notification Type is Missing"), - NOTIFICATION_FAILED_FOR_LOST(StatusConstants.MESSAGE_SENDER__FAILED_CODE + "004", - "Unable to Send Notification - UIN was not found for the Lost Packet"), - - MESSAGE_SENDER_NOTIF_SUCC(StatusConstants.MESSAGE_SENDER_NOTIF_SUCCESS_CODE + "001", - "Email and SMS Notification were sent"), - MESSAGE_SENDER_NOT_CONFIGURED(StatusConstants.MESSAGE_SENDER_NOTIF_SUCCESS_CODE + "002", - "Notification was not sent as notification type was not set"), - MESSAGE_SENDER_EMAIL_SUCCESS(StatusConstants.MESSAGE_SENDER_NOTIF_SUCCESS_CODE + "003", - "Email Notification was sent"), - MESSAGE_SENDER_SMS_SUCCESS(StatusConstants.MESSAGE_SENDER_NOTIF_SUCCESS_CODE + "004", "SMS Notification was sent"), - MESSAGE_SENDER_EMAIL_FAILED(StatusConstants.MESSAGE_SENDER__FAILED_CODE + "005", - "Notification was not sent as the required mode of channel was not available"), - MESSAGE_SENDER_SMS_FAILED(StatusConstants.MESSAGE_SENDER__FAILED_CODE + "006", - "Notification was not sent as the required mode of channel was not available"), - MESSAGE_SENDER_NOTIFICATION_FAILED(StatusConstants.MESSAGE_SENDER__FAILED_CODE + "006", - "Notification was not sent as the required mode of channel was not available"), - VID_CREATION_FAILED(StatusConstants.UIN_GENERATOR_MODULE_FAILED + "009", "VID creation failed -"), - - WORKFLOW_INTERNAL_ACTION_SUCCESS(StatusConstants.WORKFLOW_INTERNAL_ACTION + "001", - "Packet workflow internal action completed successfully"), - - WORKFLOW_INTERNAL_ACTION_REJECTED_ITERATIONS_EXCEEDED_LIMIT(StatusConstants.WORKFLOW_INTERNAL_ACTION + "002", - "Packet rejected as number of iterations exceeded permited limit."), - - WORKFLOW_ACTION_SERVICE_SUCCESS(StatusConstants.WORKFLOW_ACTION_SERVICE + "001", - "Packet workflow resume successfully"), - MANUAL_ADJUDICATION_FAILED(PlatformConstants.RPR_MANUAL_ADJUDICATION_MODULE + "000", - "manual verification failed -"), - MANUAL_ADJUDICATION_RID_SHOULD_NOT_EMPTY_OR_NULL(PlatformConstants.RPR_MANUAL_ADJUDICATION_MODULE + "001", - "Registration Id should not empty or null "), - MANUAL_ADJUDICATION_MATCHEDRID_FOUND_FOR_GIVEN_RID(PlatformConstants.RPR_MANUAL_ADJUDICATION_MODULE + "002", - "No matched reference id found for given RID"), - VERIFICATION_SUCCESS(StatusConstants.VERIFICATION_STAGE + "001", "Verification success"), - VERIFICATION_FAILED(StatusConstants.VERIFICATION_STAGE + "002", "Verification failed"), - VERIFICATION_SENT(StatusConstants.VERIFICATION_STAGE + "003", "Sent for verification"), - VERIFICATION_RESEND(StatusConstants.VERIFICATION_STAGE + "004", "Resend for verification"); - - private final String statusComment; - private final String statusCode; - - private StatusUtil(String statusCode, String statusComment) { - this.statusCode = statusCode; - this.statusComment = statusComment; - } - - public String getMessage() { - return this.statusComment; - } - - /** - * Gets the error code. - * - * @return the error code - */ - public String getCode() { - return this.statusCode; - } - +package io.mosip.registration.processor.core.status.util; + +import io.mosip.registration.processor.core.exception.util.PlatformConstants; + +public enum StatusUtil { + // Packet Receiver Stage + PACKET_RECEIVED(StatusConstants.PACKET_RECEIVER_MODULE_SUCCESS + "001", "Packet has reached Packet Receiver"), + PACKET_UPLOADED_TO_LANDING_ZONE(StatusConstants.PACKET_RECEIVER_MODULE_SUCCESS + "002", + "Packet is Uploaded to Landing Zone"), + VIRUS_SCANNER_FAILED(StatusConstants.PACKET_RECEIVER_MODULE_FAILURE + "001", "Packet is Virus Infected"), + PACKET_DECRYPTION_FAILED(StatusConstants.PACKET_RECEIVER_MODULE_FAILURE + "002", "Packet Decryption Failed"), + + // securezone notification stage + NOTIFICATION_RECEIVED_TO_SECUREZONE(StatusConstants.SECUREZONE_NOTIFICATION_SUCCESS + "001", + "Notification received to securezone"), + + // Packet uploader stage + PACKET_UPLOADED(StatusConstants.PACKET_UPLOADER_MODULE_SUCCESS + "001", "Packet is Uploaded to Packet Store"), + PACKET_CLEANUP_FAILED(StatusConstants.PACKET_UPLOADER_MODULE_FAILED + "001", + "Packet Clean Up Failed from Landing Zone"), + PACKET_ARCHIVAL_FAILED(StatusConstants.PACKET_UPLOADER_MODULE_FAILED + "002", "Packet Archival Failed"), + PACKET_UPLOAD_FAILED(StatusConstants.PACKET_UPLOADER_MODULE_FAILED + "003", "Packet Upload Failed"), + PACKET_NOT_FOUND_LANDING_ZONE(StatusConstants.PACKET_UPLOADER_MODULE_FAILED + "004", + "Packet Not Found in Landing Zone"), + PACKET_HASHCODE_VALIDATION_FAILED(StatusConstants.PACKET_UPLOADER_MODULE_FAILED + "005", + "Packet Hash Code Validation Failed"), + VIRUS_SCANNER_FAILED_UPLOADER(StatusConstants.PACKET_UPLOADER_MODULE_FAILED + "006", "Packet is Virus Infected"), + PACKET_UPLOAD_DECRYPTION_FAILED(StatusConstants.PACKET_UPLOADER_MODULE_FAILED + "007", "Packet Decryption Failed"), + PACKET_ALREADY_UPLOADED(StatusConstants.PACKET_UPLOADER_MODULE_SUCCESS + "008", + "Packet is already present in Packet Store"), + PACKET_RETRY_CNT_EXCEEDED(StatusConstants.PACKET_UPLOADER_MODULE_FAILED + "009", + "Retry count has exceeded the maximum limit specified"), + + // Quality checker stage + INDIVIDUAL_BIOMETRIC_NOT_FOUND(StatusConstants.QUALITY_CHECKER_MODULE_SUCCESS + "001", + "Individual Biometric Parameter Not Found in ID JSON so skipping biometric classification"), + BIOMETRIC_QUALITY_CHECK_SUCCESS(StatusConstants.QUALITY_CHECKER_MODULE_SUCCESS + "002", + "Biometric Quality Check is Successful"), + BIOMETRIC_QUALITY_CHECK_FAILED(StatusConstants.QUALITY_CHECKER_MODULE_FAILED + "001", + "Quality Score of Biometrics Captured is Below the Threshold"), + + // packet validator stage + PACKET_STRUCTURAL_VALIDATION_SUCCESS(StatusConstants.PACKET_VALIDATOR_MODULE_SUCCESS + "001", + "Packet Validation is Successful"), + FILE_VALIDATION_FAILED(StatusConstants.PACKET_VALIDATOR_MODULE_FAILED + "001", "File Validation Failed"), + SCHEMA_VALIDATION_FAILED(StatusConstants.PACKET_VALIDATOR_MODULE_FAILED + "002", "Schema Validation Failed"), + CHECKSUM_VALIDATION_FAILED(StatusConstants.PACKET_VALIDATOR_MODULE_FAILED + "003", "Check Sum Validation Failed"), + INDIVIDUAL_BIOMETRIC_VALIDATION_FAILED(StatusConstants.PACKET_VALIDATOR_MODULE_FAILED + "004", + "Individual Biometric Validation Failed"), + APPLICANT_DOCUMENT_VALIDATION_FAILED(StatusConstants.PACKET_VALIDATOR_MODULE_FAILED + "005", + "Applicant Document Validation Failed"), + MASTER_DATA_VALIDATION_FAILED(StatusConstants.PACKET_VALIDATOR_MODULE_FAILED + "006", + "Master Data Validation Failed"), + ACTIVATE_DEACTIVATE_FAILED(StatusConstants.PACKET_VALIDATOR_MODULE_FAILED + "007", + "Packet Validation for Activate/Deactivate Packet Failed"), + UIN_NOT_FOUND_IDREPO(StatusConstants.PACKET_VALIDATOR_MODULE_FAILED + "008", "UIN is Not Found in ID Repository"), + MANDATORY_VALIDATION_FAILED(StatusConstants.PACKET_VALIDATOR_MODULE_FAILED + "009", + "Mandatory Fields are Not Present in ID Object"), + RID_AND_TYPE_SYNC_FAILED(StatusConstants.PACKET_VALIDATOR_MODULE_FAILED + "010", + "RID & Type not matched from sync table"), + PACKET_REJECTED(StatusConstants.PACKET_VALIDATOR_MODULE_FAILED + "011", "Rejected by Supervisor"), + PACKET_MANAGER_VALIDATION_FAILURE(StatusConstants.PACKET_VALIDATOR_MODULE_FAILED + "012", + "Packet validation failed in packet manager"), + BIOMETRICS_VALIDATION_FAILURE(StatusConstants.PACKET_VALIDATOR_MODULE_FAILED + "013", + "Biometric file validation failed"), + PACKET_MANAGER_EXCEPTION(StatusConstants.PACKET_VALIDATOR_MODULE_FAILED + "014", + "Exception occured in packet manager."), + XSD_VALIDATION_EXCEPTION(StatusConstants.PACKET_VALIDATOR_MODULE_FAILED + "015", "XSD validation failed."), + BIOMETRICS_SIGNATURE_VALIDATION_FAILURE(StatusConstants.PACKET_VALIDATOR_MODULE_FAILED + "016", + "Biometric Signature validation failed"), + PACKET_CONSENT_VALIDATION(StatusConstants.PACKET_VALIDATOR_MODULE_FAILED + "017", + "Consent is not agreed for the packet to process further"), + + // packet classifier stage + PACKET_CLASSIFICATION_SUCCESS(StatusConstants.PACKET_CLASSIFIER_MODULE_SUCCESS + "001", + "Packet Classification is Successful"), + + // External stage + EXTERNAL_STAGE_SUCCESS(StatusConstants.EXTERNAL_SATGE_MODULE_SUCCESS + "001", + "Packet processing in External stage is sucessful"), + EXTERNAL_STAGE_FAILED(StatusConstants.EXTERNAL_SATGE_MODULE_SUCCESS + "001", + "Packet processing in External stage failed"), + + // CMD Validator stage + CMD_VALIDATION_SUCCESS(StatusConstants.CMD_VALIDAOR_MODULE_SUCCESS + "001", "CMD Validation is Successful"), + GPS_DETAILS_NOT_FOUND(StatusConstants.CMD_VALIDAOR_MODULE_FAILED + "001", "GPS Details are Not Found in Packet"), + CENTER_ID_NOT_FOUND(StatusConstants.CMD_VALIDAOR_MODULE_FAILED + "002", "Center ID Not Found in Master DB - "), + CENTER_ID_INACTIVE(StatusConstants.CMD_VALIDAOR_MODULE_FAILED + "003", + "Center was InActive during Packet Creation - "), + MACHINE_ID_NOT_FOUND(StatusConstants.CMD_VALIDAOR_MODULE_FAILED + "004", "Machine ID Not Found in Master DB - "), + MACHINE_ID_NOT_ACTIVE(StatusConstants.CMD_VALIDAOR_MODULE_FAILED + "005", + "Machine ID was InActive during Packet Creation - "), + CENTER_DEVICE_MAPPING_NOT_FOUND(StatusConstants.CMD_VALIDAOR_MODULE_FAILED + "006", + "Center-Device Mapping Not Found - "), + CENTER_DEVICE_MAPPING_INACTIVE(StatusConstants.CMD_VALIDAOR_MODULE_FAILED + "007", + "Center-Device Mapping was InActive during Packet Creation - "), + DEVICE_NOT_FOUND_MASTER_DB(StatusConstants.CMD_VALIDAOR_MODULE_FAILED + "008", "Device Not Found in Master DB - "), + DEVICE_VALIDATION_FAILED(StatusConstants.CMD_VALIDAOR_MODULE_FAILED + "009", "Device Validation Failed"), + PACKET_CREATION_WORKING_HOURS(StatusConstants.CMD_VALIDAOR_MODULE_FAILED + "010", + "Packet was Not Created during Working Hours - "), + REGISTRATION_CENTER_TIMESTAMP_FAILURE(StatusConstants.CMD_VALIDAOR_MODULE_FAILED + "011", + "Registration Center timestamp failed"), + FAILED_TO_GET_MACHINE_DETAIL(StatusConstants.CMD_VALIDAOR_MODULE_FAILED + "012", + "Failed to Get machine id details "), + FAILED_TO_GET_CENTER_DETAIL(StatusConstants.CMD_VALIDAOR_MODULE_FAILED + "013", "Failed to Get center id details "), + VALIDATION_FAILED_EXCEPTION(StatusConstants.CMD_VALIDAOR_MODULE_FAILED + "014", + "Exception occured due to validation failure."), + MACHINE_ID_NOT_FOUND_MASTER_DB(StatusConstants.CMD_VALIDAOR_MODULE_FAILED + "015", + "MachineId not found in master db - "), + TIMESTAMP_NOT_VALID(StatusConstants.CMD_VALIDAOR_MODULE_FAILED + "016", + "digital id timestamp is not within acctable time range of packet creation time"), + DEVICE_HOTLISTED(StatusConstants.CMD_VALIDAOR_MODULE_FAILED + "017", "Device has been hot listed"), + DEVICE_SIGNATURE_VALIDATION_FAILED(StatusConstants.CMD_VALIDAOR_MODULE_FAILED + "018", + "DigitalId signature Validation Failed"), + CMD_LANGUAGE_NOT_SET(StatusConstants.CMD_VALIDAOR_MODULE_FAILED + "019", + "Mandatory/Optional Language not set for CMD validation."), + + // Operator Validator stage + OPERATOR_VALIDATION_SUCCESS(StatusConstants.OVM_VALIDAOR_MODULE_SUCCESS + "001", + "OPERATOR Validation is Successful"), + OFFICER_NOT_ACTIVE(StatusConstants.OVM_VALIDAOR_MODULE_FAILED + "001", "OfficerId is inActive"), + OPERATOR_PACKET_CREATION_DATE_NOT_FOUND_IN_PACKET(StatusConstants.OVM_VALIDAOR_MODULE_FAILED + "002", + "Packet Creation Date is NULL"), + OPERATOR_PASSWORD_OTP_FAILURE(StatusConstants.OVM_VALIDAOR_MODULE_FAILED + "003", + "Password or OTP Verification Failed for Officer - "), + OFFICER_WAS_INACTIVE(StatusConstants.OVM_VALIDAOR_MODULE_FAILED + "004", + "Officer was Not Active during Packet Creation - "), + OFFICER_NOT_FOUND_PACKET(StatusConstants.OVM_VALIDAOR_MODULE_FAILED + "005", "Officer ID is NULL"), + + // Supervisor Validator stage + SUPERVISOR_VALIDATION_SUCCESS(StatusConstants.SVM_VALIDAOR_MODULE_SUCCESS + "001", + "SUPERVISOR Validation is Successful"), + SUPERVISOR_NOT_ACTIVE(StatusConstants.SVM_VALIDAOR_MODULE_FAILED + "001", "SupervisorId is inActive"), + SUPERVISOR_PACKET_CREATION_DATE_NOT_FOUND_IN_PACKET(StatusConstants.SVM_VALIDAOR_MODULE_FAILED + "002", + "Packet Creation Date is NULL"), + SUPERVISOR_PASSWORD_OTP_FAILURE(StatusConstants.SVM_VALIDAOR_MODULE_FAILED + "003", + "Password or OTP Verification Failed for Officer - "), + SUPERVISOR_WAS_INACTIVE(StatusConstants.SVM_VALIDAOR_MODULE_FAILED + "004", + "Supervisor was Not Active during Packet Creation - "), + PASSWORD_OTP_FAILURE_SUPERVISOR(StatusConstants.SVM_VALIDAOR_MODULE_FAILED + "005", + "Password or OTP Verification Failed for Supervisor - "), + SUPERVISOR_NOT_FOUND_PACKET(StatusConstants.OVM_VALIDAOR_MODULE_FAILED + "006", "Supervisor ID is NULL"), + + // Introducer Validator stage + INTRODUCER_VALIDATION_SUCCESS(StatusConstants.IVM_VALIDAOR_MODULE_SUCCESS + "001", + "INTRODUCER Validation is Successful"), + INTRODUCER_AUTHENTICATION_FAILED(StatusConstants.IVM_VALIDAOR_MODULE_FAILED + "001", + "INTRODUCER Biometric Authentication Failed - "), + UIN_RID_NOT_FOUND(StatusConstants.IVM_VALIDAOR_MODULE_FAILED + "002", + "UIN or RID of Introducer Not Found in Packet"), + INTRODUCER_UIN_NOT_FOUND(StatusConstants.IVM_VALIDAOR_MODULE_FAILED + "003", + "Introducer UIN not Found for the Given RID"), + INTRODUCER_BIOMETRIC_FILE_NAME_NOT_FOUND(StatusConstants.IVM_VALIDAOR_MODULE_FAILED + "004", + "Introducer Biometric File Name Not Found"), + PACKET_ON_HOLD(StatusConstants.IVM_VALIDAOR_MODULE_FAILED + "005", + "Packet On-Hold as Introducer packet is not processed yet."), + CHILD_PACKET_REJECTED(StatusConstants.IVM_VALIDAOR_MODULE_FAILED + "006", + "Packet Rejected as Parent Packet is Rejected"), + PACKET_IS_ON_HOLD(StatusConstants.IVM_VALIDAOR_MODULE_FAILED + "007", + "Packet is on Hold due to parent packet processing"), + INTRODUCER_BIOMETRIC_ALL_EXCEPTION_IN_PACKET(StatusConstants.IVM_VALIDAOR_MODULE_FAILED + "008", + "Introducer Biometrics all exceptions"), + // printing stage + PRINT_REQUEST_SUCCESS(StatusConstants.PRINT_STAGE_MODULE_SUCCESS + "001", "Print request submitted"), + PDF_ADDED_TO_QUEUE_FAILED(StatusConstants.PRINT_STAGE_MODULE_FAILED + "001", + "PDF was not added to Queue due to Queue Failure"), + PRINT_POST_COMPLETED(StatusConstants.PRINT_STAGE_MODULE_SUCCESS + "002", "Printing and Post Completed"), + RESEND_UIN_CARD(StatusConstants.PRINT_STAGE_MODULE_SUCCESS + "003", "Re-Sent UIN Card for Printing"), + PDF_GENERATION_FAILED(StatusConstants.PRINT_STAGE_MODULE_SUCCESS + "004", "Pdf Generation failed for "), + TEMPLATE_PROCESSING_FAILED(StatusConstants.PRINT_STAGE_MODULE_SUCCESS + "005", "Pdf Generation failed for "), + QUEUE_CONNECTION_NOT_FOUND(StatusConstants.PRINT_STAGE_MODULE_SUCCESS + "006", "Queue Connection not found "), + QUEUE_CONNECTION_UNAVAILABLE(StatusConstants.PRINT_STAGE_MODULE_SUCCESS + "007", + "Queue Connection unavailable for "), + PDF_SIGNTURED_FAILED(StatusConstants.PRINT_STAGE_MODULE_SUCCESS + "008", "Pdf Signature failed "), + PRINT_REQUEST_FAILED(StatusConstants.PRINT_STAGE_MODULE_FAILED + "009", "Print request failed"), + UIN_NOT_FOUND_IN_DATABASE(StatusConstants.PRINT_STAGE_MODULE_FAILED + "010", "UIN not found in database"), + /** The rpr prt vid exception. */ + VID_NOT_AVAILABLE(PlatformConstants.RPR_PRINTING_MODULE + "011", "vid not available"), + + // Abis middleware stage + INSERT_IDENTIFY_REQUEST_SUCCESS(StatusConstants.ABIS_MIDDLEWARE_MODULE_SUCCESS + "001", + "Insert or Identify Request sent to ABIS Queue is succesful"), + INSERT_IDENTIFY_REQUEST_FAILED(StatusConstants.ABIS_MIDDLEWARE_MODULE_FAILED + "001", + "Insert or Identify Request sent to ABIS Queue is Unsuccesful"), + INSERT_IDENTIFY_RESPONSE_SUCCESS(StatusConstants.ABIS_MIDDLEWARE_MODULE_SUCCESS + "002", + "Recived sucessful response from ABIS"), + INSERT_IDENTIFY_RESPONSE_FAILED(StatusConstants.ABIS_MIDDLEWARE_MODULE_SUCCESS + "002", + "Received failed response from ABIS - "), + + // System Exceptions + // Bio dedupe stage + BIO_DEDUPE_INPROGRESS(StatusConstants.BIO_DEDUPE_MODULE_SUCCESS + "001", "Biometric Deduplication In-Progress"), + BIO_DEDUPE_SUCCESS(StatusConstants.BIO_DEDUPE_MODULE_SUCCESS + "002", "Biometric Deduplication is Successful"), + BIO_DEDUPE_POTENTIAL_MATCH(StatusConstants.BIO_DEDUPE_MODULE_FAILED + "001", + "Potential Biometric Match Found while Processing Packet"), + LOST_PACKET_BIOMETRICS_NOT_FOUND(StatusConstants.BIO_DEDUPE_MODULE_FAILED + "002", + "No Match was Found for the Biometrics Received"), + LOST_PACKET_UNIQUE_MATCH_FOUND(StatusConstants.BIO_DEDUPE_MODULE_SUCCESS + "003", + "Unique Match was Found for the Biometrics Received"), + LOST_PACKET_MULTIPLE_MATCH_FOUND(StatusConstants.BIO_DEDUPE_MODULE_FAILED + "003", + "Multiple Match was Found for the Biometrics Received"), + + // Biometric authentication stage + BIOMETRIC_AUTHENTICATION_FAILED(StatusConstants.BIO_METRIC_AUTHENTICATION_MODULE_FAILED + "001", + "Biometric Authentication has Failed"), + BIOMETRIC_AUTHENTICATION_SUCCESS(StatusConstants.BIO_METRIC_AUTHENTICATION_MODULE_SUCCESS + "001", + "Biometric Authentication is Successful"), + BIOMETRIC_FILE_NOT_FOUND(StatusConstants.SYSTEM_EXCEPTION_CODE, "Biometric File Not Found"), + BIOMETRIC_AUTHENTICATION_FAILED_FILE_NOT_FOUND(StatusConstants.SYSTEM_EXCEPTION_CODE, + "Biometric Authentication Failed File is not present inside identity json"), + INDIVIDUAL_BIOMETRIC_AUTHENTICATION_FAILED(StatusConstants.BIO_METRIC_AUTHENTICATION_MODULE_FAILED + "001", + "Individual authentication failed"), + BIOMETRIC_AUTHENTICATION_SKIPPED(StatusConstants.BIO_METRIC_AUTHENTICATION_MODULE_SUCCESS + "002", + "Biometric Authentication is Skipped "), + + // Demo dedupe stage + DEMO_DEDUPE_SUCCESS(StatusConstants.DEMO_DEDUPE_MODULE_SUCCESS + "001", "Demo Dedupe is Successful"), + POTENTIAL_MATCH_FOUND_IN_ABIS(StatusConstants.DEMO_DEDUPE_MODULE_FAILED + "001", + "Biometric Duplicate was Found in ABIS"), + POTENTIAL_MATCH_FOUND(StatusConstants.DEMO_DEDUPE_MODULE_FAILED + "002", "Potential Demo Match was Found"), + DEMO_DEDUPE_SKIPPED(StatusConstants.DEMO_DEDUPE_MODULE_SKIPPED + "003", "Demographic Deduplication Skipped"), + + // Manual verification stage + MANUAL_VERIFIER_APPROVED_PACKET(StatusConstants.MANUAL_VERIFICATION_MODULE_SUCCESS + "001", + "Match Not Found by Manual Verifier"), + MANUAL_VERIFIER_REJECTED_PACKET(StatusConstants.MANUAL_VERIFICATION_MODULE_FAILED + "002", + "Match Found by Manual Verifier"), + RPR_MANUAL_VERIFICATION_RESEND(StatusConstants.MANUAL_VERIFICATION_MODULE_FAILED + "003", + "Error in manual verification"), + RPR_MANUAL_VERIFICATION_SENT_TO_QUEUE(PlatformConstants.RPR_MANUAL_ADJUDICATION_MODULE + "002", + "Manual verification request sent to queue"), + + // Uin generator stage + UIN_GENERATED_SUCCESS(StatusConstants.UIN_GENERATOR_MODULE_SUCCESS + "001", "UIN Generated Successfully"), + UIN_DATA_UPDATION_SUCCESS(StatusConstants.UIN_GENERATOR_MODULE_SUCCESS + "002", "UIN Data is drafted Successfully"), + UIN_ACTIVATED_SUCCESS(StatusConstants.UIN_GENERATOR_MODULE_SUCCESS + "003", "UIN is Activated"), + UIN_DEACTIVATION_SUCCESS(StatusConstants.UIN_GENERATOR_MODULE_SUCCESS + "004", "UIN is Deactivated"), + LINK_RID_FOR_LOST_PACKET_SUCCESS(StatusConstants.UIN_GENERATOR_MODULE_SUCCESS + "005", + "RID linked Successfully for Lost UIN Packet"), + + UIN_ALREADY_ACTIVATED(StatusConstants.UIN_GENERATOR_MODULE_FAILED + "001", "UIN is already Activated"), + UIN_ACTIVATED_FAILED(StatusConstants.UIN_GENERATOR_MODULE_FAILED + "002", "UIN Activation Failed"), + UIN_ALREADY_DEACTIVATED(StatusConstants.UIN_GENERATOR_MODULE_FAILED + "003", "UIN already deactivated"), + + UIN_GENERATION_FAILED(StatusConstants.UIN_GENERATOR_MODULE_FAILED + "004", "UIN Generation failed - "), + UIN_DATA_UPDATION_FAILED(StatusConstants.UIN_GENERATOR_MODULE_FAILED + "005", "UIN Updation failed - "), + UIN_REACTIVATION_FAILED(StatusConstants.UIN_GENERATOR_MODULE_FAILED + "006", "UIN Reactivation failed - "), + UIN_DEACTIVATION_FAILED(StatusConstants.UIN_GENERATOR_MODULE_FAILED + "007", "UIN Deactivation failed - "), + LINK_RID_FOR_LOST_PACKET_FAILED(StatusConstants.UIN_GENERATOR_MODULE_FAILED + "008", + "UIn not found the the matched RID"), + IDREPO_DRAFT_EXCEPTION(StatusConstants.UIN_GENERATOR_MODULE_FAILED + "008", + "Exception occured updating idrepo draft."), + + // Biometric extraction stage + BIOMETRIC_EXTRACTION_SUCCESS(StatusConstants.BIOMETRIC_EXTRACTION_MODULE_SUCCESS + "001", + "biometric extaction was successful"), + BIOMETRIC_EXTRACTION_DRAFT_REQUEST_UNAVAILABLE(StatusConstants.BIOMETRIC_EXTRACTION_MODULE_FAILED + "001", + "Draft request is unavaialble in id-repo draft repository."), + + FINALIZATION_SUCCESS(StatusConstants.FINALIZATION_MODULE_SUCCESS + "001", + "idrepo draft was published successfuly"), + FINALIZATION_FAILURE(StatusConstants.FINALIZATION_MODULE_FAILED + "001", "Draft request failed to publish."), + FINALIZATION_DRAFT_REQUEST_UNAVAILABLE(StatusConstants.FINALIZATION_MODULE_FAILED + "001", + "Draft request is unavaialble in id-repo draft repository."), + + // Request handler service + // 1)Resident UIN update + RESIDENT_UPDATE_SUCCES(StatusConstants.REQUEST_HANDLER_MODULE_SUCCESS + "001", + "Resident Uin data updated sucessfully"), + RESIDENT_UPDATE_FAILED(StatusConstants.REQUEST_HANDLER_MODULE_FAILED + "001", "Resident Uin update failed"), + INVALID_REQUEST(StatusConstants.REQUEST_HANDLER_MODULE_FAILED + "001", "Invalid Request Value - "), + INVALID_CENTER(StatusConstants.REQUEST_HANDLER_MODULE_FAILED + "002", "Invalid Request Value - "), + INVALID_MACHINE(StatusConstants.REQUEST_HANDLER_MODULE_FAILED + "003", "Invalid Request Value - "), + + // 2)PacketGeneration + PACKET_GENERATION_SUCCESS(StatusConstants.REQUEST_HANDLER_MODULE_SUCCESS + "001", "Packet generated sucessfully"), + PACKET_GENERATION_FAILED(StatusConstants.REQUEST_HANDLER_MODULE_FAILED + "001", "Packet generated failed"), + + // 3)Uin card reprint + UIN_CARD_REPRINT_SUCCESS(StatusConstants.REQUEST_HANDLER_MODULE_SUCCESS + "001", "UIN card reprint success"), + UIN_CARD_REPRINT_FAILED(StatusConstants.REQUEST_HANDLER_MODULE_FAILED + "001", "UIN card reprint failed"), + + // System Exceptions + VIRUS_SCANNER_SERVICE_NOT_ACCESSIBLE(StatusConstants.SYSTEM_EXCEPTION_CODE, + "Virus Scanner Service is not accessible"), + DB_NOT_ACCESSIBLE(StatusConstants.SYSTEM_EXCEPTION_CODE, "Databse Not Accessible"), + PACKET_NOT_FOUND_PACKET_STORE(StatusConstants.SYSTEM_EXCEPTION_CODE, "Packet not found in File System"), + OBJECT_STORE_EXCEPTION(StatusConstants.SYSTEM_EXCEPTION_CODE, "Object store exception occured"), + JSCH_EXCEPTION_OCCURED(StatusConstants.SYSTEM_EXCEPTION_CODE, "JSCH Connection Exception Occurred"), + NGINX_ACCESS_EXCEPTION(StatusConstants.SYSTEM_EXCEPTION_CODE, "NGINX url is not accessible"), + IO_EXCEPTION(StatusConstants.SYSTEM_EXCEPTION_CODE, "IO Exception Occurred"), + BIO_METRIC_EXCEPTION(StatusConstants.SYSTEM_EXCEPTION_CODE, "Biometric Exception Occurred in IDA "), + BIO_METRIC_FILE_MISSING(StatusConstants.SYSTEM_EXCEPTION_CODE, "Applicant biometric fileName/file is missing"), + BIO_METRIC_TYPE_EXCEPTION(StatusConstants.SYSTEM_EXCEPTION_CODE, "Requested biometric type not found"), + + UNKNOWN_EXCEPTION_OCCURED(StatusConstants.SYSTEM_EXCEPTION_CODE, "Unknown exception occured "), + API_RESOUCE_ACCESS_FAILED(StatusConstants.SYSTEM_EXCEPTION_CODE, "Unable to access API resource"), + AUTH_SYSTEM_EXCEPTION(StatusConstants.SYSTEM_EXCEPTION_CODE, "Auth System Exception"), + JSON_PARSING_EXCEPTION(StatusConstants.SYSTEM_EXCEPTION_CODE, "Error Occurred while Parsing JSON"), + BASE_CHECKED_EXCEPTION(StatusConstants.SYSTEM_EXCEPTION_CODE, "Packet validation failed "), + BASE_UNCHECKED_EXCEPTION(StatusConstants.SYSTEM_EXCEPTION_CODE, "Packet validation failed "), + + OFFICER_AUTHENTICATION_FAILED(StatusConstants.SYSTEM_EXCEPTION_CODE, "Officer Authentication Failed: "), + SUPERVISOR_AUTHENTICATION_FAILED(StatusConstants.SYSTEM_EXCEPTION_CODE, "Supervisor Authentication Failed: "), + + IDENTIFY_RESPONSE_FAILED(StatusConstants.SYSTEM_EXCEPTION_CODE, "Identify Response Failed for Request ID - "), + INSERT_RESPONSE_FAILED(StatusConstants.SYSTEM_EXCEPTION_CODE, "Insert Response Failed for Request ID - "), + SYSTEM_EXCEPTION_OCCURED(StatusConstants.SYSTEM_EXCEPTION_CODE, "Internal error occured - "), + + CBEF_NOT_FOUND(StatusConstants.SYSTEM_EXCEPTION_CODE, "Unable to Find Applicant CBEFF for Adult"), + + IIEGAL_ARGUMENT_EXCEPTION(StatusConstants.SYSTEM_EXCEPTION_CODE, "Illegal Argument Exception Occurred - "), + DEMO_DEDUPE_FAILED_IN_ABIS(StatusConstants.SYSTEM_EXCEPTION_CODE, "Demo Dedupe Failed in ABIS"), + RE_PROCESS_FAILED(StatusConstants.RE_PROCESS_MODULE_FAILED + "001", + "Reprocess count has exceeded the configured attempts"), + RE_PROCESS_COMPLETED(StatusConstants.RE_PROCESS_MODULE_SUCCESS + "001", "Reprocess Completed"), + + // Message sender stage + NOTIFICATION_SUCESSFUL(StatusConstants.MESSAGE_SENDER_NOTIF_SUCCESS_CODE + "001", "Notification Sent Successfully"), + TEMPLATE_CONFIGURATION_NOT_FOUND(StatusConstants.MESSAGE_SENDER__FAILED_CODE + "002", + "Template configuration and language not found"), + EMAIL_PHONE_TEMPLATE_NOTIFICATION_MISSING(StatusConstants.MESSAGE_SENDER__FAILED_CODE + "003", + "Email ID or Phone or Template or Notification Type is Missing"), + NOTIFICATION_FAILED_FOR_LOST(StatusConstants.MESSAGE_SENDER__FAILED_CODE + "004", + "Unable to Send Notification - UIN was not found for the Lost Packet"), + + MESSAGE_SENDER_NOTIF_SUCC(StatusConstants.MESSAGE_SENDER_NOTIF_SUCCESS_CODE + "001", + "Email and SMS Notification were sent"), + MESSAGE_SENDER_NOT_CONFIGURED(StatusConstants.MESSAGE_SENDER_NOTIF_SUCCESS_CODE + "002", + "Notification was not sent as notification type was not set"), + MESSAGE_SENDER_EMAIL_SUCCESS(StatusConstants.MESSAGE_SENDER_NOTIF_SUCCESS_CODE + "003", + "Email Notification was sent"), + MESSAGE_SENDER_SMS_SUCCESS(StatusConstants.MESSAGE_SENDER_NOTIF_SUCCESS_CODE + "004", "SMS Notification was sent"), + MESSAGE_SENDER_EMAIL_FAILED(StatusConstants.MESSAGE_SENDER__FAILED_CODE + "005", + "Notification was not sent as the required mode of channel was not available"), + MESSAGE_SENDER_SMS_FAILED(StatusConstants.MESSAGE_SENDER__FAILED_CODE + "006", + "Notification was not sent as the required mode of channel was not available"), + MESSAGE_SENDER_NOTIFICATION_FAILED(StatusConstants.MESSAGE_SENDER__FAILED_CODE + "006", + "Notification was not sent as the required mode of channel was not available"), + VID_CREATION_FAILED(StatusConstants.UIN_GENERATOR_MODULE_FAILED + "009", "VID creation failed -"), + + WORKFLOW_INTERNAL_ACTION_SUCCESS(StatusConstants.WORKFLOW_INTERNAL_ACTION + "001", + "Packet workflow internal action completed successfully"), + + WORKFLOW_INTERNAL_ACTION_REJECTED_ITERATIONS_EXCEEDED_LIMIT(StatusConstants.WORKFLOW_INTERNAL_ACTION + "002", + "Packet rejected as number of iterations exceeded permited limit."), + + WORKFLOW_ACTION_SERVICE_SUCCESS(StatusConstants.WORKFLOW_ACTION_SERVICE + "001", + "Packet workflow resume successfully"), + MANUAL_ADJUDICATION_FAILED(PlatformConstants.RPR_MANUAL_ADJUDICATION_MODULE + "000", + "manual verification failed -"), + MANUAL_ADJUDICATION_RID_SHOULD_NOT_EMPTY_OR_NULL(PlatformConstants.RPR_MANUAL_ADJUDICATION_MODULE + "001", + "Registration Id should not empty or null "), + MANUAL_ADJUDICATION_MATCHEDRID_FOUND_FOR_GIVEN_RID(PlatformConstants.RPR_MANUAL_ADJUDICATION_MODULE + "002", + "No matched reference id found for given RID"), + VERIFICATION_SUCCESS(StatusConstants.VERIFICATION_STAGE + "001", "Verification success"), + VERIFICATION_FAILED(StatusConstants.VERIFICATION_STAGE + "002", "Verification failed"), + VERIFICATION_SENT(StatusConstants.VERIFICATION_STAGE + "003", "Sent for verification"), + VERIFICATION_RESEND(StatusConstants.VERIFICATION_STAGE + "004", "Resend for verification"); + + private final String statusComment; + private final String statusCode; + + private StatusUtil(String statusCode, String statusComment) { + this.statusCode = statusCode; + this.statusComment = statusComment; + } + + public String getMessage() { + return this.statusComment; + } + + /** + * Gets the error code. + * + * @return the error code + */ + public String getCode() { + return this.statusCode; + } + } \ No newline at end of file diff --git a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/util/RegistrationExceptionMapperUtil.java b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/util/RegistrationExceptionMapperUtil.java index 2b0ef62f0b0..88d926adb88 100644 --- a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/util/RegistrationExceptionMapperUtil.java +++ b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/util/RegistrationExceptionMapperUtil.java @@ -1,213 +1,215 @@ -package io.mosip.registration.processor.core.util; - -import java.util.Collections; -import java.util.EnumMap; -import java.util.Map; - -import io.mosip.registration.processor.core.code.RegistrationExceptionTypeCode; -import io.mosip.registration.processor.core.code.RegistrationTransactionStatusCode; - -/** - * The Class RegistrationExceptionMapperUtil. - */ -public class RegistrationExceptionMapperUtil { - /** - * The status map. - */ - private static EnumMap statusMap = new EnumMap<>( - RegistrationExceptionTypeCode.class); - - /** - * The unmodifiable map. - */ - private static Map unmodifiableMap = Collections - .unmodifiableMap(statusMap); - - /** - * Instantiates a new registration exception mapper util. - */ - public RegistrationExceptionMapperUtil() { - super(); - } - - /** - * Status mapper. - * - * @return the map - */ - private static Map statusMapper() { - - statusMap.put(RegistrationExceptionTypeCode.REG_STATUS_VALIDATION_EXCEPTION, - RegistrationTransactionStatusCode.FAILED); - - statusMap.put(RegistrationExceptionTypeCode.IOEXCEPTION, RegistrationTransactionStatusCode.ERROR); - statusMap.put(RegistrationExceptionTypeCode.VALIDATION_FAILED_EXCEPTION, RegistrationTransactionStatusCode.FAILED); - statusMap.put(RegistrationExceptionTypeCode.VIRUS_SCAN_FAILED_EXCEPTION, - RegistrationTransactionStatusCode.FAILED); - statusMap.put(RegistrationExceptionTypeCode.VIRUS_SCANNER_SERVICE_FAILED, - RegistrationTransactionStatusCode.FAILED); - statusMap.put(RegistrationExceptionTypeCode.PACKET_DECRYPTION_FAILURE_EXCEPTION, - RegistrationTransactionStatusCode.ERROR); - statusMap.put(RegistrationExceptionTypeCode.PACKET_HASH_VALIDATION_FAILED, - RegistrationTransactionStatusCode.ERROR); - statusMap.put(RegistrationExceptionTypeCode.PACKET_MANAGER_EXCEPTION, - RegistrationTransactionStatusCode.REPROCESS); - statusMap.put(RegistrationExceptionTypeCode.EXCEPTION, RegistrationTransactionStatusCode.ERROR); - statusMap.put(RegistrationExceptionTypeCode.DUPLICATE_UPLOAD_REQUEST_EXCEPTION, - RegistrationTransactionStatusCode.ERROR); - statusMap.put(RegistrationExceptionTypeCode.INVALID_KEY_SPEC_EXCEPTION, - RegistrationTransactionStatusCode.ERROR); - statusMap.put(RegistrationExceptionTypeCode.INVALID_ID_EXCEPTION, RegistrationTransactionStatusCode.ERROR); - statusMap.put(RegistrationExceptionTypeCode.ILLEGAL_ARGUMENT_EXCEPTION, - RegistrationTransactionStatusCode.ERROR); - statusMap.put(RegistrationExceptionTypeCode.INSTANTIATION_EXCEPTION, RegistrationTransactionStatusCode.ERROR); - statusMap.put(RegistrationExceptionTypeCode.ILLEGAL_ACCESS_EXCEPTION, RegistrationTransactionStatusCode.ERROR); - statusMap.put(RegistrationExceptionTypeCode.NO_SUCH_FIELD_EXCEPTION, RegistrationTransactionStatusCode.ERROR); - statusMap.put(RegistrationExceptionTypeCode.SECURITY_EXCEPTION, RegistrationTransactionStatusCode.ERROR); - statusMap.put(RegistrationExceptionTypeCode.JSON_PARSE_EXCEPTION, RegistrationTransactionStatusCode.ERROR); - statusMap.put(RegistrationExceptionTypeCode.PACKET_CMD_VALIDATION_FAILED, - RegistrationTransactionStatusCode.ERROR); - statusMap.put(RegistrationExceptionTypeCode.JSON_MAPPING_EXCEPTION, RegistrationTransactionStatusCode.ERROR); - statusMap.put(RegistrationExceptionTypeCode.JSON_PROCESSING_EXCEPTION, RegistrationTransactionStatusCode.ERROR); - statusMap.put(RegistrationExceptionTypeCode.JSON_IO_EXCEPTION, RegistrationTransactionStatusCode.ERROR); - statusMap.put(RegistrationExceptionTypeCode.JSON_SCHEMA_IO_EXCEPTION, RegistrationTransactionStatusCode.ERROR); - statusMap.put(RegistrationExceptionTypeCode.FILE_IO_EXCEPTION, RegistrationTransactionStatusCode.ERROR); - statusMap.put(RegistrationExceptionTypeCode.FILE_NOT_FOUND_EXCEPTION, RegistrationTransactionStatusCode.ERROR); - statusMap.put(RegistrationExceptionTypeCode.NO_SUCH_ALGORITHM_EXCEPTION, - RegistrationTransactionStatusCode.ERROR); - statusMap.put(RegistrationExceptionTypeCode.MOSIP_INVALID_DATA_EXCEPTION, - RegistrationTransactionStatusCode.ERROR); - statusMap.put(RegistrationExceptionTypeCode.MOSIP_INVALID_KEY_EXCEPTION, - RegistrationTransactionStatusCode.ERROR); - statusMap.put(RegistrationExceptionTypeCode.IDENTITY_NOT_FOUND_EXCEPTION, - RegistrationTransactionStatusCode.ERROR); - statusMap.put(RegistrationExceptionTypeCode.FILE_NOT_FOUND_IN_DESTINATION_EXCEPTION, - RegistrationTransactionStatusCode.ERROR); - statusMap.put(RegistrationExceptionTypeCode.PARSE_EXCEPTION, RegistrationTransactionStatusCode.ERROR); - statusMap.put(RegistrationExceptionTypeCode.UNSUPPORTED_ENCODING_EXCEPTION, - RegistrationTransactionStatusCode.ERROR); - statusMap.put(RegistrationExceptionTypeCode.CLASS_NOT_FOUND_EXCEPTION, RegistrationTransactionStatusCode.ERROR); - - statusMap.put(RegistrationExceptionTypeCode.INVOCATION_TARGET_EXCEPTION, - RegistrationTransactionStatusCode.ERROR); - statusMap.put(RegistrationExceptionTypeCode.INTROSPECTION_EXCEPTION, RegistrationTransactionStatusCode.ERROR); - - statusMap.put(RegistrationExceptionTypeCode.TABLE_NOT_ACCESSIBLE_EXCEPTION, - RegistrationTransactionStatusCode.REPROCESS); - statusMap.put(RegistrationExceptionTypeCode.NO_RECORDS_ASSIGNED, - RegistrationTransactionStatusCode.FAILED); - statusMap.put(RegistrationExceptionTypeCode.INTERNAL_SERVER_ERROR, RegistrationTransactionStatusCode.REPROCESS); - statusMap.put(RegistrationExceptionTypeCode.PACKET_NOT_FOUND_EXCEPTION, - RegistrationTransactionStatusCode.ERROR); - statusMap.put(RegistrationExceptionTypeCode.DATA_ACCESS_EXCEPTION, RegistrationTransactionStatusCode.REPROCESS); - statusMap.put(RegistrationExceptionTypeCode.DATA_ACCESS_LAYER_EXCEPTION, - RegistrationTransactionStatusCode.REPROCESS); - statusMap.put(RegistrationExceptionTypeCode.OBJECT_STORE_EXCEPTION, - RegistrationTransactionStatusCode.REPROCESS); - statusMap.put(RegistrationExceptionTypeCode.INTERRUPTED_EXCEPTION, RegistrationTransactionStatusCode.REPROCESS); - statusMap.put(RegistrationExceptionTypeCode.EXECUTION_EXCEPTION, RegistrationTransactionStatusCode.REPROCESS); - statusMap.put(RegistrationExceptionTypeCode.UNKNOWN_HOST_EXCEPTION, - RegistrationTransactionStatusCode.REPROCESS); - statusMap.put(RegistrationExceptionTypeCode.APIS_RESOURCE_ACCESS_EXCEPTION, - RegistrationTransactionStatusCode.REPROCESS); - statusMap.put(RegistrationExceptionTypeCode.QUEUE_CONNECTION_NOT_FOUND, - RegistrationTransactionStatusCode.REPROCESS); - statusMap.put(RegistrationExceptionTypeCode.CONNECTION_UNAVAILABLE_EXCEPTION, - RegistrationTransactionStatusCode.REPROCESS); - statusMap.put(RegistrationExceptionTypeCode.RUN_TIME_EXCEPTION, RegistrationTransactionStatusCode.REPROCESS); - statusMap.put(RegistrationExceptionTypeCode.CONFIGURATION_NOT_FOUND_EXCEPTION, - RegistrationTransactionStatusCode.REPROCESS); - statusMap.put(RegistrationExceptionTypeCode.UNEXCEPTED_ERROR, RegistrationTransactionStatusCode.REPROCESS); - statusMap.put(RegistrationExceptionTypeCode.NGINX_ACCESS_EXCEPTION, - RegistrationTransactionStatusCode.REPROCESS); - statusMap.put(RegistrationExceptionTypeCode.PACKET_OSI_VALIDATION_FAILED, - RegistrationTransactionStatusCode.FAILED); - statusMap.put(RegistrationExceptionTypeCode.PACKET_STRUCTURAL_VALIDATION_FAILED, - RegistrationTransactionStatusCode.FAILED); - statusMap.put(RegistrationExceptionTypeCode.PACKET_UPLOADER_FAILED, RegistrationTransactionStatusCode.FAILED); - statusMap.put(RegistrationExceptionTypeCode.PACKET_UIN_GENERATION_FAILED, - RegistrationTransactionStatusCode.FAILED); - statusMap.put(RegistrationExceptionTypeCode.PACKET_UIN_GENERATION_REPROCESS, - RegistrationTransactionStatusCode.REPROCESS); - statusMap.put(RegistrationExceptionTypeCode.BIOMETRIC_EXTRACTION_REPROCESS, - RegistrationTransactionStatusCode.REPROCESS); - statusMap.put(RegistrationExceptionTypeCode.BIOMETRIC_EXTRACTION_FAILED, - RegistrationTransactionStatusCode.FAILED); - statusMap.put(RegistrationExceptionTypeCode.DRAFT_REQUEST_UNAVAILABLE, - RegistrationTransactionStatusCode.FAILED); - statusMap.put(RegistrationExceptionTypeCode.BASE_UNCHECKED_EXCEPTION, RegistrationTransactionStatusCode.ERROR); - statusMap.put(RegistrationExceptionTypeCode.BASE_CHECKED_EXCEPTION, RegistrationTransactionStatusCode.ERROR); - statusMap.put(RegistrationExceptionTypeCode.EXTERNAL_INTEGRATION_FAILED, - RegistrationTransactionStatusCode.FAILED); - - statusMap.put(RegistrationExceptionTypeCode.CBEFF_NOT_PRESENT_EXCEPTION, - RegistrationTransactionStatusCode.FAILED); - statusMap.put(RegistrationExceptionTypeCode.DEMO_DEDUPE_ABIS_RESPONSE_ERROR, - RegistrationTransactionStatusCode.REPROCESS); - statusMap.put(RegistrationExceptionTypeCode.ON_HOLD_INTRODUCER_PACKET, - RegistrationTransactionStatusCode.REPROCESS); - statusMap.put(RegistrationExceptionTypeCode.INTRODUCER_UIN_AND_RID_NOT_IN_PACKET, - RegistrationTransactionStatusCode.FAILED); - statusMap.put(RegistrationExceptionTypeCode.INTRODUCER_UIN_NOT_AVAIALBLE, - RegistrationTransactionStatusCode.FAILED); - statusMap.put(RegistrationExceptionTypeCode.OSI_FAILED_REJECTED_INTRODUCER, - RegistrationTransactionStatusCode.FAILED); - statusMap.put(RegistrationExceptionTypeCode.SUPERVISORID_AND_OFFICERID_NOT_PRESENT_IN_PACKET, - RegistrationTransactionStatusCode.FAILED); - statusMap.put(RegistrationExceptionTypeCode.OFFICERID_NOT_PRESENT_IN_PACKET, - RegistrationTransactionStatusCode.FAILED); - statusMap.put(RegistrationExceptionTypeCode.SUPERVISORID_NOT_PRESENT_IN_PACKET, - RegistrationTransactionStatusCode.FAILED); - statusMap.put(RegistrationExceptionTypeCode.PACKET_UPLOAD_FAILED_ON_MAX_RETRY_CNT, - RegistrationTransactionStatusCode.FAILED); - statusMap.put(RegistrationExceptionTypeCode.PACKET_CREATION_DATE_NOT_PRESENT_IN_PACKET, - RegistrationTransactionStatusCode.FAILED); - statusMap.put(RegistrationExceptionTypeCode.SUPERVISOR_OR_OFFICER_WAS_INACTIVE, - RegistrationTransactionStatusCode.FAILED); - statusMap.put(RegistrationExceptionTypeCode.OFFICER_WAS_INACTIVE, RegistrationTransactionStatusCode.FAILED); - statusMap.put(RegistrationExceptionTypeCode.SUPERVISOR_WAS_INACTIVE, RegistrationTransactionStatusCode.FAILED); - statusMap.put(RegistrationExceptionTypeCode.INTRODUCER_BIOMETRIC_NOT_IN_PACKET, - RegistrationTransactionStatusCode.FAILED); - statusMap.put(RegistrationExceptionTypeCode.OFFICER_BIOMETRIC_NOT_IN_PACKET, - RegistrationTransactionStatusCode.FAILED); - statusMap.put(RegistrationExceptionTypeCode.SUPERVISOR_BIOMETRIC_NOT_IN_PACKET, - RegistrationTransactionStatusCode.FAILED); - statusMap.put(RegistrationExceptionTypeCode.FINALIZATION_FAILED, - RegistrationTransactionStatusCode.FAILED); - statusMap.put(RegistrationExceptionTypeCode.IDREPO_DRAFT_EXCEPTION, - RegistrationTransactionStatusCode.FAILED); - statusMap.put(RegistrationExceptionTypeCode.FINALIZATION_REPROCESS, - RegistrationTransactionStatusCode.REPROCESS); - statusMap.put(RegistrationExceptionTypeCode.AUTH_ERROR, RegistrationTransactionStatusCode.FAILED); - statusMap.put(RegistrationExceptionTypeCode.AUTH_FAILED, RegistrationTransactionStatusCode.FAILED); - statusMap.put(RegistrationExceptionTypeCode.IDA_AUTHENTICATION_FAILURE, - RegistrationTransactionStatusCode.FAILED); - statusMap.put(RegistrationExceptionTypeCode.OPERATOR_PASSWORD_OTP_FAILURE, RegistrationTransactionStatusCode.FAILED); - statusMap.put(RegistrationExceptionTypeCode.SUPERVISOR_PASSWORD_OTP_FAILURE, RegistrationTransactionStatusCode.FAILED); - statusMap.put(RegistrationExceptionTypeCode.BIOMETRIC_EXCEPTION, RegistrationTransactionStatusCode.REPROCESS); - statusMap.put(RegistrationExceptionTypeCode.PACKET_UIN_GENERATION_ID_REPO_ERROR, - RegistrationTransactionStatusCode.REPROCESS); - statusMap.put(RegistrationExceptionTypeCode.BIOMETRIC_TYPE_EXCEPTION, - RegistrationTransactionStatusCode.REPROCESS); - statusMap.put(RegistrationExceptionTypeCode.AUTH_SYSTEM_EXCEPTION, RegistrationTransactionStatusCode.REPROCESS); - statusMap.put(RegistrationExceptionTypeCode.VID_CREATION_EXCEPTION, - RegistrationTransactionStatusCode.REPROCESS); - statusMap.put(RegistrationExceptionTypeCode.PACKET_REJECTED, RegistrationTransactionStatusCode.REJECTED); - - return unmodifiableMap; - - } - - /** - * Gets the status code. - * - * @param exceptionCode the exception code - * @return the status code - */ - public String getStatusCode(RegistrationExceptionTypeCode exceptionCode) { - Map mapStatus = RegistrationExceptionMapperUtil - .statusMapper(); - - return mapStatus.get(RegistrationExceptionTypeCode.valueOf(exceptionCode.toString())).toString(); - } +package io.mosip.registration.processor.core.util; + +import java.util.Collections; +import java.util.EnumMap; +import java.util.Map; + +import io.mosip.registration.processor.core.code.RegistrationExceptionTypeCode; +import io.mosip.registration.processor.core.code.RegistrationTransactionStatusCode; + +/** + * The Class RegistrationExceptionMapperUtil. + */ +public class RegistrationExceptionMapperUtil { + /** + * The status map. + */ + private static EnumMap statusMap = new EnumMap<>( + RegistrationExceptionTypeCode.class); + + /** + * The unmodifiable map. + */ + private static Map unmodifiableMap = Collections + .unmodifiableMap(statusMap); + + /** + * Instantiates a new registration exception mapper util. + */ + public RegistrationExceptionMapperUtil() { + super(); + } + + /** + * Status mapper. + * + * @return the map + */ + private static Map statusMapper() { + + statusMap.put(RegistrationExceptionTypeCode.REG_STATUS_VALIDATION_EXCEPTION, + RegistrationTransactionStatusCode.FAILED); + + statusMap.put(RegistrationExceptionTypeCode.IOEXCEPTION, RegistrationTransactionStatusCode.ERROR); + statusMap.put(RegistrationExceptionTypeCode.VALIDATION_FAILED_EXCEPTION, RegistrationTransactionStatusCode.FAILED); + statusMap.put(RegistrationExceptionTypeCode.VIRUS_SCAN_FAILED_EXCEPTION, + RegistrationTransactionStatusCode.FAILED); + statusMap.put(RegistrationExceptionTypeCode.VIRUS_SCANNER_SERVICE_FAILED, + RegistrationTransactionStatusCode.FAILED); + statusMap.put(RegistrationExceptionTypeCode.PACKET_DECRYPTION_FAILURE_EXCEPTION, + RegistrationTransactionStatusCode.ERROR); + statusMap.put(RegistrationExceptionTypeCode.PACKET_HASH_VALIDATION_FAILED, + RegistrationTransactionStatusCode.ERROR); + statusMap.put(RegistrationExceptionTypeCode.PACKET_MANAGER_EXCEPTION, + RegistrationTransactionStatusCode.REPROCESS); + statusMap.put(RegistrationExceptionTypeCode.EXCEPTION, RegistrationTransactionStatusCode.ERROR); + statusMap.put(RegistrationExceptionTypeCode.DUPLICATE_UPLOAD_REQUEST_EXCEPTION, + RegistrationTransactionStatusCode.ERROR); + statusMap.put(RegistrationExceptionTypeCode.INVALID_KEY_SPEC_EXCEPTION, + RegistrationTransactionStatusCode.ERROR); + statusMap.put(RegistrationExceptionTypeCode.INVALID_ID_EXCEPTION, RegistrationTransactionStatusCode.ERROR); + statusMap.put(RegistrationExceptionTypeCode.ILLEGAL_ARGUMENT_EXCEPTION, + RegistrationTransactionStatusCode.ERROR); + statusMap.put(RegistrationExceptionTypeCode.INSTANTIATION_EXCEPTION, RegistrationTransactionStatusCode.ERROR); + statusMap.put(RegistrationExceptionTypeCode.ILLEGAL_ACCESS_EXCEPTION, RegistrationTransactionStatusCode.ERROR); + statusMap.put(RegistrationExceptionTypeCode.NO_SUCH_FIELD_EXCEPTION, RegistrationTransactionStatusCode.ERROR); + statusMap.put(RegistrationExceptionTypeCode.SECURITY_EXCEPTION, RegistrationTransactionStatusCode.ERROR); + statusMap.put(RegistrationExceptionTypeCode.JSON_PARSE_EXCEPTION, RegistrationTransactionStatusCode.ERROR); + statusMap.put(RegistrationExceptionTypeCode.PACKET_CMD_VALIDATION_FAILED, + RegistrationTransactionStatusCode.ERROR); + statusMap.put(RegistrationExceptionTypeCode.JSON_MAPPING_EXCEPTION, RegistrationTransactionStatusCode.ERROR); + statusMap.put(RegistrationExceptionTypeCode.JSON_PROCESSING_EXCEPTION, RegistrationTransactionStatusCode.ERROR); + statusMap.put(RegistrationExceptionTypeCode.JSON_IO_EXCEPTION, RegistrationTransactionStatusCode.ERROR); + statusMap.put(RegistrationExceptionTypeCode.JSON_SCHEMA_IO_EXCEPTION, RegistrationTransactionStatusCode.ERROR); + statusMap.put(RegistrationExceptionTypeCode.FILE_IO_EXCEPTION, RegistrationTransactionStatusCode.ERROR); + statusMap.put(RegistrationExceptionTypeCode.FILE_NOT_FOUND_EXCEPTION, RegistrationTransactionStatusCode.ERROR); + statusMap.put(RegistrationExceptionTypeCode.NO_SUCH_ALGORITHM_EXCEPTION, + RegistrationTransactionStatusCode.ERROR); + statusMap.put(RegistrationExceptionTypeCode.MOSIP_INVALID_DATA_EXCEPTION, + RegistrationTransactionStatusCode.ERROR); + statusMap.put(RegistrationExceptionTypeCode.MOSIP_INVALID_KEY_EXCEPTION, + RegistrationTransactionStatusCode.ERROR); + statusMap.put(RegistrationExceptionTypeCode.IDENTITY_NOT_FOUND_EXCEPTION, + RegistrationTransactionStatusCode.ERROR); + statusMap.put(RegistrationExceptionTypeCode.FILE_NOT_FOUND_IN_DESTINATION_EXCEPTION, + RegistrationTransactionStatusCode.ERROR); + statusMap.put(RegistrationExceptionTypeCode.PARSE_EXCEPTION, RegistrationTransactionStatusCode.ERROR); + statusMap.put(RegistrationExceptionTypeCode.UNSUPPORTED_ENCODING_EXCEPTION, + RegistrationTransactionStatusCode.ERROR); + statusMap.put(RegistrationExceptionTypeCode.CLASS_NOT_FOUND_EXCEPTION, RegistrationTransactionStatusCode.ERROR); + + statusMap.put(RegistrationExceptionTypeCode.INVOCATION_TARGET_EXCEPTION, + RegistrationTransactionStatusCode.ERROR); + statusMap.put(RegistrationExceptionTypeCode.INTROSPECTION_EXCEPTION, RegistrationTransactionStatusCode.ERROR); + + statusMap.put(RegistrationExceptionTypeCode.TABLE_NOT_ACCESSIBLE_EXCEPTION, + RegistrationTransactionStatusCode.REPROCESS); + statusMap.put(RegistrationExceptionTypeCode.NO_RECORDS_ASSIGNED, + RegistrationTransactionStatusCode.FAILED); + statusMap.put(RegistrationExceptionTypeCode.INTERNAL_SERVER_ERROR, RegistrationTransactionStatusCode.REPROCESS); + statusMap.put(RegistrationExceptionTypeCode.PACKET_NOT_FOUND_EXCEPTION, + RegistrationTransactionStatusCode.ERROR); + statusMap.put(RegistrationExceptionTypeCode.DATA_ACCESS_EXCEPTION, RegistrationTransactionStatusCode.REPROCESS); + statusMap.put(RegistrationExceptionTypeCode.DATA_ACCESS_LAYER_EXCEPTION, + RegistrationTransactionStatusCode.REPROCESS); + statusMap.put(RegistrationExceptionTypeCode.OBJECT_STORE_EXCEPTION, + RegistrationTransactionStatusCode.REPROCESS); + statusMap.put(RegistrationExceptionTypeCode.INTERRUPTED_EXCEPTION, RegistrationTransactionStatusCode.REPROCESS); + statusMap.put(RegistrationExceptionTypeCode.EXECUTION_EXCEPTION, RegistrationTransactionStatusCode.REPROCESS); + statusMap.put(RegistrationExceptionTypeCode.UNKNOWN_HOST_EXCEPTION, + RegistrationTransactionStatusCode.REPROCESS); + statusMap.put(RegistrationExceptionTypeCode.APIS_RESOURCE_ACCESS_EXCEPTION, + RegistrationTransactionStatusCode.REPROCESS); + statusMap.put(RegistrationExceptionTypeCode.QUEUE_CONNECTION_NOT_FOUND, + RegistrationTransactionStatusCode.REPROCESS); + statusMap.put(RegistrationExceptionTypeCode.CONNECTION_UNAVAILABLE_EXCEPTION, + RegistrationTransactionStatusCode.REPROCESS); + statusMap.put(RegistrationExceptionTypeCode.RUN_TIME_EXCEPTION, RegistrationTransactionStatusCode.REPROCESS); + statusMap.put(RegistrationExceptionTypeCode.CONFIGURATION_NOT_FOUND_EXCEPTION, + RegistrationTransactionStatusCode.REPROCESS); + statusMap.put(RegistrationExceptionTypeCode.UNEXCEPTED_ERROR, RegistrationTransactionStatusCode.REPROCESS); + statusMap.put(RegistrationExceptionTypeCode.NGINX_ACCESS_EXCEPTION, + RegistrationTransactionStatusCode.REPROCESS); + statusMap.put(RegistrationExceptionTypeCode.PACKET_OSI_VALIDATION_FAILED, + RegistrationTransactionStatusCode.FAILED); + statusMap.put(RegistrationExceptionTypeCode.PACKET_STRUCTURAL_VALIDATION_FAILED, + RegistrationTransactionStatusCode.FAILED); + statusMap.put(RegistrationExceptionTypeCode.PACKET_UPLOADER_FAILED, RegistrationTransactionStatusCode.FAILED); + statusMap.put(RegistrationExceptionTypeCode.PACKET_UIN_GENERATION_FAILED, + RegistrationTransactionStatusCode.FAILED); + statusMap.put(RegistrationExceptionTypeCode.PACKET_UIN_GENERATION_REPROCESS, + RegistrationTransactionStatusCode.REPROCESS); + statusMap.put(RegistrationExceptionTypeCode.BIOMETRIC_EXTRACTION_REPROCESS, + RegistrationTransactionStatusCode.REPROCESS); + statusMap.put(RegistrationExceptionTypeCode.BIOMETRIC_EXTRACTION_FAILED, + RegistrationTransactionStatusCode.FAILED); + statusMap.put(RegistrationExceptionTypeCode.DRAFT_REQUEST_UNAVAILABLE, + RegistrationTransactionStatusCode.FAILED); + statusMap.put(RegistrationExceptionTypeCode.BASE_UNCHECKED_EXCEPTION, RegistrationTransactionStatusCode.ERROR); + statusMap.put(RegistrationExceptionTypeCode.BASE_CHECKED_EXCEPTION, RegistrationTransactionStatusCode.ERROR); + statusMap.put(RegistrationExceptionTypeCode.EXTERNAL_INTEGRATION_FAILED, + RegistrationTransactionStatusCode.FAILED); + + statusMap.put(RegistrationExceptionTypeCode.CBEFF_NOT_PRESENT_EXCEPTION, + RegistrationTransactionStatusCode.FAILED); + statusMap.put(RegistrationExceptionTypeCode.DEMO_DEDUPE_ABIS_RESPONSE_ERROR, + RegistrationTransactionStatusCode.REPROCESS); + statusMap.put(RegistrationExceptionTypeCode.ON_HOLD_INTRODUCER_PACKET, + RegistrationTransactionStatusCode.REPROCESS); + statusMap.put(RegistrationExceptionTypeCode.INTRODUCER_UIN_AND_RID_NOT_IN_PACKET, + RegistrationTransactionStatusCode.FAILED); + statusMap.put(RegistrationExceptionTypeCode.INTRODUCER_UIN_NOT_AVAIALBLE, + RegistrationTransactionStatusCode.FAILED); + statusMap.put(RegistrationExceptionTypeCode.OSI_FAILED_REJECTED_INTRODUCER, + RegistrationTransactionStatusCode.FAILED); + statusMap.put(RegistrationExceptionTypeCode.SUPERVISORID_AND_OFFICERID_NOT_PRESENT_IN_PACKET, + RegistrationTransactionStatusCode.FAILED); + statusMap.put(RegistrationExceptionTypeCode.OFFICERID_NOT_PRESENT_IN_PACKET, + RegistrationTransactionStatusCode.FAILED); + statusMap.put(RegistrationExceptionTypeCode.SUPERVISORID_NOT_PRESENT_IN_PACKET, + RegistrationTransactionStatusCode.FAILED); + statusMap.put(RegistrationExceptionTypeCode.PACKET_UPLOAD_FAILED_ON_MAX_RETRY_CNT, + RegistrationTransactionStatusCode.FAILED); + statusMap.put(RegistrationExceptionTypeCode.PACKET_CREATION_DATE_NOT_PRESENT_IN_PACKET, + RegistrationTransactionStatusCode.FAILED); + statusMap.put(RegistrationExceptionTypeCode.SUPERVISOR_OR_OFFICER_WAS_INACTIVE, + RegistrationTransactionStatusCode.FAILED); + statusMap.put(RegistrationExceptionTypeCode.OFFICER_WAS_INACTIVE, RegistrationTransactionStatusCode.FAILED); + statusMap.put(RegistrationExceptionTypeCode.SUPERVISOR_WAS_INACTIVE, RegistrationTransactionStatusCode.FAILED); + statusMap.put(RegistrationExceptionTypeCode.INTRODUCER_BIOMETRIC_NOT_IN_PACKET, + RegistrationTransactionStatusCode.FAILED); + statusMap.put(RegistrationExceptionTypeCode.OFFICER_BIOMETRIC_NOT_IN_PACKET, + RegistrationTransactionStatusCode.FAILED); + statusMap.put(RegistrationExceptionTypeCode.SUPERVISOR_BIOMETRIC_NOT_IN_PACKET, + RegistrationTransactionStatusCode.FAILED); + statusMap.put(RegistrationExceptionTypeCode.FINALIZATION_FAILED, + RegistrationTransactionStatusCode.FAILED); + statusMap.put(RegistrationExceptionTypeCode.IDREPO_DRAFT_EXCEPTION, + RegistrationTransactionStatusCode.FAILED); + statusMap.put(RegistrationExceptionTypeCode.FINALIZATION_REPROCESS, + RegistrationTransactionStatusCode.REPROCESS); + statusMap.put(RegistrationExceptionTypeCode.AUTH_ERROR, RegistrationTransactionStatusCode.FAILED); + statusMap.put(RegistrationExceptionTypeCode.AUTH_FAILED, RegistrationTransactionStatusCode.FAILED); + statusMap.put(RegistrationExceptionTypeCode.IDA_AUTHENTICATION_FAILURE, + RegistrationTransactionStatusCode.FAILED); + statusMap.put(RegistrationExceptionTypeCode.OPERATOR_PASSWORD_OTP_FAILURE, RegistrationTransactionStatusCode.FAILED); + statusMap.put(RegistrationExceptionTypeCode.SUPERVISOR_PASSWORD_OTP_FAILURE, RegistrationTransactionStatusCode.FAILED); + statusMap.put(RegistrationExceptionTypeCode.BIOMETRIC_EXCEPTION, RegistrationTransactionStatusCode.REPROCESS); + statusMap.put(RegistrationExceptionTypeCode.PACKET_UIN_GENERATION_ID_REPO_ERROR, + RegistrationTransactionStatusCode.REPROCESS); + statusMap.put(RegistrationExceptionTypeCode.BIOMETRIC_TYPE_EXCEPTION, + RegistrationTransactionStatusCode.REPROCESS); + statusMap.put(RegistrationExceptionTypeCode.AUTH_SYSTEM_EXCEPTION, RegistrationTransactionStatusCode.REPROCESS); + statusMap.put(RegistrationExceptionTypeCode.VID_CREATION_EXCEPTION, + RegistrationTransactionStatusCode.REPROCESS); + statusMap.put(RegistrationExceptionTypeCode.PACKET_REJECTED, RegistrationTransactionStatusCode.REJECTED); + statusMap.put(RegistrationExceptionTypeCode.INTRODUCER_BIOMETRIC_ALL_EXCEPTION_IN_PACKET, + RegistrationTransactionStatusCode.FAILED); + + return unmodifiableMap; + + } + + /** + * Gets the status code. + * + * @param exceptionCode the exception code + * @return the status code + */ + public String getStatusCode(RegistrationExceptionTypeCode exceptionCode) { + Map mapStatus = RegistrationExceptionMapperUtil + .statusMapper(); + + return mapStatus.get(RegistrationExceptionTypeCode.valueOf(exceptionCode.toString())).toString(); + } } \ No newline at end of file From 0b5264003ef6888e8063a3c23f5b38e714993b9e Mon Sep 17 00:00:00 2001 From: Khuddus shariff Date: Thu, 6 Jul 2023 16:06:54 +0530 Subject: [PATCH 084/133] DDl files removed --- .../ddl/regprc-additional_info_request.sql | 27 --------------- .../ddl/regprc-anonymous_profile.sql | 29 ---------------- .../mosip_regprc/ddl/regprc-crypto_salt.sql | 25 -------------- .../ddl/regprc-reg_verification.sql | 33 ------------------- 4 files changed, 114 deletions(-) delete mode 100644 db_upgrade_scripts/mosip_regprc/ddl/regprc-additional_info_request.sql delete mode 100644 db_upgrade_scripts/mosip_regprc/ddl/regprc-anonymous_profile.sql delete mode 100644 db_upgrade_scripts/mosip_regprc/ddl/regprc-crypto_salt.sql delete mode 100644 db_upgrade_scripts/mosip_regprc/ddl/regprc-reg_verification.sql diff --git a/db_upgrade_scripts/mosip_regprc/ddl/regprc-additional_info_request.sql b/db_upgrade_scripts/mosip_regprc/ddl/regprc-additional_info_request.sql deleted file mode 100644 index 4e468a7216c..00000000000 --- a/db_upgrade_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_upgrade_scripts/mosip_regprc/ddl/regprc-anonymous_profile.sql b/db_upgrade_scripts/mosip_regprc/ddl/regprc-anonymous_profile.sql deleted file mode 100644 index 820eff5fe5a..00000000000 --- a/db_upgrade_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_upgrade_scripts/mosip_regprc/ddl/regprc-crypto_salt.sql b/db_upgrade_scripts/mosip_regprc/ddl/regprc-crypto_salt.sql deleted file mode 100644 index 0aceabc96cc..00000000000 --- a/db_upgrade_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_upgrade_scripts/mosip_regprc/ddl/regprc-reg_verification.sql b/db_upgrade_scripts/mosip_regprc/ddl/regprc-reg_verification.sql deleted file mode 100644 index 7d0193fdb12..00000000000 --- a/db_upgrade_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 From c3008db348ed30b62338a1cfb2f02c10fe508274 Mon Sep 17 00:00:00 2001 From: Sowmya Ujjappa Banakar Date: Fri, 7 Jul 2023 12:32:41 +0530 Subject: [PATCH 085/133] MOSIP-28305 Code changes to revert digital card changes --- .../processor/print/stage/PrintingStage.java | 924 +++++++++--------- .../src/main/resources/bootstrap.properties | 8 +- .../print/stage/test/PrintingStageTest.java | 8 +- .../processor/core/code/ApiName.java | 405 ++++---- 4 files changed, 652 insertions(+), 693 deletions(-) diff --git a/registration-processor/post-processor/registration-processor-printing-stage/src/main/java/io/mosip/registration/processor/print/stage/PrintingStage.java b/registration-processor/post-processor/registration-processor-printing-stage/src/main/java/io/mosip/registration/processor/print/stage/PrintingStage.java index 086178dff69..c46df5eec54 100644 --- a/registration-processor/post-processor/registration-processor-printing-stage/src/main/java/io/mosip/registration/processor/print/stage/PrintingStage.java +++ b/registration-processor/post-processor/registration-processor-printing-stage/src/main/java/io/mosip/registration/processor/print/stage/PrintingStage.java @@ -1,478 +1,448 @@ -package io.mosip.registration.processor.print.stage; - -import java.io.File; -import java.io.IOException; -import java.net.URLEncoder; -import java.nio.charset.StandardCharsets; -import java.security.NoSuchAlgorithmException; -import java.security.SecureRandom; -import java.time.LocalDateTime; -import java.time.format.DateTimeFormatter; -import java.util.List; -import java.util.Map; -import java.util.Random; -import java.util.HashMap; -import java.util.ArrayList; - -import org.apache.commons.codec.binary.Base64; -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.cloud.context.config.annotation.RefreshScope; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.core.env.Environment; -import org.springframework.http.MediaType; -import org.springframework.scheduling.annotation.EnableScheduling; -import org.springframework.scheduling.annotation.Scheduled; -import org.springframework.stereotype.Service; - -import com.fasterxml.jackson.databind.ObjectMapper; - -import io.mosip.kernel.core.exception.ServiceError; -import io.mosip.kernel.core.logger.spi.Logger; -import io.mosip.kernel.core.util.DateUtils; -import io.mosip.registration.processor.core.abstractverticle.MessageBusAddress; -import io.mosip.registration.processor.core.abstractverticle.MessageDTO; -import io.mosip.registration.processor.core.abstractverticle.MosipEventBus; -import io.mosip.registration.processor.core.abstractverticle.MosipRouter; -import io.mosip.registration.processor.core.abstractverticle.MosipVerticleAPIManager; -import io.mosip.registration.processor.core.code.ApiName; -import io.mosip.registration.processor.core.code.EventId; -import io.mosip.registration.processor.core.code.EventName; -import io.mosip.registration.processor.core.code.EventType; -import io.mosip.registration.processor.core.code.ModuleName; -import io.mosip.registration.processor.core.code.RegistrationTransactionStatusCode; -import io.mosip.registration.processor.core.code.RegistrationTransactionTypeCode; -import io.mosip.registration.processor.core.common.rest.dto.ErrorDTO; -import io.mosip.registration.processor.core.constant.IdType; -import io.mosip.registration.processor.core.constant.LoggerFileConstant; -import io.mosip.registration.processor.core.constant.VidType; -import io.mosip.registration.processor.core.exception.ApisResourceAccessException; -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.RequestWrapper; -import io.mosip.registration.processor.core.http.ResponseWrapper; -import io.mosip.registration.processor.core.idrepo.dto.CredentialRequestDto; -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.logger.LogDescription; -import io.mosip.registration.processor.core.logger.RegProcessorLogger; -import io.mosip.registration.processor.core.spi.restclient.RegistrationProcessorRestClientService; -import io.mosip.registration.processor.core.status.util.StatusUtil; -import io.mosip.registration.processor.core.status.util.TrimExceptionMessage; -import io.mosip.registration.processor.core.util.JsonUtil; -import io.mosip.registration.processor.packet.storage.utils.Utilities; -import io.mosip.registration.processor.print.stage.exception.VidNotAvailableException; -import io.mosip.registration.processor.rest.client.audit.builder.AuditLogRequestBuilder; -import io.mosip.registration.processor.status.dto.InternalRegistrationStatusDto; -import io.mosip.registration.processor.status.dto.RegistrationStatusDto; -import io.mosip.registration.processor.status.service.RegistrationStatusService; - -/** - * The Class PrintStage. - * - * @author M1048358 Alok - * @author Ranjitha Siddegowda - * @author Sowmya - */ -@RefreshScope -@Service -@Configuration -@EnableScheduling -@ComponentScan(basePackages = { "${mosip.auth.adapter.impl.basepackage}", - "io.mosip.registration.processor.core.config", - "io.mosip.registration.processor.stages.config", - "io.mosip.registration.processor.print.config", - "io.mosip.registrationprocessor.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.kernel.idobjectvalidator.config", - "io.mosip.registration.processor.core.kernel.beans" }) -public class PrintingStage extends MosipVerticleAPIManager { - - private static final String STAGE_PROPERTY_PREFIX = "mosip.regproc.printing."; - private Random sr = null; - private static final int max = 999999; - private static final int min = 100000; - - /** The Constant FILE_SEPARATOR. */ - public static final String FILE_SEPARATOR = File.separator; - - - /** The reg proc logger. */ - private static Logger regProcLogger = RegProcessorLogger.getLogger(PrintingStage.class); - - /** The cluster manager url. */ - @Value("${vertx.cluster.configuration}") - private String clusterManagerUrl; - - - /** The core audit request builder. */ - @Autowired - private AuditLogRequestBuilder auditLogRequestBuilder; - - /** The mosip event bus. */ - private MosipEventBus mosipEventBus; - - /** The registration status service. */ - @Autowired - RegistrationStatusService registrationStatusService; - - /** worker pool size. */ - @Value("${worker.pool.size}") - private Integer workerPoolSize; - - /** After this time intervel, message should be considered as expired (In seconds). */ - @Value("${mosip.regproc.printing.message.expiry-time-limit}") - private Long messageExpiryTimeLimit; - - - @Value("${mosip.registration.processor.encrypt:false}") - private boolean encrypt; - - @Value("${mosip.registration.processor.default.issuer:mpartner-default-print}") - private String issuer; - - - /** Mosip router for APIs */ - @Autowired - MosipRouter router; - - boolean isConnection = false; - - private static final String SEPERATOR = "::"; - - @Autowired - private RegistrationProcessorRestClientService restClientService; - - @Autowired - private ObjectMapper mapper; - - @Autowired - private Environment env; - - private static final String DATETIME_PATTERN = "mosip.registration.processor.datetime.pattern"; - - private static final String ISSUERS = "mosip.registration.processor.issuer"; - - @Value("${mosip.registration.processor.rid.delimiter:-PDF}") - private String pdfDelimiter; - - private static String SEMICOLON = ";"; - private static String COLON = ":"; - - @Autowired - private Utilities utilities; - - @Override - protected String getPropertyPrefix() { - return STAGE_PROPERTY_PREFIX; - } - - /** - * Deploy verticle. - */ - public void deployVerticle() { - mosipEventBus = this.getEventBus(this, clusterManagerUrl, workerPoolSize); - this.consumeAndSend(mosipEventBus, MessageBusAddress.PRINTING_BUS_IN, MessageBusAddress.PRINTING_BUS_OUT, - messageExpiryTimeLimit); - } - - /* - * (non-Javadoc) - * - * @see - * io.mosip.registration.processor.core.spi.eventbus.EventBusManager#process( - * java.lang.Object) - */ - @Override - public MessageDTO process(MessageDTO object) { - TrimExceptionMessage trimeExpMessage = new TrimExceptionMessage(); - object.setMessageBusAddress(MessageBusAddress.PRINTING_BUS_IN); - object.setInternalError(Boolean.FALSE); - object.setIsValid(Boolean.FALSE); - LogDescription description = new LogDescription(); - - boolean isTransactionSuccessful = false; - String uin = null; - String regId = object.getRid(); - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - regId, "PrintStage::process()::entry"); - - InternalRegistrationStatusDto registrationStatusDto = null; - RequestWrapper requestWrapper = new RequestWrapper<>(); - ResponseWrapper responseWrapper = null; - CredentialResponseDto credentialResponseDto; - try { - registrationStatusDto = registrationStatusService.getRegistrationStatus( - regId, object.getReg_type(), object.getIteration(), object.getWorkflowInstanceId()); - registrationStatusDto - .setLatestTransactionTypeCode(RegistrationTransactionTypeCode.PRINT_SERVICE.toString()); - registrationStatusDto.setRegistrationStageName(getStageName()); - JSONObject jsonObject = utilities.retrieveUIN(regId); - uin = JsonUtil.getJSONValue(jsonObject, IdType.UIN.toString()); - if (uin == null) { - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), - LoggerFileConstant.REGISTRATIONID.toString(), null, - PlatformErrorMessages.RPR_PRT_UIN_NOT_FOUND_IN_DATABASE.name()); - object.setIsValid(Boolean.FALSE); - isTransactionSuccessful = false; - description.setMessage(PlatformErrorMessages.RPR_PRT_PRINT_REQUEST_FAILED.getMessage()); - description.setCode(PlatformErrorMessages.RPR_PRT_PRINT_REQUEST_FAILED.getCode()); - - registrationStatusDto.setStatusComment( - StatusUtil.UIN_NOT_FOUND_IN_DATABASE.getMessage()); - registrationStatusDto.setSubStatusCode(StatusUtil.UIN_NOT_FOUND_IN_DATABASE.getCode()); - registrationStatusDto - .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.FAILED.toString()); - registrationStatusDto - .setLatestTransactionTypeCode(RegistrationTransactionTypeCode.PRINT_SERVICE.toString()); - - } - else { - String vid = getVid(uin); - requestWrapper.setId(env.getProperty("mosip.registration.processor.credential.request.service.id")); - String issuers= env.getProperty(ISSUERS); - DateTimeFormatter format = DateTimeFormatter.ofPattern(env.getProperty(DATETIME_PATTERN)); - LocalDateTime localdatetime = LocalDateTime - .parse(DateUtils.getUTCCurrentDateTimeString(env.getProperty(DATETIME_PATTERN)), format); - requestWrapper.setRequesttime(localdatetime); - requestWrapper.setVersion("1.0"); - for (String key : issuers.split(SEMICOLON)) { - CredentialRequestDto credentialRequestDto=null; - String[] parts = key.split(COLON, 3); - credentialRequestDto = getCredentialRequestDto(regId, parts[0], parts[1], parts[2]); - requestWrapper.setRequest(credentialRequestDto); - if (parts[0].equalsIgnoreCase(issuer)) { // for default issuer stage is calling v1 api and for others stage is calling v2 api for credential - responseWrapper = (ResponseWrapper) restClientService.postApi(ApiName.CREDENTIALREQUEST, null, null, - requestWrapper, ResponseWrapper.class, MediaType.APPLICATION_JSON); - } else { - List pathsegments = new ArrayList<>(); - pathsegments.add(regId + pdfDelimiter); // #PDF suffix is added to identify the requested credential via rid - responseWrapper = (ResponseWrapper) restClientService.postApi(ApiName.CREDENTIALREQUESTV2, MediaType.APPLICATION_JSON, pathsegments, null, - null, requestWrapper, ResponseWrapper.class); - } - } - - if (responseWrapper.getErrors() != null && !responseWrapper.getErrors().isEmpty()) { - ErrorDTO error = responseWrapper.getErrors().get(0); - object.setIsValid(Boolean.FALSE); - isTransactionSuccessful = false; - description.setMessage(PlatformErrorMessages.RPR_PRT_PRINT_REQUEST_FAILED.getMessage()); - description.setCode(PlatformErrorMessages.RPR_PRT_PRINT_REQUEST_FAILED.getCode()); - - registrationStatusDto.setStatusComment( - StatusUtil.PRINT_REQUEST_FAILED.getMessage() + SEPERATOR + error.getMessage()); - registrationStatusDto.setSubStatusCode(StatusUtil.PRINT_REQUEST_FAILED.getCode()); - registrationStatusDto - .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.REPROCESS.toString()); - registrationStatusDto - .setLatestTransactionTypeCode(RegistrationTransactionTypeCode.PRINT_SERVICE.toString()); - } else { - credentialResponseDto = mapper.readValue(mapper.writeValueAsString(responseWrapper.getResponse()), - CredentialResponseDto.class); - - registrationStatusDto.setRefId(credentialResponseDto.getRequestId()); - object.setIsValid(Boolean.TRUE); - isTransactionSuccessful = true; - description.setMessage(PlatformSuccessMessages.RPR_PRINT_STAGE_REQUEST_SUCCESS.getMessage()); - description.setCode(PlatformSuccessMessages.RPR_PRINT_STAGE_REQUEST_SUCCESS.getCode()); - registrationStatusDto.setStatusComment( - trimeExpMessage.trimExceptionMessage(StatusUtil.PRINT_REQUEST_SUCCESS.getMessage())); - registrationStatusDto.setSubStatusCode(StatusUtil.PRINT_REQUEST_SUCCESS.getCode()); - registrationStatusDto - .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.PROCESSED.toString()); - registrationStatusDto - .setLatestTransactionTypeCode(RegistrationTransactionTypeCode.PRINT_SERVICE.toString()); - - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), - LoggerFileConstant.REGISTRATIONID.toString(), regId, "PrintStage::process()::exit"); - } - } - } catch (ApisResourceAccessException e) { - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - regId, PlatformErrorMessages.RPR_PRT_PRINT_REQUEST_FAILED.name() + e.getMessage() - + ExceptionUtils.getStackTrace(e)); - registrationStatusDto - .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.REPROCESS.toString()); - registrationStatusDto.setStatusComment(trimeExpMessage.trimExceptionMessage( - StatusUtil.API_RESOUCE_ACCESS_FAILED.getMessage() + SEPERATOR + e.getMessage())); - registrationStatusDto.setSubStatusCode(StatusUtil.API_RESOUCE_ACCESS_FAILED.getCode()); - description.setMessage(PlatformErrorMessages.RPR_PRT_PRINT_REQUEST_FAILED.getMessage()); - description.setCode(PlatformErrorMessages.RPR_PRT_PRINT_REQUEST_FAILED.getCode()); - object.setInternalError(Boolean.TRUE); - } catch (IOException e) { - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - regId, PlatformErrorMessages.RPR_PRT_PRINT_REQUEST_FAILED.name() + e.getMessage() - + ExceptionUtils.getStackTrace(e)); - registrationStatusDto - .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.REPROCESS.toString()); - registrationStatusDto.setStatusComment( - trimeExpMessage.trimExceptionMessage(StatusUtil.IO_EXCEPTION.getMessage() + e.getMessage())); - registrationStatusDto.setSubStatusCode(StatusUtil.IO_EXCEPTION.getCode()); - description.setMessage(PlatformErrorMessages.RPR_PRT_PRINT_REQUEST_FAILED.getMessage()); - description.setCode(PlatformErrorMessages.RPR_PRT_PRINT_REQUEST_FAILED.getCode()); - object.setInternalError(Boolean.TRUE); - } catch (VidNotAvailableException e) { - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - regId, PlatformErrorMessages.RPR_PRT_PRINT_REQUEST_FAILED.name() + e.getMessage() - + ExceptionUtils.getStackTrace(e)); - registrationStatusDto - .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.REPROCESS.toString()); - registrationStatusDto.setStatusComment( - trimeExpMessage.trimExceptionMessage(StatusUtil.VID_NOT_AVAILABLE.getMessage())); - registrationStatusDto.setSubStatusCode(StatusUtil.VID_NOT_AVAILABLE.getCode()); - description.setMessage(PlatformErrorMessages.RPR_PRT_PRINT_REQUEST_FAILED.getMessage()); - description.setCode(PlatformErrorMessages.RPR_PRT_PRINT_REQUEST_FAILED.getCode()); - object.setInternalError(Boolean.TRUE); - } catch (Exception e) { - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - regId, PlatformErrorMessages.RPR_PRT_PRINT_REQUEST_FAILED.name() + e.getMessage() - + ExceptionUtils.getStackTrace(e)); - registrationStatusDto - .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.REPROCESS.toString()); - registrationStatusDto.setStatusComment( - trimeExpMessage.trimExceptionMessage(StatusUtil.UNKNOWN_EXCEPTION_OCCURED.getMessage())); - registrationStatusDto.setSubStatusCode(StatusUtil.UNKNOWN_EXCEPTION_OCCURED.getCode()); - description.setMessage(PlatformErrorMessages.RPR_PRT_PRINT_REQUEST_FAILED.getMessage()); - description.setCode(PlatformErrorMessages.RPR_PRT_PRINT_REQUEST_FAILED.getCode()); - object.setInternalError(Boolean.TRUE); - } - finally { - if (object.getInternalError()) { - updateErrorFlags(registrationStatusDto, object); - } - String eventId = ""; - String eventName = ""; - String eventType = ""; - eventId = isTransactionSuccessful ? EventId.RPR_402.toString() : EventId.RPR_405.toString(); - eventName = eventId.equalsIgnoreCase(EventId.RPR_402.toString()) ? EventName.UPDATE.toString() - : EventName.EXCEPTION.toString(); - eventType = eventId.equalsIgnoreCase(EventId.RPR_402.toString()) ? EventType.BUSINESS.toString() - : EventType.SYSTEM.toString(); - /** Module-Id can be Both Success/Error code */ - String moduleId = isTransactionSuccessful - ? PlatformSuccessMessages.RPR_PRINT_STAGE_REQUEST_SUCCESS.getCode() - : description.getCode(); - String moduleName = ModuleName.PRINT_STAGE.toString(); - registrationStatusService.updateRegistrationStatus(registrationStatusDto, moduleId, moduleName); - - auditLogRequestBuilder.createAuditRequestBuilder(description.getMessage(), eventId, eventName, eventType, - moduleId, moduleName, regId); - - } - - return object; - } - - private CredentialRequestDto getCredentialRequestDto(String regId,String issuerId,String credentialType,String templateTypeCode) { - CredentialRequestDto credentialRequestDto = new CredentialRequestDto(); - Map additionalAttributes=new HashMap<>(); - - credentialRequestDto.setCredentialType(credentialType); - credentialRequestDto.setEncrypt(encrypt); - - credentialRequestDto.setId(regId); - - credentialRequestDto.setIssuer(issuerId); - - credentialRequestDto.setEncryptionKey(generatePin()); - additionalAttributes.put("templateTypeCode",templateTypeCode); - credentialRequestDto.setAdditionalData(additionalAttributes); - - return credentialRequestDto; - } - - - /* - * (non-Javadoc) - * - * @see io.vertx.core.AbstractVerticle#start() - */ - @Override - public void start() { - router.setRoute(this.postUrl(getVertx(), - MessageBusAddress.PRINTING_BUS_IN, MessageBusAddress.PRINTING_BUS_OUT)); - this.createServer(router.getRouter(), getPort()); - } - - public String generatePin() { - if (sr == null) - instantiate(); - int randomInteger = sr.nextInt(max - min) + min; - return String.valueOf(randomInteger); - } - - @SuppressWarnings("unchecked") - private String getVid(String uin) throws ApisResourceAccessException, VidNotAvailableException { - List pathsegments = new ArrayList<>(); - pathsegments.add(uin); - String vid = null; - - VidsInfosDTO vidsInfosDTO; - - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), "", - "PrintServiceImpl::getVid():: get GETVIDSBYUIN service call started with request data : " - ); - - vidsInfosDTO = (VidsInfosDTO) restClientService.getApi(ApiName.GETVIDSBYUIN, - pathsegments, "", "", VidsInfosDTO.class); - - if (vidsInfosDTO.getErrors() != null && !vidsInfosDTO.getErrors().isEmpty()) { - ServiceError error = vidsInfosDTO.getErrors().get(0); - throw new VidNotAvailableException(PlatformErrorMessages.RPR_PRT_VID_NOT_AVAILABLE_EXCEPTION.getCode(), - error.getMessage()); - - } else { - if(vidsInfosDTO.getResponse()!=null && !vidsInfosDTO.getResponse().isEmpty()) { - for (VidInfoDTO VidInfoDTO : vidsInfosDTO.getResponse()) { - if (VidType.PERPETUAL.name().equalsIgnoreCase(VidInfoDTO.getVidType())) { - vid = VidInfoDTO.getVid(); - break; - } - } - if (vid == null) { - throw new VidNotAvailableException( - PlatformErrorMessages.RPR_PRT_VID_NOT_AVAILABLE_EXCEPTION.getCode(), - PlatformErrorMessages.RPR_PRT_VID_NOT_AVAILABLE_EXCEPTION.getMessage()); - } - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), - LoggerFileConstant.REGISTRATIONID.toString(), "", - "PrintServiceImpl::getVid():: get GETVIDSBYUIN service call ended successfully"); - - }else { - throw new VidNotAvailableException(PlatformErrorMessages.RPR_PRT_VID_NOT_AVAILABLE_EXCEPTION.getCode(), - PlatformErrorMessages.RPR_PRT_VID_NOT_AVAILABLE_EXCEPTION.getMessage()); - } - - } - - return vid; - } - - private void updateErrorFlags(InternalRegistrationStatusDto registrationStatusDto, MessageDTO object) { - object.setInternalError(true); - if (registrationStatusDto.getLatestTransactionStatusCode() - .equalsIgnoreCase(RegistrationTransactionStatusCode.REPROCESS.toString())) { - object.setIsValid(true); - } else { - object.setIsValid(false); - } - } - - @Scheduled(fixedDelayString = "${mosip.regproc.printstage.pingeneration.refresh.millisecs:1800000}", - initialDelayString = "${mosip.regproc.printstage.pingeneration.refresh.delay-on-startup.millisecs:5000}") - private void instantiate() { - regProcLogger.debug("Instantiating SecureRandom for credential pin generation............"); - try { - sr = SecureRandom.getInstance("SHA1PRNG"); - } catch (NoSuchAlgorithmException e) { - regProcLogger.error("Could not instantiate SecureRandom for credential pin generation", e); - } - } +package io.mosip.registration.processor.print.stage; + +import java.io.File; +import java.io.IOException; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.List; +import java.util.Random; + +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.cloud.context.config.annotation.RefreshScope; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.env.Environment; +import org.springframework.http.MediaType; +import org.springframework.scheduling.annotation.EnableScheduling; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Service; + +import com.fasterxml.jackson.databind.ObjectMapper; + +import io.mosip.kernel.core.exception.ServiceError; +import io.mosip.kernel.core.logger.spi.Logger; +import io.mosip.kernel.core.util.DateUtils; +import io.mosip.registration.processor.core.abstractverticle.MessageBusAddress; +import io.mosip.registration.processor.core.abstractverticle.MessageDTO; +import io.mosip.registration.processor.core.abstractverticle.MosipEventBus; +import io.mosip.registration.processor.core.abstractverticle.MosipRouter; +import io.mosip.registration.processor.core.abstractverticle.MosipVerticleAPIManager; +import io.mosip.registration.processor.core.code.ApiName; +import io.mosip.registration.processor.core.code.EventId; +import io.mosip.registration.processor.core.code.EventName; +import io.mosip.registration.processor.core.code.EventType; +import io.mosip.registration.processor.core.code.ModuleName; +import io.mosip.registration.processor.core.code.RegistrationTransactionStatusCode; +import io.mosip.registration.processor.core.code.RegistrationTransactionTypeCode; +import io.mosip.registration.processor.core.common.rest.dto.ErrorDTO; +import io.mosip.registration.processor.core.constant.IdType; +import io.mosip.registration.processor.core.constant.LoggerFileConstant; +import io.mosip.registration.processor.core.constant.VidType; +import io.mosip.registration.processor.core.exception.ApisResourceAccessException; +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.RequestWrapper; +import io.mosip.registration.processor.core.http.ResponseWrapper; +import io.mosip.registration.processor.core.idrepo.dto.CredentialRequestDto; +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.logger.LogDescription; +import io.mosip.registration.processor.core.logger.RegProcessorLogger; +import io.mosip.registration.processor.core.spi.restclient.RegistrationProcessorRestClientService; +import io.mosip.registration.processor.core.status.util.StatusUtil; +import io.mosip.registration.processor.core.status.util.TrimExceptionMessage; +import io.mosip.registration.processor.core.util.JsonUtil; +import io.mosip.registration.processor.packet.storage.utils.Utilities; +import io.mosip.registration.processor.print.stage.exception.VidNotAvailableException; +import io.mosip.registration.processor.rest.client.audit.builder.AuditLogRequestBuilder; +import io.mosip.registration.processor.status.dto.InternalRegistrationStatusDto; +import io.mosip.registration.processor.status.dto.RegistrationStatusDto; +import io.mosip.registration.processor.status.service.RegistrationStatusService; + +/** + * The Class PrintStage. + * + * @author M1048358 Alok + * @author Ranjitha Siddegowda + * @author Sowmya + */ +@RefreshScope +@Service +@Configuration +@EnableScheduling +@ComponentScan(basePackages = { "${mosip.auth.adapter.impl.basepackage}", + "io.mosip.registration.processor.core.config", + "io.mosip.registration.processor.stages.config", + "io.mosip.registration.processor.print.config", + "io.mosip.registrationprocessor.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.kernel.idobjectvalidator.config", + "io.mosip.registration.processor.core.kernel.beans" }) +public class PrintingStage extends MosipVerticleAPIManager { + + private static final String STAGE_PROPERTY_PREFIX = "mosip.regproc.printing."; + private Random sr = null; + private static final int max = 999999; + private static final int min = 100000; + + /** The Constant FILE_SEPARATOR. */ + public static final String FILE_SEPARATOR = File.separator; + + + /** The reg proc logger. */ + private static Logger regProcLogger = RegProcessorLogger.getLogger(PrintingStage.class); + + /** The cluster manager url. */ + @Value("${vertx.cluster.configuration}") + private String clusterManagerUrl; + + + /** The core audit request builder. */ + @Autowired + private AuditLogRequestBuilder auditLogRequestBuilder; + + /** The mosip event bus. */ + private MosipEventBus mosipEventBus; + + /** The registration status service. */ + @Autowired + RegistrationStatusService registrationStatusService; + + /** worker pool size. */ + @Value("${worker.pool.size}") + private Integer workerPoolSize; + + /** After this time intervel, message should be considered as expired (In seconds). */ + @Value("${mosip.regproc.printing.message.expiry-time-limit}") + private Long messageExpiryTimeLimit; + + + @Value("${mosip.registration.processor.encrypt:false}") + private boolean encrypt; + + /** Mosip router for APIs */ + @Autowired + MosipRouter router; + + boolean isConnection = false; + + private static final String SEPERATOR = "::"; + + @Autowired + private RegistrationProcessorRestClientService restClientService; + + @Autowired + private ObjectMapper mapper; + + @Autowired + private Environment env; + + private static final String DATETIME_PATTERN = "mosip.registration.processor.datetime.pattern"; + + + @Autowired + private Utilities utilities; + + @Override + protected String getPropertyPrefix() { + return STAGE_PROPERTY_PREFIX; + } + + /** + * Deploy verticle. + */ + public void deployVerticle() { + mosipEventBus = this.getEventBus(this, clusterManagerUrl, workerPoolSize); + this.consumeAndSend(mosipEventBus, MessageBusAddress.PRINTING_BUS_IN, MessageBusAddress.PRINTING_BUS_OUT, + messageExpiryTimeLimit); + } + + /* + * (non-Javadoc) + * + * @see + * io.mosip.registration.processor.core.spi.eventbus.EventBusManager#process( + * java.lang.Object) + */ + @Override + public MessageDTO process(MessageDTO object) { + TrimExceptionMessage trimeExpMessage = new TrimExceptionMessage(); + object.setMessageBusAddress(MessageBusAddress.PRINTING_BUS_IN); + object.setInternalError(Boolean.FALSE); + object.setIsValid(Boolean.FALSE); + LogDescription description = new LogDescription(); + + boolean isTransactionSuccessful = false; + String uin = null; + String regId = object.getRid(); + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + regId, "PrintStage::process()::entry"); + + InternalRegistrationStatusDto registrationStatusDto = null; + RequestWrapper requestWrapper = new RequestWrapper<>(); + ResponseWrapper responseWrapper = null; + CredentialResponseDto credentialResponseDto; + try { + registrationStatusDto = registrationStatusService.getRegistrationStatus( + regId, object.getReg_type(), object.getIteration(), object.getWorkflowInstanceId()); + registrationStatusDto + .setLatestTransactionTypeCode(RegistrationTransactionTypeCode.PRINT_SERVICE.toString()); + registrationStatusDto.setRegistrationStageName(getStageName()); + JSONObject jsonObject = utilities.retrieveUIN(regId); + uin = JsonUtil.getJSONValue(jsonObject, IdType.UIN.toString()); + if (uin == null) { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString(), null, + PlatformErrorMessages.RPR_PRT_UIN_NOT_FOUND_IN_DATABASE.name()); + object.setIsValid(Boolean.FALSE); + isTransactionSuccessful = false; + description.setMessage(PlatformErrorMessages.RPR_PRT_PRINT_REQUEST_FAILED.getMessage()); + description.setCode(PlatformErrorMessages.RPR_PRT_PRINT_REQUEST_FAILED.getCode()); + + registrationStatusDto.setStatusComment( + StatusUtil.UIN_NOT_FOUND_IN_DATABASE.getMessage()); + registrationStatusDto.setSubStatusCode(StatusUtil.UIN_NOT_FOUND_IN_DATABASE.getCode()); + registrationStatusDto + .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.FAILED.toString()); + registrationStatusDto + .setLatestTransactionTypeCode(RegistrationTransactionTypeCode.PRINT_SERVICE.toString()); + + } + else { + String vid = getVid(uin); + CredentialRequestDto credentialRequestDto = getCredentialRequestDto(vid); + requestWrapper.setId(env.getProperty("mosip.registration.processor.credential.request.service.id")); + DateTimeFormatter format = DateTimeFormatter.ofPattern(env.getProperty(DATETIME_PATTERN)); + LocalDateTime localdatetime = LocalDateTime + .parse(DateUtils.getUTCCurrentDateTimeString(env.getProperty(DATETIME_PATTERN)), format); + requestWrapper.setRequesttime(localdatetime); + requestWrapper.setVersion("1.0"); + requestWrapper.setRequest(credentialRequestDto); + responseWrapper = (ResponseWrapper) restClientService.postApi(ApiName.CREDENTIALREQUEST, null, + null, + requestWrapper, ResponseWrapper.class, MediaType.APPLICATION_JSON); + if (responseWrapper.getErrors() != null && !responseWrapper.getErrors().isEmpty()) { + ErrorDTO error = responseWrapper.getErrors().get(0); + object.setIsValid(Boolean.FALSE); + isTransactionSuccessful = false; + description.setMessage(PlatformErrorMessages.RPR_PRT_PRINT_REQUEST_FAILED.getMessage()); + description.setCode(PlatformErrorMessages.RPR_PRT_PRINT_REQUEST_FAILED.getCode()); + + registrationStatusDto.setStatusComment( + StatusUtil.PRINT_REQUEST_FAILED.getMessage() + SEPERATOR + error.getMessage()); + registrationStatusDto.setSubStatusCode(StatusUtil.PRINT_REQUEST_FAILED.getCode()); + registrationStatusDto + .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.REPROCESS.toString()); + registrationStatusDto + .setLatestTransactionTypeCode(RegistrationTransactionTypeCode.PRINT_SERVICE.toString()); + } else { + credentialResponseDto = mapper.readValue(mapper.writeValueAsString(responseWrapper.getResponse()), + CredentialResponseDto.class); + + registrationStatusDto.setRefId(credentialResponseDto.getRequestId()); + object.setIsValid(Boolean.TRUE); + isTransactionSuccessful = true; + description.setMessage(PlatformSuccessMessages.RPR_PRINT_STAGE_REQUEST_SUCCESS.getMessage()); + description.setCode(PlatformSuccessMessages.RPR_PRINT_STAGE_REQUEST_SUCCESS.getCode()); + registrationStatusDto.setStatusComment( + trimeExpMessage.trimExceptionMessage(StatusUtil.PRINT_REQUEST_SUCCESS.getMessage())); + registrationStatusDto.setSubStatusCode(StatusUtil.PRINT_REQUEST_SUCCESS.getCode()); + registrationStatusDto + .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.PROCESSED.toString()); + registrationStatusDto + .setLatestTransactionTypeCode(RegistrationTransactionTypeCode.PRINT_SERVICE.toString()); + + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString(), regId, "PrintStage::process()::exit"); + } + } + } catch (ApisResourceAccessException e) { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + regId, PlatformErrorMessages.RPR_PRT_PRINT_REQUEST_FAILED.name() + e.getMessage() + + ExceptionUtils.getStackTrace(e)); + registrationStatusDto + .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.REPROCESS.toString()); + registrationStatusDto.setStatusComment(trimeExpMessage.trimExceptionMessage( + StatusUtil.API_RESOUCE_ACCESS_FAILED.getMessage() + SEPERATOR + e.getMessage())); + registrationStatusDto.setSubStatusCode(StatusUtil.API_RESOUCE_ACCESS_FAILED.getCode()); + description.setMessage(PlatformErrorMessages.RPR_PRT_PRINT_REQUEST_FAILED.getMessage()); + description.setCode(PlatformErrorMessages.RPR_PRT_PRINT_REQUEST_FAILED.getCode()); + object.setInternalError(Boolean.TRUE); + } catch (IOException e) { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + regId, PlatformErrorMessages.RPR_PRT_PRINT_REQUEST_FAILED.name() + e.getMessage() + + ExceptionUtils.getStackTrace(e)); + registrationStatusDto + .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.REPROCESS.toString()); + registrationStatusDto.setStatusComment( + trimeExpMessage.trimExceptionMessage(StatusUtil.IO_EXCEPTION.getMessage() + e.getMessage())); + registrationStatusDto.setSubStatusCode(StatusUtil.IO_EXCEPTION.getCode()); + description.setMessage(PlatformErrorMessages.RPR_PRT_PRINT_REQUEST_FAILED.getMessage()); + description.setCode(PlatformErrorMessages.RPR_PRT_PRINT_REQUEST_FAILED.getCode()); + object.setInternalError(Boolean.TRUE); + } catch (VidNotAvailableException e) { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + regId, PlatformErrorMessages.RPR_PRT_PRINT_REQUEST_FAILED.name() + e.getMessage() + + ExceptionUtils.getStackTrace(e)); + registrationStatusDto + .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.REPROCESS.toString()); + registrationStatusDto.setStatusComment( + trimeExpMessage.trimExceptionMessage(StatusUtil.VID_NOT_AVAILABLE.getMessage())); + registrationStatusDto.setSubStatusCode(StatusUtil.VID_NOT_AVAILABLE.getCode()); + description.setMessage(PlatformErrorMessages.RPR_PRT_PRINT_REQUEST_FAILED.getMessage()); + description.setCode(PlatformErrorMessages.RPR_PRT_PRINT_REQUEST_FAILED.getCode()); + object.setInternalError(Boolean.TRUE); + } catch (Exception e) { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + regId, PlatformErrorMessages.RPR_PRT_PRINT_REQUEST_FAILED.name() + e.getMessage() + + ExceptionUtils.getStackTrace(e)); + registrationStatusDto + .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.REPROCESS.toString()); + registrationStatusDto.setStatusComment( + trimeExpMessage.trimExceptionMessage(StatusUtil.UNKNOWN_EXCEPTION_OCCURED.getMessage())); + registrationStatusDto.setSubStatusCode(StatusUtil.UNKNOWN_EXCEPTION_OCCURED.getCode()); + description.setMessage(PlatformErrorMessages.RPR_PRT_PRINT_REQUEST_FAILED.getMessage()); + description.setCode(PlatformErrorMessages.RPR_PRT_PRINT_REQUEST_FAILED.getCode()); + object.setInternalError(Boolean.TRUE); + } + finally { + if (object.getInternalError()) { + updateErrorFlags(registrationStatusDto, object); + } + String eventId = ""; + String eventName = ""; + String eventType = ""; + eventId = isTransactionSuccessful ? EventId.RPR_402.toString() : EventId.RPR_405.toString(); + eventName = eventId.equalsIgnoreCase(EventId.RPR_402.toString()) ? EventName.UPDATE.toString() + : EventName.EXCEPTION.toString(); + eventType = eventId.equalsIgnoreCase(EventId.RPR_402.toString()) ? EventType.BUSINESS.toString() + : EventType.SYSTEM.toString(); + /** Module-Id can be Both Success/Error code */ + String moduleId = isTransactionSuccessful + ? PlatformSuccessMessages.RPR_PRINT_STAGE_REQUEST_SUCCESS.getCode() + : description.getCode(); + String moduleName = ModuleName.PRINT_STAGE.toString(); + registrationStatusService.updateRegistrationStatus(registrationStatusDto, moduleId, moduleName); + + auditLogRequestBuilder.createAuditRequestBuilder(description.getMessage(), eventId, eventName, eventType, + moduleId, moduleName, regId); + + } + + return object; + } + + private CredentialRequestDto getCredentialRequestDto(String vid) { + CredentialRequestDto credentialRequestDto = new CredentialRequestDto(); + + credentialRequestDto.setCredentialType(env.getProperty("mosip.registration.processor.credentialtype")); + + credentialRequestDto.setEncrypt(encrypt); + + credentialRequestDto.setId(vid); + + credentialRequestDto.setIssuer(env.getProperty("mosip.registration.processor.issuer")); + + credentialRequestDto.setEncryptionKey(generatePin()); + + return credentialRequestDto; + } + + + /* + * (non-Javadoc) + * + * @see io.vertx.core.AbstractVerticle#start() + */ + @Override + public void start() { + router.setRoute(this.postUrl(getVertx(), + MessageBusAddress.PRINTING_BUS_IN, MessageBusAddress.PRINTING_BUS_OUT)); + this.createServer(router.getRouter(), getPort()); + } + + public String generatePin() { + if (sr == null) + instantiate(); + int randomInteger = sr.nextInt(max - min) + min; + return String.valueOf(randomInteger); + } + + @SuppressWarnings("unchecked") + private String getVid(String uin) throws ApisResourceAccessException, VidNotAvailableException { + List pathsegments = new ArrayList<>(); + pathsegments.add(uin); + String vid = null; + + VidsInfosDTO vidsInfosDTO; + + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), "", + "PrintServiceImpl::getVid():: get GETVIDSBYUIN service call started with request data : " + ); + + vidsInfosDTO = (VidsInfosDTO) restClientService.getApi(ApiName.GETVIDSBYUIN, + pathsegments, "", "", VidsInfosDTO.class); + + if (vidsInfosDTO.getErrors() != null && !vidsInfosDTO.getErrors().isEmpty()) { + ServiceError error = vidsInfosDTO.getErrors().get(0); + throw new VidNotAvailableException(PlatformErrorMessages.RPR_PRT_VID_NOT_AVAILABLE_EXCEPTION.getCode(), + error.getMessage()); + + } else { + if(vidsInfosDTO.getResponse()!=null && !vidsInfosDTO.getResponse().isEmpty()) { + for (VidInfoDTO VidInfoDTO : vidsInfosDTO.getResponse()) { + if (VidType.PERPETUAL.name().equalsIgnoreCase(VidInfoDTO.getVidType())) { + vid = VidInfoDTO.getVid(); + break; + } + } + if (vid == null) { + throw new VidNotAvailableException( + PlatformErrorMessages.RPR_PRT_VID_NOT_AVAILABLE_EXCEPTION.getCode(), + PlatformErrorMessages.RPR_PRT_VID_NOT_AVAILABLE_EXCEPTION.getMessage()); + } + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString(), "", + "PrintServiceImpl::getVid():: get GETVIDSBYUIN service call ended successfully"); + + }else { + throw new VidNotAvailableException(PlatformErrorMessages.RPR_PRT_VID_NOT_AVAILABLE_EXCEPTION.getCode(), + PlatformErrorMessages.RPR_PRT_VID_NOT_AVAILABLE_EXCEPTION.getMessage()); + } + + } + + return vid; + } + + private void updateErrorFlags(InternalRegistrationStatusDto registrationStatusDto, MessageDTO object) { + object.setInternalError(true); + if (registrationStatusDto.getLatestTransactionStatusCode() + .equalsIgnoreCase(RegistrationTransactionStatusCode.REPROCESS.toString())) { + object.setIsValid(true); + } else { + object.setIsValid(false); + } + } + + @Scheduled(fixedDelayString = "${mosip.regproc.printstage.pingeneration.refresh.millisecs:1800000}", + initialDelayString = "${mosip.regproc.printstage.pingeneration.refresh.delay-on-startup.millisecs:5000}") + private void instantiate() { + regProcLogger.debug("Instantiating SecureRandom for credential pin generation............"); + try { + sr = SecureRandom.getInstance("SHA1PRNG"); + } catch (NoSuchAlgorithmException e) { + regProcLogger.error("Could not instantiate SecureRandom for credential pin generation", e); + } + } } \ No newline at end of file diff --git a/registration-processor/post-processor/registration-processor-printing-stage/src/main/resources/bootstrap.properties b/registration-processor/post-processor/registration-processor-printing-stage/src/main/resources/bootstrap.properties index 45ce04ae614..64b25477db4 100644 --- a/registration-processor/post-processor/registration-processor-printing-stage/src/main/resources/bootstrap.properties +++ b/registration-processor/post-processor/registration-processor-printing-stage/src/main/resources/bootstrap.properties @@ -22,10 +22,4 @@ eventbus.port=5722 mosip.regproc.eventbus.kafka.commit.type=${mosip.regproc.printing.eventbus.kafka.commit.type} mosip.regproc.eventbus.kafka.max.poll.records=${mosip.regproc.printing.eventbus.kafka.max.poll.records} mosip.regproc.eventbus.kafka.poll.frequency=${mosip.regproc.printing.eventbus.kafka.poll.frequency} -mosip.regproc.eventbus.kafka.group.id=${mosip.regproc.printing.eventbus.kafka.group.id} -mosip.registration.processor.digitalcard.credentialtype=PDFCard -mosip.registration.processor.print.credentialtype=euin -mosip.registration.processor.digitalcard.template=RPR_UIN_CARD_TEMPLATE -mosip.registration.processor.print.template=RPR_UIN_CARD_TEMPLATE -# this property is used to define issuers eg partnerid:credentialType:templateTypeCode -mosip.registration.processor.issuer=mpartner-default-print:${mosip.registration.processor.print.credentialtype}:${mosip.registration.processor.print.template};mpartner-default-digitalcard:${mosip.registration.processor.digitalcard.credentialtype}:${mosip.registration.processor.digitalcard.template} \ No newline at end of file +mosip.regproc.eventbus.kafka.group.id=${mosip.regproc.printing.eventbus.kafka.group.id} \ No newline at end of file diff --git a/registration-processor/post-processor/registration-processor-printing-stage/src/test/java/io/mosip/registrationprocessor/print/stage/test/PrintingStageTest.java b/registration-processor/post-processor/registration-processor-printing-stage/src/test/java/io/mosip/registrationprocessor/print/stage/test/PrintingStageTest.java index 43b6c73e975..dc4c470177a 100644 --- a/registration-processor/post-processor/registration-processor-printing-stage/src/test/java/io/mosip/registrationprocessor/print/stage/test/PrintingStageTest.java +++ b/registration-processor/post-processor/registration-processor-printing-stage/src/test/java/io/mosip/registrationprocessor/print/stage/test/PrintingStageTest.java @@ -184,14 +184,11 @@ 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.printing.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, "pdfDelimiter", "-PDF"); - ReflectionTestUtils.setField(stage, "issuer", "mpartner-default-print"); System.setProperty("server.port", "8099"); //ReflectionTestUtils.setField(stage, "port", "8080"); @@ -278,8 +275,7 @@ public void testPrintStageSuccess() 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()); diff --git a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/code/ApiName.java b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/code/ApiName.java index bfaaa1ae892..2408b0c1a67 100644 --- a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/code/ApiName.java +++ b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/code/ApiName.java @@ -1,203 +1,202 @@ -package io.mosip.registration.processor.core.code; - -/** - * The Enum ApiName. - * - * @author Rishabh Keshari - */ -public enum ApiName { - - /** The auth. */ - AUTH, - - /** The authinternal. */ - AUTHINTERNAL, - - /** The master data. */ - MASTER, - - /** The iam. */ - IAM, - - /** The audit. */ - AUDIT, - - /** The ida. */ - IDA, - - /** The regstatus. */ - REGSTATUS, - - /** The regsync. */ - REGSYNC, - - /** The machine history. */ - MACHINEHISTORY, - - /** The center history. */ - CENTERHISTORY, - - /** The center-machine-user history. */ - CENTERUSERMACHINEHISTORY, - - /** The sms notifier. */ - SMSNOTIFIER, - - /** The email notifier. */ - EMAILNOTIFIER, - - /** The biodedupeinsert. */ - BIODEDUPEINSERT, - - /** The biodedupepotential. */ - BIODEDUPEPOTENTIAL, - - /** The biodedupe. */ - BIODEDUPE, - - /** The idrepository. */ - IDREPOSITORY, - - /** The idrepository get id by uin. */ - IDREPOGETIDBYUIN, - - /** The uingenerator. */ - UINGENERATOR, - - /** The idrepodev. */ - IDREPODEV, - - /** The Cryptomaanger *. */ - CRYPTOMANAGERDECRYPT, - - ENCRYPTURL, - - IDAUTHENCRYPTION, - - IDAUTHPUBLICKEY, - - IDAUTHCERTIFICATE, - - /** The ReverseDataSync *. */ - REVERSEDATASYNC, - - /** The Device history *. */ - DEVICESHISTORIES, - - /** The Reg center device history *. */ - REGISTRATIONCENTERDEVICEHISTORY, - - /** The registration center timestamp *. */ - REGISTRATIONCENTERTIMESTAMP, - - /** The registration connector *. */ - REGISTRATIONCONNECTOR, - - /** The fullname. */ - FULLNAME, - - /** The residencestatus. */ - RESIDENCESTATUS, - - /** The phone. */ - PHONE, - - /** The email. */ - EMAIL, - - /** The proofofidentity. */ - PROOFOFIDENTITY, - - /** The proofofaddress. */ - PROOFOFADDRESS, - - /** The proofofrelationship. */ - PROOFOFRELATIONSHIP, - - /** The proofofdateofbirth. */ - PROOFOFDATEOFBIRTH, - - /** The introducerbiometrics. */ - INTRODUCERBIOMETRICS, - - /** The idschemaversion. */ - IDSCHEMAVERSION, - - /** The encryptionservice. */ - ENCRYPTIONSERVICE, - - /** The centerdetails. */ - CENTERDETAILS, - - /** The machinedetails. */ - MACHINEDETAILS, - - /** The external service. */ - EISERVICE, - - /** The retrieveidentity. */ - RETRIEVEIDENTITY, - - /** The retrieveidentity using rid. */ - RETRIEVEIDENTITYFROMRID, - - /** The digitalsignature. */ - DIGITALSIGNATURE, - - /** The Language. */ - LANGUAGE, - - /** The Vid creation. */ - CREATEVID, - - /** The user details. */ - USERDETAILS, - - /** get operator rid from id. */ - GETRIDFROMUSERID, - - /** get individualId from userid. */ - GETINDIVIDUALIDFROMUSERID, - - /** The internalauth. */ - INTERNALAUTH, - - /** The templates. */ - TEMPLATES, - - GETUINBYVID, - - DEVICEVALIDATEHISTORY, - - NGINXDMZURL, - - IDSCHEMAURL, - - PACKETMANAGER_SEARCH_FIELD, - PACKETMANAGER_SEARCH_FIELDS, - PACKETMANAGER_SEARCH_METAINFO, - PACKETMANAGER_INFO, - PACKETMANAGER_VALIDATE, - PACKETMANAGER_SEARCH_DOCUMENT, - PACKETMANAGER_SEARCH_BIOMETRICS, - PACKETMANAGER_SEARCH_AUDITS, - PACKETMANAGER_UPDATE_TAGS, - PACKETMANAGER_DELETE_TAGS, - PACKETMANAGER_GET_TAGS, - DATASHARECREATEURL, - PMS, - PARTNERGETBIOEXTRACTOR, - DATASHAREGETEURL, - CREDENTIALREQUEST, GETVIDSBYUIN, - JWTVERIFY, - DEVICEHOTLIST, - IDREPOHASDRAFT, - IDREPOGETDRAFT, - IDREPOCREATEDRAFT, - IDREPOUPDATEDRAFT, - IDREPOPUBLISHDRAFT, - IDREPOEXTRACTBIOMETRICS, - CREDENTIALREQUESTV2; - -} - +package io.mosip.registration.processor.core.code; + +/** + * The Enum ApiName. + * + * @author Rishabh Keshari + */ +public enum ApiName { + + /** The auth. */ + AUTH, + + /** The authinternal. */ + AUTHINTERNAL, + + /** The master data. */ + MASTER, + + /** The iam. */ + IAM, + + /** The audit. */ + AUDIT, + + /** The ida. */ + IDA, + + /** The regstatus. */ + REGSTATUS, + + /** The regsync. */ + REGSYNC, + + /** The machine history. */ + MACHINEHISTORY, + + /** The center history. */ + CENTERHISTORY, + + /** The center-machine-user history. */ + CENTERUSERMACHINEHISTORY, + + /** The sms notifier. */ + SMSNOTIFIER, + + /** The email notifier. */ + EMAILNOTIFIER, + + /** The biodedupeinsert. */ + BIODEDUPEINSERT, + + /** The biodedupepotential. */ + BIODEDUPEPOTENTIAL, + + /** The biodedupe. */ + BIODEDUPE, + + /** The idrepository. */ + IDREPOSITORY, + + /** The idrepository get id by uin. */ + IDREPOGETIDBYUIN, + + /** The uingenerator. */ + UINGENERATOR, + + /** The idrepodev. */ + IDREPODEV, + + /** The Cryptomaanger *. */ + CRYPTOMANAGERDECRYPT, + + ENCRYPTURL, + + IDAUTHENCRYPTION, + + IDAUTHPUBLICKEY, + + IDAUTHCERTIFICATE, + + /** The ReverseDataSync *. */ + REVERSEDATASYNC, + + /** The Device history *. */ + DEVICESHISTORIES, + + /** The Reg center device history *. */ + REGISTRATIONCENTERDEVICEHISTORY, + + /** The registration center timestamp *. */ + REGISTRATIONCENTERTIMESTAMP, + + /** The registration connector *. */ + REGISTRATIONCONNECTOR, + + /** The fullname. */ + FULLNAME, + + /** The residencestatus. */ + RESIDENCESTATUS, + + /** The phone. */ + PHONE, + + /** The email. */ + EMAIL, + + /** The proofofidentity. */ + PROOFOFIDENTITY, + + /** The proofofaddress. */ + PROOFOFADDRESS, + + /** The proofofrelationship. */ + PROOFOFRELATIONSHIP, + + /** The proofofdateofbirth. */ + PROOFOFDATEOFBIRTH, + + /** The introducerbiometrics. */ + INTRODUCERBIOMETRICS, + + /** The idschemaversion. */ + IDSCHEMAVERSION, + + /** The encryptionservice. */ + ENCRYPTIONSERVICE, + + /** The centerdetails. */ + CENTERDETAILS, + + /** The machinedetails. */ + MACHINEDETAILS, + + /** The external service. */ + EISERVICE, + + /** The retrieveidentity. */ + RETRIEVEIDENTITY, + + /** The retrieveidentity using rid. */ + RETRIEVEIDENTITYFROMRID, + + /** The digitalsignature. */ + DIGITALSIGNATURE, + + /** The Language. */ + LANGUAGE, + + /** The Vid creation. */ + CREATEVID, + + /** The user details. */ + USERDETAILS, + + /** get operator rid from id. */ + GETRIDFROMUSERID, + + /** get individualId from userid. */ + GETINDIVIDUALIDFROMUSERID, + + /** The internalauth. */ + INTERNALAUTH, + + /** The templates. */ + TEMPLATES, + + GETUINBYVID, + + DEVICEVALIDATEHISTORY, + + NGINXDMZURL, + + IDSCHEMAURL, + + PACKETMANAGER_SEARCH_FIELD, + PACKETMANAGER_SEARCH_FIELDS, + PACKETMANAGER_SEARCH_METAINFO, + PACKETMANAGER_INFO, + PACKETMANAGER_VALIDATE, + PACKETMANAGER_SEARCH_DOCUMENT, + PACKETMANAGER_SEARCH_BIOMETRICS, + PACKETMANAGER_SEARCH_AUDITS, + PACKETMANAGER_UPDATE_TAGS, + PACKETMANAGER_DELETE_TAGS, + PACKETMANAGER_GET_TAGS, + DATASHARECREATEURL, + PMS, + PARTNERGETBIOEXTRACTOR, + DATASHAREGETEURL, + CREDENTIALREQUEST, GETVIDSBYUIN, + JWTVERIFY, + DEVICEHOTLIST, + IDREPOHASDRAFT, + IDREPOGETDRAFT, + IDREPOCREATEDRAFT, + IDREPOUPDATEDRAFT, + IDREPOPUBLISHDRAFT, + IDREPOEXTRACTBIOMETRICS; + +} + From 1758440a689bd14c3aa44e1c2567bf8e47d73df1 Mon Sep 17 00:00:00 2001 From: Sowmya Ujjappa Banakar Date: Fri, 7 Jul 2023 13:30:23 +0530 Subject: [PATCH 086/133] MOSIP-28217 scripts added --- .../mosip_regprc/sql/1.2.0.1-B1_to_1.2.0.1_rollback.sql | 1 + .../mosip_regprc/sql/1.2.0.1-B1_to_1.2.0.1_upgrade.sql | 1 + 2 files changed, 2 insertions(+) create mode 100644 db_upgrade_scripts/mosip_regprc/sql/1.2.0.1-B1_to_1.2.0.1_rollback.sql create mode 100644 db_upgrade_scripts/mosip_regprc/sql/1.2.0.1-B1_to_1.2.0.1_upgrade.sql diff --git a/db_upgrade_scripts/mosip_regprc/sql/1.2.0.1-B1_to_1.2.0.1_rollback.sql b/db_upgrade_scripts/mosip_regprc/sql/1.2.0.1-B1_to_1.2.0.1_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_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_upgrade.sql b/db_upgrade_scripts/mosip_regprc/sql/1.2.0.1-B1_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-B1_to_1.2.0.1_upgrade.sql @@ -0,0 +1 @@ +\echo 'Upgrade Queries not required for transition from $CURRENT_VERSION to $UPGRADE_VERSION' From 26b9aa3b91c0995565568ea08875e4f3bd686d3f Mon Sep 17 00:00:00 2001 From: Sowmya Ujjappa Banakar Date: Fri, 7 Jul 2023 16:19:59 +0530 Subject: [PATCH 087/133] MOSIP-28217 script renamed --- ...to_1.2.0.1_rollback.sql => 1.2.0.1-B2_to_1.2.0.1_rollback.sql} | 0 ...1_to_1.2.0.1_upgrade.sql => 1.2.0.1-B2_to_1.2.0.1_upgrade.sql} | 0 2 files changed, 0 insertions(+), 0 deletions(-) rename db_upgrade_scripts/mosip_regprc/sql/{1.2.0.1-B1_to_1.2.0.1_rollback.sql => 1.2.0.1-B2_to_1.2.0.1_rollback.sql} (100%) rename db_upgrade_scripts/mosip_regprc/sql/{1.2.0.1-B1_to_1.2.0.1_upgrade.sql => 1.2.0.1-B2_to_1.2.0.1_upgrade.sql} (100%) diff --git a/db_upgrade_scripts/mosip_regprc/sql/1.2.0.1-B1_to_1.2.0.1_rollback.sql b/db_upgrade_scripts/mosip_regprc/sql/1.2.0.1-B2_to_1.2.0.1_rollback.sql similarity index 100% rename from db_upgrade_scripts/mosip_regprc/sql/1.2.0.1-B1_to_1.2.0.1_rollback.sql rename to db_upgrade_scripts/mosip_regprc/sql/1.2.0.1-B2_to_1.2.0.1_rollback.sql diff --git a/db_upgrade_scripts/mosip_regprc/sql/1.2.0.1-B1_to_1.2.0.1_upgrade.sql b/db_upgrade_scripts/mosip_regprc/sql/1.2.0.1-B2_to_1.2.0.1_upgrade.sql similarity index 100% rename from db_upgrade_scripts/mosip_regprc/sql/1.2.0.1-B1_to_1.2.0.1_upgrade.sql rename to db_upgrade_scripts/mosip_regprc/sql/1.2.0.1-B2_to_1.2.0.1_upgrade.sql From 92ff7bc92bf9fade7571522a15d46823f8bab3b2 Mon Sep 17 00:00:00 2001 From: Keshav Mishra Date: Tue, 11 Jul 2023 13:20:30 +0530 Subject: [PATCH 088/133] [DSD-3010] added changes to run nginx in foreground Signed-off-by: Keshav Mishra --- .../init/registration-processor-dmz-packet-server/Dockerfile | 5 +++++ 1 file changed, 5 insertions(+) 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;"] From b8bf08dd3710f190cadefe890b0be9d0d8085103 Mon Sep 17 00:00:00 2001 From: Sowmya Ujjappa Banakar Date: Wed, 12 Jul 2023 14:30:43 +0530 Subject: [PATCH 089/133] MOSIP-28217 script changes --- .../dml/regprc-transaction_type.csv | 36 ------------------- 1 file changed, 36 deletions(-) delete mode 100644 db_upgrade_scripts/mosip_regprc/dml/regprc-transaction_type.csv diff --git a/db_upgrade_scripts/mosip_regprc/dml/regprc-transaction_type.csv b/db_upgrade_scripts/mosip_regprc/dml/regprc-transaction_type.csv deleted file mode 100644 index 8b812c5e06e..00000000000 --- a/db_upgrade_scripts/mosip_regprc/dml/regprc-transaction_type.csv +++ /dev/null @@ -1,36 +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() -MANUAL_VERIFICATION,transaction done,eng,TRUE,MOSIP_SYSTEM,now() -VERIFICATION,transaction done,eng,TRUE,MOSIP_SYSTEM,now() From 2763e75a65f5e23af8ed4bbb9ca6ab19caca97a4 Mon Sep 17 00:00:00 2001 From: Sowmya Ujjappa Banakar Date: Wed, 12 Jul 2023 18:42:19 +0530 Subject: [PATCH 090/133] Removed DB health check for camel --- .../core/abstractverticle/MosipVerticleAPIManager.java | 2 ++ 1 file changed, 2 insertions(+) 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 0ff829c06a1..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 @@ -162,7 +162,9 @@ public void configureHealthCheckEndpoint(Vertx vertx, Router router, final Strin } healthCheckHandler.register("diskSpace", healthCheckTimeOut, healthCheckHandler::dispSpaceHealthChecker); + if (!servletPath.contains("camel")) { healthCheckHandler.register("db", healthCheckTimeOut, healthCheckHandler::databaseHealthChecker); + } } private boolean checkServletPath(String servletPath) { From b83d2faea04f63421bf2fa1a5b300a321baecd37 Mon Sep 17 00:00:00 2001 From: Sowmya Ujjappa Banakar Date: Fri, 14 Jul 2023 18:21:47 +0530 Subject: [PATCH 091/133] MOSIP-28478 Code fix --- .../abis/handler/stage/AbisHandlerStage.java | 1584 +++++++++-------- .../stage/test/AbisHandlerStageTest.java | 8 +- 2 files changed, 816 insertions(+), 776 deletions(-) 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 7eb95b004ad..8877edcfeb9 100644 --- a/registration-processor/core-processor/registration-processor-abis-handler-stage/src/main/java/io/mosip/registration/processor/abis/handler/stage/AbisHandlerStage.java +++ b/registration-processor/core-processor/registration-processor-abis-handler-stage/src/main/java/io/mosip/registration/processor/abis/handler/stage/AbisHandlerStage.java @@ -1,775 +1,811 @@ -package io.mosip.registration.processor.abis.handler.stage; - -import java.io.IOException; -import java.net.URL; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.Set; -import java.util.UUID; -import java.util.stream.Collectors; - -import io.mosip.kernel.core.util.StringUtils; -import io.mosip.registration.processor.packet.storage.utils.PacketManagerService; -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.cloud.context.config.annotation.RefreshScope; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.core.env.Environment; -import org.springframework.core.io.ByteArrayResource; -import org.springframework.http.MediaType; -import org.springframework.stereotype.Service; -import org.springframework.util.CollectionUtils; -import org.springframework.util.LinkedMultiValueMap; -import org.springframework.util.MultiValueMap; - -import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.JsonMappingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.google.common.collect.Lists; - -import io.mosip.kernel.biometrics.constant.BiometricType; -import io.mosip.kernel.biometrics.entities.BIR; -import io.mosip.kernel.biometrics.entities.BiometricRecord; -import io.mosip.kernel.biometrics.spi.CbeffUtil; -import io.mosip.kernel.core.logger.spi.Logger; -import io.mosip.kernel.core.util.DateUtils; -import io.mosip.kernel.core.util.JsonUtils; -import io.mosip.kernel.core.util.exception.JsonProcessingException; -import io.mosip.registration.processor.abis.handler.constant.AbisHandlerStageConstant; -import io.mosip.registration.processor.abis.handler.dto.DataShareResponseDto; -import io.mosip.registration.processor.core.packet.dto.datashare.Filter; -import io.mosip.registration.processor.core.packet.dto.datashare.ShareableAttributes; -import io.mosip.registration.processor.core.packet.dto.datashare.Source; -import io.mosip.registration.processor.abis.handler.exception.AbisHandlerException; -import io.mosip.registration.processor.abis.handler.exception.DataShareException; -import io.mosip.registration.processor.abis.queue.dto.AbisQueueDetails; -import io.mosip.registration.processor.core.abstractverticle.MessageBusAddress; -import io.mosip.registration.processor.core.abstractverticle.MessageDTO; -import io.mosip.registration.processor.core.abstractverticle.MosipEventBus; -import io.mosip.registration.processor.core.abstractverticle.MosipRouter; -import io.mosip.registration.processor.core.abstractverticle.MosipVerticleAPIManager; -import io.mosip.registration.processor.core.code.AbisStatusCode; -import io.mosip.registration.processor.core.code.ApiName; -import io.mosip.registration.processor.core.code.EventId; -import io.mosip.registration.processor.core.code.EventName; -import io.mosip.registration.processor.core.code.EventType; -import io.mosip.registration.processor.core.code.ModuleName; -import io.mosip.registration.processor.core.code.RegistrationTransactionStatusCode; -import io.mosip.registration.processor.core.constant.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.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.packet.dto.abis.AbisIdentifyRequestDto; -import io.mosip.registration.processor.core.packet.dto.abis.AbisIdentifyRequestGalleryDto; -import io.mosip.registration.processor.core.packet.dto.abis.AbisInsertRequestDto; -import io.mosip.registration.processor.core.packet.dto.abis.AbisRequestDto; -import io.mosip.registration.processor.core.packet.dto.abis.Flag; -import io.mosip.registration.processor.core.packet.dto.abis.ReferenceIdDto; -import io.mosip.registration.processor.core.packet.dto.abis.RegBioRefDto; -import io.mosip.registration.processor.core.packet.dto.abis.RegDemoDedupeListDto; -import io.mosip.registration.processor.core.spi.packetmanager.PacketInfoManager; -import io.mosip.registration.processor.core.spi.restclient.RegistrationProcessorRestClientService; -import io.mosip.registration.processor.core.status.util.StatusUtil; -import io.mosip.registration.processor.core.status.util.TrimExceptionMessage; -import io.mosip.registration.processor.core.util.JsonUtil; -import io.mosip.registration.processor.packet.storage.dto.ApplicantInfoDto; -import io.mosip.registration.processor.packet.storage.utils.PriorityBasedPacketManagerService; -import io.mosip.registration.processor.packet.storage.utils.Utilities; -import io.mosip.registration.processor.rest.client.audit.builder.AuditLogRequestBuilder; -import io.mosip.registration.processor.status.dto.InternalRegistrationStatusDto; -import io.mosip.registration.processor.status.dto.RegistrationStatusDto; -import io.mosip.registration.processor.status.service.RegistrationStatusService; - -/** - * The Class AbisHandlerStage. - * - * @author M1048358 Alok - */ -@RefreshScope -@Service -@Configuration -@ComponentScan(basePackages = { "${mosip.auth.adapter.impl.basepackage}", - "io.mosip.registration.processor.abis.handler.config", - "io.mosip.registration.processor.status.config", "io.mosip.registration.processor.rest.client.config", - "io.mosip.registration.processor.packet.storage.config", "io.mosip.registration.processor.core.config", - "io.mosip.registration.processor.core.kernel.beans", "io.mosip.kernel.packetmanager.config" }) -public class AbisHandlerStage extends MosipVerticleAPIManager { - - private static final String STAGE_PROPERTY_PREFIX = "mosip.regproc.abis.handler."; - private Map> typeAndSubTypeMap = new HashMap<>(); - LinkedHashMap datasharePolicies = null; - - /** The cluster manager url. */ - @Value("${vertx.cluster.configuration}") - private String clusterManagerUrl; - - /** The max results. */ - @Value("${registration.processor.abis.maxResults}") - private String maxResults; - - /** The target FPIR. */ - @Value("${registration.processor.abis.targetFPIR}") - private String targetFPIR; - - /** worker pool size. */ - @Value("${worker.pool.size}") - private Integer workerPoolSize; - - /** - * After this time intervel, message should be considered as expired (In - * seconds). - */ - @Value("${mosip.regproc.abis.handler.message.expiry-time-limit}") - private Long messageExpiryTimeLimit; - - @Value("${registration.processor.policy.id}") - private String policyId; - - @Value("${registration.processor.subscriber.id}") - private String subscriberId; - - @Value("${mosip.regproc.data.share.protocol}") - private String httpProtocol; - - @Value("${mosip.regproc.data.share.internal.domain.name}") - private String internalDomainName; - - @Value("#{${mosip.regproc.abis.handler.biometric-modalities-segments-mapping.INFANT}}") - private Map> biometricModalitySegmentsMapInfant; - - @Value("#{${mosip.regproc.abis.handler.biometric-modalities-segments-mapping.MINOR}}") - private Map> biometricModalitySegmentsMapMinor; - - @Value("#{${mosip.regproc.abis.handler.biometric-modalities-segments-mapping.ADULT}}") - private Map> biometricModalitySegmentsMapAdult; - - @Value("#{${mosip.regproc.abis.handler.biometric-segments-exceptions-mapping}}") - private Map exceptionSegmentsMap; - - @Autowired - private RegistrationProcessorRestClientService registrationProcessorRestClientService; - - /** The reg proc logger. */ - private static Logger regProcLogger = RegProcessorLogger.getLogger(AbisHandlerStage.class); - - /** The core audit request builder. */ - @Autowired - private AuditLogRequestBuilder auditLogRequestBuilder; - - /** The registration status service. */ - @Autowired - private RegistrationStatusService registrationStatusService; - - /** The packet info manager. */ - @Autowired - private PacketInfoManager packetInfoManager; - - @Autowired - private PacketManagerService packetManagerService; - - @Autowired - private Utilities utility; - - @Autowired - private ObjectMapper mapper; - - /** The mosip event bus. */ - MosipEventBus mosipEventBus = null; - - /** Mosip router for APIs */ - @Autowired - MosipRouter router; - - @Autowired - private CbeffUtil cbeffutil; - - @Autowired - private Environment env; - - @Autowired - private PriorityBasedPacketManagerService priorityBasedPacketManagerService; - - private static final String DATASHARECREATEURL = "DATASHARECREATEURL"; - - private static final String DATETIME_PATTERN = "mosip.registration.processor.datetime.pattern"; - - /** - * Deploy verticle. - */ - public void deployVerticle() { - mosipEventBus = this.getEventBus(this, clusterManagerUrl, workerPoolSize); - this.consumeAndSend(mosipEventBus, MessageBusAddress.ABIS_HANDLER_BUS_IN, - MessageBusAddress.ABIS_HANDLER_BUS_OUT, messageExpiryTimeLimit); - } - - @Override - public void start() { - router.setRoute(this.postUrl(getVertx(), MessageBusAddress.ABIS_HANDLER_BUS_IN, - MessageBusAddress.ABIS_HANDLER_BUS_OUT)); - this.createServer(router.getRouter(), getPort()); - } - - @Override - protected String getPropertyPrefix() { - return STAGE_PROPERTY_PREFIX; - } - - /* - * (non-Javadoc) - * - * @see - * io.mosip.registration.processor.core.spi.eventbus.EventBusManager#process( - * java.lang.Object) - */ - @Override - public MessageDTO process(MessageDTO object) { - TrimExceptionMessage trimExceptionMessage = new TrimExceptionMessage(); - LogDescription description = new LogDescription(); - object.setMessageBusAddress(MessageBusAddress.ABIS_HANDLER_BUS_IN); - object.setIsValid(Boolean.TRUE); - Boolean isTransactionSuccessful = false; - String regId = object.getRid(); - object.setInternalError(Boolean.FALSE); - InternalRegistrationStatusDto registrationStatusDto = null; - String transactionTypeCode = null; - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - regId, "AbisHandlerStage::process()::entry"); - try { - registrationStatusDto = registrationStatusService.getRegistrationStatus(regId, object.getReg_type(), - object.getIteration(), object.getWorkflowInstanceId()); - transactionTypeCode = registrationStatusDto.getLatestTransactionTypeCode(); - String transactionId = registrationStatusDto.getLatestRegistrationTransactionId(); - - Boolean isIdentifyRequestPresent = packetInfoManager.getIdentifyByTransactionId(transactionId, - AbisHandlerStageConstant.IDENTIFY); - - if (!isIdentifyRequestPresent) { - List abisQueueDetails = utility.getAbisQueueDetails(); - if (abisQueueDetails.isEmpty()) { - description.setStatusComment(AbisHandlerStageConstant.DETAILS_NOT_FOUND); - description.setMessage(PlatformErrorMessages.RPR_DETAILS_NOT_FOUND.getMessage()); - description.setCode(PlatformErrorMessages.RPR_DETAILS_NOT_FOUND.getCode()); - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), - LoggerFileConstant.REGISTRATIONID.toString(), "", - AbisHandlerStageConstant.DETAILS_NOT_FOUND); - throw new AbisHandlerException(PlatformErrorMessages.RPR_ABIS_INTERNAL_ERROR.getCode()); - } - createRequest(regId, abisQueueDetails, transactionId, registrationStatusDto.getRegistrationType(),registrationStatusDto.getIteration(), - registrationStatusDto.getWorkflowInstanceId(), description, transactionTypeCode); - object.setMessageBusAddress(MessageBusAddress.ABIS_MIDDLEWARE_BUS_IN); - } else { - if (transactionTypeCode.equalsIgnoreCase(AbisHandlerStageConstant.DEMOGRAPHIC_VERIFICATION)) { - object.setMessageBusAddress(MessageBusAddress.DEMO_DEDUPE_BUS_IN); - } else if (transactionTypeCode.equalsIgnoreCase(AbisHandlerStageConstant.BIOGRAPHIC_VERIFICATION)) { - object.setMessageBusAddress(MessageBusAddress.BIO_DEDUPE_BUS_IN); - } - } - description.setStatusComment(AbisHandlerStageConstant.ABIS_HANDLER_SUCCESS); - description.setMessage(PlatformSuccessMessages.RPR_ABIS_HANDLER_STAGE_SUCCESS.getMessage()); - description.setCode(PlatformSuccessMessages.RPR_ABIS_HANDLER_STAGE_SUCCESS.getCode()); - isTransactionSuccessful = true; - regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - regId, description.getMessage()); - } catch (Exception e) { - - if (e instanceof DataShareException) { - object.setIsValid(false); - } - description.setStatusComment(AbisHandlerStageConstant.ERROR_IN_ABIS_HANDLER); - description.setMessage(PlatformErrorMessages.RPR_MESSAGE_SENDER_STAGE_FAILED.getMessage()); - description.setCode(PlatformErrorMessages.RPR_MESSAGE_SENDER_STAGE_FAILED.getCode()); - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - regId, ExceptionUtils.getStackTrace(e)); - object.setInternalError(Boolean.TRUE); - registrationStatusDto - .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.REPROCESS.toString()); - registrationStatusDto.setSubStatusCode(StatusUtil.SYSTEM_EXCEPTION_OCCURED.getCode()); - if (transactionTypeCode.equalsIgnoreCase(AbisHandlerStageConstant.DEMOGRAPHIC_VERIFICATION)) { - registrationStatusDto.setRegistrationStageName(AbisHandlerStageConstant.DEMO_DEDUPE_STAGE); - } else if (transactionTypeCode.equalsIgnoreCase(AbisHandlerStageConstant.BIOGRAPHIC_VERIFICATION)) { - registrationStatusDto.setRegistrationStageName(AbisHandlerStageConstant.BIO_DEDUPE_STAGE); - } - registrationStatusDto.setStatusComment(trimExceptionMessage - .trimExceptionMessage(StatusUtil.UNKNOWN_EXCEPTION_OCCURED.getMessage() + e.getMessage())); - String moduleId = description.getCode(); - String moduleName = ModuleName.ABIS_HANDLER.toString(); - registrationStatusService.updateRegistrationStatus(registrationStatusDto, moduleId, moduleName); - } finally { - if (object.getInternalError()) { - updateErrorFlags(registrationStatusDto, object); - } - String eventId = isTransactionSuccessful ? EventId.RPR_402.toString() : EventId.RPR_405.toString(); - String eventName = isTransactionSuccessful ? EventName.UPDATE.toString() : EventName.EXCEPTION.toString(); - String eventType = isTransactionSuccessful ? EventType.BUSINESS.toString() : EventType.SYSTEM.toString(); - - /** Module-Id can be Both Success/Error code */ - String moduleId = isTransactionSuccessful ? PlatformSuccessMessages.RPR_ABIS_HANDLER_STAGE_SUCCESS.getCode() - : description.getCode(); - String moduleName = ModuleName.ABIS_HANDLER.toString(); - - auditLogRequestBuilder.createAuditRequestBuilder(description.getMessage(), eventId, eventName, eventType, - moduleId, moduleName, regId); - - } - - return object; - } - - private void createRequest(String regId, List abisQueueDetails, String transactionId, - String process, int iteration, String workflowInstanceId, LogDescription description, String transactionTypeCode) throws Exception { - String bioRefId = getUUID(); - insertInBioRef(regId, bioRefId,process,iteration, workflowInstanceId); - createInsertRequest(abisQueueDetails, transactionId, bioRefId, regId, process, description); - createIdentifyRequest(abisQueueDetails, transactionId, bioRefId, transactionTypeCode, description); - - } - - /** - * Creates the identify request. - * - * @param abisQueueDetails the abis application dto list - * @param transactionId the transaction id - * @param bioRefId the bio ref id - * @param transactionTypeCode the transaction type code - * @param description - */ - private void createIdentifyRequest(List abisQueueDetails, String transactionId, String bioRefId, - String transactionTypeCode, LogDescription description) { - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", - "AbisHandlerStage::createIdentifyRequest()::entry"); - String batchId = getUUID(); - for (AbisQueueDetails abisQueue : abisQueueDetails) { - AbisRequestDto abisRequestDto = new AbisRequestDto(); - String id = getUUID(); - abisRequestDto.setId(id); - abisRequestDto.setAbisAppCode(abisQueue.getName()); - abisRequestDto.setBioRefId(bioRefId); - abisRequestDto.setRequestType(AbisHandlerStageConstant.IDENTIFY); - abisRequestDto.setReqBatchId(batchId); - abisRequestDto.setRefRegtrnId(transactionId); - - byte[] abisIdentifyRequestBytes = getIdentifyRequestBytes(transactionId, bioRefId, transactionTypeCode, id, - description); - abisRequestDto.setReqText(abisIdentifyRequestBytes); - - abisRequestDto.setStatusCode(RegistrationTransactionStatusCode.IN_PROGRESS.toString()); - abisRequestDto.setStatusComment(null); - abisRequestDto.setLangCode(AbisHandlerStageConstant.ENG); - abisRequestDto.setCrBy(AbisHandlerStageConstant.USER); - abisRequestDto.setUpdBy(null); - abisRequestDto.setIsDeleted(Boolean.FALSE); - - String moduleId = PlatformSuccessMessages.RPR_ABIS_HANDLER_STAGE_SUCCESS.getCode(); - String moduleName = ModuleName.ABIS_HANDLER.toString(); - packetInfoManager.saveAbisRequest(abisRequestDto, moduleId, moduleName); - } - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", - "AbisHandlerStage::createIdentifyRequest()::exit"); - } - - /** - * Gets the identify request bytes. - * - * @param transactionId the transaction id - * @param bioRefId the bio ref id - * @param transactionTypeCode the transaction type code - * @param id the id - * @param description - * @return the identify request bytes - */ - private byte[] getIdentifyRequestBytes(String transactionId, String bioRefId, String transactionTypeCode, String id, - LogDescription description) { - AbisIdentifyRequestDto abisIdentifyRequestDto = new AbisIdentifyRequestDto(); - Flag flag = new Flag(); - abisIdentifyRequestDto.setId(AbisHandlerStageConstant.MOSIP_ABIS_IDENTIFY); - abisIdentifyRequestDto.setVersion(AbisHandlerStageConstant.VERSION); - abisIdentifyRequestDto.setRequestId(id); - abisIdentifyRequestDto.setReferenceId(bioRefId); - abisIdentifyRequestDto.setReferenceUrl(""); - abisIdentifyRequestDto.setRequesttime(DateUtils.getUTCCurrentDateTimeString(env.getProperty(DATETIME_PATTERN))); - flag.setMaxResults(maxResults); - flag.setTargetFPIR(targetFPIR); - abisIdentifyRequestDto.setFlags(flag); - - // Added Gallery data for demo dedupe - if (transactionTypeCode.equalsIgnoreCase(AbisHandlerStageConstant.DEMOGRAPHIC_VERIFICATION)) { - List regDemoDedupeListDtoList = packetInfoManager - .getDemoListByTransactionId(transactionId); - if (regDemoDedupeListDtoList.isEmpty()) { - description.setStatusComment(AbisHandlerStageConstant.NO_RECORD_FOUND); - description.setMessage(PlatformErrorMessages.RPR_NO_RECORD_FOUND.getMessage()); - description.setCode(PlatformErrorMessages.RPR_NO_RECORD_FOUND.getCode()); - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), - LoggerFileConstant.REGISTRATIONID.toString(), "", - "Potential Match Records are Not Found for Demo Dedupe Potential Match"); - throw new AbisHandlerException(description.getMessage()); - } - List referenceIdDtos = new ArrayList<>(); - - for (RegDemoDedupeListDto dedupeListDto : regDemoDedupeListDtoList) { - ReferenceIdDto dto = new ReferenceIdDto(); - List regBioRefDto = packetInfoManager.getBioRefIdByRegId(dedupeListDto.getMatchedRegId()); - if (!CollectionUtils.isEmpty(regBioRefDto)) { - dto.setReferenceId(regBioRefDto.get(0).getBioRefId()); - } - - referenceIdDtos.add(dto); - } - AbisIdentifyRequestGalleryDto galleryDto = new AbisIdentifyRequestGalleryDto(); - galleryDto.setReferenceIds(referenceIdDtos); - abisIdentifyRequestDto.setGallery(galleryDto); - } - - try { - String jsonString = JsonUtils.javaObjectToJsonString(abisIdentifyRequestDto); - return jsonString.getBytes(); - } catch (JsonProcessingException e) { - description.setStatusComment(AbisHandlerStageConstant.ERROR_IN_ABIS_HANDLER_IDENTIFY_REQUEST); - description.setMessage(PlatformErrorMessages.RPR_ERROR_IN_ABIS_HANDLER_IDENTIFY_REQUEST.getMessage()); - description.setCode(PlatformErrorMessages.RPR_ERROR_IN_ABIS_HANDLER_IDENTIFY_REQUEST.getCode()); - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - "", AbisHandlerStageConstant.ERROR_IN_ABIS_HANDLER_IDENTIFY_REQUEST); - throw new AbisHandlerException(PlatformErrorMessages.RPR_ABIS_INTERNAL_ERROR.getCode(), e); - } - } - - /** - * Insert in bio ref. - * - * @param regId the reg id - * @param bioRefId the bio ref id - */ - private void insertInBioRef(String regId, String bioRefId, String process, int iteration, String workflowInstanceId) { - RegBioRefDto regBioRefDto = new RegBioRefDto(); - regBioRefDto.setBioRefId(bioRefId); - regBioRefDto.setCrBy(AbisHandlerStageConstant.USER); - regBioRefDto.setIsActive(Boolean.TRUE); - regBioRefDto.setIsDeleted(Boolean.FALSE); - regBioRefDto.setRegId(regId); - regBioRefDto.setUpdBy(null); - regBioRefDto.setProcess(process); - regBioRefDto.setIteration(iteration); - regBioRefDto.setWorkflowInstanceId(workflowInstanceId); - String moduleId = PlatformSuccessMessages.RPR_ABIS_HANDLER_STAGE_SUCCESS.getCode(); - String moduleName = ModuleName.ABIS_HANDLER.toString(); - packetInfoManager.saveBioRef(regBioRefDto, moduleId, moduleName); - } - - /** - * Creates the insert request. - * - * @param abisQueueDetails the abis application dto list - * @param transactionId the transaction id - * @param bioRefId the bio ref id - * @param regId the reg id - * @param description - */ - private void createInsertRequest(List abisQueueDetails, String transactionId, String bioRefId, - String regId, String process, LogDescription description) throws Exception { - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - regId, "AbisHandlerStage::createInsertRequest()::entry"); - String batchId = getUUID(); - List abisProcessedInsertAppCodeList = packetInfoManager.getAbisProcessedRequestsAppCodeByBioRefId( - bioRefId, AbisStatusCode.INSERT.toString(), AbisStatusCode.PROCESSED.toString()); - List abisAppCodeList = new ArrayList<>(); - for (AbisQueueDetails abisQueue : abisQueueDetails) { - abisAppCodeList.add(abisQueue.getName()); - } - - for (String appCode : abisAppCodeList) { - - AbisRequestDto abisRequestDto = new AbisRequestDto(); - String id = getUUID(); - abisRequestDto.setId(id); - abisRequestDto.setAbisAppCode(appCode); - abisRequestDto.setBioRefId(bioRefId); - abisRequestDto.setRequestType(AbisHandlerStageConstant.INSERT); - abisRequestDto.setReqBatchId(batchId); - abisRequestDto.setRefRegtrnId(transactionId); - - - abisRequestDto.setStatusCode(AbisStatusCode.IN_PROGRESS.toString()); - abisRequestDto.setStatusComment(null); - abisRequestDto.setLangCode(AbisHandlerStageConstant.ENG); - abisRequestDto.setCrBy(AbisHandlerStageConstant.USER); - abisRequestDto.setUpdBy(null); - abisRequestDto.setIsDeleted(Boolean.FALSE); - String moduleId = PlatformSuccessMessages.RPR_ABIS_HANDLER_STAGE_SUCCESS.getCode(); - String moduleName = ModuleName.ABIS_HANDLER.toString(); - byte[] abisInsertRequestBytes =null; - if (abisProcessedInsertAppCodeList != null && abisProcessedInsertAppCodeList.contains(appCode)) { - - abisInsertRequestBytes = getInsertRequestBytes(regId, id, process, bioRefId, description, - AbisStatusCode.ALREADY_PROCESSED.toString()); - abisRequestDto.setStatusCode(AbisStatusCode.ALREADY_PROCESSED.toString()); - - } else { - abisInsertRequestBytes = getInsertRequestBytes(regId, id, process, bioRefId, description, - AbisStatusCode.IN_PROGRESS.toString()); - abisRequestDto.setStatusCode(AbisStatusCode.IN_PROGRESS.toString()); - - } - abisRequestDto.setReqText(abisInsertRequestBytes); - packetInfoManager.saveAbisRequest(abisRequestDto, moduleId, moduleName); - } - - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", - "AbisHandlerStage::createInsertRequest()::exit"); - } - - /** - * Gets the insert request bytes. - * - * @param regId the reg id - * @param id the id - * @param bioRefId the bio ref id - * @param description - * @param status - * @return the insert request bytes - */ - private byte[] getInsertRequestBytes(String regId, String id, String process, String bioRefId, - LogDescription description, String status) throws Exception { - AbisInsertRequestDto abisInsertRequestDto = new AbisInsertRequestDto(); - abisInsertRequestDto.setId(AbisHandlerStageConstant.MOSIP_ABIS_INSERT); - abisInsertRequestDto.setReferenceId(bioRefId); - abisInsertRequestDto.setReferenceURL(status.equalsIgnoreCase(AbisStatusCode.IN_PROGRESS.toString())?getDataShareUrl(regId, process):null); - abisInsertRequestDto.setRequestId(id); - abisInsertRequestDto.setRequesttime(DateUtils.getUTCCurrentDateTimeString(env.getProperty(DATETIME_PATTERN))); - abisInsertRequestDto.setVersion(AbisHandlerStageConstant.VERSION); - try { - String jsonString = JsonUtils.javaObjectToJsonString(abisInsertRequestDto); - return jsonString.getBytes(); - } catch (JsonProcessingException e) { - description.setStatusComment(AbisHandlerStageConstant.ERROR_IN_ABIS_HANDLER_IDENTIFY_REQUEST); - description.setMessage(PlatformErrorMessages.RPR_ERROR_IN_ABIS_HANDLER_IDENTIFY_REQUEST.getMessage()); - description.setCode(PlatformErrorMessages.RPR_ERROR_IN_ABIS_HANDLER_IDENTIFY_REQUEST.getCode()); - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - "", AbisHandlerStageConstant.ERROR_IN_ABIS_HANDLER_IDENTIFY_REQUEST); - throw new AbisHandlerException(PlatformErrorMessages.RPR_ABIS_INTERNAL_ERROR.getCode(), e); - } - } - - /** - * Gets the uuid. - * - * @return the uuid - */ - private String getUUID() { - return UUID.randomUUID().toString(); - } - - private String getDataShareUrl(String id, String process) throws Exception { - Map> typeAndSubtypMap = createTypeSubtypeMapping(); - List modalities = new ArrayList<>(); - for (Map.Entry> entry : typeAndSubtypMap.entrySet()) { - if (entry.getValue() == null) { - modalities.add(entry.getKey()); - } else { - modalities.addAll(entry.getValue()); - } - } - JSONObject regProcessorIdentityJson = utility - .getRegistrationProcessorMappingJson(MappingJsonConstants.IDENTITY); - String individualBiometricsLabel = JsonUtil.getJSONValue( - JsonUtil.getJSONObject(regProcessorIdentityJson, MappingJsonConstants.INDIVIDUAL_BIOMETRICS), - MappingJsonConstants.VALUE); - BiometricRecord biometricRecord = priorityBasedPacketManagerService.getBiometrics(id, individualBiometricsLabel, - modalities, process, ProviderStageName.BIO_DEDUPE); - - Map tags = packetManagerService.getAllTags(id); - String ageGroup = tags.get("AGE_GROUP"); - - if (ageGroup.equalsIgnoreCase("INFANT")) { - validateBiometricRecord(biometricRecord, modalities, biometricModalitySegmentsMapInfant, - priorityBasedPacketManagerService.getMetaInfo(id, process, ProviderStageName.BIO_DEDUPE)); - } else if (ageGroup.equalsIgnoreCase("MINOR")) { - validateBiometricRecord(biometricRecord, modalities, biometricModalitySegmentsMapMinor, - priorityBasedPacketManagerService.getMetaInfo(id, process, ProviderStageName.BIO_DEDUPE)); - } else if (ageGroup.equalsIgnoreCase("ADULT")) { - validateBiometricRecord(biometricRecord, modalities, biometricModalitySegmentsMapAdult, - priorityBasedPacketManagerService.getMetaInfo(id, process, ProviderStageName.BIO_DEDUPE)); - } else { - validateBiometricRecord(biometricRecord, modalities, biometricModalitySegmentsMapAdult, - priorityBasedPacketManagerService.getMetaInfo(id, process, ProviderStageName.BIO_DEDUPE)); - } - - byte[] content = cbeffutil.createXML(filterExceptionBiometrics(biometricRecord).getSegments()); - - MultiValueMap map = new LinkedMultiValueMap<>(); - map.add("name", individualBiometricsLabel); - map.add("filename", individualBiometricsLabel); - - ByteArrayResource contentsAsResource = new ByteArrayResource(content) { - @Override - public String getFilename() { - return individualBiometricsLabel; - } - }; - map.add("file", contentsAsResource); - - List pathSegments = new ArrayList<>(); - pathSegments.add(policyId); - pathSegments.add(subscriberId); - String protocol = StringUtils.isNotEmpty(httpProtocol) ? PolicyConstant.HTTP_PROTOCOL : PolicyConstant.HTTPS_PROTOCOL; - String url = null; - - if (!CollectionUtils.isEmpty(datasharePolicies) && datasharePolicies.get(PolicyConstant.SHAREDOMAIN_WRITE) != null) - url = datasharePolicies.get(PolicyConstant.SHAREDOMAIN_WRITE) + env.getProperty(ApiName.DATASHARECREATEURL.name()); - else - url = protocol + internalDomainName + env.getProperty(ApiName.DATASHARECREATEURL.name()); - url = url.replaceAll("[\\[\\]]", ""); - DataShareResponseDto response = (DataShareResponseDto) registrationProcessorRestClientService.postApi(url, - MediaType.MULTIPART_FORM_DATA, pathSegments, null, null, map, DataShareResponseDto.class); - if (response == null || (response.getErrors() != null && response.getErrors().size() > 0)) - throw new DataShareException( - response == null ? "Datashare response is null" : response.getErrors().get(0).getMessage()); - - return response.getDataShare().getUrl(); - } - - @SuppressWarnings("deprecation") - private void validateBiometricRecord(BiometricRecord biometricRecord, List modalities, - Map> biometricModalitySegmentsMap, Map metaInfoMap) - throws DataShareException, JsonParseException, JsonMappingException, IOException { - if (modalities == null || modalities.isEmpty()) { - throw new DataShareException("Data Share Policy Modalities were Empty"); - } - if (biometricRecord == null || biometricRecord.getSegments() == null - || biometricRecord.getSegments().isEmpty()) { - throw new DataShareException("No Biometrics Found with Data Share Policy"); - } - Map> metaInfoExceptionBiometrics = metaInfoMap != null - && metaInfoMap.containsKey("exceptionBiometrics") - ? mapper.readValue(metaInfoMap.get("exceptionBiometrics"), - new TypeReference>>() { - }) - : null; - Set exceptionList = null; - if (metaInfoExceptionBiometrics != null && metaInfoExceptionBiometrics.containsKey("applicant")) { - exceptionList = metaInfoExceptionBiometrics.get("applicant").keySet(); - } - boolean isBioFound = false; - for (String biometricSegment : biometricModalitySegmentsMap.keySet()) { - if (!modalities.contains(biometricSegment)) { - throw new DataShareException("Biometrics Segments Not Configured for modality : " + biometricSegment); - } - for (String segment : biometricModalitySegmentsMap.get(biometricSegment)) { - Optional optionalBIR = Optional.empty(); - if (segment.equalsIgnoreCase("Face")) { - optionalBIR = biometricRecord.getSegments().stream() - .filter(bir -> bir.getBdbInfo().getType() != null - && bir.getBdbInfo().getType().get(0).equals(BiometricType.FACE)) - .findFirst(); - } else { - String[] segmentArray = segment.split(" "); - optionalBIR = biometricRecord.getSegments().stream() - .filter(bir -> bir.getBdbInfo().getSubtype()!=null && bir.getBdbInfo().getSubtype().size() == segmentArray.length - ? (bir.getBdbInfo().getSubtype().get(0).equalsIgnoreCase(segmentArray[0]) - && (segmentArray.length == 2 - ? bir.getBdbInfo().getSubtype().get(1) - .equalsIgnoreCase(segmentArray[1]) - : true)) - : false) - .findFirst(); - } - if (optionalBIR.isPresent()) { - BIR bir = optionalBIR.get(); - Map othersMap = new HashMap(); - if (bir.getOthers() != null) { - othersMap = bir.getOthers().entrySet().stream() - .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue())); - } - - if (bir.getBdb() != null) { - isBioFound = true; - } else if ((othersMap == null || !othersMap.containsKey("EXCEPTION")) ? true - : !(Boolean.parseBoolean(othersMap.get("EXCEPTION")))) { - throw new DataShareException("Biometric BDB Not Found : " + segment); - } - } else if (exceptionList == null || !exceptionList.contains(exceptionSegmentsMap.get(segment))) { - throw new DataShareException("Biometrics/Exceptions Not Found : " + segment); - } - } - } - if (!isBioFound) { - throw new DataShareException("No Biometric Matched with Data Share Policy"); - } - } - - private BiometricRecord filterExceptionBiometrics(BiometricRecord biometricRecord) { - List segments = biometricRecord.getSegments().stream().filter(bio -> { - Map othersMap = bio.getOthers().entrySet().stream() - .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue())); - return (othersMap == null || !othersMap.containsKey("EXCEPTION")) ? true - : !(Boolean.parseBoolean(othersMap.get("EXCEPTION"))); - }).collect(Collectors.toList()); - BiometricRecord biorecord = new BiometricRecord(); - biorecord.setSegments(segments); - return biorecord; - } - - public Map> createTypeSubtypeMapping() throws ApisResourceAccessException, DataShareException, - IOException { - - // Call only once and use cache - if (!CollectionUtils.isEmpty(typeAndSubTypeMap) && !CollectionUtils.isEmpty(datasharePolicies)) - return typeAndSubTypeMap; - - ResponseWrapper policyResponse = (ResponseWrapper) registrationProcessorRestClientService.getApi( - ApiName.PMS, Lists.newArrayList(policyId, PolicyConstant.PARTNER_ID, subscriberId), "", "", - ResponseWrapper.class); - if (policyResponse == null || (policyResponse.getErrors() != null && policyResponse.getErrors().size() > 0)) { - throw new DataShareException(policyResponse == null ? "Policy Response response is null" - : policyResponse.getErrors().get(0).getMessage()); - - } else { - LinkedHashMap responseMap = (LinkedHashMap) policyResponse.getResponse(); - LinkedHashMap policies = (LinkedHashMap) responseMap - .get(PolicyConstant.POLICIES); - List attributes = (List) policies.get(PolicyConstant.SHAREABLE_ATTRIBUTES); - datasharePolicies = (LinkedHashMap) policies.get(PolicyConstant.DATASHARE_POLICIES); - ShareableAttributes shareableAttributes = mapper.readValue(mapper.writeValueAsString(attributes.get(0)), - ShareableAttributes.class); - for (Source source : shareableAttributes.getSource()) { - List filterList = source.getFilter(); - if (filterList != null && !filterList.isEmpty()) { - - filterList.forEach(filter -> { - if (filter.getSubType() != null && !filter.getSubType().isEmpty()) { - typeAndSubTypeMap.put(filter.getType(), filter.getSubType()); - } else { - typeAndSubTypeMap.put(filter.getType(), null); - } - }); - } - } - } - return typeAndSubTypeMap; - - } - - private void updateErrorFlags(InternalRegistrationStatusDto registrationStatusDto, MessageDTO object) { - object.setInternalError(true); - if (registrationStatusDto.getLatestTransactionStatusCode() - .equalsIgnoreCase(RegistrationTransactionStatusCode.REPROCESS.toString())) { - object.setIsValid(true); - } else { - object.setIsValid(false); - } - } +package io.mosip.registration.processor.abis.handler.stage; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.stream.Collectors; + +import org.apache.commons.lang3.exception.ExceptionUtils; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.simple.JSONObject; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.cloud.context.config.annotation.RefreshScope; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.env.Environment; +import org.springframework.core.io.ByteArrayResource; +import org.springframework.http.MediaType; +import org.springframework.stereotype.Service; +import org.springframework.util.CollectionUtils; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; + +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.common.collect.Lists; + +import io.mosip.kernel.biometrics.constant.BiometricType; +import io.mosip.kernel.biometrics.entities.BIR; +import io.mosip.kernel.biometrics.entities.BiometricRecord; +import io.mosip.kernel.biometrics.spi.CbeffUtil; +import io.mosip.kernel.core.logger.spi.Logger; +import io.mosip.kernel.core.util.DateUtils; +import io.mosip.kernel.core.util.JsonUtils; +import io.mosip.kernel.core.util.StringUtils; +import io.mosip.kernel.core.util.exception.JsonProcessingException; +import io.mosip.registration.processor.abis.handler.constant.AbisHandlerStageConstant; +import io.mosip.registration.processor.abis.handler.dto.DataShareResponseDto; +import io.mosip.registration.processor.abis.handler.exception.AbisHandlerException; +import io.mosip.registration.processor.abis.handler.exception.DataShareException; +import io.mosip.registration.processor.abis.queue.dto.AbisQueueDetails; +import io.mosip.registration.processor.core.abstractverticle.MessageBusAddress; +import io.mosip.registration.processor.core.abstractverticle.MessageDTO; +import io.mosip.registration.processor.core.abstractverticle.MosipEventBus; +import io.mosip.registration.processor.core.abstractverticle.MosipRouter; +import io.mosip.registration.processor.core.abstractverticle.MosipVerticleAPIManager; +import io.mosip.registration.processor.core.code.AbisStatusCode; +import io.mosip.registration.processor.core.code.ApiName; +import io.mosip.registration.processor.core.code.EventId; +import io.mosip.registration.processor.core.code.EventName; +import io.mosip.registration.processor.core.code.EventType; +import io.mosip.registration.processor.core.code.ModuleName; +import io.mosip.registration.processor.core.code.RegistrationTransactionStatusCode; +import io.mosip.registration.processor.core.constant.JsonConstant; +import io.mosip.registration.processor.core.constant.LoggerFileConstant; +import io.mosip.registration.processor.core.constant.MappingJsonConstants; +import io.mosip.registration.processor.core.constant.PolicyConstant; +import io.mosip.registration.processor.core.constant.ProviderStageName; +import io.mosip.registration.processor.core.exception.ApisResourceAccessException; +import io.mosip.registration.processor.core.exception.PacketManagerException; +import io.mosip.registration.processor.core.exception.util.PlatformErrorMessages; +import io.mosip.registration.processor.core.exception.util.PlatformSuccessMessages; +import io.mosip.registration.processor.core.http.ResponseWrapper; +import io.mosip.registration.processor.core.logger.LogDescription; +import io.mosip.registration.processor.core.logger.RegProcessorLogger; +import io.mosip.registration.processor.core.packet.dto.FieldValue; +import io.mosip.registration.processor.core.packet.dto.Identity; +import io.mosip.registration.processor.core.packet.dto.abis.AbisIdentifyRequestDto; +import io.mosip.registration.processor.core.packet.dto.abis.AbisIdentifyRequestGalleryDto; +import io.mosip.registration.processor.core.packet.dto.abis.AbisInsertRequestDto; +import io.mosip.registration.processor.core.packet.dto.abis.AbisRequestDto; +import io.mosip.registration.processor.core.packet.dto.abis.Flag; +import io.mosip.registration.processor.core.packet.dto.abis.ReferenceIdDto; +import io.mosip.registration.processor.core.packet.dto.abis.RegBioRefDto; +import io.mosip.registration.processor.core.packet.dto.abis.RegDemoDedupeListDto; +import io.mosip.registration.processor.core.packet.dto.datashare.Filter; +import io.mosip.registration.processor.core.packet.dto.datashare.ShareableAttributes; +import io.mosip.registration.processor.core.packet.dto.datashare.Source; +import io.mosip.registration.processor.core.spi.packetmanager.PacketInfoManager; +import io.mosip.registration.processor.core.spi.restclient.RegistrationProcessorRestClientService; +import io.mosip.registration.processor.core.status.util.StatusUtil; +import io.mosip.registration.processor.core.status.util.TrimExceptionMessage; +import io.mosip.registration.processor.core.util.JsonUtil; +import io.mosip.registration.processor.packet.storage.dto.ApplicantInfoDto; +import io.mosip.registration.processor.packet.storage.utils.PacketManagerService; +import io.mosip.registration.processor.packet.storage.utils.PriorityBasedPacketManagerService; +import io.mosip.registration.processor.packet.storage.utils.Utilities; +import io.mosip.registration.processor.rest.client.audit.builder.AuditLogRequestBuilder; +import io.mosip.registration.processor.status.dto.InternalRegistrationStatusDto; +import io.mosip.registration.processor.status.dto.RegistrationStatusDto; +import io.mosip.registration.processor.status.service.RegistrationStatusService; + +/** + * The Class AbisHandlerStage. + * + * @author M1048358 Alok + */ +@RefreshScope +@Service +@Configuration +@ComponentScan(basePackages = { "${mosip.auth.adapter.impl.basepackage}", + "io.mosip.registration.processor.abis.handler.config", + "io.mosip.registration.processor.status.config", "io.mosip.registration.processor.rest.client.config", + "io.mosip.registration.processor.packet.storage.config", "io.mosip.registration.processor.core.config", + "io.mosip.registration.processor.core.kernel.beans", "io.mosip.kernel.packetmanager.config" }) +public class AbisHandlerStage extends MosipVerticleAPIManager { + + private static final String STAGE_PROPERTY_PREFIX = "mosip.regproc.abis.handler."; + private Map> typeAndSubTypeMap = new HashMap<>(); + LinkedHashMap datasharePolicies = null; + + /** The cluster manager url. */ + @Value("${vertx.cluster.configuration}") + private String clusterManagerUrl; + + /** The max results. */ + @Value("${registration.processor.abis.maxResults}") + private String maxResults; + + /** The target FPIR. */ + @Value("${registration.processor.abis.targetFPIR}") + private String targetFPIR; + + /** worker pool size. */ + @Value("${worker.pool.size}") + private Integer workerPoolSize; + + /** + * After this time intervel, message should be considered as expired (In + * seconds). + */ + @Value("${mosip.regproc.abis.handler.message.expiry-time-limit}") + private Long messageExpiryTimeLimit; + + @Value("${registration.processor.policy.id}") + private String policyId; + + @Value("${registration.processor.subscriber.id}") + private String subscriberId; + + @Value("${mosip.regproc.data.share.protocol}") + private String httpProtocol; + + @Value("${mosip.regproc.data.share.internal.domain.name}") + private String internalDomainName; + + @Value("#{${mosip.regproc.abis.handler.biometric-modalities-segments-mapping.INFANT}}") + private Map> biometricModalitySegmentsMapInfant; + + @Value("#{${mosip.regproc.abis.handler.biometric-modalities-segments-mapping.MINOR}}") + private Map> biometricModalitySegmentsMapMinor; + + @Value("#{${mosip.regproc.abis.handler.biometric-modalities-segments-mapping.ADULT}}") + private Map> biometricModalitySegmentsMapAdult; + + @Value("#{${mosip.regproc.abis.handler.biometric-segments-exceptions-mapping}}") + private Map exceptionSegmentsMap; + + @Autowired + private RegistrationProcessorRestClientService registrationProcessorRestClientService; + + /** The reg proc logger. */ + private static Logger regProcLogger = RegProcessorLogger.getLogger(AbisHandlerStage.class); + + /** The core audit request builder. */ + @Autowired + private AuditLogRequestBuilder auditLogRequestBuilder; + + /** The registration status service. */ + @Autowired + private RegistrationStatusService registrationStatusService; + + /** The packet info manager. */ + @Autowired + private PacketInfoManager packetInfoManager; + + @Autowired + private PacketManagerService packetManagerService; + + @Autowired + private Utilities utility; + + @Autowired + private ObjectMapper mapper; + + /** The mosip event bus. */ + MosipEventBus mosipEventBus = null; + + /** Mosip router for APIs */ + @Autowired + MosipRouter router; + + @Autowired + private CbeffUtil cbeffutil; + + @Autowired + private Environment env; + + @Autowired + private PriorityBasedPacketManagerService priorityBasedPacketManagerService; + + private static final String DATASHARECREATEURL = "DATASHARECREATEURL"; + + private static final String DATETIME_PATTERN = "mosip.registration.processor.datetime.pattern"; + + @Value("#{T(java.util.Arrays).asList('${mosip.regproc.common.before-cbeff-others-attibute.reg-client-versions:}')}") + private List regClientVersionsBeforeCbeffOthersAttritube; + + /** + * Deploy verticle. + */ + public void deployVerticle() { + mosipEventBus = this.getEventBus(this, clusterManagerUrl, workerPoolSize); + this.consumeAndSend(mosipEventBus, MessageBusAddress.ABIS_HANDLER_BUS_IN, + MessageBusAddress.ABIS_HANDLER_BUS_OUT, messageExpiryTimeLimit); + } + + @Override + public void start() { + router.setRoute(this.postUrl(getVertx(), MessageBusAddress.ABIS_HANDLER_BUS_IN, + MessageBusAddress.ABIS_HANDLER_BUS_OUT)); + this.createServer(router.getRouter(), getPort()); + } + + @Override + protected String getPropertyPrefix() { + return STAGE_PROPERTY_PREFIX; + } + + /* + * (non-Javadoc) + * + * @see + * io.mosip.registration.processor.core.spi.eventbus.EventBusManager#process( + * java.lang.Object) + */ + @Override + public MessageDTO process(MessageDTO object) { + TrimExceptionMessage trimExceptionMessage = new TrimExceptionMessage(); + LogDescription description = new LogDescription(); + object.setMessageBusAddress(MessageBusAddress.ABIS_HANDLER_BUS_IN); + object.setIsValid(Boolean.TRUE); + Boolean isTransactionSuccessful = false; + String regId = object.getRid(); + object.setInternalError(Boolean.FALSE); + InternalRegistrationStatusDto registrationStatusDto = null; + String transactionTypeCode = null; + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + regId, "AbisHandlerStage::process()::entry"); + try { + registrationStatusDto = registrationStatusService.getRegistrationStatus(regId, object.getReg_type(), + object.getIteration(), object.getWorkflowInstanceId()); + transactionTypeCode = registrationStatusDto.getLatestTransactionTypeCode(); + String transactionId = registrationStatusDto.getLatestRegistrationTransactionId(); + + Boolean isIdentifyRequestPresent = packetInfoManager.getIdentifyByTransactionId(transactionId, + AbisHandlerStageConstant.IDENTIFY); + + if (!isIdentifyRequestPresent) { + List abisQueueDetails = utility.getAbisQueueDetails(); + if (abisQueueDetails.isEmpty()) { + description.setStatusComment(AbisHandlerStageConstant.DETAILS_NOT_FOUND); + description.setMessage(PlatformErrorMessages.RPR_DETAILS_NOT_FOUND.getMessage()); + description.setCode(PlatformErrorMessages.RPR_DETAILS_NOT_FOUND.getCode()); + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString(), "", + AbisHandlerStageConstant.DETAILS_NOT_FOUND); + throw new AbisHandlerException(PlatformErrorMessages.RPR_ABIS_INTERNAL_ERROR.getCode()); + } + createRequest(regId, abisQueueDetails, transactionId, registrationStatusDto.getRegistrationType(),registrationStatusDto.getIteration(), + registrationStatusDto.getWorkflowInstanceId(), description, transactionTypeCode); + object.setMessageBusAddress(MessageBusAddress.ABIS_MIDDLEWARE_BUS_IN); + } else { + if (transactionTypeCode.equalsIgnoreCase(AbisHandlerStageConstant.DEMOGRAPHIC_VERIFICATION)) { + object.setMessageBusAddress(MessageBusAddress.DEMO_DEDUPE_BUS_IN); + } else if (transactionTypeCode.equalsIgnoreCase(AbisHandlerStageConstant.BIOGRAPHIC_VERIFICATION)) { + object.setMessageBusAddress(MessageBusAddress.BIO_DEDUPE_BUS_IN); + } + } + description.setStatusComment(AbisHandlerStageConstant.ABIS_HANDLER_SUCCESS); + description.setMessage(PlatformSuccessMessages.RPR_ABIS_HANDLER_STAGE_SUCCESS.getMessage()); + description.setCode(PlatformSuccessMessages.RPR_ABIS_HANDLER_STAGE_SUCCESS.getCode()); + isTransactionSuccessful = true; + regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + regId, description.getMessage()); + } catch (Exception e) { + + if (e instanceof DataShareException) { + object.setIsValid(false); + } + description.setStatusComment(AbisHandlerStageConstant.ERROR_IN_ABIS_HANDLER); + description.setMessage(PlatformErrorMessages.RPR_MESSAGE_SENDER_STAGE_FAILED.getMessage()); + description.setCode(PlatformErrorMessages.RPR_MESSAGE_SENDER_STAGE_FAILED.getCode()); + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + regId, ExceptionUtils.getStackTrace(e)); + object.setInternalError(Boolean.TRUE); + registrationStatusDto + .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.REPROCESS.toString()); + registrationStatusDto.setSubStatusCode(StatusUtil.SYSTEM_EXCEPTION_OCCURED.getCode()); + if (transactionTypeCode.equalsIgnoreCase(AbisHandlerStageConstant.DEMOGRAPHIC_VERIFICATION)) { + registrationStatusDto.setRegistrationStageName(AbisHandlerStageConstant.DEMO_DEDUPE_STAGE); + } else if (transactionTypeCode.equalsIgnoreCase(AbisHandlerStageConstant.BIOGRAPHIC_VERIFICATION)) { + registrationStatusDto.setRegistrationStageName(AbisHandlerStageConstant.BIO_DEDUPE_STAGE); + } + registrationStatusDto.setStatusComment(trimExceptionMessage + .trimExceptionMessage(StatusUtil.UNKNOWN_EXCEPTION_OCCURED.getMessage() + e.getMessage())); + String moduleId = description.getCode(); + String moduleName = ModuleName.ABIS_HANDLER.toString(); + registrationStatusService.updateRegistrationStatus(registrationStatusDto, moduleId, moduleName); + } finally { + if (object.getInternalError()) { + updateErrorFlags(registrationStatusDto, object); + } + String eventId = isTransactionSuccessful ? EventId.RPR_402.toString() : EventId.RPR_405.toString(); + String eventName = isTransactionSuccessful ? EventName.UPDATE.toString() : EventName.EXCEPTION.toString(); + String eventType = isTransactionSuccessful ? EventType.BUSINESS.toString() : EventType.SYSTEM.toString(); + + /** Module-Id can be Both Success/Error code */ + String moduleId = isTransactionSuccessful ? PlatformSuccessMessages.RPR_ABIS_HANDLER_STAGE_SUCCESS.getCode() + : description.getCode(); + String moduleName = ModuleName.ABIS_HANDLER.toString(); + + auditLogRequestBuilder.createAuditRequestBuilder(description.getMessage(), eventId, eventName, eventType, + moduleId, moduleName, regId); + + } + + return object; + } + + private void createRequest(String regId, List abisQueueDetails, String transactionId, + String process, int iteration, String workflowInstanceId, LogDescription description, String transactionTypeCode) throws Exception { + String bioRefId = getUUID(); + insertInBioRef(regId, bioRefId,process,iteration, workflowInstanceId); + createInsertRequest(abisQueueDetails, transactionId, bioRefId, regId, process, description); + createIdentifyRequest(abisQueueDetails, transactionId, bioRefId, transactionTypeCode, description); + + } + + /** + * Creates the identify request. + * + * @param abisQueueDetails the abis application dto list + * @param transactionId the transaction id + * @param bioRefId the bio ref id + * @param transactionTypeCode the transaction type code + * @param description + */ + private void createIdentifyRequest(List abisQueueDetails, String transactionId, String bioRefId, + String transactionTypeCode, LogDescription description) { + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", + "AbisHandlerStage::createIdentifyRequest()::entry"); + String batchId = getUUID(); + for (AbisQueueDetails abisQueue : abisQueueDetails) { + AbisRequestDto abisRequestDto = new AbisRequestDto(); + String id = getUUID(); + abisRequestDto.setId(id); + abisRequestDto.setAbisAppCode(abisQueue.getName()); + abisRequestDto.setBioRefId(bioRefId); + abisRequestDto.setRequestType(AbisHandlerStageConstant.IDENTIFY); + abisRequestDto.setReqBatchId(batchId); + abisRequestDto.setRefRegtrnId(transactionId); + + byte[] abisIdentifyRequestBytes = getIdentifyRequestBytes(transactionId, bioRefId, transactionTypeCode, id, + description); + abisRequestDto.setReqText(abisIdentifyRequestBytes); + + abisRequestDto.setStatusCode(RegistrationTransactionStatusCode.IN_PROGRESS.toString()); + abisRequestDto.setStatusComment(null); + abisRequestDto.setLangCode(AbisHandlerStageConstant.ENG); + abisRequestDto.setCrBy(AbisHandlerStageConstant.USER); + abisRequestDto.setUpdBy(null); + abisRequestDto.setIsDeleted(Boolean.FALSE); + + String moduleId = PlatformSuccessMessages.RPR_ABIS_HANDLER_STAGE_SUCCESS.getCode(); + String moduleName = ModuleName.ABIS_HANDLER.toString(); + packetInfoManager.saveAbisRequest(abisRequestDto, moduleId, moduleName); + } + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", + "AbisHandlerStage::createIdentifyRequest()::exit"); + } + + /** + * Gets the identify request bytes. + * + * @param transactionId the transaction id + * @param bioRefId the bio ref id + * @param transactionTypeCode the transaction type code + * @param id the id + * @param description + * @return the identify request bytes + */ + private byte[] getIdentifyRequestBytes(String transactionId, String bioRefId, String transactionTypeCode, String id, + LogDescription description) { + AbisIdentifyRequestDto abisIdentifyRequestDto = new AbisIdentifyRequestDto(); + Flag flag = new Flag(); + abisIdentifyRequestDto.setId(AbisHandlerStageConstant.MOSIP_ABIS_IDENTIFY); + abisIdentifyRequestDto.setVersion(AbisHandlerStageConstant.VERSION); + abisIdentifyRequestDto.setRequestId(id); + abisIdentifyRequestDto.setReferenceId(bioRefId); + abisIdentifyRequestDto.setReferenceUrl(""); + abisIdentifyRequestDto.setRequesttime(DateUtils.getUTCCurrentDateTimeString(env.getProperty(DATETIME_PATTERN))); + flag.setMaxResults(maxResults); + flag.setTargetFPIR(targetFPIR); + abisIdentifyRequestDto.setFlags(flag); + + // Added Gallery data for demo dedupe + if (transactionTypeCode.equalsIgnoreCase(AbisHandlerStageConstant.DEMOGRAPHIC_VERIFICATION)) { + List regDemoDedupeListDtoList = packetInfoManager + .getDemoListByTransactionId(transactionId); + if (regDemoDedupeListDtoList.isEmpty()) { + description.setStatusComment(AbisHandlerStageConstant.NO_RECORD_FOUND); + description.setMessage(PlatformErrorMessages.RPR_NO_RECORD_FOUND.getMessage()); + description.setCode(PlatformErrorMessages.RPR_NO_RECORD_FOUND.getCode()); + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString(), "", + "Potential Match Records are Not Found for Demo Dedupe Potential Match"); + throw new AbisHandlerException(description.getMessage()); + } + List referenceIdDtos = new ArrayList<>(); + + for (RegDemoDedupeListDto dedupeListDto : regDemoDedupeListDtoList) { + ReferenceIdDto dto = new ReferenceIdDto(); + List regBioRefDto = packetInfoManager.getBioRefIdByRegId(dedupeListDto.getMatchedRegId()); + if (!CollectionUtils.isEmpty(regBioRefDto)) { + dto.setReferenceId(regBioRefDto.get(0).getBioRefId()); + } + + referenceIdDtos.add(dto); + } + AbisIdentifyRequestGalleryDto galleryDto = new AbisIdentifyRequestGalleryDto(); + galleryDto.setReferenceIds(referenceIdDtos); + abisIdentifyRequestDto.setGallery(galleryDto); + } + + try { + String jsonString = JsonUtils.javaObjectToJsonString(abisIdentifyRequestDto); + return jsonString.getBytes(); + } catch (JsonProcessingException e) { + description.setStatusComment(AbisHandlerStageConstant.ERROR_IN_ABIS_HANDLER_IDENTIFY_REQUEST); + description.setMessage(PlatformErrorMessages.RPR_ERROR_IN_ABIS_HANDLER_IDENTIFY_REQUEST.getMessage()); + description.setCode(PlatformErrorMessages.RPR_ERROR_IN_ABIS_HANDLER_IDENTIFY_REQUEST.getCode()); + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + "", AbisHandlerStageConstant.ERROR_IN_ABIS_HANDLER_IDENTIFY_REQUEST); + throw new AbisHandlerException(PlatformErrorMessages.RPR_ABIS_INTERNAL_ERROR.getCode(), e); + } + } + + /** + * Insert in bio ref. + * + * @param regId the reg id + * @param bioRefId the bio ref id + */ + private void insertInBioRef(String regId, String bioRefId, String process, int iteration, String workflowInstanceId) { + RegBioRefDto regBioRefDto = new RegBioRefDto(); + regBioRefDto.setBioRefId(bioRefId); + regBioRefDto.setCrBy(AbisHandlerStageConstant.USER); + regBioRefDto.setIsActive(Boolean.TRUE); + regBioRefDto.setIsDeleted(Boolean.FALSE); + regBioRefDto.setRegId(regId); + regBioRefDto.setUpdBy(null); + regBioRefDto.setProcess(process); + regBioRefDto.setIteration(iteration); + regBioRefDto.setWorkflowInstanceId(workflowInstanceId); + String moduleId = PlatformSuccessMessages.RPR_ABIS_HANDLER_STAGE_SUCCESS.getCode(); + String moduleName = ModuleName.ABIS_HANDLER.toString(); + packetInfoManager.saveBioRef(regBioRefDto, moduleId, moduleName); + } + + /** + * Creates the insert request. + * + * @param abisQueueDetails the abis application dto list + * @param transactionId the transaction id + * @param bioRefId the bio ref id + * @param regId the reg id + * @param description + */ + private void createInsertRequest(List abisQueueDetails, String transactionId, String bioRefId, + String regId, String process, LogDescription description) throws Exception { + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + regId, "AbisHandlerStage::createInsertRequest()::entry"); + String batchId = getUUID(); + List abisProcessedInsertAppCodeList = packetInfoManager.getAbisProcessedRequestsAppCodeByBioRefId( + bioRefId, AbisStatusCode.INSERT.toString(), AbisStatusCode.PROCESSED.toString()); + List abisAppCodeList = new ArrayList<>(); + for (AbisQueueDetails abisQueue : abisQueueDetails) { + abisAppCodeList.add(abisQueue.getName()); + } + + for (String appCode : abisAppCodeList) { + + AbisRequestDto abisRequestDto = new AbisRequestDto(); + String id = getUUID(); + abisRequestDto.setId(id); + abisRequestDto.setAbisAppCode(appCode); + abisRequestDto.setBioRefId(bioRefId); + abisRequestDto.setRequestType(AbisHandlerStageConstant.INSERT); + abisRequestDto.setReqBatchId(batchId); + abisRequestDto.setRefRegtrnId(transactionId); + + + abisRequestDto.setStatusCode(AbisStatusCode.IN_PROGRESS.toString()); + abisRequestDto.setStatusComment(null); + abisRequestDto.setLangCode(AbisHandlerStageConstant.ENG); + abisRequestDto.setCrBy(AbisHandlerStageConstant.USER); + abisRequestDto.setUpdBy(null); + abisRequestDto.setIsDeleted(Boolean.FALSE); + String moduleId = PlatformSuccessMessages.RPR_ABIS_HANDLER_STAGE_SUCCESS.getCode(); + String moduleName = ModuleName.ABIS_HANDLER.toString(); + byte[] abisInsertRequestBytes =null; + if (abisProcessedInsertAppCodeList != null && abisProcessedInsertAppCodeList.contains(appCode)) { + + abisInsertRequestBytes = getInsertRequestBytes(regId, id, process, bioRefId, description, + AbisStatusCode.ALREADY_PROCESSED.toString()); + abisRequestDto.setStatusCode(AbisStatusCode.ALREADY_PROCESSED.toString()); + + } else { + abisInsertRequestBytes = getInsertRequestBytes(regId, id, process, bioRefId, description, + AbisStatusCode.IN_PROGRESS.toString()); + abisRequestDto.setStatusCode(AbisStatusCode.IN_PROGRESS.toString()); + + } + abisRequestDto.setReqText(abisInsertRequestBytes); + packetInfoManager.saveAbisRequest(abisRequestDto, moduleId, moduleName); + } + + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", + "AbisHandlerStage::createInsertRequest()::exit"); + } + + /** + * Gets the insert request bytes. + * + * @param regId the reg id + * @param id the id + * @param bioRefId the bio ref id + * @param description + * @param status + * @return the insert request bytes + */ + private byte[] getInsertRequestBytes(String regId, String id, String process, String bioRefId, + LogDescription description, String status) throws Exception { + AbisInsertRequestDto abisInsertRequestDto = new AbisInsertRequestDto(); + abisInsertRequestDto.setId(AbisHandlerStageConstant.MOSIP_ABIS_INSERT); + abisInsertRequestDto.setReferenceId(bioRefId); + abisInsertRequestDto.setReferenceURL(status.equalsIgnoreCase(AbisStatusCode.IN_PROGRESS.toString())?getDataShareUrl(regId, process):null); + abisInsertRequestDto.setRequestId(id); + abisInsertRequestDto.setRequesttime(DateUtils.getUTCCurrentDateTimeString(env.getProperty(DATETIME_PATTERN))); + abisInsertRequestDto.setVersion(AbisHandlerStageConstant.VERSION); + try { + String jsonString = JsonUtils.javaObjectToJsonString(abisInsertRequestDto); + return jsonString.getBytes(); + } catch (JsonProcessingException e) { + description.setStatusComment(AbisHandlerStageConstant.ERROR_IN_ABIS_HANDLER_IDENTIFY_REQUEST); + description.setMessage(PlatformErrorMessages.RPR_ERROR_IN_ABIS_HANDLER_IDENTIFY_REQUEST.getMessage()); + description.setCode(PlatformErrorMessages.RPR_ERROR_IN_ABIS_HANDLER_IDENTIFY_REQUEST.getCode()); + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + "", AbisHandlerStageConstant.ERROR_IN_ABIS_HANDLER_IDENTIFY_REQUEST); + throw new AbisHandlerException(PlatformErrorMessages.RPR_ABIS_INTERNAL_ERROR.getCode(), e); + } + } + + /** + * Gets the uuid. + * + * @return the uuid + */ + private String getUUID() { + return UUID.randomUUID().toString(); + } + + private String getDataShareUrl(String id, String process) throws Exception { + Map> typeAndSubtypMap = createTypeSubtypeMapping(); + List modalities = new ArrayList<>(); + for (Map.Entry> entry : typeAndSubtypMap.entrySet()) { + if (entry.getValue() == null) { + modalities.add(entry.getKey()); + } else { + modalities.addAll(entry.getValue()); + } + } + JSONObject regProcessorIdentityJson = utility + .getRegistrationProcessorMappingJson(MappingJsonConstants.IDENTITY); + String individualBiometricsLabel = JsonUtil.getJSONValue( + JsonUtil.getJSONObject(regProcessorIdentityJson, MappingJsonConstants.INDIVIDUAL_BIOMETRICS), + MappingJsonConstants.VALUE); + BiometricRecord biometricRecord = priorityBasedPacketManagerService.getBiometrics(id, individualBiometricsLabel, + modalities, process, ProviderStageName.BIO_DEDUPE); + + Map tags = packetManagerService.getAllTags(id); + String ageGroup = tags.get("AGE_GROUP"); + + if (ageGroup.equalsIgnoreCase("INFANT")) { + validateBiometricRecord(biometricRecord, modalities, biometricModalitySegmentsMapInfant, + priorityBasedPacketManagerService.getMetaInfo(id, process, ProviderStageName.BIO_DEDUPE)); + } else if (ageGroup.equalsIgnoreCase("MINOR")) { + validateBiometricRecord(biometricRecord, modalities, biometricModalitySegmentsMapMinor, + priorityBasedPacketManagerService.getMetaInfo(id, process, ProviderStageName.BIO_DEDUPE)); + } else if (ageGroup.equalsIgnoreCase("ADULT")) { + validateBiometricRecord(biometricRecord, modalities, biometricModalitySegmentsMapAdult, + priorityBasedPacketManagerService.getMetaInfo(id, process, ProviderStageName.BIO_DEDUPE)); + } else { + validateBiometricRecord(biometricRecord, modalities, biometricModalitySegmentsMapAdult, + priorityBasedPacketManagerService.getMetaInfo(id, process, ProviderStageName.BIO_DEDUPE)); + } + + byte[] content = cbeffutil.createXML(filterExceptionBiometrics(biometricRecord,id,process).getSegments()); + + MultiValueMap map = new LinkedMultiValueMap<>(); + map.add("name", individualBiometricsLabel); + map.add("filename", individualBiometricsLabel); + + ByteArrayResource contentsAsResource = new ByteArrayResource(content) { + @Override + public String getFilename() { + return individualBiometricsLabel; + } + }; + map.add("file", contentsAsResource); + + List pathSegments = new ArrayList<>(); + pathSegments.add(policyId); + pathSegments.add(subscriberId); + String protocol = StringUtils.isNotEmpty(httpProtocol) ? PolicyConstant.HTTP_PROTOCOL : PolicyConstant.HTTPS_PROTOCOL; + String url = null; + + if (!CollectionUtils.isEmpty(datasharePolicies) && datasharePolicies.get(PolicyConstant.SHAREDOMAIN_WRITE) != null) + url = datasharePolicies.get(PolicyConstant.SHAREDOMAIN_WRITE) + env.getProperty(ApiName.DATASHARECREATEURL.name()); + else + url = protocol + internalDomainName + env.getProperty(ApiName.DATASHARECREATEURL.name()); + url = url.replaceAll("[\\[\\]]", ""); + DataShareResponseDto response = (DataShareResponseDto) registrationProcessorRestClientService.postApi(url, + MediaType.MULTIPART_FORM_DATA, pathSegments, null, null, map, DataShareResponseDto.class); + if (response == null || (response.getErrors() != null && response.getErrors().size() > 0)) + throw new DataShareException( + response == null ? "Datashare response is null" : response.getErrors().get(0).getMessage()); + + return response.getDataShare().getUrl(); + } + + @SuppressWarnings("deprecation") + private void validateBiometricRecord(BiometricRecord biometricRecord, List modalities, + Map> biometricModalitySegmentsMap, Map metaInfoMap) + throws DataShareException, JsonParseException, JsonMappingException, IOException { + if (modalities == null || modalities.isEmpty()) { + throw new DataShareException("Data Share Policy Modalities were Empty"); + } + if (biometricRecord == null || biometricRecord.getSegments() == null + || biometricRecord.getSegments().isEmpty()) { + throw new DataShareException("No Biometrics Found with Data Share Policy"); + } + Map> metaInfoExceptionBiometrics = metaInfoMap != null + && metaInfoMap.containsKey("exceptionBiometrics") + ? mapper.readValue(metaInfoMap.get("exceptionBiometrics"), + new TypeReference>>() { + }) + : null; + Set exceptionList = null; + if (metaInfoExceptionBiometrics != null && metaInfoExceptionBiometrics.containsKey("applicant")) { + exceptionList = metaInfoExceptionBiometrics.get("applicant").keySet(); + } + boolean isBioFound = false; + for (String biometricSegment : biometricModalitySegmentsMap.keySet()) { + if (!modalities.contains(biometricSegment)) { + throw new DataShareException("Biometrics Segments Not Configured for modality : " + biometricSegment); + } + for (String segment : biometricModalitySegmentsMap.get(biometricSegment)) { + Optional optionalBIR = Optional.empty(); + if (segment.equalsIgnoreCase("Face")) { + optionalBIR = biometricRecord.getSegments().stream() + .filter(bir -> bir.getBdbInfo().getType() != null + && bir.getBdbInfo().getType().get(0).equals(BiometricType.FACE)) + .findFirst(); + } else { + String[] segmentArray = segment.split(" "); + optionalBIR = biometricRecord.getSegments().stream() + .filter(bir -> bir.getBdbInfo().getSubtype()!=null && bir.getBdbInfo().getSubtype().size() == segmentArray.length + ? (bir.getBdbInfo().getSubtype().get(0).equalsIgnoreCase(segmentArray[0]) + && (segmentArray.length == 2 + ? bir.getBdbInfo().getSubtype().get(1) + .equalsIgnoreCase(segmentArray[1]) + : true)) + : false) + .findFirst(); + } + if (optionalBIR.isPresent()) { + BIR bir = optionalBIR.get(); + Map othersMap = new HashMap(); + if (bir.getOthers() != null) { + othersMap = bir.getOthers().entrySet().stream() + .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue())); + } + + if (bir.getBdb() != null) { + isBioFound = true; + } else if ((othersMap == null || !othersMap.containsKey("EXCEPTION")) ? true + : !(Boolean.parseBoolean(othersMap.get("EXCEPTION")))) { + throw new DataShareException("Biometric BDB Not Found : " + segment); + } + } else if (exceptionList == null || !exceptionList.contains(exceptionSegmentsMap.get(segment))) { + throw new DataShareException("Biometrics/Exceptions Not Found : " + segment); + } + } + } + if (!isBioFound) { + throw new DataShareException("No Biometric Matched with Data Share Policy"); + } + } + + private BiometricRecord filterExceptionBiometrics(BiometricRecord biometricRecord, String id, String process) + throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException, + JSONException + { + + String version = getRegClientVersionFromMetaInfo(id, process, priorityBasedPacketManagerService.getMetaInfo(id, process, ProviderStageName.BIO_DEDUPE)); + if (regClientVersionsBeforeCbeffOthersAttritube.contains(version)) { + return biometricRecord; + } + List segments = biometricRecord.getSegments().stream().filter(bio -> { + Map othersMap = bio.getOthers().entrySet().stream() + .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue())); + return (othersMap == null || !othersMap.containsKey("EXCEPTION")) ? true + : !(Boolean.parseBoolean(othersMap.get("EXCEPTION"))); + }).collect(Collectors.toList()); + BiometricRecord biorecord = new BiometricRecord(); + biorecord.setSegments(segments); + return biorecord; + } + + private String getRegClientVersionFromMetaInfo(String id, String process, Map metaInfoMap) + throws ApisResourceAccessException, PacketManagerException, IOException, JSONException { + String metadata = metaInfoMap.get(JsonConstant.METADATA); + String version = null; + if (StringUtils.isNotEmpty(metadata)) { + JSONArray jsonArray = new JSONArray(metadata); + + for (int i = 0; i < jsonArray.length(); i++) { + if (!jsonArray.isNull(i)) { + org.json.JSONObject jsonObject = (org.json.JSONObject) jsonArray.get(i); + FieldValue fieldValue = mapper.readValue(jsonObject.toString(), FieldValue.class); + if (fieldValue.getLabel().equalsIgnoreCase(JsonConstant.REGCLIENTVERSION)) { + version = fieldValue.getValue(); + break; + } + } + } + } + return version; + } + + public Map> createTypeSubtypeMapping() throws ApisResourceAccessException, DataShareException, + IOException { + + // Call only once and use cache + if (!CollectionUtils.isEmpty(typeAndSubTypeMap) && !CollectionUtils.isEmpty(datasharePolicies)) + return typeAndSubTypeMap; + + ResponseWrapper policyResponse = (ResponseWrapper) registrationProcessorRestClientService.getApi( + ApiName.PMS, Lists.newArrayList(policyId, PolicyConstant.PARTNER_ID, subscriberId), "", "", + ResponseWrapper.class); + if (policyResponse == null || (policyResponse.getErrors() != null && policyResponse.getErrors().size() > 0)) { + throw new DataShareException(policyResponse == null ? "Policy Response response is null" + : policyResponse.getErrors().get(0).getMessage()); + + } else { + LinkedHashMap responseMap = (LinkedHashMap) policyResponse.getResponse(); + LinkedHashMap policies = (LinkedHashMap) responseMap + .get(PolicyConstant.POLICIES); + List attributes = (List) policies.get(PolicyConstant.SHAREABLE_ATTRIBUTES); + datasharePolicies = (LinkedHashMap) policies.get(PolicyConstant.DATASHARE_POLICIES); + ShareableAttributes shareableAttributes = mapper.readValue(mapper.writeValueAsString(attributes.get(0)), + ShareableAttributes.class); + for (Source source : shareableAttributes.getSource()) { + List filterList = source.getFilter(); + if (filterList != null && !filterList.isEmpty()) { + + filterList.forEach(filter -> { + if (filter.getSubType() != null && !filter.getSubType().isEmpty()) { + typeAndSubTypeMap.put(filter.getType(), filter.getSubType()); + } else { + typeAndSubTypeMap.put(filter.getType(), null); + } + }); + } + } + } + return typeAndSubTypeMap; + + } + + private void updateErrorFlags(InternalRegistrationStatusDto registrationStatusDto, MessageDTO object) { + object.setInternalError(true); + if (registrationStatusDto.getLatestTransactionStatusCode() + .equalsIgnoreCase(RegistrationTransactionStatusCode.REPROCESS.toString())) { + object.setIsValid(true); + } else { + object.setIsValid(false); + } + } } \ No newline at end of file diff --git a/registration-processor/core-processor/registration-processor-abis-handler-stage/src/test/java/io/mosip/registration/processor/abis/handler/stage/test/AbisHandlerStageTest.java b/registration-processor/core-processor/registration-processor-abis-handler-stage/src/test/java/io/mosip/registration/processor/abis/handler/stage/test/AbisHandlerStageTest.java index 0e13a0f5306..7cf1e4e112c 100644 --- a/registration-processor/core-processor/registration-processor-abis-handler-stage/src/test/java/io/mosip/registration/processor/abis/handler/stage/test/AbisHandlerStageTest.java +++ b/registration-processor/core-processor/registration-processor-abis-handler-stage/src/test/java/io/mosip/registration/processor/abis/handler/stage/test/AbisHandlerStageTest.java @@ -53,6 +53,7 @@ import io.mosip.registration.processor.core.abstractverticle.MessageDTO; import io.mosip.registration.processor.core.abstractverticle.MosipEventBus; import io.mosip.registration.processor.core.common.rest.dto.ErrorDTO; +import io.mosip.registration.processor.core.constant.JsonConstant; import io.mosip.registration.processor.core.constant.PolicyConstant; import io.mosip.registration.processor.core.exception.ApisResourceAccessException; import io.mosip.registration.processor.core.exception.PacketManagerException; @@ -213,7 +214,8 @@ public void setUp() throws Exception { ReflectionTestUtils.setField(abisHandlerStage, "biometricModalitySegmentsMapMinor", biometricModalitySegmentsMap); ReflectionTestUtils.setField(abisHandlerStage, "biometricModalitySegmentsMapAdult", biometricModalitySegmentsMap); ReflectionTestUtils.setField(abisHandlerStage, "exceptionSegmentsMap", getExceptionModalityMap()); - + ReflectionTestUtils.setField(abisHandlerStage, "regClientVersionsBeforeCbeffOthersAttritube", + Arrays.asList("1.1.3")); Mockito.when(env.getProperty("DATASHARECREATEURL")).thenReturn("/v1/datashare/create"); AbisApplicationDto dto = new AbisApplicationDto(); dto.setCode("ABIS1"); @@ -968,8 +970,10 @@ private void setMetaInfoMap(List exceptionAttributes) throws ApisResourc exceptionBiometrcisMap.put("applicant", applicantExceptionBiometrcisMap); String gsonString =mapper.writeValueAsString(exceptionBiometrcisMap); - + metaInfoMap.put("exceptionBiometrics", gsonString); + metaInfoMap.put(JsonConstant.METADATA, + "[{\n \"label\" : \"Registration Client Version Number\",\n \"value\" : \"1.2.0\"\n}]"); Mockito.when(packetManagerService.getMetaInfo(any(), any(), any())).thenReturn(metaInfoMap); } From 5fb5d42be3b005acc1ab7757395c4040d3200e89 Mon Sep 17 00:00:00 2001 From: Sowmya Ujjappa Banakar <43202851+sowmya695@users.noreply.github.com> Date: Fri, 28 Jul 2023 15:05:05 +0530 Subject: [PATCH 092/133] MOSIP-28557 Bug fix (#1754) Co-authored-by: Sowmya Ujjappa Banakar --- .../IntroducerValidator.java | 573 ++++++----- .../introducer/IntroducerValidatorTest.java | 907 +++++++++--------- 2 files changed, 767 insertions(+), 713 deletions(-) diff --git a/registration-processor/pre-processor/registration-processor-introducer-validator-stage/src/main/java/io/mosip/registration/processor/stages/introducervalidator/IntroducerValidator.java b/registration-processor/pre-processor/registration-processor-introducer-validator-stage/src/main/java/io/mosip/registration/processor/stages/introducervalidator/IntroducerValidator.java index e957c160d2f..396888c5b04 100644 --- a/registration-processor/pre-processor/registration-processor-introducer-validator-stage/src/main/java/io/mosip/registration/processor/stages/introducervalidator/IntroducerValidator.java +++ b/registration-processor/pre-processor/registration-processor-introducer-validator-stage/src/main/java/io/mosip/registration/processor/stages/introducervalidator/IntroducerValidator.java @@ -1,267 +1,308 @@ -package io.mosip.registration.processor.stages.introducervalidator; - -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - -import javax.xml.parsers.ParserConfigurationException; - -import org.apache.commons.collections.CollectionUtils; -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.constant.BiometricType; -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.registration.processor.core.code.RegistrationExceptionTypeCode; -import io.mosip.registration.processor.core.constant.MappingJsonConstants; -import io.mosip.registration.processor.core.constant.ProviderStageName; -import io.mosip.registration.processor.core.constant.RegistrationType; -import io.mosip.registration.processor.core.exception.IntroducerOnHoldException; -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.logger.RegProcessorLogger; -import io.mosip.registration.processor.core.status.util.StatusUtil; -import io.mosip.registration.processor.core.util.RegistrationExceptionMapperUtil; -import io.mosip.registration.processor.packet.manager.idreposervice.IdRepoService; -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; -import io.mosip.registration.processor.status.dto.RegistrationStatusDto; -import io.mosip.registration.processor.status.service.RegistrationStatusService; - -@Service -public class IntroducerValidator { - - private static Logger regProcLogger = RegProcessorLogger.getLogger(IntroducerValidator.class); - - public static final String INDIVIDUAL_TYPE_UIN = "UIN"; - - @Autowired - RegistrationExceptionMapperUtil registrationExceptionMapperUtil; - - @Autowired - private PriorityBasedPacketManagerService packetManagerService; - - @Autowired - private IdRepoService idRepoService; - - @Autowired - RegistrationStatusService registrationStatusService; - - @Autowired - ObjectMapper mapper; - - - - @Autowired - private Utilities utility; - - @Autowired - private BioSdkUtil bioUtil; - - /** - * Checks if is valid introducer. - * - * @param registrationId the registration id - * @param registrationStatusDto - * @throws SAXException - * @throws ParserConfigurationException - * @throws BiometricException - * @throws io.mosip.kernel.core.exception.IOException - * @throws Exception - * @throws PacketDecryptionFailureException - * @throws RegistrationProcessorCheckedException - */ - public void validate(String registrationId, InternalRegistrationStatusDto registrationStatusDto) throws Exception { - - regProcLogger.debug("validate called for registrationId {}", registrationId); - - String introducerUIN = packetManagerService.getFieldByMappingJsonKey(registrationId, - MappingJsonConstants.INTRODUCER_UIN, registrationStatusDto.getRegistrationType(), - ProviderStageName.INTRODUCER_VALIDATOR); - String introducerRID = packetManagerService.getFieldByMappingJsonKey(registrationId, - MappingJsonConstants.INTRODUCER_RID, registrationStatusDto.getRegistrationType(), - ProviderStageName.INTRODUCER_VALIDATOR); - - if (isValidIntroducer(introducerUIN, introducerRID)) { - registrationStatusDto.setLatestTransactionStatusCode(registrationExceptionMapperUtil - .getStatusCode(RegistrationExceptionTypeCode.INTRODUCER_UIN_AND_RID_NOT_IN_PACKET)); - registrationStatusDto.setStatusCode(RegistrationStatusCode.REJECTED.toString()); - regProcLogger.debug("validate called for registrationId {} {}", registrationId, - StatusUtil.UIN_RID_NOT_FOUND.getMessage()); - throw new BaseCheckedException(StatusUtil.UIN_RID_NOT_FOUND.getMessage(), - StatusUtil.UIN_RID_NOT_FOUND.getCode()); - } - - if ((introducerUIN == null || introducerUIN.isEmpty()) - && isValidIntroducerRid(introducerRID, registrationId, registrationStatusDto)) { - - introducerUIN = idRepoService.getUinByRid(introducerRID, utility.getGetRegProcessorDemographicIdentity()); - - if (introducerUIN == null) { - registrationStatusDto.setLatestTransactionStatusCode(registrationExceptionMapperUtil - .getStatusCode(RegistrationExceptionTypeCode.INTRODUCER_UIN_NOT_AVAIALBLE)); - registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.toString()); - regProcLogger.debug("validate called for registrationId {} {}", registrationId, - StatusUtil.INTRODUCER_UIN_NOT_FOUND.getMessage()); - throw new BaseCheckedException(StatusUtil.INTRODUCER_UIN_NOT_FOUND.getMessage(), - StatusUtil.INTRODUCER_UIN_NOT_FOUND.getCode()); - } - - } - if (introducerUIN != null && !introducerUIN.isEmpty()) { - validateIntroducerBiometric(registrationId, registrationStatusDto, introducerUIN); - } else { - throw new ValidationFailedException(StatusUtil.INTRODUCER_AUTHENTICATION_FAILED.getMessage(), - StatusUtil.INTRODUCER_AUTHENTICATION_FAILED.getCode()); - } - - regProcLogger.debug("validate call ended for registrationId {}", registrationId); - } - - private boolean isValidIntroducer(String introducerUIN, String introducerRID) { - return ((introducerUIN == null && introducerRID == null) || ((introducerUIN != null && introducerUIN.isEmpty()) - && (introducerRID != null && introducerRID.isEmpty()))); - } - - /** - * Validate introducer rid. - * - * @param introducerRid the introducer rid - * @param registrationId the registration id - * @param registrationStatusDto - * @return true, if successful - * @throws BaseCheckedException - */ - private boolean isValidIntroducerRid(String introducerRid, String registrationId, - InternalRegistrationStatusDto registrationStatusDto) throws BaseCheckedException { - - List internalRegistrationStatusDtoList= registrationStatusService.getAllRegistrationStatuses(introducerRid); - InternalRegistrationStatusDto introducerRegistrationStatusDto=CollectionUtils.isNotEmpty(internalRegistrationStatusDtoList) ? - internalRegistrationStatusDtoList.stream().filter(s -> RegistrationType.NEW.name().equalsIgnoreCase(s.getRegistrationType())).collect(Collectors.toList()).iterator().next() - : null; - if (introducerRegistrationStatusDto != null) { - if (introducerRegistrationStatusDto.getStatusCode().equals(RegistrationStatusCode.PROCESSING.toString())) { - - registrationStatusDto.setLatestTransactionStatusCode(registrationExceptionMapperUtil - .getStatusCode(RegistrationExceptionTypeCode.ON_HOLD_INTRODUCER_PACKET)); - - registrationStatusDto.setStatusComment(StatusUtil.PACKET_ON_HOLD.getMessage()); - registrationStatusDto.setSubStatusCode(StatusUtil.PACKET_ON_HOLD.getCode()); - registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); - regProcLogger.debug("isValidIntroducerRid call ended for registrationId {} {}", registrationId, - StatusUtil.PACKET_ON_HOLD.getMessage()); - throw new IntroducerOnHoldException(StatusUtil.PACKET_ON_HOLD.getCode(), - StatusUtil.PACKET_ON_HOLD.getMessage()); - - } else if (introducerRegistrationStatusDto.getStatusCode() - .equals(RegistrationStatusCode.REJECTED.toString()) - || introducerRegistrationStatusDto.getStatusCode() - .equals(RegistrationStatusCode.FAILED.toString())) { - - registrationStatusDto.setLatestTransactionStatusCode(registrationExceptionMapperUtil - .getStatusCode(RegistrationExceptionTypeCode.OSI_FAILED_REJECTED_INTRODUCER)); - - registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.toString()); - regProcLogger.debug("isValidIntroducerRid call ended for registrationId {} {}", registrationId, - StatusUtil.CHILD_PACKET_REJECTED.getMessage()); - throw new BaseCheckedException(StatusUtil.CHILD_PACKET_REJECTED.getMessage(), - StatusUtil.CHILD_PACKET_REJECTED.getCode()); - } else { - return true; - } - - } else { - registrationStatusDto.setLatestTransactionStatusCode(registrationExceptionMapperUtil - .getStatusCode(RegistrationExceptionTypeCode.ON_HOLD_INTRODUCER_PACKET)); - - registrationStatusDto.setStatusComment(StatusUtil.PACKET_IS_ON_HOLD.getMessage()); - registrationStatusDto.setSubStatusCode(StatusUtil.PACKET_IS_ON_HOLD.getCode()); - registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); - regProcLogger.debug("isValidIntroducerRid call ended for registrationId {} {}", registrationId, - StatusUtil.PACKET_ON_HOLD.getMessage()); - throw new IntroducerOnHoldException(StatusUtil.PACKET_ON_HOLD.getCode(), - StatusUtil.PACKET_ON_HOLD.getMessage()); - } - } - - private void validateIntroducerBiometric(String registrationId, InternalRegistrationStatusDto registrationStatusDto, - String introducerUIN) - throws Exception { - BiometricRecord biometricRecord = packetManagerService.getBiometricsByMappingJsonKey(registrationId, - MappingJsonConstants.INTRODUCER_BIO, registrationStatusDto.getRegistrationType(), - ProviderStageName.INTRODUCER_VALIDATOR); - if (biometricRecord != null && biometricRecord.getSegments() != null) { - biometricRecord = filterExceptionBiometrics(biometricRecord); - if (biometricRecord != null && biometricRecord.getSegments() != null) { - validateUserBiometric(registrationId, introducerUIN, biometricRecord.getSegments(), INDIVIDUAL_TYPE_UIN, - registrationStatusDto); - } else { - registrationStatusDto.setLatestTransactionStatusCode(registrationExceptionMapperUtil - .getStatusCode(RegistrationExceptionTypeCode.INTRODUCER_BIOMETRIC_ALL_EXCEPTION_IN_PACKET)); - registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.toString()); - regProcLogger.debug("validateIntroducerBiometric call ended for registrationId {} {}", registrationId, - StatusUtil.INTRODUCER_BIOMETRIC_ALL_EXCEPTION_IN_PACKET.getMessage()); - throw new BaseCheckedException(StatusUtil.INTRODUCER_BIOMETRIC_ALL_EXCEPTION_IN_PACKET.getMessage(), - StatusUtil.INTRODUCER_BIOMETRIC_ALL_EXCEPTION_IN_PACKET.getCode()); - } - - } else { - registrationStatusDto.setLatestTransactionStatusCode(registrationExceptionMapperUtil - .getStatusCode(RegistrationExceptionTypeCode.INTRODUCER_BIOMETRIC_NOT_IN_PACKET)); - registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.toString()); - regProcLogger.debug("validateIntroducerBiometric call ended for registrationId {} {}", registrationId, - StatusUtil.INTRODUCER_BIOMETRIC_FILE_NAME_NOT_FOUND.getMessage()); - throw new BaseCheckedException(StatusUtil.INTRODUCER_BIOMETRIC_FILE_NAME_NOT_FOUND.getMessage(), - StatusUtil.INTRODUCER_BIOMETRIC_FILE_NAME_NOT_FOUND.getCode()); - } - } - - - /** - * 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 - * @throws BiometricException - */ - - private void validateUserBiometric(String registrationId, String userId, List list, String individualType, - InternalRegistrationStatusDto registrationStatusDto) throws Exception { - regProcLogger.info("validateUserBiometric call started for registrationId {}", registrationId); - bioUtil.authenticateBiometrics(userId, individualType, list, registrationStatusDto,StatusUtil.INTRODUCER_AUTHENTICATION_FAILED.getCode(),StatusUtil.INTRODUCER_AUTHENTICATION_FAILED.getCode()); - regProcLogger.debug("validateUserBiometric call ended for registrationId {}", registrationId); - } - - private BiometricRecord filterExceptionBiometrics(BiometricRecord biometricRecord) { - List segments = biometricRecord.getSegments().stream().filter(bio -> { - Map othersMap = bio.getOthers().entrySet().stream() - .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue())); - return (othersMap == null || !othersMap.containsKey("EXCEPTION")) ? true - : !(Boolean.parseBoolean(othersMap.get("EXCEPTION"))); - }).collect(Collectors.toList()); - if (segments != null) { - segments = segments.stream().filter(bio -> !bio.getBdbInfo().getType().get(0).name() - .equalsIgnoreCase(BiometricType.EXCEPTION_PHOTO.name())).collect(Collectors.toList()); - } - BiometricRecord biorecord = new BiometricRecord(); - biorecord.setSegments(segments); - return biorecord; - } - +package io.mosip.registration.processor.stages.introducervalidator; + +import java.io.IOException; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import javax.xml.parsers.ParserConfigurationException; + +import org.apache.commons.collections.CollectionUtils; +import org.json.JSONArray; +import org.json.JSONException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; +import org.xml.sax.SAXException; + +import com.fasterxml.jackson.databind.ObjectMapper; + +import io.mosip.kernel.biometrics.constant.BiometricType; +import io.mosip.kernel.biometrics.entities.BIR; +import io.mosip.kernel.biometrics.entities.BiometricRecord; +import io.mosip.kernel.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.kernel.core.util.exception.JsonProcessingException; +import io.mosip.registration.processor.core.code.RegistrationExceptionTypeCode; +import io.mosip.registration.processor.core.constant.JsonConstant; +import io.mosip.registration.processor.core.constant.MappingJsonConstants; +import io.mosip.registration.processor.core.constant.ProviderStageName; +import io.mosip.registration.processor.core.constant.RegistrationType; +import io.mosip.registration.processor.core.exception.ApisResourceAccessException; +import io.mosip.registration.processor.core.exception.IntroducerOnHoldException; +import io.mosip.registration.processor.core.exception.PacketDecryptionFailureException; +import io.mosip.registration.processor.core.exception.PacketManagerException; +import io.mosip.registration.processor.core.exception.RegistrationProcessorCheckedException; +import io.mosip.registration.processor.core.exception.ValidationFailedException; +import io.mosip.registration.processor.core.logger.RegProcessorLogger; +import io.mosip.registration.processor.core.packet.dto.FieldValue; +import io.mosip.registration.processor.core.status.util.StatusUtil; +import io.mosip.registration.processor.core.util.RegistrationExceptionMapperUtil; +import io.mosip.registration.processor.packet.manager.idreposervice.IdRepoService; +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; +import io.mosip.registration.processor.status.dto.RegistrationStatusDto; +import io.mosip.registration.processor.status.service.RegistrationStatusService; + +@Service +public class IntroducerValidator { + + private static Logger regProcLogger = RegProcessorLogger.getLogger(IntroducerValidator.class); + + public static final String INDIVIDUAL_TYPE_UIN = "UIN"; + + @Autowired + RegistrationExceptionMapperUtil registrationExceptionMapperUtil; + + @Autowired + private PriorityBasedPacketManagerService packetManagerService; + + @Autowired + private IdRepoService idRepoService; + + @Autowired + RegistrationStatusService registrationStatusService; + + @Autowired + ObjectMapper mapper; + + + + @Autowired + private Utilities utility; + + @Autowired + private BioSdkUtil bioUtil; + + @Value("#{T(java.util.Arrays).asList('${mosip.regproc.common.before-cbeff-others-attibute.reg-client-versions:}')}") + private List regClientVersionsBeforeCbeffOthersAttritube; + + /** + * Checks if is valid introducer. + * + * @param registrationId the registration id + * @param registrationStatusDto + * @throws SAXException + * @throws ParserConfigurationException + * @throws BiometricException + * @throws io.mosip.kernel.core.exception.IOException + * @throws Exception + * @throws PacketDecryptionFailureException + * @throws RegistrationProcessorCheckedException + */ + public void validate(String registrationId, InternalRegistrationStatusDto registrationStatusDto) throws Exception { + + regProcLogger.debug("validate called for registrationId {}", registrationId); + + String introducerUIN = packetManagerService.getFieldByMappingJsonKey(registrationId, + MappingJsonConstants.INTRODUCER_UIN, registrationStatusDto.getRegistrationType(), + ProviderStageName.INTRODUCER_VALIDATOR); + String introducerRID = packetManagerService.getFieldByMappingJsonKey(registrationId, + MappingJsonConstants.INTRODUCER_RID, registrationStatusDto.getRegistrationType(), + ProviderStageName.INTRODUCER_VALIDATOR); + + if (isValidIntroducer(introducerUIN, introducerRID)) { + registrationStatusDto.setLatestTransactionStatusCode(registrationExceptionMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.INTRODUCER_UIN_AND_RID_NOT_IN_PACKET)); + registrationStatusDto.setStatusCode(RegistrationStatusCode.REJECTED.toString()); + regProcLogger.debug("validate called for registrationId {} {}", registrationId, + StatusUtil.UIN_RID_NOT_FOUND.getMessage()); + throw new BaseCheckedException(StatusUtil.UIN_RID_NOT_FOUND.getMessage(), + StatusUtil.UIN_RID_NOT_FOUND.getCode()); + } + + if ((introducerUIN == null || introducerUIN.isEmpty()) + && isValidIntroducerRid(introducerRID, registrationId, registrationStatusDto)) { + + introducerUIN = idRepoService.getUinByRid(introducerRID, utility.getGetRegProcessorDemographicIdentity()); + + if (introducerUIN == null) { + registrationStatusDto.setLatestTransactionStatusCode(registrationExceptionMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.INTRODUCER_UIN_NOT_AVAIALBLE)); + registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.toString()); + regProcLogger.debug("validate called for registrationId {} {}", registrationId, + StatusUtil.INTRODUCER_UIN_NOT_FOUND.getMessage()); + throw new BaseCheckedException(StatusUtil.INTRODUCER_UIN_NOT_FOUND.getMessage(), + StatusUtil.INTRODUCER_UIN_NOT_FOUND.getCode()); + } + + } + if (introducerUIN != null && !introducerUIN.isEmpty()) { + validateIntroducerBiometric(registrationId, registrationStatusDto, introducerUIN); + } else { + throw new ValidationFailedException(StatusUtil.INTRODUCER_AUTHENTICATION_FAILED.getMessage(), + StatusUtil.INTRODUCER_AUTHENTICATION_FAILED.getCode()); + } + + regProcLogger.debug("validate call ended for registrationId {}", registrationId); + } + + private boolean isValidIntroducer(String introducerUIN, String introducerRID) { + return ((introducerUIN == null && introducerRID == null) || ((introducerUIN != null && introducerUIN.isEmpty()) + && (introducerRID != null && introducerRID.isEmpty()))); + } + + /** + * Validate introducer rid. + * + * @param introducerRid the introducer rid + * @param registrationId the registration id + * @param registrationStatusDto + * @return true, if successful + * @throws BaseCheckedException + */ + private boolean isValidIntroducerRid(String introducerRid, String registrationId, + InternalRegistrationStatusDto registrationStatusDto) throws BaseCheckedException { + + List internalRegistrationStatusDtoList= registrationStatusService.getAllRegistrationStatuses(introducerRid); + InternalRegistrationStatusDto introducerRegistrationStatusDto=CollectionUtils.isNotEmpty(internalRegistrationStatusDtoList) ? + internalRegistrationStatusDtoList.stream().filter(s -> RegistrationType.NEW.name().equalsIgnoreCase(s.getRegistrationType())).collect(Collectors.toList()).iterator().next() + : null; + if (introducerRegistrationStatusDto != null) { + if (introducerRegistrationStatusDto.getStatusCode().equals(RegistrationStatusCode.PROCESSING.toString())) { + + registrationStatusDto.setLatestTransactionStatusCode(registrationExceptionMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.ON_HOLD_INTRODUCER_PACKET)); + + registrationStatusDto.setStatusComment(StatusUtil.PACKET_ON_HOLD.getMessage()); + registrationStatusDto.setSubStatusCode(StatusUtil.PACKET_ON_HOLD.getCode()); + registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); + regProcLogger.debug("isValidIntroducerRid call ended for registrationId {} {}", registrationId, + StatusUtil.PACKET_ON_HOLD.getMessage()); + throw new IntroducerOnHoldException(StatusUtil.PACKET_ON_HOLD.getCode(), + StatusUtil.PACKET_ON_HOLD.getMessage()); + + } else if (introducerRegistrationStatusDto.getStatusCode() + .equals(RegistrationStatusCode.REJECTED.toString()) + || introducerRegistrationStatusDto.getStatusCode() + .equals(RegistrationStatusCode.FAILED.toString())) { + + registrationStatusDto.setLatestTransactionStatusCode(registrationExceptionMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.OSI_FAILED_REJECTED_INTRODUCER)); + + registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.toString()); + regProcLogger.debug("isValidIntroducerRid call ended for registrationId {} {}", registrationId, + StatusUtil.CHILD_PACKET_REJECTED.getMessage()); + throw new BaseCheckedException(StatusUtil.CHILD_PACKET_REJECTED.getMessage(), + StatusUtil.CHILD_PACKET_REJECTED.getCode()); + } else { + return true; + } + + } else { + registrationStatusDto.setLatestTransactionStatusCode(registrationExceptionMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.ON_HOLD_INTRODUCER_PACKET)); + + registrationStatusDto.setStatusComment(StatusUtil.PACKET_IS_ON_HOLD.getMessage()); + registrationStatusDto.setSubStatusCode(StatusUtil.PACKET_IS_ON_HOLD.getCode()); + registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); + regProcLogger.debug("isValidIntroducerRid call ended for registrationId {} {}", registrationId, + StatusUtil.PACKET_ON_HOLD.getMessage()); + throw new IntroducerOnHoldException(StatusUtil.PACKET_ON_HOLD.getCode(), + StatusUtil.PACKET_ON_HOLD.getMessage()); + } + } + + private void validateIntroducerBiometric(String registrationId, InternalRegistrationStatusDto registrationStatusDto, + String introducerUIN) + throws Exception { + BiometricRecord biometricRecord = packetManagerService.getBiometricsByMappingJsonKey(registrationId, + MappingJsonConstants.INTRODUCER_BIO, registrationStatusDto.getRegistrationType(), + ProviderStageName.INTRODUCER_VALIDATOR); + if (biometricRecord != null && biometricRecord.getSegments() != null) { + biometricRecord = filterExceptionBiometrics(biometricRecord, registrationId, + registrationStatusDto.getRegistrationType()); + if (biometricRecord != null && biometricRecord.getSegments() != null) { + validateUserBiometric(registrationId, introducerUIN, biometricRecord.getSegments(), INDIVIDUAL_TYPE_UIN, + registrationStatusDto); + } else { + registrationStatusDto.setLatestTransactionStatusCode(registrationExceptionMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.INTRODUCER_BIOMETRIC_ALL_EXCEPTION_IN_PACKET)); + registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.toString()); + regProcLogger.debug("validateIntroducerBiometric call ended for registrationId {} {}", registrationId, + StatusUtil.INTRODUCER_BIOMETRIC_ALL_EXCEPTION_IN_PACKET.getMessage()); + throw new BaseCheckedException(StatusUtil.INTRODUCER_BIOMETRIC_ALL_EXCEPTION_IN_PACKET.getMessage(), + StatusUtil.INTRODUCER_BIOMETRIC_ALL_EXCEPTION_IN_PACKET.getCode()); + } + + } else { + registrationStatusDto.setLatestTransactionStatusCode(registrationExceptionMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.INTRODUCER_BIOMETRIC_NOT_IN_PACKET)); + registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.toString()); + regProcLogger.debug("validateIntroducerBiometric call ended for registrationId {} {}", registrationId, + StatusUtil.INTRODUCER_BIOMETRIC_FILE_NAME_NOT_FOUND.getMessage()); + throw new BaseCheckedException(StatusUtil.INTRODUCER_BIOMETRIC_FILE_NAME_NOT_FOUND.getMessage(), + StatusUtil.INTRODUCER_BIOMETRIC_FILE_NAME_NOT_FOUND.getCode()); + } + } + + + /** + * 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 + * @throws BiometricException + */ + + private void validateUserBiometric(String registrationId, String userId, List list, String individualType, + InternalRegistrationStatusDto registrationStatusDto) throws Exception { + regProcLogger.info("validateUserBiometric call started for registrationId {}", registrationId); + bioUtil.authenticateBiometrics(userId, individualType, list, registrationStatusDto,StatusUtil.INTRODUCER_AUTHENTICATION_FAILED.getCode(),StatusUtil.INTRODUCER_AUTHENTICATION_FAILED.getCode()); + regProcLogger.debug("validateUserBiometric call ended for registrationId {}", registrationId); + } + + private BiometricRecord filterExceptionBiometrics(BiometricRecord biometricRecord, String id, String process) + throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException, + JSONException { + String version = getRegClientVersionFromMetaInfo(id, process, + packetManagerService.getMetaInfo(id, process, ProviderStageName.INTRODUCER_VALIDATOR)); + if (regClientVersionsBeforeCbeffOthersAttritube.contains(version)) { + return biometricRecord; + } + List segments = biometricRecord.getSegments().stream().filter(bio -> { + Map othersMap = bio.getOthers().entrySet().stream() + .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue())); + return (othersMap == null || !othersMap.containsKey("EXCEPTION")) ? true + : !(Boolean.parseBoolean(othersMap.get("EXCEPTION"))); + }).collect(Collectors.toList()); + if (segments != null) { + segments = segments.stream().filter(bio -> !bio.getBdbInfo().getType().get(0).name() + .equalsIgnoreCase(BiometricType.EXCEPTION_PHOTO.name())).collect(Collectors.toList()); + } + BiometricRecord biorecord = new BiometricRecord(); + biorecord.setSegments(segments); + return biorecord; + } + + private String getRegClientVersionFromMetaInfo(String id, String process, Map metaInfoMap) + throws ApisResourceAccessException, PacketManagerException, IOException, JSONException { + String metadata = metaInfoMap.get(JsonConstant.METADATA); + String version = null; + if (StringUtils.isNotEmpty(metadata)) { + JSONArray jsonArray = new JSONArray(metadata); + + for (int i = 0; i < jsonArray.length(); i++) { + if (!jsonArray.isNull(i)) { + org.json.JSONObject jsonObject = (org.json.JSONObject) jsonArray.get(i); + FieldValue fieldValue = mapper.readValue(jsonObject.toString(), FieldValue.class); + if (fieldValue.getLabel().equalsIgnoreCase(JsonConstant.REGCLIENTVERSION)) { + version = fieldValue.getValue(); + break; + } + } + } + } + return version; + } } \ No newline at end of file diff --git a/registration-processor/pre-processor/registration-processor-introducer-validator-stage/src/test/java/io/mosip/registration/processor/introducer/IntroducerValidatorTest.java b/registration-processor/pre-processor/registration-processor-introducer-validator-stage/src/test/java/io/mosip/registration/processor/introducer/IntroducerValidatorTest.java index d2f0307812f..c7216226b71 100644 --- a/registration-processor/pre-processor/registration-processor-introducer-validator-stage/src/test/java/io/mosip/registration/processor/introducer/IntroducerValidatorTest.java +++ b/registration-processor/pre-processor/registration-processor-introducer-validator-stage/src/test/java/io/mosip/registration/processor/introducer/IntroducerValidatorTest.java @@ -1,448 +1,461 @@ -package io.mosip.registration.processor.introducer; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.when; -import static org.mockito.Mockito.doNothing; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.security.NoSuchAlgorithmException; -import java.security.spec.InvalidKeySpecException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import javax.xml.parsers.ParserConfigurationException; - -import org.apache.commons.io.IOUtils; -import org.assertj.core.util.Lists; -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.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.xml.sax.SAXException; - -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.core.bioapi.exception.BiometricException; -import io.mosip.kernel.core.exception.BaseCheckedException; -import io.mosip.registration.processor.core.auth.dto.AuthResponseDTO; -import io.mosip.registration.processor.core.auth.dto.ErrorDTO; -import io.mosip.registration.processor.core.constant.JsonConstant; -import io.mosip.registration.processor.core.constant.MappingJsonConstants; -import io.mosip.registration.processor.core.constant.PacketFiles; -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.BioTypeException; -import io.mosip.registration.processor.core.exception.IntroducerOnHoldException; -import io.mosip.registration.processor.core.idrepo.dto.IdResponseDTO; -import io.mosip.registration.processor.core.idrepo.dto.ResponseDTO; -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.RIDResponseDto; -import io.mosip.registration.processor.core.packet.dto.RidDto; -import io.mosip.registration.processor.core.packet.dto.demographicinfo.DemographicInfoDto; -import io.mosip.registration.processor.core.packet.dto.masterdata.UserDetailsDto; -import io.mosip.registration.processor.core.packet.dto.masterdata.UserDetailsResponseDto; -import io.mosip.registration.processor.core.packet.dto.masterdata.UserResponseDto; -import io.mosip.registration.processor.core.util.JsonUtil; -import io.mosip.registration.processor.core.util.RegistrationExceptionMapperUtil; -import io.mosip.registration.processor.packet.manager.idreposervice.IdRepoService; -import io.mosip.registration.processor.packet.storage.utils.ABISHandlerUtil; -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.stages.introducervalidator.IntroducerValidator; -import io.mosip.registration.processor.status.code.RegistrationStatusCode; -import io.mosip.registration.processor.status.dto.InternalRegistrationStatusDto; -import io.mosip.registration.processor.status.dto.RegistrationStatusDto; -import io.mosip.registration.processor.status.dto.TransactionDto; -import io.mosip.registration.processor.status.service.RegistrationStatusService; -import io.mosip.registration.processor.status.service.TransactionService; - -/** - * The Class IntroducerValidatorTest. - * - * @author M1022006 - */ -@RunWith(PowerMockRunner.class) -@PrepareForTest({ Utilities.class, IOUtils.class }) -@PowerMockIgnore({ "com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "javax.management.*", "javax.net.ssl.*" }) -public class IntroducerValidatorTest { - - /** The input stream. */ - @Mock - private InputStream inputStream; - - /** The registration status service. */ - @Mock - RegistrationStatusService registrationStatusService; - - @Mock - private IdRepoService idRepoService; - - /** The transcation status service. */ - @Mock - private TransactionService transcationStatusService; - - /** The auth response DTO. */ -// @Mock -// AuthResponseDTO authResponseDTO = new AuthResponseDTO(); - - - @Mock - BioSdkUtil biosdk; - - @Mock - private ABISHandlerUtil abisHandlerUtil; - - /** The env. */ - @Mock - Environment env; - - /** The data. */ - byte[] data = "1234567890".getBytes(); - - /** The registration status dto. */ - InternalRegistrationStatusDto registrationStatusDto = new InternalRegistrationStatusDto(); - - /** The transaction dto. */ - TransactionDto transactionDto = new TransactionDto(); - - /** The supervisor validator. */ - @InjectMocks - IntroducerValidator introducerValidator; - - @Mock - private Utilities utility; - - - - /** The demographic dedupe dto list. */ - List demographicDedupeDtoList = new ArrayList<>(); - - /** The demographic info dto. */ - DemographicInfoDto demographicInfoDto = new DemographicInfoDto(); - - /** The identity. */ - private Identity identity = new Identity(); - - private JSONObject demoJson = new JSONObject(); - private UserResponseDto userResponseDto = new UserResponseDto(); - private RidDto ridDto = new RidDto(); - private ResponseDTO responseDTO1 = new ResponseDTO(); - private RIDResponseDto ridResponseDto1 = new RIDResponseDto(); - private IdResponseDTO idResponseDTO = new IdResponseDTO(); - @Mock - RegistrationExceptionMapperUtil registrationExceptionMapperUtil; - - @Mock - LogDescription description; - private ClassLoader classLoader; - - @Mock - private PriorityBasedPacketManagerService packetManagerService; - - /** - * Sets the up. - * - * @throws Exception the exception - */ - @Before - public void setUp() throws Exception { - classLoader = getClass().getClassLoader(); - - Mockito.when(utility.isUinMissingFromIdAuth(any(),any(),any())).thenReturn(false); - Mockito.when(utility.getGetRegProcessorDemographicIdentity()).thenReturn("identity"); - File file = new File(classLoader.getResource("RegistrationProcessorIdentity.json").getFile()); - InputStream inputStream = new FileInputStream(file); - String mappingJson = IOUtils.toString(inputStream); - JSONObject mappingJSONObject = JsonUtil.objectMapperReadValue(mappingJson, JSONObject.class); - Mockito.when(utility.getRegistrationProcessorMappingJson(anyString())) - .thenReturn(JsonUtil.getJSONObject(mappingJSONObject, MappingJsonConstants.IDENTITY)); - PowerMockito.mockStatic(Utilities.class); - PowerMockito.when(Utilities.class, "getJson", anyString(), anyString()).thenReturn(mappingJson); - Mockito.doNothing().when(description).setMessage(any()); - Mockito.when(registrationExceptionMapperUtil.getStatusCode(any())).thenReturn("ERROR"); - - demographicDedupeDtoList.add(demographicInfoDto); - - Mockito.when(env.getProperty("mosip.kernel.applicant.type.age.limit")).thenReturn("5"); - PowerMockito.mockStatic(IOUtils.class); - PowerMockito.when(IOUtils.class, "toByteArray", inputStream).thenReturn(data); - - // Mockito.when(authUtil.authByIdAuthentication(anyString(), any(), any())).thenReturn(authResponseDTO); - - registrationStatusDto.setRegistrationId("reg1234"); - registrationStatusDto.setApplicantType("Child"); - registrationStatusDto.setRegistrationType("New"); - - Mockito.when(registrationStatusService.getRegistrationStatus(anyString(), any(), any(), any())).thenReturn(registrationStatusDto); - - FieldValue officerBiofileName = new FieldValue(); - officerBiofileName.setLabel(MappingJsonConstants.OFFICERBIOMETRICFILENAME); - officerBiofileName.setValue("officer_bio_CBEFF"); - - FieldValue officerPassword = new FieldValue(); - officerPassword.setLabel(JsonConstant.OFFICERPWR); - officerPassword.setValue("false"); - - FieldValue officerOtp = new FieldValue(); - officerOtp.setLabel(JsonConstant.OFFICEROTPAUTHENTICATION); - officerOtp.setValue("false"); - - FieldValue supervisorPassword = new FieldValue(); - supervisorPassword.setLabel(JsonConstant.SUPERVISORPWR); - supervisorPassword.setValue("true"); - - FieldValue supervisorId = new FieldValue(); - supervisorId.setLabel(JsonConstant.SUPERVISORID); - supervisorId.setValue("110016"); - - FieldValue supervisorOtp = new FieldValue(); - supervisorOtp.setLabel(MappingJsonConstants.SUPERVISOROTPAUTHENTICATION); - supervisorOtp.setValue("false"); - - FieldValue supervisorBiofileName = new FieldValue(); - supervisorBiofileName.setLabel(MappingJsonConstants.SUPERVISORBIOMETRICFILENAME); - supervisorBiofileName.setValue("supervisor_bio_CBEFF"); - - FieldValue creationDate = new FieldValue(); - creationDate.setLabel("creationDate"); - creationDate.setValue("2019-04-30T12:42:03.541Z"); - - identity.setOsiData((Arrays.asList(officerBiofileName, officerOtp, officerPassword, supervisorOtp, - supervisorPassword, supervisorId, supervisorBiofileName))); - identity.setMetaData((Arrays.asList(creationDate))); - List fieldValueArrayList = new ArrayList(); - FieldValueArray introducerBiometric = new FieldValueArray(); - introducerBiometric.setLabel(PacketFiles.INTRODUCERBIOMETRICSEQUENCE.name()); - List introducerBiometricValues = new ArrayList(); - introducerBiometricValues.add("introducer_bio_CBEFF"); - introducerBiometric.setValue(introducerBiometricValues); - fieldValueArrayList.add(introducerBiometric); - identity.setHashSequence(fieldValueArrayList); - - UserDetailsResponseDto userDetailsResponseDto = new UserDetailsResponseDto(); - UserDetailsDto userDetailsDto = new UserDetailsDto(); - userDetailsDto.setIsActive(true); - userDetailsResponseDto.setUserResponseDto(Arrays.asList(userDetailsDto)); - userResponseDto.setResponse(userDetailsResponseDto); - ridDto.setRid("reg4567"); - ridResponseDto1.setResponse(ridDto); - String identityJson = "{\"UIN\":\"123456\"}"; - responseDTO1.setIdentity(identityJson); - idResponseDTO.setResponse(responseDTO1); - - //File cbeffFile = new File(classLoader.getResource("cbeff.xml").getFile()); - - BIR birType3 = new BIR.BIRBuilder().build(); - BDBInfo bdbInfoType3 = new BDBInfo.BDBInfoBuilder().build(); - bdbInfoType3.setQuality(new QualityType()); - BiometricType singleType3 = BiometricType.IRIS; - List singleTypeList3 = new ArrayList<>(); - singleTypeList3.add(singleType3); - List subtype3 = new ArrayList<>(Arrays.asList("Right")); - bdbInfoType3.setSubtype(subtype3); - bdbInfoType3.setType(singleTypeList3); - birType3.setBdbInfo(bdbInfoType3); - - BIR birType4 = new BIR.BIRBuilder().build(); - BDBInfo bdbInfoType4 = new BDBInfo.BDBInfoBuilder().build(); - bdbInfoType4.setQuality(new QualityType()); - BiometricType singleType4 = BiometricType.FACE; - List singleTypeList4 = new ArrayList<>(); - singleTypeList4.add(singleType4); - List subtype4 = new ArrayList<>(); - bdbInfoType4.setSubtype(subtype4); - bdbInfoType4.setType(singleTypeList4); - birType4.setBdbInfo(bdbInfoType4); - - BiometricRecord biometricRecord = new BiometricRecord(); - biometricRecord.setSegments(Lists.newArrayList(birType3, birType4)); - when(packetManagerService.getBiometricsByMappingJsonKey(anyString(), any(), any(), any())) - .thenReturn(biometricRecord); - - when(packetManagerService.getFieldByMappingJsonKey(anyString(), anyString(), anyString(), any())) - .thenReturn("field"); - - doNothing().when(biosdk).authenticateBiometrics(Mockito.anyString(), Mockito.anyString(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any()); - } - - /** - * Test introducer details null. - * - * @throws Exception the exception - */ - @Test - @Ignore - public void testIntroducerDetailsNull() throws Exception { - introducerValidator.validate("reg1234", registrationStatusDto); - } - - /** - * Test invalid iris. - * - * @throws SAXException - * @throws ParserConfigurationException - * @throws BioTypeException - * @throws BiometricException - * @throws NoSuchAlgorithmException - * @throws InvalidKeySpecException - * @throws NumberFormatException - * @throws ApisResourceAccessException the apis resource access exception - * @throws IOException Signals that an I/O exception has - * occurred. - */ - @Test(expected = BaseCheckedException.class) - public void testIntroducerRIDFailedOnHold() throws ApisResourceAccessException, IOException, Exception { - registrationStatusDto.setStatusCode("FAILED"); - List internalRegistrationStatusDtoList=new ArrayList(); - internalRegistrationStatusDtoList.add(registrationStatusDto); - - Mockito.when(registrationStatusService.getAllRegistrationStatuses(anyString())).thenReturn(internalRegistrationStatusDtoList); - when(packetManagerService.getFieldByMappingJsonKey("reg1234", "introducerUIN", "New", - ProviderStageName.INTRODUCER_VALIDATOR)).thenReturn(null); - when(packetManagerService.getFieldByMappingJsonKey("reg1234", "introducerRID", "New", - ProviderStageName.INTRODUCER_VALIDATOR)).thenReturn("field"); - introducerValidator.validate("reg1234", registrationStatusDto); - } - - @Test(expected = BaseCheckedException.class) - public void testIntroducerBiometricValidationFailed() throws ApisResourceAccessException, IOException, Exception { - - when(packetManagerService.getFieldByMappingJsonKey("reg1234", "introducerUIN", "New", - ProviderStageName.INTRODUCER_VALIDATOR)).thenReturn("2832677"); - when(packetManagerService.getFieldByMappingJsonKey("reg1234", "introducerRID", "New", - ProviderStageName.INTRODUCER_VALIDATOR)).thenReturn("field"); - when(packetManagerService.getBiometricsByMappingJsonKey(anyString(), any(), any(), any())) - .thenReturn(null); - introducerValidator.validate("reg1234", registrationStatusDto); - } - - @Test(expected = BaseCheckedException.class) - public void testIntroducerRIDUINNotFound() throws ApisResourceAccessException, IOException, Exception { - registrationStatusDto.setStatusCode("PROCESSED"); - List internalRegistrationStatusDtoList=new ArrayList(); - internalRegistrationStatusDtoList.add(registrationStatusDto); - - Mockito.when(registrationStatusService.getAllRegistrationStatuses(anyString())).thenReturn(internalRegistrationStatusDtoList); - when(packetManagerService.getFieldByMappingJsonKey("reg1234", "introducerUIN", "New", - ProviderStageName.INTRODUCER_VALIDATOR)).thenReturn(null); - when(packetManagerService.getFieldByMappingJsonKey("reg1234", "introducerRID", "New", - ProviderStageName.INTRODUCER_VALIDATOR)).thenReturn("field"); - introducerValidator.validate("reg1234", registrationStatusDto); - } - - @Test(expected = IntroducerOnHoldException.class) - public void testIntroducerRIDProcessingOnHold() - throws Exception { - registrationStatusDto.setStatusCode((RegistrationStatusCode.PROCESSING.toString())); - List internalRegistrationStatusDtoList=new ArrayList(); - internalRegistrationStatusDtoList.add(registrationStatusDto); - Mockito.when(registrationStatusService.getAllRegistrationStatuses(anyString())).thenReturn(internalRegistrationStatusDtoList); - - when(packetManagerService.getFieldByMappingJsonKey("reg1234", "introducerUIN", "New", - ProviderStageName.INTRODUCER_VALIDATOR)).thenReturn(null); - when(packetManagerService.getFieldByMappingJsonKey("reg1234", "introducerRID", "New", - ProviderStageName.INTRODUCER_VALIDATOR)).thenReturn("field"); - - introducerValidator.validate("reg1234", registrationStatusDto); - } - - @Test(expected = BaseCheckedException.class) - public void testIntroducerUINAndRIDNotPresent() throws Exception { - when(packetManagerService.getFieldByMappingJsonKey("reg1234", "introducerUIN", "New", - ProviderStageName.INTRODUCER_VALIDATOR)).thenReturn(""); - when(packetManagerService.getFieldByMappingJsonKey("reg1234", "introducerRID", "New", - ProviderStageName.INTRODUCER_VALIDATOR)).thenReturn(""); - - introducerValidator.validate("reg1234", registrationStatusDto); - } - - @Test(expected = IntroducerOnHoldException.class) - @Ignore - public void testIntroducerNotInRegProc() throws Exception { - InternalRegistrationStatusDto registrationStatusDto = new InternalRegistrationStatusDto(); - registrationStatusDto.setStatusCode(RegistrationStatusCode.REJECTED.toString()); - registrationStatusDto.setRegistrationType("NEW"); - when(packetManagerService.getFieldByMappingJsonKey("reg1234", "introducerUIN", "New", - ProviderStageName.INTRODUCER_VALIDATOR)).thenReturn(null); - when(packetManagerService.getFieldByMappingJsonKey("reg1234", "introducerRID", "New", - ProviderStageName.INTRODUCER_VALIDATOR)).thenReturn("field"); - - Mockito.when(registrationStatusService.getAllRegistrationStatuses(anyString())).thenReturn(null); - introducerValidator.validate("reg1234", registrationStatusDto); - } - - @Test - public void testIntroducerBioFileNotNull() throws Exception { - demoJson.put("value", "biometreics"); - - // AuthResponseDTO authResponseDTO1 = new AuthResponseDTO(); - // authResponseDTO1.setErrors(null); - io.mosip.registration.processor.core.auth.dto.ResponseDTO responseDTO = new io.mosip.registration.processor.core.auth.dto.ResponseDTO(); - responseDTO.setAuthStatus(true); - // authResponseDTO1.setResponse(responseDTO); - //Mockito.when(authUtil.authByIdAuthentication(anyString(), any(), any())).thenReturn(authResponseDTO1); - - registrationStatusDto.setStatusCode("PROCESSED"); - Mockito.when(registrationStatusService.getRegistrationStatus(anyString(), any(), any(), any())).thenReturn(registrationStatusDto); - Mockito.when(idRepoService.getUinByRid(any(), any())).thenReturn("123456789"); - introducerValidator.validate("reg1234", registrationStatusDto); - } - - @Test - public void testIntroducerErrorTrue() throws Exception { - // Mockito.when(osiUtils.getMetaDataValue(anyString(), - // any())).thenReturn("2015/01/01"); - demoJson.put("value", "biometreics"); - introducerValidator.validate("reg1234", registrationStatusDto); - } - - @Test - public void testIntroducerAuthSystemError() throws Exception { - demoJson.put("value", "biometreics"); - introducerValidator.validate("reg1234", registrationStatusDto); - } - - @Test - public void testIntroducerAuthFalse() throws Exception { - registrationStatusDto.setStatusCode("PROCESSED"); - Mockito.when(registrationStatusService.getRegistrationStatus(anyString(), any(), any(), any())).thenReturn(registrationStatusDto); - Mockito.when(idRepoService.getUinByRid(any(), any())).thenReturn("123456789"); - introducerValidator.validate("reg1234", registrationStatusDto); - } - - @Test(expected = BaseCheckedException.class) - public void testIntroducerUINNull() throws Exception { - InternalRegistrationStatusDto introducerRegistrationStatusDto = new InternalRegistrationStatusDto(); - introducerRegistrationStatusDto.setStatusCode((RegistrationStatusCode.PROCESSED.toString())); - Mockito.when(registrationStatusService.getRegistrationStatus(anyString(), any(), any(), any())) - .thenReturn(introducerRegistrationStatusDto); - when(packetManagerService.getFieldByMappingJsonKey("reg1234", "introducerUIN", "New", - ProviderStageName.INTRODUCER_VALIDATOR)).thenReturn(null); - when(packetManagerService.getFieldByMappingJsonKey("reg1234", "introducerRID", "New", - ProviderStageName.INTRODUCER_VALIDATOR)).thenReturn("field"); - Mockito.when(idRepoService.getUinByRid(any(), any())).thenReturn(null); - - introducerValidator.validate("reg1234", registrationStatusDto); - } +package io.mosip.registration.processor.introducer; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.when; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.security.NoSuchAlgorithmException; +import java.security.spec.InvalidKeySpecException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.xml.parsers.ParserConfigurationException; + +import org.apache.commons.io.IOUtils; +import org.assertj.core.util.Lists; +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.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 org.xml.sax.SAXException; + +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.core.bioapi.exception.BiometricException; +import io.mosip.kernel.core.exception.BaseCheckedException; +import io.mosip.registration.processor.core.constant.JsonConstant; +import io.mosip.registration.processor.core.constant.MappingJsonConstants; +import io.mosip.registration.processor.core.constant.PacketFiles; +import io.mosip.registration.processor.core.constant.ProviderStageName; +import io.mosip.registration.processor.core.exception.ApisResourceAccessException; +import io.mosip.registration.processor.core.exception.BioTypeException; +import io.mosip.registration.processor.core.exception.IntroducerOnHoldException; +import io.mosip.registration.processor.core.idrepo.dto.IdResponseDTO; +import io.mosip.registration.processor.core.idrepo.dto.ResponseDTO; +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.RIDResponseDto; +import io.mosip.registration.processor.core.packet.dto.RidDto; +import io.mosip.registration.processor.core.packet.dto.demographicinfo.DemographicInfoDto; +import io.mosip.registration.processor.core.packet.dto.masterdata.UserDetailsDto; +import io.mosip.registration.processor.core.packet.dto.masterdata.UserDetailsResponseDto; +import io.mosip.registration.processor.core.packet.dto.masterdata.UserResponseDto; +import io.mosip.registration.processor.core.util.JsonUtil; +import io.mosip.registration.processor.core.util.RegistrationExceptionMapperUtil; +import io.mosip.registration.processor.packet.manager.idreposervice.IdRepoService; +import io.mosip.registration.processor.packet.storage.utils.ABISHandlerUtil; +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.stages.introducervalidator.IntroducerValidator; +import io.mosip.registration.processor.status.code.RegistrationStatusCode; +import io.mosip.registration.processor.status.dto.InternalRegistrationStatusDto; +import io.mosip.registration.processor.status.dto.RegistrationStatusDto; +import io.mosip.registration.processor.status.dto.TransactionDto; +import io.mosip.registration.processor.status.service.RegistrationStatusService; +import io.mosip.registration.processor.status.service.TransactionService; + +/** + * The Class IntroducerValidatorTest. + * + * @author M1022006 + */ +@RunWith(PowerMockRunner.class) +@PrepareForTest({ Utilities.class, IOUtils.class }) +@PowerMockIgnore({ "com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "javax.management.*", "javax.net.ssl.*" }) +public class IntroducerValidatorTest { + + /** The input stream. */ + @Mock + private InputStream inputStream; + + /** The registration status service. */ + @Mock + RegistrationStatusService registrationStatusService; + + @Mock + private IdRepoService idRepoService; + + /** The transcation status service. */ + @Mock + private TransactionService transcationStatusService; + + /** The auth response DTO. */ +// @Mock +// AuthResponseDTO authResponseDTO = new AuthResponseDTO(); + + + @Mock + BioSdkUtil biosdk; + + @Mock + private ABISHandlerUtil abisHandlerUtil; + + /** The env. */ + @Mock + Environment env; + + /** The data. */ + byte[] data = "1234567890".getBytes(); + + /** The registration status dto. */ + InternalRegistrationStatusDto registrationStatusDto = new InternalRegistrationStatusDto(); + + /** The transaction dto. */ + TransactionDto transactionDto = new TransactionDto(); + + /** The supervisor validator. */ + @InjectMocks + IntroducerValidator introducerValidator; + + @Mock + private Utilities utility; + + + + /** The demographic dedupe dto list. */ + List demographicDedupeDtoList = new ArrayList<>(); + + /** The demographic info dto. */ + DemographicInfoDto demographicInfoDto = new DemographicInfoDto(); + + /** The identity. */ + private Identity identity = new Identity(); + + private JSONObject demoJson = new JSONObject(); + private UserResponseDto userResponseDto = new UserResponseDto(); + private RidDto ridDto = new RidDto(); + private ResponseDTO responseDTO1 = new ResponseDTO(); + private RIDResponseDto ridResponseDto1 = new RIDResponseDto(); + private IdResponseDTO idResponseDTO = new IdResponseDTO(); + @Mock + RegistrationExceptionMapperUtil registrationExceptionMapperUtil; + + @Mock + LogDescription description; + private ClassLoader classLoader; + + @Mock + private PriorityBasedPacketManagerService packetManagerService; + + @Mock + ObjectMapper mapper; + + /** + * Sets the up. + * + * @throws Exception the exception + */ + @Before + public void setUp() throws Exception { + classLoader = getClass().getClassLoader(); + + Mockito.when(utility.isUinMissingFromIdAuth(any(),any(),any())).thenReturn(false); + Mockito.when(utility.getGetRegProcessorDemographicIdentity()).thenReturn("identity"); + File file = new File(classLoader.getResource("RegistrationProcessorIdentity.json").getFile()); + InputStream inputStream = new FileInputStream(file); + String mappingJson = IOUtils.toString(inputStream); + JSONObject mappingJSONObject = JsonUtil.objectMapperReadValue(mappingJson, JSONObject.class); + Mockito.when(utility.getRegistrationProcessorMappingJson(anyString())) + .thenReturn(JsonUtil.getJSONObject(mappingJSONObject, MappingJsonConstants.IDENTITY)); + PowerMockito.mockStatic(Utilities.class); + PowerMockito.when(Utilities.class, "getJson", anyString(), anyString()).thenReturn(mappingJson); + Mockito.doNothing().when(description).setMessage(any()); + Mockito.when(registrationExceptionMapperUtil.getStatusCode(any())).thenReturn("ERROR"); + + demographicDedupeDtoList.add(demographicInfoDto); + + Mockito.when(env.getProperty("mosip.kernel.applicant.type.age.limit")).thenReturn("5"); + PowerMockito.mockStatic(IOUtils.class); + PowerMockito.when(IOUtils.class, "toByteArray", inputStream).thenReturn(data); + + // Mockito.when(authUtil.authByIdAuthentication(anyString(), any(), any())).thenReturn(authResponseDTO); + + registrationStatusDto.setRegistrationId("reg1234"); + registrationStatusDto.setApplicantType("Child"); + registrationStatusDto.setRegistrationType("New"); + + Mockito.when(registrationStatusService.getRegistrationStatus(anyString(), any(), any(), any())).thenReturn(registrationStatusDto); + + FieldValue officerBiofileName = new FieldValue(); + officerBiofileName.setLabel(MappingJsonConstants.OFFICERBIOMETRICFILENAME); + officerBiofileName.setValue("officer_bio_CBEFF"); + + FieldValue officerPassword = new FieldValue(); + officerPassword.setLabel(JsonConstant.OFFICERPWR); + officerPassword.setValue("false"); + + FieldValue officerOtp = new FieldValue(); + officerOtp.setLabel(JsonConstant.OFFICEROTPAUTHENTICATION); + officerOtp.setValue("false"); + + FieldValue supervisorPassword = new FieldValue(); + supervisorPassword.setLabel(JsonConstant.SUPERVISORPWR); + supervisorPassword.setValue("true"); + + FieldValue supervisorId = new FieldValue(); + supervisorId.setLabel(JsonConstant.SUPERVISORID); + supervisorId.setValue("110016"); + + FieldValue supervisorOtp = new FieldValue(); + supervisorOtp.setLabel(MappingJsonConstants.SUPERVISOROTPAUTHENTICATION); + supervisorOtp.setValue("false"); + + FieldValue supervisorBiofileName = new FieldValue(); + supervisorBiofileName.setLabel(MappingJsonConstants.SUPERVISORBIOMETRICFILENAME); + supervisorBiofileName.setValue("supervisor_bio_CBEFF"); + + FieldValue creationDate = new FieldValue(); + creationDate.setLabel("creationDate"); + creationDate.setValue("2019-04-30T12:42:03.541Z"); + + identity.setOsiData((Arrays.asList(officerBiofileName, officerOtp, officerPassword, supervisorOtp, + supervisorPassword, supervisorId, supervisorBiofileName))); + identity.setMetaData((Arrays.asList(creationDate))); + List fieldValueArrayList = new ArrayList(); + FieldValueArray introducerBiometric = new FieldValueArray(); + introducerBiometric.setLabel(PacketFiles.INTRODUCERBIOMETRICSEQUENCE.name()); + List introducerBiometricValues = new ArrayList(); + introducerBiometricValues.add("introducer_bio_CBEFF"); + introducerBiometric.setValue(introducerBiometricValues); + fieldValueArrayList.add(introducerBiometric); + identity.setHashSequence(fieldValueArrayList); + + UserDetailsResponseDto userDetailsResponseDto = new UserDetailsResponseDto(); + UserDetailsDto userDetailsDto = new UserDetailsDto(); + userDetailsDto.setIsActive(true); + userDetailsResponseDto.setUserResponseDto(Arrays.asList(userDetailsDto)); + userResponseDto.setResponse(userDetailsResponseDto); + ridDto.setRid("reg4567"); + ridResponseDto1.setResponse(ridDto); + String identityJson = "{\"UIN\":\"123456\"}"; + responseDTO1.setIdentity(identityJson); + idResponseDTO.setResponse(responseDTO1); + + //File cbeffFile = new File(classLoader.getResource("cbeff.xml").getFile()); + + BIR birType3 = new BIR.BIRBuilder().build(); + BDBInfo bdbInfoType3 = new BDBInfo.BDBInfoBuilder().build(); + bdbInfoType3.setQuality(new QualityType()); + BiometricType singleType3 = BiometricType.IRIS; + List singleTypeList3 = new ArrayList<>(); + singleTypeList3.add(singleType3); + List subtype3 = new ArrayList<>(Arrays.asList("Right")); + bdbInfoType3.setSubtype(subtype3); + bdbInfoType3.setType(singleTypeList3); + birType3.setBdbInfo(bdbInfoType3); + + BIR birType4 = new BIR.BIRBuilder().build(); + BDBInfo bdbInfoType4 = new BDBInfo.BDBInfoBuilder().build(); + bdbInfoType4.setQuality(new QualityType()); + BiometricType singleType4 = BiometricType.FACE; + List singleTypeList4 = new ArrayList<>(); + singleTypeList4.add(singleType4); + List subtype4 = new ArrayList<>(); + bdbInfoType4.setSubtype(subtype4); + bdbInfoType4.setType(singleTypeList4); + birType4.setBdbInfo(bdbInfoType4); + + BiometricRecord biometricRecord = new BiometricRecord(); + biometricRecord.setSegments(Lists.newArrayList(birType3, birType4)); + when(packetManagerService.getBiometricsByMappingJsonKey(anyString(), any(), any(), any())) + .thenReturn(biometricRecord); + + when(packetManagerService.getFieldByMappingJsonKey(anyString(), anyString(), anyString(), any())) + .thenReturn("field"); + ReflectionTestUtils.setField(introducerValidator, "regClientVersionsBeforeCbeffOthersAttritube", + Arrays.asList("1.1.3")); + Map metaInfoMap = new HashMap<>(); + metaInfoMap.put(JsonConstant.METADATA, + "[{\n \"label\" : \"Registration Client Version Number\",\n \"value\" : \"1.2.0\"\n}]"); + Mockito.when(mapper.readValue(anyString(), any(Class.class))) + .thenReturn(new FieldValue("Registration Client Version Number", "1.2.0")); + Mockito.when(packetManagerService.getMetaInfo(any(), any(), any())).thenReturn(metaInfoMap); + doNothing().when(biosdk).authenticateBiometrics(Mockito.anyString(), Mockito.anyString(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any()); + } + + /** + * Test introducer details null. + * + * @throws Exception the exception + */ + @Test + @Ignore + public void testIntroducerDetailsNull() throws Exception { + introducerValidator.validate("reg1234", registrationStatusDto); + } + + /** + * Test invalid iris. + * + * @throws SAXException + * @throws ParserConfigurationException + * @throws BioTypeException + * @throws BiometricException + * @throws NoSuchAlgorithmException + * @throws InvalidKeySpecException + * @throws NumberFormatException + * @throws ApisResourceAccessException the apis resource access exception + * @throws IOException Signals that an I/O exception has + * occurred. + */ + @Test(expected = BaseCheckedException.class) + public void testIntroducerRIDFailedOnHold() throws ApisResourceAccessException, IOException, Exception { + registrationStatusDto.setStatusCode("FAILED"); + List internalRegistrationStatusDtoList=new ArrayList(); + internalRegistrationStatusDtoList.add(registrationStatusDto); + + Mockito.when(registrationStatusService.getAllRegistrationStatuses(anyString())).thenReturn(internalRegistrationStatusDtoList); + when(packetManagerService.getFieldByMappingJsonKey("reg1234", "introducerUIN", "New", + ProviderStageName.INTRODUCER_VALIDATOR)).thenReturn(null); + when(packetManagerService.getFieldByMappingJsonKey("reg1234", "introducerRID", "New", + ProviderStageName.INTRODUCER_VALIDATOR)).thenReturn("field"); + introducerValidator.validate("reg1234", registrationStatusDto); + } + + @Test(expected = BaseCheckedException.class) + public void testIntroducerBiometricValidationFailed() throws ApisResourceAccessException, IOException, Exception { + + when(packetManagerService.getFieldByMappingJsonKey("reg1234", "introducerUIN", "New", + ProviderStageName.INTRODUCER_VALIDATOR)).thenReturn("2832677"); + when(packetManagerService.getFieldByMappingJsonKey("reg1234", "introducerRID", "New", + ProviderStageName.INTRODUCER_VALIDATOR)).thenReturn("field"); + when(packetManagerService.getBiometricsByMappingJsonKey(anyString(), any(), any(), any())) + .thenReturn(null); + introducerValidator.validate("reg1234", registrationStatusDto); + } + + @Test(expected = BaseCheckedException.class) + public void testIntroducerRIDUINNotFound() throws ApisResourceAccessException, IOException, Exception { + registrationStatusDto.setStatusCode("PROCESSED"); + List internalRegistrationStatusDtoList=new ArrayList(); + internalRegistrationStatusDtoList.add(registrationStatusDto); + + Mockito.when(registrationStatusService.getAllRegistrationStatuses(anyString())).thenReturn(internalRegistrationStatusDtoList); + when(packetManagerService.getFieldByMappingJsonKey("reg1234", "introducerUIN", "New", + ProviderStageName.INTRODUCER_VALIDATOR)).thenReturn(null); + when(packetManagerService.getFieldByMappingJsonKey("reg1234", "introducerRID", "New", + ProviderStageName.INTRODUCER_VALIDATOR)).thenReturn("field"); + introducerValidator.validate("reg1234", registrationStatusDto); + } + + @Test(expected = IntroducerOnHoldException.class) + public void testIntroducerRIDProcessingOnHold() + throws Exception { + registrationStatusDto.setStatusCode((RegistrationStatusCode.PROCESSING.toString())); + List internalRegistrationStatusDtoList=new ArrayList(); + internalRegistrationStatusDtoList.add(registrationStatusDto); + Mockito.when(registrationStatusService.getAllRegistrationStatuses(anyString())).thenReturn(internalRegistrationStatusDtoList); + + when(packetManagerService.getFieldByMappingJsonKey("reg1234", "introducerUIN", "New", + ProviderStageName.INTRODUCER_VALIDATOR)).thenReturn(null); + when(packetManagerService.getFieldByMappingJsonKey("reg1234", "introducerRID", "New", + ProviderStageName.INTRODUCER_VALIDATOR)).thenReturn("field"); + + introducerValidator.validate("reg1234", registrationStatusDto); + } + + @Test(expected = BaseCheckedException.class) + public void testIntroducerUINAndRIDNotPresent() throws Exception { + when(packetManagerService.getFieldByMappingJsonKey("reg1234", "introducerUIN", "New", + ProviderStageName.INTRODUCER_VALIDATOR)).thenReturn(""); + when(packetManagerService.getFieldByMappingJsonKey("reg1234", "introducerRID", "New", + ProviderStageName.INTRODUCER_VALIDATOR)).thenReturn(""); + + introducerValidator.validate("reg1234", registrationStatusDto); + } + + @Test(expected = IntroducerOnHoldException.class) + @Ignore + public void testIntroducerNotInRegProc() throws Exception { + InternalRegistrationStatusDto registrationStatusDto = new InternalRegistrationStatusDto(); + registrationStatusDto.setStatusCode(RegistrationStatusCode.REJECTED.toString()); + registrationStatusDto.setRegistrationType("NEW"); + when(packetManagerService.getFieldByMappingJsonKey("reg1234", "introducerUIN", "New", + ProviderStageName.INTRODUCER_VALIDATOR)).thenReturn(null); + when(packetManagerService.getFieldByMappingJsonKey("reg1234", "introducerRID", "New", + ProviderStageName.INTRODUCER_VALIDATOR)).thenReturn("field"); + + Mockito.when(registrationStatusService.getAllRegistrationStatuses(anyString())).thenReturn(null); + introducerValidator.validate("reg1234", registrationStatusDto); + } + + @Test + public void testIntroducerBioFileNotNull() throws Exception { + demoJson.put("value", "biometreics"); + + // AuthResponseDTO authResponseDTO1 = new AuthResponseDTO(); + // authResponseDTO1.setErrors(null); + io.mosip.registration.processor.core.auth.dto.ResponseDTO responseDTO = new io.mosip.registration.processor.core.auth.dto.ResponseDTO(); + responseDTO.setAuthStatus(true); + // authResponseDTO1.setResponse(responseDTO); + //Mockito.when(authUtil.authByIdAuthentication(anyString(), any(), any())).thenReturn(authResponseDTO1); + + registrationStatusDto.setStatusCode("PROCESSED"); + Mockito.when(registrationStatusService.getRegistrationStatus(anyString(), any(), any(), any())).thenReturn(registrationStatusDto); + Mockito.when(idRepoService.getUinByRid(any(), any())).thenReturn("123456789"); + introducerValidator.validate("reg1234", registrationStatusDto); + } + + @Test + public void testIntroducerErrorTrue() throws Exception { + // Mockito.when(osiUtils.getMetaDataValue(anyString(), + // any())).thenReturn("2015/01/01"); + demoJson.put("value", "biometreics"); + introducerValidator.validate("reg1234", registrationStatusDto); + } + + @Test + public void testIntroducerAuthSystemError() throws Exception { + demoJson.put("value", "biometreics"); + introducerValidator.validate("reg1234", registrationStatusDto); + } + + @Test + public void testIntroducerAuthFalse() throws Exception { + registrationStatusDto.setStatusCode("PROCESSED"); + Mockito.when(registrationStatusService.getRegistrationStatus(anyString(), any(), any(), any())).thenReturn(registrationStatusDto); + Mockito.when(idRepoService.getUinByRid(any(), any())).thenReturn("123456789"); + introducerValidator.validate("reg1234", registrationStatusDto); + } + + @Test(expected = BaseCheckedException.class) + public void testIntroducerUINNull() throws Exception { + InternalRegistrationStatusDto introducerRegistrationStatusDto = new InternalRegistrationStatusDto(); + introducerRegistrationStatusDto.setStatusCode((RegistrationStatusCode.PROCESSED.toString())); + Mockito.when(registrationStatusService.getRegistrationStatus(anyString(), any(), any(), any())) + .thenReturn(introducerRegistrationStatusDto); + when(packetManagerService.getFieldByMappingJsonKey("reg1234", "introducerUIN", "New", + ProviderStageName.INTRODUCER_VALIDATOR)).thenReturn(null); + when(packetManagerService.getFieldByMappingJsonKey("reg1234", "introducerRID", "New", + ProviderStageName.INTRODUCER_VALIDATOR)).thenReturn("field"); + Mockito.when(idRepoService.getUinByRid(any(), any())).thenReturn(null); + + introducerValidator.validate("reg1234", registrationStatusDto); + } } \ No newline at end of file From 24ed61a3778cb0f1f793a0801df7f361151af528 Mon Sep 17 00:00:00 2001 From: Akila Lakshmanan <77330852+akilalakshmanan@users.noreply.github.com> Date: Tue, 22 Aug 2023 08:57:30 +0530 Subject: [PATCH 093/133] [MOSIP-28484] Added error handling for deploy.sh script (#1758) Co-authored-by: akilalakshmanan --- db_scripts/mosip_regprc/deploy.sh | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/db_scripts/mosip_regprc/deploy.sh b/db_scripts/mosip_regprc/deploy.sh index 36df1a987ce..4c5631601ef 100644 --- a/db_scripts/mosip_regprc/deploy.sh +++ b/db_scripts/mosip_regprc/deploy.sh @@ -17,31 +17,31 @@ fi ## Terminate existing connections echo "Terminating active connections" -CONN=$(PGPASSWORD=$SU_USER_PWD psql --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;) +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" ## Drop db and role echo "Dropping DB" -PGPASSWORD=$SU_USER_PWD psql --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 --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 --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 --username=$SU_USER --host=$DB_SERVERIP --port=$DB_PORT --dbname=$DEFAULT_DB_NAME -f db.sql -PGPASSWORD=$SU_USER_PWD psql --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 --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 --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 From b9cd2591b190387b7d84980806893c7201ce5145 Mon Sep 17 00:00:00 2001 From: Sowmya Ujjappa Banakar <43202851+sowmya695@users.noreply.github.com> Date: Tue, 22 Aug 2023 13:20:24 +0530 Subject: [PATCH 094/133] MOSIP-28646 code changes (#1757) Co-authored-by: Sowmya Ujjappa Banakar --- .../abis/handler/stage/AbisHandlerStage.java | 31 +- .../stage/test/AbisHandlerStageTest.java | 2060 +++++++++-------- 2 files changed, 1042 insertions(+), 1049 deletions(-) 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 8877edcfeb9..1a9185b66ec 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 @@ -153,14 +153,8 @@ public class AbisHandlerStage extends MosipVerticleAPIManager { @Value("${mosip.regproc.data.share.internal.domain.name}") private String internalDomainName; - @Value("#{${mosip.regproc.abis.handler.biometric-modalities-segments-mapping.INFANT}}") - private Map> biometricModalitySegmentsMapInfant; - - @Value("#{${mosip.regproc.abis.handler.biometric-modalities-segments-mapping.MINOR}}") - private Map> biometricModalitySegmentsMapMinor; - - @Value("#{${mosip.regproc.abis.handler.biometric-modalities-segments-mapping.ADULT}}") - private Map> biometricModalitySegmentsMapAdult; + @Value("#{${mosip.regproc.abis.handler.biometric-modalities-segments-mapping-for-age-group}}") + private Map>> biometricModalitySegmentsMapforAgeGroup; @Value("#{${mosip.regproc.abis.handler.biometric-segments-exceptions-mapping}}") private Map exceptionSegmentsMap; @@ -600,20 +594,15 @@ private String getDataShareUrl(String id, String process) throws Exception { Map tags = packetManagerService.getAllTags(id); String ageGroup = tags.get("AGE_GROUP"); - - if (ageGroup.equalsIgnoreCase("INFANT")) { - validateBiometricRecord(biometricRecord, modalities, biometricModalitySegmentsMapInfant, - priorityBasedPacketManagerService.getMetaInfo(id, process, ProviderStageName.BIO_DEDUPE)); - } else if (ageGroup.equalsIgnoreCase("MINOR")) { - validateBiometricRecord(biometricRecord, modalities, biometricModalitySegmentsMapMinor, - priorityBasedPacketManagerService.getMetaInfo(id, process, ProviderStageName.BIO_DEDUPE)); - } else if (ageGroup.equalsIgnoreCase("ADULT")) { - validateBiometricRecord(biometricRecord, modalities, biometricModalitySegmentsMapAdult, - priorityBasedPacketManagerService.getMetaInfo(id, process, ProviderStageName.BIO_DEDUPE)); - } else { - validateBiometricRecord(biometricRecord, modalities, biometricModalitySegmentsMapAdult, - priorityBasedPacketManagerService.getMetaInfo(id, process, ProviderStageName.BIO_DEDUPE)); + Map> biometricModalitySegmentsMap; + if(biometricModalitySegmentsMapforAgeGroup.containsKey(ageGroup)){ + biometricModalitySegmentsMap = biometricModalitySegmentsMapforAgeGroup.get(ageGroup); + } + else { + biometricModalitySegmentsMap = biometricModalitySegmentsMapforAgeGroup.get("DEFAULT"); } + validateBiometricRecord(biometricRecord, modalities, biometricModalitySegmentsMap, + priorityBasedPacketManagerService.getMetaInfo(id, process, ProviderStageName.BIO_DEDUPE)); byte[] content = cbeffutil.createXML(filterExceptionBiometrics(biometricRecord,id,process).getSegments()); diff --git a/registration-processor/core-processor/registration-processor-abis-handler-stage/src/test/java/io/mosip/registration/processor/abis/handler/stage/test/AbisHandlerStageTest.java b/registration-processor/core-processor/registration-processor-abis-handler-stage/src/test/java/io/mosip/registration/processor/abis/handler/stage/test/AbisHandlerStageTest.java index 7cf1e4e112c..9f3586edf3a 100644 --- a/registration-processor/core-processor/registration-processor-abis-handler-stage/src/test/java/io/mosip/registration/processor/abis/handler/stage/test/AbisHandlerStageTest.java +++ b/registration-processor/core-processor/registration-processor-abis-handler-stage/src/test/java/io/mosip/registration/processor/abis/handler/stage/test/AbisHandlerStageTest.java @@ -1,1029 +1,1033 @@ -package io.mosip.registration.processor.abis.handler.stage.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.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; - -import org.assertj.core.util.Lists; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.ArgumentMatchers; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.Spy; -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.MediaType; -import org.springframework.test.util.ReflectionTestUtils; - -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.JsonUtils; -import io.mosip.kernel.core.util.exception.JsonProcessingException; -import io.mosip.registration.processor.abis.handler.dto.DataShare; -import io.mosip.registration.processor.abis.handler.dto.DataShareResponseDto; -import io.mosip.registration.processor.abis.handler.stage.AbisHandlerStage; -import io.mosip.registration.processor.abis.queue.dto.AbisQueueDetails; -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.common.rest.dto.ErrorDTO; -import io.mosip.registration.processor.core.constant.JsonConstant; -import io.mosip.registration.processor.core.constant.PolicyConstant; -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.Identity; -import io.mosip.registration.processor.core.packet.dto.abis.AbisApplicationDto; -import io.mosip.registration.processor.core.packet.dto.abis.AbisIdentifyRequestDto; -import io.mosip.registration.processor.core.packet.dto.abis.AbisInsertRequestDto; -import io.mosip.registration.processor.core.packet.dto.abis.AbisRequestDto; -import io.mosip.registration.processor.core.packet.dto.abis.RegBioRefDto; -import io.mosip.registration.processor.core.packet.dto.abis.RegDemoDedupeListDto; -import io.mosip.registration.processor.core.packet.dto.datashare.Filter; -import io.mosip.registration.processor.core.packet.dto.datashare.ShareableAttributes; -import io.mosip.registration.processor.core.packet.dto.datashare.Source; -import io.mosip.registration.processor.core.spi.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.packet.storage.dto.ApplicantInfoDto; -import io.mosip.registration.processor.packet.storage.utils.PacketManagerService; -import io.mosip.registration.processor.packet.storage.utils.PriorityBasedPacketManagerService; -import io.mosip.registration.processor.packet.storage.utils.Utilities; -import io.mosip.registration.processor.rest.client.audit.builder.AuditLogRequestBuilder; -import io.mosip.registration.processor.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; - -@RunWith(PowerMockRunner.class) -@PrepareForTest({ JsonUtils.class }) -@PowerMockIgnore({ "com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "javax.management.*", "javax.net.ssl.*" }) -public class AbisHandlerStageTest { - - @Mock - private AuditLogRequestBuilder auditLogRequestBuilder; - - @Mock - private RegistrationStatusService registrationStatusService; - - @Mock - private PacketInfoManager packetInfoManager; - - private InternalRegistrationStatusDto registrationStatusDto = new InternalRegistrationStatusDto(); - - @Mock - private Utilities utility; - - @Spy - private ObjectMapper mapper = new ObjectMapper(); - - @Mock - private PriorityBasedPacketManagerService packetManagerService; - - @Mock - private PacketManagerService packetService; - - @Mock - private LogDescription description; - - List abisApplicationDtos = new ArrayList<>(); - - List bioRefDtos = new ArrayList<>(); - - List regDemoDedupeListDtoList = new ArrayList<>(); - - List abisRequestDtoList = new ArrayList<>(); - - Map tags = new HashMap(); - - @Mock - private Environment env; - - @Mock - private RegistrationProcessorRestClientService registrationProcessorRestClientService; - - @Mock - private CbeffUtil cbeffutil; - - @InjectMocks - private AbisHandlerStage abisHandlerStage = new AbisHandlerStage() { - @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 consumeAndSend(MosipEventBus mosipEventBus, MessageBusAddress fromAddress, - MessageBusAddress toAddress, long messageExpiryTimeLimit) { - } - - @Override - public Integer getPort() { - return 8080; - }; - }; - - @Before - public void setUp() throws Exception { - ReflectionTestUtils.setField(abisHandlerStage, "maxResults", "30"); - ReflectionTestUtils.setField(abisHandlerStage, "targetFPIR", "30"); - ReflectionTestUtils.setField(abisHandlerStage, "workerPoolSize", 10); - ReflectionTestUtils.setField(abisHandlerStage, "messageExpiryTimeLimit", Long.valueOf(0)); - ReflectionTestUtils.setField(abisHandlerStage, "clusterManagerUrl", "/dummyPath"); - ReflectionTestUtils.setField(abisHandlerStage, "httpProtocol", "http"); - ReflectionTestUtils.setField(abisHandlerStage, "internalDomainName", "localhost"); - Mockito.when(env.getProperty("mosip.registration.processor.datetime.pattern")) - .thenReturn("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); - - Map> biometricModalitySegmentsMap = new HashMap(); - Map> biometricModalitySegmentsMapInfant = new HashMap(); - biometricModalitySegmentsMapInfant.put("Face", getFaceList()); - biometricModalitySegmentsMap.put("Finger", getFingerList()); - biometricModalitySegmentsMap.put("Iris", getIrisList()); - biometricModalitySegmentsMap.put("Face", getFaceList()); - ReflectionTestUtils.setField(abisHandlerStage, "biometricModalitySegmentsMapInfant", biometricModalitySegmentsMapInfant); - ReflectionTestUtils.setField(abisHandlerStage, "biometricModalitySegmentsMapMinor", biometricModalitySegmentsMap); - ReflectionTestUtils.setField(abisHandlerStage, "biometricModalitySegmentsMapAdult", biometricModalitySegmentsMap); - ReflectionTestUtils.setField(abisHandlerStage, "exceptionSegmentsMap", getExceptionModalityMap()); - ReflectionTestUtils.setField(abisHandlerStage, "regClientVersionsBeforeCbeffOthersAttritube", - Arrays.asList("1.1.3")); - Mockito.when(env.getProperty("DATASHARECREATEURL")).thenReturn("/v1/datashare/create"); - AbisApplicationDto dto = new AbisApplicationDto(); - dto.setCode("ABIS1"); - abisApplicationDtos.add(dto); - - Mockito.doNothing().when(description).setMessage(any()); - Mockito.when(description.getMessage()).thenReturn("description"); - - - Mockito.when(packetManagerService.getBiometrics(any(), any(), any(), any(), any())).thenReturn(getBiometricRecord(Arrays.asList("Left Thumb" ,"Right Thumb" , "Left MiddleFinger" , - "Left RingFinger" ,"Left LittleFinger" ,"Left IndexFinger" ,"Right MiddleFinger" , - "Right RingFinger" ,"Right LittleFinger" ,"Right IndexFinger" , - "Left" ,"Right","Face"),false)); - mockDataSharePolicy(Lists.newArrayList(BiometricType.FINGER,BiometricType.IRIS,BiometricType.FACE)); - - List list = new LinkedList<>(); - setMetaInfoMap(list); - - //Mockito.doNothing().when(registrationStatusDto).setLatestTransactionStatusCode(any()); - Mockito.doNothing().when(registrationStatusService).updateRegistrationStatus(any(), any(), any()); - - Mockito.when(packetInfoManager.getAbisRequestsByBioRefId(any())).thenReturn(abisRequestDtoList); - - AbisQueueDetails abisQueueDetails = new AbisQueueDetails(); - abisQueueDetails.setName("ABIS1"); - List abisQueueDetailsList = new ArrayList<>(); - abisQueueDetailsList.add(abisQueueDetails); - Mockito.when(utility.getAbisQueueDetails()).thenReturn(abisQueueDetailsList); - - AuditResponseDto auditResponseDto = new AuditResponseDto(); - ResponseWrapper responseWrapper = new ResponseWrapper<>(); - responseWrapper.setResponse(auditResponseDto); - Mockito.when(auditLogRequestBuilder.createAuditRequestBuilder(any(), any(), any(), any(), any(), any(), any())) - .thenReturn(responseWrapper); - - DataShareResponseDto dataShareResponseDto = new DataShareResponseDto(); - DataShare dataShare = new DataShare(); - dataShare.setUrl("http://localhost"); - dataShareResponseDto.setDataShare(dataShare); - - mockDataSharePolicy(Lists.newArrayList(BiometricType.FACE, BiometricType.FINGER)); - - Mockito.when(registrationProcessorRestClientService.postApi(anyString(), any(MediaType.class), any(), any(), - any(), any(), any())).thenReturn(dataShareResponseDto); - - Mockito.when(cbeffutil.createXML(any())).thenReturn(new byte[2048]); - } - - private Map getExceptionModalityMap() { - Map exceptionMap = new HashMap(); - exceptionMap.put("Left Thumb" , "leftThumb"); - exceptionMap.put("Right Thumb" , "rightThumb"); - exceptionMap.put("Left MiddleFinger" , "leftMiddle"); - exceptionMap.put("Left RingFinger" , "leftRing"); - exceptionMap.put("Left LittleFinger" , "leftLittle"); - exceptionMap.put("Left IndexFinger" , "leftIndex"); - exceptionMap.put("Right MiddleFinger" , "rightMiddle"); - exceptionMap.put("Right RingFinger" , "rightRing"); - exceptionMap.put("Right LittleFinger" , "rightLittle"); - exceptionMap.put("Right IndexFinger" , "rightIndex"); - exceptionMap.put("Left" , "leftEye"); - exceptionMap.put("Right" , "rightEye"); - exceptionMap.put("Face" , "face"); - - return exceptionMap; - } - - private List getFaceList() { - return Arrays.asList("Face"); - } - - private List getIrisList() { - return Arrays.asList("Left", "Right"); - - } - - private List getFingerList() { - return Arrays.asList("Left Thumb", "Left LittleFinger", "Left IndexFinger", "Left MiddleFinger", - "Left RingFinger", "Right Thumb", "Right LittleFinger", - "Right IndexFinger", "Right MiddleFinger", - "Right RingFinger"); - } - - private void mockDataSharePolicy(List sherableBiometricList) throws ApisResourceAccessException { - when(registrationProcessorRestClientService.getApi(any(), any(), anyString(), anyString(), any())) - .thenReturn(getMockDataSharePolicy(sherableBiometricList)); - } - - private ResponseWrapper> getMockDataSharePolicy( - List sherableBiometricList) { - - ObjectMapper mapper = new ObjectMapper(); - - List attr = new LinkedList<>(); - if (sherableBiometricList != null && !sherableBiometricList.isEmpty()) { - - ShareableAttributes shareableAttributes = new ShareableAttributes(); - List sourceList = new ArrayList<>(); - - for (BiometricType bioType : sherableBiometricList) { - Filter filter = new Filter(); - filter.setType(bioType.value()); - Source src = new Source(); - src.setFilter(Lists.newArrayList(filter)); - sourceList.add(src); - } - - shareableAttributes.setSource(sourceList); - attr = Lists.newArrayList(shareableAttributes); - } - - ResponseWrapper> policy = new ResponseWrapper<>(); - LinkedHashMap policies = new LinkedHashMap<>(); - LinkedHashMap sharableAttributes = new LinkedHashMap<>(); - sharableAttributes.put(PolicyConstant.SHAREABLE_ATTRIBUTES, attr); - policies.put(PolicyConstant.POLICIES, sharableAttributes); - policy.setResponse(policies); - - return policy; - } - - @Test - public void testDeployVerticle() { - abisHandlerStage.deployVerticle(); - } - - @Test - public void testDemoToAbisHandlerTOMiddlewareSuccess() throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { - registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); - registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); - Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); - Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); - Mockito.when(packetInfoManager.getAllAbisDetails()).thenReturn(abisApplicationDtos); - - mockDataSharePolicy(Lists.newArrayList(BiometricType.IRIS, BiometricType.FINGER, BiometricType.FACE)); - Mockito.when(packetInfoManager.getBioRefIdByRegId(any())).thenReturn(bioRefDtos); - tags.put("AGE_GROUP", "ADULT"); - Mockito.when(packetService.getAllTags(any())).thenReturn(tags); - - Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); - Mockito.doNothing().when(packetInfoManager).saveAbisRequest(any(), any(), any()); - - RegDemoDedupeListDto regDemoDedupeListDto = new RegDemoDedupeListDto(); - regDemoDedupeListDto.setMatchedRegId("10003100030001520190422074511"); - regDemoDedupeListDtoList.add(regDemoDedupeListDto); - Mockito.when(packetInfoManager.getDemoListByTransactionId(any())).thenReturn(regDemoDedupeListDtoList); - - MessageDTO dto = new MessageDTO(); - dto.setRid("10003100030001520190422074511"); - MessageDTO result = abisHandlerStage.process(dto); - - assertTrue(result.getMessageBusAddress().getAddress().equalsIgnoreCase("abis-middle-ware-bus-in")); - } - - @Test - public void testBioToAbisHandlerToMiddlewareSuccess() throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { - registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); - registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); - Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); - Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); - Mockito.when(packetInfoManager.getAllAbisDetails()).thenReturn(abisApplicationDtos); - - mockDataSharePolicy(Lists.newArrayList(BiometricType.IRIS, BiometricType.FINGER, BiometricType.FACE)); - RegBioRefDto regBioRefDto = new RegBioRefDto(); - regBioRefDto.setBioRefId("1234567890"); - bioRefDtos.add(regBioRefDto); - Mockito.when(packetInfoManager.getBioRefIdByRegId(any())).thenReturn(bioRefDtos); - tags.put("AGE_GROUP", "ADULT"); - Mockito.when(packetService.getAllTags(any())).thenReturn(tags); - - Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); - Mockito.doNothing().when(packetInfoManager).saveAbisRequest(any(), any(), any()); - - RegDemoDedupeListDto regDemoDedupeListDto = new RegDemoDedupeListDto(); - regDemoDedupeListDto.setMatchedRegId("10003100030001520190422074511"); - regDemoDedupeListDtoList.add(regDemoDedupeListDto); - Mockito.when(packetInfoManager.getDemoListByTransactionId(any())).thenReturn(regDemoDedupeListDtoList); - - MessageDTO dto = new MessageDTO(); - dto.setRid("10003100030001520190422074511"); - MessageDTO result = abisHandlerStage.process(dto); - - assertTrue(result.getMessageBusAddress().getAddress().equalsIgnoreCase("abis-middle-ware-bus-in")); - } - - @Test - public void testMiddlewareToAbisHandlerToDemoSuccess() { - registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); - registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); - Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); - Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.TRUE); - - MessageDTO dto = new MessageDTO(); - dto.setRid("10003100030001520190422074511"); - MessageDTO result = abisHandlerStage.process(dto); - - assertTrue(result.getMessageBusAddress().getAddress().equalsIgnoreCase("demo-dedupe-bus-in")); - } - - @Test - public void testMiddlewareToAbisHandlerToBioSuccess() { - registrationStatusDto.setLatestTransactionTypeCode("BIOGRAPHIC_VERIFICATION"); - registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); - Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); - Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.TRUE); - - MessageDTO dto = new MessageDTO(); - dto.setRid("10003100030001520190422074511"); - MessageDTO result = abisHandlerStage.process(dto); - - assertTrue(result.getMessageBusAddress().getAddress().equalsIgnoreCase("bio-dedupe-bus-in")); - } - - @Test - public void testDemoDedupeDataNotFound() { - registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); - registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); - Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); - Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); - Mockito.when(packetInfoManager.getAllAbisDetails()).thenReturn(abisApplicationDtos); - - Mockito.when(packetInfoManager.getBioRefIdByRegId(any())).thenReturn(bioRefDtos); - - Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); - Mockito.doNothing().when(packetInfoManager).saveAbisRequest(any(), any(), any()); - - Mockito.when(packetInfoManager.getDemoListByTransactionId(any())).thenReturn(regDemoDedupeListDtoList); - - MessageDTO dto = new MessageDTO(); - dto.setRid("10003100030001520190422074511"); - MessageDTO result = abisHandlerStage.process(dto); - - assertTrue(result.getInternalError()); - assertTrue(result.getIsValid()); - } - - @Test - public void testReprocessInsert() throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { - registrationStatusDto.setLatestTransactionTypeCode("BIOGRAPHIC_VERIFICATION"); - registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); - Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); - Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); - List appCodeList = new ArrayList<>(); - appCodeList.add("ABIS1"); - Mockito.when(packetInfoManager.getAbisProcessedRequestsAppCodeByBioRefId(any(), any(), any())) - .thenReturn(appCodeList); - - Mockito.when(packetInfoManager.getAllAbisDetails()).thenReturn(abisApplicationDtos); - - RegBioRefDto bioRefDto = new RegBioRefDto(); - bioRefDtos.add(bioRefDto); - Mockito.when(packetInfoManager.getBioRefIdByRegId(any())).thenReturn(bioRefDtos); - - Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); - - AbisRequestDto abisRequestDto = new AbisRequestDto(); - abisRequestDto.setAbisAppCode("ABIS1"); - abisRequestDto.setStatusCode("IN-PROGRESS"); - abisRequestDtoList.add(abisRequestDto); - Mockito.when(packetInfoManager.getAbisRequestsByBioRefId(any())).thenReturn(abisRequestDtoList); - tags.put("AGE_GROUP", "ADULT"); - Mockito.when(packetService.getAllTags(any())).thenReturn(tags); - - Mockito.doNothing().when(packetInfoManager).saveAbisRequest(any(), any(), any()); - - Mockito.when(packetInfoManager.getDemoListByTransactionId(any())).thenReturn(regDemoDedupeListDtoList); - - MessageDTO dto = new MessageDTO(); - dto.setRid("10003100030001520190422074511"); - MessageDTO result = abisHandlerStage.process(dto); - - assertFalse(result.getInternalError()); - assertTrue(result.getIsValid()); - } - - @Test - public void testAbisDetailsNotFound() throws RegistrationProcessorCheckedException { - registrationStatusDto.setLatestTransactionTypeCode("BIOGRAPHIC_VERIFICATION"); - registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); - Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); - Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); - - List abisQueueDetails = new ArrayList<>(); - Mockito.when(utility.getAbisQueueDetails()).thenReturn(abisQueueDetails); - - MessageDTO dto = new MessageDTO(); - dto.setRid("10003100030001520190422074511"); - MessageDTO result = abisHandlerStage.process(dto); - - assertTrue(result.getInternalError()); - } - - @Test - public void testPotentialMatchNotFound() throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { - registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); - registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); - Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); - Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); - - mockDataSharePolicy(Lists.newArrayList(BiometricType.IRIS, BiometricType.FINGER, BiometricType.FACE)); - tags.put("AGE_GROUP", "ADULT"); - Mockito.when(packetService.getAllTags(any())).thenReturn(tags); - - Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); - Mockito.doNothing().when(packetInfoManager).saveAbisRequest(any(), any(), any()); - - Mockito.when(packetInfoManager.getDemoListByTransactionId(any())).thenReturn(Arrays.asList()); - - MessageDTO dto = new MessageDTO(); - dto.setRid("10003100030001520190422074511"); - MessageDTO result = abisHandlerStage.process(dto); - - assertTrue(result.getInternalError()); - } - - @Test - public void testIdentifyRequestJsonProcessingException() throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { - registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); - registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); - Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); - Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); - - mockDataSharePolicy(Lists.newArrayList(BiometricType.IRIS, BiometricType.FINGER, BiometricType.FACE)); - Mockito.when(packetInfoManager.getBioRefIdByRegId(any())).thenReturn(bioRefDtos); - tags.put("AGE_GROUP", "ADULT"); - Mockito.when(packetService.getAllTags(any())).thenReturn(tags); - - Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); - Mockito.doNothing().when(packetInfoManager).saveAbisRequest(any(), any(), any()); - - RegDemoDedupeListDto regDemoDedupeListDto = new RegDemoDedupeListDto(); - regDemoDedupeListDto.setMatchedRegId("10003100030001520190422074511"); - regDemoDedupeListDtoList.add(regDemoDedupeListDto); - Mockito.when(packetInfoManager.getDemoListByTransactionId(any())).thenReturn(regDemoDedupeListDtoList); - - PowerMockito.mockStatic(JsonUtils.class); - PowerMockito.when(JsonUtils.javaObjectToJsonString(any())).thenReturn("value").thenThrow(JsonProcessingException.class); - MessageDTO dto = new MessageDTO(); - dto.setRid("10003100030001520190422074511"); - MessageDTO result = abisHandlerStage.process(dto); - - assertTrue(result.getInternalError()); - } - - @Test - public void testInsertRequestJsonProcessingException() throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { - registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); - registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); - Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); - Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); - - mockDataSharePolicy(Lists.newArrayList(BiometricType.IRIS, BiometricType.FINGER, BiometricType.FACE)); - tags.put("AGE_GROUP", "MINOR"); - Mockito.when(packetService.getAllTags(any())).thenReturn(tags); - - Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); - - PowerMockito.mockStatic(JsonUtils.class); - PowerMockito.when(JsonUtils.javaObjectToJsonString(any())).thenThrow(JsonProcessingException.class); - MessageDTO dto = new MessageDTO(); - dto.setRid("10003100030001520190422074511"); - MessageDTO result = abisHandlerStage.process(dto); - - assertTrue(result.getInternalError()); - } - - @Test - public void testDataShareResponseNullException() throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { - registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); - registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); - Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); - Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); - - mockDataSharePolicy(Lists.newArrayList(BiometricType.IRIS, BiometricType.FINGER, BiometricType.FACE)); - tags.put("AGE_GROUP", "MINOR"); - Mockito.when(packetService.getAllTags(any())).thenReturn(tags); - - Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); - - DataShareResponseDto dataShareResponseDto = new DataShareResponseDto(); - ErrorDTO error = new ErrorDTO("ERR-001", "exception occured"); - dataShareResponseDto.setDataShare(null); - dataShareResponseDto.setErrors(Arrays.asList(error)); - Mockito.when(registrationProcessorRestClientService.postApi(anyString(), any(MediaType.class), any(), any(), - any(), any(), any())).thenReturn(dataShareResponseDto); - MessageDTO dto = new MessageDTO(); - dto.setRid("10003100030001520190422074511"); - MessageDTO result = abisHandlerStage.process(dto); - - assertTrue(result.getInternalError()); - } - - @Test - public void testCreateTypeSubtypeMappingResponseNullException() - throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { - registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); - registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); - Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())) - .thenReturn(registrationStatusDto); - Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); - ErrorDTO error = new ErrorDTO("ERR-001", "exception occured"); - ResponseWrapper> policyResponse = new ResponseWrapper<>(); - - policyResponse.setErrors(Arrays.asList(error)); - - Mockito.when(registrationProcessorRestClientService.getApi(any(), any(), anyString(), - anyString(), any())).thenReturn(policyResponse); - Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); - - MessageDTO dto = new MessageDTO(); - dto.setRid("10003100030001520190422074511"); - MessageDTO result = abisHandlerStage.process(dto); - - assertTrue(result.getInternalError()); - } - - @Test - public void testvalidateBiometricRecordModalitiesEmptyException() - throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { - registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); - registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); - Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())) - .thenReturn(registrationStatusDto); - Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); - - mockDataSharePolicy(Lists.newArrayList(BiometricType.IRIS, BiometricType.FINGER, BiometricType.FACE)); - tags.put("AGE_GROUP", "MINOR"); - Mockito.when(packetService.getAllTags(any())).thenReturn(tags); - - Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); - - ResponseWrapper> policyResponse = new ResponseWrapper<>(); - LinkedHashMap response = new LinkedHashMap(); - LinkedHashMap attributes = new LinkedHashMap(); - ShareableAttributes shareableAttributes = new ShareableAttributes(); - shareableAttributes.setSource(Arrays.asList()); - attributes.put(PolicyConstant.SHAREABLE_ATTRIBUTES, Arrays.asList(shareableAttributes)); - response.put(PolicyConstant.POLICIES, attributes); - policyResponse.setResponse(response); - - Mockito.when(registrationProcessorRestClientService.getApi(any(), any(), anyString(), anyString(), any())) - .thenReturn(policyResponse); - - MessageDTO dto = new MessageDTO(); - dto.setRid("10003100030001520190422074511"); - MessageDTO result = abisHandlerStage.process(dto); - - assertTrue(result.getInternalError()); - } - - @Test - public void testvalidateBiometricRecordSegmentEmptyException() - throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { - registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); - registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); - Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())) - .thenReturn(registrationStatusDto); - Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); - - mockDataSharePolicy(Lists.newArrayList(BiometricType.IRIS, BiometricType.FINGER, BiometricType.FACE)); - tags.put("AGE_GROUP", "ADULT"); - Mockito.when(packetService.getAllTags(any())).thenReturn(tags); - BiometricRecord biometricRecord = new BiometricRecord(); - biometricRecord.setSegments(null); - Mockito.when(packetManagerService.getBiometrics(any(), any(), any(), any(), any())).thenReturn(biometricRecord); - Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); - - MessageDTO dto = new MessageDTO(); - dto.setRid("10003100030001520190422074511"); - MessageDTO result = abisHandlerStage.process(dto); - - assertTrue(result.getInternalError()); - } - - @Test - public void testvalidateBiometricRecordOthersMapNullException() - throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { - registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); - registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); - Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())) - .thenReturn(registrationStatusDto); - Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); - - mockDataSharePolicy(Lists.newArrayList(BiometricType.IRIS, BiometricType.FINGER, BiometricType.FACE)); - tags.put("AGE_GROUP", "ADULT"); - Mockito.when(packetService.getAllTags(any())).thenReturn(tags); - BiometricRecord biometricRecord = new BiometricRecord(); - BIR bir = new BIR.BIRBuilder().build(); - BDBInfo bdbInfo = new BDBInfo.BDBInfoBuilder().build(); - bdbInfo.setSubtype(Arrays.asList("Left")); - bdbInfo.setType(Arrays.asList(BiometricType.IRIS)); - bir.setOthers(null); - bir.setBdbInfo(bdbInfo); - biometricRecord.setSegments(Arrays.asList(bir)); - Mockito.when(packetManagerService.getBiometrics(any(), any(), any(), any(), any())).thenReturn(biometricRecord); - Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); - - MessageDTO dto = new MessageDTO(); - dto.setRid("10003100030001520190422074511"); - MessageDTO result = abisHandlerStage.process(dto); - - assertTrue(result.getInternalError()); - } - - @Test - public void testCreateRequestException() throws JsonProcessingException { - registrationStatusDto.setLatestTransactionTypeCode("BIOGRAPHIC_VERIFICATION"); - registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); - Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); - Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); - - Mockito.when(packetInfoManager.getAllAbisDetails()).thenReturn(abisApplicationDtos); - - RegBioRefDto bioRefDto = new RegBioRefDto(); - bioRefDtos.add(bioRefDto); - Mockito.when(packetInfoManager.getBioRefIdByRegId(any())).thenReturn(bioRefDtos); - - Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); - - AbisRequestDto abisRequestDto = new AbisRequestDto(); - abisRequestDto.setAbisAppCode("ABIS1"); - abisRequestDto.setStatusCode("IN-PROGRESS"); - abisRequestDtoList.add(abisRequestDto); - Mockito.when(packetInfoManager.getAbisRequestsByBioRefId(any())).thenReturn(abisRequestDtoList); - - Mockito.doNothing().when(packetInfoManager).saveAbisRequest(any(), any(), any()); - - Mockito.when(packetInfoManager.getDemoListByTransactionId(any())).thenReturn(regDemoDedupeListDtoList); - - PowerMockito.mockStatic(JsonUtils.class); - PowerMockito.when(JsonUtils.javaObjectToJsonString(any(AbisInsertRequestDto.class))) - .thenThrow(JsonProcessingException.class); - - MessageDTO dto = new MessageDTO(); - dto.setRid("10003100030001520190422074511"); - MessageDTO result = abisHandlerStage.process(dto); - - assertTrue(result.getInternalError()); - assertTrue(result.getIsValid()); - } - - @Test - public void testIdentifyRequestException() throws JsonProcessingException { - registrationStatusDto.setLatestTransactionTypeCode("BIOGRAPHIC_VERIFICATION"); - registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); - Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); - Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); - - Mockito.when(packetInfoManager.getAllAbisDetails()).thenReturn(abisApplicationDtos); - - RegBioRefDto bioRefDto = new RegBioRefDto(); - bioRefDtos.add(bioRefDto); - Mockito.when(packetInfoManager.getBioRefIdByRegId(any())).thenReturn(bioRefDtos); - - Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); - - AbisRequestDto abisRequestDto = new AbisRequestDto(); - abisRequestDto.setAbisAppCode("ABIS1"); - abisRequestDto.setStatusCode("IN-PROGRESS"); - abisRequestDtoList.add(abisRequestDto); - Mockito.when(packetInfoManager.getAbisRequestsByBioRefId(any())).thenReturn(abisRequestDtoList); - - Mockito.doNothing().when(packetInfoManager).saveAbisRequest(any(), any(), any()); - - Mockito.when(packetInfoManager.getDemoListByTransactionId(any())).thenReturn(regDemoDedupeListDtoList); - - PowerMockito.mockStatic(JsonUtils.class); - PowerMockito.when(JsonUtils.javaObjectToJsonString(any(AbisInsertRequestDto.class))) - .thenReturn("AbisInsertRequestDto"); - PowerMockito.when(JsonUtils.javaObjectToJsonString(ArgumentMatchers.any(AbisIdentifyRequestDto.class))) - .thenThrow(JsonProcessingException.class); - - MessageDTO dto = new MessageDTO(); - dto.setRid("10003100030001520190422074511"); - MessageDTO result = abisHandlerStage.process(dto); - - assertTrue(result.getInternalError()); - assertTrue(result.getIsValid()); - } - - - @Test - public void bioRecordDataNotFound() - throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { - - defaultMockToProcess(); - - Mockito.when(packetManagerService.getBiometrics(any(), any(), any(), any(), any())).thenReturn(null); - mockDataSharePolicy(Lists.newArrayList(BiometricType.IRIS, BiometricType.FINGER, BiometricType.FACE)); - - setMetaInfoMap(new LinkedList<>(getExceptionModalityMap().values())); - MessageDTO dto = new MessageDTO(); - dto.setRid("10003100030001520190422074511"); - MessageDTO result = abisHandlerStage.process(dto); - - assertTrue(result.getIsValid()); - assertTrue(result.getInternalError()); - } - - @Test - public void biometricsNotFoundWithSegmentConfig() - throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { - - defaultMockToProcess(); - - Mockito.when(packetManagerService.getBiometrics(any(), any(), any(), any(), any())).thenReturn(getBiometricRecord(Arrays.asList("Left Thumb" ,"Right Thumb","Face"),false)); - - - setMetaInfoMap(Arrays.asList("leftEye")); - MessageDTO dto = new MessageDTO(); - dto.setRid("10003100030001520190422074511"); - MessageDTO result = abisHandlerStage.process(dto); - - assertTrue(result.getIsValid()); - assertTrue(result.getInternalError()); - } - - @Test - public void biometricsTypeNotFoundConfig() - throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { - - defaultMockToProcess(); - - Map> biometricModalitySegmentsMap = new HashMap(); - biometricModalitySegmentsMap.put("Finger", getFingerList()); - biometricModalitySegmentsMap.put("Iris", getIrisList()); - ReflectionTestUtils.setField(abisHandlerStage, "biometricModalitySegmentsMapAdult", biometricModalitySegmentsMap); - ReflectionTestUtils.setField(abisHandlerStage, "exceptionSegmentsMap", getExceptionModalityMap()); - - MessageDTO dto = new MessageDTO(); - dto.setRid("10003100030001520190422074511"); - MessageDTO result = abisHandlerStage.process(dto); - - assertTrue(result.getIsValid()); - assertTrue(result.getInternalError()); - } - - @Test - public void testBiometricSegmentNotConfiguredInfant() throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { - registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); - registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); - Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); - Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); - Mockito.when(packetInfoManager.getAllAbisDetails()).thenReturn(abisApplicationDtos); - - Mockito.when(packetInfoManager.getBioRefIdByRegId(any())).thenReturn(bioRefDtos); - tags.put("AGE_GROUP", "INFANT"); - Mockito.when(packetService.getAllTags(any())).thenReturn(tags); - - Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); - Mockito.doNothing().when(packetInfoManager).saveAbisRequest(any(), any(), any()); - - RegDemoDedupeListDto regDemoDedupeListDto = new RegDemoDedupeListDto(); - regDemoDedupeListDto.setMatchedRegId("10003100030001520190422074511"); - regDemoDedupeListDtoList.add(regDemoDedupeListDto); - Mockito.when(packetInfoManager.getDemoListByTransactionId(any())).thenReturn(regDemoDedupeListDtoList); - - MessageDTO dto = new MessageDTO(); - dto.setRid("10003100030001520190422074511"); - MessageDTO result = abisHandlerStage.process(dto); - - assertTrue(result.getIsValid()); - assertFalse(result.getInternalError()); - } - - - - @Test - public void emptyBdbFound() - throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { - - defaultMockToProcess(); - - boolean isBdbEmpty = true; - Mockito.when(packetManagerService.getBiometrics(any(), any(), any(), any(), any())).thenReturn(getBiometricRecord(Arrays.asList("Left RingFinger"), isBdbEmpty )); - mockDataSharePolicy(Lists.newArrayList(BiometricType.FINGER)); - - List list = new ArrayList(getExceptionModalityMap().values()); - list.remove("leftRing"); - setMetaInfoMap(list); - - MessageDTO dto = new MessageDTO(); - dto.setRid("10003100030001520190422074511"); - MessageDTO result = abisHandlerStage.process(dto); - - assertTrue(result.getIsValid()); - assertTrue(result.getInternalError()); - } - - @Test - public void noBdbInAnyBiometric() - throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { - - defaultMockToProcess(); - - Mockito.when(packetManagerService.getBiometrics(any(), any(), any(), any(), any())).thenReturn(getBiometricRecord(Arrays.asList("Left Thumb" ,"Right Thumb" , "Left MiddleFinger" , - "Left RingFinger" ,"Left LittleFinger" ,"Left IndexFinger" ,"Right MiddleFinger" , - "Right RingFinger" ,"Right LittleFinger" ,"Right IndexFinger" , - "Left" ,"Right","Face"),true)); - - MessageDTO dto = new MessageDTO(); - dto.setRid("10003100030001520190422074511"); - MessageDTO result = abisHandlerStage.process(dto); - - assertTrue(result.getIsValid()); - assertTrue(result.getInternalError()); - } - - private void defaultMockToProcess() { - registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); - registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); - Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); - Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); - Mockito.when(packetInfoManager.getAllAbisDetails()).thenReturn(abisApplicationDtos); - - RegBioRefDto regBioRefDto = new RegBioRefDto(); - regBioRefDto.setBioRefId("1234567890"); - bioRefDtos.add(regBioRefDto); - Mockito.when(packetInfoManager.getBioRefIdByRegId(any())).thenReturn(bioRefDtos); - - Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); - Mockito.doNothing().when(packetInfoManager).saveAbisRequest(any(), any(), any()); - - RegDemoDedupeListDto regDemoDedupeListDto = new RegDemoDedupeListDto(); - regDemoDedupeListDto.setMatchedRegId("10003100030001520190422074511"); - regDemoDedupeListDtoList.add(regDemoDedupeListDto); - Mockito.when(packetInfoManager.getDemoListByTransactionId(any())).thenReturn(regDemoDedupeListDtoList); - - } - - private void setMetaInfoMap(List exceptionAttributes) throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException{ - - Map metaInfoMap = new HashMap<>(); - - Map> exceptionBiometrcisMap = new HashMap<>(); - - Map applicantExceptionBiometrcisMap = new HashMap(); - - if(exceptionAttributes!=null) { - for(String exceptionAttribute : exceptionAttributes) { - - Map detailMap = new HashMap(); - detailMap.put("missingBiometric", exceptionAttribute); - detailMap.put("reason", "Temporary"); - detailMap.put("individualType", "applicant"); - - applicantExceptionBiometrcisMap.put(exceptionAttribute, detailMap); - - } - } - - - exceptionBiometrcisMap.put("applicant", applicantExceptionBiometrcisMap); - String gsonString =mapper.writeValueAsString(exceptionBiometrcisMap); - - metaInfoMap.put("exceptionBiometrics", gsonString); - metaInfoMap.put(JsonConstant.METADATA, - "[{\n \"label\" : \"Registration Client Version Number\",\n \"value\" : \"1.2.0\"\n}]"); - Mockito.when(packetManagerService.getMetaInfo(any(), any(), any())).thenReturn(metaInfoMap); - } - - private BiometricRecord getBiometricRecord(List bioAttributes, boolean isBdbEmpty) { - BiometricRecord biometricRecord = new BiometricRecord(); - - byte[] bdb = isBdbEmpty ? null : new byte[2048]; - for(String bioAttribute : bioAttributes) { - BIR birType1 = new BIR.BIRBuilder().build(); - 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 = bioAttribute.equalsIgnoreCase("face") ? BiometricType.FACE : - bioAttribute.equalsIgnoreCase("left") || bioAttribute.equalsIgnoreCase("right") ? BiometricType.IRIS : BiometricType.FINGER ; - List singleTypeList1 = new ArrayList<>(); - singleTypeList1.add(singleType1); - bdbInfoType1.setType(singleTypeList1); - - - - String[] bioAttributeArray = bioAttribute.split(" "); - - List subtype = new ArrayList<>(); - for(String attribute : bioAttributeArray) { - subtype.add(attribute); - } - bdbInfoType1.setSubtype(subtype); - - birType1.setBdbInfo(bdbInfoType1); - birType1.setBdb(bdb); - - if(bdb==null) { - Map others = new HashMap<>(); - others.put("EXCEPTION", true); - HashMap entry = new HashMap<>(); - entry.put("EXCEPTION", "true"); - birType1.setOthers(entry); - - } - - biometricRecord.getSegments().add(birType1); - } - - return biometricRecord; - } - +package io.mosip.registration.processor.abis.handler.stage.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.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +import org.assertj.core.util.Lists; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentMatchers; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.Spy; +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.MediaType; +import org.springframework.test.util.ReflectionTestUtils; + +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.JsonUtils; +import io.mosip.kernel.core.util.exception.JsonProcessingException; +import io.mosip.registration.processor.abis.handler.dto.DataShare; +import io.mosip.registration.processor.abis.handler.dto.DataShareResponseDto; +import io.mosip.registration.processor.abis.handler.stage.AbisHandlerStage; +import io.mosip.registration.processor.abis.queue.dto.AbisQueueDetails; +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.common.rest.dto.ErrorDTO; +import io.mosip.registration.processor.core.constant.JsonConstant; +import io.mosip.registration.processor.core.constant.PolicyConstant; +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.Identity; +import io.mosip.registration.processor.core.packet.dto.abis.AbisApplicationDto; +import io.mosip.registration.processor.core.packet.dto.abis.AbisIdentifyRequestDto; +import io.mosip.registration.processor.core.packet.dto.abis.AbisInsertRequestDto; +import io.mosip.registration.processor.core.packet.dto.abis.AbisRequestDto; +import io.mosip.registration.processor.core.packet.dto.abis.RegBioRefDto; +import io.mosip.registration.processor.core.packet.dto.abis.RegDemoDedupeListDto; +import io.mosip.registration.processor.core.packet.dto.datashare.Filter; +import io.mosip.registration.processor.core.packet.dto.datashare.ShareableAttributes; +import io.mosip.registration.processor.core.packet.dto.datashare.Source; +import io.mosip.registration.processor.core.spi.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.packet.storage.dto.ApplicantInfoDto; +import io.mosip.registration.processor.packet.storage.utils.PacketManagerService; +import io.mosip.registration.processor.packet.storage.utils.PriorityBasedPacketManagerService; +import io.mosip.registration.processor.packet.storage.utils.Utilities; +import io.mosip.registration.processor.rest.client.audit.builder.AuditLogRequestBuilder; +import io.mosip.registration.processor.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; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({ JsonUtils.class }) +@PowerMockIgnore({ "com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "javax.management.*", "javax.net.ssl.*" }) +public class AbisHandlerStageTest { + + @Mock + private AuditLogRequestBuilder auditLogRequestBuilder; + + @Mock + private RegistrationStatusService registrationStatusService; + + @Mock + private PacketInfoManager packetInfoManager; + + private InternalRegistrationStatusDto registrationStatusDto = new InternalRegistrationStatusDto(); + + @Mock + private Utilities utility; + + @Spy + private ObjectMapper mapper = new ObjectMapper(); + + @Mock + private PriorityBasedPacketManagerService packetManagerService; + + @Mock + private PacketManagerService packetService; + + @Mock + private LogDescription description; + + List abisApplicationDtos = new ArrayList<>(); + + List bioRefDtos = new ArrayList<>(); + + List regDemoDedupeListDtoList = new ArrayList<>(); + + List abisRequestDtoList = new ArrayList<>(); + + Map tags = new HashMap(); + + @Mock + private Environment env; + + @Mock + private RegistrationProcessorRestClientService registrationProcessorRestClientService; + + @Mock + private CbeffUtil cbeffutil; + + @InjectMocks + private AbisHandlerStage abisHandlerStage = new AbisHandlerStage() { + @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 consumeAndSend(MosipEventBus mosipEventBus, MessageBusAddress fromAddress, + MessageBusAddress toAddress, long messageExpiryTimeLimit) { + } + + @Override + public Integer getPort() { + return 8080; + }; + }; + + @Before + public void setUp() throws Exception { + ReflectionTestUtils.setField(abisHandlerStage, "maxResults", "30"); + ReflectionTestUtils.setField(abisHandlerStage, "targetFPIR", "30"); + ReflectionTestUtils.setField(abisHandlerStage, "workerPoolSize", 10); + ReflectionTestUtils.setField(abisHandlerStage, "messageExpiryTimeLimit", Long.valueOf(0)); + ReflectionTestUtils.setField(abisHandlerStage, "clusterManagerUrl", "/dummyPath"); + ReflectionTestUtils.setField(abisHandlerStage, "httpProtocol", "http"); + ReflectionTestUtils.setField(abisHandlerStage, "internalDomainName", "localhost"); + Mockito.when(env.getProperty("mosip.registration.processor.datetime.pattern")) + .thenReturn("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); + Map>> biometricModalitySegmentsMapforAgeGroup = new HashMap>>(); + Map> biometricModalitySegmentsMap = new HashMap(); + Map> biometricModalitySegmentsMapForInfant = new HashMap(); + biometricModalitySegmentsMapForInfant.put("Face", getFaceList()); + biometricModalitySegmentsMap.put("Finger", getFingerList()); + biometricModalitySegmentsMap.put("Iris", getIrisList()); + biometricModalitySegmentsMap.put("Face", getFaceList()); + biometricModalitySegmentsMapforAgeGroup.put("INFANT", biometricModalitySegmentsMapForInfant); + biometricModalitySegmentsMapforAgeGroup.put("MINOR", biometricModalitySegmentsMap); + biometricModalitySegmentsMapforAgeGroup.put("ADULT", biometricModalitySegmentsMap); + biometricModalitySegmentsMapforAgeGroup.put("DEFAULT", biometricModalitySegmentsMap); + + ReflectionTestUtils.setField(abisHandlerStage, "biometricModalitySegmentsMapforAgeGroup", biometricModalitySegmentsMapforAgeGroup); + ReflectionTestUtils.setField(abisHandlerStage, "exceptionSegmentsMap", getExceptionModalityMap()); + ReflectionTestUtils.setField(abisHandlerStage, "regClientVersionsBeforeCbeffOthersAttritube", + Arrays.asList("1.1.3")); + Mockito.when(env.getProperty("DATASHARECREATEURL")).thenReturn("/v1/datashare/create"); + AbisApplicationDto dto = new AbisApplicationDto(); + dto.setCode("ABIS1"); + abisApplicationDtos.add(dto); + + Mockito.doNothing().when(description).setMessage(any()); + Mockito.when(description.getMessage()).thenReturn("description"); + + + Mockito.when(packetManagerService.getBiometrics(any(), any(), any(), any(), any())).thenReturn(getBiometricRecord(Arrays.asList("Left Thumb" ,"Right Thumb" , "Left MiddleFinger" , + "Left RingFinger" ,"Left LittleFinger" ,"Left IndexFinger" ,"Right MiddleFinger" , + "Right RingFinger" ,"Right LittleFinger" ,"Right IndexFinger" , + "Left" ,"Right","Face"),false)); + mockDataSharePolicy(Lists.newArrayList(BiometricType.FINGER,BiometricType.IRIS,BiometricType.FACE)); + + List list = new LinkedList<>(); + setMetaInfoMap(list); + + //Mockito.doNothing().when(registrationStatusDto).setLatestTransactionStatusCode(any()); + Mockito.doNothing().when(registrationStatusService).updateRegistrationStatus(any(), any(), any()); + + Mockito.when(packetInfoManager.getAbisRequestsByBioRefId(any())).thenReturn(abisRequestDtoList); + + AbisQueueDetails abisQueueDetails = new AbisQueueDetails(); + abisQueueDetails.setName("ABIS1"); + List abisQueueDetailsList = new ArrayList<>(); + abisQueueDetailsList.add(abisQueueDetails); + Mockito.when(utility.getAbisQueueDetails()).thenReturn(abisQueueDetailsList); + + AuditResponseDto auditResponseDto = new AuditResponseDto(); + ResponseWrapper responseWrapper = new ResponseWrapper<>(); + responseWrapper.setResponse(auditResponseDto); + Mockito.when(auditLogRequestBuilder.createAuditRequestBuilder(any(), any(), any(), any(), any(), any(), any())) + .thenReturn(responseWrapper); + + DataShareResponseDto dataShareResponseDto = new DataShareResponseDto(); + DataShare dataShare = new DataShare(); + dataShare.setUrl("http://localhost"); + dataShareResponseDto.setDataShare(dataShare); + + mockDataSharePolicy(Lists.newArrayList(BiometricType.FACE, BiometricType.FINGER)); + + Mockito.when(registrationProcessorRestClientService.postApi(anyString(), any(MediaType.class), any(), any(), + any(), any(), any())).thenReturn(dataShareResponseDto); + + Mockito.when(cbeffutil.createXML(any())).thenReturn(new byte[2048]); + } + + private Map getExceptionModalityMap() { + Map exceptionMap = new HashMap(); + exceptionMap.put("Left Thumb" , "leftThumb"); + exceptionMap.put("Right Thumb" , "rightThumb"); + exceptionMap.put("Left MiddleFinger" , "leftMiddle"); + exceptionMap.put("Left RingFinger" , "leftRing"); + exceptionMap.put("Left LittleFinger" , "leftLittle"); + exceptionMap.put("Left IndexFinger" , "leftIndex"); + exceptionMap.put("Right MiddleFinger" , "rightMiddle"); + exceptionMap.put("Right RingFinger" , "rightRing"); + exceptionMap.put("Right LittleFinger" , "rightLittle"); + exceptionMap.put("Right IndexFinger" , "rightIndex"); + exceptionMap.put("Left" , "leftEye"); + exceptionMap.put("Right" , "rightEye"); + exceptionMap.put("Face" , "face"); + + return exceptionMap; + } + + private List getFaceList() { + return Arrays.asList("Face"); + } + + private List getIrisList() { + return Arrays.asList("Left", "Right"); + + } + + private List getFingerList() { + return Arrays.asList("Left Thumb", "Left LittleFinger", "Left IndexFinger", "Left MiddleFinger", + "Left RingFinger", "Right Thumb", "Right LittleFinger", + "Right IndexFinger", "Right MiddleFinger", + "Right RingFinger"); + } + + private void mockDataSharePolicy(List sherableBiometricList) throws ApisResourceAccessException { + when(registrationProcessorRestClientService.getApi(any(), any(), anyString(), anyString(), any())) + .thenReturn(getMockDataSharePolicy(sherableBiometricList)); + } + + private ResponseWrapper> getMockDataSharePolicy( + List sherableBiometricList) { + + ObjectMapper mapper = new ObjectMapper(); + + List attr = new LinkedList<>(); + if (sherableBiometricList != null && !sherableBiometricList.isEmpty()) { + + ShareableAttributes shareableAttributes = new ShareableAttributes(); + List sourceList = new ArrayList<>(); + + for (BiometricType bioType : sherableBiometricList) { + Filter filter = new Filter(); + filter.setType(bioType.value()); + Source src = new Source(); + src.setFilter(Lists.newArrayList(filter)); + sourceList.add(src); + } + + shareableAttributes.setSource(sourceList); + attr = Lists.newArrayList(shareableAttributes); + } + + ResponseWrapper> policy = new ResponseWrapper<>(); + LinkedHashMap policies = new LinkedHashMap<>(); + LinkedHashMap sharableAttributes = new LinkedHashMap<>(); + sharableAttributes.put(PolicyConstant.SHAREABLE_ATTRIBUTES, attr); + policies.put(PolicyConstant.POLICIES, sharableAttributes); + policy.setResponse(policies); + + return policy; + } + + @Test + public void testDeployVerticle() { + abisHandlerStage.deployVerticle(); + } + + @Test + public void testDemoToAbisHandlerTOMiddlewareSuccess() throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { + registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); + registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); + Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); + Mockito.when(packetInfoManager.getAllAbisDetails()).thenReturn(abisApplicationDtos); + + mockDataSharePolicy(Lists.newArrayList(BiometricType.IRIS, BiometricType.FINGER, BiometricType.FACE)); + Mockito.when(packetInfoManager.getBioRefIdByRegId(any())).thenReturn(bioRefDtos); + tags.put("AGE_GROUP", "ADULT"); + Mockito.when(packetService.getAllTags(any())).thenReturn(tags); + + Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); + Mockito.doNothing().when(packetInfoManager).saveAbisRequest(any(), any(), any()); + + RegDemoDedupeListDto regDemoDedupeListDto = new RegDemoDedupeListDto(); + regDemoDedupeListDto.setMatchedRegId("10003100030001520190422074511"); + regDemoDedupeListDtoList.add(regDemoDedupeListDto); + Mockito.when(packetInfoManager.getDemoListByTransactionId(any())).thenReturn(regDemoDedupeListDtoList); + + MessageDTO dto = new MessageDTO(); + dto.setRid("10003100030001520190422074511"); + MessageDTO result = abisHandlerStage.process(dto); + + assertTrue(result.getMessageBusAddress().getAddress().equalsIgnoreCase("abis-middle-ware-bus-in")); + } + + @Test + public void testBioToAbisHandlerToMiddlewareSuccess() throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { + registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); + registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); + Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); + Mockito.when(packetInfoManager.getAllAbisDetails()).thenReturn(abisApplicationDtos); + + mockDataSharePolicy(Lists.newArrayList(BiometricType.IRIS, BiometricType.FINGER, BiometricType.FACE)); + RegBioRefDto regBioRefDto = new RegBioRefDto(); + regBioRefDto.setBioRefId("1234567890"); + bioRefDtos.add(regBioRefDto); + Mockito.when(packetInfoManager.getBioRefIdByRegId(any())).thenReturn(bioRefDtos); + tags.put("AGE_GROUP", "ADULT"); + Mockito.when(packetService.getAllTags(any())).thenReturn(tags); + + Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); + Mockito.doNothing().when(packetInfoManager).saveAbisRequest(any(), any(), any()); + + RegDemoDedupeListDto regDemoDedupeListDto = new RegDemoDedupeListDto(); + regDemoDedupeListDto.setMatchedRegId("10003100030001520190422074511"); + regDemoDedupeListDtoList.add(regDemoDedupeListDto); + Mockito.when(packetInfoManager.getDemoListByTransactionId(any())).thenReturn(regDemoDedupeListDtoList); + + MessageDTO dto = new MessageDTO(); + dto.setRid("10003100030001520190422074511"); + MessageDTO result = abisHandlerStage.process(dto); + + assertTrue(result.getMessageBusAddress().getAddress().equalsIgnoreCase("abis-middle-ware-bus-in")); + } + + @Test + public void testMiddlewareToAbisHandlerToDemoSuccess() { + registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); + registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); + Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.TRUE); + + MessageDTO dto = new MessageDTO(); + dto.setRid("10003100030001520190422074511"); + MessageDTO result = abisHandlerStage.process(dto); + + assertTrue(result.getMessageBusAddress().getAddress().equalsIgnoreCase("demo-dedupe-bus-in")); + } + + @Test + public void testMiddlewareToAbisHandlerToBioSuccess() { + registrationStatusDto.setLatestTransactionTypeCode("BIOGRAPHIC_VERIFICATION"); + registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); + Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.TRUE); + + MessageDTO dto = new MessageDTO(); + dto.setRid("10003100030001520190422074511"); + MessageDTO result = abisHandlerStage.process(dto); + + assertTrue(result.getMessageBusAddress().getAddress().equalsIgnoreCase("bio-dedupe-bus-in")); + } + + @Test + public void testDemoDedupeDataNotFound() { + registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); + registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); + Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); + Mockito.when(packetInfoManager.getAllAbisDetails()).thenReturn(abisApplicationDtos); + + Mockito.when(packetInfoManager.getBioRefIdByRegId(any())).thenReturn(bioRefDtos); + + Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); + Mockito.doNothing().when(packetInfoManager).saveAbisRequest(any(), any(), any()); + + Mockito.when(packetInfoManager.getDemoListByTransactionId(any())).thenReturn(regDemoDedupeListDtoList); + + MessageDTO dto = new MessageDTO(); + dto.setRid("10003100030001520190422074511"); + MessageDTO result = abisHandlerStage.process(dto); + + assertTrue(result.getInternalError()); + assertTrue(result.getIsValid()); + } + + @Test + public void testReprocessInsert() throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { + registrationStatusDto.setLatestTransactionTypeCode("BIOGRAPHIC_VERIFICATION"); + registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); + Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); + List appCodeList = new ArrayList<>(); + appCodeList.add("ABIS1"); + Mockito.when(packetInfoManager.getAbisProcessedRequestsAppCodeByBioRefId(any(), any(), any())) + .thenReturn(appCodeList); + + Mockito.when(packetInfoManager.getAllAbisDetails()).thenReturn(abisApplicationDtos); + + RegBioRefDto bioRefDto = new RegBioRefDto(); + bioRefDtos.add(bioRefDto); + Mockito.when(packetInfoManager.getBioRefIdByRegId(any())).thenReturn(bioRefDtos); + + Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); + + AbisRequestDto abisRequestDto = new AbisRequestDto(); + abisRequestDto.setAbisAppCode("ABIS1"); + abisRequestDto.setStatusCode("IN-PROGRESS"); + abisRequestDtoList.add(abisRequestDto); + Mockito.when(packetInfoManager.getAbisRequestsByBioRefId(any())).thenReturn(abisRequestDtoList); + tags.put("AGE_GROUP", "ADULT"); + Mockito.when(packetService.getAllTags(any())).thenReturn(tags); + + Mockito.doNothing().when(packetInfoManager).saveAbisRequest(any(), any(), any()); + + Mockito.when(packetInfoManager.getDemoListByTransactionId(any())).thenReturn(regDemoDedupeListDtoList); + + MessageDTO dto = new MessageDTO(); + dto.setRid("10003100030001520190422074511"); + MessageDTO result = abisHandlerStage.process(dto); + + assertFalse(result.getInternalError()); + assertTrue(result.getIsValid()); + } + + @Test + public void testAbisDetailsNotFound() throws RegistrationProcessorCheckedException { + registrationStatusDto.setLatestTransactionTypeCode("BIOGRAPHIC_VERIFICATION"); + registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); + Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); + + List abisQueueDetails = new ArrayList<>(); + Mockito.when(utility.getAbisQueueDetails()).thenReturn(abisQueueDetails); + + MessageDTO dto = new MessageDTO(); + dto.setRid("10003100030001520190422074511"); + MessageDTO result = abisHandlerStage.process(dto); + + assertTrue(result.getInternalError()); + } + + @Test + public void testPotentialMatchNotFound() throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { + registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); + registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); + Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); + + mockDataSharePolicy(Lists.newArrayList(BiometricType.IRIS, BiometricType.FINGER, BiometricType.FACE)); + tags.put("AGE_GROUP", "ADULT"); + Mockito.when(packetService.getAllTags(any())).thenReturn(tags); + + Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); + Mockito.doNothing().when(packetInfoManager).saveAbisRequest(any(), any(), any()); + + Mockito.when(packetInfoManager.getDemoListByTransactionId(any())).thenReturn(Arrays.asList()); + + MessageDTO dto = new MessageDTO(); + dto.setRid("10003100030001520190422074511"); + MessageDTO result = abisHandlerStage.process(dto); + + assertTrue(result.getInternalError()); + } + + @Test + public void testIdentifyRequestJsonProcessingException() throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { + registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); + registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); + Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); + + mockDataSharePolicy(Lists.newArrayList(BiometricType.IRIS, BiometricType.FINGER, BiometricType.FACE)); + Mockito.when(packetInfoManager.getBioRefIdByRegId(any())).thenReturn(bioRefDtos); + tags.put("AGE_GROUP", "ADULT"); + Mockito.when(packetService.getAllTags(any())).thenReturn(tags); + + Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); + Mockito.doNothing().when(packetInfoManager).saveAbisRequest(any(), any(), any()); + + RegDemoDedupeListDto regDemoDedupeListDto = new RegDemoDedupeListDto(); + regDemoDedupeListDto.setMatchedRegId("10003100030001520190422074511"); + regDemoDedupeListDtoList.add(regDemoDedupeListDto); + Mockito.when(packetInfoManager.getDemoListByTransactionId(any())).thenReturn(regDemoDedupeListDtoList); + + PowerMockito.mockStatic(JsonUtils.class); + PowerMockito.when(JsonUtils.javaObjectToJsonString(any())).thenReturn("value").thenThrow(JsonProcessingException.class); + MessageDTO dto = new MessageDTO(); + dto.setRid("10003100030001520190422074511"); + MessageDTO result = abisHandlerStage.process(dto); + + assertTrue(result.getInternalError()); + } + + @Test + public void testInsertRequestJsonProcessingException() throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { + registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); + registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); + Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); + + mockDataSharePolicy(Lists.newArrayList(BiometricType.IRIS, BiometricType.FINGER, BiometricType.FACE)); + tags.put("AGE_GROUP", "MINOR"); + Mockito.when(packetService.getAllTags(any())).thenReturn(tags); + + Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); + + PowerMockito.mockStatic(JsonUtils.class); + PowerMockito.when(JsonUtils.javaObjectToJsonString(any())).thenThrow(JsonProcessingException.class); + MessageDTO dto = new MessageDTO(); + dto.setRid("10003100030001520190422074511"); + MessageDTO result = abisHandlerStage.process(dto); + + assertTrue(result.getInternalError()); + } + + @Test + public void testDataShareResponseNullException() throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { + registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); + registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); + Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); + + mockDataSharePolicy(Lists.newArrayList(BiometricType.IRIS, BiometricType.FINGER, BiometricType.FACE)); + tags.put("AGE_GROUP", "MINOR"); + Mockito.when(packetService.getAllTags(any())).thenReturn(tags); + + Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); + + DataShareResponseDto dataShareResponseDto = new DataShareResponseDto(); + ErrorDTO error = new ErrorDTO("ERR-001", "exception occured"); + dataShareResponseDto.setDataShare(null); + dataShareResponseDto.setErrors(Arrays.asList(error)); + Mockito.when(registrationProcessorRestClientService.postApi(anyString(), any(MediaType.class), any(), any(), + any(), any(), any())).thenReturn(dataShareResponseDto); + MessageDTO dto = new MessageDTO(); + dto.setRid("10003100030001520190422074511"); + MessageDTO result = abisHandlerStage.process(dto); + + assertTrue(result.getInternalError()); + } + + @Test + public void testCreateTypeSubtypeMappingResponseNullException() + throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { + registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); + registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())) + .thenReturn(registrationStatusDto); + Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); + ErrorDTO error = new ErrorDTO("ERR-001", "exception occured"); + ResponseWrapper> policyResponse = new ResponseWrapper<>(); + + policyResponse.setErrors(Arrays.asList(error)); + + Mockito.when(registrationProcessorRestClientService.getApi(any(), any(), anyString(), + anyString(), any())).thenReturn(policyResponse); + Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); + + MessageDTO dto = new MessageDTO(); + dto.setRid("10003100030001520190422074511"); + MessageDTO result = abisHandlerStage.process(dto); + + assertTrue(result.getInternalError()); + } + + @Test + public void testvalidateBiometricRecordModalitiesEmptyException() + throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { + registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); + registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())) + .thenReturn(registrationStatusDto); + Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); + + mockDataSharePolicy(Lists.newArrayList(BiometricType.IRIS, BiometricType.FINGER, BiometricType.FACE)); + tags.put("AGE_GROUP", "MINOR"); + Mockito.when(packetService.getAllTags(any())).thenReturn(tags); + + Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); + + ResponseWrapper> policyResponse = new ResponseWrapper<>(); + LinkedHashMap response = new LinkedHashMap(); + LinkedHashMap attributes = new LinkedHashMap(); + ShareableAttributes shareableAttributes = new ShareableAttributes(); + shareableAttributes.setSource(Arrays.asList()); + attributes.put(PolicyConstant.SHAREABLE_ATTRIBUTES, Arrays.asList(shareableAttributes)); + response.put(PolicyConstant.POLICIES, attributes); + policyResponse.setResponse(response); + + Mockito.when(registrationProcessorRestClientService.getApi(any(), any(), anyString(), anyString(), any())) + .thenReturn(policyResponse); + + MessageDTO dto = new MessageDTO(); + dto.setRid("10003100030001520190422074511"); + MessageDTO result = abisHandlerStage.process(dto); + + assertTrue(result.getInternalError()); + } + + @Test + public void testvalidateBiometricRecordSegmentEmptyException() + throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { + registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); + registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())) + .thenReturn(registrationStatusDto); + Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); + + mockDataSharePolicy(Lists.newArrayList(BiometricType.IRIS, BiometricType.FINGER, BiometricType.FACE)); + tags.put("AGE_GROUP", "ADULT"); + Mockito.when(packetService.getAllTags(any())).thenReturn(tags); + BiometricRecord biometricRecord = new BiometricRecord(); + biometricRecord.setSegments(null); + Mockito.when(packetManagerService.getBiometrics(any(), any(), any(), any(), any())).thenReturn(biometricRecord); + Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); + + MessageDTO dto = new MessageDTO(); + dto.setRid("10003100030001520190422074511"); + MessageDTO result = abisHandlerStage.process(dto); + + assertTrue(result.getInternalError()); + } + + @Test + public void testvalidateBiometricRecordOthersMapNullException() + throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { + registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); + registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())) + .thenReturn(registrationStatusDto); + Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); + + mockDataSharePolicy(Lists.newArrayList(BiometricType.IRIS, BiometricType.FINGER, BiometricType.FACE)); + tags.put("AGE_GROUP", "ADULT"); + Mockito.when(packetService.getAllTags(any())).thenReturn(tags); + BiometricRecord biometricRecord = new BiometricRecord(); + BIR bir = new BIR.BIRBuilder().build(); + BDBInfo bdbInfo = new BDBInfo.BDBInfoBuilder().build(); + bdbInfo.setSubtype(Arrays.asList("Left")); + bdbInfo.setType(Arrays.asList(BiometricType.IRIS)); + bir.setOthers(null); + bir.setBdbInfo(bdbInfo); + biometricRecord.setSegments(Arrays.asList(bir)); + Mockito.when(packetManagerService.getBiometrics(any(), any(), any(), any(), any())).thenReturn(biometricRecord); + Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); + + MessageDTO dto = new MessageDTO(); + dto.setRid("10003100030001520190422074511"); + MessageDTO result = abisHandlerStage.process(dto); + + assertTrue(result.getInternalError()); + } + + @Test + public void testCreateRequestException() throws JsonProcessingException { + registrationStatusDto.setLatestTransactionTypeCode("BIOGRAPHIC_VERIFICATION"); + registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); + Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); + + Mockito.when(packetInfoManager.getAllAbisDetails()).thenReturn(abisApplicationDtos); + + RegBioRefDto bioRefDto = new RegBioRefDto(); + bioRefDtos.add(bioRefDto); + Mockito.when(packetInfoManager.getBioRefIdByRegId(any())).thenReturn(bioRefDtos); + + Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); + + AbisRequestDto abisRequestDto = new AbisRequestDto(); + abisRequestDto.setAbisAppCode("ABIS1"); + abisRequestDto.setStatusCode("IN-PROGRESS"); + abisRequestDtoList.add(abisRequestDto); + Mockito.when(packetInfoManager.getAbisRequestsByBioRefId(any())).thenReturn(abisRequestDtoList); + + Mockito.doNothing().when(packetInfoManager).saveAbisRequest(any(), any(), any()); + + Mockito.when(packetInfoManager.getDemoListByTransactionId(any())).thenReturn(regDemoDedupeListDtoList); + + PowerMockito.mockStatic(JsonUtils.class); + PowerMockito.when(JsonUtils.javaObjectToJsonString(any(AbisInsertRequestDto.class))) + .thenThrow(JsonProcessingException.class); + + MessageDTO dto = new MessageDTO(); + dto.setRid("10003100030001520190422074511"); + MessageDTO result = abisHandlerStage.process(dto); + + assertTrue(result.getInternalError()); + assertTrue(result.getIsValid()); + } + + @Test + public void testIdentifyRequestException() throws JsonProcessingException { + registrationStatusDto.setLatestTransactionTypeCode("BIOGRAPHIC_VERIFICATION"); + registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); + Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); + + Mockito.when(packetInfoManager.getAllAbisDetails()).thenReturn(abisApplicationDtos); + + RegBioRefDto bioRefDto = new RegBioRefDto(); + bioRefDtos.add(bioRefDto); + Mockito.when(packetInfoManager.getBioRefIdByRegId(any())).thenReturn(bioRefDtos); + + Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); + + AbisRequestDto abisRequestDto = new AbisRequestDto(); + abisRequestDto.setAbisAppCode("ABIS1"); + abisRequestDto.setStatusCode("IN-PROGRESS"); + abisRequestDtoList.add(abisRequestDto); + Mockito.when(packetInfoManager.getAbisRequestsByBioRefId(any())).thenReturn(abisRequestDtoList); + + Mockito.doNothing().when(packetInfoManager).saveAbisRequest(any(), any(), any()); + + Mockito.when(packetInfoManager.getDemoListByTransactionId(any())).thenReturn(regDemoDedupeListDtoList); + + PowerMockito.mockStatic(JsonUtils.class); + PowerMockito.when(JsonUtils.javaObjectToJsonString(any(AbisInsertRequestDto.class))) + .thenReturn("AbisInsertRequestDto"); + PowerMockito.when(JsonUtils.javaObjectToJsonString(ArgumentMatchers.any(AbisIdentifyRequestDto.class))) + .thenThrow(JsonProcessingException.class); + + MessageDTO dto = new MessageDTO(); + dto.setRid("10003100030001520190422074511"); + MessageDTO result = abisHandlerStage.process(dto); + + assertTrue(result.getInternalError()); + assertTrue(result.getIsValid()); + } + + + @Test + public void bioRecordDataNotFound() + throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { + + defaultMockToProcess(); + + Mockito.when(packetManagerService.getBiometrics(any(), any(), any(), any(), any())).thenReturn(null); + mockDataSharePolicy(Lists.newArrayList(BiometricType.IRIS, BiometricType.FINGER, BiometricType.FACE)); + + setMetaInfoMap(new LinkedList<>(getExceptionModalityMap().values())); + MessageDTO dto = new MessageDTO(); + dto.setRid("10003100030001520190422074511"); + MessageDTO result = abisHandlerStage.process(dto); + + assertTrue(result.getIsValid()); + assertTrue(result.getInternalError()); + } + + @Test + public void biometricsNotFoundWithSegmentConfig() + throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { + + defaultMockToProcess(); + + Mockito.when(packetManagerService.getBiometrics(any(), any(), any(), any(), any())).thenReturn(getBiometricRecord(Arrays.asList("Left Thumb" ,"Right Thumb","Face"),false)); + + + setMetaInfoMap(Arrays.asList("leftEye")); + MessageDTO dto = new MessageDTO(); + dto.setRid("10003100030001520190422074511"); + MessageDTO result = abisHandlerStage.process(dto); + + assertTrue(result.getIsValid()); + assertTrue(result.getInternalError()); + } + + @Test + public void biometricsTypeNotFoundConfig() + throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { + + defaultMockToProcess(); + + Map>> biometricModalitySegmentsMapforAgeGroup = new HashMap>>(); + Map> biometricModalitySegmentsMap = new HashMap(); + + biometricModalitySegmentsMap.put("Finger", getFingerList()); + biometricModalitySegmentsMap.put("Iris", getIrisList()); + biometricModalitySegmentsMapforAgeGroup.put("DEFAULT", biometricModalitySegmentsMap); + + MessageDTO dto = new MessageDTO(); + dto.setRid("10003100030001520190422074511"); + MessageDTO result = abisHandlerStage.process(dto); + + assertTrue(result.getIsValid()); + assertTrue(result.getInternalError()); + } + + @Test + public void testBiometricSegmentNotConfiguredInfant() throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { + registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); + registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); + Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); + Mockito.when(packetInfoManager.getAllAbisDetails()).thenReturn(abisApplicationDtos); + + Mockito.when(packetInfoManager.getBioRefIdByRegId(any())).thenReturn(bioRefDtos); + tags.put("AGE_GROUP", "INFANT"); + Mockito.when(packetService.getAllTags(any())).thenReturn(tags); + + Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); + Mockito.doNothing().when(packetInfoManager).saveAbisRequest(any(), any(), any()); + + RegDemoDedupeListDto regDemoDedupeListDto = new RegDemoDedupeListDto(); + regDemoDedupeListDto.setMatchedRegId("10003100030001520190422074511"); + regDemoDedupeListDtoList.add(regDemoDedupeListDto); + Mockito.when(packetInfoManager.getDemoListByTransactionId(any())).thenReturn(regDemoDedupeListDtoList); + + MessageDTO dto = new MessageDTO(); + dto.setRid("10003100030001520190422074511"); + MessageDTO result = abisHandlerStage.process(dto); + + assertTrue(result.getIsValid()); + assertFalse(result.getInternalError()); + } + + + + @Test + public void emptyBdbFound() + throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { + + defaultMockToProcess(); + + boolean isBdbEmpty = true; + Mockito.when(packetManagerService.getBiometrics(any(), any(), any(), any(), any())).thenReturn(getBiometricRecord(Arrays.asList("Left RingFinger"), isBdbEmpty )); + mockDataSharePolicy(Lists.newArrayList(BiometricType.FINGER)); + + List list = new ArrayList(getExceptionModalityMap().values()); + list.remove("leftRing"); + setMetaInfoMap(list); + + MessageDTO dto = new MessageDTO(); + dto.setRid("10003100030001520190422074511"); + MessageDTO result = abisHandlerStage.process(dto); + + assertTrue(result.getIsValid()); + assertTrue(result.getInternalError()); + } + + @Test + public void noBdbInAnyBiometric() + throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { + + defaultMockToProcess(); + + Mockito.when(packetManagerService.getBiometrics(any(), any(), any(), any(), any())).thenReturn(getBiometricRecord(Arrays.asList("Left Thumb" ,"Right Thumb" , "Left MiddleFinger" , + "Left RingFinger" ,"Left LittleFinger" ,"Left IndexFinger" ,"Right MiddleFinger" , + "Right RingFinger" ,"Right LittleFinger" ,"Right IndexFinger" , + "Left" ,"Right","Face"),true)); + + MessageDTO dto = new MessageDTO(); + dto.setRid("10003100030001520190422074511"); + MessageDTO result = abisHandlerStage.process(dto); + + assertTrue(result.getIsValid()); + assertTrue(result.getInternalError()); + } + + private void defaultMockToProcess() { + registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); + registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); + Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); + Mockito.when(packetInfoManager.getAllAbisDetails()).thenReturn(abisApplicationDtos); + + RegBioRefDto regBioRefDto = new RegBioRefDto(); + regBioRefDto.setBioRefId("1234567890"); + bioRefDtos.add(regBioRefDto); + Mockito.when(packetInfoManager.getBioRefIdByRegId(any())).thenReturn(bioRefDtos); + + Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); + Mockito.doNothing().when(packetInfoManager).saveAbisRequest(any(), any(), any()); + + RegDemoDedupeListDto regDemoDedupeListDto = new RegDemoDedupeListDto(); + regDemoDedupeListDto.setMatchedRegId("10003100030001520190422074511"); + regDemoDedupeListDtoList.add(regDemoDedupeListDto); + Mockito.when(packetInfoManager.getDemoListByTransactionId(any())).thenReturn(regDemoDedupeListDtoList); + + } + + private void setMetaInfoMap(List exceptionAttributes) throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException{ + + Map metaInfoMap = new HashMap<>(); + + Map> exceptionBiometrcisMap = new HashMap<>(); + + Map applicantExceptionBiometrcisMap = new HashMap(); + + if(exceptionAttributes!=null) { + for(String exceptionAttribute : exceptionAttributes) { + + Map detailMap = new HashMap(); + detailMap.put("missingBiometric", exceptionAttribute); + detailMap.put("reason", "Temporary"); + detailMap.put("individualType", "applicant"); + + applicantExceptionBiometrcisMap.put(exceptionAttribute, detailMap); + + } + } + + + exceptionBiometrcisMap.put("applicant", applicantExceptionBiometrcisMap); + String gsonString =mapper.writeValueAsString(exceptionBiometrcisMap); + + metaInfoMap.put("exceptionBiometrics", gsonString); + metaInfoMap.put(JsonConstant.METADATA, + "[{\n \"label\" : \"Registration Client Version Number\",\n \"value\" : \"1.2.0\"\n}]"); + Mockito.when(packetManagerService.getMetaInfo(any(), any(), any())).thenReturn(metaInfoMap); + } + + private BiometricRecord getBiometricRecord(List bioAttributes, boolean isBdbEmpty) { + BiometricRecord biometricRecord = new BiometricRecord(); + + byte[] bdb = isBdbEmpty ? null : new byte[2048]; + for(String bioAttribute : bioAttributes) { + BIR birType1 = new BIR.BIRBuilder().build(); + 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 = bioAttribute.equalsIgnoreCase("face") ? BiometricType.FACE : + bioAttribute.equalsIgnoreCase("left") || bioAttribute.equalsIgnoreCase("right") ? BiometricType.IRIS : BiometricType.FINGER ; + List singleTypeList1 = new ArrayList<>(); + singleTypeList1.add(singleType1); + bdbInfoType1.setType(singleTypeList1); + + + + String[] bioAttributeArray = bioAttribute.split(" "); + + List subtype = new ArrayList<>(); + for(String attribute : bioAttributeArray) { + subtype.add(attribute); + } + bdbInfoType1.setSubtype(subtype); + + birType1.setBdbInfo(bdbInfoType1); + birType1.setBdb(bdb); + + if(bdb==null) { + Map others = new HashMap<>(); + others.put("EXCEPTION", true); + HashMap entry = new HashMap<>(); + entry.put("EXCEPTION", "true"); + birType1.setOthers(entry); + + } + + biometricRecord.getSegments().add(birType1); + } + + return biometricRecord; + } + } \ No newline at end of file From 5deea9bf14bdc5fe06195633941e1824b9f235a6 Mon Sep 17 00:00:00 2001 From: Sowmya Ujjappa Banakar Date: Tue, 12 Sep 2023 15:39:29 +0530 Subject: [PATCH 095/133] MOSIP-29399 code fix --- .../abis/handler/stage/AbisHandlerStage.java | 23 +++++++++++-------- 1 file changed, 13 insertions(+), 10 deletions(-) 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 1a9185b66ec..f6316a46b6b 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 @@ -577,13 +577,7 @@ private String getUUID() { private String getDataShareUrl(String id, String process) throws Exception { Map> typeAndSubtypMap = createTypeSubtypeMapping(); List modalities = new ArrayList<>(); - for (Map.Entry> entry : typeAndSubtypMap.entrySet()) { - if (entry.getValue() == null) { - modalities.add(entry.getKey()); - } else { - modalities.addAll(entry.getValue()); - } - } + modalities.addAll(typeAndSubtypMap.keySet()); JSONObject regProcessorIdentityJson = utility .getRegistrationProcessorMappingJson(MappingJsonConstants.IDENTITY); String individualBiometricsLabel = JsonUtil.getJSONValue( @@ -602,7 +596,8 @@ private String getDataShareUrl(String id, String process) throws Exception { biometricModalitySegmentsMap = biometricModalitySegmentsMapforAgeGroup.get("DEFAULT"); } validateBiometricRecord(biometricRecord, modalities, biometricModalitySegmentsMap, - priorityBasedPacketManagerService.getMetaInfo(id, process, ProviderStageName.BIO_DEDUPE)); + priorityBasedPacketManagerService.getMetaInfo(id, process, ProviderStageName.BIO_DEDUPE), + typeAndSubtypMap); byte[] content = cbeffutil.createXML(filterExceptionBiometrics(biometricRecord,id,process).getSegments()); @@ -640,7 +635,8 @@ public String getFilename() { @SuppressWarnings("deprecation") private void validateBiometricRecord(BiometricRecord biometricRecord, List modalities, - Map> biometricModalitySegmentsMap, Map metaInfoMap) + Map> biometricModalitySegmentsMap, Map metaInfoMap, + Map> typeAndSubtypMap) throws DataShareException, JsonParseException, JsonMappingException, IOException { if (modalities == null || modalities.isEmpty()) { throw new DataShareException("Data Share Policy Modalities were Empty"); @@ -662,9 +658,16 @@ private void validateBiometricRecord(BiometricRecord biometricRecord, List biometricModalitySegmentsMapFromPolicy = typeAndSubtypMap.get(biometricSegment); for (String segment : biometricModalitySegmentsMap.get(biometricSegment)) { + if (biometricModalitySegmentsMapFromPolicy != null + && !biometricModalitySegmentsMapFromPolicy.contains(segment)) { + throw new DataShareException( + "Biometrics Segments Not Configured as per policy for modality : " + biometricSegment); + } Optional optionalBIR = Optional.empty(); if (segment.equalsIgnoreCase("Face")) { optionalBIR = biometricRecord.getSegments().stream() From 17bc0ecffbb547b4f6959b1008e80a0af657fb5a Mon Sep 17 00:00:00 2001 From: Sowmya Ujjappa Banakar Date: Wed, 13 Sep 2023 11:00:28 +0530 Subject: [PATCH 096/133] MOSIP-29399 Code fix --- .../abis/handler/stage/AbisHandlerStage.java | 44 +++++++++++-------- 1 file changed, 26 insertions(+), 18 deletions(-) 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 f6316a46b6b..23ab72ea0ef 100644 --- a/registration-processor/core-processor/registration-processor-abis-handler-stage/src/main/java/io/mosip/registration/processor/abis/handler/stage/AbisHandlerStage.java +++ b/registration-processor/core-processor/registration-processor-abis-handler-stage/src/main/java/io/mosip/registration/processor/abis/handler/stage/AbisHandlerStage.java @@ -575,29 +575,37 @@ private String getUUID() { } private String getDataShareUrl(String id, String process) throws Exception { - Map> typeAndSubtypMap = createTypeSubtypeMapping(); + Map> policyTypeAndSubTypeMap = createTypeSubtypeMapping(); List modalities = new ArrayList<>(); - modalities.addAll(typeAndSubtypMap.keySet()); + List policyTypeAndSubTypeList = new ArrayList<>(); + modalities.addAll(policyTypeAndSubTypeMap.keySet()); + for (Map.Entry> entry : policyTypeAndSubTypeMap.entrySet()) { + if (entry.getValue() == null) { + policyTypeAndSubTypeList.add(entry.getKey()); + } else { + policyTypeAndSubTypeList.addAll(entry.getValue()); + } + } JSONObject regProcessorIdentityJson = utility .getRegistrationProcessorMappingJson(MappingJsonConstants.IDENTITY); String individualBiometricsLabel = JsonUtil.getJSONValue( JsonUtil.getJSONObject(regProcessorIdentityJson, MappingJsonConstants.INDIVIDUAL_BIOMETRICS), MappingJsonConstants.VALUE); BiometricRecord biometricRecord = priorityBasedPacketManagerService.getBiometrics(id, individualBiometricsLabel, - 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, + validateBiometricRecord(biometricRecord, modalities, ageGroupModalitySegmentMap, priorityBasedPacketManagerService.getMetaInfo(id, process, ProviderStageName.BIO_DEDUPE), - typeAndSubtypMap); + policyTypeAndSubTypeMap); byte[] content = cbeffutil.createXML(filterExceptionBiometrics(biometricRecord,id,process).getSegments()); @@ -635,8 +643,8 @@ public String getFilename() { @SuppressWarnings("deprecation") private void validateBiometricRecord(BiometricRecord biometricRecord, List modalities, - Map> biometricModalitySegmentsMap, Map metaInfoMap, - Map> typeAndSubtypMap) + 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"); @@ -656,17 +664,17 @@ private void validateBiometricRecord(BiometricRecord biometricRecord, List biometricModalitySegmentsMapFromPolicy = typeAndSubtypMap.get(biometricSegment); - for (String segment : biometricModalitySegmentsMap.get(biometricSegment)) { - if (biometricModalitySegmentsMapFromPolicy != null - && !biometricModalitySegmentsMapFromPolicy.contains(segment)) { + 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 : " + biometricSegment); + "Biometrics Segments Not Configured as per policy for modality : " + biometricModality); } Optional optionalBIR = Optional.empty(); if (segment.equalsIgnoreCase("Face")) { From 9fe3ebe44f839852d24122508e68d2ed022d2802 Mon Sep 17 00:00:00 2001 From: Rakshitha650 Date: Thu, 21 Sep 2023 17:50:05 +0530 Subject: [PATCH 097/133] [MOSIP-29167]added reusable workflow --- ...lear_artifacts.yml => clear-artifacts.yml} | 0 .github/workflows/mavenpublish.yml | 60 - .github/workflows/postgres-init_trigger.yml | 83 -- .github/workflows/push-trigger.yml | 131 ++ .github/workflows/push_trigger.yml | 1060 ----------------- .github/workflows/release-changes.yml | 26 + .github/workflows/release_changes.yml | 61 - .github/workflows/release_trigger.yml | 739 ------------ .github/workflows/tag.yaml | 40 +- .../pom.xml | 1 + .../pom.xml | 1 + registration-processor/init/pom.xml | 1 + registration-processor/pom.xml | 65 + .../qc-users-manger/pom.xml | 1 + 14 files changed, 241 insertions(+), 2028 deletions(-) rename .github/workflows/{clear_artifacts.yml => clear-artifacts.yml} (100%) delete mode 100644 .github/workflows/mavenpublish.yml delete mode 100644 .github/workflows/postgres-init_trigger.yml create mode 100644 .github/workflows/push-trigger.yml delete mode 100644 .github/workflows/push_trigger.yml create mode 100644 .github/workflows/release-changes.yml delete mode 100644 .github/workflows/release_changes.yml delete mode 100644 .github/workflows/release_trigger.yml diff --git a/.github/workflows/clear_artifacts.yml b/.github/workflows/clear-artifacts.yml similarity index 100% rename from .github/workflows/clear_artifacts.yml rename to .github/workflows/clear-artifacts.yml diff --git a/.github/workflows/mavenpublish.yml b/.github/workflows/mavenpublish.yml deleted file mode 100644 index a8f46091724..00000000000 --- a/.github/workflows/mavenpublish.yml +++ /dev/null @@ -1,60 +0,0 @@ -# This workflow will build a package using Maven and then publish it nexus when a pull request is merged -# For more information see: https://github.com/actions/setup-java#apache-maven-with-a-settings-path - -name: Maven Package upon a pull request - -on: - pull_request: - types: [closed] - -jobs: - build: - - runs-on: ubuntu-latest - - if: github.event.pull_request.merged == true - - steps: - - uses: actions/checkout@v2 - - name: Set up JDK 11 - uses: actions/setup-java@v1 - with: - ref: ${{ github.ref }} - java-version: 11 - server-id: ossrh # Value of the distributionManagement/repository/id field of the pom.xml - settings-path: ${{ github.workspace }} # location for the settings.xml file - - - name: Setup branch and env - run: | - # Strip git ref prefix from version - echo "BRANCH_NAME=$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')" >> $GITHUB_ENV - echo "GPG_TTY=$(tty)" >> $GITHUB_ENV - - - name: Setup branch and GPG public key - run: | - # Strip git ref prefix from version - echo ${{ env.BRANCH_NAME }} - echo ${{ env.GPG_TTY }} - sudo apt-get --yes install gnupg2 - gpg2 --import ./.github/keys/mosipgpgkey_pub.gpg - gpg2 --quiet --batch --passphrase=${{secrets.gpg_secret}} --allow-secret-key-import --import ./.github/keys/mosipgpgkey_sec.gpg - - uses: actions/cache@v1 - with: - path: ~/.m2/repository - key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }} - restore-keys: | - ${{ runner.os }}-maven-${{ env.BRANCH_NAME }} - - - name: Setup the settings file for ossrh server - run: echo " ossrh ${{secrets.ossrh_user}} ${{secrets.ossrh_secret}} ossrh true gpg2 ${{secrets.gpg_secret}} allow-snapshots true snapshots-repo https://oss.sonatype.org/content/repositories/snapshots false true releases-repo https://oss.sonatype.org/service/local/staging/deploy/maven2 true false sonar . https://sonarcloud.io false " > $GITHUB_WORKSPACE/settings.xml - - - name: Build with Maven - run: mvn -B package -s $GITHUB_WORKSPACE/settings.xml -DskipTests --file pom.xml - - - name: Publish to GitHub Packages Apache Maven - run: | - chmod +x ./deploy.sh - ./deploy.sh registration-processor $GITHUB_WORKSPACE/settings.xml SNAPSHOT - env: - GPG_TTY: $(tty) - diff --git a/.github/workflows/postgres-init_trigger.yml b/.github/workflows/postgres-init_trigger.yml deleted file mode 100644 index 3de4c6f32c5..00000000000 --- a/.github/workflows/postgres-init_trigger.yml +++ /dev/null @@ -1,83 +0,0 @@ -name: Trigger postgres-init repo upon db scripts updates - -on: - push: - branches: - - master - - 1.* - - develop - - release* - paths: - - db_release_scripts/** - - db_scripts/** - -jobs: - paths-filter: - runs-on: ubuntu-latest - outputs: - db_release_scripts: ${{ steps.filter.outputs.db_release_scripts }} - db_scripts: ${{ steps.filter.outputs.db_scripts }} - steps: - - uses: actions/checkout@v2 - - uses: dorny/paths-filter@v2 - id: filter - with: - base: ${{ github.ref }} - filters: | - db_release_scripts: - - 'db_release_scripts/**' - db_scripts: - - 'db_scripts/**' - - # run only if 'db_release_scripts' files were changed - db_release_scripts_updates: - needs: paths-filter - if: needs.paths-filter.outputs.db_release_scripts == 'true' - runs-on: ubuntu-latest - steps: - - name: Check for updates - run: echo "Updates are present in db_release_scripts directory, Triggering postgres-init repo" - - uses: 8398a7/action-slack@v3 - with: - status: ${{ job.status }} - fields: repo,message,commit,author,job,took,ref # selectable (default: repo,message) - env: - SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_DEVOPS }} # required - if: success() # Pick up events when the job is successful. - - # run only if not 'db_release_scripts' files were changed - - name: Check for no updates - if: needs.paths-filter.outputs.db_release_scripts != 'true' - run: echo "Updates are not present in db_release_scripts directory" - - # run only if 'db_scripts' files were changed - db_scripts_updates: - needs: paths-filter - if: needs.paths-filter.outputs.db_scripts == 'true' - runs-on: ubuntu-latest - steps: - - name: Check for updates - run: echo "Updates are present in db_scripts directory, Triggering postgres-init repo" - - uses: 8398a7/action-slack@v3 - with: - status: ${{ job.status }} - fields: repo,message,commit,author,job,took,ref # selectable (default: repo,message) - env: - SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_DEVOPS }} # required - if: success() # Pick up events when the job is successful. - - # run only if not 'db_scripts' files were changed - - name: Check for no updates - if: needs.paths-filter.outputs.db_scripts != 'true' - run: echo "Updates are not present in db_scripts directory" - - # This job is to trigger postgres-init repo. - trigger-postgres_init_repo: - runs-on: ubuntu-latest - steps: - - uses: peter-evans/repository-dispatch@v2 - with: - token: ${{ secrets.ACTION_PAT }} - repository: mosip/postgres-init - base: ${{ github.ref }} - event-type: db-event diff --git a/.github/workflows/push-trigger.yml b/.github/workflows/push-trigger.yml new file mode 100644 index 00000000000..ab05c642dcc --- /dev/null +++ b/.github/workflows/push-trigger.yml @@ -0,0 +1,131 @@ +name: Maven Package upon a push + +on: + release: + types: [published] + pull_request: + types: [opened] + + workflow_dispatch: + inputs: + message: + description: 'Message for manually triggering' + required: false + default: 'Triggered for Updates' + type: string + push: + branches: + - '!release-branch' + - release-1* + - master + - 1.* + - develop + +jobs: + build-maven-registration: + uses: mosip/kattu/.github/workflows/maven-build.yml@master + with: + SERVICE_LOCATION: ./registration-processor + BUILD_ARTIFACT: registration + secrets: + OSSRH_USER: ${{ secrets.OSSRH_USER }} + OSSRH_SECRET: ${{ secrets.OSSRH_SECRET }} + OSSRH_TOKEN: ${{ secrets.OSSRH_TOKEN }} + GPG_SECRET: ${{ secrets.GPG_SECRET }} + SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK }} + + publish_to_nexus: + if: "${{ !contains(github.ref, 'master') && github.event_name != 'pull_request' }}" + needs: build-maven-registration + uses: mosip/kattu/.github/workflows/maven-publish-to-nexus.yml@master + with: + SERVICE_LOCATION: ./registration-processor + secrets: + OSSRH_USER: ${{ secrets.OSSRH_USER }} + OSSRH_SECRET: ${{ secrets.OSSRH_SECRET }} + OSSRH_URL: ${{ secrets.OSSRH_SNAPSHOT_URL }} + OSSRH_TOKEN: ${{ secrets.OSSRH_TOKEN }} + GPG_SECRET: ${{ secrets.GPG_SECRET }} + SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK }} + + build-dockers: + needs: build-maven-registration + strategy: + matrix: + include: + - SERVICE_LOCATION: 'registration-processor/post-processor/registration-processor-registration-transaction-service' + SERVICE_NAME: 'registration-processor-registration-transaction-service' + BUILD_ARTIFACT: 'registration' + - SERVICE_LOCATION: 'registration-processor/stage-groups/registration-processor-stage-group-1' + SERVICE_NAME: 'registration-processor-stage-group-1' + BUILD_ARTIFACT: 'registration' + - SERVICE_LOCATION: 'registration-processor/stage-groups/registration-processor-stage-group-2' + SERVICE_NAME: 'registration-processor-stage-group-2' + BUILD_ARTIFACT: 'registration' + - SERVICE_LOCATION: 'registration-processor/stage-groups/registration-processor-stage-group-3' + SERVICE_NAME: 'registration-processor-stage-group-3' + BUILD_ARTIFACT: 'registration' + - SERVICE_LOCATION: 'registration-processor/stage-groups/registration-processor-stage-group-4' + SERVICE_NAME: 'registration-processor-stage-group-4' + BUILD_ARTIFACT: 'registration' + - SERVICE_LOCATION: 'registration-processor/stage-groups/registration-processor-stage-group-5' + SERVICE_NAME: 'registration-processor-stage-group-5' + BUILD_ARTIFACT: 'registration' + - SERVICE_LOCATION: 'registration-processor/stage-groups/registration-processor-stage-group-6' + SERVICE_NAME: 'registration-processor-stage-group-6' + BUILD_ARTIFACT: 'registration' + - SERVICE_LOCATION: 'registration-processor/stage-groups/registration-processor-stage-group-7' + SERVICE_NAME: 'registration-processor-stage-group-7' + BUILD_ARTIFACT: 'registration' + - SERVICE_LOCATION: 'registration-processor/core-processor/registration-processor-abis' + SERVICE_NAME: 'registration-processor-abis' + BUILD_ARTIFACT: 'registration' + - SERVICE_LOCATION: 'registration-processor/workflow-engine/registration-processor-reprocessor' + SERVICE_NAME: 'registration-processor-reprocessor' + BUILD_ARTIFACT: 'registration' + - SERVICE_LOCATION: 'registration-processor/init/registration-processor-dmz-packet-server' + SERVICE_NAME: 'registration-processor-dmz-packet-server' + - SERVICE_LOCATION: 'registration-processor/init/registration-processor-registration-status-service' + SERVICE_NAME: 'registration-processor-registration-status-service' + BUILD_ARTIFACT: 'registration' + - SERVICE_LOCATION: 'registration-processor/registration-processor-notification-service' + SERVICE_NAME: 'registration-processor-notification-service' + BUILD_ARTIFACT: 'registration' + - SERVICE_LOCATION: 'registration-processor/registration-processor-landing-zone' + SERVICE_NAME: 'registration-processor-landing-zone' + BUILD_ARTIFACT: 'registration' + - SERVICE_LOCATION: 'registration-processor/workflow-engine/registration-processor-workflow-manager-service' + SERVICE_NAME: 'registration-processor-workflow-manager-service' + BUILD_ARTIFACT: 'registration' + - SERVICE_LOCATION: 'registration-processor/registration-processor-common-camel-bridge' + SERVICE_NAME: 'registration-processor-common-camel-bridge' + BUILD_ARTIFACT: 'registration' + + fail-fast: false + name: ${{ matrix.SERVICE_NAME }} + uses: mosip/kattu/.github/workflows/docker-build.yml@master + with: + SERVICE_LOCATION: ${{ matrix.SERVICE_LOCATION }} + SERVICE_NAME: ${{ matrix.SERVICE_NAME }} + BUILD_ARTIFACT: ${{ matrix.BUILD_ARTIFACT || false }} + secrets: + DEV_NAMESPACE_DOCKER_HUB: ${{ secrets.DEV_NAMESPACE_DOCKER_HUB }} + ACTOR_DOCKER_HUB: ${{ secrets.ACTOR_DOCKER_HUB }} + RELEASE_DOCKER_HUB: ${{ secrets.RELEASE_DOCKER_HUB }} + SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK }} + + + sonar_analysis: + needs: build-maven-registration + if: "${{ github.event_name != 'pull_request' }}" + uses: mosip/kattu/.github/workflows/maven-sonar-analysis.yml@master + with: + SERVICE_LOCATION: ./registration-processor + secrets: + SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} + ORG_KEY: ${{ secrets.ORG_KEY }} + OSSRH_USER: ${{ secrets.OSSRH_USER }} + OSSRH_SECRET: ${{ secrets.OSSRH_SECRET }} + OSSRH_TOKEN: ${{ secrets.OSSRH_TOKEN }} + GPG_SECRET: ${{ secrets.GPG_SECRET }} + SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK }} \ No newline at end of file diff --git a/.github/workflows/push_trigger.yml b/.github/workflows/push_trigger.yml deleted file mode 100644 index f9610ca2c03..00000000000 --- a/.github/workflows/push_trigger.yml +++ /dev/null @@ -1,1060 +0,0 @@ -name: Maven Package upon a push - -on: - pull_request: - types: [closed] - push: - branches: - - '!release-branch' - - release-1* - - master - - 1.* - - develop -jobs: - build: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v2 - - name: Set up JDK 11 - uses: actions/setup-java@v1 - with: - ref: ${{ github.ref }} - java-version: 11 - server-id: ossrh # Value of the distributionManagement/repository/id field of the pom.xml - settings-path: ${{ github.workspace }} # location for the settings.xml file - - - name: Setup branch and env - run: | - # Strip git ref prefix from version - echo "BRANCH_NAME=$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')" >> $GITHUB_ENV - echo "GPG_TTY=$(tty)" >> $GITHUB_ENV - - name: Setup branch and GPG public key - run: | - # Strip git ref prefix from version - echo ${{ env.BRANCH_NAME }} - echo ${{ env.GPG_TTY }} - sudo apt-get --yes install gnupg2 - gpg2 --import ./.github/keys/mosipgpgkey_pub.gpg - gpg2 --quiet --batch --passphrase=${{secrets.gpg_secret}} --allow-secret-key-import --import ./.github/keys/mosipgpgkey_sec.gpg - - uses: actions/cache@v1 - with: - path: ~/.m2/repository - key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }} - restore-keys: | - ${{ runner.os }}-maven-${{ env.BRANCH_NAME }} - - name: Setup the settings file for ossrh server - run: echo " ossrh ${{secrets.ossrh_user}} ${{secrets.ossrh_secret}} ossrh true gpg2 ${{secrets.gpg_secret}} allow-snapshots true snapshots-repo https://oss.sonatype.org/content/repositories/snapshots false true releases-repo https://oss.sonatype.org/service/local/staging/deploy/maven2 true false sonar . https://sonarcloud.io false " > $GITHUB_WORKSPACE/settings.xml - - - name: Build with Maven - run: | - cd registration-processor - mvn -B package -s $GITHUB_WORKSPACE/settings.xml --file pom.xml - - name: Ready the springboot artifacts - run: find -name '*.jar' -executable -type f -exec zip release.zip {} + - - - - name: Upload the springboot jars - uses: actions/upload-artifact@v1 - with: - name: release - path: ./release.zip - - publish_to_nexus: - if: "!contains(github.ref, 'master')" - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v2 - - name: Set up JDK 11 - uses: actions/setup-java@v1 - with: - ref: ${{ github.ref }} - java-version: 11 - server-id: ossrh # Value of the distributionManagement/repository/id field of the pom.xml - settings-path: ${{ github.workspace }} # location for the settings.xml file - - uses: actions/checkout@v2 - - - name: Setup branch and env - run: | - # Strip git ref prefix from version - echo "BRANCH_NAME=$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')" >> $GITHUB_ENV - echo "GPG_TTY=$(tty)" >> $GITHUB_ENV - - name: Setup branch and GPG public key - run: | - # Strip git ref prefix from version - echo ${{ env.BRANCH_NAME }} - echo ${{ env.GPG_TTY }} - sudo apt-get --yes install gnupg2 - gpg2 --import ./.github/keys/mosipgpgkey_pub.gpg - gpg2 --quiet --batch --passphrase=${{secrets.gpg_secret}} --allow-secret-key-import --import ./.github/keys/mosipgpgkey_sec.gpg - - - uses: actions/cache@v1 - with: - path: ~/.m2/repository - key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }} - restore-keys: | - ${{ runner.os }}-maven-${{ env.BRANCH_NAME }} - - name: Install xmllint - run: | - sudo apt-get update - sudo apt-get install libxml2-utils - - name: Setup the settings file for ossrh server - run: echo " ossrh ${{secrets.RELEASE_USER}} ${{secrets.RELEASE_TOKEN}} ossrh true gpg2 ${{secrets.gpg_secret}} allow-snapshots true snapshots-repo https://oss.sonatype.org/content/repositories/snapshots false true releases-repo https://oss.sonatype.org/service/local/staging/deploy/maven2 true false sonar . https://sonarcloud.io false " > $GITHUB_WORKSPACE/settings.xml - - - name: Publish the maven package - run: | - mvn deploy -DaltDeploymentRepository=ossrh::default::${{ secrets.RELEASE_URL }} -s $GITHUB_WORKSPACE/settings.xml -f pom.xml - env: - GITHUB_TOKEN: ${{ secrets.RELEASE_TOKEN }} - GPG_TTY: $(tty) - - docker-registration-processor-registration-transaction-service: - needs: build - runs-on: ubuntu-latest - env: - NAMESPACE: ${{ secrets.dev_namespace_docker_hub }} - SERVICE_NAME: registration-processor-registration-transaction-service - SERVICE_LOCATION: registration-processor/post-processor/registration-processor-registration-transaction-service - steps: - - uses: actions/checkout@v2 - - uses: actions/download-artifact@v1 - with: - name: release - path: ./ - - - name: Setup branch name - run: | - # Strip git ref prefix from version - echo "BRANCH_NAME=$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')" >> $GITHUB_ENV - - name: Get version info from pom - id: getPomVersion - uses: mavrosxristoforos/get-xml-info@1.0 - with: - xml-file: ./${{ env.SERVICE_LOCATION }}/pom.xml - xpath: /*[local-name()="project"]/*[local-name()="version"] - - - name: Unzip and extract the ${{ env.SERVICE_NAME }} - run: unzip -uj "release.zip" "${{ env.SERVICE_LOCATION }}/target/*" -d "./${{ env.SERVICE_LOCATION }}/target" - - - name: Get current date - id: date - run: echo "::set-output name=date::$(date +'%Y-%m-%d')" - - - name: Build image - run: | - cd "./${{env.SERVICE_LOCATION}}" - docker build . --build-arg SOURCE=mosip --build-arg COMMIT_HASH=$(git rev-parse HEAD) --build-arg COMMIT_ID=$(git rev-parse --short HEAD) --build-arg BUILD_TIME=${{steps.date.outputs.date}} --file Dockerfile --tag ${{ env.SERVICE_NAME }} - - name: Log into registry - run: echo "${{ secrets.release_docker_hub }}" | docker login -u ${{ secrets.actor_docker_hub }} --password-stdin - - - name: Push image - run: | - IMAGE_ID=$NAMESPACE/$SERVICE_NAME - - # Change all uppercase to lowercase - IMAGE_ID=$(echo $IMAGE_ID | tr '[A-Z]' '[a-z]') - echo "push version ${{steps.getPomVersion.outputs.info}}" - if [[ $BRANCH_NAME == master ]]; then - VERSION=latest - else - VERSION=$BRANCH_NAME - fi - echo IMAGE_ID=$IMAGE_ID - echo VERSION=$VERSION - docker tag $SERVICE_NAME $IMAGE_ID:$VERSION - docker push $IMAGE_ID:$VERSION - - docker-registration-processor-stage-group-1: - needs: build - - runs-on: ubuntu-latest - env: - NAMESPACE: ${{ secrets.dev_namespace_docker_hub }} - SERVICE_NAME: registration-processor-stage-group-1 - SERVICE_LOCATION: registration-processor/stage-groups/registration-processor-stage-group-1 - - steps: - - uses: actions/checkout@v2 - - uses: actions/download-artifact@v1 - with: - name: release - path: ./ - - - name: Setup branch name - run: | - # Strip git ref prefix from version - echo "BRANCH_NAME=$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')" >> $GITHUB_ENV - - name: Get version info from pom - id: getPomVersion - uses: mavrosxristoforos/get-xml-info@1.0 - with: - xml-file: ./${{ env.SERVICE_LOCATION }}/pom.xml - xpath: /*[local-name()="project"]/*[local-name()="version"] - - - name: Unzip and extract the ${{ env.SERVICE_NAME }} - run: unzip -uj "release.zip" "${{ env.SERVICE_LOCATION }}/target/*" -d "./${{ env.SERVICE_LOCATION }}/target" - - - name: Get current date - id: date - run: echo "::set-output name=date::$(date +'%Y-%m-%d')" - - - name: Build image - run: | - cd "./${{env.SERVICE_LOCATION}}" - docker build . --build-arg SOURCE=mosip --build-arg COMMIT_HASH=$(git rev-parse HEAD) --build-arg COMMIT_ID=$(git rev-parse --short HEAD) --build-arg BUILD_TIME=${{steps.date.outputs.date}} --file Dockerfile --tag ${{ env.SERVICE_NAME }} - - name: Log into registry - run: echo "${{ secrets.release_docker_hub }}" | docker login -u ${{ secrets.actor_docker_hub }} --password-stdin - - - name: Push image - run: | - IMAGE_ID=$NAMESPACE/$SERVICE_NAME - # Change all uppercase to lowercase - IMAGE_ID=$(echo $IMAGE_ID | tr '[A-Z]' '[a-z]') - echo "push version ${{steps.getPomVersion.outputs.info}}" - if [[ $BRANCH_NAME == master ]]; then - VERSION=latest - else - VERSION=$BRANCH_NAME - fi - echo IMAGE_ID=$IMAGE_ID - echo VERSION=$VERSION - docker tag $SERVICE_NAME $IMAGE_ID:$VERSION - docker push $IMAGE_ID:$VERSION - - docker-registration-processor-stage-group-2: - needs: build - - runs-on: ubuntu-latest - env: - NAMESPACE: ${{ secrets.dev_namespace_docker_hub }} - SERVICE_NAME: registration-processor-stage-group-2 - SERVICE_LOCATION: registration-processor/stage-groups/registration-processor-stage-group-2 - - steps: - - uses: actions/checkout@v2 - - uses: actions/download-artifact@v1 - with: - name: release - path: ./ - - - name: Setup branch name - run: | - # Strip git ref prefix from version - echo "BRANCH_NAME=$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')" >> $GITHUB_ENV - - name: Get version info from pom - id: getPomVersion - uses: mavrosxristoforos/get-xml-info@1.0 - with: - xml-file: ./${{ env.SERVICE_LOCATION }}/pom.xml - xpath: /*[local-name()="project"]/*[local-name()="version"] - - - name: Unzip and extract the ${{ env.SERVICE_NAME }} - run: unzip -uj "release.zip" "${{ env.SERVICE_LOCATION }}/target/*" -d "./${{ env.SERVICE_LOCATION }}/target" - - - name: Get current date - id: date - run: echo "::set-output name=date::$(date +'%Y-%m-%d')" - - - name: Build image - run: | - cd "./${{env.SERVICE_LOCATION}}" - docker build . --build-arg SOURCE=mosip --build-arg COMMIT_HASH=$(git rev-parse HEAD) --build-arg COMMIT_ID=$(git rev-parse --short HEAD) --build-arg BUILD_TIME=${{steps.date.outputs.date}} --file Dockerfile --tag ${{ env.SERVICE_NAME }} - - name: Log into registry - run: echo "${{ secrets.release_docker_hub }}" | docker login -u ${{ secrets.actor_docker_hub }} --password-stdin - - - name: Push image - run: | - IMAGE_ID=$NAMESPACE/$SERVICE_NAME - # Change all uppercase to lowercase - IMAGE_ID=$(echo $IMAGE_ID | tr '[A-Z]' '[a-z]') - echo "push version ${{steps.getPomVersion.outputs.info}}" - if [[ $BRANCH_NAME == master ]]; then - VERSION=latest - else - VERSION=$BRANCH_NAME - fi - echo IMAGE_ID=$IMAGE_ID - echo VERSION=$VERSION - docker tag $SERVICE_NAME $IMAGE_ID:$VERSION - docker push $IMAGE_ID:$VERSION - - docker-registration-processor-stage-group-3: - needs: build - - runs-on: ubuntu-latest - env: - NAMESPACE: ${{ secrets.dev_namespace_docker_hub }} - SERVICE_NAME: registration-processor-stage-group-3 - SERVICE_LOCATION: registration-processor/stage-groups/registration-processor-stage-group-3 - - steps: - - uses: actions/checkout@v2 - - uses: actions/download-artifact@v1 - with: - name: release - path: ./ - - - name: Setup branch name - run: | - # Strip git ref prefix from version - echo "BRANCH_NAME=$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')" >> $GITHUB_ENV - - name: Get version info from pom - id: getPomVersion - uses: mavrosxristoforos/get-xml-info@1.0 - with: - xml-file: ./${{ env.SERVICE_LOCATION }}/pom.xml - xpath: /*[local-name()="project"]/*[local-name()="version"] - - - name: Unzip and extract the ${{ env.SERVICE_NAME }} - run: unzip -uj "release.zip" "${{ env.SERVICE_LOCATION }}/target/*" -d "./${{ env.SERVICE_LOCATION }}/target" - - - name: Get current date - id: date - run: echo "::set-output name=date::$(date +'%Y-%m-%d')" - - - name: Build image - run: | - cd "./${{env.SERVICE_LOCATION}}" - docker build . --build-arg SOURCE=mosip --build-arg COMMIT_HASH=$(git rev-parse HEAD) --build-arg COMMIT_ID=$(git rev-parse --short HEAD) --build-arg BUILD_TIME=${{steps.date.outputs.date}} --file Dockerfile --tag ${{ env.SERVICE_NAME }} - - name: Log into registry - run: echo "${{ secrets.release_docker_hub }}" | docker login -u ${{ secrets.actor_docker_hub }} --password-stdin - - - name: Push image - run: | - IMAGE_ID=$NAMESPACE/$SERVICE_NAME - # Change all uppercase to lowercase - IMAGE_ID=$(echo $IMAGE_ID | tr '[A-Z]' '[a-z]') - echo "push version ${{steps.getPomVersion.outputs.info}}" - if [[ $BRANCH_NAME == master ]]; then - VERSION=latest - else - VERSION=$BRANCH_NAME - fi - echo IMAGE_ID=$IMAGE_ID - echo VERSION=$VERSION - docker tag $SERVICE_NAME $IMAGE_ID:$VERSION - docker push $IMAGE_ID:$VERSION - - docker-registration-processor-stage-group-4: - needs: build - - runs-on: ubuntu-latest - env: - NAMESPACE: ${{ secrets.dev_namespace_docker_hub }} - SERVICE_NAME: registration-processor-stage-group-4 - SERVICE_LOCATION: registration-processor/stage-groups/registration-processor-stage-group-4 - - steps: - - uses: actions/checkout@v2 - - uses: actions/download-artifact@v1 - with: - name: release - path: ./ - - - name: Setup branch name - run: | - # Strip git ref prefix from version - echo "BRANCH_NAME=$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')" >> $GITHUB_ENV - - name: Get version info from pom - id: getPomVersion - uses: mavrosxristoforos/get-xml-info@1.0 - with: - xml-file: ./${{ env.SERVICE_LOCATION }}/pom.xml - xpath: /*[local-name()="project"]/*[local-name()="version"] - - - name: Unzip and extract the ${{ env.SERVICE_NAME }} - run: unzip -uj "release.zip" "${{ env.SERVICE_LOCATION }}/target/*" -d "./${{ env.SERVICE_LOCATION }}/target" - - - name: Get current date - id: date - run: echo "::set-output name=date::$(date +'%Y-%m-%d')" - - - name: Build image - run: | - cd "./${{env.SERVICE_LOCATION}}" - docker build . --build-arg SOURCE=mosip --build-arg COMMIT_HASH=$(git rev-parse HEAD) --build-arg COMMIT_ID=$(git rev-parse --short HEAD) --build-arg BUILD_TIME=${{steps.date.outputs.date}} --file Dockerfile --tag ${{ env.SERVICE_NAME }} - - name: Log into registry - run: echo "${{ secrets.release_docker_hub }}" | docker login -u ${{ secrets.actor_docker_hub }} --password-stdin - - - name: Push image - run: | - IMAGE_ID=$NAMESPACE/$SERVICE_NAME - # Change all uppercase to lowercase - IMAGE_ID=$(echo $IMAGE_ID | tr '[A-Z]' '[a-z]') - echo "push version ${{steps.getPomVersion.outputs.info}}" - if [[ $BRANCH_NAME == master ]]; then - VERSION=latest - else - VERSION=$BRANCH_NAME - fi - echo IMAGE_ID=$IMAGE_ID - echo VERSION=$VERSION - docker tag $SERVICE_NAME $IMAGE_ID:$VERSION - docker push $IMAGE_ID:$VERSION - - docker-registration-processor-stage-group-5: - needs: build - - runs-on: ubuntu-latest - env: - NAMESPACE: ${{ secrets.dev_namespace_docker_hub }} - SERVICE_NAME: registration-processor-stage-group-5 - SERVICE_LOCATION: registration-processor/stage-groups/registration-processor-stage-group-5 - - steps: - - uses: actions/checkout@v2 - - uses: actions/download-artifact@v1 - with: - name: release - path: ./ - - - name: Setup branch name - run: | - # Strip git ref prefix from version - echo "BRANCH_NAME=$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')" >> $GITHUB_ENV - - name: Get version info from pom - id: getPomVersion - uses: mavrosxristoforos/get-xml-info@1.0 - with: - xml-file: ./${{ env.SERVICE_LOCATION }}/pom.xml - xpath: /*[local-name()="project"]/*[local-name()="version"] - - - name: Unzip and extract the ${{ env.SERVICE_NAME }} - run: unzip -uj "release.zip" "${{ env.SERVICE_LOCATION }}/target/*" -d "./${{ env.SERVICE_LOCATION }}/target" - - - name: Get current date - id: date - run: echo "::set-output name=date::$(date +'%Y-%m-%d')" - - - name: Build image - run: | - cd "./${{env.SERVICE_LOCATION}}" - docker build . --build-arg SOURCE=mosip --build-arg COMMIT_HASH=$(git rev-parse HEAD) --build-arg COMMIT_ID=$(git rev-parse --short HEAD) --build-arg BUILD_TIME=${{steps.date.outputs.date}} --file Dockerfile --tag ${{ env.SERVICE_NAME }} - - name: Log into registry - run: echo "${{ secrets.release_docker_hub }}" | docker login -u ${{ secrets.actor_docker_hub }} --password-stdin - - - name: Push image - run: | - IMAGE_ID=$NAMESPACE/$SERVICE_NAME - # Change all uppercase to lowercase - IMAGE_ID=$(echo $IMAGE_ID | tr '[A-Z]' '[a-z]') - echo "push version ${{steps.getPomVersion.outputs.info}}" - if [[ $BRANCH_NAME == master ]]; then - VERSION=latest - else - VERSION=$BRANCH_NAME - fi - echo IMAGE_ID=$IMAGE_ID - echo VERSION=$VERSION - docker tag $SERVICE_NAME $IMAGE_ID:$VERSION - docker push $IMAGE_ID:$VERSION - - docker-registration-processor-stage-group-6: - needs: build - - runs-on: ubuntu-latest - env: - NAMESPACE: ${{ secrets.dev_namespace_docker_hub }} - SERVICE_NAME: registration-processor-stage-group-6 - SERVICE_LOCATION: registration-processor/stage-groups/registration-processor-stage-group-6 - - steps: - - uses: actions/checkout@v2 - - uses: actions/download-artifact@v1 - with: - name: release - path: ./ - - - name: Setup branch name - run: | - # Strip git ref prefix from version - echo "BRANCH_NAME=$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')" >> $GITHUB_ENV - - name: Get version info from pom - id: getPomVersion - uses: mavrosxristoforos/get-xml-info@1.0 - with: - xml-file: ./${{ env.SERVICE_LOCATION }}/pom.xml - xpath: /*[local-name()="project"]/*[local-name()="version"] - - - name: Unzip and extract the ${{ env.SERVICE_NAME }} - run: unzip -uj "release.zip" "${{ env.SERVICE_LOCATION }}/target/*" -d "./${{ env.SERVICE_LOCATION }}/target" - - - name: Get current date - id: date - run: echo "::set-output name=date::$(date +'%Y-%m-%d')" - - - name: Build image - run: | - cd "./${{env.SERVICE_LOCATION}}" - docker build . --build-arg SOURCE=mosip --build-arg COMMIT_HASH=$(git rev-parse HEAD) --build-arg COMMIT_ID=$(git rev-parse --short HEAD) --build-arg BUILD_TIME=${{steps.date.outputs.date}} --file Dockerfile --tag ${{ env.SERVICE_NAME }} - - name: Log into registry - run: echo "${{ secrets.release_docker_hub }}" | docker login -u ${{ secrets.actor_docker_hub }} --password-stdin - - - name: Push image - run: | - IMAGE_ID=$NAMESPACE/$SERVICE_NAME - # Change all uppercase to lowercase - IMAGE_ID=$(echo $IMAGE_ID | tr '[A-Z]' '[a-z]') - echo "push version ${{steps.getPomVersion.outputs.info}}" - if [[ $BRANCH_NAME == master ]]; then - VERSION=latest - else - VERSION=$BRANCH_NAME - fi - echo IMAGE_ID=$IMAGE_ID - echo VERSION=$VERSION - docker tag $SERVICE_NAME $IMAGE_ID:$VERSION - docker push $IMAGE_ID:$VERSION - - docker-registration-processor-stage-group-7: - needs: build - - runs-on: ubuntu-latest - env: - NAMESPACE: ${{ secrets.dev_namespace_docker_hub }} - SERVICE_NAME: registration-processor-stage-group-7 - SERVICE_LOCATION: registration-processor/stage-groups/registration-processor-stage-group-7 - - steps: - - uses: actions/checkout@v2 - - uses: actions/download-artifact@v1 - with: - name: release - path: ./ - - - name: Setup branch name - run: | - # Strip git ref prefix from version - echo "BRANCH_NAME=$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')" >> $GITHUB_ENV - - name: Get version info from pom - id: getPomVersion - uses: mavrosxristoforos/get-xml-info@1.0 - with: - xml-file: ./${{ env.SERVICE_LOCATION }}/pom.xml - xpath: /*[local-name()="project"]/*[local-name()="version"] - - - name: Unzip and extract the ${{ env.SERVICE_NAME }} - run: unzip -uj "release.zip" "${{ env.SERVICE_LOCATION }}/target/*" -d "./${{ env.SERVICE_LOCATION }}/target" - - - name: Get current date - id: date - run: echo "::set-output name=date::$(date +'%Y-%m-%d')" - - - name: Build image - run: | - cd "./${{env.SERVICE_LOCATION}}" - docker build . --build-arg SOURCE=mosip --build-arg COMMIT_HASH=$(git rev-parse HEAD) --build-arg COMMIT_ID=$(git rev-parse --short HEAD) --build-arg BUILD_TIME=${{steps.date.outputs.date}} --file Dockerfile --tag ${{ env.SERVICE_NAME }} - - name: Log into registry - run: echo "${{ secrets.release_docker_hub }}" | docker login -u ${{ secrets.actor_docker_hub }} --password-stdin - - - name: Push image - run: | - IMAGE_ID=$NAMESPACE/$SERVICE_NAME - # Change all uppercase to lowercase - IMAGE_ID=$(echo $IMAGE_ID | tr '[A-Z]' '[a-z]') - echo "push version ${{steps.getPomVersion.outputs.info}}" - if [[ $BRANCH_NAME == master ]]; then - VERSION=latest - else - VERSION=$BRANCH_NAME - fi - echo IMAGE_ID=$IMAGE_ID - echo VERSION=$VERSION - docker tag $SERVICE_NAME $IMAGE_ID:$VERSION - docker push $IMAGE_ID:$VERSION - - docker-registration-processor-abis: - needs: build - - runs-on: ubuntu-latest - env: - NAMESPACE: ${{ secrets.dev_namespace_docker_hub }} - SERVICE_NAME: registration-processor-abis - SERVICE_LOCATION: registration-processor/core-processor/registration-processor-abis - - steps: - - uses: actions/checkout@v2 - - uses: actions/download-artifact@v1 - with: - name: release - path: ./ - - - name: Setup branch name - run: | - # Strip git ref prefix from version - echo "BRANCH_NAME=$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')" >> $GITHUB_ENV - - name: Get version info from pom - id: getPomVersion - uses: mavrosxristoforos/get-xml-info@1.0 - with: - xml-file: ./${{ env.SERVICE_LOCATION }}/pom.xml - xpath: /*[local-name()="project"]/*[local-name()="version"] - - - name: Unzip and extract the ${{ env.SERVICE_NAME }} - run: unzip -uj "release.zip" "${{ env.SERVICE_LOCATION }}/target/*" -d "./${{ env.SERVICE_LOCATION }}/target" - - - name: Get current date - id: date - run: echo "::set-output name=date::$(date +'%Y-%m-%d')" - - - name: Build image - run: | - cd "./${{env.SERVICE_LOCATION}}" - docker build . --build-arg SOURCE=mosip --build-arg COMMIT_HASH=$(git rev-parse HEAD) --build-arg COMMIT_ID=$(git rev-parse --short HEAD) --build-arg BUILD_TIME=${{steps.date.outputs.date}} --file Dockerfile --tag ${{ env.SERVICE_NAME }} - - name: Log into registry - run: echo "${{ secrets.release_docker_hub }}" | docker login -u ${{ secrets.actor_docker_hub }} --password-stdin - - - name: Push image - run: | - IMAGE_ID=$NAMESPACE/$SERVICE_NAME - - # Change all uppercase to lowercase - IMAGE_ID=$(echo $IMAGE_ID | tr '[A-Z]' '[a-z]') - echo "push version ${{steps.getPomVersion.outputs.info}}" - if [[ $BRANCH_NAME == master ]]; then - VERSION=latest - else - VERSION=$BRANCH_NAME - fi - echo IMAGE_ID=$IMAGE_ID - echo VERSION=$VERSION - docker tag $SERVICE_NAME $IMAGE_ID:$VERSION - docker push $IMAGE_ID:$VERSION - - docker-registration-processor-reprocessor: - needs: build - - runs-on: ubuntu-latest - env: - NAMESPACE: ${{ secrets.dev_namespace_docker_hub }} - SERVICE_NAME: registration-processor-reprocessor - SERVICE_LOCATION: registration-processor/workflow-engine/registration-processor-reprocessor - - steps: - - uses: actions/checkout@v2 - - uses: actions/download-artifact@v1 - with: - name: release - path: ./ - - - name: Setup branch name - run: | - # Strip git ref prefix from version - echo "BRANCH_NAME=$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')" >> $GITHUB_ENV - - name: Get version info from pom - id: getPomVersion - uses: mavrosxristoforos/get-xml-info@1.0 - with: - xml-file: ./${{ env.SERVICE_LOCATION }}/pom.xml - xpath: /*[local-name()="project"]/*[local-name()="version"] - - - name: Unzip and extract the ${{ env.SERVICE_NAME }} - run: unzip -uj "release.zip" "${{ env.SERVICE_LOCATION }}/target/*" -d "./${{ env.SERVICE_LOCATION }}/target" - - - name: Get current date - id: date - run: echo "::set-output name=date::$(date +'%Y-%m-%d')" - - - name: Build image - run: | - cd "./${{env.SERVICE_LOCATION}}" - docker build . --build-arg SOURCE=mosip --build-arg COMMIT_HASH=$(git rev-parse HEAD) --build-arg COMMIT_ID=$(git rev-parse --short HEAD) --build-arg BUILD_TIME=${{steps.date.outputs.date}} --file Dockerfile --tag ${{ env.SERVICE_NAME }} - - name: Log into registry - run: echo "${{ secrets.release_docker_hub }}" | docker login -u ${{ secrets.actor_docker_hub }} --password-stdin - - - name: Push image - run: | - IMAGE_ID=$NAMESPACE/$SERVICE_NAME - - # Change all uppercase to lowercase - IMAGE_ID=$(echo $IMAGE_ID | tr '[A-Z]' '[a-z]') - echo "push version ${{steps.getPomVersion.outputs.info}}" - if [[ $BRANCH_NAME == master ]]; then - VERSION=latest - else - VERSION=$BRANCH_NAME - fi - echo IMAGE_ID=$IMAGE_ID - echo VERSION=$VERSION - docker tag $SERVICE_NAME $IMAGE_ID:$VERSION - docker push $IMAGE_ID:$VERSION - docker-registration-processor-dmz-packet-server: - needs: build - - runs-on: ubuntu-latest - env: - NAMESPACE: ${{ secrets.dev_namespace_docker_hub }} - SERVICE_NAME: registration-processor-dmz-packet-server - SERVICE_LOCATION: registration-processor/init/registration-processor-dmz-packet-server - - steps: - - uses: actions/checkout@v2 - - - name: Setup branch name - run: | - # Strip git ref prefix from version - echo "BRANCH_NAME=$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')" >> $GITHUB_ENV - - name: Get version info - id: getVersion - uses: mavrosxristoforos/get-xml-info@1.0 - with: - xml-file: ./${{ env.SERVICE_LOCATION }}/version.xml - xpath: version - - - name: Get current date - id: date - run: echo "::set-output name=date::$(date +'%Y-%m-%d')" - - - name: Build image - run: | - cd "./${{env.SERVICE_LOCATION}}" - docker build . --build-arg SOURCE=mosip --build-arg COMMIT_HASH=$(git rev-parse HEAD) --build-arg COMMIT_ID=$(git rev-parse --short HEAD) --build-arg BUILD_TIME=${{steps.date.outputs.date}} --file Dockerfile --tag ${{ env.SERVICE_NAME }} - - name: Log into registry - run: echo "${{ secrets.release_docker_hub }}" | docker login -u ${{ secrets.actor_docker_hub }} --password-stdin - - - name: Push image - run: | - IMAGE_ID=$NAMESPACE/$SERVICE_NAME - - # Change all uppercase to lowercase - IMAGE_ID=$(echo $IMAGE_ID | tr '[A-Z]' '[a-z]') - echo "push version ${{steps.getVersion.outputs.info}}" - VERSION=${{steps.getVersion.outputs.info}} - echo IMAGE_ID=$IMAGE_ID - echo VERSION=$VERSION - docker tag $SERVICE_NAME $IMAGE_ID:$VERSION - docker push $IMAGE_ID:$VERSION - docker-registration-processor-registration-status-service: - needs: build - - runs-on: ubuntu-latest - env: - NAMESPACE: ${{ secrets.dev_namespace_docker_hub }} - SERVICE_NAME: registration-processor-registration-status-service - SERVICE_LOCATION: registration-processor/init/registration-processor-registration-status-service - - steps: - - uses: actions/checkout@v2 - - uses: actions/download-artifact@v1 - with: - name: release - path: ./ - - - name: Setup branch name - run: | - # Strip git ref prefix from version - echo "BRANCH_NAME=$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')" >> $GITHUB_ENV - - name: Get version info from pom - id: getPomVersion - uses: mavrosxristoforos/get-xml-info@1.0 - with: - xml-file: ./${{ env.SERVICE_LOCATION }}/pom.xml - xpath: /*[local-name()="project"]/*[local-name()="version"] - - - name: Unzip and extract the ${{ env.SERVICE_NAME }} - run: unzip -uj "release.zip" "${{ env.SERVICE_LOCATION }}/target/*" -d "./${{ env.SERVICE_LOCATION }}/target" - - - name: Get current date - id: date - run: echo "::set-output name=date::$(date +'%Y-%m-%d')" - - - name: Build image - run: | - cd "./${{env.SERVICE_LOCATION}}" - docker build . --build-arg SOURCE=mosip --build-arg COMMIT_HASH=$(git rev-parse HEAD) --build-arg COMMIT_ID=$(git rev-parse --short HEAD) --build-arg BUILD_TIME=${{steps.date.outputs.date}} --file Dockerfile --tag ${{ env.SERVICE_NAME }} - - name: Log into registry - run: echo "${{ secrets.release_docker_hub }}" | docker login -u ${{ secrets.actor_docker_hub }} --password-stdin - - - name: Push image - run: | - IMAGE_ID=$NAMESPACE/$SERVICE_NAME - - # Change all uppercase to lowercase - IMAGE_ID=$(echo $IMAGE_ID | tr '[A-Z]' '[a-z]') - echo "push version ${{steps.getPomVersion.outputs.info}}" - if [[ $BRANCH_NAME == master ]]; then - VERSION=latest - else - VERSION=$BRANCH_NAME - fi - echo IMAGE_ID=$IMAGE_ID - echo VERSION=$VERSION - docker tag $SERVICE_NAME $IMAGE_ID:$VERSION - docker push $IMAGE_ID:$VERSION - docker-registration-processor-notification-service: - needs: build - - runs-on: ubuntu-latest - env: - NAMESPACE: ${{ secrets.dev_namespace_docker_hub }} - SERVICE_NAME: registration-processor-notification-service - SERVICE_LOCATION: registration-processor/registration-processor-notification-service - - steps: - - uses: actions/checkout@v2 - - uses: actions/download-artifact@v1 - with: - name: release - path: ./ - - - name: Setup branch name - run: | - # Strip git ref prefix from version - echo "BRANCH_NAME=$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')" >> $GITHUB_ENV - - name: Get version info from pom - id: getPomVersion - uses: mavrosxristoforos/get-xml-info@1.0 - with: - xml-file: ./${{ env.SERVICE_LOCATION }}/pom.xml - xpath: /*[local-name()="project"]/*[local-name()="version"] - - - name: Unzip and extract the ${{ env.SERVICE_NAME }} - run: unzip -uj "release.zip" "${{ env.SERVICE_LOCATION }}/target/*" -d "./${{ env.SERVICE_LOCATION }}/target" - - - name: Get current date - id: date - run: echo "::set-output name=date::$(date +'%Y-%m-%d')" - - - name: Build image - run: | - cd "./${{env.SERVICE_LOCATION}}" - docker build . --build-arg SOURCE=mosip --build-arg COMMIT_HASH=$(git rev-parse HEAD) --build-arg COMMIT_ID=$(git rev-parse --short HEAD) --build-arg BUILD_TIME=${{steps.date.outputs.date}} --file Dockerfile --tag ${{ env.SERVICE_NAME }} - - name: Log into registry - run: echo "${{ secrets.release_docker_hub }}" | docker login -u ${{ secrets.actor_docker_hub }} --password-stdin - - - name: Push image - run: | - IMAGE_ID=$NAMESPACE/$SERVICE_NAME - # Change all uppercase to lowercase - IMAGE_ID=$(echo $IMAGE_ID | tr '[A-Z]' '[a-z]') - echo "push version ${{steps.getPomVersion.outputs.info}}" - if [[ $BRANCH_NAME == master ]]; then - VERSION=latest - else - VERSION=$BRANCH_NAME - fi - echo IMAGE_ID=$IMAGE_ID - echo VERSION=$VERSION - docker tag $SERVICE_NAME $IMAGE_ID:$VERSION - docker push $IMAGE_ID:$VERSION - docker-registration-processor-landing-zone: - needs: build - - runs-on: ubuntu-latest - env: - NAMESPACE: ${{ secrets.dev_namespace_docker_hub }} - SERVICE_NAME: registration-processor-landing-zone - SERVICE_LOCATION: registration-processor/registration-processor-landing-zone - - steps: - - uses: actions/checkout@v2 - - uses: actions/download-artifact@v1 - with: - name: release - path: ./ - - - name: Setup branch name - run: | - # Strip git ref prefix from version - echo "BRANCH_NAME=$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')" >> $GITHUB_ENV - - name: Get version info from pom - id: getPomVersion - uses: mavrosxristoforos/get-xml-info@1.0 - with: - xml-file: ./${{ env.SERVICE_LOCATION }}/pom.xml - xpath: /*[local-name()="project"]/*[local-name()="version"] - - - name: Unzip and extract the ${{ env.SERVICE_NAME }} - run: unzip -uj "release.zip" "${{ env.SERVICE_LOCATION }}/target/*" -d "./${{ env.SERVICE_LOCATION }}/target" - - - name: Get current date - id: date - run: echo "::set-output name=date::$(date +'%Y-%m-%d')" - - - name: Build image - run: | - cd "./${{env.SERVICE_LOCATION}}" - docker build . --build-arg SOURCE=mosip --build-arg COMMIT_HASH=$(git rev-parse HEAD) --build-arg COMMIT_ID=$(git rev-parse --short HEAD) --build-arg BUILD_TIME=${{steps.date.outputs.date}} --file Dockerfile --tag ${{ env.SERVICE_NAME }} - - name: Log into registry - run: echo "${{ secrets.release_docker_hub }}" | docker login -u ${{ secrets.actor_docker_hub }} --password-stdin - - - name: Push image - run: | - IMAGE_ID=$NAMESPACE/$SERVICE_NAME - # Change all uppercase to lowercase - IMAGE_ID=$(echo $IMAGE_ID | tr '[A-Z]' '[a-z]') - echo "push version ${{steps.getPomVersion.outputs.info}}" - if [[ $BRANCH_NAME == master ]]; then - VERSION=latest - else - VERSION=$BRANCH_NAME - fi - echo IMAGE_ID=$IMAGE_ID - echo VERSION=$VERSION - docker tag $SERVICE_NAME $IMAGE_ID:$VERSION - docker push $IMAGE_ID:$VERSION - - docker-registration-processor-workflow-manager-service: - needs: build - - runs-on: ubuntu-latest - env: - NAMESPACE: ${{ secrets.dev_namespace_docker_hub }} - SERVICE_NAME: registration-processor-workflow-manager-service - SERVICE_LOCATION: registration-processor/workflow-engine/registration-processor-workflow-manager-service - - steps: - - uses: actions/checkout@v2 - - uses: actions/download-artifact@v1 - with: - name: release - path: ./ - - - name: Setup branch name - run: | - # Strip git ref prefix from version - echo "BRANCH_NAME=$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')" >> $GITHUB_ENV - - name: Get version info from pom - id: getPomVersion - uses: mavrosxristoforos/get-xml-info@1.0 - with: - xml-file: ./${{ env.SERVICE_LOCATION }}/pom.xml - xpath: /*[local-name()="project"]/*[local-name()="version"] - - - name: Unzip and extract the ${{ env.SERVICE_NAME }} - run: unzip -uj "release.zip" "${{ env.SERVICE_LOCATION }}/target/*" -d "./${{ env.SERVICE_LOCATION }}/target" - - - name: Get current date - id: date - run: echo "::set-output name=date::$(date +'%Y-%m-%d')" - - - name: Build image - run: | - cd "./${{env.SERVICE_LOCATION}}" - docker build . --build-arg SOURCE=mosip --build-arg COMMIT_HASH=$(git rev-parse HEAD) --build-arg COMMIT_ID=$(git rev-parse --short HEAD) --build-arg BUILD_TIME=${{steps.date.outputs.date}} --file Dockerfile --tag ${{ env.SERVICE_NAME }} - - name: Log into registry - run: echo "${{ secrets.release_docker_hub }}" | docker login -u ${{ secrets.actor_docker_hub }} --password-stdin - - - name: Push image - run: | - IMAGE_ID=$NAMESPACE/$SERVICE_NAME - # Change all uppercase to lowercase - IMAGE_ID=$(echo $IMAGE_ID | tr '[A-Z]' '[a-z]') - echo "push version ${{steps.getPomVersion.outputs.info}}" - if [[ $BRANCH_NAME == master ]]; then - VERSION=latest - else - VERSION=$BRANCH_NAME - fi - echo IMAGE_ID=$IMAGE_ID - echo VERSION=$VERSION - docker tag $SERVICE_NAME $IMAGE_ID:$VERSION - docker push $IMAGE_ID:$VERSION - registration-processor-common-camel-bridge: - needs: build - - runs-on: ubuntu-latest - env: - NAMESPACE: ${{ secrets.dev_namespace_docker_hub }} - SERVICE_NAME: registration-processor-common-camel-bridge - SERVICE_LOCATION: registration-processor/registration-processor-common-camel-bridge - - steps: - - uses: actions/checkout@v2 - - uses: actions/download-artifact@v1 - with: - name: release - path: ./ - - - name: Setup branch name - run: | - # Strip git ref prefix from version - echo "BRANCH_NAME=$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')" >> $GITHUB_ENV - - name: Get version info from pom - id: getPomVersion - uses: mavrosxristoforos/get-xml-info@1.0 - with: - xml-file: ./${{ env.SERVICE_LOCATION }}/pom.xml - xpath: /*[local-name()="project"]/*[local-name()="version"] - - - name: Unzip and extract the ${{ env.SERVICE_NAME }} - run: unzip -uj "release.zip" "${{ env.SERVICE_LOCATION }}/target/*" -d "./${{ env.SERVICE_LOCATION }}/target" - - - name: Get current date - id: date - run: echo "::set-output name=date::$(date +'%Y-%m-%d')" - - - name: Build image - run: | - cd "./${{env.SERVICE_LOCATION}}" - docker build . --build-arg SOURCE=mosip --build-arg COMMIT_HASH=$(git rev-parse HEAD) --build-arg COMMIT_ID=$(git rev-parse --short HEAD) --build-arg BUILD_TIME=${{steps.date.outputs.date}} --file Dockerfile --tag ${{ env.SERVICE_NAME }} - - name: Log into registry - run: echo "${{ secrets.release_docker_hub }}" | docker login -u ${{ secrets.actor_docker_hub }} --password-stdin - - - name: Push image - run: | - IMAGE_ID=$NAMESPACE/$SERVICE_NAME - - # Change all uppercase to lowercase - IMAGE_ID=$(echo $IMAGE_ID | tr '[A-Z]' '[a-z]') - echo "push version ${{steps.getPomVersion.outputs.info}}" - if [[ $BRANCH_NAME == master ]]; then - VERSION=latest - else - VERSION=$BRANCH_NAME - fi - echo IMAGE_ID=$IMAGE_ID - echo VERSION=$VERSION - docker tag $SERVICE_NAME $IMAGE_ID:$VERSION - docker push $IMAGE_ID:$VERSION - - sonar_analysis: - runs-on: ubuntu-latest - env: - NAMESPACE: ${{ secrets.dev_namespace_docker_hub }} - SERVICE_NAME: registration-client - SERVICE_LOCATION: registration - steps: - - uses: actions/checkout@v2 - - name: Set up JDK 11 - uses: actions/setup-java@v1 - with: - ref: ${{ github.ref }} - java-version: 11 - server-id: ossrh # Value of the distributionManagement/repository/id field of the pom.xml - settings-path: ${{ github.workspace }} # location for the settings.xml file - - - name: Setup branch and env - run: | - # Strip git ref prefix from version - echo "BRANCH_NAME=$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')" >> $GITHUB_ENV - echo "GPG_TTY=$(tty)" >> $GITHUB_ENV - - - uses: actions/cache@v1 - with: - path: ~/.m2/repository - key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }} - restore-keys: | - ${{ runner.os }}-maven-${{ env.BRANCH_NAME }} - - name: Setup the settings file for ossrh server - run: echo " ossrh ${{secrets.ossrh_user}} ${{secrets.ossrh_secret}} ossrh true gpg2 ${{secrets.gpg_secret}} allow-snapshots true snapshots-repo https://oss.sonatype.org/content/repositories/snapshots false true releases-repo https://oss.sonatype.org/service/local/staging/deploy/maven2 true false staged-releases https://oss.sonatype.org/service/local/staging/deploy/maven2/ sonar . https://sonarcloud.io false " > $GITHUB_WORKSPACE/settings.xml - - - name: Install xmllint - run: | - sudo apt-get update - sudo apt-get install libxml2-utils - - - name: Analyze with SonarCloud - run: | - cd registration-processor - mvn -B -Dgpg.skip verify sonar:sonar -Dsonar.projectKey=mosip_${{ github.event.repository.name }} -Dsonar.organization=${{ secrets.ORG_KEY }} -Dsonar.host.url=https://sonarcloud.io -Dsonar.login=${{ secrets.SONAR_TOKEN }} - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} - - - uses: 8398a7/action-slack@v3 - with: - status: ${{ job.status }} - fields: repo,message,author,ref,job # selectable (default: repo,message) - env: - SLACK_WEBHOOK_URL: ${{ secrets.SLACK_DEVOPS_WEBHOOK }} # required - if: failure() # Pick up events even if the job fails or is canceled. diff --git a/.github/workflows/release-changes.yml b/.github/workflows/release-changes.yml new file mode 100644 index 00000000000..2579ea836f1 --- /dev/null +++ b/.github/workflows/release-changes.yml @@ -0,0 +1,26 @@ +name: Release/pre-release Preparation. + +on: + workflow_dispatch: + inputs: + MESSAGE: + description: 'Triggered for release or pe-release' + required: false + default: 'Release Preparation' + RELEASE_TAG: + description: 'tag to update' + required: true + SNAPSHOT_TAG: + description: 'tag to be replaced' + required: true + BASE: + description: 'base branch for PR' + required: true +jobs: + maven-release-preparation: + uses: mosip/kattu/.github/workflows/release-changes.yml@master + with: + MESSAGE: ${{ inputs.MESSAGE }} + RELEASE_TAG: ${{ inputs.RELEASE_TAG }} + SNAPSHOT_TAG: ${{ inputs.SNAPSHOT_TAG }} + BASE: ${{ inputs.BASE }} \ No newline at end of file diff --git a/.github/workflows/release_changes.yml b/.github/workflows/release_changes.yml deleted file mode 100644 index 5d8e1a32989..00000000000 --- a/.github/workflows/release_changes.yml +++ /dev/null @@ -1,61 +0,0 @@ -name: Release/pre-release Preparation. - -on: - workflow_dispatch: - inputs: - message: - description: 'Triggered for release or pe-release' - required: false - default: 'Release Preparation' - releaseTags: - description: 'tag to update' - required: true - snapshotTags: - description: 'tag to be replaced' - required: true - base: - description: 'base branch for PR' - required: true -jobs: - build: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v2 - - name: Setup branch and env - run: | - # Strip git ref prefix from version - echo "BRANCH_NAME=$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')" >> $GITHUB_ENV - echo "GPG_TTY=$(tty)" >> $GITHUB_ENV - - - name: update Branch name in badges - run: | - sed -i 's/branch=.*)]/branch=${{ env.BRANCH_NAME }}\)]/g' README.md - sed -i 's/branch=.*\&/branch=${{ env.BRANCH_NAME }}\&/g' README.md - - - name: Mannualy changing the pom versions - run: find . -type f -name "*pom.xml" -print0 | xargs -0 sed -i "s/${{ github.event.inputs.snapshotTags }}/${{ github.event.inputs.releaseTags }}/g" - - - name: Updating the Release URL in POM - run: | - cd .github/workflows - sed -i 's/OSSRH_SNAPSHOT_URL/RELEASE_URL/g' push_trigger.yml - - - name: Updating libs-snapshot-local to libs-release local for artifactory URL's. - run: find . -type f -name "*Dockerfile" -print0 | xargs -0 sed -i "s/libs-snapshot-local/libs-release-local/g" - - - name: removing -DskipTests - run: find . -type f -name "*push_trigger.yml" -print0 | xargs -0 sed -i "s/"-DskipTests"//g" - -# - name: removing --Dgpg.skip -# run: find . -type f -name "*push_trigger.yml" -print0 | xargs -0 sed -i "s/"-Dgpg.skip"//g" - - - name: Create Pull Request - uses: peter-evans/create-pull-request@v3 - with: - token: ${{ secrets.ACTION_PAT }} - commit-message: Release Bot Pre-release changes - title: Release changes - body: Automated PR for ${{ github.event.inputs.releaseTags }} release. - branch: release-branch - delete-branch: true - base: ${{ github.event.inputs.base }} diff --git a/.github/workflows/release_trigger.yml b/.github/workflows/release_trigger.yml deleted file mode 100644 index 08bef64e9a0..00000000000 --- a/.github/workflows/release_trigger.yml +++ /dev/null @@ -1,739 +0,0 @@ - -name: Release maven packages and docker upon a release - -on: - release: - types: [published] - -jobs: - build: - - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v2 - - name: Set up JDK 11 - uses: actions/setup-java@v1 - with: - ref: ${{ github.ref }} - java-version: 11 - server-id: ossrh # Value of the distributionManagement/repository/id field of the pom.xml - settings-path: ${{ github.workspace }} # location for the settings.xml file - - - name: Setup branch and GPG public key - run: | - # Strip git ref prefix from version - echo "::set-env name=BRANCH_NAME::$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')" - echo ${{ env.BRANCH_NAME }} - echo "::set-env name=GPG_TTY::$(tty)" - echo ${{ env.GPG_TTY }} - sudo apt-get --yes install gnupg2 - gpg2 --import ./.github/keys/mosipgpgkey_pub.gpg - gpg2 --quiet --batch --passphrase=${{secrets.gpg_secret}} --allow-secret-key-import --import ./.github/keys/mosipgpgkey_sec.gpg - - - uses: actions/cache@v1 - with: - path: ~/.m2/repository - key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }} - restore-keys: | - ${{ runner.os }}-maven-${{ env.BRANCH_NAME }} - - - name: Setup the settings file for ossrh server - run: echo " ossrh ${{secrets.ossrh_user}} ${{secrets.ossrh_secret}} ossrh true gpg2 ${{secrets.gpg_secret}} allow-snapshots true snapshots-repo https://oss.sonatype.org/content/repositories/snapshots false true releases-repo https://oss.sonatype.org/service/local/staging/deploy/maven2 true false sonar . https://sonarcloud.io false " > $GITHUB_WORKSPACE/settings.xml - - - name: Build with Maven - run: | - cd registration-processor - mvn -B package -s $GITHUB_WORKSPACE/settings.xml --file pom.xml - - - name: Ready the springboot artifacts - run: find -name '*.jar' -executable -type f -exec zip release.zip {} + - - - - name: Upload the springboot jars - uses: actions/upload-artifact@v1 - with: - name: release - path: ./release.zip - - - name: Build registration-processor-stage-group-1 image - run: | - # The Mosip Stage Executor is not packaged as part of release.zip - cd "./$SERVICE_LOCATION" - docker build . --file Dockerfile --tag $SERVICE_NAME - env: - SERVICE_NAME: registration-processor-stage-group-1 - SERVICE_LOCATION: registration-processor/stage-groups/registration-processor-stage-group-1 - - name: Log into registry - run: echo "${{ secrets.release_docker_hub }}" | docker login -u ${{ secrets.actor_docker_hub }} --password-stdin - - - name: Push image - run: | - IMAGE_ID=$NAMESPACE/$SERVICE_NAME - - # Change all uppercase to lowercase - IMAGE_ID=$(echo $IMAGE_ID | tr '[A-Z]' '[a-z]') - VERSION=$BRANCH_NAME - echo IMAGE_ID=$IMAGE_ID - echo VERSION=$VERSION - docker tag $SERVICE_NAME $IMAGE_ID:$VERSION - docker push $IMAGE_ID:$VERSION - env: - NAMESPACE: ${{ secrets.dev_namespace_docker_hub }} - SERVICE_NAME: registration-processor-stage-group-1 - SERVICE_LOCATION: registration-processor/stage-groups/registration-processor-stage-group-1 - - - name: Build registration-processor-stage-group-2 image - run: | - # The Mosip Stage Executor is not packaged as part of release.zip - cd "./$SERVICE_LOCATION" - docker build . --file Dockerfile --tag $SERVICE_NAME - env: - SERVICE_NAME: registration-processor-stage-group-2 - SERVICE_LOCATION: registration-processor/stage-groups/registration-processor-stage-group-2 - - name: Log into registry - run: echo "${{ secrets.release_docker_hub }}" | docker login -u ${{ secrets.actor_docker_hub }} --password-stdin - - - name: Push image - run: | - IMAGE_ID=$NAMESPACE/$SERVICE_NAME - - # Change all uppercase to lowercase - IMAGE_ID=$(echo $IMAGE_ID | tr '[A-Z]' '[a-z]') - VERSION=$BRANCH_NAME - echo IMAGE_ID=$IMAGE_ID - echo VERSION=$VERSION - docker tag $SERVICE_NAME $IMAGE_ID:$VERSION - docker push $IMAGE_ID:$VERSION - env: - NAMESPACE: ${{ secrets.dev_namespace_docker_hub }} - SERVICE_NAME: registration-processor-stage-group-2 - SERVICE_LOCATION: registration-processor/stage-groups/registration-processor-stage-group-2 - - - name: Build registration-processor-stage-group-3 image - run: | - # The Mosip Stage Executor is not packaged as part of release.zip - cd "./$SERVICE_LOCATION" - docker build . --file Dockerfile --tag $SERVICE_NAME - env: - SERVICE_NAME: registration-processor-stage-group-3 - SERVICE_LOCATION: registration-processor/stage-groups/registration-processor-stage-group-3 - - name: Log into registry - run: echo "${{ secrets.release_docker_hub }}" | docker login -u ${{ secrets.actor_docker_hub }} --password-stdin - - - name: Push image - run: | - IMAGE_ID=$NAMESPACE/$SERVICE_NAME - - # Change all uppercase to lowercase - IMAGE_ID=$(echo $IMAGE_ID | tr '[A-Z]' '[a-z]') - VERSION=$BRANCH_NAME - echo IMAGE_ID=$IMAGE_ID - echo VERSION=$VERSION - docker tag $SERVICE_NAME $IMAGE_ID:$VERSION - docker push $IMAGE_ID:$VERSION - env: - NAMESPACE: ${{ secrets.dev_namespace_docker_hub }} - SERVICE_NAME: registration-processor-stage-group-3 - SERVICE_LOCATION: registration-processor/stage-groups/registration-processor-stage-group-3 - - - name: Build registration-processor-stage-group-4 image - run: | - # The Mosip Stage Executor is not packaged as part of release.zip - cd "./$SERVICE_LOCATION" - docker build . --file Dockerfile --tag $SERVICE_NAME - env: - SERVICE_NAME: registration-processor-stage-group-4 - SERVICE_LOCATION: registration-processor/stage-groups/registration-processor-stage-group-4 - - name: Log into registry - run: echo "${{ secrets.release_docker_hub }}" | docker login -u ${{ secrets.actor_docker_hub }} --password-stdin - - - name: Push image - run: | - IMAGE_ID=$NAMESPACE/$SERVICE_NAME - - # Change all uppercase to lowercase - IMAGE_ID=$(echo $IMAGE_ID | tr '[A-Z]' '[a-z]') - VERSION=$BRANCH_NAME - echo IMAGE_ID=$IMAGE_ID - echo VERSION=$VERSION - docker tag $SERVICE_NAME $IMAGE_ID:$VERSION - docker push $IMAGE_ID:$VERSION - env: - NAMESPACE: ${{ secrets.dev_namespace_docker_hub }} - SERVICE_NAME: registration-processor-stage-group-4 - SERVICE_LOCATION: registration-processor/stage-groups/registration-processor-stage-group-4 - - - name: Build registration-processor-stage-group-5 image - run: | - # The Mosip Stage Executor is not packaged as part of release.zip - cd "./$SERVICE_LOCATION" - docker build . --file Dockerfile --tag $SERVICE_NAME - env: - SERVICE_NAME: registration-processor-stage-group-5 - SERVICE_LOCATION: registration-processor/stage-groups/registration-processor-stage-group-5 - - name: Log into registry - run: echo "${{ secrets.release_docker_hub }}" | docker login -u ${{ secrets.actor_docker_hub }} --password-stdin - - - name: Push image - run: | - IMAGE_ID=$NAMESPACE/$SERVICE_NAME - - # Change all uppercase to lowercase - IMAGE_ID=$(echo $IMAGE_ID | tr '[A-Z]' '[a-z]') - VERSION=$BRANCH_NAME - echo IMAGE_ID=$IMAGE_ID - echo VERSION=$VERSION - docker tag $SERVICE_NAME $IMAGE_ID:$VERSION - docker push $IMAGE_ID:$VERSION - env: - NAMESPACE: ${{ secrets.dev_namespace_docker_hub }} - SERVICE_NAME: registration-processor-stage-group-5 - SERVICE_LOCATION: registration-processor/stage-groups/registration-processor-stage-group-5 - - - name: Build registration-processor-stage-group-6 image - run: | - # The Mosip Stage Executor is not packaged as part of release.zip - cd "./$SERVICE_LOCATION" - docker build . --file Dockerfile --tag $SERVICE_NAME - env: - SERVICE_NAME: registration-processor-stage-group-6 - SERVICE_LOCATION: registration-processor/stage-groups/registration-processor-stage-group-6 - - name: Log into registry - run: echo "${{ secrets.release_docker_hub }}" | docker login -u ${{ secrets.actor_docker_hub }} --password-stdin - - - name: Push image - run: | - IMAGE_ID=$NAMESPACE/$SERVICE_NAME - - # Change all uppercase to lowercase - IMAGE_ID=$(echo $IMAGE_ID | tr '[A-Z]' '[a-z]') - VERSION=$BRANCH_NAME - echo IMAGE_ID=$IMAGE_ID - echo VERSION=$VERSION - docker tag $SERVICE_NAME $IMAGE_ID:$VERSION - docker push $IMAGE_ID:$VERSION - env: - NAMESPACE: ${{ secrets.dev_namespace_docker_hub }} - SERVICE_NAME: registration-processor-stage-group-6 - SERVICE_LOCATION: registration-processor/stage-groups/registration-processor-stage-group-6 - - - - name: Build registration-processor-stage-group-7 image - run: | - # The Mosip Stage Executor is not packaged as part of release.zip - cd "./$SERVICE_LOCATION" - docker build . --file Dockerfile --tag $SERVICE_NAME - env: - SERVICE_NAME: registration-processor-stage-group-7 - SERVICE_LOCATION: registration-processor/stage-groups/registration-processor-stage-group-7 - - name: Log into registry - run: echo "${{ secrets.release_docker_hub }}" | docker login -u ${{ secrets.actor_docker_hub }} --password-stdin - - - name: Push image - run: | - IMAGE_ID=$NAMESPACE/$SERVICE_NAME - - # Change all uppercase to lowercase - IMAGE_ID=$(echo $IMAGE_ID | tr '[A-Z]' '[a-z]') - VERSION=$BRANCH_NAME - echo IMAGE_ID=$IMAGE_ID - echo VERSION=$VERSION - docker tag $SERVICE_NAME $IMAGE_ID:$VERSION - docker push $IMAGE_ID:$VERSION - env: - NAMESPACE: ${{ secrets.dev_namespace_docker_hub }} - SERVICE_NAME: registration-processor-stage-group-7 - SERVICE_LOCATION: registration-processor/stage-groups/registration-processor-stage-group-7 - - - - - name: Build camel bridge image - run: | - # The camel bridge is not packaged as part of release.zip - cd "./registration-processor/registration-processor-common-camel-bridge" - docker build . --file Dockerfile --tag registration-processor-common-camel-bridge - - name: Log into registry - run: echo "${{ secrets.release_docker_hub }}" | docker login -u ${{ secrets.actor_docker_hub }} --password-stdin - - - name: Push image - run: | - IMAGE_ID=$NAMESPACE/$SERVICE_NAME - - # Change all uppercase to lowercase - IMAGE_ID=$(echo $IMAGE_ID | tr '[A-Z]' '[a-z]') - VERSION=$BRANCH_NAME - echo IMAGE_ID=$IMAGE_ID - echo VERSION=$VERSION - docker tag $SERVICE_NAME $IMAGE_ID:$VERSION - docker push $IMAGE_ID:$VERSION - env: - NAMESPACE: ${{ secrets.dev_namespace_docker_hub }} - SERVICE_NAME: registration-processor-common-camel-bridge - SERVICE_LOCATION: registration-processor/registration-processor-common-camel-bridge - - publish_to_nexus: - - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v2 - - name: Set up JDK 11 - uses: actions/setup-java@v1 - with: - ref: ${{ github.ref }} - java-version: 11 - server-id: ossrh # Value of the distributionManagement/repository/id field of the pom.xml - settings-path: ${{ github.workspace }} # location for the settings.xml file - - uses: actions/checkout@v2 - - - - name: Setup branch and GPG public key - run: | - # Strip git ref prefix from version - echo "::set-env name=BRANCH_NAME::$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')" - echo ${{ env.BRANCH_NAME }} - echo "::set-env name=GPG_TTY::$(tty)" - echo ${{ env.GPG_TTY }} - sudo apt-get --yes install gnupg2 - gpg2 --import ./.github/keys/mosipgpgkey_pub.gpg - gpg2 --quiet --batch --passphrase=${{secrets.gpg_secret}} --allow-secret-key-import --import ./.github/keys/mosipgpgkey_sec.gpg - - - uses: actions/cache@v1 - with: - path: ~/.m2/repository - key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }} - restore-keys: | - ${{ runner.os }}-maven-${{ env.BRANCH_NAME }} - - - name: Install xmllint - run: | - sudo apt-get update - sudo apt-get install libxml2-utils - - - name: Setup the settings file for ossrh server - run: echo " ossrh ${{secrets.ossrh_user}} ${{secrets.ossrh_secret}} ossrh true gpg2 ${{secrets.gpg_secret}} allow-snapshots true snapshots-repo https://oss.sonatype.org/content/repositories/snapshots false true releases-repo https://oss.sonatype.org/service/local/staging/deploy/maven2 true false sonar . https://sonarcloud.io false " > $GITHUB_WORKSPACE/settings.xml - - - name: Build with Maven - run: | - cd registration-processor - mvn -B package --file pom.xml -s $GITHUB_WORKSPACE/settings.xml - - - name: Publish the maven package - run: | - chmod +x ./deploy.sh - ./deploy.sh registration-processor $GITHUB_WORKSPACE/settings.xml .* - env: - GITHUB_TOKEN: ${{ secrets.access_token }} - GPG_TTY: $(tty) - - name: Analyze with SonarCloud - run: | - cd registration-processor - mvn -B verify sonar:sonar -Dsonar.projectKey=${{ secrets.PROJECT_KEY }} -Dsonar.organization=${{ secrets.ORG_KEY }} -Dsonar.host.url=https://sonarcloud.io -Dsonar.login=${{ secrets.SONAR_TOKEN }} - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} - docker-registration-processor-registration-transaction-service: - needs: build - - runs-on: ubuntu-latest - env: - NAMESPACE: mosipdev - SERVICE_NAME: registration-processor-registration-transaction-service - SERVICE_LOCATION: registration-processor/post-processor/registration-processor-registration-transaction-service - - steps: - - uses: actions/checkout@v2 - - uses: actions/download-artifact@v1 - with: - name: release - path: ./ - - - name: Setup branch name - run: | - # Strip git ref prefix from version - echo "::set-env name=BRANCH_NAME::$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')" - echo ${{ env.BRANCH_NAME }} - - - name: Get version info from pom - id: getPomVersion - uses: mavrosxristoforos/get-xml-info@1.0 - with: - xml-file: ./${{ env.SERVICE_LOCATION }}/pom.xml - xpath: /*[local-name()="project"]/*[local-name()="version"] - - - name: Unzip and extract the ${{ env.SERVICE_NAME }} - run: unzip -uj "release.zip" "${{ env.SERVICE_LOCATION }}/target/*" -d "./${{ env.SERVICE_LOCATION }}/target" - - - name: Build image - run: | - cd "./${{env.SERVICE_LOCATION}}" - docker build . --file Dockerfile --tag ${{ env.SERVICE_NAME }} - - name: Log into registry - run: echo "${{ secrets.release_docker_hub }}" | docker login -u ${{ secrets.actor_docker_hub }} --password-stdin - - - name: Push image - run: | - IMAGE_ID=$NAMESPACE/$SERVICE_NAME - - # Change all uppercase to lowercase - IMAGE_ID=$(echo $IMAGE_ID | tr '[A-Z]' '[a-z]') - echo "push version ${{steps.getPomVersion.outputs.info}}" - VERSION=$BRANCH_NAME - echo IMAGE_ID=$IMAGE_ID - echo VERSION=$VERSION - docker tag $SERVICE_NAME $IMAGE_ID:$VERSION - docker push $IMAGE_ID:$VERSION - - docker-registration-processor-abis: - needs: build - - runs-on: ubuntu-latest - env: - NAMESPACE: mosipdev - SERVICE_NAME: registration-processor-abis - SERVICE_LOCATION: registration-processor/core-processor/registration-processor-abis - - steps: - - uses: actions/checkout@v2 - - uses: actions/download-artifact@v1 - with: - name: release - path: ./ - - - name: Setup branch name - run: | - # Strip git ref prefix from version - echo "::set-env name=BRANCH_NAME::$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')" - - - name: Get version info from pom - id: getPomVersion - uses: mavrosxristoforos/get-xml-info@1.0 - with: - xml-file: ./${{ env.SERVICE_LOCATION }}/pom.xml - xpath: /*[local-name()="project"]/*[local-name()="version"] - - - name: Unzip and extract the ${{ env.SERVICE_NAME }} - run: unzip -uj "release.zip" "${{ env.SERVICE_LOCATION }}/target/*" -d "./${{ env.SERVICE_LOCATION }}/target" - - - name: Build image - run: | - cd "./${{env.SERVICE_LOCATION}}" - docker build . --file Dockerfile --tag ${{ env.SERVICE_NAME }} - - name: Log into registry - run: echo "${{ secrets.release_docker_hub }}" | docker login -u ${{ secrets.actor_docker_hub }} --password-stdin - - - name: Push image - run: | - IMAGE_ID=$NAMESPACE/$SERVICE_NAME - - # Change all uppercase to lowercase - IMAGE_ID=$(echo $IMAGE_ID | tr '[A-Z]' '[a-z]') - echo "push version ${{steps.getPomVersion.outputs.info}}" - VERSION=$BRANCH_NAME - echo IMAGE_ID=$IMAGE_ID - echo VERSION=$VERSION - docker tag $SERVICE_NAME $IMAGE_ID:$VERSION - docker push $IMAGE_ID:$VERSION - - docker-registration-processor-reprocessor: - needs: build - - runs-on: ubuntu-latest - env: - NAMESPACE: mosipdev - SERVICE_NAME: registration-processor-reprocessor - SERVICE_LOCATION: registration-processor/workflow-engine/registration-processor-reprocessor - - steps: - - uses: actions/checkout@v2 - - uses: actions/download-artifact@v1 - with: - name: release - path: ./ - - - name: Setup branch name - run: | - # Strip git ref prefix from version - echo "::set-env name=BRANCH_NAME::$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')" - - - name: Get version info from pom - id: getPomVersion - uses: mavrosxristoforos/get-xml-info@1.0 - with: - xml-file: ./${{ env.SERVICE_LOCATION }}/pom.xml - xpath: /*[local-name()="project"]/*[local-name()="version"] - - - name: Unzip and extract the ${{ env.SERVICE_NAME }} - run: unzip -uj "release.zip" "${{ env.SERVICE_LOCATION }}/target/*" -d "./${{ env.SERVICE_LOCATION }}/target" - - - name: Build image - run: | - cd "./${{env.SERVICE_LOCATION}}" - docker build . --file Dockerfile --tag ${{ env.SERVICE_NAME }} - - name: Log into registry - run: echo "${{ secrets.release_docker_hub }}" | docker login -u ${{ secrets.actor_docker_hub }} --password-stdin - - - name: Push image - run: | - IMAGE_ID=$NAMESPACE/$SERVICE_NAME - - # Change all uppercase to lowercase - IMAGE_ID=$(echo $IMAGE_ID | tr '[A-Z]' '[a-z]') - echo "push version ${{steps.getPomVersion.outputs.info}}" - VERSION=$BRANCH_NAME - echo IMAGE_ID=$IMAGE_ID - echo VERSION=$VERSION - docker tag $SERVICE_NAME $IMAGE_ID:$VERSION - docker push $IMAGE_ID:$VERSION - - docker-registration-processor-dmz-packet-server: - needs: build - - runs-on: ubuntu-latest - env: - NAMESPACE: mosipdev - SERVICE_NAME: registration-processor-dmz-packet-server - SERVICE_LOCATION: registration-processor/init/registration-processor-dmz-packet-server - - steps: - - uses: actions/checkout@v2 - - - name: Setup branch name - run: | - # Strip git ref prefix from version - echo "::set-env name=BRANCH_NAME::$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')" - echo ${{ env.BRANCH_NAME }} - - - name: Get version info - id: getVersion - uses: mavrosxristoforos/get-xml-info@1.0 - with: - xml-file: ./${{ env.SERVICE_LOCATION }}/version.xml - xpath: version - - - name: Build image - run: | - cd "./${{env.SERVICE_LOCATION}}" - docker build . --file Dockerfile --tag ${{ env.SERVICE_NAME }} - - name: Log into registry - run: echo "${{ secrets.release_docker_hub }}" | docker login -u ${{ secrets.actor_docker_hub }} --password-stdin - - - name: Push image - run: | - IMAGE_ID=$NAMESPACE/$SERVICE_NAME - - # Change all uppercase to lowercase - IMAGE_ID=$(echo $IMAGE_ID | tr '[A-Z]' '[a-z]') - echo "push version ${{steps.getVersion.outputs.info}}" - VERSION=${{steps.getVersion.outputs.info}} - echo IMAGE_ID=$IMAGE_ID - echo VERSION=$VERSION - docker tag $SERVICE_NAME $IMAGE_ID:$VERSION - docker push $IMAGE_ID:$VERSION - - docker-registration-processor-registration-status-service: - needs: build - - runs-on: ubuntu-latest - env: - NAMESPACE: mosipdev - SERVICE_NAME: registration-processor-registration-status-service - SERVICE_LOCATION: registration-processor/init/registration-processor-registration-status-service - - steps: - - uses: actions/checkout@v2 - - uses: actions/download-artifact@v1 - with: - name: release - path: ./ - - - name: Setup branch name - run: | - # Strip git ref prefix from version - echo "::set-env name=BRANCH_NAME::$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')" - echo ${{ env.BRANCH_NAME }} - - - name: Get version info from pom - id: getPomVersion - uses: mavrosxristoforos/get-xml-info@1.0 - with: - xml-file: ./${{ env.SERVICE_LOCATION }}/pom.xml - xpath: /*[local-name()="project"]/*[local-name()="version"] - - - name: Unzip and extract the ${{ env.SERVICE_NAME }} - run: unzip -uj "release.zip" "${{ env.SERVICE_LOCATION }}/target/*" -d "./${{ env.SERVICE_LOCATION }}/target" - - - name: Build image - run: | - cd "./${{env.SERVICE_LOCATION}}" - docker build . --file Dockerfile --tag ${{ env.SERVICE_NAME }} - - name: Log into registry - run: echo "${{ secrets.release_docker_hub }}" | docker login -u ${{ secrets.actor_docker_hub }} --password-stdin - - - name: Push image - run: | - IMAGE_ID=$NAMESPACE/$SERVICE_NAME - - # Change all uppercase to lowercase - IMAGE_ID=$(echo $IMAGE_ID | tr '[A-Z]' '[a-z]') - echo "push version ${{steps.getPomVersion.outputs.info}}" - VERSION=$BRANCH_NAME - echo IMAGE_ID=$IMAGE_ID - echo VERSION=$VERSION - docker tag $SERVICE_NAME $IMAGE_ID:$VERSION - docker push $IMAGE_ID:$VERSION - - docker-registration-processor-notification-service: - needs: build - - runs-on: ubuntu-latest - env: - NAMESPACE: mosipdev - SERVICE_NAME: registration-processor-notification-service - SERVICE_LOCATION: registration-processor/registration-processor-notification-service - - steps: - - uses: actions/checkout@v2 - - uses: actions/download-artifact@v1 - with: - name: release - path: ./ - - - name: Setup branch name - run: | - # Strip git ref prefix from version - echo "::set-env name=BRANCH_NAME::$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')" - echo ${{ env.BRANCH_NAME }} - - - name: Get version info from pom - id: getPomVersion - uses: mavrosxristoforos/get-xml-info@1.0 - with: - xml-file: ./${{ env.SERVICE_LOCATION }}/pom.xml - xpath: /*[local-name()="project"]/*[local-name()="version"] - - - name: Unzip and extract the ${{ env.SERVICE_NAME }} - run: unzip -uj "release.zip" "${{ env.SERVICE_LOCATION }}/target/*" -d "./${{ env.SERVICE_LOCATION }}/target" - - - name: Build image - run: | - cd "./${{env.SERVICE_LOCATION}}" - docker build . --file Dockerfile --tag ${{ env.SERVICE_NAME }} - - name: Log into registry - run: echo "${{ secrets.release_docker_hub }}" | docker login -u ${{ secrets.actor_docker_hub }} --password-stdin - - - name: Push image - run: | - IMAGE_ID=$NAMESPACE/$SERVICE_NAME - - # Change all uppercase to lowercase - IMAGE_ID=$(echo $IMAGE_ID | tr '[A-Z]' '[a-z]') - echo "push version ${{steps.getPomVersion.outputs.info}}" - VERSION=$BRANCH_NAME - echo IMAGE_ID=$IMAGE_ID - echo VERSION=$VERSION - docker tag $SERVICE_NAME $IMAGE_ID:$VERSION - docker push $IMAGE_ID:$VERSION - - docker-registration-processor-landing-zone: - needs: build - - runs-on: ubuntu-latest - env: - NAMESPACE: mosipdev - SERVICE_NAME: registration-processor-landing-zone - SERVICE_LOCATION: registration-processor/registration-processor-landing-zone - - steps: - - uses: actions/checkout@v2 - - uses: actions/download-artifact@v1 - with: - name: release - path: ./ - - - name: Setup branch name - run: | - # Strip git ref prefix from version - echo "::set-env name=BRANCH_NAME::$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')" - echo ${{ env.BRANCH_NAME }} - - - name: Get version info from pom - id: getPomVersion - uses: mavrosxristoforos/get-xml-info@1.0 - with: - xml-file: ./${{ env.SERVICE_LOCATION }}/pom.xml - xpath: /*[local-name()="project"]/*[local-name()="version"] - - - name: Unzip and extract the ${{ env.SERVICE_NAME }} - run: unzip -uj "release.zip" "${{ env.SERVICE_LOCATION }}/target/*" -d "./${{ env.SERVICE_LOCATION }}/target" - - - name: Build image - run: | - cd "./${{env.SERVICE_LOCATION}}" - docker build . --file Dockerfile --tag ${{ env.SERVICE_NAME }} - - name: Log into registry - run: echo "${{ secrets.release_docker_hub }}" | docker login -u ${{ secrets.actor_docker_hub }} --password-stdin - - - name: Push image - run: | - IMAGE_ID=$NAMESPACE/$SERVICE_NAME - - # Change all uppercase to lowercase - IMAGE_ID=$(echo $IMAGE_ID | tr '[A-Z]' '[a-z]') - echo "push version ${{steps.getPomVersion.outputs.info}}" - VERSION=$BRANCH_NAME - echo IMAGE_ID=$IMAGE_ID - echo VERSION=$VERSION - docker tag $SERVICE_NAME $IMAGE_ID:$VERSION - docker push $IMAGE_ID:$VERSION - - docker-registration-processor-workflow-manager-service: - needs: build - - runs-on: ubuntu-latest - env: - NAMESPACE: mosipdev - SERVICE_NAME: registration-processor-workflow-manager-service - SERVICE_LOCATION: registration-processor/workflow-engine/registration-processor-workflow-manager-service - - steps: - - uses: actions/checkout@v2 - - uses: actions/download-artifact@v1 - with: - name: release - path: ./ - - - name: Setup branch name - run: | - # Strip git ref prefix from version - echo "::set-env name=BRANCH_NAME::$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')" - echo ${{ env.BRANCH_NAME }} - - - name: Get version info from pom - id: getPomVersion - uses: mavrosxristoforos/get-xml-info@1.0 - with: - xml-file: ./${{ env.SERVICE_LOCATION }}/pom.xml - xpath: /*[local-name()="project"]/*[local-name()="version"] - - - name: Unzip and extract the ${{ env.SERVICE_NAME }} - run: unzip -uj "release.zip" "${{ env.SERVICE_LOCATION }}/target/*" -d "./${{ env.SERVICE_LOCATION }}/target" - - - name: Build image - run: | - cd "./${{env.SERVICE_LOCATION}}" - docker build . --file Dockerfile --tag ${{ env.SERVICE_NAME }} - - name: Log into registry - run: echo "${{ secrets.release_docker_hub }}" | docker login -u ${{ secrets.actor_docker_hub }} --password-stdin - - - name: Push image - run: | - IMAGE_ID=$NAMESPACE/$SERVICE_NAME - - # Change all uppercase to lowercase - IMAGE_ID=$(echo $IMAGE_ID | tr '[A-Z]' '[a-z]') - echo "push version ${{steps.getPomVersion.outputs.info}}" - VERSION=$BRANCH_NAME - echo IMAGE_ID=$IMAGE_ID - echo VERSION=$VERSION - docker tag $SERVICE_NAME $IMAGE_ID:$VERSION - docker push $IMAGE_ID:$VERSION \ No newline at end of file diff --git a/.github/workflows/tag.yaml b/.github/workflows/tag.yaml index e9bba0e65a0..73c55b03d8f 100644 --- a/.github/workflows/tag.yaml +++ b/.github/workflows/tag.yaml @@ -1,43 +1,33 @@ name: Tagging of repos -env: - tag: v1.2.3 - on: workflow_dispatch: inputs: - tag: + TAG: description: 'Tag to be published' required: true - default: 'v1.2.3' type: string - body: + BODY: description: 'Release body message' required: true default: 'Changes in this Release' type: string - pre-release: + PRE_RELEASE: description: 'Pre-release? True/False' required: true default: False type: string + DRAFT: + description: 'Draft? True/False' + required: false + default: False + type: string jobs: - build: - name: Create Release - runs-on: ubuntu-latest - steps: - - name: Checkout code - uses: actions/checkout@v2 - - name: Create Release - id: create_release - uses: actions/create-release@v1 - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # This token is provided by Actions, you do not need to create your own token - with: - tag_name: ${{ github.event.inputs.tag }} - release_name: ${{ github.event.inputs.tag }} - body: | - ${{ github.event.inputs.body }} - draft: false - prerelease: ${{fromJSON(github.event.inputs.pre-release)}} + tag-branch: + uses: mosip/kattu/.github/workflows/tag.yml@master + with: + TAG: ${{ inputs.TAG }} + BODY: ${{ inputs.BODY }} + PRE_RELEASE: ${{ inputs.PRE_RELEASE }} + DRAFT: ${{ inputs.DRAFT }} \ No newline at end of file diff --git a/registration-processor/core-processor/registration-processor-biometric-extraction-stage/pom.xml b/registration-processor/core-processor/registration-processor-biometric-extraction-stage/pom.xml index ca855cd09a6..c22795794a5 100644 --- a/registration-processor/core-processor/registration-processor-biometric-extraction-stage/pom.xml +++ b/registration-processor/core-processor/registration-processor-biometric-extraction-stage/pom.xml @@ -8,6 +8,7 @@ 1.2.0.1-SNAPSHOT registration-processor-biometric-extraction-stage + 1.2.0.1-SNAPSHOT jar UTF-8 diff --git a/registration-processor/core-processor/registration-processor-finalization-stage/pom.xml b/registration-processor/core-processor/registration-processor-finalization-stage/pom.xml index 60f881cedfa..fe52552ff90 100644 --- a/registration-processor/core-processor/registration-processor-finalization-stage/pom.xml +++ b/registration-processor/core-processor/registration-processor-finalization-stage/pom.xml @@ -9,6 +9,7 @@ registration-processor-finalization-stage registration-processor-finalization-stage + 1.2.0.1-SNAPSHOT jar UTF-8 diff --git a/registration-processor/init/pom.xml b/registration-processor/init/pom.xml index b7e170a1cdb..e0cab04f77e 100644 --- a/registration-processor/init/pom.xml +++ b/registration-processor/init/pom.xml @@ -9,6 +9,7 @@ 1.2.0.1-SNAPSHOT init + 1.2.0.1-SNAPSHOT UTF-8 diff --git a/registration-processor/pom.xml b/registration-processor/pom.xml index 0684da75445..e3be909e5d1 100644 --- a/registration-processor/pom.xml +++ b/registration-processor/pom.xml @@ -8,6 +8,26 @@ 1.2.0.1-SNAPSHOT + + + MPL 2.0 + https://www.mozilla.org/en-US/MPL/2.0/ + + + + scm:git:git://github.com/mosip/registration.git + scm:git:ssh://github.com:mosip/registration.git + https://github.com/mosip/registration + HEAD + + + + Mosip + mosip.emailnotifier@gmail.com + io.mosip + https://github.com/mosip/registration + + io.mosip.registrationprocessor registration-processor 1.2.0.1-SNAPSHOT @@ -434,6 +454,51 @@ + + 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 diff --git a/registration-processor/qc-users-manger/pom.xml b/registration-processor/qc-users-manger/pom.xml index 850095b849e..6f5129d7735 100644 --- a/registration-processor/qc-users-manger/pom.xml +++ b/registration-processor/qc-users-manger/pom.xml @@ -5,6 +5,7 @@ qc-users-manger + 1.2.0.1-SNAPSHOT io.mosip.registrationprocessor registration-processor From dd58bffa4183ce1ce6f61cf2013bdb29addc1aba Mon Sep 17 00:00:00 2001 From: Rakshitha650 Date: Thu, 21 Sep 2023 19:11:03 +0530 Subject: [PATCH 098/133] [MOSIP-29167]added reusable workflow --- .github/workflows/clear-artifacts.yml | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/.github/workflows/clear-artifacts.yml b/.github/workflows/clear-artifacts.yml index 75b8aa96454..b98fd748405 100644 --- a/.github/workflows/clear-artifacts.yml +++ b/.github/workflows/clear-artifacts.yml @@ -5,9 +5,4 @@ on: jobs: delete-artifacts: - runs-on: ubuntu-latest - steps: - - uses: kolpav/purge-artifacts-action@v1 - with: - token: ${{ secrets. access_token }} - expire-in: 2days # Setting this to 0 will delete all artifacts + uses: mosip/kattu/.github/workflows/clear-artifacts.yml@master From 282598f81f7f8d58c6f9825246cb74b3d7a81029 Mon Sep 17 00:00:00 2001 From: khuddus shariff Date: Mon, 25 Sep 2023 12:49:15 +0530 Subject: [PATCH 099/133] quality checker level tags more specific MOSIP-29419 (#1778) * quality checker level tags more specific MOSIP-29419 * quality checker level tags more specific MOSIP-29419 * quality checker level tags more specific MOSIP-29419 --- .../stage/QualityClassifierStage.java | 4 +- .../test/QualityClassifierStageTest.java | 46 ++++++++++++++----- 2 files changed, 36 insertions(+), 14 deletions(-) diff --git a/registration-processor/pre-processor/registration-processor-quality-classifier-stage/src/main/java/io/mosip/registration/processor/quality/classifier/stage/QualityClassifierStage.java b/registration-processor/pre-processor/registration-processor-quality-classifier-stage/src/main/java/io/mosip/registration/processor/quality/classifier/stage/QualityClassifierStage.java index 7ce659d388c..8cb8c92f77f 100644 --- a/registration-processor/pre-processor/registration-processor-quality-classifier-stage/src/main/java/io/mosip/registration/processor/quality/classifier/stage/QualityClassifierStage.java +++ b/registration-processor/pre-processor/registration-processor-quality-classifier-stage/src/main/java/io/mosip/registration/processor/quality/classifier/stage/QualityClassifierStage.java @@ -137,7 +137,7 @@ public class QualityClassifierStage extends MosipVerticleAPIManager { * inclusive. */ - @Value("#{${mosip.regproc.quality.classifier.tagging.quality.ranges:{'Poor':'0-29','Average':'30-69','Good':'70-100'}}}") + @Value("#{${mosip.regproc.quality.classifier.tagging.quality.ranges:{'level-1':'0-10','level-2':'10-20','level-3':'20-30','level-4':'30-40','level-5':'40-50','level-6':'50-60','level-7':'60-70','level-8':'70-80','level-9':'80-90','level-10':'90-101',}}}") private Map qualityClassificationRangeMap; /** Quality Tag Prefix */ @@ -461,7 +461,7 @@ private Map getQualityTags(List birs) throws BiometricExcep for (Entry qualityRangeEntry : parsedQualityRangeMap.entrySet()) { if (bioTypeMinEntry.getValue() >= qualityRangeEntry.getValue()[0] - && bioTypeMinEntry.getValue() <= qualityRangeEntry.getValue()[1]) { + && bioTypeMinEntry.getValue() < qualityRangeEntry.getValue()[1]) { tags.put( qualityTagPrefix.concat(bioTypeMinEntry.getKey()), qualityRangeEntry.getKey()); break; 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 7c3dbc180e6..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,13 +107,19 @@ public class QualityClassifierStageTest { private String qualityPrefixTag = "Biometric_Quality-"; - private String AVERAGE = "Average"; - private String POOR = "Poor"; + private String level_1 = "level-1"; + private String level_2 = "level-2"; + private String level_3 = "level-3"; + private String level_4 = "level-4"; + private String level_5 = "level-5"; + private String level_6 = "level-6"; + private String level_7 = "level-7"; + private String level_8 = "level-8"; + private String level_9 = "level-9"; + private String level_10 = "level-10"; - private String GOOD = "Good"; -// JSONObject mappingJSONObject; @InjectMocks @@ -184,17 +190,33 @@ public void setUp() throws Exception { ReflectionTestUtils.setField(qualityClassifierStage, "qualityTagPrefix", qualityPrefixTag); Map qualityClassificationRangeMap = new HashMap(); - qualityClassificationRangeMap.put(POOR, "0-29"); - qualityClassificationRangeMap.put(AVERAGE, "30-69"); - qualityClassificationRangeMap.put(GOOD, "70-100"); + qualityClassificationRangeMap.put(level_1, "0-10"); + qualityClassificationRangeMap.put(level_2, "10-20"); + qualityClassificationRangeMap.put(level_3, "20-30"); + qualityClassificationRangeMap.put(level_4, "30-40"); + qualityClassificationRangeMap.put(level_5, "40-50"); + qualityClassificationRangeMap.put(level_6, "50-60"); + qualityClassificationRangeMap.put(level_7, "60-70"); + qualityClassificationRangeMap.put(level_8, "70-80"); + qualityClassificationRangeMap.put(level_9, "80-90"); + qualityClassificationRangeMap.put(level_10, "90-101"); + ReflectionTestUtils.setField(qualityClassifierStage, "qualityClassificationRangeMap", qualityClassificationRangeMap); Map parsedMap = new HashMap(); - parsedMap.put(POOR, new int[] { 0, 29 }); - parsedMap.put(AVERAGE, new int[] { 30, 69 }); - parsedMap.put(GOOD, new int[] { 70, 100 }); + parsedMap.put(level_1, new int[] { 0, 10 }); + parsedMap.put(level_2, new int[] { 10, 20 }); + parsedMap.put(level_3, new int[] { 20, 30 }); + parsedMap.put(level_4, new int[] { 30, 40 }); + parsedMap.put(level_5, new int[] { 40, 50 }); + parsedMap.put(level_6, new int[] { 50, 60 }); + parsedMap.put(level_7, new int[] { 60, 70 }); + parsedMap.put(level_8, new int[] { 70, 80 }); + parsedMap.put(level_9, new int[] { 80, 90 }); + parsedMap.put(level_10, new int[] { 90, 101 }); + ReflectionTestUtils.setField(qualityClassifierStage, "parsedQualityRangeMap", parsedMap); ReflectionTestUtils.setField(qualityClassifierStage, "modalities", Arrays.asList("Iris", "Finger", "Face")); @@ -327,7 +349,7 @@ public void testQualityClassifierMixTags() throws Exception { verify(packetManagerService, atLeastOnce()).addOrUpdateTags(any(), argument.capture()); - assertQualityTags(argument.getAllValues().get(0), AVERAGE, POOR, GOOD); + assertQualityTags(argument.getAllValues().get(0), level_5, level_3, level_10); } @@ -350,7 +372,7 @@ public void testQualityClassifierAllGoodTags() throws ApisResourceAccessExceptio verify(packetManagerService, atLeastOnce()).addOrUpdateTags(any(), argument.capture()); - assertQualityTags(argument.getAllValues().get(0), GOOD, GOOD, GOOD); + assertQualityTags(argument.getAllValues().get(0), level_10, level_10, level_10); } From 6e4056571eaf43892139e26375526280c86b2ae3 Mon Sep 17 00:00:00 2001 From: Sowmya Ujjappa Banakar Date: Mon, 25 Sep 2023 16:25:15 +0530 Subject: [PATCH 100/133] MOSIP-29117 code fix --- .../stage/BiometricAuthenticationStage.java | 781 +++++++++--------- .../BiometricAuthenticationStageTest.java | 8 + 2 files changed, 396 insertions(+), 393 deletions(-) diff --git a/registration-processor/core-processor/registration-processor-biometric-authentication-stage/src/main/java/io/mosip/registration/processor/biometric/authentication/stage/BiometricAuthenticationStage.java b/registration-processor/core-processor/registration-processor-biometric-authentication-stage/src/main/java/io/mosip/registration/processor/biometric/authentication/stage/BiometricAuthenticationStage.java index 7483f58a274..836c0b35b81 100644 --- a/registration-processor/core-processor/registration-processor-biometric-authentication-stage/src/main/java/io/mosip/registration/processor/biometric/authentication/stage/BiometricAuthenticationStage.java +++ b/registration-processor/core-processor/registration-processor-biometric-authentication-stage/src/main/java/io/mosip/registration/processor/biometric/authentication/stage/BiometricAuthenticationStage.java @@ -1,394 +1,389 @@ -package io.mosip.registration.processor.biometric.authentication.stage; - -import java.io.IOException; -import java.security.NoSuchAlgorithmException; -import java.security.cert.CertificateException; -import java.util.List; -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.cloud.context.config.annotation.RefreshScope; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.stereotype.Service; -import org.springframework.util.CollectionUtils; - -import io.mosip.kernel.biometrics.entities.BIR; -import io.mosip.kernel.biometrics.entities.BiometricRecord; -import io.mosip.kernel.core.logger.spi.Logger; -import io.mosip.kernel.core.util.exception.JsonProcessingException; -import io.mosip.registration.processor.biometric.authentication.constants.BiometricAuthenticationConstants; -import io.mosip.registration.processor.core.abstractverticle.MessageBusAddress; -import io.mosip.registration.processor.core.abstractverticle.MessageDTO; -import io.mosip.registration.processor.core.abstractverticle.MosipEventBus; -import io.mosip.registration.processor.core.abstractverticle.MosipRouter; -import io.mosip.registration.processor.core.abstractverticle.MosipVerticleAPIManager; -import io.mosip.registration.processor.core.auth.dto.AuthResponseDTO; -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.ProviderStageName; -import io.mosip.registration.processor.core.constant.RegistrationType; -import io.mosip.registration.processor.core.exception.ApisResourceAccessException; -import io.mosip.registration.processor.core.exception.AuthSystemException; -import io.mosip.registration.processor.core.exception.BioTypeException; -import io.mosip.registration.processor.core.exception.PacketManagerException; -import io.mosip.registration.processor.core.exception.ValidationFailedException; -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.RegProcessorLogger; -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.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.rest.client.audit.builder.AuditLogRequestBuilder; -import io.mosip.registration.processor.status.code.RegistrationStatusCode; -import io.mosip.registration.processor.status.dto.InternalRegistrationStatusDto; -import io.mosip.registration.processor.status.dto.RegistrationStatusDto; -import io.mosip.registration.processor.status.dto.SyncRegistrationDto; -import io.mosip.registration.processor.status.dto.SyncResponseDto; -import io.mosip.registration.processor.status.dto.SyncTypeDto; -import io.mosip.registration.processor.status.entity.SyncRegistrationEntity; -import io.mosip.registration.processor.status.service.RegistrationStatusService; -import io.mosip.registration.processor.status.service.SyncRegistrationService; - -@RefreshScope -@Service -@Configuration -@ComponentScan(basePackages = { "${mosip.auth.adapter.impl.basepackage}", - "io.mosip.registration.processor.biometric.authentication.config", - "io.mosip.registration.processor.status.config", "io.mosip.registration.processor.rest.client.config", - "io.mosip.registration.processor.packet.storage.config", "io.mosip.registration.processor.core.config", - "io.mosip.registration.processor.core.kernel.beans", "io.mosip.kernel.packetmanager.config", - "io.mosip.kernel.biosdk.provider.impl" }) -public class BiometricAuthenticationStage extends MosipVerticleAPIManager { - private static Logger regProcLogger = RegProcessorLogger.getLogger(BiometricAuthenticationStage.class); - private static final String STAGE_PROPERTY_PREFIX = "mosip.regproc.biometric.authentication."; - private static final String ADULT_BIOMETRIC_UPDATE = "as adult has come for biometric update"; - @Autowired - AuditLogRequestBuilder auditLogRequestBuilder; - - @Autowired - private Utilities utility; - - /** The registration status service. */ - @Autowired - RegistrationStatusService registrationStatusService; - - @Autowired - private BioSdkUtil bioUtil; - - @Autowired - private PriorityBasedPacketManagerService packetManagerService; - - @Autowired - RegistrationExceptionMapperUtil registrationStatusMapperUtil; - - @Value("${vertx.cluster.configuration}") - private String clusterManagerUrl; - - @Value("${mosip.kernel.applicant.type.age.limit}") - private String ageLimit; - - /** worker pool size. */ - @Value("${worker.pool.size}") - private Integer workerPoolSize; - - /** - * After this time intervel, message should be considered as expired (In - * seconds). - */ - @Value("${mosip.regproc.biometric.authentication.message.expiry-time-limit}") - private Long messageExpiryTimeLimit; - - /** The mosip event bus. */ - MosipEventBus mosipEventBus = null; - - /** Mosip router for APIs */ - @Autowired - MosipRouter router; - - @Autowired - private SyncRegistrationService syncRegistrationservice; - - public void deployVerticle() { - mosipEventBus = this.getEventBus(this, clusterManagerUrl, workerPoolSize); - this.consumeAndSend(mosipEventBus, MessageBusAddress.BIOMETRIC_AUTHENTICATION_BUS_IN, - MessageBusAddress.BIOMETRIC_AUTHENTICATION_BUS_OUT, messageExpiryTimeLimit); - } - - @Override - public void start() { - router.setRoute(this.postUrl(getVertx(), MessageBusAddress.BIOMETRIC_AUTHENTICATION_BUS_IN, - MessageBusAddress.BIOMETRIC_AUTHENTICATION_BUS_OUT)); - this.createServer(router.getRouter(), getPort()); - } - - @Override - protected String getPropertyPrefix() { - return STAGE_PROPERTY_PREFIX; - } - - @Override - public MessageDTO process(MessageDTO object) { - TrimExceptionMessage trimExceptionMessage = new TrimExceptionMessage(); - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), "", - "BiometricAuthenticationStage::BiometricAuthenticationStage::entry"); - String registrationId = object.getRid(); - object.setMessageBusAddress(MessageBusAddress.BIOMETRIC_AUTHENTICATION_BUS_IN); - object.setIsValid(Boolean.FALSE); - object.setInternalError(Boolean.FALSE); - InternalRegistrationStatusDto registrationStatusDto = registrationStatusService.getRegistrationStatus( - registrationId, object.getReg_type(), object.getIteration(), object.getWorkflowInstanceId()); - - registrationStatusDto - .setLatestTransactionTypeCode(RegistrationTransactionTypeCode.BIOMETRIC_AUTHENTICATION.toString()); - registrationStatusDto.setRegistrationStageName(getStageName()); - SyncRegistrationEntity regEntity = syncRegistrationservice - .findByWorkflowInstanceId(object.getWorkflowInstanceId()); - String description = ""; - String code = ""; - boolean isBioAuthSkipped = false; - boolean isTransactionSuccessful = false; - - try { - String process = registrationStatusDto.getRegistrationType(); - String registartionType = regEntity.getRegistrationType(); - int applicantAge = utility.getApplicantAge(registrationId, process, ProviderStageName.BIO_AUTH); - int childAgeLimit = Integer.parseInt(ageLimit); - String applicantType = BiometricAuthenticationConstants.ADULT; - if (applicantAge <= childAgeLimit && applicantAge > 0) { - applicantType = BiometricAuthenticationConstants.CHILD; - } - if (isUpdateAdultPacket(registartionType, applicantType)) { - - String biometricsLabel = packetManagerService.getFieldByMappingJsonKey(registrationId, - MappingJsonConstants.INDIVIDUAL_BIOMETRICS, registrationStatusDto.getRegistrationType(), - ProviderStageName.BIO_AUTH); - if (StringUtils.isEmpty(biometricsLabel)) { - isTransactionSuccessful = checkIndividualAuthentication(registrationId, process, - registrationStatusDto); - description = isTransactionSuccessful - ? PlatformSuccessMessages.RPR_PKR_BIOMETRIC_AUTHENTICATION.getMessage() - : PlatformErrorMessages.BIOMETRIC_AUTHENTICATION_FAILED.getMessage(); - } else { - String individualBiometricsFileName = JsonUtil.getJSONValue( - JsonUtil.readValueWithUnknownProperties(biometricsLabel, JSONObject.class), - MappingJsonConstants.VALUE); - if (individualBiometricsFileName != null && !individualBiometricsFileName.isEmpty()) { - BiometricRecord biometricRecord = packetManagerService.getBiometricsByMappingJsonKey( - registrationId, MappingJsonConstants.INDIVIDUAL_BIOMETRICS, process, - ProviderStageName.BIO_AUTH); - if (biometricRecord == null || biometricRecord.getSegments() == null - || biometricRecord.getSegments().isEmpty()) { - isTransactionSuccessful = false; - description = StatusUtil.BIOMETRIC_FILE_NOT_FOUND.getMessage(); - regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), - LoggerFileConstant.REGISTRATIONID.toString(), registrationId, description); - registrationStatusDto.setStatusComment(description); - registrationStatusDto.setSubStatusCode(StatusUtil.BIOMETRIC_FILE_NOT_FOUND.getCode()); - } else { - isBioAuthSkipped = true; - regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), - LoggerFileConstant.REGISTRATIONID.toString(), registrationId, - "BiometricAuthenticationStage::skipped"); - isTransactionSuccessful = true; - description = StatusUtil.BIOMETRIC_AUTHENTICATION_SKIPPED.getMessage() - + ADULT_BIOMETRIC_UPDATE; - } - } else { - isTransactionSuccessful = true; - description = PlatformSuccessMessages.RPR_PKR_BIOMETRIC_AUTHENTICATION.getMessage(); - } - } - } - - else { - isBioAuthSkipped = true; - isTransactionSuccessful = true; - regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), - LoggerFileConstant.REGISTRATIONID.toString(), registrationId, - "BiometricAuthenticationStage::success"); - if (applicantType.equals(BiometricAuthenticationConstants.CHILD)) { - description = BiometricAuthenticationConstants.CHILD_PACKET_DESCRIPTION; - - } else - description = StatusUtil.BIOMETRIC_AUTHENTICATION_SKIPPED.getMessage(); - } - - if (isTransactionSuccessful) { - object.setIsValid(Boolean.TRUE); - registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.name()); - registrationStatusDto - .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.SUCCESS.toString()); - if (isBioAuthSkipped) { - registrationStatusDto.setSubStatusCode(StatusUtil.BIOMETRIC_AUTHENTICATION_SKIPPED.getCode()); - registrationStatusDto - .setStatusComment(StatusUtil.BIOMETRIC_AUTHENTICATION_SKIPPED.getMessage() + description); - } else { - registrationStatusDto.setSubStatusCode(StatusUtil.BIOMETRIC_AUTHENTICATION_SUCCESS.getCode()); - registrationStatusDto.setStatusComment(StatusUtil.BIOMETRIC_AUTHENTICATION_SUCCESS.getMessage()); - } - } else { - registrationStatusDto - .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.FAILED.toString()); - registrationStatusDto.setStatusCode(RegistrationTransactionStatusCode.FAILED.toString()); - } - - } catch (IOException | NoSuchAlgorithmException e) { - registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.name()); - registrationStatusDto.setSubStatusCode(StatusUtil.IO_EXCEPTION.getCode()); - registrationStatusDto.setStatusComment( - trimExceptionMessage.trimExceptionMessage(StatusUtil.IO_EXCEPTION.getMessage() + e.getMessage())); - object.setInternalError(Boolean.TRUE); - registrationStatusDto.setLatestTransactionStatusCode( - registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.IOEXCEPTION)); - code = PlatformErrorMessages.BIOMETRIC_AUTHENTICATION_IOEXCEPTION.getCode(); - description = PlatformErrorMessages.BIOMETRIC_AUTHENTICATION_IOEXCEPTION.getMessage(); - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), code, registrationId, - description + e.getMessage() + ExceptionUtils.getStackTrace(e)); - } catch (JsonProcessingException e) { - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - registrationId, - RegistrationStatusCode.FAILED.toString() + e.getMessage() + ExceptionUtils.getStackTrace(e)); - registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.toString()); - registrationStatusDto.setStatusComment(trimExceptionMessage - .trimExceptionMessage(StatusUtil.JSON_PARSING_EXCEPTION.getMessage() + e.getMessage())); - registrationStatusDto.setSubStatusCode(StatusUtil.JSON_PARSING_EXCEPTION.getCode()); - registrationStatusDto.setLatestTransactionStatusCode(registrationStatusMapperUtil - .getStatusCode(RegistrationExceptionTypeCode.JSON_PROCESSING_EXCEPTION)); - isTransactionSuccessful = false; - description = (PlatformErrorMessages.RPR_SYS_JSON_PARSING_EXCEPTION.getMessage()); - code = (PlatformErrorMessages.RPR_SYS_JSON_PARSING_EXCEPTION.getCode()); - object.setInternalError(Boolean.TRUE); - object.setRid(registrationStatusDto.getRegistrationId()); - } catch (PacketManagerException e) { - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - registrationId, - RegistrationStatusCode.FAILED.toString() + e.getMessage() + ExceptionUtils.getStackTrace(e)); - registrationStatusDto.setStatusComment(trimExceptionMessage - .trimExceptionMessage(StatusUtil.PACKET_MANAGER_EXCEPTION.getMessage() + e.getMessage())); - registrationStatusDto.setSubStatusCode(StatusUtil.PACKET_MANAGER_EXCEPTION.getCode()); - registrationStatusDto.setLatestTransactionStatusCode( - registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.PACKET_MANAGER_EXCEPTION)); - registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.name()); - description = (PlatformErrorMessages.PACKET_MANAGER_EXCEPTION.getMessage()); - code = (PlatformErrorMessages.PACKET_MANAGER_EXCEPTION.getCode()); - object.setInternalError(Boolean.TRUE); - object.setRid(registrationStatusDto.getRegistrationId()); - } catch (ApisResourceAccessException e) { - registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.name()); - registrationStatusDto.setSubStatusCode(StatusUtil.API_RESOUCE_ACCESS_FAILED.getCode()); - registrationStatusDto.setStatusComment(trimExceptionMessage - .trimExceptionMessage(StatusUtil.API_RESOUCE_ACCESS_FAILED.getMessage() + e.getMessage())); - registrationStatusDto.setLatestTransactionStatusCode(registrationStatusMapperUtil - .getStatusCode(RegistrationExceptionTypeCode.APIS_RESOURCE_ACCESS_EXCEPTION)); - code = PlatformErrorMessages.BIOMETRIC_AUTHENTICATION_API_RESOURCE_EXCEPTION.getCode(); - description = PlatformErrorMessages.BIOMETRIC_AUTHENTICATION_API_RESOURCE_EXCEPTION.getMessage(); - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), code, registrationId, - description + e.getMessage() + ExceptionUtils.getStackTrace(e)); - object.setInternalError(Boolean.TRUE); - } catch (AuthSystemException e) { - registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.name()); - registrationStatusDto.setSubStatusCode(StatusUtil.AUTH_SYSTEM_EXCEPTION.getCode()); - registrationStatusDto.setStatusComment(trimExceptionMessage - .trimExceptionMessage(StatusUtil.AUTH_SYSTEM_EXCEPTION.getMessage() + e.getMessage())); - registrationStatusDto.setLatestTransactionStatusCode( - registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.AUTH_SYSTEM_EXCEPTION)); - code = PlatformErrorMessages.BIOMETRIC_AUTHENTICATION_AUTH_SYSTEM_EXCEPTION.getCode(); - description = PlatformErrorMessages.BIOMETRIC_AUTHENTICATION_AUTH_SYSTEM_EXCEPTION.getMessage(); - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), code, registrationId, - description + e.getMessage() + ExceptionUtils.getStackTrace(e)); - object.setInternalError(Boolean.TRUE); - } catch (ValidationFailedException e) { - isTransactionSuccessful=false; - description=PlatformErrorMessages.INDIVIDUAL_BIOMETRIC_AUTHENTICATION_FAILED.getMessage(); - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), code, registrationId, - description + e.getMessage() + ExceptionUtils.getStackTrace(e)); - object.setInternalError(Boolean.TRUE); - - } catch (Exception ex) { - registrationStatusDto.setSubStatusCode(StatusUtil.UNKNOWN_EXCEPTION_OCCURED.getCode()); - registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.name()); - registrationStatusDto.setStatusComment(trimExceptionMessage - .trimExceptionMessage(StatusUtil.UNKNOWN_EXCEPTION_OCCURED.getMessage() + ex.getMessage())); - registrationStatusDto.setLatestTransactionStatusCode( - registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.EXCEPTION)); - code = PlatformErrorMessages.BIOMETRIC_AUTHENTICATION_FAILED.getCode(); - description = PlatformErrorMessages.BIOMETRIC_AUTHENTICATION_FAILED.getMessage(); - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), code, registrationId, - description + ex.getMessage() + ExceptionUtils.getStackTrace(ex)); - object.setInternalError(Boolean.TRUE); - } finally { - if (object.getInternalError()) { - updateErrorFlags(registrationStatusDto, object); - } - /** Module-Id can be Both Success/Error code */ - String moduleId = isTransactionSuccessful - ? PlatformSuccessMessages.RPR_PKR_BIOMETRIC_AUTHENTICATION.getCode() - : code; - String moduleName = ModuleName.BIOMETRIC_AUTHENTICATION.toString(); - registrationStatusService.updateRegistrationStatus(registrationStatusDto, moduleId, moduleName); - description = isTransactionSuccessful - ? PlatformSuccessMessages.RPR_PKR_BIOMETRIC_AUTHENTICATION.getMessage() - : description; - String eventId = isTransactionSuccessful ? EventId.RPR_402.toString() : EventId.RPR_405.toString(); - String eventName = isTransactionSuccessful ? EventName.UPDATE.toString() : EventName.EXCEPTION.toString(); - String eventType = isTransactionSuccessful ? EventType.BUSINESS.toString() : EventType.SYSTEM.toString(); - - auditLogRequestBuilder.createAuditRequestBuilder(description, eventId, eventName, eventType, moduleId, - moduleName, registrationId); - } - - return object; - } - - private boolean isUpdateAdultPacket(String registartionType, String applicantType) { - return (registartionType.equalsIgnoreCase(RegistrationType.UPDATE.name()) - || registartionType.equalsIgnoreCase(RegistrationType.RES_UPDATE.name())) - && applicantType.equalsIgnoreCase(BiometricAuthenticationConstants.ADULT); - } - - private boolean checkIndividualAuthentication(String registrationId, String process, - InternalRegistrationStatusDto registrationStatusDto) throws IOException, BioTypeException, - AuthSystemException, ApisResourceAccessException, PacketManagerException, JsonProcessingException, CertificateException, NoSuchAlgorithmException,ValidationFailedException,Exception { - - BiometricRecord biometricRecord = packetManagerService.getBiometricsByMappingJsonKey(registrationId, - MappingJsonConstants.AUTHENTICATION_BIOMETRICS, process, ProviderStageName.BIO_AUTH); - if (biometricRecord == null || CollectionUtils.isEmpty(biometricRecord.getSegments())) { - registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.toString()); - registrationStatusDto - .setStatusComment(StatusUtil.BIOMETRIC_AUTHENTICATION_FAILED_FILE_NOT_FOUND.getMessage()); - registrationStatusDto.setSubStatusCode(StatusUtil.BIOMETRIC_AUTHENTICATION_FAILED_FILE_NOT_FOUND.getCode()); - return false; - } - String uin = utility.getUIn(registrationId, process, ProviderStageName.BIO_AUTH); - - bioUtil.authenticateBiometrics(uin,BiometricAuthenticationConstants.INDIVIDUAL_TYPE_UIN,biometricRecord.getSegments(),registrationStatusDto,StatusUtil.INTRODUCER_AUTHENTICATION_FAILED.getMessage(),StatusUtil.INTRODUCER_AUTHENTICATION_FAILED.getCode()); - return true; - } - - private void updateErrorFlags(InternalRegistrationStatusDto registrationStatusDto, MessageDTO object) { - object.setInternalError(true); - if (registrationStatusDto.getLatestTransactionStatusCode() - .equalsIgnoreCase(RegistrationTransactionStatusCode.REPROCESS.toString())) { - object.setIsValid(true); - } else { - object.setIsValid(false); - } - } - +package io.mosip.registration.processor.biometric.authentication.stage; + +import java.io.IOException; +import java.security.NoSuchAlgorithmException; +import java.security.cert.CertificateException; + +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.cloud.context.config.annotation.RefreshScope; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.stereotype.Service; +import org.springframework.util.CollectionUtils; + +import io.mosip.kernel.biometrics.entities.BiometricRecord; +import io.mosip.kernel.core.logger.spi.Logger; +import io.mosip.kernel.core.util.exception.JsonProcessingException; +import io.mosip.registration.processor.biometric.authentication.constants.BiometricAuthenticationConstants; +import io.mosip.registration.processor.core.abstractverticle.MessageBusAddress; +import io.mosip.registration.processor.core.abstractverticle.MessageDTO; +import io.mosip.registration.processor.core.abstractverticle.MosipEventBus; +import io.mosip.registration.processor.core.abstractverticle.MosipRouter; +import io.mosip.registration.processor.core.abstractverticle.MosipVerticleAPIManager; +import io.mosip.registration.processor.core.code.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.ProviderStageName; +import io.mosip.registration.processor.core.constant.RegistrationType; +import io.mosip.registration.processor.core.exception.ApisResourceAccessException; +import io.mosip.registration.processor.core.exception.AuthSystemException; +import io.mosip.registration.processor.core.exception.BioTypeException; +import io.mosip.registration.processor.core.exception.PacketManagerException; +import io.mosip.registration.processor.core.exception.ValidationFailedException; +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.RegProcessorLogger; +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.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.rest.client.audit.builder.AuditLogRequestBuilder; +import io.mosip.registration.processor.status.code.RegistrationStatusCode; +import io.mosip.registration.processor.status.dto.InternalRegistrationStatusDto; +import io.mosip.registration.processor.status.dto.RegistrationStatusDto; +import io.mosip.registration.processor.status.dto.SyncRegistrationDto; +import io.mosip.registration.processor.status.dto.SyncResponseDto; +import io.mosip.registration.processor.status.entity.SyncRegistrationEntity; +import io.mosip.registration.processor.status.service.RegistrationStatusService; +import io.mosip.registration.processor.status.service.SyncRegistrationService; + +@RefreshScope +@Service +@Configuration +@ComponentScan(basePackages = { "${mosip.auth.adapter.impl.basepackage}", + "io.mosip.registration.processor.biometric.authentication.config", + "io.mosip.registration.processor.status.config", "io.mosip.registration.processor.rest.client.config", + "io.mosip.registration.processor.packet.storage.config", "io.mosip.registration.processor.core.config", + "io.mosip.registration.processor.core.kernel.beans", "io.mosip.kernel.packetmanager.config", + "io.mosip.kernel.biosdk.provider.impl" }) +public class BiometricAuthenticationStage extends MosipVerticleAPIManager { + private static Logger regProcLogger = RegProcessorLogger.getLogger(BiometricAuthenticationStage.class); + private static final String STAGE_PROPERTY_PREFIX = "mosip.regproc.biometric.authentication."; + private static final String ADULT_BIOMETRIC_UPDATE = "as adult has come for biometric update"; + @Autowired + AuditLogRequestBuilder auditLogRequestBuilder; + + @Autowired + private Utilities utility; + + /** The registration status service. */ + @Autowired + RegistrationStatusService registrationStatusService; + + @Autowired + private BioSdkUtil bioUtil; + + @Autowired + private PriorityBasedPacketManagerService packetManagerService; + + @Autowired + RegistrationExceptionMapperUtil registrationStatusMapperUtil; + + @Value("${vertx.cluster.configuration}") + private String clusterManagerUrl; + + @Value("${mosip.kernel.applicant.type.age.limit}") + private String ageLimit; + + /** worker pool size. */ + @Value("${worker.pool.size}") + private Integer workerPoolSize; + + /** + * After this time intervel, message should be considered as expired (In + * seconds). + */ + @Value("${mosip.regproc.biometric.authentication.message.expiry-time-limit}") + private Long messageExpiryTimeLimit; + + /** The mosip event bus. */ + MosipEventBus mosipEventBus = null; + + /** Mosip router for APIs */ + @Autowired + MosipRouter router; + + @Autowired + private SyncRegistrationService syncRegistrationservice; + + public void deployVerticle() { + mosipEventBus = this.getEventBus(this, clusterManagerUrl, workerPoolSize); + this.consumeAndSend(mosipEventBus, MessageBusAddress.BIOMETRIC_AUTHENTICATION_BUS_IN, + MessageBusAddress.BIOMETRIC_AUTHENTICATION_BUS_OUT, messageExpiryTimeLimit); + } + + @Override + public void start() { + router.setRoute(this.postUrl(getVertx(), MessageBusAddress.BIOMETRIC_AUTHENTICATION_BUS_IN, + MessageBusAddress.BIOMETRIC_AUTHENTICATION_BUS_OUT)); + this.createServer(router.getRouter(), getPort()); + } + + @Override + protected String getPropertyPrefix() { + return STAGE_PROPERTY_PREFIX; + } + + @Override + public MessageDTO process(MessageDTO object) { + TrimExceptionMessage trimExceptionMessage = new TrimExceptionMessage(); + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), "", + "BiometricAuthenticationStage::BiometricAuthenticationStage::entry"); + String registrationId = object.getRid(); + object.setMessageBusAddress(MessageBusAddress.BIOMETRIC_AUTHENTICATION_BUS_IN); + object.setIsValid(Boolean.FALSE); + object.setInternalError(Boolean.FALSE); + InternalRegistrationStatusDto registrationStatusDto = registrationStatusService.getRegistrationStatus( + registrationId, object.getReg_type(), object.getIteration(), object.getWorkflowInstanceId()); + + registrationStatusDto + .setLatestTransactionTypeCode(RegistrationTransactionTypeCode.BIOMETRIC_AUTHENTICATION.toString()); + registrationStatusDto.setRegistrationStageName(getStageName()); + SyncRegistrationEntity regEntity = syncRegistrationservice + .findByWorkflowInstanceId(object.getWorkflowInstanceId()); + String description = ""; + String code = ""; + boolean isBioAuthSkipped = false; + boolean isTransactionSuccessful = false; + + try { + String process = registrationStatusDto.getRegistrationType(); + String registartionType = regEntity.getRegistrationType(); + int applicantAge = utility.getApplicantAge(registrationId, process, ProviderStageName.BIO_AUTH); + int childAgeLimit = Integer.parseInt(ageLimit); + String applicantType = BiometricAuthenticationConstants.ADULT; + if (applicantAge <= childAgeLimit && applicantAge >= 0) { + applicantType = BiometricAuthenticationConstants.CHILD; + } + if (isUpdateAdultPacket(registartionType, applicantType)) { + + String biometricsLabel = packetManagerService.getFieldByMappingJsonKey(registrationId, + MappingJsonConstants.INDIVIDUAL_BIOMETRICS, registrationStatusDto.getRegistrationType(), + ProviderStageName.BIO_AUTH); + if (StringUtils.isEmpty(biometricsLabel)) { + isTransactionSuccessful = checkIndividualAuthentication(registrationId, process, + registrationStatusDto); + description = isTransactionSuccessful + ? PlatformSuccessMessages.RPR_PKR_BIOMETRIC_AUTHENTICATION.getMessage() + : PlatformErrorMessages.BIOMETRIC_AUTHENTICATION_FAILED.getMessage(); + } else { + String individualBiometricsFileName = JsonUtil.getJSONValue( + JsonUtil.readValueWithUnknownProperties(biometricsLabel, JSONObject.class), + MappingJsonConstants.VALUE); + if (individualBiometricsFileName != null && !individualBiometricsFileName.isEmpty()) { + BiometricRecord biometricRecord = packetManagerService.getBiometricsByMappingJsonKey( + registrationId, MappingJsonConstants.INDIVIDUAL_BIOMETRICS, process, + ProviderStageName.BIO_AUTH); + if (biometricRecord == null || biometricRecord.getSegments() == null + || biometricRecord.getSegments().isEmpty()) { + isTransactionSuccessful = false; + description = StatusUtil.BIOMETRIC_FILE_NOT_FOUND.getMessage(); + regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString(), registrationId, description); + registrationStatusDto.setStatusComment(description); + registrationStatusDto.setSubStatusCode(StatusUtil.BIOMETRIC_FILE_NOT_FOUND.getCode()); + } else { + isBioAuthSkipped = true; + regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString(), registrationId, + "BiometricAuthenticationStage::skipped"); + isTransactionSuccessful = true; + description = StatusUtil.BIOMETRIC_AUTHENTICATION_SKIPPED.getMessage() + + ADULT_BIOMETRIC_UPDATE; + } + } else { + isTransactionSuccessful = true; + description = PlatformSuccessMessages.RPR_PKR_BIOMETRIC_AUTHENTICATION.getMessage(); + } + } + } + + else { + isBioAuthSkipped = true; + isTransactionSuccessful = true; + regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString(), registrationId, + "BiometricAuthenticationStage::success"); + if (applicantType.equals(BiometricAuthenticationConstants.CHILD)) { + description = BiometricAuthenticationConstants.CHILD_PACKET_DESCRIPTION; + + } else + description = StatusUtil.BIOMETRIC_AUTHENTICATION_SKIPPED.getMessage(); + } + + if (isTransactionSuccessful) { + object.setIsValid(Boolean.TRUE); + registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.name()); + registrationStatusDto + .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.SUCCESS.toString()); + if (isBioAuthSkipped) { + registrationStatusDto.setSubStatusCode(StatusUtil.BIOMETRIC_AUTHENTICATION_SKIPPED.getCode()); + registrationStatusDto + .setStatusComment(StatusUtil.BIOMETRIC_AUTHENTICATION_SKIPPED.getMessage() + description); + } else { + registrationStatusDto.setSubStatusCode(StatusUtil.BIOMETRIC_AUTHENTICATION_SUCCESS.getCode()); + registrationStatusDto.setStatusComment(StatusUtil.BIOMETRIC_AUTHENTICATION_SUCCESS.getMessage()); + } + } else { + registrationStatusDto + .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.FAILED.toString()); + registrationStatusDto.setStatusCode(RegistrationTransactionStatusCode.FAILED.toString()); + } + + } catch (IOException | NoSuchAlgorithmException e) { + registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.name()); + registrationStatusDto.setSubStatusCode(StatusUtil.IO_EXCEPTION.getCode()); + registrationStatusDto.setStatusComment( + trimExceptionMessage.trimExceptionMessage(StatusUtil.IO_EXCEPTION.getMessage() + e.getMessage())); + object.setInternalError(Boolean.TRUE); + registrationStatusDto.setLatestTransactionStatusCode( + registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.IOEXCEPTION)); + code = PlatformErrorMessages.BIOMETRIC_AUTHENTICATION_IOEXCEPTION.getCode(); + description = PlatformErrorMessages.BIOMETRIC_AUTHENTICATION_IOEXCEPTION.getMessage(); + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), code, registrationId, + description + e.getMessage() + ExceptionUtils.getStackTrace(e)); + } catch (JsonProcessingException e) { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + registrationId, + RegistrationStatusCode.FAILED.toString() + e.getMessage() + ExceptionUtils.getStackTrace(e)); + registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.toString()); + registrationStatusDto.setStatusComment(trimExceptionMessage + .trimExceptionMessage(StatusUtil.JSON_PARSING_EXCEPTION.getMessage() + e.getMessage())); + registrationStatusDto.setSubStatusCode(StatusUtil.JSON_PARSING_EXCEPTION.getCode()); + registrationStatusDto.setLatestTransactionStatusCode(registrationStatusMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.JSON_PROCESSING_EXCEPTION)); + isTransactionSuccessful = false; + description = (PlatformErrorMessages.RPR_SYS_JSON_PARSING_EXCEPTION.getMessage()); + code = (PlatformErrorMessages.RPR_SYS_JSON_PARSING_EXCEPTION.getCode()); + object.setInternalError(Boolean.TRUE); + object.setRid(registrationStatusDto.getRegistrationId()); + } catch (PacketManagerException e) { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + registrationId, + RegistrationStatusCode.FAILED.toString() + e.getMessage() + ExceptionUtils.getStackTrace(e)); + registrationStatusDto.setStatusComment(trimExceptionMessage + .trimExceptionMessage(StatusUtil.PACKET_MANAGER_EXCEPTION.getMessage() + e.getMessage())); + registrationStatusDto.setSubStatusCode(StatusUtil.PACKET_MANAGER_EXCEPTION.getCode()); + registrationStatusDto.setLatestTransactionStatusCode( + registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.PACKET_MANAGER_EXCEPTION)); + registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.name()); + description = (PlatformErrorMessages.PACKET_MANAGER_EXCEPTION.getMessage()); + code = (PlatformErrorMessages.PACKET_MANAGER_EXCEPTION.getCode()); + object.setInternalError(Boolean.TRUE); + object.setRid(registrationStatusDto.getRegistrationId()); + } catch (ApisResourceAccessException e) { + registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.name()); + registrationStatusDto.setSubStatusCode(StatusUtil.API_RESOUCE_ACCESS_FAILED.getCode()); + registrationStatusDto.setStatusComment(trimExceptionMessage + .trimExceptionMessage(StatusUtil.API_RESOUCE_ACCESS_FAILED.getMessage() + e.getMessage())); + registrationStatusDto.setLatestTransactionStatusCode(registrationStatusMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.APIS_RESOURCE_ACCESS_EXCEPTION)); + code = PlatformErrorMessages.BIOMETRIC_AUTHENTICATION_API_RESOURCE_EXCEPTION.getCode(); + description = PlatformErrorMessages.BIOMETRIC_AUTHENTICATION_API_RESOURCE_EXCEPTION.getMessage(); + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), code, registrationId, + description + e.getMessage() + ExceptionUtils.getStackTrace(e)); + object.setInternalError(Boolean.TRUE); + } catch (AuthSystemException e) { + registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.name()); + registrationStatusDto.setSubStatusCode(StatusUtil.AUTH_SYSTEM_EXCEPTION.getCode()); + registrationStatusDto.setStatusComment(trimExceptionMessage + .trimExceptionMessage(StatusUtil.AUTH_SYSTEM_EXCEPTION.getMessage() + e.getMessage())); + registrationStatusDto.setLatestTransactionStatusCode( + registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.AUTH_SYSTEM_EXCEPTION)); + code = PlatformErrorMessages.BIOMETRIC_AUTHENTICATION_AUTH_SYSTEM_EXCEPTION.getCode(); + description = PlatformErrorMessages.BIOMETRIC_AUTHENTICATION_AUTH_SYSTEM_EXCEPTION.getMessage(); + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), code, registrationId, + description + e.getMessage() + ExceptionUtils.getStackTrace(e)); + object.setInternalError(Boolean.TRUE); + } catch (ValidationFailedException e) { + isTransactionSuccessful=false; + description=PlatformErrorMessages.INDIVIDUAL_BIOMETRIC_AUTHENTICATION_FAILED.getMessage(); + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), code, registrationId, + description + e.getMessage() + ExceptionUtils.getStackTrace(e)); + object.setInternalError(Boolean.TRUE); + + } catch (Exception ex) { + registrationStatusDto.setSubStatusCode(StatusUtil.UNKNOWN_EXCEPTION_OCCURED.getCode()); + registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.name()); + registrationStatusDto.setStatusComment(trimExceptionMessage + .trimExceptionMessage(StatusUtil.UNKNOWN_EXCEPTION_OCCURED.getMessage() + ex.getMessage())); + registrationStatusDto.setLatestTransactionStatusCode( + registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.EXCEPTION)); + code = PlatformErrorMessages.BIOMETRIC_AUTHENTICATION_FAILED.getCode(); + description = PlatformErrorMessages.BIOMETRIC_AUTHENTICATION_FAILED.getMessage(); + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), code, registrationId, + description + ex.getMessage() + ExceptionUtils.getStackTrace(ex)); + object.setInternalError(Boolean.TRUE); + } finally { + if (object.getInternalError()) { + updateErrorFlags(registrationStatusDto, object); + } + /** Module-Id can be Both Success/Error code */ + String moduleId = isTransactionSuccessful + ? PlatformSuccessMessages.RPR_PKR_BIOMETRIC_AUTHENTICATION.getCode() + : code; + String moduleName = ModuleName.BIOMETRIC_AUTHENTICATION.toString(); + registrationStatusService.updateRegistrationStatus(registrationStatusDto, moduleId, moduleName); + description = isTransactionSuccessful + ? PlatformSuccessMessages.RPR_PKR_BIOMETRIC_AUTHENTICATION.getMessage() + : description; + String eventId = isTransactionSuccessful ? EventId.RPR_402.toString() : EventId.RPR_405.toString(); + String eventName = isTransactionSuccessful ? EventName.UPDATE.toString() : EventName.EXCEPTION.toString(); + String eventType = isTransactionSuccessful ? EventType.BUSINESS.toString() : EventType.SYSTEM.toString(); + + auditLogRequestBuilder.createAuditRequestBuilder(description, eventId, eventName, eventType, moduleId, + moduleName, registrationId); + } + + return object; + } + + private boolean isUpdateAdultPacket(String registartionType, String applicantType) { + return (registartionType.equalsIgnoreCase(RegistrationType.UPDATE.name()) + || registartionType.equalsIgnoreCase(RegistrationType.RES_UPDATE.name())) + && applicantType.equalsIgnoreCase(BiometricAuthenticationConstants.ADULT); + } + + private boolean checkIndividualAuthentication(String registrationId, String process, + InternalRegistrationStatusDto registrationStatusDto) throws IOException, BioTypeException, + AuthSystemException, ApisResourceAccessException, PacketManagerException, JsonProcessingException, CertificateException, NoSuchAlgorithmException,ValidationFailedException,Exception { + + BiometricRecord biometricRecord = packetManagerService.getBiometricsByMappingJsonKey(registrationId, + MappingJsonConstants.AUTHENTICATION_BIOMETRICS, process, ProviderStageName.BIO_AUTH); + if (biometricRecord == null || CollectionUtils.isEmpty(biometricRecord.getSegments())) { + registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.toString()); + registrationStatusDto + .setStatusComment(StatusUtil.BIOMETRIC_AUTHENTICATION_FAILED_FILE_NOT_FOUND.getMessage()); + registrationStatusDto.setSubStatusCode(StatusUtil.BIOMETRIC_AUTHENTICATION_FAILED_FILE_NOT_FOUND.getCode()); + return false; + } + String uin = utility.getUIn(registrationId, process, ProviderStageName.BIO_AUTH); + + bioUtil.authenticateBiometrics(uin,BiometricAuthenticationConstants.INDIVIDUAL_TYPE_UIN,biometricRecord.getSegments(),registrationStatusDto,StatusUtil.INTRODUCER_AUTHENTICATION_FAILED.getMessage(),StatusUtil.INTRODUCER_AUTHENTICATION_FAILED.getCode()); + return true; + } + + private void updateErrorFlags(InternalRegistrationStatusDto registrationStatusDto, MessageDTO object) { + object.setInternalError(true); + if (registrationStatusDto.getLatestTransactionStatusCode() + .equalsIgnoreCase(RegistrationTransactionStatusCode.REPROCESS.toString())) { + object.setIsValid(true); + } else { + object.setIsValid(false); + } + } + } \ No newline at end of file diff --git a/registration-processor/core-processor/registration-processor-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 fc7425c53f4..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 @@ -618,4 +618,12 @@ public void testPacketManagerException() throws ApisResourceAccessException, IOE assertTrue(messageDto.getInternalError()); assertTrue(messageDto.getIsValid()); } + + @Test + public void testChildPacketWithLessThanOneYear() throws ApisResourceAccessException, JsonProcessingException, io.mosip.kernel.core.exception.IOException, PacketManagerException, IOException { + when(regentity.getRegistrationType()).thenReturn("UPDATE"); + when(utility.getApplicantAge(anyString(),anyString(), any())).thenReturn(0); + MessageDTO messageDto = biometricAuthenticationStage.process(dto); + assertTrue(messageDto.getIsValid()); + } } From 43d4129b5acfbeaea4a7784dbb98930927a3497b Mon Sep 17 00:00:00 2001 From: Rakshithb1 <79500257+Rakshithb1@users.noreply.github.com> Date: Fri, 24 Nov 2023 16:46:18 +0530 Subject: [PATCH 101/133] [MOSIP-29918] added db-test.yml (#1794) Signed-off-by: Rakshithb1 --- .github/workflows/db-test.yml | 39 +++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 .github/workflows/db-test.yml diff --git a/.github/workflows/db-test.yml b/.github/workflows/db-test.yml new file mode 100644 index 00000000000..35a2e6a3585 --- /dev/null +++ b/.github/workflows/db-test.yml @@ -0,0 +1,39 @@ +name: PostgreSQL Test + +on: + release: + types: [published] + pull_request: + types: [opened, reopened, synchronize] + paths: + - 'db_scripts/**' + workflow_dispatch: + inputs: + message: + description: 'Message for manually triggering' + required: false + default: 'Triggered for Updates' + type: string + push: + branches: + - '!release-branch' + - release* + - master + - 1.* + - develop* + - MOSIP* + paths: + - 'db_scripts/**' + +jobs: + build-db-test: + strategy: + matrix: + include: + - DB_LOCATION: 'db_scripts/mosip_regprc' + DB_NAME: 'mosip_regprc' + fail-fast: false + name: ${{ matrix.DB_NAME }} + uses: mosip/kattu/.github/workflows/db-test.yml@master + with: + DB_LOCATION: ${{ matrix.DB_LOCATION}} From ee26da3d85ab4cc2cc29e5d922957b7e5b87f93f Mon Sep 17 00:00:00 2001 From: techno-467 Date: Tue, 19 Dec 2023 15:33:24 +0530 Subject: [PATCH 102/133] [DSD-3932] removed release-changes.yml, tag.yml and updated push-trigger.yml file Signed-off-by: techno-467 --- .github/workflows/push-trigger.yml | 4 ++-- .github/workflows/release-changes.yml | 26 --------------------- .github/workflows/tag.yaml | 33 --------------------------- 3 files changed, 2 insertions(+), 61 deletions(-) delete mode 100644 .github/workflows/release-changes.yml delete mode 100644 .github/workflows/tag.yaml diff --git a/.github/workflows/push-trigger.yml b/.github/workflows/push-trigger.yml index ab05c642dcc..fd0f12aa220 100644 --- a/.github/workflows/push-trigger.yml +++ b/.github/workflows/push-trigger.yml @@ -4,7 +4,7 @@ on: release: types: [published] pull_request: - types: [opened] + types: [opened, reopened, synchronize] workflow_dispatch: inputs: @@ -35,7 +35,7 @@ jobs: SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK }} publish_to_nexus: - if: "${{ !contains(github.ref, 'master') && github.event_name != 'pull_request' }}" + if: "${{ !contains(github.ref, 'master') && github.event_name != 'pull_request' && github.event_name != 'release' && github.event_name != 'prerelease' && github.event_name != 'publish' }}" needs: build-maven-registration uses: mosip/kattu/.github/workflows/maven-publish-to-nexus.yml@master with: diff --git a/.github/workflows/release-changes.yml b/.github/workflows/release-changes.yml deleted file mode 100644 index 2579ea836f1..00000000000 --- a/.github/workflows/release-changes.yml +++ /dev/null @@ -1,26 +0,0 @@ -name: Release/pre-release Preparation. - -on: - workflow_dispatch: - inputs: - MESSAGE: - description: 'Triggered for release or pe-release' - required: false - default: 'Release Preparation' - RELEASE_TAG: - description: 'tag to update' - required: true - SNAPSHOT_TAG: - description: 'tag to be replaced' - required: true - BASE: - description: 'base branch for PR' - required: true -jobs: - maven-release-preparation: - uses: mosip/kattu/.github/workflows/release-changes.yml@master - with: - MESSAGE: ${{ inputs.MESSAGE }} - RELEASE_TAG: ${{ inputs.RELEASE_TAG }} - SNAPSHOT_TAG: ${{ inputs.SNAPSHOT_TAG }} - BASE: ${{ inputs.BASE }} \ No newline at end of file diff --git a/.github/workflows/tag.yaml b/.github/workflows/tag.yaml deleted file mode 100644 index 73c55b03d8f..00000000000 --- a/.github/workflows/tag.yaml +++ /dev/null @@ -1,33 +0,0 @@ -name: Tagging of repos - -on: - workflow_dispatch: - inputs: - TAG: - description: 'Tag to be published' - required: true - type: string - BODY: - description: 'Release body message' - required: true - default: 'Changes in this Release' - type: string - PRE_RELEASE: - description: 'Pre-release? True/False' - required: true - default: False - type: string - DRAFT: - description: 'Draft? True/False' - required: false - default: False - type: string - -jobs: - tag-branch: - uses: mosip/kattu/.github/workflows/tag.yml@master - with: - TAG: ${{ inputs.TAG }} - BODY: ${{ inputs.BODY }} - PRE_RELEASE: ${{ inputs.PRE_RELEASE }} - DRAFT: ${{ inputs.DRAFT }} \ No newline at end of file From af48a4d6e7ffd99020f2272c356e06b4b6215472 Mon Sep 17 00:00:00 2001 From: PRAFUL RAKHADE <99539100+Prafulrakhade@users.noreply.github.com> Date: Thu, 21 Dec 2023 08:11:02 +0530 Subject: [PATCH 103/133] [DSD-3932] removed release-changes.yml, tag.yml and updated push-trigger.yml file (#1808) Signed-off-by: techno-467 --- .github/workflows/push-trigger.yml | 4 ++-- .github/workflows/release-changes.yml | 26 --------------------- .github/workflows/tag.yaml | 33 --------------------------- 3 files changed, 2 insertions(+), 61 deletions(-) delete mode 100644 .github/workflows/release-changes.yml delete mode 100644 .github/workflows/tag.yaml diff --git a/.github/workflows/push-trigger.yml b/.github/workflows/push-trigger.yml index ab05c642dcc..fd0f12aa220 100644 --- a/.github/workflows/push-trigger.yml +++ b/.github/workflows/push-trigger.yml @@ -4,7 +4,7 @@ on: release: types: [published] pull_request: - types: [opened] + types: [opened, reopened, synchronize] workflow_dispatch: inputs: @@ -35,7 +35,7 @@ jobs: SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK }} publish_to_nexus: - if: "${{ !contains(github.ref, 'master') && github.event_name != 'pull_request' }}" + if: "${{ !contains(github.ref, 'master') && github.event_name != 'pull_request' && github.event_name != 'release' && github.event_name != 'prerelease' && github.event_name != 'publish' }}" needs: build-maven-registration uses: mosip/kattu/.github/workflows/maven-publish-to-nexus.yml@master with: diff --git a/.github/workflows/release-changes.yml b/.github/workflows/release-changes.yml deleted file mode 100644 index 2579ea836f1..00000000000 --- a/.github/workflows/release-changes.yml +++ /dev/null @@ -1,26 +0,0 @@ -name: Release/pre-release Preparation. - -on: - workflow_dispatch: - inputs: - MESSAGE: - description: 'Triggered for release or pe-release' - required: false - default: 'Release Preparation' - RELEASE_TAG: - description: 'tag to update' - required: true - SNAPSHOT_TAG: - description: 'tag to be replaced' - required: true - BASE: - description: 'base branch for PR' - required: true -jobs: - maven-release-preparation: - uses: mosip/kattu/.github/workflows/release-changes.yml@master - with: - MESSAGE: ${{ inputs.MESSAGE }} - RELEASE_TAG: ${{ inputs.RELEASE_TAG }} - SNAPSHOT_TAG: ${{ inputs.SNAPSHOT_TAG }} - BASE: ${{ inputs.BASE }} \ No newline at end of file diff --git a/.github/workflows/tag.yaml b/.github/workflows/tag.yaml deleted file mode 100644 index 73c55b03d8f..00000000000 --- a/.github/workflows/tag.yaml +++ /dev/null @@ -1,33 +0,0 @@ -name: Tagging of repos - -on: - workflow_dispatch: - inputs: - TAG: - description: 'Tag to be published' - required: true - type: string - BODY: - description: 'Release body message' - required: true - default: 'Changes in this Release' - type: string - PRE_RELEASE: - description: 'Pre-release? True/False' - required: true - default: False - type: string - DRAFT: - description: 'Draft? True/False' - required: false - default: False - type: string - -jobs: - tag-branch: - uses: mosip/kattu/.github/workflows/tag.yml@master - with: - TAG: ${{ inputs.TAG }} - BODY: ${{ inputs.BODY }} - PRE_RELEASE: ${{ inputs.PRE_RELEASE }} - DRAFT: ${{ inputs.DRAFT }} \ No newline at end of file From df170b56dcf66639958d0dd53dbb92d1114572a6 Mon Sep 17 00:00:00 2001 From: Chandra Keshav Mishra Date: Thu, 21 Dec 2023 10:25:13 +0530 Subject: [PATCH 104/133] Release changes (#1811) * Updated Pom versions for release changes Signed-off-by: GitHub * [DSD-3932] Update pom.xml Signed-off-by: Chandra Keshav Mishra * [DSD-3932] Update pom.xml Signed-off-by: Chandra Keshav Mishra --------- Signed-off-by: GitHub Signed-off-by: Chandra Keshav Mishra Co-authored-by: Prafulrakhade --- .github/workflows/push-trigger.yml | 2 +- pom.xml | 2 +- registration-processor/core-processor/pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../registration-processor-abis/pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- registration-processor/init/pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../mosip-stage-executor/pom.xml | 4 +- registration-processor/pom.xml | 52 +++++++++---------- registration-processor/post-processor/pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- registration-processor/pre-processor/pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../qc-users-manger/pom.xml | 4 +- .../pom.xml | 4 +- .../dependency-reduced-pom.xml | 2 +- .../pom.xml | 6 +-- .../registration-processor-core/pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- registration-processor/stage-groups/pom.xml | 4 +- .../pom.xml | 8 +-- .../pom.xml | 12 ++--- .../pom.xml | 14 ++--- .../pom.xml | 10 ++-- .../pom.xml | 16 +++--- .../pom.xml | 12 ++--- .../pom.xml | 14 ++--- .../workflow-engine/pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- 56 files changed, 163 insertions(+), 163 deletions(-) diff --git a/.github/workflows/push-trigger.yml b/.github/workflows/push-trigger.yml index fd0f12aa220..876c4757fac 100644 --- a/.github/workflows/push-trigger.yml +++ b/.github/workflows/push-trigger.yml @@ -43,7 +43,7 @@ jobs: secrets: OSSRH_USER: ${{ secrets.OSSRH_USER }} OSSRH_SECRET: ${{ secrets.OSSRH_SECRET }} - OSSRH_URL: ${{ secrets.OSSRH_SNAPSHOT_URL }} + OSSRH_URL: ${{ secrets.RELEASE_URL }} OSSRH_TOKEN: ${{ secrets.OSSRH_TOKEN }} GPG_SECRET: ${{ secrets.GPG_SECRET }} SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK }} diff --git a/pom.xml b/pom.xml index 965197ff54e..74d8bfe6922 100644 --- a/pom.xml +++ b/pom.xml @@ -4,7 +4,7 @@ 4.0.0 io.mosip registration - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 pom MOSIP Registration Parent POM diff --git a/registration-processor/core-processor/pom.xml b/registration-processor/core-processor/pom.xml index 1e70249927a..bf9c23de124 100644 --- a/registration-processor/core-processor/pom.xml +++ b/registration-processor/core-processor/pom.xml @@ -5,9 +5,9 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 core-processor core-processor diff --git a/registration-processor/core-processor/registration-processor-abis-handler-stage/pom.xml b/registration-processor/core-processor/registration-processor-abis-handler-stage/pom.xml index b993ca03858..85a81893eae 100644 --- a/registration-processor/core-processor/registration-processor-abis-handler-stage/pom.xml +++ b/registration-processor/core-processor/registration-processor-abis-handler-stage/pom.xml @@ -5,11 +5,11 @@ io.mosip.registrationprocessor core-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 registration-processor-abis-handler-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 jar UTF-8 diff --git a/registration-processor/core-processor/registration-processor-abis-middleware-stage/pom.xml b/registration-processor/core-processor/registration-processor-abis-middleware-stage/pom.xml index e50a32b7d0d..fe6903760b9 100644 --- a/registration-processor/core-processor/registration-processor-abis-middleware-stage/pom.xml +++ b/registration-processor/core-processor/registration-processor-abis-middleware-stage/pom.xml @@ -5,10 +5,10 @@ io.mosip.registrationprocessor core-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 registration-processor-abis-middleware-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 jar UTF-8 diff --git a/registration-processor/core-processor/registration-processor-abis/pom.xml b/registration-processor/core-processor/registration-processor-abis/pom.xml index 29a7bcb63ff..44478edfd46 100644 --- a/registration-processor/core-processor/registration-processor-abis/pom.xml +++ b/registration-processor/core-processor/registration-processor-abis/pom.xml @@ -8,10 +8,10 @@ io.mosip.registrationprocessor core-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 registration-processor-abis - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 registration-processor-abis UTF-8 diff --git a/registration-processor/core-processor/registration-processor-bio-dedupe-stage/pom.xml b/registration-processor/core-processor/registration-processor-bio-dedupe-stage/pom.xml index 51b750768e9..6c7f16156f5 100644 --- a/registration-processor/core-processor/registration-processor-bio-dedupe-stage/pom.xml +++ b/registration-processor/core-processor/registration-processor-bio-dedupe-stage/pom.xml @@ -5,11 +5,11 @@ io.mosip.registrationprocessor core-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 registration-processor-bio-dedupe-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 jar UTF-8 diff --git a/registration-processor/core-processor/registration-processor-biometric-authentication-stage/pom.xml b/registration-processor/core-processor/registration-processor-biometric-authentication-stage/pom.xml index 754cbb84860..fcfdda19409 100644 --- a/registration-processor/core-processor/registration-processor-biometric-authentication-stage/pom.xml +++ b/registration-processor/core-processor/registration-processor-biometric-authentication-stage/pom.xml @@ -5,10 +5,10 @@ io.mosip.registrationprocessor core-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 registration-processor-biometric-authentication-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 jar UTF-8 diff --git a/registration-processor/core-processor/registration-processor-biometric-extraction-stage/pom.xml b/registration-processor/core-processor/registration-processor-biometric-extraction-stage/pom.xml index c22795794a5..44498c08008 100644 --- a/registration-processor/core-processor/registration-processor-biometric-extraction-stage/pom.xml +++ b/registration-processor/core-processor/registration-processor-biometric-extraction-stage/pom.xml @@ -5,10 +5,10 @@ io.mosip.registrationprocessor core-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 registration-processor-biometric-extraction-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 jar UTF-8 diff --git a/registration-processor/core-processor/registration-processor-demo-dedupe-stage/pom.xml b/registration-processor/core-processor/registration-processor-demo-dedupe-stage/pom.xml index 80e30419cfa..50a6e2e0bbe 100644 --- a/registration-processor/core-processor/registration-processor-demo-dedupe-stage/pom.xml +++ b/registration-processor/core-processor/registration-processor-demo-dedupe-stage/pom.xml @@ -5,10 +5,10 @@ io.mosip.registrationprocessor core-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 registration-processor-demo-dedupe-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 jar UTF-8 diff --git a/registration-processor/core-processor/registration-processor-finalization-stage/pom.xml b/registration-processor/core-processor/registration-processor-finalization-stage/pom.xml index fe52552ff90..a28f5d90d57 100644 --- a/registration-processor/core-processor/registration-processor-finalization-stage/pom.xml +++ b/registration-processor/core-processor/registration-processor-finalization-stage/pom.xml @@ -5,11 +5,11 @@ io.mosip.registrationprocessor core-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 registration-processor-finalization-stage registration-processor-finalization-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 jar UTF-8 diff --git a/registration-processor/core-processor/registration-processor-manual-adjudication-stage/pom.xml b/registration-processor/core-processor/registration-processor-manual-adjudication-stage/pom.xml index 796d3317026..fce39b78f54 100644 --- a/registration-processor/core-processor/registration-processor-manual-adjudication-stage/pom.xml +++ b/registration-processor/core-processor/registration-processor-manual-adjudication-stage/pom.xml @@ -8,11 +8,11 @@ io.mosip.registrationprocessor core-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 registration-processor-manual-adjudication-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 UTF-8 diff --git a/registration-processor/core-processor/registration-processor-uin-generator-stage/pom.xml b/registration-processor/core-processor/registration-processor-uin-generator-stage/pom.xml index 3a163267596..4718decb596 100644 --- a/registration-processor/core-processor/registration-processor-uin-generator-stage/pom.xml +++ b/registration-processor/core-processor/registration-processor-uin-generator-stage/pom.xml @@ -4,10 +4,10 @@ io.mosip.registrationprocessor core-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 registration-processor-uin-generator-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 jar UTF-8 diff --git a/registration-processor/core-processor/registration-processor-verification-stage/pom.xml b/registration-processor/core-processor/registration-processor-verification-stage/pom.xml index 804ff7f221b..d2c335892f2 100644 --- a/registration-processor/core-processor/registration-processor-verification-stage/pom.xml +++ b/registration-processor/core-processor/registration-processor-verification-stage/pom.xml @@ -8,11 +8,11 @@ io.mosip.registrationprocessor core-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 registration-processor-verification-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 UTF-8 diff --git a/registration-processor/init/pom.xml b/registration-processor/init/pom.xml index e0cab04f77e..ca7568449f2 100644 --- a/registration-processor/init/pom.xml +++ b/registration-processor/init/pom.xml @@ -6,10 +6,10 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 init - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 UTF-8 diff --git a/registration-processor/init/registration-processor-packet-receiver-stage/pom.xml b/registration-processor/init/registration-processor-packet-receiver-stage/pom.xml index 65c49693beb..857c65202ae 100644 --- a/registration-processor/init/registration-processor-packet-receiver-stage/pom.xml +++ b/registration-processor/init/registration-processor-packet-receiver-stage/pom.xml @@ -7,11 +7,11 @@ io.mosip.registrationprocessor init - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 registration-processor-packet-receiver-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 jar registration-processor-packet-receiver-stage diff --git a/registration-processor/init/registration-processor-registration-status-service/pom.xml b/registration-processor/init/registration-processor-registration-status-service/pom.xml index 7d35fa6396c..688979aac3a 100644 --- a/registration-processor/init/registration-processor-registration-status-service/pom.xml +++ b/registration-processor/init/registration-processor-registration-status-service/pom.xml @@ -8,10 +8,10 @@ io.mosip.registrationprocessor init - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 registration-processor-registration-status-service - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 registration-processor-registration-status-service diff --git a/registration-processor/mosip-stage-executor/pom.xml b/registration-processor/mosip-stage-executor/pom.xml index 22617e270bd..c09a699b8f7 100644 --- a/registration-processor/mosip-stage-executor/pom.xml +++ b/registration-processor/mosip-stage-executor/pom.xml @@ -5,11 +5,11 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 mosip-stage-executor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 diff --git a/registration-processor/pom.xml b/registration-processor/pom.xml index e3be909e5d1..a649d38190e 100644 --- a/registration-processor/pom.xml +++ b/registration-processor/pom.xml @@ -5,7 +5,7 @@ io.mosip registration - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 @@ -30,7 +30,7 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 pom registration-processor @@ -128,31 +128,31 @@ 0.1.55 - 1.2.0.1-SNAPSHOT - 1.2.0.1-SNAPSHOT - 1.2.0.1-SNAPSHOT - 1.2.0.1-SNAPSHOT - 1.2.0.1-SNAPSHOT - 1.2.0.1-SNAPSHOT - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 + 1.2.0.1-B3 + 1.2.0.1-B3 + 1.2.0.1-B3 + 1.2.0.1-B3 + 1.2.0.1-B3 + 1.2.0.1-B3 - 1.2.0.1-SNAPSHOT - 1.2.0.1-SNAPSHOT - 1.2.0.1-SNAPSHOT - 1.2.0.1-SNAPSHOT - 1.2.0.1-SNAPSHOT - 1.2.0.1-SNAPSHOT - 1.2.0.1-SNAPSHOT - 1.2.0.1-SNAPSHOT - 1.2.0.1-SNAPSHOT - 1.2.0.1-SNAPSHOT - 1.2.0.1-SNAPSHOT - 1.2.0.1-SNAPSHOT - 1.2.0.1-SNAPSHOT - 1.2.0.1-SNAPSHOT - 1.2.0.1-SNAPSHOT - 1.2.0.1-SNAPSHOT + 1.2.0.1-B2 + 1.2.0.1-B2 + 1.2.0.1-B2 + 1.2.0.1-B2 + 1.2.0.1-B2 + 1.2.0.1-B2 + 1.2.0.1-B3 + 1.2.0.1-B2 + 1.2.0.1-B2 + 1.2.0.1-B2 + 1.2.0.1-B2 + 1.2.0.1-B2 + 1.2.0.1-B2 + 1.2.0.1-B3 + 1.2.0.1-B2 + 1.2.0.1-B2 **/dto/**, **/exception/*Exception.java, **/config/*Config.java, @@ -564,4 +564,4 @@ - \ No newline at end of file + diff --git a/registration-processor/post-processor/pom.xml b/registration-processor/post-processor/pom.xml index 25da34901cd..0a55dd17040 100644 --- a/registration-processor/post-processor/pom.xml +++ b/registration-processor/post-processor/pom.xml @@ -6,9 +6,9 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 post-processor post-processor diff --git a/registration-processor/post-processor/registration-processor-message-sender-stage/pom.xml b/registration-processor/post-processor/registration-processor-message-sender-stage/pom.xml index ddca10912f8..8026fdd5074 100644 --- a/registration-processor/post-processor/registration-processor-message-sender-stage/pom.xml +++ b/registration-processor/post-processor/registration-processor-message-sender-stage/pom.xml @@ -7,11 +7,11 @@ io.mosip.registrationprocessor post-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 registration-processor-message-sender-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 UTF-8 UTF-8 diff --git a/registration-processor/post-processor/registration-processor-printing-stage/pom.xml b/registration-processor/post-processor/registration-processor-printing-stage/pom.xml index 4a9f585821d..5fe9b79df20 100644 --- a/registration-processor/post-processor/registration-processor-printing-stage/pom.xml +++ b/registration-processor/post-processor/registration-processor-printing-stage/pom.xml @@ -6,10 +6,10 @@ io.mosip.registrationprocessor post-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 registration-processor-printing-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 UTF-8 UTF-8 diff --git a/registration-processor/post-processor/registration-processor-registration-transaction-service/pom.xml b/registration-processor/post-processor/registration-processor-registration-transaction-service/pom.xml index 2e3d4210fe5..15993e06a96 100644 --- a/registration-processor/post-processor/registration-processor-registration-transaction-service/pom.xml +++ b/registration-processor/post-processor/registration-processor-registration-transaction-service/pom.xml @@ -5,10 +5,10 @@ io.mosip.registrationprocessor post-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 registration-processor-registration-transaction-service - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 registration-processor-registration-transaction-service UTF-8 diff --git a/registration-processor/pre-processor/pom.xml b/registration-processor/pre-processor/pom.xml index 23941368b71..641eb0338e2 100644 --- a/registration-processor/pre-processor/pom.xml +++ b/registration-processor/pre-processor/pom.xml @@ -7,9 +7,9 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 pre-processor pre-processor diff --git a/registration-processor/pre-processor/registration-processor-cmd-validator-stage/pom.xml b/registration-processor/pre-processor/registration-processor-cmd-validator-stage/pom.xml index 099373ee95f..ecd645121a6 100644 --- a/registration-processor/pre-processor/registration-processor-cmd-validator-stage/pom.xml +++ b/registration-processor/pre-processor/registration-processor-cmd-validator-stage/pom.xml @@ -6,10 +6,10 @@ io.mosip.registrationprocessor pre-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 registration-processor-cmd-validator-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 registration-processor-cmd-validator-stage UTF-8 diff --git a/registration-processor/pre-processor/registration-processor-introducer-validator-stage/pom.xml b/registration-processor/pre-processor/registration-processor-introducer-validator-stage/pom.xml index 39b9fc3ac83..939274addf5 100644 --- a/registration-processor/pre-processor/registration-processor-introducer-validator-stage/pom.xml +++ b/registration-processor/pre-processor/registration-processor-introducer-validator-stage/pom.xml @@ -6,10 +6,10 @@ io.mosip.registrationprocessor pre-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 registration-processor-introducer-validator-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 registration-processor-introducer-validator-stage UTF-8 diff --git a/registration-processor/pre-processor/registration-processor-operator-validator-stage/pom.xml b/registration-processor/pre-processor/registration-processor-operator-validator-stage/pom.xml index 6c2fd429574..83f2f06f324 100644 --- a/registration-processor/pre-processor/registration-processor-operator-validator-stage/pom.xml +++ b/registration-processor/pre-processor/registration-processor-operator-validator-stage/pom.xml @@ -6,10 +6,10 @@ io.mosip.registrationprocessor pre-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 registration-processor-operator-validator-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 registration-processor-operator-validator-stage UTF-8 diff --git a/registration-processor/pre-processor/registration-processor-packet-classifier-stage/pom.xml b/registration-processor/pre-processor/registration-processor-packet-classifier-stage/pom.xml index d0f9e67ba80..47a977300f6 100644 --- a/registration-processor/pre-processor/registration-processor-packet-classifier-stage/pom.xml +++ b/registration-processor/pre-processor/registration-processor-packet-classifier-stage/pom.xml @@ -7,10 +7,10 @@ io.mosip.registrationprocessor pre-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 registration-processor-packet-classifier-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 jar UTF-8 diff --git a/registration-processor/pre-processor/registration-processor-packet-uploader-stage/pom.xml b/registration-processor/pre-processor/registration-processor-packet-uploader-stage/pom.xml index d28b27ff418..848e5c823eb 100644 --- a/registration-processor/pre-processor/registration-processor-packet-uploader-stage/pom.xml +++ b/registration-processor/pre-processor/registration-processor-packet-uploader-stage/pom.xml @@ -9,9 +9,9 @@ io.mosip.registrationprocessor pre-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 UTF-8 diff --git a/registration-processor/pre-processor/registration-processor-packet-validator-stage/pom.xml b/registration-processor/pre-processor/registration-processor-packet-validator-stage/pom.xml index 9485563f780..4fdfef18387 100644 --- a/registration-processor/pre-processor/registration-processor-packet-validator-stage/pom.xml +++ b/registration-processor/pre-processor/registration-processor-packet-validator-stage/pom.xml @@ -7,10 +7,10 @@ io.mosip.registrationprocessor pre-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 registration-processor-packet-validator-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 jar UTF-8 diff --git a/registration-processor/pre-processor/registration-processor-quality-classifier-stage/pom.xml b/registration-processor/pre-processor/registration-processor-quality-classifier-stage/pom.xml index 6b7b4c50d00..e55d1b46d1d 100644 --- a/registration-processor/pre-processor/registration-processor-quality-classifier-stage/pom.xml +++ b/registration-processor/pre-processor/registration-processor-quality-classifier-stage/pom.xml @@ -5,11 +5,11 @@ io.mosip.registrationprocessor pre-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 registration-processor-quality-classifier-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 UTF-8 diff --git a/registration-processor/pre-processor/registration-processor-securezone-notification-stage/pom.xml b/registration-processor/pre-processor/registration-processor-securezone-notification-stage/pom.xml index 5d796c8376a..a83af1000e4 100644 --- a/registration-processor/pre-processor/registration-processor-securezone-notification-stage/pom.xml +++ b/registration-processor/pre-processor/registration-processor-securezone-notification-stage/pom.xml @@ -5,10 +5,10 @@ pre-processor io.mosip.registrationprocessor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 4.0.0 - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 registration-processor-securezone-notification-stage diff --git a/registration-processor/pre-processor/registration-processor-supervisor-validator-stage/pom.xml b/registration-processor/pre-processor/registration-processor-supervisor-validator-stage/pom.xml index 7caa4059e46..cd29c89e18a 100644 --- a/registration-processor/pre-processor/registration-processor-supervisor-validator-stage/pom.xml +++ b/registration-processor/pre-processor/registration-processor-supervisor-validator-stage/pom.xml @@ -6,10 +6,10 @@ io.mosip.registrationprocessor pre-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 registration-processor-supervisor-validator-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 registration-processor-supervisor-validator-stage UTF-8 diff --git a/registration-processor/qc-users-manger/pom.xml b/registration-processor/qc-users-manger/pom.xml index 6f5129d7735..36abc9db7e0 100644 --- a/registration-processor/qc-users-manger/pom.xml +++ b/registration-processor/qc-users-manger/pom.xml @@ -5,11 +5,11 @@ qc-users-manger - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 io.mosip.registrationprocessor registration-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 diff --git a/registration-processor/registration-processor-bio-dedupe-service-impl/pom.xml b/registration-processor/registration-processor-bio-dedupe-service-impl/pom.xml index 78f76c5951f..fc1fe39af20 100644 --- a/registration-processor/registration-processor-bio-dedupe-service-impl/pom.xml +++ b/registration-processor/registration-processor-bio-dedupe-service-impl/pom.xml @@ -5,11 +5,11 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 registration-processor-bio-dedupe-service-impl - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 registration-processor-bio-dedupe-service-impl diff --git a/registration-processor/registration-processor-common-camel-bridge/dependency-reduced-pom.xml b/registration-processor/registration-processor-common-camel-bridge/dependency-reduced-pom.xml index a761ced8384..0aa37a8a669 100644 --- a/registration-processor/registration-processor-common-camel-bridge/dependency-reduced-pom.xml +++ b/registration-processor/registration-processor-common-camel-bridge/dependency-reduced-pom.xml @@ -3,7 +3,7 @@ registration-processor io.mosip.registrationprocessor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 4.0.0 registration-processor-common-camel-bridge diff --git a/registration-processor/registration-processor-common-camel-bridge/pom.xml b/registration-processor/registration-processor-common-camel-bridge/pom.xml index f71a52f5c98..9fec69b43d3 100644 --- a/registration-processor/registration-processor-common-camel-bridge/pom.xml +++ b/registration-processor/registration-processor-common-camel-bridge/pom.xml @@ -6,16 +6,16 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 registration-processor-common-camel-bridge - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 jar io.mosip.registration.processor.camel.bridge.MosipCamelBridge 1.0.5 - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 diff --git a/registration-processor/registration-processor-core/pom.xml b/registration-processor/registration-processor-core/pom.xml index 15856637960..355be5e09bb 100644 --- a/registration-processor/registration-processor-core/pom.xml +++ b/registration-processor/registration-processor-core/pom.xml @@ -7,10 +7,10 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 registration-processor-core - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 org.mockito diff --git a/registration-processor/registration-processor-info-storage-service/pom.xml b/registration-processor/registration-processor-info-storage-service/pom.xml index a96ba4ed241..18e8cee31b3 100644 --- a/registration-processor/registration-processor-info-storage-service/pom.xml +++ b/registration-processor/registration-processor-info-storage-service/pom.xml @@ -7,10 +7,10 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 registration-processor-info-storage-service - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 registration-processor-info-storage-service UTF-8 diff --git a/registration-processor/registration-processor-landing-zone/pom.xml b/registration-processor/registration-processor-landing-zone/pom.xml index f3d1e06edd0..d215f8fbb5a 100644 --- a/registration-processor/registration-processor-landing-zone/pom.xml +++ b/registration-processor/registration-processor-landing-zone/pom.xml @@ -5,11 +5,11 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 registration-processor-landing-zone registration-processor-landing-zone - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 UTF-8 diff --git a/registration-processor/registration-processor-message-sender-impl/pom.xml b/registration-processor/registration-processor-message-sender-impl/pom.xml index 4ec8cd0b4d0..b90101fd636 100644 --- a/registration-processor/registration-processor-message-sender-impl/pom.xml +++ b/registration-processor/registration-processor-message-sender-impl/pom.xml @@ -8,11 +8,11 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 registration-processor-message-sender-impl - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 UTF-8 diff --git a/registration-processor/registration-processor-notification-service/pom.xml b/registration-processor/registration-processor-notification-service/pom.xml index 083e1972676..472a222535a 100644 --- a/registration-processor/registration-processor-notification-service/pom.xml +++ b/registration-processor/registration-processor-notification-service/pom.xml @@ -8,11 +8,11 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 registration-processor-notification-service - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 UTF-8 UTF-8 diff --git a/registration-processor/registration-processor-packet-manager/pom.xml b/registration-processor/registration-processor-packet-manager/pom.xml index c6d8b1600eb..790897abbb4 100644 --- a/registration-processor/registration-processor-packet-manager/pom.xml +++ b/registration-processor/registration-processor-packet-manager/pom.xml @@ -7,12 +7,12 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 registration-processor-packet-manager registration-processor-packet-manager - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 UTF-8 diff --git a/registration-processor/registration-processor-registration-status-service-impl/pom.xml b/registration-processor/registration-processor-registration-status-service-impl/pom.xml index 599d1b7c828..7d4be79101e 100644 --- a/registration-processor/registration-processor-registration-status-service-impl/pom.xml +++ b/registration-processor/registration-processor-registration-status-service-impl/pom.xml @@ -8,10 +8,10 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 registration-processor-registration-status-service-impl - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 UTF-8 diff --git a/registration-processor/registration-processor-rest-client/pom.xml b/registration-processor/registration-processor-rest-client/pom.xml index 3d66c5b85ae..dbabdd7b0e2 100644 --- a/registration-processor/registration-processor-rest-client/pom.xml +++ b/registration-processor/registration-processor-rest-client/pom.xml @@ -9,12 +9,12 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 registration-processor-rest-client registration-processor-rest-client - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 UTF-8 diff --git a/registration-processor/stage-groups/pom.xml b/registration-processor/stage-groups/pom.xml index 4abd296cb2c..73229c7023c 100644 --- a/registration-processor/stage-groups/pom.xml +++ b/registration-processor/stage-groups/pom.xml @@ -7,9 +7,9 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 stage-groups stage-groups diff --git a/registration-processor/stage-groups/registration-processor-stage-group-1/pom.xml b/registration-processor/stage-groups/registration-processor-stage-group-1/pom.xml index d2c037eee4a..26c9bbe68a7 100644 --- a/registration-processor/stage-groups/registration-processor-stage-group-1/pom.xml +++ b/registration-processor/stage-groups/registration-processor-stage-group-1/pom.xml @@ -5,11 +5,11 @@ io.mosip.registrationprocessor stage-groups - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 registration-processor-stage-group-1 - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 UTF-8 @@ -21,14 +21,14 @@ io.mosip.registrationprocessor mosip-stage-executor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 io.mosip.registrationprocessor registration-processor-packet-receiver-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 diff --git a/registration-processor/stage-groups/registration-processor-stage-group-2/pom.xml b/registration-processor/stage-groups/registration-processor-stage-group-2/pom.xml index c0cf46343d5..360a2926f7c 100644 --- a/registration-processor/stage-groups/registration-processor-stage-group-2/pom.xml +++ b/registration-processor/stage-groups/registration-processor-stage-group-2/pom.xml @@ -5,11 +5,11 @@ io.mosip.registrationprocessor stage-groups - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 registration-processor-stage-group-2 - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 UTF-8 @@ -21,24 +21,24 @@ io.mosip.registrationprocessor mosip-stage-executor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 io.mosip.registrationprocessor registration-processor-quality-classifier-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 io.mosip.registrationprocessor registration-processor-securezone-notification-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 io.mosip.registrationprocessor registration-processor-message-sender-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 diff --git a/registration-processor/stage-groups/registration-processor-stage-group-3/pom.xml b/registration-processor/stage-groups/registration-processor-stage-group-3/pom.xml index e96279087b6..d097331bf51 100644 --- a/registration-processor/stage-groups/registration-processor-stage-group-3/pom.xml +++ b/registration-processor/stage-groups/registration-processor-stage-group-3/pom.xml @@ -5,11 +5,11 @@ io.mosip.registrationprocessor stage-groups - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 registration-processor-stage-group-3 - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 UTF-8 @@ -21,29 +21,29 @@ io.mosip.registrationprocessor mosip-stage-executor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 io.mosip.registrationprocessor registration-processor-abis-handler-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 io.mosip.registrationprocessor registration-processor-abis-middleware-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 io.mosip.registrationprocessor registration-processor-bio-dedupe-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 io.mosip.registrationprocessor registration-processor-manual-adjudication-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 diff --git a/registration-processor/stage-groups/registration-processor-stage-group-4/pom.xml b/registration-processor/stage-groups/registration-processor-stage-group-4/pom.xml index ce1cdc96545..d0c2707466c 100644 --- a/registration-processor/stage-groups/registration-processor-stage-group-4/pom.xml +++ b/registration-processor/stage-groups/registration-processor-stage-group-4/pom.xml @@ -5,11 +5,11 @@ io.mosip.registrationprocessor stage-groups - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 registration-processor-stage-group-4 - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 UTF-8 @@ -21,19 +21,19 @@ io.mosip.registrationprocessor mosip-stage-executor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 io.mosip.registrationprocessor registration-processor-biometric-authentication-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 io.mosip.registrationprocessor registration-processor-demo-dedupe-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 diff --git a/registration-processor/stage-groups/registration-processor-stage-group-5/pom.xml b/registration-processor/stage-groups/registration-processor-stage-group-5/pom.xml index f167b1d15b3..a75eb2f08ad 100644 --- a/registration-processor/stage-groups/registration-processor-stage-group-5/pom.xml +++ b/registration-processor/stage-groups/registration-processor-stage-group-5/pom.xml @@ -5,11 +5,11 @@ io.mosip.registrationprocessor stage-groups - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 registration-processor-stage-group-5 - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 UTF-8 @@ -21,34 +21,34 @@ io.mosip.registrationprocessor mosip-stage-executor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 io.mosip.registrationprocessor registration-processor-cmd-validator-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 io.mosip.registrationprocessor registration-processor-operator-validator-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 io.mosip.registrationprocessor registration-processor-supervisor-validator-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 io.mosip.registrationprocessor registration-processor-introducer-validator-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 io.mosip.registrationprocessor registration-processor-packet-validator-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 diff --git a/registration-processor/stage-groups/registration-processor-stage-group-6/pom.xml b/registration-processor/stage-groups/registration-processor-stage-group-6/pom.xml index 114783da14d..e74f7393085 100644 --- a/registration-processor/stage-groups/registration-processor-stage-group-6/pom.xml +++ b/registration-processor/stage-groups/registration-processor-stage-group-6/pom.xml @@ -5,11 +5,11 @@ io.mosip.registrationprocessor stage-groups - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 registration-processor-stage-group-6 - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 UTF-8 @@ -21,24 +21,24 @@ io.mosip.registrationprocessor mosip-stage-executor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 io.mosip.registrationprocessor registration-processor-packet-uploader-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 io.mosip.registrationprocessor registration-processor-packet-classifier-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 io.mosip.registrationprocessor registration-processor-verification-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 diff --git a/registration-processor/stage-groups/registration-processor-stage-group-7/pom.xml b/registration-processor/stage-groups/registration-processor-stage-group-7/pom.xml index 4fc1177f84a..c1a8220c7a6 100644 --- a/registration-processor/stage-groups/registration-processor-stage-group-7/pom.xml +++ b/registration-processor/stage-groups/registration-processor-stage-group-7/pom.xml @@ -5,11 +5,11 @@ io.mosip.registrationprocessor stage-groups - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 registration-processor-stage-group-7 - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 UTF-8 @@ -21,29 +21,29 @@ io.mosip.registrationprocessor mosip-stage-executor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 io.mosip.registrationprocessor registration-processor-uin-generator-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 io.mosip.registrationprocessor registration-processor-biometric-extraction-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 io.mosip.registrationprocessor registration-processor-finalization-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 io.mosip.registrationprocessor registration-processor-printing-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 diff --git a/registration-processor/workflow-engine/pom.xml b/registration-processor/workflow-engine/pom.xml index cebeb084931..e0ea116118a 100644 --- a/registration-processor/workflow-engine/pom.xml +++ b/registration-processor/workflow-engine/pom.xml @@ -5,9 +5,9 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 workflow-engine workflow-engine diff --git a/registration-processor/workflow-engine/registration-processor-reprocessor/pom.xml b/registration-processor/workflow-engine/registration-processor-reprocessor/pom.xml index 8df1096a769..56d459efd73 100644 --- a/registration-processor/workflow-engine/registration-processor-reprocessor/pom.xml +++ b/registration-processor/workflow-engine/registration-processor-reprocessor/pom.xml @@ -7,10 +7,10 @@ io.mosip.registrationprocessor workflow-engine - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 registration-processor-reprocessor - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 registration-processor-reprocessor UTF-8 diff --git a/registration-processor/workflow-engine/registration-processor-workflow-manager-service/pom.xml b/registration-processor/workflow-engine/registration-processor-workflow-manager-service/pom.xml index c69945fe557..9a6bab4ba88 100644 --- a/registration-processor/workflow-engine/registration-processor-workflow-manager-service/pom.xml +++ b/registration-processor/workflow-engine/registration-processor-workflow-manager-service/pom.xml @@ -5,10 +5,10 @@ io.mosip.registrationprocessor workflow-engine - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 registration-processor-workflow-manager-service - 1.2.0.1-SNAPSHOT + 1.2.0.1-B3 registration-processor-workflow-manager-service UTF-8 From 46e6d5536c0703fd55577ebe271dfb1a58b4ebf3 Mon Sep 17 00:00:00 2001 From: Rakshith B <79500257+Rakshithb1@users.noreply.github.com> Date: Tue, 2 Jan 2024 17:47:56 +0530 Subject: [PATCH 105/133] [MOSIP-29961] removed paths from db-test.yml (#1817) Signed-off-by: Rakshith B <79500257+Rakshithb1@users.noreply.github.com> --- .github/workflows/db-test.yml | 2 -- 1 file changed, 2 deletions(-) diff --git a/.github/workflows/db-test.yml b/.github/workflows/db-test.yml index 35a2e6a3585..6d650a592e3 100644 --- a/.github/workflows/db-test.yml +++ b/.github/workflows/db-test.yml @@ -5,8 +5,6 @@ on: types: [published] pull_request: types: [opened, reopened, synchronize] - paths: - - 'db_scripts/**' workflow_dispatch: inputs: message: From d8faaed8993e6eef2dbd4a9e30dc12695686851e Mon Sep 17 00:00:00 2001 From: Vishwa Date: Fri, 17 Nov 2023 10:56:44 +0530 Subject: [PATCH 106/133] Merge pull request #1774 from MonobikashDas/MOSIP-28121 MOSIP-28121 : rename print stage to credential requestor stage --- registration-processor/pom.xml | 1129 ++++++++--------- registration-processor/post-processor/pom.xml | 44 +- .../Dockerfile-not-used | 110 +- .../README.md | 4 +- .../pom.xml | 218 ++-- .../CredentialRequestorStageApplication.java} | 8 +- .../config/CredentialRequestorConfigBean.java | 15 + .../dto/CredentialPartner.java | 16 + .../dto/CredentialPartnersList.java | 10 + .../stage/CredentialRequestorStage.java} | 925 +++++++------- .../exception/VidNotAvailableException.java | 54 +- .../util/CredentialPartnerUtil.java | 225 ++++ .../src/main/resources/bootstrap.properties | 58 +- .../src/main/resources/logback.xml | 0 .../test/CredentialRequestorStageTest.java} | 911 ++++++------- .../processor/core/code/ApiName.java | 3 +- .../core/constant/ProviderStageName.java | 3 +- .../exception/util/PlatformErrorMessages.java | 5 + .../pom.xml | 146 +-- 19 files changed, 2112 insertions(+), 1772 deletions(-) rename registration-processor/post-processor/{registration-processor-printing-stage => registration-processor-credential-requestor-stage}/Dockerfile-not-used (85%) rename registration-processor/post-processor/{registration-processor-printing-stage => registration-processor-credential-requestor-stage}/README.md (57%) rename registration-processor/post-processor/{registration-processor-printing-stage => registration-processor-credential-requestor-stage}/pom.xml (94%) rename registration-processor/post-processor/{registration-processor-printing-stage/src/main/java/io/mosip/registration/processor/print/PrintStageApplication.java => registration-processor-credential-requestor-stage/src/main/java/io/mosip/registration/processor/credentialrequestor/CredentialRequestorStageApplication.java} (68%) create mode 100644 registration-processor/post-processor/registration-processor-credential-requestor-stage/src/main/java/io/mosip/registration/processor/credentialrequestor/config/CredentialRequestorConfigBean.java create mode 100644 registration-processor/post-processor/registration-processor-credential-requestor-stage/src/main/java/io/mosip/registration/processor/credentialrequestor/dto/CredentialPartner.java create mode 100644 registration-processor/post-processor/registration-processor-credential-requestor-stage/src/main/java/io/mosip/registration/processor/credentialrequestor/dto/CredentialPartnersList.java rename registration-processor/post-processor/{registration-processor-printing-stage/src/main/java/io/mosip/registration/processor/print/stage/PrintingStage.java => registration-processor-credential-requestor-stage/src/main/java/io/mosip/registration/processor/credentialrequestor/stage/CredentialRequestorStage.java} (67%) rename registration-processor/post-processor/{registration-processor-printing-stage/src/main/java/io/mosip/registration/processor/print => registration-processor-credential-requestor-stage/src/main/java/io/mosip/registration/processor/credentialrequestor}/stage/exception/VidNotAvailableException.java (85%) create mode 100644 registration-processor/post-processor/registration-processor-credential-requestor-stage/src/main/java/io/mosip/registration/processor/credentialrequestor/util/CredentialPartnerUtil.java rename registration-processor/post-processor/{registration-processor-printing-stage => registration-processor-credential-requestor-stage}/src/main/resources/bootstrap.properties (50%) rename registration-processor/post-processor/{registration-processor-printing-stage => registration-processor-credential-requestor-stage}/src/main/resources/logback.xml (100%) rename registration-processor/post-processor/{registration-processor-printing-stage/src/test/java/io/mosip/registrationprocessor/print/stage/test/PrintingStageTest.java => registration-processor-credential-requestor-stage/src/test/java/io/mosip/registrationprocessor/credentialrequestor/test/CredentialRequestorStageTest.java} (87%) diff --git a/registration-processor/pom.xml b/registration-processor/pom.xml index a649d38190e..4197c1f9c75 100644 --- a/registration-processor/pom.xml +++ b/registration-processor/pom.xml @@ -1,567 +1,562 @@ - - - 4.0.0 - - - io.mosip - registration - 1.2.0.1-B3 - - - - - MPL 2.0 - https://www.mozilla.org/en-US/MPL/2.0/ - - - - scm:git:git://github.com/mosip/registration.git - scm:git:ssh://github.com:mosip/registration.git - https://github.com/mosip/registration - HEAD - - - - Mosip - mosip.emailnotifier@gmail.com - io.mosip - https://github.com/mosip/registration - - - io.mosip.registrationprocessor - registration-processor - 1.2.0.1-B3 - pom - - registration-processor - Parent project of MOSIP Registration processor - - - none - UTF-8 - 11 - 11 - 3.8.0 - 3.0.2 - 3.1.0 - 2.22.0 - 0.8.5 - 3.7.0.1746 - 3.2.0 - 3.3.0 - - - 5.0.6.RELEASE - 5.0.4.RELEASE - 2.0.2.RELEASE - 2.0.9.RELEASE - 2.0.0.RELEASE - - 4.0.1.RELEASE - 2.0.0.RELEASE - - - 3.0.0 - 2.0.1.Final - 2.12.0 - 2.12.0 - 6.0.12.Final - 2.1.1 - 1.7.25 - 4.5.6 - - - 2.9.2 - - - 2.5.0 - 5.1.46 - 1.4.195 - 42.2.2 - - - 1.18.8 - - - 2.3.0 - - - 1.60 - 1.6 - - - 3.6.1 - 3.7 - 2.6 - 1.10 - 1.9.2 - 2.2 - 2.6 - 1.7 - 2.0 - - - 4.12 - 1.2.3 - 1.7.19 - 3.4.4 - 2.0.7 - 2.0.7 - 3.1.0 - 1.1.1 - 1.9 - - 1.11.368 - 0.2.4 - - - 3.9.1 - 2.23.0 - 1.0.0 - - 1.1.1 - - - 2.8.1 - - - 0.1.55 - - - 1.2.0.1-B3 - 1.2.0.1-B3 - 1.2.0.1-B3 - 1.2.0.1-B3 - 1.2.0.1-B3 - 1.2.0.1-B3 - 1.2.0.1-B3 - - - 1.2.0.1-B2 - 1.2.0.1-B2 - 1.2.0.1-B2 - 1.2.0.1-B2 - 1.2.0.1-B2 - 1.2.0.1-B2 - 1.2.0.1-B3 - 1.2.0.1-B2 - 1.2.0.1-B2 - 1.2.0.1-B2 - 1.2.0.1-B2 - 1.2.0.1-B2 - 1.2.0.1-B2 - 1.2.0.1-B3 - 1.2.0.1-B2 - 1.2.0.1-B2 - **/dto/**, - **/exception/*Exception.java, - **/config/*Config.java, - **/handler/*ExceptionHandler.java, - **/**/*Application.java, - **/utilities/*.java, - **/validator/*Validator.java, - **/utils/*.java, - **/util/*.java, - **/code/*.java, - **/entity/*.java, - **/config/*.java, - - **/core/code/*.java, - **/packet/storage/entity/*.java, - **/manager/exception/systemexception/*.java, - **/registration/processor/rest/client/*.java, - **/registration/processor/rest/client/audit/builder/*.java, - - **/registration/processor/packet/receiver/*.java, - **/registration/processor/packet/receiver/exception/systemexception/*.java, - **/registration/processor/failoverstage/*.java, - **/registration/processor/stages/*.java, - **/registration/processor/retry/verticle/*.java, - **/registration/processor/retry/verticle/stages/*.java, - **/registration/processor/retry/verticle/constants/*.java, - **/registration/processor/packet/decrypter/job/stage/*.java, - **/registration/processor/packet/decryptor/job/exception/constant/*.java, - - **/registration/processor/virus/scanner/job/exceptions/*.java, - - - **/registration/processor/stages/app/*.java, - **/registration/processor/stages/executor/*.java, - **/registration/processor/camel/bridge/processor/*.java, - **/registration/processor/core/constant/*.java, - **/registration/processor/core/packet/dto/demographicinfo/*.java, - **/registration/processor/core/packet/dto/demographicinfo/identify/*.java, - **/registration/processor/core/packet/dto/regcentermachine/*.java, - - **/registration/processor/quality/check/client/*.java, - **/registration/processor/quality/check/code/*.java, - **/registration/processor/quality/check/entity/*.java, - **/registration/processor/quality/check/exception/*.java, - **/registration/processor/quality/check/*.java, - **/registration/processor/message/sender/*.java, - **/registration/processor/message/sender/utility/*.java, - **/registration/processor/core/logger/*.java, - **/registration/processor/core/notification/template/mapping/*.java, - **/registration/processor/bio/dedupe/service/*.java, - **/registration/processor/bio/dedupe/exception/*.java, - - **/registration/processor/packet/storage/storage/*.java, - **/registration/processor/packet/storage/exception/*.java, - **/registration/processor/status/repositary/*.java, - **/registration/processor/status/entity/*.java, - **/registration/processor/virus/scanner/job/*.java, - - - **/registration/processor/packet/uploader/*.java, - **/registration/processor/biodedupe/*.java, - - - **/registration/processor/abis/config/*.java, - **/registration/processor/abis/controller/*.java, - **/registration/processor/abis/exception/*.java, - **/registration/processor/abis/messagequeue/*.java, - **/registration/processor/abis/service/*.java, - **/registration/processor/abis/service/impl/*.java, - - - **/registration/processor/abis/handler/*.java, - **/registration/processor/abis/handler/config/*.java, - - **/registration/processor/packet/service/**/*.java, - **/registration/processor/packet/upload/**/*.java, - - **/registration/processor/status/code/*.java, - **/registration/processor/rest/client/config/RestConfigBean.java, - **/registration/processor/bio/dedupe/api/BioDedupeApiApp.java, - **/registration/processor/manual/verification/response/builder/*.java, - **/registration/processor/manual/verification/config/*.java, - **/registration/processor/stages/config/OSIConfigBean.java, - **/registration/processor/stages/demo/dedupe/StatusMessage.java, - **/registration/processor/stages/demo/dedupe/DemodedupeStage.java, - **/registration/processor/stages/demo/dedupe/BiometricValidation.java, - **/registration/processor/core/exception/ExceptionJSONInfo.java, - **/registration/processor/core/config/CoreConfigBean.java, - **/registration/processor/core/kernel/beans/KernelConfig.java, - **/registration/processor/core/abstractverticle/MosipVerticleAPIManager.java, - **/registration/processor/core/abstractverticle/WorkflowInternalActionDTO.java, - **/registration/processor/core/http/*.java, - **/registration/processor/core/queue/factory/*.java, - **/registration/processor/core/queue/impl/*.java, - **/registration/processor/core/tracing/*.java, - **/registration/processor/message/sender/config/MsgNotificationBeanCofig.java, - **/registration/processor/print/exception/QueueConnectionNotFound.java, - **/registration/processor/stages/demodedupe/StatusMessage.java, - **/registration/processor/print/service/utility/UINCardConstant.java, - **/registration/processor/stages/demodedupe/BiometricValidation.java, - **/registration/processor/camel/bridge/MosipBridgeFactory.java, - **/registration/processor/manual/verification/stage/ManualVerificationStage.java, - **/registration/processor/packet/receiver/builder/PacketReceiverResponseBuilder.java, - **/registration/processor/packet/receiver/stage/PacketReceiverStage.java, - **/registration/processor/camel/bridge/**/*.java, - **/registration/processor/stages/connector/stage/**/*.java, - **/registration/processor/stages/demodedupe/DemoDedupeStage.java, - - **/registration/processor/packet/storage/mapper/PacketInfoMapper.java, - **/registration/processor/packet/storage/dao/PacketInfoDao.java, - **/registration/processor/packet/uploader/constants/*.java, - **/registration/processor/packet/manager/constant/*.java, - **/registration/processor/print/exception/PrintGlobalExceptionHandler.java, - **/registration/processor/packet/receiver/constants/*.java, - **/registration/processor/print/service/exception/*.java, - **/registration/processor/print/exception/*.java, - **/registration/processor/packet/uploader/constants/*.java, - **/registration/processor/packet/uploader/decryptor/*.java, - **/registration/processor/core/abstractverticle/MosipRouter.java, - **/registration/processor/packet/uploader/decryptor/*.java, - - **/registration/processor/print/service/impl/PrintPostServiceImpl.java, - - **/registration/processor/message/sender/constants/*.java, - **/registration/processor/core/abstractverticle/BaseHealthCheckModel.java, - **/registration/processor/core/**/TokenValidator.java, - **/registration/processor/core/abstractverticle/StageHealthCheckHandler.java, - **/registration/processor/core/abstractverticle/MessageDTO.java, - **/registration/processor/request/handler/**/*.java - - **/dto/**,**/entity/**,**/config/**,**/handler/**,**/utilities/**, - **/validator/**, **/utils/**,**/util/**,**/code/** - none - - - - - ossrh - CentralRepository - https://oss.sonatype.org/content/repositories/snapshots - default - - true - - - - central - MavenCentral - default - https://repo1.maven.org/maven2 - - false - - - - - - - - org.mockito - mockito-core - 3.4.4 - test - - - - net.bytebuddy - byte-buddy - 1.10.13 - - - org.springframework.boot - spring-boot-dependencies - ${spring.boot.version} - pom - import - - - org.projectlombok - lombok - 1.18.8 - provided - - - org.powermock - powermock-core - 2.0.7 - test - - - javax.xml.bind - jaxb-api - 2.3.1 - - - org.javassist - javassist - 3.27.0-GA - - - com.fasterxml.jackson.core - jackson-databind - ${jackson.version} - - - com.fasterxml.jackson.core - jackson-core - ${jackson.version} - - - com.fasterxml.jackson.core - jackson-annotations - ${jackson.version} - - - - - - registration-processor-core - registration-processor-rest-client - registration-processor-packet-manager - registration-processor-common-camel-bridge - registration-processor-bio-dedupe-service-impl - registration-processor-info-storage-service - registration-processor-registration-status-service-impl - registration-processor-message-sender-impl - registration-processor-notification-service - init - pre-processor - core-processor - post-processor - mosip-stage-executor - stage-groups - 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} - - - - - - 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 - ${maven.javadoc.version} - - true - none - - - - - - - sonar - - . - src/main/java/**,src/main/resources/** - ${sonar.coverage.exclusions} - https://sonarcloud.io - - - false - - - - - org.sonarsource.scanner.maven - sonar-maven-plugin - ${maven.sonar.plugin.version} - - - verify - - sonar - - - - - - - - - + + + 4.0.0 + + + io.mosip + registration + 1.2.0.1-B3 + + + + + MPL 2.0 + https://www.mozilla.org/en-US/MPL/2.0/ + + + + scm:git:git://github.com/mosip/registration.git + scm:git:ssh://github.com:mosip/registration.git + https://github.com/mosip/registration + HEAD + + + + Mosip + mosip.emailnotifier@gmail.com + io.mosip + https://github.com/mosip/registration + + + io.mosip.registrationprocessor + registration-processor + 1.2.0.1-B3 + pom + + registration-processor + Parent project of MOSIP Registration processor + + + none + UTF-8 + 11 + 11 + 3.8.0 + 3.0.2 + 3.1.0 + 2.22.0 + 0.8.5 + 3.7.0.1746 + 3.2.0 + 3.3.0 + + + 5.0.6.RELEASE + 5.0.4.RELEASE + 2.0.2.RELEASE + 2.0.9.RELEASE + 2.0.0.RELEASE + + 4.0.1.RELEASE + 2.0.0.RELEASE + + + 3.0.0 + 2.0.1.Final + 2.12.0 + 2.12.0 + 6.0.12.Final + 2.1.1 + 1.7.25 + 4.5.6 + + + 2.9.2 + + + 2.5.0 + 5.1.46 + 1.4.195 + 42.2.2 + + + 1.18.8 + + + 2.3.0 + + + 1.60 + 1.6 + + + 3.6.1 + 3.7 + 2.6 + 1.10 + 1.9.2 + 2.2 + 2.6 + 1.7 + 2.0 + + + 4.12 + 1.2.3 + 1.7.19 + 3.4.4 + 2.0.7 + 2.0.7 + 3.1.0 + 1.1.1 + 1.9 + + 1.11.368 + 0.2.4 + + + 3.9.1 + 2.23.0 + 1.0.0 + + 1.1.1 + + + 2.8.1 + + + 0.1.55 + + + 1.2.0.1-B3 + 1.2.0.1-B3 + 1.2.0.1-B3 + 1.2.0.1-B3 + 1.2.0.1-B3 + 1.2.0.1-B3 + 1.2.0.1-B3 + + + 1.2.0.1-B2 + 1.2.0.1-B2 + 1.2.0.1-B2 + 1.2.0.1-B2 + 1.2.0.1-B2 + 1.2.0.1-B2 + 1.2.0.1-B3 + 1.2.0.1-B2 + 1.2.0.1-B2 + 1.2.0.1-B2 + 1.2.0.1-B2 + 1.2.0.1-B2 + 1.2.0.1-B2 + 1.2.0.1-B3 + 1.2.0.1-B2 + 1.2.0.1-B2 + **/dto/**, + **/exception/*Exception.java, + **/config/*Config.java, + **/handler/*ExceptionHandler.java, + **/**/*Application.java, + **/utilities/*.java, + **/validator/*Validator.java, + **/utils/*.java, + **/util/*.java, + **/code/*.java, + **/entity/*.java, + **/config/*.java, + + **/core/code/*.java, + **/packet/storage/entity/*.java, + **/manager/exception/systemexception/*.java, + **/registration/processor/rest/client/*.java, + **/registration/processor/rest/client/audit/builder/*.java, + + **/registration/processor/packet/receiver/*.java, + **/registration/processor/packet/receiver/exception/systemexception/*.java, + **/registration/processor/failoverstage/*.java, + **/registration/processor/stages/*.java, + **/registration/processor/retry/verticle/*.java, + **/registration/processor/retry/verticle/stages/*.java, + **/registration/processor/retry/verticle/constants/*.java, + **/registration/processor/packet/decrypter/job/stage/*.java, + **/registration/processor/packet/decryptor/job/exception/constant/*.java, + + **/registration/processor/virus/scanner/job/exceptions/*.java, + + + **/registration/processor/stages/app/*.java, + **/registration/processor/stages/executor/*.java, + **/registration/processor/camel/bridge/processor/*.java, + **/registration/processor/core/constant/*.java, + **/registration/processor/core/packet/dto/demographicinfo/*.java, + **/registration/processor/core/packet/dto/demographicinfo/identify/*.java, + **/registration/processor/core/packet/dto/regcentermachine/*.java, + + **/registration/processor/quality/check/client/*.java, + **/registration/processor/quality/check/code/*.java, + **/registration/processor/quality/check/entity/*.java, + **/registration/processor/quality/check/exception/*.java, + **/registration/processor/quality/check/*.java, + **/registration/processor/message/sender/*.java, + **/registration/processor/message/sender/utility/*.java, + **/registration/processor/core/logger/*.java, + **/registration/processor/core/notification/template/mapping/*.java, + **/registration/processor/bio/dedupe/service/*.java, + **/registration/processor/bio/dedupe/exception/*.java, + + **/registration/processor/packet/storage/storage/*.java, + **/registration/processor/packet/storage/exception/*.java, + **/registration/processor/status/repositary/*.java, + **/registration/processor/status/entity/*.java, + **/registration/processor/virus/scanner/job/*.java, + + + **/registration/processor/packet/uploader/*.java, + **/registration/processor/biodedupe/*.java, + + + **/registration/processor/abis/config/*.java, + **/registration/processor/abis/controller/*.java, + **/registration/processor/abis/exception/*.java, + **/registration/processor/abis/messagequeue/*.java, + **/registration/processor/abis/service/*.java, + **/registration/processor/abis/service/impl/*.java, + + + **/registration/processor/abis/handler/*.java, + **/registration/processor/abis/handler/config/*.java, + + **/registration/processor/packet/service/**/*.java, + **/registration/processor/packet/upload/**/*.java, + + **/registration/processor/status/code/*.java, + **/registration/processor/rest/client/config/RestConfigBean.java, + **/registration/processor/bio/dedupe/api/BioDedupeApiApp.java, + **/registration/processor/manual/verification/response/builder/*.java, + **/registration/processor/manual/verification/config/*.java, + **/registration/processor/stages/config/OSIConfigBean.java, + **/registration/processor/stages/demo/dedupe/StatusMessage.java, + **/registration/processor/stages/demo/dedupe/DemodedupeStage.java, + **/registration/processor/stages/demo/dedupe/BiometricValidation.java, + **/registration/processor/core/exception/ExceptionJSONInfo.java, + **/registration/processor/core/config/CoreConfigBean.java, + **/registration/processor/core/kernel/beans/KernelConfig.java, + **/registration/processor/core/abstractverticle/MosipVerticleAPIManager.java, + **/registration/processor/core/abstractverticle/WorkflowInternalActionDTO.java, + **/registration/processor/core/http/*.java, + **/registration/processor/core/queue/factory/*.java, + **/registration/processor/core/queue/impl/*.java, + **/registration/processor/core/tracing/*.java, + **/registration/processor/message/sender/config/MsgNotificationBeanCofig.java, + **/registration/processor/abis/exception/QueueConnectionNotFound.java, + **/registration/processor/stages/demodedupe/StatusMessage.java, + **/registration/processor/stages/demodedupe/BiometricValidation.java, + **/registration/processor/camel/bridge/MosipBridgeFactory.java, + **/registration/processor/manual/verification/stage/ManualVerificationStage.java, + **/registration/processor/packet/receiver/builder/PacketReceiverResponseBuilder.java, + **/registration/processor/packet/receiver/stage/PacketReceiverStage.java, + **/registration/processor/camel/bridge/**/*.java, + **/registration/processor/stages/connector/stage/**/*.java, + **/registration/processor/stages/demodedupe/DemoDedupeStage.java, + + **/registration/processor/packet/storage/mapper/PacketInfoMapper.java, + **/registration/processor/packet/storage/dao/PacketInfoDao.java, + **/registration/processor/packet/uploader/constants/*.java, + **/registration/processor/packet/manager/constant/*.java, + **/registration/processor/packet/receiver/constants/*.java, + **/registration/processor/credentialrequestor/stage/exception/*.java, + **/registration/processor/packet/uploader/constants/*.java, + **/registration/processor/packet/uploader/decryptor/*.java, + **/registration/processor/core/abstractverticle/MosipRouter.java, + **/registration/processor/packet/uploader/decryptor/*.java, + + **/registration/processor/message/sender/constants/*.java, + **/registration/processor/core/abstractverticle/BaseHealthCheckModel.java, + **/registration/processor/core/**/TokenValidator.java, + **/registration/processor/core/abstractverticle/StageHealthCheckHandler.java, + **/registration/processor/core/abstractverticle/MessageDTO.java, + **/registration/processor/request/handler/**/*.java + + **/dto/**,**/entity/**,**/config/**,**/handler/**,**/utilities/**, + **/validator/**, **/utils/**,**/util/**,**/code/** + none + + + + + ossrh + CentralRepository + https://oss.sonatype.org/content/repositories/snapshots + default + + true + + + + central + MavenCentral + default + https://repo1.maven.org/maven2 + + false + + + + + + + + org.mockito + mockito-core + 3.4.4 + test + + + + net.bytebuddy + byte-buddy + 1.10.13 + + + org.springframework.boot + spring-boot-dependencies + ${spring.boot.version} + pom + import + + + org.projectlombok + lombok + 1.18.8 + provided + + + org.powermock + powermock-core + 2.0.7 + test + + + javax.xml.bind + jaxb-api + 2.3.1 + + + org.javassist + javassist + 3.27.0-GA + + + com.fasterxml.jackson.core + jackson-databind + ${jackson.version} + + + com.fasterxml.jackson.core + jackson-core + ${jackson.version} + + + com.fasterxml.jackson.core + jackson-annotations + ${jackson.version} + + + + + + registration-processor-core + registration-processor-rest-client + registration-processor-packet-manager + registration-processor-common-camel-bridge + registration-processor-bio-dedupe-service-impl + registration-processor-info-storage-service + registration-processor-registration-status-service-impl + registration-processor-message-sender-impl + registration-processor-notification-service + init + pre-processor + core-processor + post-processor + mosip-stage-executor + stage-groups + 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} + + + + + + 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 + ${maven.javadoc.version} + + true + none + + + + + + + sonar + + . + src/main/java/**,src/main/resources/** + ${sonar.coverage.exclusions} + https://sonarcloud.io + + + false + + + + + org.sonarsource.scanner.maven + sonar-maven-plugin + ${maven.sonar.plugin.version} + + + verify + + sonar + + + + + + + + + diff --git a/registration-processor/post-processor/pom.xml b/registration-processor/post-processor/pom.xml index 0a55dd17040..325ff6ddac3 100644 --- a/registration-processor/post-processor/pom.xml +++ b/registration-processor/post-processor/pom.xml @@ -1,22 +1,22 @@ - - - 4.0.0 - pom - - io.mosip.registrationprocessor - registration-processor - 1.2.0.1-B3 - - 1.2.0.1-B3 - post-processor - post-processor - - UTF-8 - - - registration-processor-message-sender-stage - registration-processor-printing-stage - registration-processor-registration-transaction-service - - + + + 4.0.0 + pom + + io.mosip.registrationprocessor + registration-processor + 1.2.0.1-B3 + + 1.2.0.1-B3 + post-processor + post-processor + + UTF-8 + + + registration-processor-message-sender-stage + registration-processor-credential-requestor-stage + registration-processor-registration-transaction-service + + diff --git a/registration-processor/post-processor/registration-processor-printing-stage/Dockerfile-not-used b/registration-processor/post-processor/registration-processor-credential-requestor-stage/Dockerfile-not-used similarity index 85% rename from registration-processor/post-processor/registration-processor-printing-stage/Dockerfile-not-used rename to registration-processor/post-processor/registration-processor-credential-requestor-stage/Dockerfile-not-used index 2c43739a850..2767feb48d7 100644 --- a/registration-processor/post-processor/registration-processor-printing-stage/Dockerfile-not-used +++ b/registration-processor/post-processor/registration-processor-credential-requestor-stage/Dockerfile-not-used @@ -1,55 +1,55 @@ -FROM openjdk:11 - -#Uncomment below and Comment above line(i.e. FROM openjdk:8) for OS specific (e.g. Alpine OS ) docker base image -#FROM openjdk:8-jdk-alpine - -# can be passed during Docker build as build time environment for github branch to pickup configuration from. -ARG spring_config_label - -# can be passed during Docker build as build time environment for spring profiles active -ARG active_profile - -# can be passed during Docker build as build time environment for config server URL -ARG spring_config_url - -# can be passed during Docker build as build time environment for glowroot -ARG is_glowroot - -# can be passed during Docker build as build time environment for artifactory URL -ARG artifactory_url - -# environment variable to pass active profile such as DEV, QA etc at docker runtime -ENV active_profile_env=${active_profile} - -# environment variable to pass github branch to pickup configuration from, at docker runtime -ENV spring_config_label_env=${spring_config_label} - -# environment variable to pass github branch to pickup configuration from, at docker runtime -ENV spring_config_label_env=${spring_config_label} - -# environment variable to pass glowroot, at docker runtime -ENV is_glowroot_env=${is_glowroot} - -# environment variable to pass artifactory url, at docker runtime -ENV artifactory_url_env=${artifactory_url} - -# change volume to whichever storage directory you want to use for this container. -VOLUME /home/logs - -COPY ./target/registration-processor-printing-stage-*.jar registration-processor-printing-stage.jar - -CMD if [ "$is_glowroot_env" = "present" ]; then \ - wget "${artifactory_url_env}"/artifactory/libs-release-local/io/mosip/testing/glowroot.zip ; \ - apt-get update && apt-get install -y unzip ; \ - unzip glowroot.zip ; \ - rm -rf glowroot.zip ; \ - - sed -i 's//registration-processor-printing-stage/g' glowroot/glowroot.properties ; \ - java -Dspring.cloud.config.label="${spring_config_label_env}" -Dspring.profiles.active="${active_profile_env}" -Dspring.cloud.config.uri="${spring_config_url_env}" -jar -javaagent:glowroot/glowroot.jar registration-processor-printing-stage.jar ; \ - else \ - java -Dspring.cloud.config.label="${spring_config_label_env}" -Dspring.profiles.active="${active_profile_env}" -Dspring.cloud.config.uri="${spring_config_url_env}" -jar registration-processor-printing-stage.jar ; \ - fi - - -#CMD ["java","-Dspring.cloud.config.label=${spring_config_label_env}","-Dspring.profiles.active=${active_profile_env}","-Dspring.cloud.config.uri=${spring_config_url_env}","-jar","registration-processor-printing-stage.jar"] - +FROM openjdk:11 + +#Uncomment below and Comment above line(i.e. FROM openjdk:8) for OS specific (e.g. Alpine OS ) docker base image +#FROM openjdk:8-jdk-alpine + +# can be passed during Docker build as build time environment for github branch to pickup configuration from. +ARG spring_config_label + +# can be passed during Docker build as build time environment for spring profiles active +ARG active_profile + +# can be passed during Docker build as build time environment for config server URL +ARG spring_config_url + +# can be passed during Docker build as build time environment for glowroot +ARG is_glowroot + +# can be passed during Docker build as build time environment for artifactory URL +ARG artifactory_url + +# environment variable to pass active profile such as DEV, QA etc at docker runtime +ENV active_profile_env=${active_profile} + +# environment variable to pass github branch to pickup configuration from, at docker runtime +ENV spring_config_label_env=${spring_config_label} + +# environment variable to pass github branch to pickup configuration from, at docker runtime +ENV spring_config_label_env=${spring_config_label} + +# environment variable to pass glowroot, at docker runtime +ENV is_glowroot_env=${is_glowroot} + +# environment variable to pass artifactory url, at docker runtime +ENV artifactory_url_env=${artifactory_url} + +# change volume to whichever storage directory you want to use for this container. +VOLUME /home/logs + +COPY ./target/registration-processor-credential-requestor-stage-*.jar registration-processor-credential-requestor-stage.jar + +CMD if [ "$is_glowroot_env" = "present" ]; then \ + wget "${artifactory_url_env}"/artifactory/libs-release-local/io/mosip/testing/glowroot.zip ; \ + apt-get update && apt-get install -y unzip ; \ + unzip glowroot.zip ; \ + rm -rf glowroot.zip ; \ + + sed -i 's//registration-processor-credential-requestor-stage/g' glowroot/glowroot.properties ; \ + java -Dspring.cloud.config.label="${spring_config_label_env}" -Dspring.profiles.active="${active_profile_env}" -Dspring.cloud.config.uri="${spring_config_url_env}" -jar -javaagent:glowroot/glowroot.jar registration-processor-credential-requestor-stage.jar ; \ + else \ + java -Dspring.cloud.config.label="${spring_config_label_env}" -Dspring.profiles.active="${active_profile_env}" -Dspring.cloud.config.uri="${spring_config_url_env}" -jar registration-processor-credential-requestor-stage.jar ; \ + fi + + +#CMD ["java","-Dspring.cloud.config.label=${spring_config_label_env}","-Dspring.profiles.active=${active_profile_env}","-Dspring.cloud.config.uri=${spring_config_url_env}","-jar","registration-processor-credential-requestor-stage.jar"] + diff --git a/registration-processor/post-processor/registration-processor-printing-stage/README.md b/registration-processor/post-processor/registration-processor-credential-requestor-stage/README.md similarity index 57% rename from registration-processor/post-processor/registration-processor-printing-stage/README.md rename to registration-processor/post-processor/registration-processor-credential-requestor-stage/README.md index 71b6369e3b6..320dffd6672 100644 --- a/registration-processor/post-processor/registration-processor-printing-stage/README.md +++ b/registration-processor/post-processor/registration-processor-credential-requestor-stage/README.md @@ -1,7 +1,7 @@ -# Priting Stage +# Credential Requestor Stage ## About -Creates Credential Request for printing systems. +Creates Credential Request for internal/external systems. ## Default context, path, port Refert to [bootstrap properties](src/main/resources/bootstrap.properties) diff --git a/registration-processor/post-processor/registration-processor-printing-stage/pom.xml b/registration-processor/post-processor/registration-processor-credential-requestor-stage/pom.xml similarity index 94% rename from registration-processor/post-processor/registration-processor-printing-stage/pom.xml rename to registration-processor/post-processor/registration-processor-credential-requestor-stage/pom.xml index 5fe9b79df20..e716cc6f348 100644 --- a/registration-processor/post-processor/registration-processor-printing-stage/pom.xml +++ b/registration-processor/post-processor/registration-processor-credential-requestor-stage/pom.xml @@ -1,107 +1,111 @@ - - - 4.0.0 - - io.mosip.registrationprocessor - post-processor - 1.2.0.1-B3 - - registration-processor-printing-stage - 1.2.0.1-B3 - - UTF-8 - UTF-8 - - - - - org.springframework.cloud - spring-cloud-starter-config - ${spring-cloud-config.version} - - - org.mockito - mockito-core - ${mockito.version} - test - - - com.h2database - h2 - ${h2.version} - - - - - - org.springframework - spring-context - ${spring-framework.version} - - - org.springframework - spring-tx - ${spring-framework.version} - - - io.vertx - vertx-unit - ${vertx.version} - test - - - io.vertx - vertx-web-client - ${vertx.version} - - - org.apache.httpcomponents - httpmime - 4.3.1 - - - io.mosip.registrationprocessor - registration-processor-core - ${registration.processor.core.version} - - - io.mosip.registrationprocessor - registration-processor-registration-status-service-impl - ${registration.status.service.version} - - - io.mosip.registrationprocessor - registration-processor-rest-client - ${registration.processor.rest.client.version} - - - - junit - junit - test - - - org.powermock - powermock-module-junit4 - ${powermock.module.junit4.version} - test - - - org.powermock - powermock-api-mockito2 - ${powermock.api.mockito.version} - test - - - io.mosip.registrationprocessor - registration-processor-info-storage-service - ${packet.info.storage.service.version} - - - - - - - + + + 4.0.0 + + io.mosip.registrationprocessor + post-processor + 1.2.0.1-B3 + + registration-processor-credential-requestor-stage + 1.2.0.1-B3 + + UTF-8 + UTF-8 + + + + + org.springframework.cloud + spring-cloud-starter-config + ${spring-cloud-config.version} + + + org.mockito + mockito-core + ${mockito.version} + test + + + com.h2database + h2 + ${h2.version} + + + + + + org.springframework + spring-context + ${spring-framework.version} + + + org.springframework + spring-tx + ${spring-framework.version} + + + io.vertx + vertx-unit + ${vertx.version} + test + + + io.vertx + vertx-web-client + ${vertx.version} + + + org.apache.httpcomponents + httpmime + 4.3.1 + + + io.mosip.registrationprocessor + registration-processor-core + ${registration.processor.core.version} + + + io.mosip.registrationprocessor + registration-processor-registration-status-service-impl + ${registration.status.service.version} + + + io.mosip.registrationprocessor + registration-processor-rest-client + ${registration.processor.rest.client.version} + + + org.mvel + mvel2 + 2.4.12.Final + + + junit + junit + test + + + org.powermock + powermock-module-junit4 + ${powermock.module.junit4.version} + test + + + org.powermock + powermock-api-mockito2 + ${powermock.api.mockito.version} + test + + + io.mosip.registrationprocessor + registration-processor-info-storage-service + ${packet.info.storage.service.version} + + + + + + + diff --git a/registration-processor/post-processor/registration-processor-printing-stage/src/main/java/io/mosip/registration/processor/print/PrintStageApplication.java b/registration-processor/post-processor/registration-processor-credential-requestor-stage/src/main/java/io/mosip/registration/processor/credentialrequestor/CredentialRequestorStageApplication.java similarity index 68% rename from registration-processor/post-processor/registration-processor-printing-stage/src/main/java/io/mosip/registration/processor/print/PrintStageApplication.java rename to registration-processor/post-processor/registration-processor-credential-requestor-stage/src/main/java/io/mosip/registration/processor/credentialrequestor/CredentialRequestorStageApplication.java index 742d6a00973..25c6ce2c4be 100644 --- a/registration-processor/post-processor/registration-processor-printing-stage/src/main/java/io/mosip/registration/processor/print/PrintStageApplication.java +++ b/registration-processor/post-processor/registration-processor-credential-requestor-stage/src/main/java/io/mosip/registration/processor/credentialrequestor/CredentialRequestorStageApplication.java @@ -1,14 +1,14 @@ -package io.mosip.registration.processor.print; +package io.mosip.registration.processor.credentialrequestor; import org.springframework.context.annotation.AnnotationConfigApplicationContext; -import io.mosip.registration.processor.print.stage.PrintingStage; +import io.mosip.registration.processor.credentialrequestor.stage.CredentialRequestorStage; /** * @author M1048399 * */ -public class PrintStageApplication { +public class CredentialRequestorStageApplication { public static void main(String[] args) { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); @@ -19,7 +19,7 @@ public static void main(String[] args) { "io.mosip.registration.processor.packet.storage.config"); ctx.refresh(); - PrintingStage printStage = ctx.getBean(PrintingStage.class); + CredentialRequestorStage printStage = ctx.getBean(CredentialRequestorStage.class); printStage.deployVerticle(); } diff --git a/registration-processor/post-processor/registration-processor-credential-requestor-stage/src/main/java/io/mosip/registration/processor/credentialrequestor/config/CredentialRequestorConfigBean.java b/registration-processor/post-processor/registration-processor-credential-requestor-stage/src/main/java/io/mosip/registration/processor/credentialrequestor/config/CredentialRequestorConfigBean.java new file mode 100644 index 00000000000..344cb73d687 --- /dev/null +++ b/registration-processor/post-processor/registration-processor-credential-requestor-stage/src/main/java/io/mosip/registration/processor/credentialrequestor/config/CredentialRequestorConfigBean.java @@ -0,0 +1,15 @@ +package io.mosip.registration.processor.credentialrequestor.config; + +import io.mosip.registration.processor.credentialrequestor.util.CredentialPartnerUtil; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class CredentialRequestorConfigBean { + + @Bean + CredentialPartnerUtil credentialPartnerUtil() { + return new CredentialPartnerUtil(); + } + +} \ 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/dto/CredentialPartner.java b/registration-processor/post-processor/registration-processor-credential-requestor-stage/src/main/java/io/mosip/registration/processor/credentialrequestor/dto/CredentialPartner.java new file mode 100644 index 00000000000..4cd399b0e5b --- /dev/null +++ b/registration-processor/post-processor/registration-processor-credential-requestor-stage/src/main/java/io/mosip/registration/processor/credentialrequestor/dto/CredentialPartner.java @@ -0,0 +1,16 @@ +package io.mosip.registration.processor.credentialrequestor.dto; + +import lombok.Data; + +import java.util.List; + +@Data +public class CredentialPartner { + private String id; + private String partnerId; + private String credentialType; + private String template; + private String appIdBasedCredentialIdSuffix; + private List process; + private List metaInfoFields; +} diff --git a/registration-processor/post-processor/registration-processor-credential-requestor-stage/src/main/java/io/mosip/registration/processor/credentialrequestor/dto/CredentialPartnersList.java b/registration-processor/post-processor/registration-processor-credential-requestor-stage/src/main/java/io/mosip/registration/processor/credentialrequestor/dto/CredentialPartnersList.java new file mode 100644 index 00000000000..72afbab0056 --- /dev/null +++ b/registration-processor/post-processor/registration-processor-credential-requestor-stage/src/main/java/io/mosip/registration/processor/credentialrequestor/dto/CredentialPartnersList.java @@ -0,0 +1,10 @@ +package io.mosip.registration.processor.credentialrequestor.dto; + +import lombok.Data; + +import java.util.List; + +@Data +public class CredentialPartnersList { + private List partners; +} diff --git a/registration-processor/post-processor/registration-processor-printing-stage/src/main/java/io/mosip/registration/processor/print/stage/PrintingStage.java b/registration-processor/post-processor/registration-processor-credential-requestor-stage/src/main/java/io/mosip/registration/processor/credentialrequestor/stage/CredentialRequestorStage.java similarity index 67% rename from registration-processor/post-processor/registration-processor-printing-stage/src/main/java/io/mosip/registration/processor/print/stage/PrintingStage.java rename to registration-processor/post-processor/registration-processor-credential-requestor-stage/src/main/java/io/mosip/registration/processor/credentialrequestor/stage/CredentialRequestorStage.java index c46df5eec54..39ee23c62ca 100644 --- a/registration-processor/post-processor/registration-processor-printing-stage/src/main/java/io/mosip/registration/processor/print/stage/PrintingStage.java +++ b/registration-processor/post-processor/registration-processor-credential-requestor-stage/src/main/java/io/mosip/registration/processor/credentialrequestor/stage/CredentialRequestorStage.java @@ -1,448 +1,479 @@ -package io.mosip.registration.processor.print.stage; - -import java.io.File; -import java.io.IOException; -import java.security.NoSuchAlgorithmException; -import java.security.SecureRandom; -import java.time.LocalDateTime; -import java.time.format.DateTimeFormatter; -import java.util.ArrayList; -import java.util.List; -import java.util.Random; - -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.cloud.context.config.annotation.RefreshScope; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.core.env.Environment; -import org.springframework.http.MediaType; -import org.springframework.scheduling.annotation.EnableScheduling; -import org.springframework.scheduling.annotation.Scheduled; -import org.springframework.stereotype.Service; - -import com.fasterxml.jackson.databind.ObjectMapper; - -import io.mosip.kernel.core.exception.ServiceError; -import io.mosip.kernel.core.logger.spi.Logger; -import io.mosip.kernel.core.util.DateUtils; -import io.mosip.registration.processor.core.abstractverticle.MessageBusAddress; -import io.mosip.registration.processor.core.abstractverticle.MessageDTO; -import io.mosip.registration.processor.core.abstractverticle.MosipEventBus; -import io.mosip.registration.processor.core.abstractverticle.MosipRouter; -import io.mosip.registration.processor.core.abstractverticle.MosipVerticleAPIManager; -import io.mosip.registration.processor.core.code.ApiName; -import io.mosip.registration.processor.core.code.EventId; -import io.mosip.registration.processor.core.code.EventName; -import io.mosip.registration.processor.core.code.EventType; -import io.mosip.registration.processor.core.code.ModuleName; -import io.mosip.registration.processor.core.code.RegistrationTransactionStatusCode; -import io.mosip.registration.processor.core.code.RegistrationTransactionTypeCode; -import io.mosip.registration.processor.core.common.rest.dto.ErrorDTO; -import io.mosip.registration.processor.core.constant.IdType; -import io.mosip.registration.processor.core.constant.LoggerFileConstant; -import io.mosip.registration.processor.core.constant.VidType; -import io.mosip.registration.processor.core.exception.ApisResourceAccessException; -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.RequestWrapper; -import io.mosip.registration.processor.core.http.ResponseWrapper; -import io.mosip.registration.processor.core.idrepo.dto.CredentialRequestDto; -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.logger.LogDescription; -import io.mosip.registration.processor.core.logger.RegProcessorLogger; -import io.mosip.registration.processor.core.spi.restclient.RegistrationProcessorRestClientService; -import io.mosip.registration.processor.core.status.util.StatusUtil; -import io.mosip.registration.processor.core.status.util.TrimExceptionMessage; -import io.mosip.registration.processor.core.util.JsonUtil; -import io.mosip.registration.processor.packet.storage.utils.Utilities; -import io.mosip.registration.processor.print.stage.exception.VidNotAvailableException; -import io.mosip.registration.processor.rest.client.audit.builder.AuditLogRequestBuilder; -import io.mosip.registration.processor.status.dto.InternalRegistrationStatusDto; -import io.mosip.registration.processor.status.dto.RegistrationStatusDto; -import io.mosip.registration.processor.status.service.RegistrationStatusService; - -/** - * The Class PrintStage. - * - * @author M1048358 Alok - * @author Ranjitha Siddegowda - * @author Sowmya - */ -@RefreshScope -@Service -@Configuration -@EnableScheduling -@ComponentScan(basePackages = { "${mosip.auth.adapter.impl.basepackage}", - "io.mosip.registration.processor.core.config", - "io.mosip.registration.processor.stages.config", - "io.mosip.registration.processor.print.config", - "io.mosip.registrationprocessor.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.kernel.idobjectvalidator.config", - "io.mosip.registration.processor.core.kernel.beans" }) -public class PrintingStage extends MosipVerticleAPIManager { - - private static final String STAGE_PROPERTY_PREFIX = "mosip.regproc.printing."; - private Random sr = null; - private static final int max = 999999; - private static final int min = 100000; - - /** The Constant FILE_SEPARATOR. */ - public static final String FILE_SEPARATOR = File.separator; - - - /** The reg proc logger. */ - private static Logger regProcLogger = RegProcessorLogger.getLogger(PrintingStage.class); - - /** The cluster manager url. */ - @Value("${vertx.cluster.configuration}") - private String clusterManagerUrl; - - - /** The core audit request builder. */ - @Autowired - private AuditLogRequestBuilder auditLogRequestBuilder; - - /** The mosip event bus. */ - private MosipEventBus mosipEventBus; - - /** The registration status service. */ - @Autowired - RegistrationStatusService registrationStatusService; - - /** worker pool size. */ - @Value("${worker.pool.size}") - private Integer workerPoolSize; - - /** After this time intervel, message should be considered as expired (In seconds). */ - @Value("${mosip.regproc.printing.message.expiry-time-limit}") - private Long messageExpiryTimeLimit; - - - @Value("${mosip.registration.processor.encrypt:false}") - private boolean encrypt; - - /** Mosip router for APIs */ - @Autowired - MosipRouter router; - - boolean isConnection = false; - - private static final String SEPERATOR = "::"; - - @Autowired - private RegistrationProcessorRestClientService restClientService; - - @Autowired - private ObjectMapper mapper; - - @Autowired - private Environment env; - - private static final String DATETIME_PATTERN = "mosip.registration.processor.datetime.pattern"; - - - @Autowired - private Utilities utilities; - - @Override - protected String getPropertyPrefix() { - return STAGE_PROPERTY_PREFIX; - } - - /** - * Deploy verticle. - */ - public void deployVerticle() { - mosipEventBus = this.getEventBus(this, clusterManagerUrl, workerPoolSize); - this.consumeAndSend(mosipEventBus, MessageBusAddress.PRINTING_BUS_IN, MessageBusAddress.PRINTING_BUS_OUT, - messageExpiryTimeLimit); - } - - /* - * (non-Javadoc) - * - * @see - * io.mosip.registration.processor.core.spi.eventbus.EventBusManager#process( - * java.lang.Object) - */ - @Override - public MessageDTO process(MessageDTO object) { - TrimExceptionMessage trimeExpMessage = new TrimExceptionMessage(); - object.setMessageBusAddress(MessageBusAddress.PRINTING_BUS_IN); - object.setInternalError(Boolean.FALSE); - object.setIsValid(Boolean.FALSE); - LogDescription description = new LogDescription(); - - boolean isTransactionSuccessful = false; - String uin = null; - String regId = object.getRid(); - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - regId, "PrintStage::process()::entry"); - - InternalRegistrationStatusDto registrationStatusDto = null; - RequestWrapper requestWrapper = new RequestWrapper<>(); - ResponseWrapper responseWrapper = null; - CredentialResponseDto credentialResponseDto; - try { - registrationStatusDto = registrationStatusService.getRegistrationStatus( - regId, object.getReg_type(), object.getIteration(), object.getWorkflowInstanceId()); - registrationStatusDto - .setLatestTransactionTypeCode(RegistrationTransactionTypeCode.PRINT_SERVICE.toString()); - registrationStatusDto.setRegistrationStageName(getStageName()); - JSONObject jsonObject = utilities.retrieveUIN(regId); - uin = JsonUtil.getJSONValue(jsonObject, IdType.UIN.toString()); - if (uin == null) { - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), - LoggerFileConstant.REGISTRATIONID.toString(), null, - PlatformErrorMessages.RPR_PRT_UIN_NOT_FOUND_IN_DATABASE.name()); - object.setIsValid(Boolean.FALSE); - isTransactionSuccessful = false; - description.setMessage(PlatformErrorMessages.RPR_PRT_PRINT_REQUEST_FAILED.getMessage()); - description.setCode(PlatformErrorMessages.RPR_PRT_PRINT_REQUEST_FAILED.getCode()); - - registrationStatusDto.setStatusComment( - StatusUtil.UIN_NOT_FOUND_IN_DATABASE.getMessage()); - registrationStatusDto.setSubStatusCode(StatusUtil.UIN_NOT_FOUND_IN_DATABASE.getCode()); - registrationStatusDto - .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.FAILED.toString()); - registrationStatusDto - .setLatestTransactionTypeCode(RegistrationTransactionTypeCode.PRINT_SERVICE.toString()); - - } - else { - String vid = getVid(uin); - CredentialRequestDto credentialRequestDto = getCredentialRequestDto(vid); - requestWrapper.setId(env.getProperty("mosip.registration.processor.credential.request.service.id")); - DateTimeFormatter format = DateTimeFormatter.ofPattern(env.getProperty(DATETIME_PATTERN)); - LocalDateTime localdatetime = LocalDateTime - .parse(DateUtils.getUTCCurrentDateTimeString(env.getProperty(DATETIME_PATTERN)), format); - requestWrapper.setRequesttime(localdatetime); - requestWrapper.setVersion("1.0"); - requestWrapper.setRequest(credentialRequestDto); - responseWrapper = (ResponseWrapper) restClientService.postApi(ApiName.CREDENTIALREQUEST, null, - null, - requestWrapper, ResponseWrapper.class, MediaType.APPLICATION_JSON); - if (responseWrapper.getErrors() != null && !responseWrapper.getErrors().isEmpty()) { - ErrorDTO error = responseWrapper.getErrors().get(0); - object.setIsValid(Boolean.FALSE); - isTransactionSuccessful = false; - description.setMessage(PlatformErrorMessages.RPR_PRT_PRINT_REQUEST_FAILED.getMessage()); - description.setCode(PlatformErrorMessages.RPR_PRT_PRINT_REQUEST_FAILED.getCode()); - - registrationStatusDto.setStatusComment( - StatusUtil.PRINT_REQUEST_FAILED.getMessage() + SEPERATOR + error.getMessage()); - registrationStatusDto.setSubStatusCode(StatusUtil.PRINT_REQUEST_FAILED.getCode()); - registrationStatusDto - .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.REPROCESS.toString()); - registrationStatusDto - .setLatestTransactionTypeCode(RegistrationTransactionTypeCode.PRINT_SERVICE.toString()); - } else { - credentialResponseDto = mapper.readValue(mapper.writeValueAsString(responseWrapper.getResponse()), - CredentialResponseDto.class); - - registrationStatusDto.setRefId(credentialResponseDto.getRequestId()); - object.setIsValid(Boolean.TRUE); - isTransactionSuccessful = true; - description.setMessage(PlatformSuccessMessages.RPR_PRINT_STAGE_REQUEST_SUCCESS.getMessage()); - description.setCode(PlatformSuccessMessages.RPR_PRINT_STAGE_REQUEST_SUCCESS.getCode()); - registrationStatusDto.setStatusComment( - trimeExpMessage.trimExceptionMessage(StatusUtil.PRINT_REQUEST_SUCCESS.getMessage())); - registrationStatusDto.setSubStatusCode(StatusUtil.PRINT_REQUEST_SUCCESS.getCode()); - registrationStatusDto - .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.PROCESSED.toString()); - registrationStatusDto - .setLatestTransactionTypeCode(RegistrationTransactionTypeCode.PRINT_SERVICE.toString()); - - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), - LoggerFileConstant.REGISTRATIONID.toString(), regId, "PrintStage::process()::exit"); - } - } - } catch (ApisResourceAccessException e) { - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - regId, PlatformErrorMessages.RPR_PRT_PRINT_REQUEST_FAILED.name() + e.getMessage() - + ExceptionUtils.getStackTrace(e)); - registrationStatusDto - .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.REPROCESS.toString()); - registrationStatusDto.setStatusComment(trimeExpMessage.trimExceptionMessage( - StatusUtil.API_RESOUCE_ACCESS_FAILED.getMessage() + SEPERATOR + e.getMessage())); - registrationStatusDto.setSubStatusCode(StatusUtil.API_RESOUCE_ACCESS_FAILED.getCode()); - description.setMessage(PlatformErrorMessages.RPR_PRT_PRINT_REQUEST_FAILED.getMessage()); - description.setCode(PlatformErrorMessages.RPR_PRT_PRINT_REQUEST_FAILED.getCode()); - object.setInternalError(Boolean.TRUE); - } catch (IOException e) { - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - regId, PlatformErrorMessages.RPR_PRT_PRINT_REQUEST_FAILED.name() + e.getMessage() - + ExceptionUtils.getStackTrace(e)); - registrationStatusDto - .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.REPROCESS.toString()); - registrationStatusDto.setStatusComment( - trimeExpMessage.trimExceptionMessage(StatusUtil.IO_EXCEPTION.getMessage() + e.getMessage())); - registrationStatusDto.setSubStatusCode(StatusUtil.IO_EXCEPTION.getCode()); - description.setMessage(PlatformErrorMessages.RPR_PRT_PRINT_REQUEST_FAILED.getMessage()); - description.setCode(PlatformErrorMessages.RPR_PRT_PRINT_REQUEST_FAILED.getCode()); - object.setInternalError(Boolean.TRUE); - } catch (VidNotAvailableException e) { - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - regId, PlatformErrorMessages.RPR_PRT_PRINT_REQUEST_FAILED.name() + e.getMessage() - + ExceptionUtils.getStackTrace(e)); - registrationStatusDto - .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.REPROCESS.toString()); - registrationStatusDto.setStatusComment( - trimeExpMessage.trimExceptionMessage(StatusUtil.VID_NOT_AVAILABLE.getMessage())); - registrationStatusDto.setSubStatusCode(StatusUtil.VID_NOT_AVAILABLE.getCode()); - description.setMessage(PlatformErrorMessages.RPR_PRT_PRINT_REQUEST_FAILED.getMessage()); - description.setCode(PlatformErrorMessages.RPR_PRT_PRINT_REQUEST_FAILED.getCode()); - object.setInternalError(Boolean.TRUE); - } catch (Exception e) { - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - regId, PlatformErrorMessages.RPR_PRT_PRINT_REQUEST_FAILED.name() + e.getMessage() - + ExceptionUtils.getStackTrace(e)); - registrationStatusDto - .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.REPROCESS.toString()); - registrationStatusDto.setStatusComment( - trimeExpMessage.trimExceptionMessage(StatusUtil.UNKNOWN_EXCEPTION_OCCURED.getMessage())); - registrationStatusDto.setSubStatusCode(StatusUtil.UNKNOWN_EXCEPTION_OCCURED.getCode()); - description.setMessage(PlatformErrorMessages.RPR_PRT_PRINT_REQUEST_FAILED.getMessage()); - description.setCode(PlatformErrorMessages.RPR_PRT_PRINT_REQUEST_FAILED.getCode()); - object.setInternalError(Boolean.TRUE); - } - finally { - if (object.getInternalError()) { - updateErrorFlags(registrationStatusDto, object); - } - String eventId = ""; - String eventName = ""; - String eventType = ""; - eventId = isTransactionSuccessful ? EventId.RPR_402.toString() : EventId.RPR_405.toString(); - eventName = eventId.equalsIgnoreCase(EventId.RPR_402.toString()) ? EventName.UPDATE.toString() - : EventName.EXCEPTION.toString(); - eventType = eventId.equalsIgnoreCase(EventId.RPR_402.toString()) ? EventType.BUSINESS.toString() - : EventType.SYSTEM.toString(); - /** Module-Id can be Both Success/Error code */ - String moduleId = isTransactionSuccessful - ? PlatformSuccessMessages.RPR_PRINT_STAGE_REQUEST_SUCCESS.getCode() - : description.getCode(); - String moduleName = ModuleName.PRINT_STAGE.toString(); - registrationStatusService.updateRegistrationStatus(registrationStatusDto, moduleId, moduleName); - - auditLogRequestBuilder.createAuditRequestBuilder(description.getMessage(), eventId, eventName, eventType, - moduleId, moduleName, regId); - - } - - return object; - } - - private CredentialRequestDto getCredentialRequestDto(String vid) { - CredentialRequestDto credentialRequestDto = new CredentialRequestDto(); - - credentialRequestDto.setCredentialType(env.getProperty("mosip.registration.processor.credentialtype")); - - credentialRequestDto.setEncrypt(encrypt); - - credentialRequestDto.setId(vid); - - credentialRequestDto.setIssuer(env.getProperty("mosip.registration.processor.issuer")); - - credentialRequestDto.setEncryptionKey(generatePin()); - - return credentialRequestDto; - } - - - /* - * (non-Javadoc) - * - * @see io.vertx.core.AbstractVerticle#start() - */ - @Override - public void start() { - router.setRoute(this.postUrl(getVertx(), - MessageBusAddress.PRINTING_BUS_IN, MessageBusAddress.PRINTING_BUS_OUT)); - this.createServer(router.getRouter(), getPort()); - } - - public String generatePin() { - if (sr == null) - instantiate(); - int randomInteger = sr.nextInt(max - min) + min; - return String.valueOf(randomInteger); - } - - @SuppressWarnings("unchecked") - private String getVid(String uin) throws ApisResourceAccessException, VidNotAvailableException { - List pathsegments = new ArrayList<>(); - pathsegments.add(uin); - String vid = null; - - VidsInfosDTO vidsInfosDTO; - - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), "", - "PrintServiceImpl::getVid():: get GETVIDSBYUIN service call started with request data : " - ); - - vidsInfosDTO = (VidsInfosDTO) restClientService.getApi(ApiName.GETVIDSBYUIN, - pathsegments, "", "", VidsInfosDTO.class); - - if (vidsInfosDTO.getErrors() != null && !vidsInfosDTO.getErrors().isEmpty()) { - ServiceError error = vidsInfosDTO.getErrors().get(0); - throw new VidNotAvailableException(PlatformErrorMessages.RPR_PRT_VID_NOT_AVAILABLE_EXCEPTION.getCode(), - error.getMessage()); - - } else { - if(vidsInfosDTO.getResponse()!=null && !vidsInfosDTO.getResponse().isEmpty()) { - for (VidInfoDTO VidInfoDTO : vidsInfosDTO.getResponse()) { - if (VidType.PERPETUAL.name().equalsIgnoreCase(VidInfoDTO.getVidType())) { - vid = VidInfoDTO.getVid(); - break; - } - } - if (vid == null) { - throw new VidNotAvailableException( - PlatformErrorMessages.RPR_PRT_VID_NOT_AVAILABLE_EXCEPTION.getCode(), - PlatformErrorMessages.RPR_PRT_VID_NOT_AVAILABLE_EXCEPTION.getMessage()); - } - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), - LoggerFileConstant.REGISTRATIONID.toString(), "", - "PrintServiceImpl::getVid():: get GETVIDSBYUIN service call ended successfully"); - - }else { - throw new VidNotAvailableException(PlatformErrorMessages.RPR_PRT_VID_NOT_AVAILABLE_EXCEPTION.getCode(), - PlatformErrorMessages.RPR_PRT_VID_NOT_AVAILABLE_EXCEPTION.getMessage()); - } - - } - - return vid; - } - - private void updateErrorFlags(InternalRegistrationStatusDto registrationStatusDto, MessageDTO object) { - object.setInternalError(true); - if (registrationStatusDto.getLatestTransactionStatusCode() - .equalsIgnoreCase(RegistrationTransactionStatusCode.REPROCESS.toString())) { - object.setIsValid(true); - } else { - object.setIsValid(false); - } - } - - @Scheduled(fixedDelayString = "${mosip.regproc.printstage.pingeneration.refresh.millisecs:1800000}", - initialDelayString = "${mosip.regproc.printstage.pingeneration.refresh.delay-on-startup.millisecs:5000}") - private void instantiate() { - regProcLogger.debug("Instantiating SecureRandom for credential pin generation............"); - try { - sr = SecureRandom.getInstance("SHA1PRNG"); - } catch (NoSuchAlgorithmException e) { - regProcLogger.error("Could not instantiate SecureRandom for credential pin generation", e); - } - } +package io.mosip.registration.processor.credentialrequestor.stage; + +import com.fasterxml.jackson.databind.ObjectMapper; +import io.mosip.kernel.core.exception.BaseUncheckedException; +import io.mosip.kernel.core.exception.ServiceError; +import io.mosip.kernel.core.logger.spi.Logger; +import io.mosip.kernel.core.util.DateUtils; +import io.mosip.registration.processor.core.abstractverticle.*; +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; +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.RequestWrapper; +import io.mosip.registration.processor.core.http.ResponseWrapper; +import io.mosip.registration.processor.core.idrepo.dto.CredentialRequestDto; +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.logger.LogDescription; +import io.mosip.registration.processor.core.logger.RegProcessorLogger; +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.credentialrequestor.dto.CredentialPartner; +import io.mosip.registration.processor.credentialrequestor.stage.exception.VidNotAvailableException; +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.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.service.RegistrationStatusService; +import org.apache.commons.collections.CollectionUtils; +import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang3.exception.ExceptionUtils; +import org.json.JSONArray; +import org.json.simple.JSONObject; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.cloud.context.config.annotation.RefreshScope; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.env.Environment; +import org.springframework.http.MediaType; +import org.springframework.scheduling.annotation.EnableScheduling; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Service; + +import java.io.IOException; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.*; +import java.util.stream.Collectors; + +/** + * The Class PrintStage. + * + * @author M1048358 Alok + * @author Ranjitha Siddegowda + * @author Sowmya + */ +@RefreshScope +@Service +@Configuration +@EnableScheduling +@ComponentScan(basePackages = { "${mosip.auth.adapter.impl.basepackage}", + "io.mosip.registration.processor.core.config", + "io.mosip.registration.processor.stages.config", + "io.mosip.registration.processor.credentialrequestor.config", + "io.mosip.registrationprocessor.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.kernel.idobjectvalidator.config", + "io.mosip.registration.processor.core.kernel.beans" }) +public class CredentialRequestorStage extends MosipVerticleAPIManager { + + private static final String STAGE_PROPERTY_PREFIX = "mosip.regproc.credentialrequestor."; + private Random sr = null; + private static final int max = 999999; + private static final int min = 100000; + + /** The reg proc logger. */ + private static Logger regProcLogger = RegProcessorLogger.getLogger(CredentialRequestorStage.class); + + /** The cluster manager url. */ + @Value("${vertx.cluster.configuration}") + private String clusterManagerUrl; + + + /** The core audit request builder. */ + @Autowired + private AuditLogRequestBuilder auditLogRequestBuilder; + + /** The mosip event bus. */ + private MosipEventBus mosipEventBus; + + /** The registration status service. */ + @Autowired + RegistrationStatusService registrationStatusService; + + /** worker pool size. */ + @Value("${worker.pool.size}") + private Integer workerPoolSize; + + /** After this time intervel, message should be considered as expired (In seconds). */ + @Value("${mosip.regproc.credentialrequestor.message.expiry-time-limit}") + private Long messageExpiryTimeLimit; + + @Value("${mosip.registration.processor.encrypt:false}") + private boolean encrypt; + + /** Mosip router for APIs */ + @Autowired + MosipRouter router; + + private static final String SEPERATOR = "::"; + + @Autowired + private RegistrationProcessorRestClientService restClientService; + + @Autowired + private ObjectMapper mapper; + + @Autowired + private Environment env; + + private static final String DATETIME_PATTERN = "mosip.registration.processor.datetime.pattern"; + + private static final String ISSUERS = "mosip.registration.processor.issuer"; + + @Value("#{T(java.util.Arrays).asList('${mosip.registration.processor.credential.default.partner-ids:}')}") + private List defaultPartners; + + private static String COMMA = ","; + private static String HASH_DELIMITER = "#"; + + @Autowired + private Utilities utilities; + + @Autowired + private CredentialPartnerUtil credentialPartnerUtil; + + @Override + protected String getPropertyPrefix() { + return STAGE_PROPERTY_PREFIX; + } + + /** + * Deploy verticle. + */ + public void deployVerticle() { + mosipEventBus = this.getEventBus(this, clusterManagerUrl, workerPoolSize); + this.consumeAndSend(mosipEventBus, MessageBusAddress.PRINTING_BUS_IN, MessageBusAddress.PRINTING_BUS_OUT, + messageExpiryTimeLimit); + } + + /* + * (non-Javadoc) + * + * @see + * io.mosip.registration.processor.core.spi.eventbus.EventBusManager#process( + * java.lang.Object) + */ + @Override + public MessageDTO process(MessageDTO object) { + TrimExceptionMessage trimeExpMessage = new TrimExceptionMessage(); + object.setMessageBusAddress(MessageBusAddress.PRINTING_BUS_IN); + object.setInternalError(Boolean.FALSE); + object.setIsValid(Boolean.FALSE); + LogDescription description = new LogDescription(); + + boolean isTransactionSuccessful = false; + String uin = null; + String refIds = null; + String regId = object.getRid(); + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + regId, "PrintStage::process()::entry"); + + InternalRegistrationStatusDto registrationStatusDto = null; + RequestWrapper requestWrapper = new RequestWrapper<>(); + ResponseWrapper responseWrapper = null; + CredentialResponseDto credentialResponseDto; + try { + registrationStatusDto = registrationStatusService.getRegistrationStatus( + regId, object.getReg_type(), object.getIteration(), object.getWorkflowInstanceId()); + registrationStatusDto + .setLatestTransactionTypeCode(RegistrationTransactionTypeCode.PRINT_SERVICE.toString()); + registrationStatusDto.setRegistrationStageName(getStageName()); + JSONObject jsonObject = utilities.retrieveUIN(regId); + uin = JsonUtil.getJSONValue(jsonObject, IdType.UIN.toString()); + if (uin == null) { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString(), null, + PlatformErrorMessages.RPR_PRT_UIN_NOT_FOUND_IN_DATABASE.name()); + object.setIsValid(Boolean.FALSE); + isTransactionSuccessful = false; + description.setMessage(PlatformErrorMessages.RPR_PRT_PRINT_REQUEST_FAILED.getMessage()); + description.setCode(PlatformErrorMessages.RPR_PRT_PRINT_REQUEST_FAILED.getCode()); + + registrationStatusDto.setStatusComment( + StatusUtil.UIN_NOT_FOUND_IN_DATABASE.getMessage()); + registrationStatusDto.setSubStatusCode(StatusUtil.UIN_NOT_FOUND_IN_DATABASE.getCode()); + registrationStatusDto + .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.FAILED.toString()); + registrationStatusDto + .setLatestTransactionTypeCode(RegistrationTransactionTypeCode.PRINT_SERVICE.toString()); + + } else { + requestWrapper.setId(env.getProperty("mosip.registration.processor.credential.request.service.id")); + DateTimeFormatter format = DateTimeFormatter.ofPattern(env.getProperty(DATETIME_PATTERN)); + requestWrapper.setVersion("1.0"); + List allIssuerList = credentialPartnerUtil.getAllCredentialPartners().getPartners(); + // filtering with default partner ids and process + List filteredPartners = allIssuerList.stream() + .filter(issuer -> defaultPartners.contains(issuer.getId())) + .filter(issuer -> (issuer.getProcess() == null) || (issuer.getProcess().contains(object.getReg_type()))) + .collect(Collectors.toList()); + filteredPartners.addAll(credentialPartnerUtil.getCredentialPartners( + regId, registrationStatusDto.getRegistrationType(), jsonObject)); + for (CredentialPartner key : filteredPartners) { + CredentialRequestDto credentialRequestDto = getCredentialRequestDto(regId, registrationStatusDto.getRegistrationType(), key); + LocalDateTime localdatetime = LocalDateTime.parse( + DateUtils.getUTCCurrentDateTimeString(env.getProperty(DATETIME_PATTERN)), format); + requestWrapper.setRequesttime(localdatetime); + requestWrapper.setRequest(credentialRequestDto); + // issuers with appIdBasedCredentialIdSuffix is calling v1 api and for others stage is calling v2 api for credential + if (StringUtils.isNotEmpty(key.getAppIdBasedCredentialIdSuffix())) { + List pathsegments = new ArrayList<>(); + pathsegments.add(regId + key.getAppIdBasedCredentialIdSuffix()); // #PDF suffix is added to identify the requested credential via rid + responseWrapper = (ResponseWrapper) restClientService.postApi(ApiName.CREDENTIALREQUESTV2, MediaType.APPLICATION_JSON, pathsegments, null, + null, requestWrapper, ResponseWrapper.class); + } else { + responseWrapper = (ResponseWrapper) restClientService.postApi(ApiName.CREDENTIALREQUEST, null, null, + requestWrapper, ResponseWrapper.class, MediaType.APPLICATION_JSON); + } + if (responseWrapper.getErrors() != null && !responseWrapper.getErrors().isEmpty()) { + ErrorDTO error = responseWrapper.getErrors().get(0); + object.setIsValid(Boolean.FALSE); + isTransactionSuccessful = false; + registrationStatusDto.setRefId(refIds); + description.setMessage(PlatformErrorMessages.RPR_PRT_PRINT_REQUEST_FAILED.getMessage()); + description.setCode(PlatformErrorMessages.RPR_PRT_PRINT_REQUEST_FAILED.getCode()); + + registrationStatusDto.setStatusComment( + StatusUtil.PRINT_REQUEST_FAILED.getMessage() + SEPERATOR + error.getMessage()); + registrationStatusDto.setSubStatusCode(StatusUtil.PRINT_REQUEST_FAILED.getCode()); + registrationStatusDto + .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.REPROCESS.toString()); + registrationStatusDto + .setLatestTransactionTypeCode(RegistrationTransactionTypeCode.PRINT_SERVICE.toString()); + break; + } else { + credentialResponseDto = mapper.readValue(mapper.writeValueAsString(responseWrapper.getResponse()), + CredentialResponseDto.class); + refIds = credentialResponseDto.getRequestId(); + isTransactionSuccessful = true; + } + } + if (isTransactionSuccessful) { + registrationStatusDto.setRefId(refIds); + object.setIsValid(Boolean.TRUE); + description.setMessage(PlatformSuccessMessages.RPR_PRINT_STAGE_REQUEST_SUCCESS.getMessage()); + description.setCode(PlatformSuccessMessages.RPR_PRINT_STAGE_REQUEST_SUCCESS.getCode()); + registrationStatusDto.setStatusComment( + trimeExpMessage.trimExceptionMessage(StatusUtil.PRINT_REQUEST_SUCCESS.getMessage())); + registrationStatusDto.setSubStatusCode(StatusUtil.PRINT_REQUEST_SUCCESS.getCode()); + registrationStatusDto + .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.PROCESSED.toString()); + registrationStatusDto + .setLatestTransactionTypeCode(RegistrationTransactionTypeCode.PRINT_SERVICE.toString()); + + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString(), regId, "PrintStage::process()::exit"); + } + } + } catch (ApisResourceAccessException e) { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + regId, PlatformErrorMessages.RPR_PRT_PRINT_REQUEST_FAILED.name() + e.getMessage() + + ExceptionUtils.getStackTrace(e)); + registrationStatusDto + .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.REPROCESS.toString()); + registrationStatusDto.setStatusComment(trimeExpMessage.trimExceptionMessage( + StatusUtil.API_RESOUCE_ACCESS_FAILED.getMessage() + SEPERATOR + e.getMessage())); + registrationStatusDto.setSubStatusCode(StatusUtil.API_RESOUCE_ACCESS_FAILED.getCode()); + description.setMessage(PlatformErrorMessages.RPR_PRT_PRINT_REQUEST_FAILED.getMessage()); + description.setCode(PlatformErrorMessages.RPR_PRT_PRINT_REQUEST_FAILED.getCode()); + object.setInternalError(Boolean.TRUE); + } catch (IOException e) { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + regId, PlatformErrorMessages.RPR_PRT_PRINT_REQUEST_FAILED.name() + e.getMessage() + + ExceptionUtils.getStackTrace(e)); + registrationStatusDto + .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.REPROCESS.toString()); + registrationStatusDto.setStatusComment( + trimeExpMessage.trimExceptionMessage(StatusUtil.IO_EXCEPTION.getMessage() + e.getMessage())); + registrationStatusDto.setSubStatusCode(StatusUtil.IO_EXCEPTION.getCode()); + description.setMessage(PlatformErrorMessages.RPR_PRT_PRINT_REQUEST_FAILED.getMessage()); + description.setCode(PlatformErrorMessages.RPR_PRT_PRINT_REQUEST_FAILED.getCode()); + object.setInternalError(Boolean.TRUE); + } catch (Exception e) { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + regId, PlatformErrorMessages.RPR_PRT_PRINT_REQUEST_FAILED.name() + e.getMessage() + + ExceptionUtils.getStackTrace(e)); + registrationStatusDto + .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.REPROCESS.toString()); + registrationStatusDto.setStatusComment( + trimeExpMessage.trimExceptionMessage(StatusUtil.UNKNOWN_EXCEPTION_OCCURED.getMessage())); + registrationStatusDto.setSubStatusCode(StatusUtil.UNKNOWN_EXCEPTION_OCCURED.getCode()); + description.setMessage(PlatformErrorMessages.RPR_PRT_PRINT_REQUEST_FAILED.getMessage()); + description.setCode(PlatformErrorMessages.RPR_PRT_PRINT_REQUEST_FAILED.getCode()); + object.setInternalError(Boolean.TRUE); + } + finally { + if (object.getInternalError()) { + updateErrorFlags(registrationStatusDto, object); + } + String eventId = ""; + String eventName = ""; + String eventType = ""; + eventId = isTransactionSuccessful ? EventId.RPR_402.toString() : EventId.RPR_405.toString(); + eventName = eventId.equalsIgnoreCase(EventId.RPR_402.toString()) ? EventName.UPDATE.toString() + : EventName.EXCEPTION.toString(); + eventType = eventId.equalsIgnoreCase(EventId.RPR_402.toString()) ? EventType.BUSINESS.toString() + : EventType.SYSTEM.toString(); + /** Module-Id can be Both Success/Error code */ + String moduleId = isTransactionSuccessful + ? PlatformSuccessMessages.RPR_PRINT_STAGE_REQUEST_SUCCESS.getCode() + : description.getCode(); + String moduleName = ModuleName.PRINT_STAGE.toString(); + registrationStatusService.updateRegistrationStatus(registrationStatusDto, moduleId, moduleName); + + auditLogRequestBuilder.createAuditRequestBuilder(description.getMessage(), eventId, eventName, eventType, + moduleId, moduleName, regId); + + } + + return object; + } + + private CredentialRequestDto getCredentialRequestDto(String regId, String process, CredentialPartner key) { + CredentialRequestDto credentialRequestDto = new CredentialRequestDto(); + Map additionalAttributes=new HashMap<>(); + + credentialRequestDto.setCredentialType(key.getCredentialType()); + credentialRequestDto.setEncrypt(encrypt); + + credentialRequestDto.setId(regId); + + credentialRequestDto.setIssuer(key.getPartnerId()); + + credentialRequestDto.setEncryptionKey(generatePin()); + additionalAttributes.put("templateTypeCode", key.getTemplate()); + additionalAttributes.put("registrationId", regId); + if (CollectionUtils.isNotEmpty(key.getMetaInfoFields())) + getAdditionalCredentialFields(regId, process, key.getMetaInfoFields(), additionalAttributes); + credentialRequestDto.setAdditionalData(additionalAttributes); + + return credentialRequestDto; + } + + private void getAdditionalCredentialFields(String regId, String process, + List metaInfoFields, + Map additionalAttributes) { + try { + Map metaInfo = utilities.getPacketManagerService().getMetaInfo(regId, process, ProviderStageName.CREDENTIAL_REQUESTOR); + JSONArray metadata = new JSONArray(metaInfo.get(JsonConstant.METADATA)); + for(int i=0; i pathsegments = new ArrayList<>(); + pathsegments.add(uin); + String vid = null; + + VidsInfosDTO vidsInfosDTO; + + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), "", + "PrintServiceImpl::getVid():: get GETVIDSBYUIN service call started with request data : " + ); + + vidsInfosDTO = (VidsInfosDTO) restClientService.getApi(ApiName.GETVIDSBYUIN, + pathsegments, "", "", VidsInfosDTO.class); + + if (vidsInfosDTO.getErrors() != null && !vidsInfosDTO.getErrors().isEmpty()) { + ServiceError error = vidsInfosDTO.getErrors().get(0); + throw new VidNotAvailableException(PlatformErrorMessages.RPR_PRT_VID_NOT_AVAILABLE_EXCEPTION.getCode(), + error.getMessage()); + + } else { + if(vidsInfosDTO.getResponse()!=null && !vidsInfosDTO.getResponse().isEmpty()) { + for (VidInfoDTO VidInfoDTO : vidsInfosDTO.getResponse()) { + if (VidType.PERPETUAL.name().equalsIgnoreCase(VidInfoDTO.getVidType())) { + vid = VidInfoDTO.getVid(); + break; + } + } + if (vid == null) { + throw new VidNotAvailableException( + PlatformErrorMessages.RPR_PRT_VID_NOT_AVAILABLE_EXCEPTION.getCode(), + PlatformErrorMessages.RPR_PRT_VID_NOT_AVAILABLE_EXCEPTION.getMessage()); + } + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString(), "", + "PrintServiceImpl::getVid():: get GETVIDSBYUIN service call ended successfully"); + + }else { + throw new VidNotAvailableException(PlatformErrorMessages.RPR_PRT_VID_NOT_AVAILABLE_EXCEPTION.getCode(), + PlatformErrorMessages.RPR_PRT_VID_NOT_AVAILABLE_EXCEPTION.getMessage()); + } + + } + + return vid; + } + + private void updateErrorFlags(InternalRegistrationStatusDto registrationStatusDto, MessageDTO object) { + object.setInternalError(true); + if (registrationStatusDto.getLatestTransactionStatusCode() + .equalsIgnoreCase(RegistrationTransactionStatusCode.REPROCESS.toString())) { + object.setIsValid(true); + } else { + object.setIsValid(false); + } + } + + @Scheduled(fixedDelayString = "${mosip.regproc.printstage.pingeneration.refresh.millisecs:1800000}", + initialDelayString = "${mosip.regproc.printstage.pingeneration.refresh.delay-on-startup.millisecs:5000}") + private void instantiate() { + regProcLogger.debug("Instantiating SecureRandom for credential pin generation............"); + try { + sr = SecureRandom.getInstance("SHA1PRNG"); + } catch (NoSuchAlgorithmException e) { + regProcLogger.error("Could not instantiate SecureRandom for credential pin generation", e); + } + } } \ No newline at end of file diff --git a/registration-processor/post-processor/registration-processor-printing-stage/src/main/java/io/mosip/registration/processor/print/stage/exception/VidNotAvailableException.java b/registration-processor/post-processor/registration-processor-credential-requestor-stage/src/main/java/io/mosip/registration/processor/credentialrequestor/stage/exception/VidNotAvailableException.java similarity index 85% rename from registration-processor/post-processor/registration-processor-printing-stage/src/main/java/io/mosip/registration/processor/print/stage/exception/VidNotAvailableException.java rename to registration-processor/post-processor/registration-processor-credential-requestor-stage/src/main/java/io/mosip/registration/processor/credentialrequestor/stage/exception/VidNotAvailableException.java index 394a0e79e46..334fcc34b86 100644 --- a/registration-processor/post-processor/registration-processor-printing-stage/src/main/java/io/mosip/registration/processor/print/stage/exception/VidNotAvailableException.java +++ b/registration-processor/post-processor/registration-processor-credential-requestor-stage/src/main/java/io/mosip/registration/processor/credentialrequestor/stage/exception/VidNotAvailableException.java @@ -1,27 +1,27 @@ -package io.mosip.registration.processor.print.stage.exception; - -import io.mosip.kernel.core.exception.BaseCheckedException; - -public class VidNotAvailableException extends BaseCheckedException { - - /** - * - */ - private static final long serialVersionUID = 1L; - - public VidNotAvailableException() { - super(); - } - - /** - * Instantiates a new reg proc checked exception. - * - * @param errorCode - * the error code - * @param errorMessage - * the error message - */ - public VidNotAvailableException(String errorCode, String errorMessage) { - super(errorCode, errorMessage); - } -} +package io.mosip.registration.processor.credentialrequestor.stage.exception; + +import io.mosip.kernel.core.exception.BaseCheckedException; + +public class VidNotAvailableException extends BaseCheckedException { + + /** + * + */ + private static final long serialVersionUID = 1L; + + public VidNotAvailableException() { + super(); + } + + /** + * Instantiates a new reg proc checked exception. + * + * @param errorCode + * the error code + * @param errorMessage + * the error message + */ + public VidNotAvailableException(String errorCode, String errorMessage) { + super(errorCode, errorMessage); + } +} diff --git a/registration-processor/post-processor/registration-processor-credential-requestor-stage/src/main/java/io/mosip/registration/processor/credentialrequestor/util/CredentialPartnerUtil.java b/registration-processor/post-processor/registration-processor-credential-requestor-stage/src/main/java/io/mosip/registration/processor/credentialrequestor/util/CredentialPartnerUtil.java new file mode 100644 index 00000000000..b357a6076e0 --- /dev/null +++ b/registration-processor/post-processor/registration-processor-credential-requestor-stage/src/main/java/io/mosip/registration/processor/credentialrequestor/util/CredentialPartnerUtil.java @@ -0,0 +1,225 @@ +package io.mosip.registration.processor.credentialrequestor.util; + +import com.fasterxml.jackson.databind.ObjectMapper; +import io.mosip.kernel.core.exception.BaseCheckedException; +import io.mosip.kernel.core.exception.ExceptionUtils; +import io.mosip.kernel.core.logger.spi.Logger; +import io.mosip.kernel.core.util.exception.JsonProcessingException; +import io.mosip.registration.processor.core.constant.JsonConstant; +import io.mosip.registration.processor.core.constant.LoggerFileConstant; +import io.mosip.registration.processor.core.constant.MappingJsonConstants; +import io.mosip.registration.processor.core.constant.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.logger.RegProcessorLogger; +import io.mosip.registration.processor.core.packet.dto.FieldValue; +import io.mosip.registration.processor.core.util.JsonUtil; +import io.mosip.registration.processor.credentialrequestor.dto.CredentialPartner; +import io.mosip.registration.processor.credentialrequestor.dto.CredentialPartnersList; +import io.mosip.registration.processor.packet.storage.exception.ParsingException; +import io.mosip.registration.processor.packet.storage.utils.IdSchemaUtil; +import io.mosip.registration.processor.packet.storage.utils.Utilities; +import org.apache.commons.collections.MapUtils; +import org.assertj.core.util.Lists; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.simple.JSONObject; +import org.mvel2.MVEL; +import org.mvel2.ParserContext; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Component; +import org.springframework.util.StringUtils; + +import javax.annotation.PostConstruct; +import java.io.IOException; +import java.util.*; +import java.util.stream.Collectors; + +@Component +public class CredentialPartnerUtil { + + private static final Logger regProcLogger = RegProcessorLogger.getLogger(CredentialPartnerUtil.class); + private static final String VALUE_LABEL = "value"; + private static final String LANGUAGE = "language"; + + private CredentialPartnersList credentialPartners; + + @Autowired + private ObjectMapper objectMapper; + + @Autowired + private Environment env; + + @Autowired + private Utilities utilities; + + @Autowired + IdSchemaUtil idSchemaUtil; + + @Value("${mosip.registration.processor.credential.partner-profiles}") + private String partnerProfileFileName; + + @Value("#{T(java.util.Arrays).asList('${mosip.mandatory-languages:}')}") + private List mandatoryLanguages; + + @Value("${mosip.registration.processor.credential.conditional.no-match-partner-ids}") + private String noMatchIssuer; + + @Value("#{${mosip.registration.processor.credential.conditional.partner-id-map:{}}}") + private Map credentialPartnerExpression; + + @Value("${config.server.file.storage.uri}") + private String configServerFileStorageURL; + + /** + * This map will hold the actual field names after resolving, using mapping JSON as keys and + * configured field names as values + */ + private Map requiredIDObjectFieldNamesMap; + /** + * Configured Id object fields + */ + private List requiredIdObjectFieldNames; + + @PostConstruct + private void getIdObjectFieldNames() throws BaseCheckedException { + regProcLogger.info( "CredentialPartnerUtil::getIdObjectFieldNames()::PostConstruct"); + try { + org.json.simple.JSONObject identityMappingJson = + utilities.getRegistrationProcessorMappingJson(MappingJsonConstants.IDENTITY); + requiredIDObjectFieldNamesMap = new HashMap<>(); + for(Map.Entry expressionEntry : credentialPartnerExpression.entrySet()) { + ParserContext parserContext = ParserContext.create(); + MVEL.analysisCompile(expressionEntry.getValue(), parserContext); + Map expressionVariablesMap = parserContext.getInputs(); + for(Map.Entry variableEntry: expressionVariablesMap.entrySet()) { + String actualFieldName = JsonUtil.getJSONValue( + JsonUtil.getJSONObject(identityMappingJson, variableEntry.getKey()), + VALUE_LABEL); + if(actualFieldName == null) + throw new BaseCheckedException( + PlatformErrorMessages.RPR_PCM_FIELD_NAME_NOT_AVAILABLE_IN_MAPPING_JSON.getCode(), + PlatformErrorMessages.RPR_PCM_FIELD_NAME_NOT_AVAILABLE_IN_MAPPING_JSON.getMessage()); + requiredIDObjectFieldNamesMap.put(actualFieldName, variableEntry.getKey()); + } + } + requiredIdObjectFieldNames = requiredIDObjectFieldNamesMap.keySet().stream().collect(Collectors.toList()); + } catch (IOException e) { + throw new BaseCheckedException( + PlatformErrorMessages.RPR_PCM_ACCESSING_IDOBJECT_MAPPING_FILE_FAILED.getCode(), + PlatformErrorMessages.RPR_PCM_ACCESSING_IDOBJECT_MAPPING_FILE_FAILED.getMessage(), e); + } + } + + public List getCredentialPartners(String regId, String registrationType, JSONObject identity) throws PacketManagerException, JSONException, ApisResourceAccessException, IOException, JsonProcessingException { + + regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + regId, "CredentialPartnerUtil::getCredentialPartners()::entry"); + + List filteredPartners = new ArrayList<>(); + if (credentialPartnerExpression == null || credentialPartnerExpression.isEmpty()) { + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString(), regId, + PlatformErrorMessages.RPR_PRT_ISSUER_NOT_FOUND_IN_PROPERTY.name()); + return Lists.emptyList(); + } + + Map identityFieldValueMap = utilities.getPacketManagerService().getFields(regId, + requiredIdObjectFieldNames, registrationType, ProviderStageName.CREDENTIAL_REQUESTOR); + + Map context = new HashMap<>(); + for (Map.Entry identityAttribute: identityFieldValueMap.entrySet()) { + JSONObject attributeObject = new JSONObject(identityFieldValueMap); + try { + if (identityAttribute.getKey() != null && identityAttribute.getValue() != null) { + Object obj = attributeObject.get(identityAttribute.getKey()); + if (obj instanceof org.json.simple.JSONArray) { + org.json.simple.JSONArray attributeArray = (org.json.simple.JSONArray) obj; + for (int i = 0; i < attributeArray.size(); i++) { + JSONObject jsonObject = (JSONObject) attributeArray.get(i); + if (mandatoryLanguages.get(0).equalsIgnoreCase((String) jsonObject.get(LANGUAGE))) { + context.put(identityAttribute.getKey(), jsonObject.get(VALUE_LABEL)); + } + } + } else { + if (obj != null) { + context.put(identityAttribute.getKey(), obj.toString()); + } + } + } else + context.put(identityAttribute.getKey(), identityAttribute.getValue()); + } catch (Exception e) { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), "", + ExceptionUtils.getStackTrace(e)); + throw new ParsingException(PlatformErrorMessages.RPR_PRT_DATA_VALIDATION_FAILED.getCode(), e); + } + } + + // adding additional metadata so that it can be used for MVEL expression + Map metaInfo = utilities.getPacketManagerService().getMetaInfo(regId, registrationType, ProviderStageName.CREDENTIAL_REQUESTOR); + if (MapUtils.isNotEmpty(metaInfo)) { + String metadata = metaInfo.get(JsonConstant.METADATA); + if (!StringUtils.isEmpty(metadata)) { + JSONArray jsonArray = new JSONArray(metadata); + addToMap(jsonArray, context); + } + } + + regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + regId, "CredentialPartnerUtil::CredentialPartnerExpression::" + credentialPartnerExpression.toString()); + + for(Map.Entry entry : credentialPartnerExpression.entrySet()) { + Boolean result = (Boolean) MVEL.eval(entry.getValue(), context); + if (result) { + filteredPartners.add(entry.getKey()); + } + } + if (StringUtils.hasText(noMatchIssuer) && filteredPartners.isEmpty()) { + filteredPartners.add(noMatchIssuer); + } + regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + regId, "CredentialPartnerUtil::FilteredPartners::" + filteredPartners.toString()); + + List finalList = new ArrayList<>(); + if (!filteredPartners.isEmpty()) { + filteredPartners.forEach( + p -> { + Optional partner = credentialPartners.getPartners() + .stream().filter(pr -> pr.getId().equalsIgnoreCase(p)).findAny(); + if (partner.isPresent()) + finalList.add(partner.get()); + }); + } + return finalList; + } + + private void addToMap(JSONArray jsonArray, Map allMap) throws JSONException, IOException { + for (int i =0; i < jsonArray.length(); i++) { + org.json.JSONObject jsonObject = (org.json.JSONObject) jsonArray.get(i); + FieldValue fieldValue = objectMapper.readValue(jsonObject.toString(), FieldValue.class); + allMap.put(fieldValue.getLabel(), fieldValue.getValue()); + } + } + + @PostConstruct + public void loadPartnerDetails() throws RegistrationProcessorCheckedException { + try { + String partners = Utilities.getJson(configServerFileStorageURL, partnerProfileFileName); + credentialPartners = JsonUtil.readValueWithUnknownProperties(partners, CredentialPartnersList.class); + } catch (Exception e) { + regProcLogger.error("Error loading credential Partners", e); + throw new RegistrationProcessorCheckedException(PlatformErrorMessages.RPR_SYS_IO_EXCEPTION.getCode(), + PlatformErrorMessages.RPR_SYS_IO_EXCEPTION.getMessage(), e); + } + } + + public CredentialPartnersList getAllCredentialPartners() throws RegistrationProcessorCheckedException { + if (credentialPartners == null) + loadPartnerDetails(); + return credentialPartners; + } +} diff --git a/registration-processor/post-processor/registration-processor-printing-stage/src/main/resources/bootstrap.properties b/registration-processor/post-processor/registration-processor-credential-requestor-stage/src/main/resources/bootstrap.properties similarity index 50% rename from registration-processor/post-processor/registration-processor-printing-stage/src/main/resources/bootstrap.properties rename to registration-processor/post-processor/registration-processor-credential-requestor-stage/src/main/resources/bootstrap.properties index 64b25477db4..e812af75ff3 100644 --- a/registration-processor/post-processor/registration-processor-printing-stage/src/main/resources/bootstrap.properties +++ b/registration-processor/post-processor/registration-processor-credential-requestor-stage/src/main/resources/bootstrap.properties @@ -1,25 +1,33 @@ -spring.cloud.config.uri=localhost -spring.cloud.config.label=master -spring.application.name=application,registration-processor -spring.profiles.active=dev -spring.cloud.config.name=application,registration-processor -registration.processor.identityjson=RegistrationProcessorIdentity.json -registration.processor.demographic.identity=identity -packet.info.storage.service=registration-processor-packet-info-storage-service -config.server.file.storage.uri=${spring.cloud.config.uri}/${packet.info.storage.service}/${spring.profiles.active}/${spring.cloud.config.label}/ -management.endpoints.web.exposure.include=refresh -registration.processor.zone=secure -vertx.cluster.configuration=${spring.cloud.config.uri}/*/${spring.profiles.active}/${spring.cloud.config.label}/hazelcast_${registration.processor.zone}.xml -#management.security.enabled=false -server.port=8099 -server.servlet.path=/registrationprocessor/v1/print-stage - -#disabling health check so that client doesnt try to load properties from sprint config server every -# 5 minutes (should not be done in production) -health.config.enabled=false -eventbus.port=5722 -#Kafka event bus configruations -mosip.regproc.eventbus.kafka.commit.type=${mosip.regproc.printing.eventbus.kafka.commit.type} -mosip.regproc.eventbus.kafka.max.poll.records=${mosip.regproc.printing.eventbus.kafka.max.poll.records} -mosip.regproc.eventbus.kafka.poll.frequency=${mosip.regproc.printing.eventbus.kafka.poll.frequency} -mosip.regproc.eventbus.kafka.group.id=${mosip.regproc.printing.eventbus.kafka.group.id} \ No newline at end of file +spring.cloud.config.uri=localhost +spring.cloud.config.label=master +spring.application.name=application,registration-processor +spring.profiles.active=dev +spring.cloud.config.name=application,registration-processor +registration.processor.identityjson=RegistrationProcessorIdentity.json +registration.processor.demographic.identity=identity +packet.info.storage.service=registration-processor-packet-info-storage-service +config.server.file.storage.uri=${spring.cloud.config.uri}/${packet.info.storage.service}/${spring.profiles.active}/${spring.cloud.config.label}/ +management.endpoints.web.exposure.include=refresh +registration.processor.zone=secure +vertx.cluster.configuration=${spring.cloud.config.uri}/*/${spring.profiles.active}/${spring.cloud.config.label}/hazelcast_${registration.processor.zone}.xml +#management.security.enabled=false +server.port=8099 +server.servlet.path=/registrationprocessor/v1/credential-requestor + +#disabling health check so that client doesnt try to load properties from sprint config server every +# 5 minutes (should not be done in production) +health.config.enabled=false +eventbus.port=5722 +#Kafka event bus configruations +mosip.regproc.eventbus.kafka.commit.type=${mosip.regproc.credentialrequestor.eventbus.kafka.commit.type} +mosip.regproc.eventbus.kafka.max.poll.records=${mosip.regproc.credentialrequestor.eventbus.kafka.max.poll.records} +mosip.regproc.eventbus.kafka.poll.frequency=${mosip.regproc.credentialrequestor.eventbus.kafka.poll.frequency} +mosip.regproc.eventbus.kafka.group.id=${mosip.regproc.credentialrequestor.eventbus.kafka.group.id} +mosip.registration.processor.digitalcard.credentialtype=PDFCard +mosip.registration.processor.print.credentialtype=euin +mosip.registration.processor.digitalcard.template=RPR_UIN_CARD_TEMPLATE +mosip.registration.processor.print.template=RPR_UIN_CARD_TEMPLATE +# this property is used to define issuers eg partnerid:credentialType:templateTypeCode +mosip.registration.processor.default.internal.issuers=mpartner-default-digitalcard#PDFCard#RPR_UIN_CARD_TEMPLATE + +mosip.registration.processor.default.issuers=mpartner-default-print#euin#RPR_UIN_CARD_TEMPLATE \ No newline at end of file diff --git a/registration-processor/post-processor/registration-processor-printing-stage/src/main/resources/logback.xml b/registration-processor/post-processor/registration-processor-credential-requestor-stage/src/main/resources/logback.xml similarity index 100% rename from registration-processor/post-processor/registration-processor-printing-stage/src/main/resources/logback.xml rename to registration-processor/post-processor/registration-processor-credential-requestor-stage/src/main/resources/logback.xml diff --git a/registration-processor/post-processor/registration-processor-printing-stage/src/test/java/io/mosip/registrationprocessor/print/stage/test/PrintingStageTest.java b/registration-processor/post-processor/registration-processor-credential-requestor-stage/src/test/java/io/mosip/registrationprocessor/credentialrequestor/test/CredentialRequestorStageTest.java similarity index 87% rename from registration-processor/post-processor/registration-processor-printing-stage/src/test/java/io/mosip/registrationprocessor/print/stage/test/PrintingStageTest.java rename to registration-processor/post-processor/registration-processor-credential-requestor-stage/src/test/java/io/mosip/registrationprocessor/credentialrequestor/test/CredentialRequestorStageTest.java index dc4c470177a..1177e4e19c7 100644 --- a/registration-processor/post-processor/registration-processor-printing-stage/src/test/java/io/mosip/registrationprocessor/print/stage/test/PrintingStageTest.java +++ b/registration-processor/post-processor/registration-processor-credential-requestor-stage/src/test/java/io/mosip/registrationprocessor/credentialrequestor/test/CredentialRequestorStageTest.java @@ -1,442 +1,471 @@ -package io.mosip.registrationprocessor.print.stage.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.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.print.stage.PrintingStage; -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 PrintingStageTest { - - @Mock - private AuditLogRequestBuilder auditLogRequestBuilder; - - @Mock - MosipRouter router; - - @Mock - protected PropertiesUtil propertiesUtil; - - @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 PrintingStage stage = new PrintingStage() { - @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.printing.server.port")).thenReturn("8099"); - - ReflectionTestUtils.setField(stage, "workerPoolSize", 10); - ReflectionTestUtils.setField(stage, "messageExpiryTimeLimit", Long.valueOf(0)); - ReflectionTestUtils.setField(stage, "clusterManagerUrl", "/dummyPath"); - ReflectionTestUtils.setField(stage, "busOutHaltAddresses", Arrays.asList()); - System.setProperty("server.port", "8099"); - - //ReflectionTestUtils.setField(stage, "port", "8080"); - ReflectionTestUtils.setField(stage, "encrypt", false); - 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.retrieveUIN(any())).thenReturn(jsonObject); - - - - } - - @Test - public void testAll() throws Exception { - testDeployVerticle(); - testStart(); - testPrintStageSuccess(); - testPrintStageFailure(); - } - - 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); - - 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(), any(), any(), any(), any(), any(MediaType.class))) - .thenReturn(responseWrapper); - - MessageDTO result = stage.process(dto); - assertFalse(result.getIsValid()); - assertFalse(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.retrieveUIN(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 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.retrieveUIN(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.retrieveUIN(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/registration-processor-core/src/main/java/io/mosip/registration/processor/core/code/ApiName.java b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/code/ApiName.java index 2408b0c1a67..4a85dc07a65 100644 --- a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/code/ApiName.java +++ b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/code/ApiName.java @@ -196,7 +196,8 @@ public enum ApiName { IDREPOCREATEDRAFT, IDREPOUPDATEDRAFT, IDREPOPUBLISHDRAFT, - IDREPOEXTRACTBIOMETRICS; + IDREPOEXTRACTBIOMETRICS, + CREDENTIALREQUESTV2; } diff --git a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/constant/ProviderStageName.java b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/constant/ProviderStageName.java index c8ea5efdfed..9a9e0bea9a5 100644 --- a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/constant/ProviderStageName.java +++ b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/constant/ProviderStageName.java @@ -19,7 +19,8 @@ public enum ProviderStageName { VERIFICATION("verification"), UIN_GENERATOR("uingenerator"), WORKFLOW_MANAGER("workflowmanager"), - MESSAGE_SENDER("messagesender"); + MESSAGE_SENDER("messagesender"), + CREDENTIAL_REQUESTOR("credentialrequestor"); private String value; 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 fa6aa67cdc2..92ef5f6ebac 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 @@ -1135,6 +1135,11 @@ public enum PlatformErrorMessages { 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 "), diff --git a/registration-processor/stage-groups/registration-processor-stage-group-7/pom.xml b/registration-processor/stage-groups/registration-processor-stage-group-7/pom.xml index c1a8220c7a6..8d85e80b286 100644 --- a/registration-processor/stage-groups/registration-processor-stage-group-7/pom.xml +++ b/registration-processor/stage-groups/registration-processor-stage-group-7/pom.xml @@ -1,74 +1,74 @@ - - - 4.0.0 - - io.mosip.registrationprocessor - stage-groups - 1.2.0.1-B3 - - - registration-processor-stage-group-7 - 1.2.0.1-B3 - - - UTF-8 - - - - - - - io.mosip.registrationprocessor - mosip-stage-executor - 1.2.0.1-B3 - - - - - io.mosip.registrationprocessor - registration-processor-uin-generator-stage - 1.2.0.1-B3 - - - io.mosip.registrationprocessor - registration-processor-biometric-extraction-stage - 1.2.0.1-B3 - - - io.mosip.registrationprocessor - registration-processor-finalization-stage - 1.2.0.1-B3 - - - io.mosip.registrationprocessor - registration-processor-printing-stage - 1.2.0.1-B3 - - - - - - - - - org.springframework.boot - spring-boot-maven-plugin - ${spring.boot.version} - - true - io.mosip.registration.processor.stages.executor.MosipStageExecutorApplication - ZIP - - - - - build-info - repackage - - - - - - + + + 4.0.0 + + io.mosip.registrationprocessor + stage-groups + 1.2.0.1-B3 + + + registration-processor-stage-group-7 + 1.2.0.1-B3 + + + UTF-8 + + + + + + + io.mosip.registrationprocessor + mosip-stage-executor + 1.2.0.1-B3 + + + + + io.mosip.registrationprocessor + registration-processor-uin-generator-stage + 1.2.0.1-B3 + + + io.mosip.registrationprocessor + registration-processor-biometric-extraction-stage + 1.2.0.1-B3 + + + io.mosip.registrationprocessor + registration-processor-finalization-stage + 1.2.0.1-B3 + + + io.mosip.registrationprocessor + registration-processor-credential-requestor-stage + 1.2.0.1-B3 + + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + ${spring.boot.version} + + true + io.mosip.registration.processor.stages.executor.MosipStageExecutorApplication + ZIP + + + + + build-info + repackage + + + + + + \ No newline at end of file From 565d9ab65209bcc30fd5222117e0365be36e6721 Mon Sep 17 00:00:00 2001 From: Vishwa Date: Wed, 3 Jan 2024 19:50:05 +0530 Subject: [PATCH 107/133] Merge pull request #1818 from MonobikashDas/develop MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit MOSIP-28121 : calling idrepo instead of packetmanager in credential r… Signed-off-by: Monobikash Das --- .../stage/CredentialRequestorStage.java | 3 +-- .../util/CredentialPartnerUtil.java | 11 ++++------- .../test/CredentialRequestorStageTest.java | 4 ++-- .../processor/packet/storage/utils/Utilities.java | 2 +- .../service/impl/MessageNotificationServiceImpl.java | 2 +- .../service/MessageNotificationServiceImplTest.java | 2 +- 6 files changed, 10 insertions(+), 14 deletions(-) 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 39ee23c62ca..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 @@ -196,7 +196,7 @@ public MessageDTO process(MessageDTO object) { registrationStatusDto .setLatestTransactionTypeCode(RegistrationTransactionTypeCode.PRINT_SERVICE.toString()); registrationStatusDto.setRegistrationStageName(getStageName()); - JSONObject jsonObject = utilities.retrieveUIN(regId); + JSONObject jsonObject = utilities.idrepoRetrieveIdentityByRid(regId); uin = JsonUtil.getJSONValue(jsonObject, IdType.UIN.toString()); if (uin == null) { regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), @@ -343,7 +343,6 @@ public MessageDTO process(MessageDTO object) { moduleId, moduleName, regId); } - return object; } diff --git a/registration-processor/post-processor/registration-processor-credential-requestor-stage/src/main/java/io/mosip/registration/processor/credentialrequestor/util/CredentialPartnerUtil.java b/registration-processor/post-processor/registration-processor-credential-requestor-stage/src/main/java/io/mosip/registration/processor/credentialrequestor/util/CredentialPartnerUtil.java index b357a6076e0..4495ae6e7ed 100644 --- a/registration-processor/post-processor/registration-processor-credential-requestor-stage/src/main/java/io/mosip/registration/processor/credentialrequestor/util/CredentialPartnerUtil.java +++ b/registration-processor/post-processor/registration-processor-credential-requestor-stage/src/main/java/io/mosip/registration/processor/credentialrequestor/util/CredentialPartnerUtil.java @@ -5,10 +5,7 @@ import io.mosip.kernel.core.exception.ExceptionUtils; import io.mosip.kernel.core.logger.spi.Logger; import io.mosip.kernel.core.util.exception.JsonProcessingException; -import io.mosip.registration.processor.core.constant.JsonConstant; -import io.mosip.registration.processor.core.constant.LoggerFileConstant; -import io.mosip.registration.processor.core.constant.MappingJsonConstants; -import io.mosip.registration.processor.core.constant.ProviderStageName; +import io.mosip.registration.processor.core.constant.*; import io.mosip.registration.processor.core.exception.ApisResourceAccessException; import io.mosip.registration.processor.core.exception.PacketManagerException; import io.mosip.registration.processor.core.exception.RegistrationProcessorCheckedException; @@ -128,11 +125,11 @@ public List getCredentialPartners(String regId, String regist return Lists.emptyList(); } - Map identityFieldValueMap = utilities.getPacketManagerService().getFields(regId, - requiredIdObjectFieldNames, registrationType, ProviderStageName.CREDENTIAL_REQUESTOR); + Map identityFieldValueMap = new HashMap<>(); + requiredIdObjectFieldNames.forEach(field -> identityFieldValueMap.put(field, JsonUtil.getJSONValue(identity, field))); Map context = new HashMap<>(); - for (Map.Entry identityAttribute: identityFieldValueMap.entrySet()) { + for (Map.Entry identityAttribute: identityFieldValueMap.entrySet()) { JSONObject attributeObject = new JSONObject(identityFieldValueMap); try { if (identityAttribute.getKey() != null && identityAttribute.getValue() != null) { 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 1177e4e19c7..b635ab725a1 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 @@ -245,7 +245,7 @@ public void setup() throws Exception { Map map1 = new HashMap<>(); map1.put("UIN", "4238135072"); JSONObject jsonObject = new JSONObject(map1); - Mockito.when(utitilites.retrieveUIN(any())).thenReturn(jsonObject); + Mockito.when(utitilites.idrepoRetrieveIdentityByRid(any())).thenReturn(jsonObject); CredentialPartner partner1 = new CredentialPartner(); partner1.setId("digitalcardPartner"); @@ -394,7 +394,7 @@ public void testUINNotavailable() Map map1 = new HashMap<>(); JSONObject jsonObject = new JSONObject(map1); - Mockito.when(utitilites.retrieveUIN(any())).thenReturn(jsonObject); + Mockito.when(utitilites.idrepoRetrieveIdentityByRid(any())).thenReturn(jsonObject); MessageDTO result = stage.process(dto); assertFalse(result.getIsValid()); 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 99b7abac080..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 @@ -662,7 +662,7 @@ public String getLatestTransactionId(String registrationId, String process, int * @throws IOException Signals that an I/O exception has * occurred. */ - public JSONObject retrieveUIN(String regId) throws ApisResourceAccessException, IdRepoAppException, IOException { + public JSONObject idrepoRetrieveIdentityByRid(String regId) throws ApisResourceAccessException, IdRepoAppException, IOException { regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), regId, "Utilities::retrieveUIN()::entry"); 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 cd551b37bd3..36413df5774 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 @@ -449,7 +449,7 @@ private Map setAttributes(String id, String process, String lang String uin = ""; if (idType.toString().equalsIgnoreCase(UIN)) { - JSONObject jsonObject = utility.retrieveUIN(id); + JSONObject jsonObject = utility.idrepoRetrieveIdentityByRid(id); uin = JsonUtil.getJSONValue(jsonObject, UIN); attributes.put("RID", id); attributes.put("UIN", uin); diff --git a/registration-processor/registration-processor-message-sender-impl/src/test/java/io/mosip/registration/processor/message/sender/test/service/MessageNotificationServiceImplTest.java b/registration-processor/registration-processor-message-sender-impl/src/test/java/io/mosip/registration/processor/message/sender/test/service/MessageNotificationServiceImplTest.java index 4f242aa7e98..ea6d1b11d1e 100644 --- a/registration-processor/registration-processor-message-sender-impl/src/test/java/io/mosip/registration/processor/message/sender/test/service/MessageNotificationServiceImplTest.java +++ b/registration-processor/registration-processor-message-sender-impl/src/test/java/io/mosip/registration/processor/message/sender/test/service/MessageNotificationServiceImplTest.java @@ -202,7 +202,7 @@ public void setup() throws Exception { map1.put("UIN", "423072"); JSONObject jsonObject1 = new JSONObject(map1); - Mockito.when(utility.retrieveUIN(any())).thenReturn(jsonObject1); + Mockito.when(utility.idrepoRetrieveIdentityByRid(any())).thenReturn(jsonObject1); Mockito.when(utility.getGetRegProcessorDemographicIdentity()).thenReturn("identity"); InputStream in = IOUtils.toInputStream("Hi Alok, Your UIN is generated", "UTF-8"); From 3892c5a0c7aa27b2b8a938cc14b75857080e4e83 Mon Sep 17 00:00:00 2001 From: Sowmya Ujjappa Banakar Date: Thu, 4 Jan 2024 17:33:22 +0530 Subject: [PATCH 108/133] updated versions to snapshot Signed-off-by: Sowmya Ujjappa Banakar --- pom.xml | 324 +++++++++--------- registration-processor/core-processor/pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../registration-processor-abis/pom.xml | 228 ++++++------ .../pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- registration-processor/init/pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../mosip-stage-executor/pom.xml | 4 +- registration-processor/pom.xml | 50 +-- registration-processor/post-processor/pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- registration-processor/pre-processor/pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../qc-users-manger/pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 6 +- .../registration-processor-core/pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 6 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- registration-processor/stage-groups/pom.xml | 4 +- .../pom.xml | 8 +- .../pom.xml | 12 +- .../pom.xml | 14 +- .../pom.xml | 10 +- .../pom.xml | 16 +- .../pom.xml | 12 +- .../pom.xml | 14 +- .../workflow-engine/pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- 54 files changed, 434 insertions(+), 434 deletions(-) diff --git a/pom.xml b/pom.xml index 74d8bfe6922..6b44f7c6668 100644 --- a/pom.xml +++ b/pom.xml @@ -1,162 +1,162 @@ - - - - 4.0.0 - io.mosip - registration - 1.2.0.1-B3 - pom - - MOSIP Registration Parent POM - Mosip Registration Project - https://github.com/mosip/registration - - - MPL 2.0 - https://www.mozilla.org/en-US/MPL/2.0/ - - - - scm:git:git://github.com/mosip/registration.git - scm:git:ssh://github.com:mosip/registration.git - https://github.com/mosip/registration - HEAD - - - - Mosip - mosip.emailnotifier@gmail.com - io.mosip - https://github.com/mosip/registration - - - - - - ossrh - Central Repository - https://oss.sonatype.org/content/repositories/snapshots - default - - true - - - - central - Maven Central - 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/ - - - - - - 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 - - - - - org.apache.maven.plugins - maven-gpg-plugin - 1.5 - - - sign-artifacts - verify - - sign - - - - --pinentry-mode - loopback - - - - - - - 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 - - - - - - - - - registration-processor - - + + + + 4.0.0 + io.mosip + registration + 1.2.0.1-SNAPSHOT + pom + + MOSIP Registration Parent POM + Mosip Registration Project + https://github.com/mosip/registration + + + MPL 2.0 + https://www.mozilla.org/en-US/MPL/2.0/ + + + + scm:git:git://github.com/mosip/registration.git + scm:git:ssh://github.com:mosip/registration.git + https://github.com/mosip/registration + HEAD + + + + Mosip + mosip.emailnotifier@gmail.com + io.mosip + https://github.com/mosip/registration + + + + + + ossrh + Central Repository + https://oss.sonatype.org/content/repositories/snapshots + default + + true + + + + central + Maven Central + 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/ + + + + + + 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 + + + + + org.apache.maven.plugins + maven-gpg-plugin + 1.5 + + + sign-artifacts + verify + + sign + + + + --pinentry-mode + loopback + + + + + + + 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 + + + + + + + + + registration-processor + + diff --git a/registration-processor/core-processor/pom.xml b/registration-processor/core-processor/pom.xml index bf9c23de124..1e70249927a 100644 --- a/registration-processor/core-processor/pom.xml +++ b/registration-processor/core-processor/pom.xml @@ -5,9 +5,9 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT core-processor core-processor diff --git a/registration-processor/core-processor/registration-processor-abis-handler-stage/pom.xml b/registration-processor/core-processor/registration-processor-abis-handler-stage/pom.xml index 85a81893eae..b993ca03858 100644 --- a/registration-processor/core-processor/registration-processor-abis-handler-stage/pom.xml +++ b/registration-processor/core-processor/registration-processor-abis-handler-stage/pom.xml @@ -5,11 +5,11 @@ io.mosip.registrationprocessor core-processor - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT registration-processor-abis-handler-stage - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT jar UTF-8 diff --git a/registration-processor/core-processor/registration-processor-abis-middleware-stage/pom.xml b/registration-processor/core-processor/registration-processor-abis-middleware-stage/pom.xml index fe6903760b9..e50a32b7d0d 100644 --- a/registration-processor/core-processor/registration-processor-abis-middleware-stage/pom.xml +++ b/registration-processor/core-processor/registration-processor-abis-middleware-stage/pom.xml @@ -5,10 +5,10 @@ io.mosip.registrationprocessor core-processor - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT registration-processor-abis-middleware-stage - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT jar UTF-8 diff --git a/registration-processor/core-processor/registration-processor-abis/pom.xml b/registration-processor/core-processor/registration-processor-abis/pom.xml index 44478edfd46..f74c9c31884 100644 --- a/registration-processor/core-processor/registration-processor-abis/pom.xml +++ b/registration-processor/core-processor/registration-processor-abis/pom.xml @@ -1,114 +1,114 @@ - - - 4.0.0 - jar - - - io.mosip.registrationprocessor - core-processor - 1.2.0.1-B3 - - registration-processor-abis - 1.2.0.1-B3 - registration-processor-abis - - UTF-8 - - - - - org.springframework.cloud - spring-cloud-starter-config - ${spring-cloud-config.version} - - - org.mockito - mockito-core - ${mockito.version} - test - - - com.h2database - h2 - ${h2.version} - - - - - - junit - junit - test - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-test - - - io.springfox - springfox-swagger-ui - ${swagger.version} - - - io.springfox - springfox-swagger2 - ${swagger.version} - - - io.mosip.registrationprocessor - registration-processor-rest-client - ${registration.processor.rest.client.version} - - - io.mosip.registrationprocessor - registration-processor-info-storage-service - ${packet.info.storage.service.version} - - - org.powermock - powermock-module-junit4 - ${powermock.module.junit4.version} - test - - - org.powermock - powermock-api-mockito2 - ${powermock.api.mockito.version} - test - - - com.h2database - h2 - - - org.postgresql - postgresql - - - - - - org.springframework.boot - spring-boot-maven-plugin - ${spring.boot.version} - - true - - - - - build-info - repackage - - - - - - - + + + 4.0.0 + jar + + + io.mosip.registrationprocessor + core-processor + 1.2.0.1-SNAPSHOT + + registration-processor-abis + 1.2.0.1-SNAPSHOT + registration-processor-abis + + UTF-8 + + + + + org.springframework.cloud + spring-cloud-starter-config + ${spring-cloud-config.version} + + + org.mockito + mockito-core + ${mockito.version} + test + + + com.h2database + h2 + ${h2.version} + + + + + + junit + junit + test + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-test + + + io.springfox + springfox-swagger-ui + ${swagger.version} + + + io.springfox + springfox-swagger2 + ${swagger.version} + + + io.mosip.registrationprocessor + registration-processor-rest-client + ${registration.processor.rest.client.version} + + + io.mosip.registrationprocessor + registration-processor-info-storage-service + ${packet.info.storage.service.version} + + + org.powermock + powermock-module-junit4 + ${powermock.module.junit4.version} + test + + + org.powermock + powermock-api-mockito2 + ${powermock.api.mockito.version} + test + + + com.h2database + h2 + + + org.postgresql + postgresql + + + + + + org.springframework.boot + spring-boot-maven-plugin + ${spring.boot.version} + + true + + + + + build-info + repackage + + + + + + + diff --git a/registration-processor/core-processor/registration-processor-bio-dedupe-stage/pom.xml b/registration-processor/core-processor/registration-processor-bio-dedupe-stage/pom.xml index 6c7f16156f5..51b750768e9 100644 --- a/registration-processor/core-processor/registration-processor-bio-dedupe-stage/pom.xml +++ b/registration-processor/core-processor/registration-processor-bio-dedupe-stage/pom.xml @@ -5,11 +5,11 @@ io.mosip.registrationprocessor core-processor - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT registration-processor-bio-dedupe-stage - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT jar UTF-8 diff --git a/registration-processor/core-processor/registration-processor-biometric-authentication-stage/pom.xml b/registration-processor/core-processor/registration-processor-biometric-authentication-stage/pom.xml index fcfdda19409..754cbb84860 100644 --- a/registration-processor/core-processor/registration-processor-biometric-authentication-stage/pom.xml +++ b/registration-processor/core-processor/registration-processor-biometric-authentication-stage/pom.xml @@ -5,10 +5,10 @@ io.mosip.registrationprocessor core-processor - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT registration-processor-biometric-authentication-stage - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT jar UTF-8 diff --git a/registration-processor/core-processor/registration-processor-biometric-extraction-stage/pom.xml b/registration-processor/core-processor/registration-processor-biometric-extraction-stage/pom.xml index 44498c08008..c22795794a5 100644 --- a/registration-processor/core-processor/registration-processor-biometric-extraction-stage/pom.xml +++ b/registration-processor/core-processor/registration-processor-biometric-extraction-stage/pom.xml @@ -5,10 +5,10 @@ io.mosip.registrationprocessor core-processor - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT registration-processor-biometric-extraction-stage - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT jar UTF-8 diff --git a/registration-processor/core-processor/registration-processor-demo-dedupe-stage/pom.xml b/registration-processor/core-processor/registration-processor-demo-dedupe-stage/pom.xml index 50a6e2e0bbe..80e30419cfa 100644 --- a/registration-processor/core-processor/registration-processor-demo-dedupe-stage/pom.xml +++ b/registration-processor/core-processor/registration-processor-demo-dedupe-stage/pom.xml @@ -5,10 +5,10 @@ io.mosip.registrationprocessor core-processor - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT registration-processor-demo-dedupe-stage - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT jar UTF-8 diff --git a/registration-processor/core-processor/registration-processor-finalization-stage/pom.xml b/registration-processor/core-processor/registration-processor-finalization-stage/pom.xml index a28f5d90d57..fe52552ff90 100644 --- a/registration-processor/core-processor/registration-processor-finalization-stage/pom.xml +++ b/registration-processor/core-processor/registration-processor-finalization-stage/pom.xml @@ -5,11 +5,11 @@ io.mosip.registrationprocessor core-processor - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT registration-processor-finalization-stage registration-processor-finalization-stage - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT jar UTF-8 diff --git a/registration-processor/core-processor/registration-processor-manual-adjudication-stage/pom.xml b/registration-processor/core-processor/registration-processor-manual-adjudication-stage/pom.xml index fce39b78f54..796d3317026 100644 --- a/registration-processor/core-processor/registration-processor-manual-adjudication-stage/pom.xml +++ b/registration-processor/core-processor/registration-processor-manual-adjudication-stage/pom.xml @@ -8,11 +8,11 @@ io.mosip.registrationprocessor core-processor - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT registration-processor-manual-adjudication-stage - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT UTF-8 diff --git a/registration-processor/core-processor/registration-processor-uin-generator-stage/pom.xml b/registration-processor/core-processor/registration-processor-uin-generator-stage/pom.xml index 4718decb596..3a163267596 100644 --- a/registration-processor/core-processor/registration-processor-uin-generator-stage/pom.xml +++ b/registration-processor/core-processor/registration-processor-uin-generator-stage/pom.xml @@ -4,10 +4,10 @@ io.mosip.registrationprocessor core-processor - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT registration-processor-uin-generator-stage - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT jar UTF-8 diff --git a/registration-processor/core-processor/registration-processor-verification-stage/pom.xml b/registration-processor/core-processor/registration-processor-verification-stage/pom.xml index d2c335892f2..804ff7f221b 100644 --- a/registration-processor/core-processor/registration-processor-verification-stage/pom.xml +++ b/registration-processor/core-processor/registration-processor-verification-stage/pom.xml @@ -8,11 +8,11 @@ io.mosip.registrationprocessor core-processor - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT registration-processor-verification-stage - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT UTF-8 diff --git a/registration-processor/init/pom.xml b/registration-processor/init/pom.xml index ca7568449f2..e0cab04f77e 100644 --- a/registration-processor/init/pom.xml +++ b/registration-processor/init/pom.xml @@ -6,10 +6,10 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT init - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT UTF-8 diff --git a/registration-processor/init/registration-processor-packet-receiver-stage/pom.xml b/registration-processor/init/registration-processor-packet-receiver-stage/pom.xml index 857c65202ae..65c49693beb 100644 --- a/registration-processor/init/registration-processor-packet-receiver-stage/pom.xml +++ b/registration-processor/init/registration-processor-packet-receiver-stage/pom.xml @@ -7,11 +7,11 @@ io.mosip.registrationprocessor init - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT registration-processor-packet-receiver-stage - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT jar registration-processor-packet-receiver-stage diff --git a/registration-processor/init/registration-processor-registration-status-service/pom.xml b/registration-processor/init/registration-processor-registration-status-service/pom.xml index 688979aac3a..7d35fa6396c 100644 --- a/registration-processor/init/registration-processor-registration-status-service/pom.xml +++ b/registration-processor/init/registration-processor-registration-status-service/pom.xml @@ -8,10 +8,10 @@ io.mosip.registrationprocessor init - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT registration-processor-registration-status-service - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT registration-processor-registration-status-service diff --git a/registration-processor/mosip-stage-executor/pom.xml b/registration-processor/mosip-stage-executor/pom.xml index c09a699b8f7..22617e270bd 100644 --- a/registration-processor/mosip-stage-executor/pom.xml +++ b/registration-processor/mosip-stage-executor/pom.xml @@ -5,11 +5,11 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT mosip-stage-executor - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT diff --git a/registration-processor/pom.xml b/registration-processor/pom.xml index a649d38190e..08ff68e0874 100644 --- a/registration-processor/pom.xml +++ b/registration-processor/pom.xml @@ -5,7 +5,7 @@ io.mosip registration - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT @@ -30,7 +30,7 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT pom registration-processor @@ -128,31 +128,31 @@ 0.1.55 - 1.2.0.1-B3 - 1.2.0.1-B3 - 1.2.0.1-B3 - 1.2.0.1-B3 - 1.2.0.1-B3 - 1.2.0.1-B3 - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT + 1.2.0.1-SNAPSHOT + 1.2.0.1-SNAPSHOT + 1.2.0.1-SNAPSHOT + 1.2.0.1-SNAPSHOT + 1.2.0.1-SNAPSHOT + 1.2.0.1-SNAPSHOT - 1.2.0.1-B2 - 1.2.0.1-B2 - 1.2.0.1-B2 - 1.2.0.1-B2 - 1.2.0.1-B2 - 1.2.0.1-B2 - 1.2.0.1-B3 - 1.2.0.1-B2 - 1.2.0.1-B2 - 1.2.0.1-B2 - 1.2.0.1-B2 - 1.2.0.1-B2 - 1.2.0.1-B2 - 1.2.0.1-B3 - 1.2.0.1-B2 - 1.2.0.1-B2 + 1.2.0.1-SNAPSHOT + 1.2.0.1-SNAPSHOT + 1.2.0.1-SNAPSHOT + 1.2.0.1-SNAPSHOT + 1.2.0.1-SNAPSHOT + 1.2.0.1-SNAPSHOT + 1.2.0.1-SNAPSHOT + 1.2.0.1-SNAPSHOT + 1.2.0.1-SNAPSHOT + 1.2.0.1-SNAPSHOT + 1.2.0.1-SNAPSHOT + 1.2.0.1-SNAPSHOT + 1.2.0.1-SNAPSHOT + 1.2.0.1-SNAPSHOT + 1.2.0.1-SNAPSHOT + 1.2.0.1-SNAPSHOT **/dto/**, **/exception/*Exception.java, **/config/*Config.java, diff --git a/registration-processor/post-processor/pom.xml b/registration-processor/post-processor/pom.xml index 0a55dd17040..25da34901cd 100644 --- a/registration-processor/post-processor/pom.xml +++ b/registration-processor/post-processor/pom.xml @@ -6,9 +6,9 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT post-processor post-processor diff --git a/registration-processor/post-processor/registration-processor-message-sender-stage/pom.xml b/registration-processor/post-processor/registration-processor-message-sender-stage/pom.xml index 8026fdd5074..ddca10912f8 100644 --- a/registration-processor/post-processor/registration-processor-message-sender-stage/pom.xml +++ b/registration-processor/post-processor/registration-processor-message-sender-stage/pom.xml @@ -7,11 +7,11 @@ io.mosip.registrationprocessor post-processor - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT registration-processor-message-sender-stage - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT UTF-8 UTF-8 diff --git a/registration-processor/post-processor/registration-processor-printing-stage/pom.xml b/registration-processor/post-processor/registration-processor-printing-stage/pom.xml index 5fe9b79df20..4a9f585821d 100644 --- a/registration-processor/post-processor/registration-processor-printing-stage/pom.xml +++ b/registration-processor/post-processor/registration-processor-printing-stage/pom.xml @@ -6,10 +6,10 @@ io.mosip.registrationprocessor post-processor - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT registration-processor-printing-stage - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT UTF-8 UTF-8 diff --git a/registration-processor/post-processor/registration-processor-registration-transaction-service/pom.xml b/registration-processor/post-processor/registration-processor-registration-transaction-service/pom.xml index 15993e06a96..2e3d4210fe5 100644 --- a/registration-processor/post-processor/registration-processor-registration-transaction-service/pom.xml +++ b/registration-processor/post-processor/registration-processor-registration-transaction-service/pom.xml @@ -5,10 +5,10 @@ io.mosip.registrationprocessor post-processor - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT registration-processor-registration-transaction-service - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT registration-processor-registration-transaction-service UTF-8 diff --git a/registration-processor/pre-processor/pom.xml b/registration-processor/pre-processor/pom.xml index 641eb0338e2..23941368b71 100644 --- a/registration-processor/pre-processor/pom.xml +++ b/registration-processor/pre-processor/pom.xml @@ -7,9 +7,9 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT pre-processor pre-processor diff --git a/registration-processor/pre-processor/registration-processor-cmd-validator-stage/pom.xml b/registration-processor/pre-processor/registration-processor-cmd-validator-stage/pom.xml index ecd645121a6..099373ee95f 100644 --- a/registration-processor/pre-processor/registration-processor-cmd-validator-stage/pom.xml +++ b/registration-processor/pre-processor/registration-processor-cmd-validator-stage/pom.xml @@ -6,10 +6,10 @@ io.mosip.registrationprocessor pre-processor - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT registration-processor-cmd-validator-stage - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT registration-processor-cmd-validator-stage UTF-8 diff --git a/registration-processor/pre-processor/registration-processor-introducer-validator-stage/pom.xml b/registration-processor/pre-processor/registration-processor-introducer-validator-stage/pom.xml index 939274addf5..39b9fc3ac83 100644 --- a/registration-processor/pre-processor/registration-processor-introducer-validator-stage/pom.xml +++ b/registration-processor/pre-processor/registration-processor-introducer-validator-stage/pom.xml @@ -6,10 +6,10 @@ io.mosip.registrationprocessor pre-processor - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT registration-processor-introducer-validator-stage - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT registration-processor-introducer-validator-stage UTF-8 diff --git a/registration-processor/pre-processor/registration-processor-operator-validator-stage/pom.xml b/registration-processor/pre-processor/registration-processor-operator-validator-stage/pom.xml index 83f2f06f324..6c2fd429574 100644 --- a/registration-processor/pre-processor/registration-processor-operator-validator-stage/pom.xml +++ b/registration-processor/pre-processor/registration-processor-operator-validator-stage/pom.xml @@ -6,10 +6,10 @@ io.mosip.registrationprocessor pre-processor - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT registration-processor-operator-validator-stage - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT registration-processor-operator-validator-stage UTF-8 diff --git a/registration-processor/pre-processor/registration-processor-packet-classifier-stage/pom.xml b/registration-processor/pre-processor/registration-processor-packet-classifier-stage/pom.xml index 47a977300f6..d0f9e67ba80 100644 --- a/registration-processor/pre-processor/registration-processor-packet-classifier-stage/pom.xml +++ b/registration-processor/pre-processor/registration-processor-packet-classifier-stage/pom.xml @@ -7,10 +7,10 @@ io.mosip.registrationprocessor pre-processor - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT registration-processor-packet-classifier-stage - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT jar UTF-8 diff --git a/registration-processor/pre-processor/registration-processor-packet-uploader-stage/pom.xml b/registration-processor/pre-processor/registration-processor-packet-uploader-stage/pom.xml index 848e5c823eb..d28b27ff418 100644 --- a/registration-processor/pre-processor/registration-processor-packet-uploader-stage/pom.xml +++ b/registration-processor/pre-processor/registration-processor-packet-uploader-stage/pom.xml @@ -9,9 +9,9 @@ io.mosip.registrationprocessor pre-processor - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT UTF-8 diff --git a/registration-processor/pre-processor/registration-processor-packet-validator-stage/pom.xml b/registration-processor/pre-processor/registration-processor-packet-validator-stage/pom.xml index 4fdfef18387..9485563f780 100644 --- a/registration-processor/pre-processor/registration-processor-packet-validator-stage/pom.xml +++ b/registration-processor/pre-processor/registration-processor-packet-validator-stage/pom.xml @@ -7,10 +7,10 @@ io.mosip.registrationprocessor pre-processor - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT registration-processor-packet-validator-stage - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT jar UTF-8 diff --git a/registration-processor/pre-processor/registration-processor-quality-classifier-stage/pom.xml b/registration-processor/pre-processor/registration-processor-quality-classifier-stage/pom.xml index e55d1b46d1d..6b7b4c50d00 100644 --- a/registration-processor/pre-processor/registration-processor-quality-classifier-stage/pom.xml +++ b/registration-processor/pre-processor/registration-processor-quality-classifier-stage/pom.xml @@ -5,11 +5,11 @@ io.mosip.registrationprocessor pre-processor - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT registration-processor-quality-classifier-stage - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT UTF-8 diff --git a/registration-processor/pre-processor/registration-processor-securezone-notification-stage/pom.xml b/registration-processor/pre-processor/registration-processor-securezone-notification-stage/pom.xml index a83af1000e4..5d796c8376a 100644 --- a/registration-processor/pre-processor/registration-processor-securezone-notification-stage/pom.xml +++ b/registration-processor/pre-processor/registration-processor-securezone-notification-stage/pom.xml @@ -5,10 +5,10 @@ pre-processor io.mosip.registrationprocessor - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT 4.0.0 - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT registration-processor-securezone-notification-stage diff --git a/registration-processor/pre-processor/registration-processor-supervisor-validator-stage/pom.xml b/registration-processor/pre-processor/registration-processor-supervisor-validator-stage/pom.xml index cd29c89e18a..7caa4059e46 100644 --- a/registration-processor/pre-processor/registration-processor-supervisor-validator-stage/pom.xml +++ b/registration-processor/pre-processor/registration-processor-supervisor-validator-stage/pom.xml @@ -6,10 +6,10 @@ io.mosip.registrationprocessor pre-processor - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT registration-processor-supervisor-validator-stage - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT registration-processor-supervisor-validator-stage UTF-8 diff --git a/registration-processor/qc-users-manger/pom.xml b/registration-processor/qc-users-manger/pom.xml index 36abc9db7e0..6f5129d7735 100644 --- a/registration-processor/qc-users-manger/pom.xml +++ b/registration-processor/qc-users-manger/pom.xml @@ -5,11 +5,11 @@ qc-users-manger - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT io.mosip.registrationprocessor registration-processor - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT diff --git a/registration-processor/registration-processor-bio-dedupe-service-impl/pom.xml b/registration-processor/registration-processor-bio-dedupe-service-impl/pom.xml index fc1fe39af20..78f76c5951f 100644 --- a/registration-processor/registration-processor-bio-dedupe-service-impl/pom.xml +++ b/registration-processor/registration-processor-bio-dedupe-service-impl/pom.xml @@ -5,11 +5,11 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT registration-processor-bio-dedupe-service-impl - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT registration-processor-bio-dedupe-service-impl diff --git a/registration-processor/registration-processor-common-camel-bridge/pom.xml b/registration-processor/registration-processor-common-camel-bridge/pom.xml index 9fec69b43d3..f71a52f5c98 100644 --- a/registration-processor/registration-processor-common-camel-bridge/pom.xml +++ b/registration-processor/registration-processor-common-camel-bridge/pom.xml @@ -6,16 +6,16 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT registration-processor-common-camel-bridge - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT jar io.mosip.registration.processor.camel.bridge.MosipCamelBridge 1.0.5 - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT diff --git a/registration-processor/registration-processor-core/pom.xml b/registration-processor/registration-processor-core/pom.xml index 355be5e09bb..15856637960 100644 --- a/registration-processor/registration-processor-core/pom.xml +++ b/registration-processor/registration-processor-core/pom.xml @@ -7,10 +7,10 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT registration-processor-core - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT org.mockito diff --git a/registration-processor/registration-processor-info-storage-service/pom.xml b/registration-processor/registration-processor-info-storage-service/pom.xml index 18e8cee31b3..a96ba4ed241 100644 --- a/registration-processor/registration-processor-info-storage-service/pom.xml +++ b/registration-processor/registration-processor-info-storage-service/pom.xml @@ -7,10 +7,10 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT registration-processor-info-storage-service - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT registration-processor-info-storage-service UTF-8 diff --git a/registration-processor/registration-processor-landing-zone/pom.xml b/registration-processor/registration-processor-landing-zone/pom.xml index d215f8fbb5a..f3d1e06edd0 100644 --- a/registration-processor/registration-processor-landing-zone/pom.xml +++ b/registration-processor/registration-processor-landing-zone/pom.xml @@ -5,11 +5,11 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT registration-processor-landing-zone registration-processor-landing-zone - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT UTF-8 diff --git a/registration-processor/registration-processor-message-sender-impl/pom.xml b/registration-processor/registration-processor-message-sender-impl/pom.xml index b90101fd636..4ec8cd0b4d0 100644 --- a/registration-processor/registration-processor-message-sender-impl/pom.xml +++ b/registration-processor/registration-processor-message-sender-impl/pom.xml @@ -8,11 +8,11 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT registration-processor-message-sender-impl - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT UTF-8 diff --git a/registration-processor/registration-processor-notification-service/pom.xml b/registration-processor/registration-processor-notification-service/pom.xml index 472a222535a..8c37156f16c 100644 --- a/registration-processor/registration-processor-notification-service/pom.xml +++ b/registration-processor/registration-processor-notification-service/pom.xml @@ -8,15 +8,15 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT registration-processor-notification-service - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT UTF-8 UTF-8 - 1.2.0.1-B1 + 1.2.0.1-SNAPSHOT diff --git a/registration-processor/registration-processor-packet-manager/pom.xml b/registration-processor/registration-processor-packet-manager/pom.xml index 790897abbb4..c6d8b1600eb 100644 --- a/registration-processor/registration-processor-packet-manager/pom.xml +++ b/registration-processor/registration-processor-packet-manager/pom.xml @@ -7,12 +7,12 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT registration-processor-packet-manager registration-processor-packet-manager - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT UTF-8 diff --git a/registration-processor/registration-processor-registration-status-service-impl/pom.xml b/registration-processor/registration-processor-registration-status-service-impl/pom.xml index 7d4be79101e..599d1b7c828 100644 --- a/registration-processor/registration-processor-registration-status-service-impl/pom.xml +++ b/registration-processor/registration-processor-registration-status-service-impl/pom.xml @@ -8,10 +8,10 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT registration-processor-registration-status-service-impl - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT UTF-8 diff --git a/registration-processor/registration-processor-rest-client/pom.xml b/registration-processor/registration-processor-rest-client/pom.xml index dbabdd7b0e2..3d66c5b85ae 100644 --- a/registration-processor/registration-processor-rest-client/pom.xml +++ b/registration-processor/registration-processor-rest-client/pom.xml @@ -9,12 +9,12 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT registration-processor-rest-client registration-processor-rest-client - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT UTF-8 diff --git a/registration-processor/stage-groups/pom.xml b/registration-processor/stage-groups/pom.xml index 73229c7023c..4abd296cb2c 100644 --- a/registration-processor/stage-groups/pom.xml +++ b/registration-processor/stage-groups/pom.xml @@ -7,9 +7,9 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT stage-groups stage-groups diff --git a/registration-processor/stage-groups/registration-processor-stage-group-1/pom.xml b/registration-processor/stage-groups/registration-processor-stage-group-1/pom.xml index 26c9bbe68a7..d2c037eee4a 100644 --- a/registration-processor/stage-groups/registration-processor-stage-group-1/pom.xml +++ b/registration-processor/stage-groups/registration-processor-stage-group-1/pom.xml @@ -5,11 +5,11 @@ io.mosip.registrationprocessor stage-groups - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT registration-processor-stage-group-1 - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT UTF-8 @@ -21,14 +21,14 @@ io.mosip.registrationprocessor mosip-stage-executor - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT io.mosip.registrationprocessor registration-processor-packet-receiver-stage - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT diff --git a/registration-processor/stage-groups/registration-processor-stage-group-2/pom.xml b/registration-processor/stage-groups/registration-processor-stage-group-2/pom.xml index 360a2926f7c..c0cf46343d5 100644 --- a/registration-processor/stage-groups/registration-processor-stage-group-2/pom.xml +++ b/registration-processor/stage-groups/registration-processor-stage-group-2/pom.xml @@ -5,11 +5,11 @@ io.mosip.registrationprocessor stage-groups - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT registration-processor-stage-group-2 - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT UTF-8 @@ -21,24 +21,24 @@ io.mosip.registrationprocessor mosip-stage-executor - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT io.mosip.registrationprocessor registration-processor-quality-classifier-stage - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT io.mosip.registrationprocessor registration-processor-securezone-notification-stage - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT io.mosip.registrationprocessor registration-processor-message-sender-stage - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT diff --git a/registration-processor/stage-groups/registration-processor-stage-group-3/pom.xml b/registration-processor/stage-groups/registration-processor-stage-group-3/pom.xml index d097331bf51..e96279087b6 100644 --- a/registration-processor/stage-groups/registration-processor-stage-group-3/pom.xml +++ b/registration-processor/stage-groups/registration-processor-stage-group-3/pom.xml @@ -5,11 +5,11 @@ io.mosip.registrationprocessor stage-groups - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT registration-processor-stage-group-3 - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT UTF-8 @@ -21,29 +21,29 @@ io.mosip.registrationprocessor mosip-stage-executor - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT io.mosip.registrationprocessor registration-processor-abis-handler-stage - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT io.mosip.registrationprocessor registration-processor-abis-middleware-stage - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT io.mosip.registrationprocessor registration-processor-bio-dedupe-stage - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT io.mosip.registrationprocessor registration-processor-manual-adjudication-stage - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT diff --git a/registration-processor/stage-groups/registration-processor-stage-group-4/pom.xml b/registration-processor/stage-groups/registration-processor-stage-group-4/pom.xml index d0c2707466c..ce1cdc96545 100644 --- a/registration-processor/stage-groups/registration-processor-stage-group-4/pom.xml +++ b/registration-processor/stage-groups/registration-processor-stage-group-4/pom.xml @@ -5,11 +5,11 @@ io.mosip.registrationprocessor stage-groups - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT registration-processor-stage-group-4 - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT UTF-8 @@ -21,19 +21,19 @@ io.mosip.registrationprocessor mosip-stage-executor - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT io.mosip.registrationprocessor registration-processor-biometric-authentication-stage - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT io.mosip.registrationprocessor registration-processor-demo-dedupe-stage - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT diff --git a/registration-processor/stage-groups/registration-processor-stage-group-5/pom.xml b/registration-processor/stage-groups/registration-processor-stage-group-5/pom.xml index a75eb2f08ad..f167b1d15b3 100644 --- a/registration-processor/stage-groups/registration-processor-stage-group-5/pom.xml +++ b/registration-processor/stage-groups/registration-processor-stage-group-5/pom.xml @@ -5,11 +5,11 @@ io.mosip.registrationprocessor stage-groups - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT registration-processor-stage-group-5 - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT UTF-8 @@ -21,34 +21,34 @@ io.mosip.registrationprocessor mosip-stage-executor - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT io.mosip.registrationprocessor registration-processor-cmd-validator-stage - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT io.mosip.registrationprocessor registration-processor-operator-validator-stage - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT io.mosip.registrationprocessor registration-processor-supervisor-validator-stage - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT io.mosip.registrationprocessor registration-processor-introducer-validator-stage - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT io.mosip.registrationprocessor registration-processor-packet-validator-stage - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT diff --git a/registration-processor/stage-groups/registration-processor-stage-group-6/pom.xml b/registration-processor/stage-groups/registration-processor-stage-group-6/pom.xml index e74f7393085..114783da14d 100644 --- a/registration-processor/stage-groups/registration-processor-stage-group-6/pom.xml +++ b/registration-processor/stage-groups/registration-processor-stage-group-6/pom.xml @@ -5,11 +5,11 @@ io.mosip.registrationprocessor stage-groups - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT registration-processor-stage-group-6 - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT UTF-8 @@ -21,24 +21,24 @@ io.mosip.registrationprocessor mosip-stage-executor - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT io.mosip.registrationprocessor registration-processor-packet-uploader-stage - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT io.mosip.registrationprocessor registration-processor-packet-classifier-stage - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT io.mosip.registrationprocessor registration-processor-verification-stage - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT diff --git a/registration-processor/stage-groups/registration-processor-stage-group-7/pom.xml b/registration-processor/stage-groups/registration-processor-stage-group-7/pom.xml index c1a8220c7a6..4fc1177f84a 100644 --- a/registration-processor/stage-groups/registration-processor-stage-group-7/pom.xml +++ b/registration-processor/stage-groups/registration-processor-stage-group-7/pom.xml @@ -5,11 +5,11 @@ io.mosip.registrationprocessor stage-groups - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT registration-processor-stage-group-7 - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT UTF-8 @@ -21,29 +21,29 @@ io.mosip.registrationprocessor mosip-stage-executor - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT io.mosip.registrationprocessor registration-processor-uin-generator-stage - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT io.mosip.registrationprocessor registration-processor-biometric-extraction-stage - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT io.mosip.registrationprocessor registration-processor-finalization-stage - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT io.mosip.registrationprocessor registration-processor-printing-stage - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT diff --git a/registration-processor/workflow-engine/pom.xml b/registration-processor/workflow-engine/pom.xml index e0ea116118a..cebeb084931 100644 --- a/registration-processor/workflow-engine/pom.xml +++ b/registration-processor/workflow-engine/pom.xml @@ -5,9 +5,9 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT workflow-engine workflow-engine diff --git a/registration-processor/workflow-engine/registration-processor-reprocessor/pom.xml b/registration-processor/workflow-engine/registration-processor-reprocessor/pom.xml index 56d459efd73..8df1096a769 100644 --- a/registration-processor/workflow-engine/registration-processor-reprocessor/pom.xml +++ b/registration-processor/workflow-engine/registration-processor-reprocessor/pom.xml @@ -7,10 +7,10 @@ io.mosip.registrationprocessor workflow-engine - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT registration-processor-reprocessor - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT registration-processor-reprocessor UTF-8 diff --git a/registration-processor/workflow-engine/registration-processor-workflow-manager-service/pom.xml b/registration-processor/workflow-engine/registration-processor-workflow-manager-service/pom.xml index 9a6bab4ba88..c69945fe557 100644 --- a/registration-processor/workflow-engine/registration-processor-workflow-manager-service/pom.xml +++ b/registration-processor/workflow-engine/registration-processor-workflow-manager-service/pom.xml @@ -5,10 +5,10 @@ io.mosip.registrationprocessor workflow-engine - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT registration-processor-workflow-manager-service - 1.2.0.1-B3 + 1.2.0.1-SNAPSHOT registration-processor-workflow-manager-service UTF-8 From 520425feffe02ad6239b905b3aa981b0add4632b Mon Sep 17 00:00:00 2001 From: Sowmya Ujjappa Banakar <43202851+sowmya695@users.noreply.github.com> Date: Mon, 8 Jan 2024 13:13:29 +0530 Subject: [PATCH 109/133] MOSIP-29935 Code changes (#1800) (#1815) * MOSIP-29935 Code changes * MOSIP-29935 intial changes after new approach * MOSIP-29935 code fix * MOSIP-29935 code fix * MOSIp-29935 code fix after testing --------- Signed-off-by: Sowmya Ujjappa Banakar Co-authored-by: Sowmya Ujjappa Banakar --- .../util/PlatformSuccessMessages.java | 431 +++++----- .../core/status/util/StatusUtil.java | 2 + .../verticle/ReprocessorVerticle.java | 772 ++++++++++-------- .../verticle/ReprocessorVerticleTest.java | 34 + 4 files changed, 678 insertions(+), 561 deletions(-) diff --git a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/exception/util/PlatformSuccessMessages.java b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/exception/util/PlatformSuccessMessages.java index c18347781b7..51956273957 100644 --- a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/exception/util/PlatformSuccessMessages.java +++ b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/exception/util/PlatformSuccessMessages.java @@ -1,214 +1,217 @@ -package io.mosip.registration.processor.core.exception.util; - -/** - * - * @author M1048399 Horteppa - * - */ -public enum PlatformSuccessMessages { - - // Packet Receiver Success messages. - - /** The rpr pkr packet receiver. */ - PACKET_RECEIVER_VALIDATION_SUCCESS(PlatformConstants.RPR_PACKET_RECEIVER_MODULE + "001", - "Packet receiver validation success"), - - /** The rpr pkr packet receiver. */ - RPR_PKR_PACKET_RECEIVER(PlatformConstants.RPR_PACKET_RECEIVER_MODULE + "000", - "Packet received and uploaded to landing zone"), - - // securezone notification success messages - /** The rpr sez notification. */ - RPR_SEZ_SECUREZONE_NOTIFICATION(PlatformConstants.RPR_SECUREZONE_NOTIFICATION_MODULE + "000", "Securezone Notification Success"), - - RPR_PUM_PACKET_UPLOADER(PlatformConstants.RPR_PACKET_UPLOADER_MODULE + "000", "Packet uploaded to file system"), - - RPR_PUM_PACKET_ARCHIVED(PlatformConstants.RPR_PACKET_UPLOADER_MODULE + "001", "Packet successfully archived"), - - RPR_PUM_PACKET_UPLOADER_ALREADY_UPLOADED(PlatformConstants.RPR_PACKET_UPLOADER_MODULE + "002", "Packet already present in object store"), - - // Packet Validator Success messages - /** The rpr pkr packet validate. */ - RPR_PKR_PACKET_VALIDATE(PlatformConstants.RPR_PACKET_VALIDATOR_MODULE + "000", "Packet Validation Success"), - /** The reverse data sync success. */ - REVERSE_DATA_SYNC_SUCCESS(PlatformConstants.RPR_PACKET_VALIDATOR_MODULE + "017", "Reverse Data Sync Success"), - // Packet Classifier Success messages - /** The rpr pkr packet classifier. */ - RPR_PKR_PACKET_CLASSIFIER(PlatformConstants.RPR_PACKET_CLASSIFIER_MODULE + "000", "Packet Classifier Success"), - - RPR_PKR_ADDITIONAL_INFO_DELETED(PlatformConstants.RPR_PACKET_VALIDATOR_MODULE + "000", "Deleted additionalInfo from RegistrationList"), - - RPR_PKR_OPERATOR_VALIDATE(PlatformConstants.RPR_OVM_VALIDATOR_MODULE + "000", "OPERATOR Validation Success"), - - RPR_PKR_SUPERVISOR_VALIDATE(PlatformConstants.RPR_SVM_VALIDATOR_MODULE + "000", "SUPERVISOR Validation Success"), - - RPR_PKR_INTRODUCER_VALIDATE(PlatformConstants.RPR_IVM_VALIDATOR_MODULE + "000", "INTRODUCER Validation Success"), - - // CMD validator Success messages - RPR_PKR_CMD_VALIDATE(PlatformConstants.RPR_CMD_VALIDATOR_MODULE + "000", "CMD Validation Success"), - - // DEMO-De-dupe Success Messages - /** The rpr pkr demode-dupe validate. */ - RPR_PKR_DEMO_DE_DUP(PlatformConstants.RPR_DEMO_DEDUPE_MODULE + "000", "Demo-de-dupe Success"), - - RPR_PKR_DEMO_DE_DUP_POTENTIAL_DUPLICATION_FOUND(PlatformConstants.RPR_DEMO_DEDUPE_MODULE + "001", - "Potential duplicate packet found for registration id : "), - - RPR_PKR_DEMO_DE_DUP_SKIP(PlatformConstants.RPR_DEMO_DEDUPE_MODULE + "002", "Demographic Deduplication Skipped"), - - // Biometric Authentication Success Messages - RPR_PKR_BIOMETRIC_AUTHENTICATION(PlatformConstants.RPR_BIOMETRIC_AUTHENTICATION_MODULE + "000", - "Biometric Authentication Success"), - - - - // Bio-De-dupe Success messages - /** The Constant PACKET_BIODEDUPE_SUCCESS. */ - RPR_BIO_DEDUPE_SUCCESS(PlatformConstants.RPR_BIO_DEDUPE_STAGE_MODULE + "000", "Packet biodedupe successful"), - - /** The Constant PACKET_BIOMETRIC_POTENTIAL_MATCH. */ - RPR_BIO_METRIC_POTENTIAL_MATCH(PlatformConstants.RPR_BIO_DEDUPE_STAGE_MODULE + "000", - "Potential match found while processing bio dedupe"), - - RPR_BIO_LOST_PACKET_UNIQUE_MATCH_FOUND(PlatformConstants.RPR_BIO_DEDUPE_STAGE_MODULE + "001", - "Unique Match was Found for the Biometrics Received"), - - RPR_RE_PROCESS_SUCCESS(PlatformConstants.RPR_REPROCESSOR_VERTICLE + "000", "Reprocessor Success"), - - RPR_RE_PROCESS_FAILED(PlatformConstants.RPR_REPROCESSOR_VERTICLE + "002", "Reprocessor FAILED"), - - RPR_SENT_TO_REPROCESS_SUCCESS(PlatformConstants.RPR_REPROCESSOR_VERTICLE + "001", "sent to reprocess Success"), - - RPR_WORKFLOW_INTERNAL_ACTION_SUCCESS(PlatformConstants.RPR_WORKFLOW_INTERNAL_ACTION + "000", - "Workflow internal action completed successfully"), - - RPR_WORKFLOW_ACTION_SERVICE_SUCCESS(PlatformConstants.RPR_WORKFLOW_ACTION_SERVICE + "000", - "Processed the workflow action - %s"), - - RPR_WORKFLOW_ACTION_API_SUCCESS(PlatformConstants.RPR_WORKFLOW_ACTION_API + "000", - "Process the workflow action success"), - RPR_WORKFLOW_SEARCH_API_SUCCESS(PlatformConstants.RPR_WORKFLOW_SEARCH_API + "000", - "Process the workflow search success"), - RPR_WORKFLOW_ACTION_JOB_SUCCESS(PlatformConstants.RPR_WORKFLOW_ACTION_JOB + "000", "Workflow action job success"), - - RPR_EXTERNAL_STAGE_SUCCESS(PlatformConstants.RPR_EXTERNAL_STAGE + "000", "External stage Success"), - - RPR_UIN_GENERATOR_STAGE_SUCCESS(PlatformConstants.RPR_UIN_GENERATOR_STAGE + "000", "UIN Generator Success"), - - RPR_BIOMETRIC_EXTRACTION_SUCCESS(PlatformConstants.RPR_BIOMETRIC_EXTRACTION_STAGE + "000", - "biometric extraction success"), - - RPR_FINALIZATION_SUCCESS(PlatformConstants.RPR_FINALIZATION_STAGE + "000", - "Finalization success"), - - RPR_UIN_DATA_UPDATION_SUCCESS(PlatformConstants.RPR_UIN_GENERATOR_STAGE + "001", "UIN Generator Success"), - - RPR_UIN_ACTIVATED_SUCCESS(PlatformConstants.RPR_UIN_GENERATOR_STAGE + "002", "UIN Generator Success"), - - RPR_UIN_DEACTIVATION_SUCCESS(PlatformConstants.RPR_UIN_GENERATOR_STAGE + "003", "UIN Generator Success"), - - RPR_LINK_RID_FOR_LOST_PACKET_SUCCESS(PlatformConstants.RPR_UIN_GENERATOR_STAGE + "004", "UIN Generator Success"), - - RPR_QUALITY_CHECK_SUCCESS(PlatformConstants.RPR_QUALITY_CHECKER_MODULE + "000", "Quality check Success"), - - RPR_PRINT_STAGE_REQUEST_SUCCESS(PlatformConstants.RPR_PRINTING_MODULE + "000", - "Print request submitted"), - - RPR_PRINT_STAGE_SUCCESS(PlatformConstants.RPR_PRINTING_MODULE + "001", "Print and Post Completed"), - - RPR_MESSAGE_SENDER_STAGE_SUCCESS(PlatformConstants.RPR_MESSAGE_SENDER_TEMPLATE + "001", - "Message Sender Stage success"), - - RPR_ABIS_HANDLER_STAGE_SUCCESS(PlatformConstants.RPR_ABIS_HANDLER + "000", "ABIS hanlder stage success"), - - RPR_ABIS_MIDDLEWARE_STAGE_SUCCESS(PlatformConstants.RPR_ABIS_MIDDLEWARE + "000", - "Abis insertRequests sucessfully sent to Queue"), - - RPR_MANUAL_VERIFICATION_APPROVED(PlatformConstants.RPR_MANUAL_ADJUDICATION_MODULE + "000", - "Manual verification approved"), - - RPR_MANUAL_VERIFICATION_RESEND(PlatformConstants.RPR_MANUAL_ADJUDICATION_MODULE + "002", - "Manual verification resend"), - - RPR_MANUAL_VERIFICATION_SENT(PlatformConstants.RPR_MANUAL_ADJUDICATION_MODULE + "001", - "Manual verification Sent to queue"), - - RPR_VERIFICATION_SENT(PlatformConstants.RPR_VERIFICATION_MODULE + "000", - "Sent for Verification"), - - RPR_VERIFICATION_SUCCESS(PlatformConstants.RPR_VERIFICATION_MODULE + "001", - "Verification successful"), - - RPR_DECRYPTION_SUCCESS(PlatformConstants.RPR_PACKET_DECRYPTION_MODULE + "000", "Decryption success"), - - RPR_ENCRYPTION_SUCCESS(PlatformConstants.RPR_PACKET_DECRYPTION_MODULE + "000", "Encryption success"), - - RPR_PRINT_SERVICE_SUCCESS(PlatformConstants.RPR_PRINTING_MODULE + "002", "Pdf generated and sent to print stage"), - - RPR_SYNC_REGISTRATION_SERVICE_SUCCESS(PlatformConstants.RPR_REGISTRATION_STATUS_MODULE + "000", "SYNC successfull"), - - RPR_REQUEST_HANDLER_LOST_PACKET_SUCCESS(PlatformConstants.RPR_PACKET_REQUEST_HANDLER_MODULE + "000", - "Lost packet id value fetched successfully"), - - PACKET_MARK_AS_PAUSED(PlatformConstants.RPR_CAMEL_BRIDGE_MODULE + "000", - "Packet paused because of pause settings match"), - PACKET_COMPLETE_AS_PROCESSED(PlatformConstants.RPR_CAMEL_BRIDGE_MODULE + "001", - "Packet processing completed with processed status"), - PACKET_COMPLETE_AS_REJECTED(PlatformConstants.RPR_CAMEL_BRIDGE_MODULE + "002", - "Packet processing completed with reject status"), - PACKET_COMPLETE_AS_FAILED(PlatformConstants.RPR_CAMEL_BRIDGE_MODULE + "003", - "Packet processing completed with failed status"), - PACKET_MARK_AS_REPROCESS(PlatformConstants.RPR_CAMEL_BRIDGE_MODULE + "004", "Packet marked for reprocessing"), - PACKET_PROCESSING_COMPLETED(PlatformConstants.RPR_CAMEL_BRIDGE_MODULE + "009", - "Packet processing completed with action code : "), - - PAUSE_AND_REQUEST_ADDITIONAL_INFO(PlatformConstants.RPR_CAMEL_BRIDGE_MODULE + "005", - "packet paused and request additional info"), - - PACKET_RESTART_PARENT_FLOW(PlatformConstants.RPR_CAMEL_BRIDGE_MODULE + "006", - "Packet parent flow restart initiated"), - - PACKET_COMPLETE_AS_REJECTED_WITHOUT_PARENT_FLOW(PlatformConstants.RPR_CAMEL_BRIDGE_MODULE + "007", - "Packet processing completed with reject status without Parent flow"), - - PACKET_ANONYMOUS_PROFILE(PlatformConstants.RPR_CAMEL_BRIDGE_MODULE + "008", - "Packet anonymous profile flow initiated"); - - /** The success message. */ - private final String successMessage; - - /** The success code. */ - private final String successCode; - - /** - * Instantiates a new platform success messages. - * - * @param errorCode - * the error code - * @param errorMsg - * the error msg - */ - private PlatformSuccessMessages(String errorCode, String errorMsg) { - this.successCode = errorCode; - this.successMessage = errorMsg; - } - - /** - * Gets the message. - * - * @return the message - */ - public String getMessage() { - return this.successMessage; - } - - /** - * Gets the code. - * - * @return the code - */ - public String getCode() { - return this.successCode; - } - -} +package io.mosip.registration.processor.core.exception.util; + +/** + * + * @author M1048399 Horteppa + * + */ +public enum PlatformSuccessMessages { + + // Packet Receiver Success messages. + + /** The rpr pkr packet receiver. */ + PACKET_RECEIVER_VALIDATION_SUCCESS(PlatformConstants.RPR_PACKET_RECEIVER_MODULE + "001", + "Packet receiver validation success"), + + /** The rpr pkr packet receiver. */ + RPR_PKR_PACKET_RECEIVER(PlatformConstants.RPR_PACKET_RECEIVER_MODULE + "000", + "Packet received and uploaded to landing zone"), + + // securezone notification success messages + /** The rpr sez notification. */ + RPR_SEZ_SECUREZONE_NOTIFICATION(PlatformConstants.RPR_SECUREZONE_NOTIFICATION_MODULE + "000", "Securezone Notification Success"), + + RPR_PUM_PACKET_UPLOADER(PlatformConstants.RPR_PACKET_UPLOADER_MODULE + "000", "Packet uploaded to file system"), + + RPR_PUM_PACKET_ARCHIVED(PlatformConstants.RPR_PACKET_UPLOADER_MODULE + "001", "Packet successfully archived"), + + RPR_PUM_PACKET_UPLOADER_ALREADY_UPLOADED(PlatformConstants.RPR_PACKET_UPLOADER_MODULE + "002", "Packet already present in object store"), + + // Packet Validator Success messages + /** The rpr pkr packet validate. */ + RPR_PKR_PACKET_VALIDATE(PlatformConstants.RPR_PACKET_VALIDATOR_MODULE + "000", "Packet Validation Success"), + /** The reverse data sync success. */ + REVERSE_DATA_SYNC_SUCCESS(PlatformConstants.RPR_PACKET_VALIDATOR_MODULE + "017", "Reverse Data Sync Success"), + // Packet Classifier Success messages + /** The rpr pkr packet classifier. */ + RPR_PKR_PACKET_CLASSIFIER(PlatformConstants.RPR_PACKET_CLASSIFIER_MODULE + "000", "Packet Classifier Success"), + + RPR_PKR_ADDITIONAL_INFO_DELETED(PlatformConstants.RPR_PACKET_VALIDATOR_MODULE + "000", "Deleted additionalInfo from RegistrationList"), + + RPR_PKR_OPERATOR_VALIDATE(PlatformConstants.RPR_OVM_VALIDATOR_MODULE + "000", "OPERATOR Validation Success"), + + RPR_PKR_SUPERVISOR_VALIDATE(PlatformConstants.RPR_SVM_VALIDATOR_MODULE + "000", "SUPERVISOR Validation Success"), + + RPR_PKR_INTRODUCER_VALIDATE(PlatformConstants.RPR_IVM_VALIDATOR_MODULE + "000", "INTRODUCER Validation Success"), + + // CMD validator Success messages + RPR_PKR_CMD_VALIDATE(PlatformConstants.RPR_CMD_VALIDATOR_MODULE + "000", "CMD Validation Success"), + + // DEMO-De-dupe Success Messages + /** The rpr pkr demode-dupe validate. */ + RPR_PKR_DEMO_DE_DUP(PlatformConstants.RPR_DEMO_DEDUPE_MODULE + "000", "Demo-de-dupe Success"), + + RPR_PKR_DEMO_DE_DUP_POTENTIAL_DUPLICATION_FOUND(PlatformConstants.RPR_DEMO_DEDUPE_MODULE + "001", + "Potential duplicate packet found for registration id : "), + + RPR_PKR_DEMO_DE_DUP_SKIP(PlatformConstants.RPR_DEMO_DEDUPE_MODULE + "002", "Demographic Deduplication Skipped"), + + // Biometric Authentication Success Messages + RPR_PKR_BIOMETRIC_AUTHENTICATION(PlatformConstants.RPR_BIOMETRIC_AUTHENTICATION_MODULE + "000", + "Biometric Authentication Success"), + + + + // Bio-De-dupe Success messages + /** The Constant PACKET_BIODEDUPE_SUCCESS. */ + RPR_BIO_DEDUPE_SUCCESS(PlatformConstants.RPR_BIO_DEDUPE_STAGE_MODULE + "000", "Packet biodedupe successful"), + + /** The Constant PACKET_BIOMETRIC_POTENTIAL_MATCH. */ + RPR_BIO_METRIC_POTENTIAL_MATCH(PlatformConstants.RPR_BIO_DEDUPE_STAGE_MODULE + "000", + "Potential match found while processing bio dedupe"), + + RPR_BIO_LOST_PACKET_UNIQUE_MATCH_FOUND(PlatformConstants.RPR_BIO_DEDUPE_STAGE_MODULE + "001", + "Unique Match was Found for the Biometrics Received"), + + RPR_RE_PROCESS_SUCCESS(PlatformConstants.RPR_REPROCESSOR_VERTICLE + "000", "Reprocessor Success"), + + RPR_RE_PROCESS_FAILED(PlatformConstants.RPR_REPROCESSOR_VERTICLE + "002", "Reprocessor FAILED"), + + RPR_SENT_TO_REPROCESS_SUCCESS(PlatformConstants.RPR_REPROCESSOR_VERTICLE + "001", "sent to reprocess Success"), + + RPR_SENT_TO_REPROCESS_RESTART_FROM_STAGE_SUCCESS(PlatformConstants.RPR_REPROCESSOR_VERTICLE + "002", + "sent to reprocess restart from stage Success"), + + RPR_WORKFLOW_INTERNAL_ACTION_SUCCESS(PlatformConstants.RPR_WORKFLOW_INTERNAL_ACTION + "000", + "Workflow internal action completed successfully"), + + RPR_WORKFLOW_ACTION_SERVICE_SUCCESS(PlatformConstants.RPR_WORKFLOW_ACTION_SERVICE + "000", + "Processed the workflow action - %s"), + + RPR_WORKFLOW_ACTION_API_SUCCESS(PlatformConstants.RPR_WORKFLOW_ACTION_API + "000", + "Process the workflow action success"), + RPR_WORKFLOW_SEARCH_API_SUCCESS(PlatformConstants.RPR_WORKFLOW_SEARCH_API + "000", + "Process the workflow search success"), + RPR_WORKFLOW_ACTION_JOB_SUCCESS(PlatformConstants.RPR_WORKFLOW_ACTION_JOB + "000", "Workflow action job success"), + + RPR_EXTERNAL_STAGE_SUCCESS(PlatformConstants.RPR_EXTERNAL_STAGE + "000", "External stage Success"), + + RPR_UIN_GENERATOR_STAGE_SUCCESS(PlatformConstants.RPR_UIN_GENERATOR_STAGE + "000", "UIN Generator Success"), + + RPR_BIOMETRIC_EXTRACTION_SUCCESS(PlatformConstants.RPR_BIOMETRIC_EXTRACTION_STAGE + "000", + "biometric extraction success"), + + RPR_FINALIZATION_SUCCESS(PlatformConstants.RPR_FINALIZATION_STAGE + "000", + "Finalization success"), + + RPR_UIN_DATA_UPDATION_SUCCESS(PlatformConstants.RPR_UIN_GENERATOR_STAGE + "001", "UIN Generator Success"), + + RPR_UIN_ACTIVATED_SUCCESS(PlatformConstants.RPR_UIN_GENERATOR_STAGE + "002", "UIN Generator Success"), + + RPR_UIN_DEACTIVATION_SUCCESS(PlatformConstants.RPR_UIN_GENERATOR_STAGE + "003", "UIN Generator Success"), + + RPR_LINK_RID_FOR_LOST_PACKET_SUCCESS(PlatformConstants.RPR_UIN_GENERATOR_STAGE + "004", "UIN Generator Success"), + + RPR_QUALITY_CHECK_SUCCESS(PlatformConstants.RPR_QUALITY_CHECKER_MODULE + "000", "Quality check Success"), + + RPR_PRINT_STAGE_REQUEST_SUCCESS(PlatformConstants.RPR_PRINTING_MODULE + "000", + "Print request submitted"), + + RPR_PRINT_STAGE_SUCCESS(PlatformConstants.RPR_PRINTING_MODULE + "001", "Print and Post Completed"), + + RPR_MESSAGE_SENDER_STAGE_SUCCESS(PlatformConstants.RPR_MESSAGE_SENDER_TEMPLATE + "001", + "Message Sender Stage success"), + + RPR_ABIS_HANDLER_STAGE_SUCCESS(PlatformConstants.RPR_ABIS_HANDLER + "000", "ABIS hanlder stage success"), + + RPR_ABIS_MIDDLEWARE_STAGE_SUCCESS(PlatformConstants.RPR_ABIS_MIDDLEWARE + "000", + "Abis insertRequests sucessfully sent to Queue"), + + RPR_MANUAL_VERIFICATION_APPROVED(PlatformConstants.RPR_MANUAL_ADJUDICATION_MODULE + "000", + "Manual verification approved"), + + RPR_MANUAL_VERIFICATION_RESEND(PlatformConstants.RPR_MANUAL_ADJUDICATION_MODULE + "002", + "Manual verification resend"), + + RPR_MANUAL_VERIFICATION_SENT(PlatformConstants.RPR_MANUAL_ADJUDICATION_MODULE + "001", + "Manual verification Sent to queue"), + + RPR_VERIFICATION_SENT(PlatformConstants.RPR_VERIFICATION_MODULE + "000", + "Sent for Verification"), + + RPR_VERIFICATION_SUCCESS(PlatformConstants.RPR_VERIFICATION_MODULE + "001", + "Verification successful"), + + RPR_DECRYPTION_SUCCESS(PlatformConstants.RPR_PACKET_DECRYPTION_MODULE + "000", "Decryption success"), + + RPR_ENCRYPTION_SUCCESS(PlatformConstants.RPR_PACKET_DECRYPTION_MODULE + "000", "Encryption success"), + + RPR_PRINT_SERVICE_SUCCESS(PlatformConstants.RPR_PRINTING_MODULE + "002", "Pdf generated and sent to print stage"), + + RPR_SYNC_REGISTRATION_SERVICE_SUCCESS(PlatformConstants.RPR_REGISTRATION_STATUS_MODULE + "000", "SYNC successfull"), + + RPR_REQUEST_HANDLER_LOST_PACKET_SUCCESS(PlatformConstants.RPR_PACKET_REQUEST_HANDLER_MODULE + "000", + "Lost packet id value fetched successfully"), + + PACKET_MARK_AS_PAUSED(PlatformConstants.RPR_CAMEL_BRIDGE_MODULE + "000", + "Packet paused because of pause settings match"), + PACKET_COMPLETE_AS_PROCESSED(PlatformConstants.RPR_CAMEL_BRIDGE_MODULE + "001", + "Packet processing completed with processed status"), + PACKET_COMPLETE_AS_REJECTED(PlatformConstants.RPR_CAMEL_BRIDGE_MODULE + "002", + "Packet processing completed with reject status"), + PACKET_COMPLETE_AS_FAILED(PlatformConstants.RPR_CAMEL_BRIDGE_MODULE + "003", + "Packet processing completed with failed status"), + PACKET_MARK_AS_REPROCESS(PlatformConstants.RPR_CAMEL_BRIDGE_MODULE + "004", "Packet marked for reprocessing"), + PACKET_PROCESSING_COMPLETED(PlatformConstants.RPR_CAMEL_BRIDGE_MODULE + "009", + "Packet processing completed with action code : "), + + PAUSE_AND_REQUEST_ADDITIONAL_INFO(PlatformConstants.RPR_CAMEL_BRIDGE_MODULE + "005", + "packet paused and request additional info"), + + PACKET_RESTART_PARENT_FLOW(PlatformConstants.RPR_CAMEL_BRIDGE_MODULE + "006", + "Packet parent flow restart initiated"), + + PACKET_COMPLETE_AS_REJECTED_WITHOUT_PARENT_FLOW(PlatformConstants.RPR_CAMEL_BRIDGE_MODULE + "007", + "Packet processing completed with reject status without Parent flow"), + + PACKET_ANONYMOUS_PROFILE(PlatformConstants.RPR_CAMEL_BRIDGE_MODULE + "008", + "Packet anonymous profile flow initiated"); + + /** The success message. */ + private final String successMessage; + + /** The success code. */ + private final String successCode; + + /** + * Instantiates a new platform success messages. + * + * @param errorCode + * the error code + * @param errorMsg + * the error msg + */ + private PlatformSuccessMessages(String errorCode, String errorMsg) { + this.successCode = errorCode; + this.successMessage = errorMsg; + } + + /** + * Gets the message. + * + * @return the message + */ + public String getMessage() { + return this.successMessage; + } + + /** + * Gets the code. + * + * @return the code + */ + public String getCode() { + return this.successCode; + } + +} diff --git a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/status/util/StatusUtil.java b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/status/util/StatusUtil.java index 8b860e167c3..7d3910b450f 100644 --- a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/status/util/StatusUtil.java +++ b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/status/util/StatusUtil.java @@ -314,6 +314,8 @@ public enum StatusUtil { RE_PROCESS_FAILED(StatusConstants.RE_PROCESS_MODULE_FAILED + "001", "Reprocess count has exceeded the configured attempts"), RE_PROCESS_COMPLETED(StatusConstants.RE_PROCESS_MODULE_SUCCESS + "001", "Reprocess Completed"), + RE_PROCESS_RESTART_FROM_STAGE(StatusConstants.RE_PROCESS_MODULE_SUCCESS + "002", + "Reprocess restart from stage Completed"), // Message sender stage NOTIFICATION_SUCESSFUL(StatusConstants.MESSAGE_SENDER_NOTIF_SUCCESS_CODE + "001", "Notification Sent Successfully"), diff --git a/registration-processor/workflow-engine/registration-processor-reprocessor/src/main/java/io/mosip/registration/processor/reprocessor/verticle/ReprocessorVerticle.java b/registration-processor/workflow-engine/registration-processor-reprocessor/src/main/java/io/mosip/registration/processor/reprocessor/verticle/ReprocessorVerticle.java index 8233e09837d..bebd730a69a 100644 --- a/registration-processor/workflow-engine/registration-processor-reprocessor/src/main/java/io/mosip/registration/processor/reprocessor/verticle/ReprocessorVerticle.java +++ b/registration-processor/workflow-engine/registration-processor-reprocessor/src/main/java/io/mosip/registration/processor/reprocessor/verticle/ReprocessorVerticle.java @@ -1,347 +1,425 @@ -package io.mosip.registration.processor.reprocessor.verticle; - -import java.util.ArrayList; -import java.util.List; - -import io.mosip.registration.processor.reprocessor.constants.ReprocessorConstants; -import org.apache.commons.lang3.exception.ExceptionUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.core.env.Environment; -import org.springframework.stereotype.Component; -import org.springframework.util.CollectionUtils; - -import io.mosip.kernel.core.logger.spi.Logger; -import io.mosip.registration.processor.core.abstractverticle.MessageBusAddress; -import io.mosip.registration.processor.core.abstractverticle.MessageDTO; -import io.mosip.registration.processor.core.abstractverticle.MosipEventBus; -import io.mosip.registration.processor.core.abstractverticle.MosipRouter; -import io.mosip.registration.processor.core.abstractverticle.MosipVerticleAPIManager; -import io.mosip.registration.processor.core.code.EventId; -import io.mosip.registration.processor.core.code.EventName; -import io.mosip.registration.processor.core.code.EventType; -import io.mosip.registration.processor.core.code.ModuleName; -import io.mosip.registration.processor.core.code.RegistrationTransactionStatusCode; -import io.mosip.registration.processor.core.code.RegistrationTransactionTypeCode; -import io.mosip.registration.processor.core.constant.LoggerFileConstant; -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.status.util.StatusUtil; -import io.mosip.registration.processor.core.util.MessageBusUtil; -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.vertx.core.AsyncResult; -import io.vertx.core.Vertx; -import io.vertx.core.eventbus.EventBus; -import io.vertx.core.json.JsonObject; - -/** - * The Reprocessor Verticle to deploy the scheduler and implement re-processing - * logic - * - * @author Alok Ranjan - * @author Sowmya - * @author Pranav Kumar - * - * @since 0.10.0 - * - */ -@Component -public class ReprocessorVerticle extends MosipVerticleAPIManager { - - private static final String VERTICLE_PROPERTY_PREFIX = "mosip.regproc.reprocessor."; - - private static Logger regProcLogger = RegProcessorLogger.getLogger(ReprocessorVerticle.class); - - /** The cluster manager url. */ - @Value("${vertx.cluster.configuration}") - private String clusterManagerUrl; - - /** The environment. */ - @Autowired - Environment environment; - - /** The mosip event bus. */ - MosipEventBus mosipEventBus = null; - - /** The fetch size. */ - @Value("${registration.processor.reprocess.fetchsize}") - private Integer fetchSize; - - /** The elapse time. */ - @Value("${registration.processor.reprocess.elapse.time}") - private long elapseTime; - - /** The reprocess count. */ - @Value("${registration.processor.reprocess.attempt.count}") - private Integer reprocessCount; - - /** Comman seperated stage names that should be excluded while reprocessing. */ - @Value("#{T(java.util.Arrays).asList('${mosip.registration.processor.reprocessor.exclude-stage-names:PacketReceiverStage}')}") - private List reprocessExcludeStageNames; - - /** The is transaction successful. */ - boolean isTransactionSuccessful; - - /** The registration status service. */ - @Autowired - RegistrationStatusService registrationStatusService; - - /** The core audit request builder. */ - @Autowired - AuditLogRequestBuilder auditLogRequestBuilder; - - /** Mosip router for APIs */ - @Autowired - MosipRouter router; - - /** The port. */ - @Value("${server.port}") - private String port; - - /** - * Deploy verticle. - */ - public void deployVerticle() { - mosipEventBus = this.getEventBus(this, clusterManagerUrl); - deployScheduler(getVertx()); - - } - - /** - * This method deploys the chime scheduler - * - * @param vertx - * the vertx - */ - private void deployScheduler(Vertx vertx) { - vertx.deployVerticle(ReprocessorConstants.CEYLON_SCHEDULER, this::schedulerResult); - } - - public void schedulerResult(AsyncResult res) { - if (res.succeeded()) { - regProcLogger.info("ReprocessorVerticle::schedular()::deployed"); - cronScheduling(vertx); - } else { - regProcLogger.error("ReprocessorVerticle::schedular()::deployment failure " + res.cause().getMessage()); - } - } - - /** - * This method does the cron scheduling by fetchin cron expression from config - * server - * - * @param vertx - * the vertx - */ - private void cronScheduling(Vertx vertx) { - - EventBus eventBus = vertx.eventBus(); - // listen the timer events - eventBus.consumer((ReprocessorConstants.TIMER_EVENT), message -> { - - process(new MessageDTO()); - }); - - // description of timers - JsonObject timer = (new JsonObject()) - .put(ReprocessorConstants.TYPE, environment.getProperty(ReprocessorConstants.TYPE_VALUE)) - .put(ReprocessorConstants.SECONDS, environment.getProperty(ReprocessorConstants.SECONDS_VALUE)) - .put(ReprocessorConstants.MINUTES, environment.getProperty(ReprocessorConstants.MINUTES_VALUE)) - .put(ReprocessorConstants.HOURS, environment.getProperty(ReprocessorConstants.HOURS_VALUE)) - .put(ReprocessorConstants.DAY_OF_MONTH, - environment.getProperty(ReprocessorConstants.DAY_OF_MONTH_VALUE)) - .put(ReprocessorConstants.MONTHS, environment.getProperty(ReprocessorConstants.MONTHS_VALUE)) - .put(ReprocessorConstants.DAYS_OF_WEEK, - environment.getProperty(ReprocessorConstants.DAYS_OF_WEEK_VALUE)); - - // create scheduler - eventBus.send(ReprocessorConstants.CHIME, - (new JsonObject()).put(ReprocessorConstants.OPERATION, ReprocessorConstants.OPERATION_VALUE) - .put(ReprocessorConstants.NAME, ReprocessorConstants.NAME_VALUE) - .put(ReprocessorConstants.DESCRIPTION, timer), - ar -> { - if (ar.succeeded()) { - regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), - LoggerFileConstant.REGISTRATIONID.toString(), "", - "ReprocessorVerticle::schedular()::started"); - } else { - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), - LoggerFileConstant.REGISTRATIONID.toString(), "", - "ReprocessorVerticle::schedular()::failed " + ar.cause()); - vertx.close(); - } - }); - - } - - /** - * Send message. - * - * @param message - * the message - * @param toAddress - * the to address - */ - public void sendMessage(MessageDTO message, MessageBusAddress toAddress) { - this.send(this.mosipEventBus, toAddress, message); - } - - @Override - public void start() { - router.setRoute(this.postUrl(getVertx(), null, null)); - this.createServer(router.getRouter(), Integer.parseInt(port)); - } - - /* - * (non-Javadoc) - * - * @see - * io.mosip.registration.processor.core.spi.eventbus.EventBusManager#process( - * java.lang.Object) - */ - @Override - public MessageDTO process(MessageDTO object) { - List reprocessorDtoList = null; - LogDescription description = new LogDescription(); - List statusList = new ArrayList<>(); - statusList.add(RegistrationTransactionStatusCode.SUCCESS.toString()); - statusList.add(RegistrationTransactionStatusCode.REPROCESS.toString()); - statusList.add(RegistrationTransactionStatusCode.IN_PROGRESS.toString()); - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), "", - "ReprocessorVerticle::process()::entry"); - StringBuffer ridSb=new StringBuffer(); - try { - reprocessorDtoList = registrationStatusService.getResumablePackets(fetchSize); - if (!CollectionUtils.isEmpty(reprocessorDtoList)) { - if (reprocessorDtoList.size() < fetchSize) { - List reprocessorPacketList = registrationStatusService.getUnProcessedPackets(fetchSize - reprocessorDtoList.size(), elapseTime, - reprocessCount, statusList, reprocessExcludeStageNames); - if (!CollectionUtils.isEmpty(reprocessorPacketList)) { - reprocessorDtoList.addAll(reprocessorPacketList); - } - } - } else { - reprocessorDtoList = registrationStatusService.getUnProcessedPackets(fetchSize, elapseTime, - reprocessCount, statusList, reprocessExcludeStageNames); - } - - - if (!CollectionUtils.isEmpty(reprocessorDtoList)) { - reprocessorDtoList.forEach(dto -> { - String registrationId = dto.getRegistrationId(); - ridSb.append(registrationId); - ridSb.append(","); - MessageDTO messageDTO = new MessageDTO(); - messageDTO.setRid(registrationId); - messageDTO.setReg_type(dto.getRegistrationType()); - messageDTO.setSource(dto.getSource()); - messageDTO.setIteration(dto.getIteration()); - messageDTO.setWorkflowInstanceId(dto.getWorkflowInstanceId()); - if (reprocessCount.equals(dto.getReProcessRetryCount())) { - dto.setLatestTransactionStatusCode( - RegistrationTransactionStatusCode.REPROCESS_FAILED.toString()); - dto.setLatestTransactionTypeCode( - RegistrationTransactionTypeCode.PACKET_REPROCESS.toString()); - dto.setStatusComment(StatusUtil.RE_PROCESS_FAILED.getMessage()); - dto.setStatusCode(RegistrationStatusCode.REPROCESS_FAILED.toString()); - dto.setSubStatusCode(StatusUtil.RE_PROCESS_FAILED.getCode()); - messageDTO.setIsValid(false); - description.setMessage(PlatformSuccessMessages.RPR_RE_PROCESS_FAILED.getMessage()); - description.setCode(PlatformSuccessMessages.RPR_RE_PROCESS_FAILED.getCode()); - - } else { - messageDTO.setIsValid(true); - isTransactionSuccessful = true; - String stageName = MessageBusUtil.getMessageBusAdress(dto.getRegistrationStageName()); - if (RegistrationTransactionStatusCode.SUCCESS.name() - .equalsIgnoreCase(dto.getLatestTransactionStatusCode())) { - stageName = stageName.concat(ReprocessorConstants.BUS_OUT); - } else { - stageName = stageName.concat(ReprocessorConstants.BUS_IN); - } - MessageBusAddress address = new MessageBusAddress(stageName); - sendMessage(messageDTO, address); - dto.setUpdatedBy(ReprocessorConstants.USER); - Integer reprocessRetryCount = dto.getReProcessRetryCount() != null - ? dto.getReProcessRetryCount() + 1 - : 1; - dto.setReProcessRetryCount(reprocessRetryCount); - dto.setLatestTransactionStatusCode(RegistrationTransactionStatusCode.REPROCESS.toString()); - dto.setLatestTransactionTypeCode( - RegistrationTransactionTypeCode.PACKET_REPROCESS.toString()); - dto.setStatusComment(StatusUtil.RE_PROCESS_COMPLETED.getMessage()); - dto.setSubStatusCode(StatusUtil.RE_PROCESS_COMPLETED.getCode()); - description.setMessage(PlatformSuccessMessages.RPR_SENT_TO_REPROCESS_SUCCESS.getMessage()); - description.setCode(PlatformSuccessMessages.RPR_SENT_TO_REPROCESS_SUCCESS.getCode()); - } - regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), - LoggerFileConstant.REGISTRATIONID.toString(), registrationId, description.getMessage()); - - /** Module-Id can be Both Success/Error code */ - String moduleId = PlatformSuccessMessages.RPR_SENT_TO_REPROCESS_SUCCESS.getCode(); - String moduleName = ModuleName.RE_PROCESSOR.toString(); - registrationStatusService.updateRegistrationStatusForWorkflowEngine(dto, moduleId, moduleName); - String eventId = EventId.RPR_402.toString(); - String eventName = EventName.UPDATE.toString(); - String eventType = EventType.BUSINESS.toString(); - - if (!isTransactionSuccessful) - auditLogRequestBuilder.createAuditRequestBuilder(description.getMessage(), eventId, eventName, - eventType, moduleId, moduleName, registrationId); - }); - - } - } catch (TablenotAccessibleException e) { - isTransactionSuccessful = false; - object.setInternalError(Boolean.TRUE); - 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() + " -- ", - PlatformErrorMessages.RPR_RGS_REGISTRATION_TABLE_NOT_ACCESSIBLE.getMessage(), e.toString()); - - }catch (Exception ex) { - isTransactionSuccessful = false; - description.setMessage(PlatformErrorMessages.REPROCESSOR_VERTICLE_FAILED.getMessage()); - description.setCode(PlatformErrorMessages.REPROCESSOR_VERTICLE_FAILED.getCode()); - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - description.getCode() + " -- ", - PlatformErrorMessages.REPROCESSOR_VERTICLE_FAILED.getMessage() + ex.getMessage() - + ExceptionUtils.getStackTrace(ex)); - object.setInternalError(Boolean.TRUE); - - } finally { - regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - null, description.getMessage()); - if (isTransactionSuccessful) - description.setMessage(PlatformSuccessMessages.RPR_RE_PROCESS_SUCCESS.getMessage()); - - String eventId = isTransactionSuccessful ? EventId.RPR_402.toString() : EventId.RPR_405.toString(); - String eventName = isTransactionSuccessful ? EventName.UPDATE.toString() : EventName.EXCEPTION.toString(); - String eventType = isTransactionSuccessful ? EventType.BUSINESS.toString() : EventType.SYSTEM.toString(); - - /** Module-Id can be Both Success/Error code */ - String moduleId = isTransactionSuccessful ? PlatformSuccessMessages.RPR_RE_PROCESS_SUCCESS.getCode() - : description.getCode(); - String moduleName = ModuleName.RE_PROCESSOR.toString(); - auditLogRequestBuilder.createAuditRequestBuilder(description.getMessage(), eventId, eventName, eventType, - moduleId, moduleName, (ridSb.toString().length()>1?ridSb.substring(0,ridSb.length()-1):"")); - } - - return object; - } - - - - @Override - protected String getPropertyPrefix() { - return VERTICLE_PROPERTY_PREFIX; - } -} +package io.mosip.registration.processor.reprocessor.verticle; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.apache.commons.lang3.exception.ExceptionUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Component; +import org.springframework.util.CollectionUtils; + +import io.mosip.kernel.core.logger.spi.Logger; +import io.mosip.registration.processor.core.abstractverticle.MessageBusAddress; +import io.mosip.registration.processor.core.abstractverticle.MessageDTO; +import io.mosip.registration.processor.core.abstractverticle.MosipEventBus; +import io.mosip.registration.processor.core.abstractverticle.MosipRouter; +import io.mosip.registration.processor.core.abstractverticle.MosipVerticleAPIManager; +import io.mosip.registration.processor.core.code.EventId; +import io.mosip.registration.processor.core.code.EventName; +import io.mosip.registration.processor.core.code.EventType; +import io.mosip.registration.processor.core.code.ModuleName; +import io.mosip.registration.processor.core.code.RegistrationTransactionStatusCode; +import io.mosip.registration.processor.core.code.RegistrationTransactionTypeCode; +import io.mosip.registration.processor.core.constant.LoggerFileConstant; +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.status.util.StatusUtil; +import io.mosip.registration.processor.core.util.MessageBusUtil; +import io.mosip.registration.processor.reprocessor.constants.ReprocessorConstants; +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.vertx.core.AsyncResult; +import io.vertx.core.Vertx; +import io.vertx.core.eventbus.EventBus; +import io.vertx.core.json.JsonObject; + +/** + * The Reprocessor Verticle to deploy the scheduler and implement re-processing + * logic + * + * @author Alok Ranjan + * @author Sowmya + * @author Pranav Kumar + * + * @since 0.10.0 + * + */ +@Component +public class ReprocessorVerticle extends MosipVerticleAPIManager { + + private static final String VERTICLE_PROPERTY_PREFIX = "mosip.regproc.reprocessor."; + + private static Logger regProcLogger = RegProcessorLogger.getLogger(ReprocessorVerticle.class); + + /** The cluster manager url. */ + @Value("${vertx.cluster.configuration}") + private String clusterManagerUrl; + + /** The environment. */ + @Autowired + Environment environment; + + /** The mosip event bus. */ + MosipEventBus mosipEventBus = null; + + /** The fetch size. */ + @Value("${registration.processor.reprocess.fetchsize}") + private Integer fetchSize; + + /** The elapse time. */ + @Value("${registration.processor.reprocess.elapse.time}") + private long elapseTime; + + /** The reprocess count. */ + @Value("${registration.processor.reprocess.attempt.count}") + private Integer reprocessCount; + + /** Comman seperated stage names that should be excluded while reprocessing. */ + @Value("#{T(java.util.Arrays).asList('${mosip.registration.processor.reprocessor.exclude-stage-names:PacketReceiverStage}')}") + private List reprocessExcludeStageNames; + + @Value("${registration.processor.reprocess.restart-from-stage}") + private String reprocessRestartFromStage; + + @Value("#{'${registration.processor.reprocess.restart-trigger-filter}'.split(',')}") + private List reprocessRestartTriggerFilter; + + /** The is transaction successful. */ + boolean isTransactionSuccessful; + + /** The registration status service. */ + @Autowired + RegistrationStatusService registrationStatusService; + + /** The core audit request builder. */ + @Autowired + AuditLogRequestBuilder auditLogRequestBuilder; + + /** Mosip router for APIs */ + @Autowired + MosipRouter router; + + /** The port. */ + @Value("${server.port}") + private String port; + + /** + * Deploy verticle. + */ + public void deployVerticle() { + mosipEventBus = this.getEventBus(this, clusterManagerUrl); + deployScheduler(getVertx()); + + } + + /** + * This method deploys the chime scheduler + * + * @param vertx + * the vertx + */ + private void deployScheduler(Vertx vertx) { + vertx.deployVerticle(ReprocessorConstants.CEYLON_SCHEDULER, this::schedulerResult); + } + + public void schedulerResult(AsyncResult res) { + if (res.succeeded()) { + regProcLogger.info("ReprocessorVerticle::schedular()::deployed"); + cronScheduling(vertx); + } else { + regProcLogger.error("ReprocessorVerticle::schedular()::deployment failure " + res.cause().getMessage()); + } + } + + /** + * This method does the cron scheduling by fetchin cron expression from config + * server + * + * @param vertx + * the vertx + */ + private void cronScheduling(Vertx vertx) { + + EventBus eventBus = vertx.eventBus(); + // listen the timer events + eventBus.consumer((ReprocessorConstants.TIMER_EVENT), message -> { + + process(new MessageDTO()); + }); + + // description of timers + JsonObject timer = (new JsonObject()) + .put(ReprocessorConstants.TYPE, environment.getProperty(ReprocessorConstants.TYPE_VALUE)) + .put(ReprocessorConstants.SECONDS, environment.getProperty(ReprocessorConstants.SECONDS_VALUE)) + .put(ReprocessorConstants.MINUTES, environment.getProperty(ReprocessorConstants.MINUTES_VALUE)) + .put(ReprocessorConstants.HOURS, environment.getProperty(ReprocessorConstants.HOURS_VALUE)) + .put(ReprocessorConstants.DAY_OF_MONTH, + environment.getProperty(ReprocessorConstants.DAY_OF_MONTH_VALUE)) + .put(ReprocessorConstants.MONTHS, environment.getProperty(ReprocessorConstants.MONTHS_VALUE)) + .put(ReprocessorConstants.DAYS_OF_WEEK, + environment.getProperty(ReprocessorConstants.DAYS_OF_WEEK_VALUE)); + + // create scheduler + eventBus.send(ReprocessorConstants.CHIME, + (new JsonObject()).put(ReprocessorConstants.OPERATION, ReprocessorConstants.OPERATION_VALUE) + .put(ReprocessorConstants.NAME, ReprocessorConstants.NAME_VALUE) + .put(ReprocessorConstants.DESCRIPTION, timer), + ar -> { + if (ar.succeeded()) { + regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString(), "", + "ReprocessorVerticle::schedular()::started"); + } else { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString(), "", + "ReprocessorVerticle::schedular()::failed " + ar.cause()); + vertx.close(); + } + }); + + } + + /** + * Send message. + * + * @param message + * the message + * @param toAddress + * the to address + */ + public void sendMessage(MessageDTO message, MessageBusAddress toAddress) { + this.send(this.mosipEventBus, toAddress, message); + } + + @Override + public void start() { + router.setRoute(this.postUrl(getVertx(), null, null)); + this.createServer(router.getRouter(), Integer.parseInt(port)); + } + + /* + * (non-Javadoc) + * + * @see + * io.mosip.registration.processor.core.spi.eventbus.EventBusManager#process( + * java.lang.Object) + */ + @Override + public MessageDTO process(MessageDTO object) { + List reprocessorDtoList = null; + LogDescription description = new LogDescription(); + List statusList = new ArrayList<>(); + statusList.add(RegistrationTransactionStatusCode.SUCCESS.toString()); + statusList.add(RegistrationTransactionStatusCode.REPROCESS.toString()); + statusList.add(RegistrationTransactionStatusCode.IN_PROGRESS.toString()); + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), "", + "ReprocessorVerticle::process()::entry"); + StringBuffer ridSb=new StringBuffer(); + try { + Map> reprocessRestartTriggerMap = intializeReprocessRestartTriggerMapping(); + reprocessorDtoList = registrationStatusService.getResumablePackets(fetchSize); + if (!CollectionUtils.isEmpty(reprocessorDtoList)) { + if (reprocessorDtoList.size() < fetchSize) { + List reprocessorPacketList = registrationStatusService.getUnProcessedPackets(fetchSize - reprocessorDtoList.size(), elapseTime, + reprocessCount, statusList, reprocessExcludeStageNames); + if (!CollectionUtils.isEmpty(reprocessorPacketList)) { + reprocessorDtoList.addAll(reprocessorPacketList); + } + } + } else { + reprocessorDtoList = registrationStatusService.getUnProcessedPackets(fetchSize, elapseTime, + reprocessCount, statusList, reprocessExcludeStageNames); + } + + + if (!CollectionUtils.isEmpty(reprocessorDtoList)) { + reprocessorDtoList.forEach(dto -> { + String registrationId = dto.getRegistrationId(); + ridSb.append(registrationId); + ridSb.append(","); + MessageDTO messageDTO = new MessageDTO(); + messageDTO.setRid(registrationId); + messageDTO.setReg_type(dto.getRegistrationType()); + messageDTO.setSource(dto.getSource()); + messageDTO.setIteration(dto.getIteration()); + messageDTO.setWorkflowInstanceId(dto.getWorkflowInstanceId()); + if (reprocessCount.equals(dto.getReProcessRetryCount())) { + dto.setLatestTransactionStatusCode( + RegistrationTransactionStatusCode.REPROCESS_FAILED.toString()); + dto.setLatestTransactionTypeCode( + RegistrationTransactionTypeCode.PACKET_REPROCESS.toString()); + dto.setStatusComment(StatusUtil.RE_PROCESS_FAILED.getMessage()); + dto.setStatusCode(RegistrationStatusCode.REPROCESS_FAILED.toString()); + dto.setSubStatusCode(StatusUtil.RE_PROCESS_FAILED.getCode()); + messageDTO.setIsValid(false); + description.setMessage(PlatformSuccessMessages.RPR_RE_PROCESS_FAILED.getMessage()); + description.setCode(PlatformSuccessMessages.RPR_RE_PROCESS_FAILED.getCode()); + + } else { + messageDTO.setIsValid(true); + isTransactionSuccessful = true; + String stageName; + if (isRestartFromStageRequired(dto, reprocessRestartTriggerMap)) { + stageName = MessageBusUtil.getMessageBusAdress(reprocessRestartFromStage); + stageName = stageName.concat(ReprocessorConstants.BUS_IN); + sendAndSetStatus(dto, messageDTO, stageName); + dto.setStatusComment(StatusUtil.RE_PROCESS_RESTART_FROM_STAGE.getMessage()); + dto.setSubStatusCode(StatusUtil.RE_PROCESS_RESTART_FROM_STAGE.getCode()); + description + .setMessage( + PlatformSuccessMessages.RPR_SENT_TO_REPROCESS_RESTART_FROM_STAGE_SUCCESS + .getMessage()); + description.setCode( + PlatformSuccessMessages.RPR_SENT_TO_REPROCESS_RESTART_FROM_STAGE_SUCCESS + .getCode()); + + } else { + stageName = MessageBusUtil.getMessageBusAdress(dto.getRegistrationStageName()); + if (RegistrationTransactionStatusCode.SUCCESS.name() + .equalsIgnoreCase(dto.getLatestTransactionStatusCode())) { + stageName = stageName.concat(ReprocessorConstants.BUS_OUT); + } else { + stageName = stageName.concat(ReprocessorConstants.BUS_IN); + } + sendAndSetStatus(dto, messageDTO, stageName); + dto.setStatusComment(StatusUtil.RE_PROCESS_COMPLETED.getMessage()); + dto.setSubStatusCode(StatusUtil.RE_PROCESS_COMPLETED.getCode()); + description.setMessage(PlatformSuccessMessages.RPR_SENT_TO_REPROCESS_SUCCESS.getMessage()); + description.setCode(PlatformSuccessMessages.RPR_SENT_TO_REPROCESS_SUCCESS.getCode()); + } + } + regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString(), registrationId, description.getMessage()); + + /** Module-Id can be Both Success/Error code */ + String moduleId = PlatformSuccessMessages.RPR_SENT_TO_REPROCESS_SUCCESS.getCode(); + String moduleName = ModuleName.RE_PROCESSOR.toString(); + registrationStatusService.updateRegistrationStatusForWorkflowEngine(dto, moduleId, moduleName); + String eventId = EventId.RPR_402.toString(); + String eventName = EventName.UPDATE.toString(); + String eventType = EventType.BUSINESS.toString(); + + if (!isTransactionSuccessful) + auditLogRequestBuilder.createAuditRequestBuilder(description.getMessage(), eventId, eventName, + eventType, moduleId, moduleName, registrationId); + }); + + } + } catch (TablenotAccessibleException e) { + isTransactionSuccessful = false; + object.setInternalError(Boolean.TRUE); + 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() + " -- ", + PlatformErrorMessages.RPR_RGS_REGISTRATION_TABLE_NOT_ACCESSIBLE.getMessage(), e.toString()); + + }catch (Exception ex) { + isTransactionSuccessful = false; + description.setMessage(PlatformErrorMessages.REPROCESSOR_VERTICLE_FAILED.getMessage()); + description.setCode(PlatformErrorMessages.REPROCESSOR_VERTICLE_FAILED.getCode()); + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + description.getCode() + " -- ", + PlatformErrorMessages.REPROCESSOR_VERTICLE_FAILED.getMessage() + ex.getMessage() + + ExceptionUtils.getStackTrace(ex)); + object.setInternalError(Boolean.TRUE); + + } finally { + regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + null, description.getMessage()); + if (isTransactionSuccessful) + description.setMessage(PlatformSuccessMessages.RPR_RE_PROCESS_SUCCESS.getMessage()); + + String eventId = isTransactionSuccessful ? EventId.RPR_402.toString() : EventId.RPR_405.toString(); + String eventName = isTransactionSuccessful ? EventName.UPDATE.toString() : EventName.EXCEPTION.toString(); + String eventType = isTransactionSuccessful ? EventType.BUSINESS.toString() : EventType.SYSTEM.toString(); + + /** Module-Id can be Both Success/Error code */ + String moduleId = isTransactionSuccessful ? PlatformSuccessMessages.RPR_RE_PROCESS_SUCCESS.getCode() + : description.getCode(); + String moduleName = ModuleName.RE_PROCESSOR.toString(); + auditLogRequestBuilder.createAuditRequestBuilder(description.getMessage(), eventId, eventName, eventType, + moduleId, moduleName, (ridSb.toString().length()>1?ridSb.substring(0,ridSb.length()-1):"")); + } + + return object; + } + + private Map> intializeReprocessRestartTriggerMapping() { + Map> reprocessRestartTriggerMap = new HashMap>(); + for (String filter : reprocessRestartTriggerFilter) { + String[] stageAndStatus = filter.split(":"); + String stageName = stageAndStatus[0]; + String latestTransactionStatusCode = stageAndStatus[1]; + Set latestTransactionStatusCodeSet; + if (reprocessRestartTriggerMap.containsKey(stageName)) { + latestTransactionStatusCodeSet = reprocessRestartTriggerMap.get(stageName); + if (latestTransactionStatusCodeSet.size() != 3) { + setReprocessRestartTriggerMap(reprocessRestartTriggerMap, stageName, latestTransactionStatusCode, + latestTransactionStatusCodeSet); + } + } else { + latestTransactionStatusCodeSet = new HashSet(); + setReprocessRestartTriggerMap(reprocessRestartTriggerMap, stageName, latestTransactionStatusCode, + latestTransactionStatusCodeSet); + } + } + return reprocessRestartTriggerMap; + + + } + + private void setReprocessRestartTriggerMap(Map> reprocessRestartTriggerMap, String stageName, + String latestTransactionStatusCode, Set latestTransactionStatusCodeSet) { + if (latestTransactionStatusCode.equalsIgnoreCase("*")) { + latestTransactionStatusCodeSet.add(RegistrationTransactionStatusCode.SUCCESS.toString()); + latestTransactionStatusCodeSet.add(RegistrationTransactionStatusCode.IN_PROGRESS.toString()); + latestTransactionStatusCodeSet.add(RegistrationTransactionStatusCode.REPROCESS.toString()); + } else { + latestTransactionStatusCodeSet.add(latestTransactionStatusCode.toUpperCase()); + } + reprocessRestartTriggerMap.put(stageName, latestTransactionStatusCodeSet); + } + + private boolean isRestartFromStageRequired(InternalRegistrationStatusDto dto, + Map> reprocessRestartTriggerMap) { + boolean isRestartFromStageRequired = false; + String stageName = dto.getRegistrationStageName(); + if (reprocessRestartTriggerMap.containsKey(stageName)) { + Set latestTransactionStatusCodes = reprocessRestartTriggerMap.get(stageName); + if (latestTransactionStatusCodes.contains(dto.getLatestTransactionStatusCode())) { + isRestartFromStageRequired = true; + } + } + return isRestartFromStageRequired; + } + + private void sendAndSetStatus(InternalRegistrationStatusDto dto, MessageDTO messageDTO, String stageName) { + MessageBusAddress address = new MessageBusAddress(stageName); + sendMessage(messageDTO, address); + dto.setUpdatedBy(ReprocessorConstants.USER); + Integer reprocessRetryCount = dto.getReProcessRetryCount() != null ? dto.getReProcessRetryCount() + 1 : 1; + dto.setReProcessRetryCount(reprocessRetryCount); + dto.setLatestTransactionStatusCode(RegistrationTransactionStatusCode.REPROCESS.toString()); + dto.setLatestTransactionTypeCode(RegistrationTransactionTypeCode.PACKET_REPROCESS.toString()); + } + + + + @Override + protected String getPropertyPrefix() { + return VERTICLE_PROPERTY_PREFIX; + } +} diff --git a/registration-processor/workflow-engine/registration-processor-reprocessor/src/test/java/io/mosip/registration/processor/reprocessor/verticle/ReprocessorVerticleTest.java b/registration-processor/workflow-engine/registration-processor-reprocessor/src/test/java/io/mosip/registration/processor/reprocessor/verticle/ReprocessorVerticleTest.java index cb182bf77db..b028d511454 100644 --- a/registration-processor/workflow-engine/registration-processor-reprocessor/src/test/java/io/mosip/registration/processor/reprocessor/verticle/ReprocessorVerticleTest.java +++ b/registration-processor/workflow-engine/registration-processor-reprocessor/src/test/java/io/mosip/registration/processor/reprocessor/verticle/ReprocessorVerticleTest.java @@ -38,6 +38,7 @@ import io.mosip.registration.processor.core.spi.restclient.RegistrationProcessorRestClientService; 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.code.RegistrationStatusCode; import io.mosip.registration.processor.status.code.RegistrationType; import io.mosip.registration.processor.status.dto.InternalRegistrationStatusDto; import io.mosip.registration.processor.status.dto.RegistrationStatusDto; @@ -120,6 +121,16 @@ public void setup() throws Exception { ReflectionTestUtils.setField(reprocessorVerticle, "elapseTime", 21600); ReflectionTestUtils.setField(reprocessorVerticle, "reprocessCount", 3); ReflectionTestUtils.setField(reprocessorVerticle, "reprocessExcludeStageNames", new ArrayList<>()); + List reprocessRestartTriggerFilterList = new ArrayList<>(); + reprocessRestartTriggerFilterList.add("DemodedupStage:Success"); + reprocessRestartTriggerFilterList.add("BioDedupeStage:*"); + reprocessRestartTriggerFilterList.add("UinGeneratorStage:reprocess"); + reprocessRestartTriggerFilterList.add("BioDedupeStage:reprocess"); + + ReflectionTestUtils.setField(reprocessorVerticle, "reprocessRestartTriggerFilter", + reprocessRestartTriggerFilterList); + ReflectionTestUtils.setField(reprocessorVerticle, "reprocessRestartFromStage", + "SecurezoneNotificationStage"); Field auditLog = AuditLogRequestBuilder.class.getDeclaredField("registrationProcessorRestService"); auditLog.setAccessible(true); @SuppressWarnings("unchecked") @@ -259,4 +270,27 @@ public void testProcessValidWithResumablePackets() throws TablenotAccessibleExce reprocessorVerticle.process(dto); } + + @Test + public void testProcessWithRestartFromStage() throws TablenotAccessibleException, + PacketManagerException, + ApisResourceAccessException, WorkflowActionException { + + List dtolist = new ArrayList<>(); + InternalRegistrationStatusDto registrationStatusDto = new InternalRegistrationStatusDto(); + + registrationStatusDto.setRegistrationId("2018701130000410092018110735"); + registrationStatusDto.setRegistrationType(RegistrationType.NEW.toString()); + registrationStatusDto.setRegistrationStageName("BioDedupeStage"); + registrationStatusDto.setReProcessRetryCount(0); + registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); + registrationStatusDto.setLatestTransactionStatusCode(RegistrationTransactionStatusCode.REPROCESS.toString()); + dtolist.add(registrationStatusDto); + Mockito.when( + registrationStatusService.getUnProcessedPackets(anyInt(), anyLong(), anyInt(), anyList(), anyList())) + .thenReturn(dtolist); + reprocessorVerticle.process(dto); + + } + } From f7e38a4d4d0f766cdedc6e9caae8618120cc2ba4 Mon Sep 17 00:00:00 2001 From: Sowmya Ujjappa Banakar <43202851+sowmya695@users.noreply.github.com> Date: Mon, 8 Jan 2024 15:04:55 +0530 Subject: [PATCH 110/133] MOSIP-28185 Code fix for notification (#1782) (#1787) * MOSIP-28185 Code fix for notification (#1782) Co-authored-by: Sowmya Ujjappa Banakar Signed-off-by: Sowmya Ujjappa Banakar * MOSIP-28185 registration confirmation notification corrected (#1789) * MOSIP-28185 registration confirmation notification corrected Signed-off-by: Sowmya Ujjappa Banakar * MOSIP-28185 code fix for packet validator Signed-off-by: Sowmya Ujjappa Banakar --------- Signed-off-by: Sowmya Ujjappa Banakar Signed-off-by: Sowmya Ujjappa Banakar Co-authored-by: Sowmya Ujjappa Banakar Co-authored-by: Sowmya Ujjappa Banakar --------- Signed-off-by: Sowmya Ujjappa Banakar Signed-off-by: Sowmya Ujjappa Banakar Co-authored-by: Sowmya Ujjappa Banakar Co-authored-by: Sowmya Ujjappa Banakar --- .../stages/utils/NotificationUtility.java | 11 +++++--- .../impl/MessageNotificationServiceImpl.java | 26 ++++++++++++------- 2 files changed, 25 insertions(+), 12 deletions(-) diff --git a/registration-processor/pre-processor/registration-processor-packet-validator-stage/src/main/java/io/mosip/registration/processor/stages/utils/NotificationUtility.java b/registration-processor/pre-processor/registration-processor-packet-validator-stage/src/main/java/io/mosip/registration/processor/stages/utils/NotificationUtility.java index e3c63542a05..92881b9ea38 100644 --- a/registration-processor/pre-processor/registration-processor-packet-validator-stage/src/main/java/io/mosip/registration/processor/stages/utils/NotificationUtility.java +++ b/registration-processor/pre-processor/registration-processor-packet-validator-stage/src/main/java/io/mosip/registration/processor/stages/utils/NotificationUtility.java @@ -155,13 +155,18 @@ public void sendNotification(RegistrationAdditionalInfoDTO registrationAdditiona String nameField = JsonUtil.getJSONValue( JsonUtil.getJSONObject(regProcessorIdentityJson, MappingJsonConstants.NAME), MappingJsonConstants.VALUE); + String[] nameArray = nameField.toString().split(","); for(String preferredLanguage:preferredLanguages) { if (registrationAdditionalInfoDTO.getName() != null) { - attributes.put(nameField , registrationAdditionalInfoDTO.getName()); + attributes.put(nameArray[0] + "_" + preferredLanguage, registrationAdditionalInfoDTO.getName()); } else { - attributes.put(nameField, ""); + attributes.put(nameArray[0] + "_" + preferredLanguage, ""); + } + if (nameArray.length > 1) { + for (int i = 1; i < nameArray.length; i++) { + attributes.put(nameArray[i] + "_" + preferredLanguage, ""); + } } - if (isProcessingSuccess) { type = setNotificationTemplateType(registrationStatusDto, type); } else if (!isValidSupervisorStatus) { 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 36413df5774..17df50c9917 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 @@ -7,6 +7,7 @@ import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; +import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; @@ -74,7 +75,6 @@ import io.mosip.registration.processor.message.sender.exception.TemplateNotFoundException; import io.mosip.registration.processor.message.sender.template.TemplateGenerator; import io.mosip.registration.processor.packet.manager.decryptor.Decryptor; -import io.mosip.registration.processor.packet.storage.dto.ConfigEnum; import io.mosip.registration.processor.packet.storage.exception.IdRepoAppException; import io.mosip.registration.processor.packet.storage.utils.PriorityBasedPacketManagerService; import io.mosip.registration.processor.packet.storage.utils.Utilities; @@ -560,7 +560,7 @@ private Map setAttributes(String idJsonString, Map setAttributesFromIdJson(String id, String process, M String regType, String lang, StringBuilder phoneNumber, StringBuilder emailId) throws IOException, ApisResourceAccessException, PacketManagerException, JsonProcessingException, JSONException, PacketDecryptionFailureException, JsonParseException, JsonMappingException, io.mosip.kernel.core.exception.IOException { - JSONObject mapperIdentity = utility.getRegistrationProcessorMappingJson(MappingJsonConstants.IDENTITY); - + if (mapperJsonKeys == null) { + String mapperJsonString = Utilities.getJson(utility.getConfigServerFileStorageURL(), + utility.getGetRegProcessorIdentityJson()); + JSONObject mapperJson = JsonUtil.objectMapperReadValue(mapperJsonString, JSONObject.class); + mapperIdentity = JsonUtil.getJSONObject(mapperJson, utility.getGetRegProcessorDemographicIdentity()); + mapperJsonKeys = new ArrayList<>(mapperIdentity.keySet()); + } List mapperJsonValues = new ArrayList<>(); - JsonUtil.getJSONValue(JsonUtil.getJSONObject(mapperIdentity, MappingJsonConstants.INDIVIDUAL_BIOMETRICS), VALUE); - mapperIdentity.keySet().forEach(key -> mapperJsonValues.add(JsonUtil.getJSONValue(JsonUtil.getJSONObject(mapperIdentity, key), VALUE))); - - String source = utility.getDefaultSource(process, ConfigEnum.READER); + for (String key : mapperJsonKeys) { + JSONObject jsonValue = JsonUtil.getJSONObject(mapperIdentity, key); + if (jsonValue.get(VALUE) != null && !jsonValue.get(VALUE).toString().isBlank()) { + String[] valueArray = jsonValue.get(VALUE).toString().split(","); + mapperJsonValues.addAll(new ArrayList(Arrays.asList(valueArray))); + } + } Map fieldMap =null; try { fieldMap = packetManagerService.getFields(id, mapperJsonValues, process, ProviderStageName.MESSAGE_SENDER); @@ -640,7 +648,7 @@ else if (json instanceof org.json.JSONArray) { Object obj = jsonArray.get(i); JsonValue jsonValue = mapper.readValue(obj.toString(), JsonValue.class); if(jsonValue.getLanguage().equalsIgnoreCase(lang)) { - attribute.putIfAbsent(e.getKey().toString(), jsonValue.getValue()); + attribute.putIfAbsent(e.getKey().toString() + "_" + lang, jsonValue.getValue()); } } } else From 257a30acb6fb4f72bc9f580e26f474d82af28167 Mon Sep 17 00:00:00 2001 From: Vishwa Date: Tue, 7 Nov 2023 11:01:51 +0530 Subject: [PATCH 111/133] [Mosip_29895]cherry pick develop from mosip_29896 Signed-off-by: khuddus shariff --- .../validator/PacketValidateProcessor.java | 37 ++++++++- .../PacketValidateProcessorTest.java | 83 +++++++++++++------ .../exception/util/PlatformErrorMessages.java | 10 +++ .../dto/InternalRegistrationStatusDto.java | 11 +++ .../entity/RegistrationStatusEntity.java | 12 +++ .../impl/RegistrationStatusServiceImpl.java | 2 + 6 files changed, 129 insertions(+), 26 deletions(-) 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 08aff65faf6..cc47a1bf95e 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 @@ -4,12 +4,16 @@ 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; @@ -166,6 +170,9 @@ public class PacketValidateProcessor { @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(); @@ -184,10 +191,9 @@ public MessageDTO process(MessageDTO object, String stageName) { "", "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); @@ -447,6 +453,33 @@ public MessageDTO process(MessageDTO object, String stageName) { } + + private void setPacketCreatedDateTime(InternalRegistrationStatusDto registrationStatusDto) throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { + try { + Map metaInfo = packetManagerService.getMetaInfo( + registrationStatusDto.getRefId(), 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)) { diff --git a/registration-processor/pre-processor/registration-processor-packet-validator-stage/src/test/java/io/mosip/registration/processor/stages/packet/validator/PacketValidateProcessorTest.java b/registration-processor/pre-processor/registration-processor-packet-validator-stage/src/test/java/io/mosip/registration/processor/stages/packet/validator/PacketValidateProcessorTest.java index 4b52a8820a2..264e8799ab6 100644 --- a/registration-processor/pre-processor/registration-processor-packet-validator-stage/src/test/java/io/mosip/registration/processor/stages/packet/validator/PacketValidateProcessorTest.java +++ b/registration-processor/pre-processor/registration-processor-packet-validator-stage/src/test/java/io/mosip/registration/processor/stages/packet/validator/PacketValidateProcessorTest.java @@ -42,13 +42,11 @@ import io.mosip.registration.processor.status.service.SyncRegistrationService; import org.apache.commons.io.IOUtils; import org.json.JSONException; +import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Matchers; -import org.mockito.Mock; -import org.mockito.Mockito; +import org.mockito.*; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; @@ -64,17 +62,19 @@ import java.io.IOException; import java.io.InputStream; import java.security.MessageDigest; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; + import static org.mockito.ArgumentMatchers.any; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.anyBoolean; +import static org.junit.Assert.*; /** @@ -127,6 +127,9 @@ public class PacketValidateProcessorTest { @Mock private NotificationUtility notificationUtility; + + @Mock + DateTimeFormatter dateTimeFormatter; private MessageDTO messageDTO; private String stageName; @@ -136,6 +139,7 @@ public class PacketValidateProcessorTest { @Before public void setup() throws Exception { ReflectionTestUtils.setField(packetValidateProcessor, "notificationTypes", "SMS|EMAIL"); + ReflectionTestUtils.setField(packetValidateProcessor, "dateformat", "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); messageDTO=new MessageDTO(); messageDTO.setRid("123456789"); messageDTO.setInternalError(false); @@ -245,43 +249,64 @@ public void setup() throws Exception { Map metamap = new HashMap<>(); org.json.JSONArray jsonArray = new org.json.JSONArray(); org.json.JSONObject jsonObject1 = new org.json.JSONObject(); + metamap.put(JsonConstant.CREATIONDATE,"2023-10-17T03:01:09.893"); + metamap.put("creationDate","2023-10-17T03:01:09.893Z"); jsonObject1.put("preRegistrationId", "12345"); jsonArray.put(0, jsonObject1); metamap.put(JsonConstant.METADATA, jsonArray.toString()); - Mockito.when(packetManagerService.getMetaInfo(anyString(), any(), any())).thenReturn(metamap); - + Mockito.when(packetManagerService.getMetaInfo(any(), any(), any())).thenReturn(metamap); Mockito.when(objectMapper.readValue(anyString(), any(Class.class))).thenReturn(new FieldValue("preRegistrationId", "12345")); + } - + @Test + public void PacketValidationSuccessTest() throws PacketManagerException, ApisResourceAccessException, IOException, JsonProcessingException { + Map metainfo1 = new HashMap<>(); + metainfo1.put(JsonConstant.CREATIONDATE,"2023-10-17T03:01:09.893"); + MessageDTO object = packetValidateProcessor.process(messageDTO, stageName); + ArgumentCaptor argument = ArgumentCaptor + .forClass(InternalRegistrationStatusDto.class); + Mockito.verify(registrationStatusService,Mockito.atLeastOnce()).updateRegistrationStatus(argument.capture(), Mockito.any(), + Mockito.any()); + Assert.assertEquals(LocalDateTime.parse(metainfo1.get(JsonConstant.CREATIONDATE)), argument.getAllValues().get(0).getPacketCreateDateTime()); + Assert.assertTrue(object.getIsValid()); + Assert.assertFalse(object.getInternalError()); } - + @Test - public void PacketValidationSuccessTest() { + public void PacketValidationSuccessTestwithPacketCreatedDateTimeNull() throws PacketManagerException, ApisResourceAccessException, IOException, JsonProcessingException { + Map metainfo = new HashMap<>(); + metainfo.put(JsonConstant.CREATIONDATE,null); + Mockito.when(packetManagerService.getMetaInfo(any(), any(), any())).thenReturn(metainfo); MessageDTO object = packetValidateProcessor.process(messageDTO, stageName); + ArgumentCaptor argument = ArgumentCaptor + .forClass(InternalRegistrationStatusDto.class); + Mockito.verify(registrationStatusService,Mockito.atLeastOnce()).updateRegistrationStatus(argument.capture(), Mockito.any(), + Mockito.any()); + assertEquals(metainfo.get(JsonConstant.CREATIONDATE), argument.getAllValues().get(0).getPacketCreateDateTime()); assertTrue(object.getIsValid()); assertFalse(object.getInternalError()); } - + @Test - public void PacketValidationFailureTest() throws PacketValidatorException, ApisResourceAccessException, JsonProcessingException, RegistrationProcessorCheckedException, IOException, PacketManagerException { - registrationStatusDto.setRetryCount(1); - Mockito.when(packetValidator.validate(any(), any(),any())).thenReturn(false); + public void PacketValidationSuccessTestwithPacketCreatedDateTimeInvalidFormat() throws PacketManagerException, ApisResourceAccessException, IOException, JsonProcessingException { + Map metainfo = new HashMap<>(); + metainfo.put(JsonConstant.CREATIONDATE,"2023-10-1703:01:09.893"); + Mockito.when(packetManagerService.getMetaInfo(any(), any(), any())).thenReturn(metainfo); MessageDTO object = packetValidateProcessor.process(messageDTO, stageName); - assertFalse(object.getIsValid()); - assertFalse(object.getInternalError()); + ArgumentCaptor argument = ArgumentCaptor + .forClass(InternalRegistrationStatusDto.class); + Mockito.verify(registrationStatusService,Mockito.atLeastOnce()).updateRegistrationStatus(argument.capture(),any(),any()); + assertEquals(null, argument.getAllValues().get(0).getPacketCreateDateTime()); } - + @Test - public void invalidSupervisorStatusTest() throws PacketValidatorException { + public void PacketValidationFailureTest() throws PacketValidatorException, ApisResourceAccessException, JsonProcessingException, RegistrationProcessorCheckedException, IOException, PacketManagerException { registrationStatusDto.setRetryCount(1); - regEntity=new SyncRegistrationEntity(); - regEntity.setSupervisorStatus("REJECTED"); - Mockito.when(syncRegistrationService.findByWorkflowInstanceId(any())).thenReturn(regEntity); + Mockito.when(packetValidator.validate(any(), any(),any())).thenReturn(false); MessageDTO object = packetValidateProcessor.process(messageDTO, stageName); assertFalse(object.getIsValid()); assertFalse(object.getInternalError()); } - @Test public void PacketValidationPacketManagerFailedTest() throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { @@ -293,7 +318,17 @@ public void PacketValidationPacketManagerFailedTest() assertTrue(object.getIsValid()); assertTrue(object.getInternalError()); } - + + @Test + public void invalidSupervisorStatusTest() throws PacketValidatorException { + registrationStatusDto.setRetryCount(1); + regEntity=new SyncRegistrationEntity(); + regEntity.setSupervisorStatus("REJECTED"); + Mockito.when(syncRegistrationService.findByWorkflowInstanceId(any())).thenReturn(regEntity); + MessageDTO object = packetValidateProcessor.process(messageDTO, stageName); + assertFalse(object.getIsValid()); + assertFalse(object.getInternalError()); + } @Test public void PacketValidationParsingFailedTest() throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { 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 92ef5f6ebac..78ce28d105a 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 @@ -411,6 +411,16 @@ public enum PlatformErrorMessages { 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"), diff --git a/registration-processor/registration-processor-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/dto/InternalRegistrationStatusDto.java b/registration-processor/registration-processor-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/dto/InternalRegistrationStatusDto.java index e045890f79c..5779b35f83f 100644 --- a/registration-processor/registration-processor-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/dto/InternalRegistrationStatusDto.java +++ b/registration-processor/registration-processor-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/dto/InternalRegistrationStatusDto.java @@ -48,6 +48,17 @@ public class InternalRegistrationStatusDto implements Serializable { /** The update date time. */ private LocalDateTime updateDateTime; + /** Packet Created Date and Time**/ + private LocalDateTime packetCreateDateTime; + + public LocalDateTime getPacketCreateDateTime() { + return packetCreateDateTime; + } + + public void setPacketCreateDateTime(LocalDateTime packetCreateDateTime) { + this.packetCreateDateTime = packetCreateDateTime; + } + /** The is deleted. */ private Boolean isDeleted; diff --git a/registration-processor/registration-processor-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/entity/RegistrationStatusEntity.java b/registration-processor/registration-processor-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/entity/RegistrationStatusEntity.java index c44c9eb35f4..0f40de4eaa2 100644 --- a/registration-processor/registration-processor-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/entity/RegistrationStatusEntity.java +++ b/registration-processor/registration-processor-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/entity/RegistrationStatusEntity.java @@ -67,6 +67,18 @@ public class RegistrationStatusEntity extends BaseRegistrationEntity Date: Tue, 28 Nov 2023 16:03:37 +0530 Subject: [PATCH 112/133] [Mosip_29895]cherry pick develop from mosip_29896 Signed-off-by: khuddus shariff --- .../validator/PacketValidateProcessor.java | 22 +++++++++---------- 1 file changed, 10 insertions(+), 12 deletions(-) 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 cc47a1bf95e..27b9b7d0e93 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 @@ -158,6 +158,8 @@ public class PacketValidateProcessor { 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; @@ -177,8 +179,6 @@ 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 @@ -204,10 +204,9 @@ public MessageDTO process(MessageDTO object, String stageName) { if (isValid) { // save audit details InternalRegistrationStatusDto finalRegistrationStatusDto = registrationStatusDto; - String finalRegistrationId = registrationId; Runnable r = () -> { try { - auditUtility.saveAuditDetails(finalRegistrationId, + auditUtility.saveAuditDetails(registrationId, finalRegistrationStatusDto.getRegistrationType()); } catch (Exception e) { regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), @@ -457,7 +456,7 @@ public MessageDTO process(MessageDTO object, String stageName) { private void setPacketCreatedDateTime(InternalRegistrationStatusDto registrationStatusDto) throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { try { Map metaInfo = packetManagerService.getMetaInfo( - registrationStatusDto.getRefId(), registrationStatusDto.getRegistrationType(), ProviderStageName.PACKET_VALIDATOR); + registrationStatusDto.getRegistrationId(), registrationStatusDto.getRegistrationType(), ProviderStageName.PACKET_VALIDATOR); DateTimeFormatter formatter = DateTimeFormatter.ofPattern(dateformat); String packetCreatedDateTime = metaInfo.get(JsonConstant.CREATIONDATE); if (packetCreatedDateTime != null && !packetCreatedDateTime.isEmpty()) { @@ -515,12 +514,12 @@ private void reverseDataSync(String id, String process, LogDescription descripti } } if (preRegId == null || preRegId.trim().isEmpty()) { - regProcLogger.info(LoggerFileConstant.REGISTRATIONID.toString(), id, + regProcLogger.info(LoggerFileConstant.REGISTRATIONID.toString(), registrationId, "Pre-registration id not present.", "Reverse datasync is not applicable for the registration id"); return; } - if (id != null) { + if (registrationId != null) { packetValidationDto.setTransactionSuccessful(false); MainResponseDTO mainResponseDto = null; if (preRegId != null && !preRegId.trim().isEmpty()) { @@ -532,14 +531,14 @@ private void reverseDataSync(String id, String process, LogDescription descripti reverseDataSyncRequestDto.setPreRegistrationIds(Arrays.asList(preRegId)); mainRequestDto.setRequest(reverseDataSyncRequestDto); regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), - LoggerFileConstant.REGISTRATIONID.toString(), id, + 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(), id, + LoggerFileConstant.REGISTRATIONID.toString(), registrationId, "\"PacketValidateProcessor::reverseDataSync()::ReverseDataSync Api call ended with response data : " + JsonUtil.objectMapperObjectToJson(mainResponseDto)); packetValidationDto.setTransactionSuccessful(true); @@ -547,7 +546,7 @@ private void reverseDataSync(String id, String process, LogDescription descripti } if (mainResponseDto != null && mainResponseDto.getErrors() != null && mainResponseDto.getErrors().size() > 0) { - regProcLogger.error(LoggerFileConstant.REGISTRATIONID.toString(), id, + regProcLogger.error(LoggerFileConstant.REGISTRATIONID.toString(), registrationId, PlatformErrorMessages.REVERSE_DATA_SYNC_FAILED.getMessage(), mainResponseDto.getErrors().toString()); packetValidationDto.setTransactionSuccessful(false); @@ -559,7 +558,7 @@ private void reverseDataSync(String id, String process, LogDescription descripti + " null response from rest client "); } else { packetValidationDto.setTransactionSuccessful(true); - regProcLogger.info(LoggerFileConstant.REGISTRATIONID.toString(), id, + regProcLogger.info(LoggerFileConstant.REGISTRATIONID.toString(), registrationId, PlatformSuccessMessages.REVERSE_DATA_SYNC_SUCCESS.getMessage(), ""); } @@ -581,7 +580,6 @@ private void updateErrorFlags(InternalRegistrationStatusDto registrationStatusDt 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; From ea41e99712b3e1986ff47e52259338c14c36f0cb Mon Sep 17 00:00:00 2001 From: khuddus shariff Date: Tue, 9 Jan 2024 13:07:33 +0530 Subject: [PATCH 113/133] [Mosip_29895]cherry pick develop from mosip_29896 Signed-off-by: khuddus shariff --- .../packet/validator/PacketValidateProcessor.java | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) 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 27b9b7d0e93..9dd37cd573d 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 @@ -514,12 +514,12 @@ private void reverseDataSync(String id, String process, LogDescription descripti } } if (preRegId == null || preRegId.trim().isEmpty()) { - regProcLogger.info(LoggerFileConstant.REGISTRATIONID.toString(), registrationId, + regProcLogger.info(LoggerFileConstant.REGISTRATIONID.toString(), id, "Pre-registration id not present.", "Reverse datasync is not applicable for the registration id"); return; } - if (registrationId != null) { + if (id != null) { packetValidationDto.setTransactionSuccessful(false); MainResponseDTO mainResponseDto = null; if (preRegId != null && !preRegId.trim().isEmpty()) { @@ -531,14 +531,14 @@ private void reverseDataSync(String id, String process, LogDescription descripti reverseDataSyncRequestDto.setPreRegistrationIds(Arrays.asList(preRegId)); mainRequestDto.setRequest(reverseDataSyncRequestDto); regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), - LoggerFileConstant.REGISTRATIONID.toString(), registrationId, + 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(), registrationId, + LoggerFileConstant.REGISTRATIONID.toString(), id, "\"PacketValidateProcessor::reverseDataSync()::ReverseDataSync Api call ended with response data : " + JsonUtil.objectMapperObjectToJson(mainResponseDto)); packetValidationDto.setTransactionSuccessful(true); @@ -546,7 +546,7 @@ private void reverseDataSync(String id, String process, LogDescription descripti } if (mainResponseDto != null && mainResponseDto.getErrors() != null && mainResponseDto.getErrors().size() > 0) { - regProcLogger.error(LoggerFileConstant.REGISTRATIONID.toString(), registrationId, + regProcLogger.error(LoggerFileConstant.REGISTRATIONID.toString(), id, PlatformErrorMessages.REVERSE_DATA_SYNC_FAILED.getMessage(), mainResponseDto.getErrors().toString()); packetValidationDto.setTransactionSuccessful(false); @@ -558,7 +558,7 @@ private void reverseDataSync(String id, String process, LogDescription descripti + " null response from rest client "); } else { packetValidationDto.setTransactionSuccessful(true); - regProcLogger.info(LoggerFileConstant.REGISTRATIONID.toString(), registrationId, + regProcLogger.info(LoggerFileConstant.REGISTRATIONID.toString(), id, PlatformSuccessMessages.REVERSE_DATA_SYNC_SUCCESS.getMessage(), ""); } From 2cb1d4c73054f2f1e4c6ecb9558b6f4dac52daf0 Mon Sep 17 00:00:00 2001 From: khuddus shariff Date: Tue, 9 Jan 2024 13:52:44 +0530 Subject: [PATCH 114/133] [Mosip_29895]cherry pick develop from mosip_29896 Signed-off-by: khuddus shariff --- .../stages/packet/validator/PacketValidateProcessor.java | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) 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 9dd37cd573d..89ff3c5d92a 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 @@ -201,12 +201,14 @@ public MessageDTO process(MessageDTO object, String stageName) { if (isValidSupervisorStatus) { Boolean isValid = compositePacketValidator.validate(object.getRid(), registrationStatusDto.getRegistrationType(), packetValidationDto); + if (isValid) { // save audit details InternalRegistrationStatusDto finalRegistrationStatusDto = registrationStatusDto; Runnable r = () -> { + String finalRegistrationId = registrationId; try { - auditUtility.saveAuditDetails(registrationId, + auditUtility.saveAuditDetails(finalRegistrationId, finalRegistrationStatusDto.getRegistrationType()); } catch (Exception e) { regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), @@ -580,6 +582,7 @@ private void updateErrorFlags(InternalRegistrationStatusDto registrationStatusDt 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; From 1d571717496c068a5f2512564e164d3f4b851d01 Mon Sep 17 00:00:00 2001 From: khuddus shariff Date: Tue, 9 Jan 2024 13:54:54 +0530 Subject: [PATCH 115/133] [Mosip_29895]cherry pick develop from mosip_29896 Signed-off-by: khuddus shariff --- .../stages/packet/validator/PacketValidateProcessor.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 89ff3c5d92a..379f9e6578e 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 @@ -205,8 +205,8 @@ public MessageDTO process(MessageDTO object, String stageName) { if (isValid) { // save audit details InternalRegistrationStatusDto finalRegistrationStatusDto = registrationStatusDto; + String finalRegistrationId = registrationId; Runnable r = () -> { - String finalRegistrationId = registrationId; try { auditUtility.saveAuditDetails(finalRegistrationId, finalRegistrationStatusDto.getRegistrationType()); From 295dc1c74a980e485f5a4344dfdc967987937c87 Mon Sep 17 00:00:00 2001 From: khuddus shariff Date: Tue, 9 Jan 2024 14:06:57 +0530 Subject: [PATCH 116/133] [Mosip_29895]cherry pick develop from mosip_29896 Signed-off-by: khuddus shariff --- .../stages/packet/validator/PacketValidateProcessor.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) 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 379f9e6578e..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 @@ -158,7 +158,7 @@ public class PacketValidateProcessor { 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; @@ -179,6 +179,7 @@ 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 From 271aebb2d2f0f5eb0145a51e5099d7d2784b5563 Mon Sep 17 00:00:00 2001 From: Sowmya Ujjappa Banakar <43202851+sowmya695@users.noreply.github.com> Date: Wed, 10 Jan 2024 11:20:05 +0530 Subject: [PATCH 117/133] MOSIP-31016 code changes (#1824) Signed-off-by: Sowmya Ujjappa Banakar Co-authored-by: Sowmya Ujjappa Banakar --- pom.xml | 162 --------------------------------- registration-processor/pom.xml | 9 +- 2 files changed, 1 insertion(+), 170 deletions(-) diff --git a/pom.xml b/pom.xml index 6b44f7c6668..e69de29bb2d 100644 --- a/pom.xml +++ b/pom.xml @@ -1,162 +0,0 @@ - - - - 4.0.0 - io.mosip - registration - 1.2.0.1-SNAPSHOT - pom - - MOSIP Registration Parent POM - Mosip Registration Project - https://github.com/mosip/registration - - - MPL 2.0 - https://www.mozilla.org/en-US/MPL/2.0/ - - - - scm:git:git://github.com/mosip/registration.git - scm:git:ssh://github.com:mosip/registration.git - https://github.com/mosip/registration - HEAD - - - - Mosip - mosip.emailnotifier@gmail.com - io.mosip - https://github.com/mosip/registration - - - - - - ossrh - Central Repository - https://oss.sonatype.org/content/repositories/snapshots - default - - true - - - - central - Maven Central - 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/ - - - - - - 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 - - - - - org.apache.maven.plugins - maven-gpg-plugin - 1.5 - - - sign-artifacts - verify - - sign - - - - --pinentry-mode - loopback - - - - - - - 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 - - - - - - - - - registration-processor - - diff --git a/registration-processor/pom.xml b/registration-processor/pom.xml index 0cc02dad78e..72b79796186 100644 --- a/registration-processor/pom.xml +++ b/registration-processor/pom.xml @@ -1,13 +1,6 @@ 4.0.0 - - - io.mosip - registration - 1.2.0.1-SNAPSHOT - - MPL 2.0 @@ -336,7 +329,7 @@ powermock-core 2.0.7 test - + javax.xml.bind jaxb-api From 6a544b7e096b7f61203feca7789fee820ba070f4 Mon Sep 17 00:00:00 2001 From: Sowmya Ujjappa Banakar Date: Thu, 11 Jan 2024 12:31:49 +0530 Subject: [PATCH 118/133] MOSIP-31016 pom removed as its added as empty in cherry pick with conflicts resolving Signed-off-by: Sowmya Ujjappa Banakar --- pom.xml | 0 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 pom.xml diff --git a/pom.xml b/pom.xml deleted file mode 100644 index e69de29bb2d..00000000000 From 7b019f91b2c27c3b500e351ce35f06992c121389 Mon Sep 17 00:00:00 2001 From: techno-467 Date: Thu, 11 Jan 2024 12:44:51 +0530 Subject: [PATCH 119/133] [DSD-3932] updated snapshot url in release-1.2.0.1 branch Signed-off-by: techno-467 --- .github/workflows/push-trigger.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/push-trigger.yml b/.github/workflows/push-trigger.yml index 876c4757fac..326df0539bb 100644 --- a/.github/workflows/push-trigger.yml +++ b/.github/workflows/push-trigger.yml @@ -43,7 +43,7 @@ jobs: secrets: OSSRH_USER: ${{ secrets.OSSRH_USER }} OSSRH_SECRET: ${{ secrets.OSSRH_SECRET }} - OSSRH_URL: ${{ secrets.RELEASE_URL }} + OSSRH_URL: ${{ secrets.OSSRH_SNAPSHOT_URL }} OSSRH_TOKEN: ${{ secrets.OSSRH_TOKEN }} GPG_SECRET: ${{ secrets.GPG_SECRET }} SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK }} @@ -128,4 +128,4 @@ jobs: OSSRH_SECRET: ${{ secrets.OSSRH_SECRET }} OSSRH_TOKEN: ${{ secrets.OSSRH_TOKEN }} GPG_SECRET: ${{ secrets.GPG_SECRET }} - SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK }} \ No newline at end of file + SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK }} From 6dc966f6d4a5cff9ef5702dcef5277fbea730d01 Mon Sep 17 00:00:00 2001 From: Praful Rakhade <99539100+Prafulrakhade@users.noreply.github.com> Date: Wed, 17 Jan 2024 17:55:15 +0530 Subject: [PATCH 120/133] Rename 1.2.0.1-B2_to_1.2.0.1_rollback.sql to 1.2.0.1-B2_to_1.2.0.1-B3_rollback.sql Signed-off-by: Praful Rakhade <99539100+Prafulrakhade@users.noreply.github.com> --- ...2.0.1_rollback.sql => 1.2.0.1-B2_to_1.2.0.1-B3_rollback.sql} | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename db_upgrade_scripts/mosip_regprc/sql/{1.2.0.1-B2_to_1.2.0.1_rollback.sql => 1.2.0.1-B2_to_1.2.0.1-B3_rollback.sql} (68%) diff --git a/db_upgrade_scripts/mosip_regprc/sql/1.2.0.1-B2_to_1.2.0.1_rollback.sql b/db_upgrade_scripts/mosip_regprc/sql/1.2.0.1-B2_to_1.2.0.1-B3_rollback.sql similarity index 68% rename from db_upgrade_scripts/mosip_regprc/sql/1.2.0.1-B2_to_1.2.0.1_rollback.sql rename to db_upgrade_scripts/mosip_regprc/sql/1.2.0.1-B2_to_1.2.0.1-B3_rollback.sql index 381e2be11c1..5548b94e9cb 100644 --- a/db_upgrade_scripts/mosip_regprc/sql/1.2.0.1-B2_to_1.2.0.1_rollback.sql +++ b/db_upgrade_scripts/mosip_regprc/sql/1.2.0.1-B2_to_1.2.0.1-B3_rollback.sql @@ -1 +1 @@ -\echo 'Upgrade Queries not required for transition from $CURRENT_VERSION to $UPGRADE_VERSION' \ No newline at end of file +\echo 'Upgrade Queries not required for transition from $CURRENT_VERSION to $UPGRADE_VERSION' From 9038944b00b6308e4681f5084afc8a99c6996255 Mon Sep 17 00:00:00 2001 From: Praful Rakhade <99539100+Prafulrakhade@users.noreply.github.com> Date: Wed, 17 Jan 2024 17:55:39 +0530 Subject: [PATCH 121/133] Rename 1.2.0.1-B2_to_1.2.0.1_upgrade.sql to 1.2.0.1-B2_to_1.2.0.1-B3_upgrade.sql Signed-off-by: Praful Rakhade <99539100+Prafulrakhade@users.noreply.github.com> --- ...o_1.2.0.1_upgrade.sql => 1.2.0.1-B2_to_1.2.0.1-B3_upgrade.sql} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename db_upgrade_scripts/mosip_regprc/sql/{1.2.0.1-B2_to_1.2.0.1_upgrade.sql => 1.2.0.1-B2_to_1.2.0.1-B3_upgrade.sql} (100%) diff --git a/db_upgrade_scripts/mosip_regprc/sql/1.2.0.1-B2_to_1.2.0.1_upgrade.sql b/db_upgrade_scripts/mosip_regprc/sql/1.2.0.1-B2_to_1.2.0.1-B3_upgrade.sql similarity index 100% rename from db_upgrade_scripts/mosip_regprc/sql/1.2.0.1-B2_to_1.2.0.1_upgrade.sql rename to db_upgrade_scripts/mosip_regprc/sql/1.2.0.1-B2_to_1.2.0.1-B3_upgrade.sql From 92a09743ee6fadfcd6d08f7633d79ef5c65f4689 Mon Sep 17 00:00:00 2001 From: Sowmya Ujjappa Banakar <43202851+sowmya695@users.noreply.github.com> Date: Wed, 24 Jan 2024 11:35:45 +0530 Subject: [PATCH 122/133] Merge pull request #1788 from sowmya695/MOSIP-29780_develop (#1836) Mosip 29780 develop Signed-off-by: Sowmya Ujjappa Banakar Co-authored-by: Vishwa --- .../stage/BiometricExtractionStage.java | 44 +- .../test/BiometricExtractionStageTest.java | 25 + .../finalization/stage/FinalizationStage.java | 23 +- .../stage/tests/FinalizationStageTest.java | 18 + .../uingenerator/stage/UinGeneratorStage.java | 2229 +++++++++-------- .../uigenerator/UinGeneratorStageTest.java | 71 +- .../code/RegistrationExceptionTypeCode.java | 5 +- .../core/status/util/StatusUtil.java | 17 +- .../util/RegistrationExceptionMapperUtil.java | 2 + .../IdrepoDraftReprocessableException.java | 10 + .../idreposervice/IdrepoDraftService.java | 268 +- .../impl/test/IdrepoDraftServiceTest.java | 434 ++-- 12 files changed, 1673 insertions(+), 1473 deletions(-) create mode 100644 registration-processor/registration-processor-packet-manager/src/main/java/io/mosip/registration/processor/packet/manager/exception/IdrepoDraftReprocessableException.java diff --git a/registration-processor/core-processor/registration-processor-biometric-extraction-stage/src/main/java/io/mosip/registration/processor/stages/biometric/extraction/stage/BiometricExtractionStage.java b/registration-processor/core-processor/registration-processor-biometric-extraction-stage/src/main/java/io/mosip/registration/processor/stages/biometric/extraction/stage/BiometricExtractionStage.java index bd355ca1600..893abfcee5a 100644 --- a/registration-processor/core-processor/registration-processor-biometric-extraction-stage/src/main/java/io/mosip/registration/processor/stages/biometric/extraction/stage/BiometricExtractionStage.java +++ b/registration-processor/core-processor/registration-processor-biometric-extraction-stage/src/main/java/io/mosip/registration/processor/stages/biometric/extraction/stage/BiometricExtractionStage.java @@ -4,8 +4,6 @@ import java.util.ArrayList; import java.util.List; -import javax.ws.rs.core.MediaType; - import org.apache.commons.lang3.exception.ExceptionUtils; import org.json.JSONArray; import org.json.JSONException; @@ -52,6 +50,7 @@ import io.mosip.registration.processor.core.util.RegistrationExceptionMapperUtil; import io.mosip.registration.processor.packet.manager.dto.IdResponseDTO; 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.IdrepoDraftService; import io.mosip.registration.processor.rest.client.audit.builder.AuditLogRequestBuilder; import io.mosip.registration.processor.status.code.RegistrationStatusCode; @@ -76,6 +75,7 @@ public class BiometricExtractionStage extends MosipVerticleAPIManager{ /** stage properties prefix */ private static final String STAGE_PROPERTY_PREFIX = "mosip.regproc.biometric.extraction."; private static final String USER = "MOSIP_SYSTEM"; + private static final String ID_REPO_KEY_MANAGER_ERROR = "IDR-IDS-003"; /** The mosip event bus. */ MosipEventBus mosipEventBus = null; @@ -267,14 +267,31 @@ public MessageDTO process(MessageDTO object) { RegistrationStatusCode.FAILED.toString() + e.getMessage() + ExceptionUtils.getStackTrace(e)); registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.name()); registrationStatusDto.setStatusComment( - trimExceptionMessage.trimExceptionMessage(StatusUtil.IDREPO_DRAFT_EXCEPTION.getMessage() + e.getMessage())); - registrationStatusDto.setSubStatusCode(StatusUtil.IDREPO_DRAFT_EXCEPTION.getCode()); + trimExceptionMessage.trimExceptionMessage( + StatusUtil.BIOMETRIC_EXTRACTION_IDREPO_DRAFT_EXCEPTION.getMessage() + e.getMessage())); + registrationStatusDto.setSubStatusCode(StatusUtil.BIOMETRIC_EXTRACTION_IDREPO_DRAFT_EXCEPTION.getCode()); registrationStatusDto.setLatestTransactionStatusCode( registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.IDREPO_DRAFT_EXCEPTION)); description.setMessage(PlatformErrorMessages.IDREPO_DRAFT_EXCEPTION.getMessage()); description.setCode(PlatformErrorMessages.IDREPO_DRAFT_EXCEPTION.getCode()); object.setInternalError(Boolean.TRUE); object.setRid(registrationStatusDto.getRegistrationId()); + } catch (IdrepoDraftReprocessableException e) { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + registrationId, + RegistrationStatusCode.PROCESSING.toString() + e.getMessage() + ExceptionUtils.getStackTrace(e)); + registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.name()); + registrationStatusDto.setStatusComment(trimExceptionMessage.trimExceptionMessage( + StatusUtil.BIOMETRIC_EXTRACTION_IDREPO_DRAFT_REPROCESSABLE_EXCEPTION.getMessage() + + e.getMessage())); + registrationStatusDto + .setSubStatusCode(StatusUtil.BIOMETRIC_EXTRACTION_IDREPO_DRAFT_REPROCESSABLE_EXCEPTION.getCode()); + registrationStatusDto.setLatestTransactionStatusCode(registrationStatusMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.IDREPO_DRAFT_REPROCESSABLE_EXCEPTION)); + description.setMessage(PlatformErrorMessages.IDREPO_DRAFT_EXCEPTION.getMessage()); + description.setCode(PlatformErrorMessages.IDREPO_DRAFT_EXCEPTION.getCode()); + object.setInternalError(Boolean.TRUE); + object.setRid(registrationStatusDto.getRegistrationId()); }catch (Exception ex) { registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.name()); registrationStatusDto.setStatusComment( @@ -323,13 +340,17 @@ public MessageDTO process(MessageDTO object) { /** * add biometric extractions to id repo + * * @param dto * @param registrationId * @throws ApisResourceAccessException - * @throws RegistrationProcessorCheckedException + * @throws IdrepoDraftReprocessableException + * @throws IdrepoDraftException + * */ private IdResponseDTO addBiometricExtractiontoIdRepository(ExtractorDto dto, - String registrationId) throws ApisResourceAccessException, RegistrationProcessorCheckedException { + String registrationId) + throws ApisResourceAccessException, IdrepoDraftReprocessableException, IdrepoDraftException { String extractionFormat = ""; if(dto.getBiometric().equals("iris")) { extractionFormat="irisExtractionFormat"; @@ -340,10 +361,15 @@ private IdResponseDTO addBiometricExtractiontoIdRepository(ExtractorDto dto, } List segments=List.of(registrationId); IdResponseDTO response= (IdResponseDTO) registrationProcessorRestClientService.putApi(ApiName.IDREPOEXTRACTBIOMETRICS, segments, extractionFormat, dto.getAttributeName(), null, IdResponseDTO.class, null); + if (response.getErrors() != null && !response.getErrors().isEmpty()) { - regProcLogger.error("Error occured while updating draft for id : " + registrationId, response.getErrors().iterator().next().toString()); - throw new RegistrationProcessorCheckedException(response.getErrors().iterator().next().getErrorCode(), - response.getErrors().iterator().next().getMessage()); + ErrorDTO error = response.getErrors().get(0); + regProcLogger.error("Error occured while updating draft for id : " + registrationId, error.toString()); + if (response.getErrors().get(0).getErrorCode().equalsIgnoreCase(ID_REPO_KEY_MANAGER_ERROR)) { + throw new IdrepoDraftReprocessableException(error.getErrorCode(), error.getMessage()); + } else { + throw new IdrepoDraftException(error.getErrorCode(), error.getMessage()); + } } return response; } 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 c0d91296e82..a39a44be7b5 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 @@ -10,6 +10,7 @@ import java.util.List; import org.apache.commons.io.IOUtils; +import org.assertj.core.util.Lists; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -35,6 +36,8 @@ 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.RegistrationType; import io.mosip.registration.processor.core.exception.ApisResourceAccessException; import io.mosip.registration.processor.core.http.ResponseWrapper; @@ -329,4 +332,26 @@ public void testBiometricExtractionDraftException() throws Exception { public void testDeployVerticle() { biometricExtractionStage.deployVerticle(); } + + @Test + public void testIdrepoDraftReprocessableException() throws Exception { + MessageDTO messageDTO = new MessageDTO(); + messageDTO.setRid("27847657360002520181210094052"); + messageDTO.setReg_type(RegistrationType.NEW.name()); + messageDTO.setWorkflowInstanceId("123er"); + messageDTO.setIteration(1); + when(registrationStatusMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.IDREPO_DRAFT_REPROCESSABLE_EXCEPTION)) + .thenReturn("REPROCESS"); + ErrorDTO errorDTO = new ErrorDTO(); + errorDTO.setMessage("Failed to either encrypt/decrypt message using Kernel Crypto Manager"); + errorDTO.setErrorCode("IDR-IDS-003"); + IdResponseDTO idResponseDTO1 = new IdResponseDTO(); + idResponseDTO1.setErrors(Lists.newArrayList(errorDTO)); + when(registrationProcessorRestClientService.putApi(any(), any(), anyString(), anyString(), any(), any(), any())) + .thenReturn(idResponseDTO1); + MessageDTO result = biometricExtractionStage.process(messageDTO); + assertTrue(result.getInternalError()); + assertTrue(result.getIsValid()); + } } diff --git a/registration-processor/core-processor/registration-processor-finalization-stage/src/main/java/io/mosip/registration/processor/stages/finalization/stage/FinalizationStage.java b/registration-processor/core-processor/registration-processor-finalization-stage/src/main/java/io/mosip/registration/processor/stages/finalization/stage/FinalizationStage.java index 38c81750354..c4236fde362 100644 --- a/registration-processor/core-processor/registration-processor-finalization-stage/src/main/java/io/mosip/registration/processor/stages/finalization/stage/FinalizationStage.java +++ b/registration-processor/core-processor/registration-processor-finalization-stage/src/main/java/io/mosip/registration/processor/stages/finalization/stage/FinalizationStage.java @@ -32,6 +32,7 @@ import io.mosip.registration.processor.core.util.RegistrationExceptionMapperUtil; import io.mosip.registration.processor.packet.manager.dto.IdResponseDTO; 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.IdrepoDraftService; import io.mosip.registration.processor.rest.client.audit.builder.AuditLogRequestBuilder; import io.mosip.registration.processor.status.code.RegistrationStatusCode; @@ -199,14 +200,32 @@ public MessageDTO process(MessageDTO object) { RegistrationStatusCode.FAILED.toString() + e.getMessage() + ExceptionUtils.getStackTrace(e)); registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.name()); registrationStatusDto.setStatusComment( - trimExceptionMessage.trimExceptionMessage(StatusUtil.IDREPO_DRAFT_EXCEPTION.getMessage() + e.getMessage())); - registrationStatusDto.setSubStatusCode(StatusUtil.IDREPO_DRAFT_EXCEPTION.getCode()); + trimExceptionMessage.trimExceptionMessage( + StatusUtil.FINALIZATION_IDREPO_DRAFT_EXCEPTION.getMessage() + e.getMessage())); + registrationStatusDto.setSubStatusCode(StatusUtil.FINALIZATION_IDREPO_DRAFT_EXCEPTION.getCode()); registrationStatusDto.setLatestTransactionStatusCode( registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.IDREPO_DRAFT_EXCEPTION)); description.setMessage(PlatformErrorMessages.IDREPO_DRAFT_EXCEPTION.getMessage()); description.setCode(PlatformErrorMessages.IDREPO_DRAFT_EXCEPTION.getCode()); object.setInternalError(Boolean.TRUE); object.setRid(registrationStatusDto.getRegistrationId()); + } catch (IdrepoDraftReprocessableException e) { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + registrationId, + RegistrationStatusCode.PROCESSING.toString() + e.getMessage() + ExceptionUtils.getStackTrace(e)); + registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.name()); + registrationStatusDto.setStatusComment(trimExceptionMessage + .trimExceptionMessage( + StatusUtil.FINALIZATION_IDREPO_DRAFT_REPROCESSABLE_EXCEPTION.getMessage() + + e.getMessage())); + registrationStatusDto + .setSubStatusCode(StatusUtil.FINALIZATION_IDREPO_DRAFT_REPROCESSABLE_EXCEPTION.getCode()); + registrationStatusDto.setLatestTransactionStatusCode(registrationStatusMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.IDREPO_DRAFT_REPROCESSABLE_EXCEPTION)); + description.setMessage(PlatformErrorMessages.IDREPO_DRAFT_EXCEPTION.getMessage()); + description.setCode(PlatformErrorMessages.IDREPO_DRAFT_EXCEPTION.getCode()); + object.setInternalError(Boolean.TRUE); + object.setRid(registrationStatusDto.getRegistrationId()); }catch (Exception ex) { registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.name()); registrationStatusDto.setStatusComment( diff --git a/registration-processor/core-processor/registration-processor-finalization-stage/src/test/java/io/mosip/registration/processor/stages/finalization/stage/tests/FinalizationStageTest.java b/registration-processor/core-processor/registration-processor-finalization-stage/src/test/java/io/mosip/registration/processor/stages/finalization/stage/tests/FinalizationStageTest.java index 5def776c4cd..f559b8ed629 100644 --- a/registration-processor/core-processor/registration-processor-finalization-stage/src/test/java/io/mosip/registration/processor/stages/finalization/stage/tests/FinalizationStageTest.java +++ b/registration-processor/core-processor/registration-processor-finalization-stage/src/test/java/io/mosip/registration/processor/stages/finalization/stage/tests/FinalizationStageTest.java @@ -29,6 +29,7 @@ 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.RegistrationType; import io.mosip.registration.processor.core.exception.ApisResourceAccessException; import io.mosip.registration.processor.core.http.ResponseWrapper; @@ -37,6 +38,7 @@ 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.IdrepoDraftService; import io.mosip.registration.processor.rest.client.audit.builder.AuditLogRequestBuilder; import io.mosip.registration.processor.rest.client.audit.dto.AuditResponseDto; @@ -247,4 +249,20 @@ public void testBiometricExtractionUnknownException() throws Exception { public void testDeployVerticle() { finalizationStage.deployVerticle(); } + + @Test + public void testIdrepoDraftReprocessableException() throws Exception { + MessageDTO messageDTO = new MessageDTO(); + messageDTO.setRid("27847657360002520181210094052"); + messageDTO.setReg_type(RegistrationType.NEW.name()); + messageDTO.setWorkflowInstanceId("123er"); + messageDTO.setIteration(1); + when(registrationStatusMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.IDREPO_DRAFT_REPROCESSABLE_EXCEPTION)) + .thenReturn("REPROCESS"); + when(idrepoDraftService.idrepoPublishDraft(anyString())).thenThrow(IdrepoDraftReprocessableException.class); + MessageDTO result = finalizationStage.process(messageDTO); + assertTrue(result.getInternalError()); + assertTrue(result.getIsValid()); + } } diff --git a/registration-processor/core-processor/registration-processor-uin-generator-stage/src/main/java/io/mosip/registration/processor/stages/uingenerator/stage/UinGeneratorStage.java b/registration-processor/core-processor/registration-processor-uin-generator-stage/src/main/java/io/mosip/registration/processor/stages/uingenerator/stage/UinGeneratorStage.java index e0fa2df1f34..5d5e8ac4421 100644 --- a/registration-processor/core-processor/registration-processor-uin-generator-stage/src/main/java/io/mosip/registration/processor/stages/uingenerator/stage/UinGeneratorStage.java +++ b/registration-processor/core-processor/registration-processor-uin-generator-stage/src/main/java/io/mosip/registration/processor/stages/uingenerator/stage/UinGeneratorStage.java @@ -1,1113 +1,1116 @@ -package io.mosip.registration.processor.stages.uingenerator.stage; - -import java.io.IOException; -import java.time.LocalDateTime; -import java.time.format.DateTimeFormatter; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -import io.mosip.registration.processor.packet.manager.exception.IdrepoDraftException; -import io.mosip.registration.processor.packet.manager.idreposervice.IdrepoDraftService; -import org.apache.commons.lang3.exception.ExceptionUtils; -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONTokener; -import org.json.simple.JSONObject; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.cloud.context.config.annotation.RefreshScope; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.core.env.Environment; -import org.springframework.stereotype.Service; -import org.springframework.web.client.HttpClientErrorException; -import org.springframework.web.client.HttpServerErrorException; - -import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.databind.JsonMappingException; -import com.fasterxml.jackson.databind.ObjectMapper; - -import io.mosip.kernel.biometrics.entities.BiometricRecord; -import io.mosip.kernel.biometrics.spi.CbeffUtil; -import io.mosip.kernel.core.http.RequestWrapper; -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.StringUtils; -import io.mosip.registration.processor.core.abstractverticle.MessageBusAddress; -import io.mosip.registration.processor.core.abstractverticle.MessageDTO; -import io.mosip.registration.processor.core.abstractverticle.MosipEventBus; -import io.mosip.registration.processor.core.abstractverticle.MosipRouter; -import io.mosip.registration.processor.core.abstractverticle.MosipVerticleAPIManager; -import io.mosip.registration.processor.core.code.ApiName; -import io.mosip.registration.processor.core.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.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.LoggerFileConstant; -import io.mosip.registration.processor.core.constant.MappingJsonConstants; -import io.mosip.registration.processor.core.constant.ProviderStageName; -import io.mosip.registration.processor.core.exception.ApisResourceAccessException; -import io.mosip.registration.processor.core.exception.PacketManagerException; -import io.mosip.registration.processor.core.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.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.logger.RegProcessorLogger; -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.idreposervice.IdRepoService; -import io.mosip.registration.processor.packet.storage.dto.Document; -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.ABISHandlerUtil; -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.stages.uingenerator.constants.UINConstants; -import io.mosip.registration.processor.stages.uingenerator.dto.UinGenResponseDto; -import io.mosip.registration.processor.stages.uingenerator.dto.VidRequestDto; -import io.mosip.registration.processor.stages.uingenerator.dto.VidResponseDto; -import io.mosip.registration.processor.stages.uingenerator.exception.VidCreationException; -import io.mosip.registration.processor.packet.manager.dto.IdRequestDto; -import io.mosip.registration.processor.packet.manager.dto.IdResponseDTO; -import io.mosip.registration.processor.packet.manager.dto.RequestDto; -import io.mosip.registration.processor.stages.uingenerator.util.UinStatusMessage; -import io.mosip.registration.processor.status.code.RegistrationStatusCode; -import io.mosip.registration.processor.status.code.RegistrationType; -import io.mosip.registration.processor.status.dto.InternalRegistrationStatusDto; -import io.mosip.registration.processor.status.dto.RegistrationStatusDto; -import io.mosip.registration.processor.status.service.RegistrationStatusService; - -/** - * The Class UinGeneratorStage. - * - * @author Ranjitha Siddegowda - * @author Rishabh Keshari - */ -@RefreshScope -@Service -@Configuration -@ComponentScan(basePackages = { "${mosip.auth.adapter.impl.basepackage}", - "io.mosip.registration.processor.core.config", - "io.mosip.registration.processor.stages.uingenerator.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.stages.config", - "io.mosip.kernel.packetmanager.config", - "io.mosip.registration.processor.packet.manager.config", - "io.mosip.registration.processor.core.kernel.beans"}) -public class UinGeneratorStage extends MosipVerticleAPIManager { - - /** The reg proc logger. */ - private static Logger regProcLogger = RegProcessorLogger.getLogger(UinGeneratorStage.class); - private static final String RECORD_ALREADY_EXISTS_ERROR = "IDR-IDC-012"; - private static final String STAGE_PROPERTY_PREFIX = "mosip.regproc.uin.generator."; - private static final String UIN = "UIN"; - private static final String IDREPO_STATUS = "DRAFTED"; - - @Autowired - private Environment env; - - @Autowired - private IdRepoService idRepoService; - - /** The mosip event bus. */ - MosipEventBus mosipEventBus = null; - - @Value("${registration.processor.id.repo.vidType}") - private String vidType; - - @Value("${mosip.commons.packet.manager.schema.validator.convertIdSchemaToDouble:true}") - private boolean convertIdschemaToDouble; - - /** The cluster manager url. */ - @Value("${vertx.cluster.configuration}") - private String clusterManagerUrl; - - /** The id repo create. */ - @Value("${registration.processor.id.repo.create}") - private String idRepoCreate; - - /** The id repo update. */ - @Value("${registration.processor.id.repo.update}") - private String idRepoUpdate; - - /** worker pool size. */ - @Value("${worker.pool.size}") - private Integer workerPoolSize; - - /** After this time intervel, message should be considered as expired (In seconds). */ - @Value("${mosip.regproc.uin.generator.message.expiry-time-limit}") - private Long messageExpiryTimeLimit; - - @Value("${uingenerator.lost.packet.allowed.update.fields:null}") - private String updateInfo; - - /** The core audit request builder. */ - @Autowired - private AuditLogRequestBuilder auditLogRequestBuilder; - - /** Mosip router for APIs */ - @Autowired - private MosipRouter router; - - @Autowired - private ObjectMapper mapper; - - @Autowired - private IdrepoDraftService idrepoDraftService; - - /** The registration processor rest client service. */ - @Autowired - private RegistrationProcessorRestClientService registrationProcessorRestClientService; - - /** The demographic dedupe repository. */ - @Autowired - private BasePacketRepository regLostUinDetEntity; - - /** The registration status service. */ - @Autowired - private RegistrationStatusService registrationStatusService; - - /** The utility. */ - @Autowired - private Utilities utility; - - @Autowired - private CbeffUtil cbeffutil; - - @Autowired - private RegistrationExceptionMapperUtil registrationStatusMapperUtil; - - @Autowired - private ABISHandlerUtil aBISHandlerUtil; - - @Autowired - private PriorityBasedPacketManagerService packetManagerService; - - @Autowired - private IdSchemaUtil idSchemaUtil; - - @Autowired - private ObjectMapper objectMapper; - - private TrimExceptionMessage trimExceptionMessage = new TrimExceptionMessage(); - - /* - * (non-Javadoc) - * - * @see - * io.mosip.registration.processor.core.spi.eventbus.EventBusManager#process( - * java.lang.Object) - */ - @SuppressWarnings("unchecked") - @Override - public MessageDTO process(MessageDTO object) { - boolean isTransactionSuccessful = Boolean.FALSE; - object.setMessageBusAddress(MessageBusAddress.UIN_GENERATION_BUS_IN); - object.setInternalError(Boolean.FALSE); - object.setIsValid(Boolean.TRUE); - LogDescription description = new LogDescription(); - String registrationId = object.getRid(); - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - registrationId, "UinGeneratorStage::process()::entry"); - UinGenResponseDto uinResponseDto = null; - - InternalRegistrationStatusDto registrationStatusDto = registrationStatusService.getRegistrationStatus( - registrationId, object.getReg_type(), object.getIteration(), object.getWorkflowInstanceId()); - try { - registrationStatusDto - .setLatestTransactionTypeCode(RegistrationTransactionTypeCode.UIN_GENERATOR.toString()); - registrationStatusDto.setRegistrationStageName(getStageName()); - - if ((RegistrationType.LOST.toString()).equalsIgnoreCase(object.getReg_type())) { - String lostPacketRegId = object.getRid(); - String matchedRegId = regLostUinDetEntity.getLostUinMatchedRegIdByWorkflowId(object.getWorkflowInstanceId()); - - if (matchedRegId != null) { - regProcLogger.info("Match for lostPacketRegId"+lostPacketRegId +"is "+matchedRegId); - lostAndUpdateUin(lostPacketRegId, matchedRegId, registrationStatusDto.getRegistrationType(), object, description); - } - - } else { - - IdResponseDTO idResponseDTO = new IdResponseDTO(); - String schemaVersion = packetManagerService.getFieldByMappingJsonKey(registrationId, MappingJsonConstants.IDSCHEMA_VERSION, registrationStatusDto.getRegistrationType(), ProviderStageName.UIN_GENERATOR); - - Map fieldMap = packetManagerService.getFields(registrationId, - idSchemaUtil.getDefaultFields(Double.valueOf(schemaVersion)), registrationStatusDto.getRegistrationType(), ProviderStageName.UIN_GENERATOR); - String uinField = fieldMap.get(utility.getMappingJsonValue(MappingJsonConstants.UIN, MappingJsonConstants.IDENTITY)); - - JSONObject demographicIdentity = new JSONObject(); - demographicIdentity.put(MappingJsonConstants.IDSCHEMA_VERSION, convertIdschemaToDouble ? Double.valueOf(schemaVersion) : schemaVersion); - - loadDemographicIdentity(fieldMap, demographicIdentity); - - if (StringUtils.isEmpty(uinField) || uinField.equalsIgnoreCase("null") ) { - - idResponseDTO = sendIdRepoWithUin(registrationId, registrationStatusDto.getRegistrationType(), demographicIdentity, - uinField); - - boolean isUinAlreadyPresent = isUinAlreadyPresent(idResponseDTO, registrationId); - - if (isIdResponseNotNull(idResponseDTO) || isUinAlreadyPresent) { - registrationStatusDto.setStatusComment(StatusUtil.UIN_GENERATED_SUCCESS.getMessage()); - registrationStatusDto.setSubStatusCode(StatusUtil.UIN_GENERATED_SUCCESS.getCode()); - isTransactionSuccessful = true; - registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); - description.setMessage(PlatformSuccessMessages.RPR_UIN_GENERATOR_STAGE_SUCCESS.getMessage()); - description.setCode(PlatformSuccessMessages.RPR_UIN_GENERATOR_STAGE_SUCCESS.getCode()); - description.setTransactionStatusCode(RegistrationTransactionStatusCode.SUCCESS.toString()); - - } else { - List errors = idResponseDTO != null ? idResponseDTO.getErrors() : null; - String statusComment = errors != null ? errors.get(0).getMessage() - : UINConstants.NULL_IDREPO_RESPONSE; - int unknownErrorCount=0; - for(ErrorDTO dto:errors) { - if(dto.getErrorCode().equalsIgnoreCase("IDR-IDC-004")||dto.getErrorCode().equalsIgnoreCase("IDR-IDC-001")) { - unknownErrorCount++; - } - } - if(unknownErrorCount>0) { - registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); - registrationStatusDto.setLatestTransactionStatusCode(registrationStatusMapperUtil - .getStatusCode(RegistrationExceptionTypeCode.PACKET_UIN_GENERATION_REPROCESS)); - description.setTransactionStatusCode(registrationStatusMapperUtil - .getStatusCode(RegistrationExceptionTypeCode.PACKET_UIN_GENERATION_REPROCESS)); - } - else { - registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.toString()); - registrationStatusDto.setLatestTransactionStatusCode(registrationStatusMapperUtil - .getStatusCode(RegistrationExceptionTypeCode.PACKET_UIN_GENERATION_FAILED)); - description.setTransactionStatusCode(registrationStatusMapperUtil - .getStatusCode(RegistrationExceptionTypeCode.PACKET_UIN_GENERATION_FAILED)); - } - registrationStatusDto.setStatusComment(trimExceptionMessage - .trimExceptionMessage(StatusUtil.UIN_GENERATION_FAILED.getMessage() + statusComment)); - object.setInternalError(Boolean.TRUE); - isTransactionSuccessful = false; - description.setMessage(PlatformErrorMessages.RPR_UGS_UIN_UPDATE_FAILURE.getMessage()); - description.setCode(PlatformErrorMessages.RPR_UGS_UIN_UPDATE_FAILURE.getCode()); - description.setSubStatusCode(StatusUtil.UIN_GENERATION_FAILED.getCode()); - String idres = idResponseDTO != null ? idResponseDTO.toString() - : UINConstants.NULL_IDREPO_RESPONSE; - - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), - LoggerFileConstant.REGISTRATIONID.toString(), registrationId, - statusComment + " : " + idres); - object.setIsValid(Boolean.FALSE); - } - - } else { - if ((RegistrationType.ACTIVATED.toString()).equalsIgnoreCase(object.getReg_type())) { - isTransactionSuccessful = reActivateUin(idResponseDTO, registrationId, uinField, object, - demographicIdentity, description); - } else if ((RegistrationType.DEACTIVATED.toString()) - .equalsIgnoreCase(object.getReg_type())) { - idResponseDTO = deactivateUin(registrationId, uinField, object, demographicIdentity, - description); - } else if (RegistrationType.UPDATE.toString().equalsIgnoreCase(object.getReg_type()) - || (RegistrationType.RES_UPDATE.toString() - .equalsIgnoreCase(object.getReg_type()))) { - isTransactionSuccessful = uinUpdate(registrationId, registrationStatusDto.getRegistrationType(), uinField, object, demographicIdentity, - description); - } - } - - } - regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - registrationId, description.getMessage()); - registrationStatusDto.setUpdatedBy(UINConstants.USER); - - } catch (io.mosip.kernel.core.util.exception.JsonProcessingException e) { - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - registrationId, - RegistrationStatusCode.FAILED.toString() + e.getMessage() + ExceptionUtils.getStackTrace(e)); - registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.toString()); - registrationStatusDto.setStatusComment( - trimExceptionMessage.trimExceptionMessage(StatusUtil.JSON_PARSING_EXCEPTION.getMessage() + e.getMessage())); - registrationStatusDto.setSubStatusCode(StatusUtil.JSON_PARSING_EXCEPTION.getCode()); - registrationStatusDto.setLatestTransactionStatusCode( - registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.JSON_PROCESSING_EXCEPTION)); - isTransactionSuccessful = false; - description.setMessage(PlatformErrorMessages.RPR_SYS_JSON_PARSING_EXCEPTION.getMessage()); - description.setCode(PlatformErrorMessages.RPR_SYS_JSON_PARSING_EXCEPTION.getCode()); - object.setInternalError(Boolean.TRUE); - object.setRid(registrationStatusDto.getRegistrationId()); - } catch (PacketManagerException e) { - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - registrationId, - RegistrationStatusCode.PROCESSING.toString() + e.getMessage() + ExceptionUtils.getStackTrace(e)); - registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.name()); - registrationStatusDto.setStatusComment( - trimExceptionMessage.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()); - object.setInternalError(Boolean.TRUE); - object.setRid(registrationStatusDto.getRegistrationId()); - } catch (ApisResourceAccessException ex) { - registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.name()); - registrationStatusDto.setStatusComment(trimExceptionMessage - .trimExceptionMessage(StatusUtil.API_RESOUCE_ACCESS_FAILED.getMessage() + ex.getMessage())); - registrationStatusDto.setSubStatusCode(StatusUtil.API_RESOUCE_ACCESS_FAILED.getCode()); - registrationStatusDto.setLatestTransactionStatusCode(registrationStatusMapperUtil - .getStatusCode(RegistrationExceptionTypeCode.APIS_RESOURCE_ACCESS_EXCEPTION)); - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - registrationId, - RegistrationStatusCode.PROCESSING.toString() + ex.getMessage() + ExceptionUtils.getStackTrace(ex)); - object.setInternalError(Boolean.TRUE); - description.setMessage(trimExceptionMessage - .trimExceptionMessage(StatusUtil.API_RESOUCE_ACCESS_FAILED.getMessage() + ex.getMessage())); - description.setCode(PlatformErrorMessages.RPR_UGS_API_RESOURCE_EXCEPTION.getCode()); - - } catch (IOException e) { - registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.name()); - registrationStatusDto.setStatusComment( - trimExceptionMessage.trimExceptionMessage(StatusUtil.IO_EXCEPTION.getMessage() + e.getMessage())); - registrationStatusDto.setSubStatusCode(StatusUtil.IO_EXCEPTION.getCode()); - registrationStatusDto.setLatestTransactionStatusCode( - registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.PACKET_UIN_GENERATION_REPROCESS)); - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - registrationId, - PlatformErrorMessages.RPR_SYS_IO_EXCEPTION.getMessage() + ExceptionUtils.getStackTrace(e)); - object.setInternalError(Boolean.TRUE); - description.setMessage(PlatformErrorMessages.RPR_SYS_IO_EXCEPTION.getMessage()); - description.setCode(PlatformErrorMessages.RPR_SYS_IO_EXCEPTION.getCode()); - } catch (IdrepoDraftException e) { - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - registrationId, - RegistrationStatusCode.PROCESSING.toString() + e.getMessage() + ExceptionUtils.getStackTrace(e)); - registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.name()); - registrationStatusDto.setStatusComment( - trimExceptionMessage.trimExceptionMessage(StatusUtil.IDREPO_DRAFT_EXCEPTION.getMessage() + e.getMessage())); - registrationStatusDto.setSubStatusCode(StatusUtil.IDREPO_DRAFT_EXCEPTION.getCode()); - registrationStatusDto.setLatestTransactionStatusCode( - registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.IDREPO_DRAFT_EXCEPTION)); - description.setMessage(PlatformErrorMessages.IDREPO_DRAFT_EXCEPTION.getMessage()); - description.setCode(PlatformErrorMessages.IDREPO_DRAFT_EXCEPTION.getCode()); - object.setInternalError(Boolean.TRUE); - object.setRid(registrationStatusDto.getRegistrationId()); - } catch (Exception ex) { - registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.name()); - registrationStatusDto.setStatusComment( - trimExceptionMessage.trimExceptionMessage(StatusUtil.UNKNOWN_EXCEPTION_OCCURED.getMessage())); - registrationStatusDto.setSubStatusCode(StatusUtil.UNKNOWN_EXCEPTION_OCCURED.getCode()); - registrationStatusDto.setLatestTransactionStatusCode( - registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.PACKET_UIN_GENERATION_REPROCESS)); - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - registrationId, - RegistrationStatusCode.PROCESSING.toString() + ex.getMessage() + ExceptionUtils.getStackTrace(ex)); - object.setInternalError(Boolean.TRUE); - description.setMessage(PlatformErrorMessages.RPR_BDD_UNKNOWN_EXCEPTION.getMessage()); - description.setCode(PlatformErrorMessages.RPR_BDD_UNKNOWN_EXCEPTION.getCode()); - } finally { - if (description.getStatusComment() != null) - registrationStatusDto.setStatusComment(description.getStatusComment()); - if (description.getStatusCode() != null) - registrationStatusDto.setStatusCode(description.getStatusCode()); - if (description.getSubStatusCode() != null) - registrationStatusDto.setSubStatusCode(description.getSubStatusCode()); - if (description.getTransactionStatusCode() != null) - registrationStatusDto.setLatestTransactionStatusCode(description.getTransactionStatusCode()); - - if (object.getInternalError()) { - updateErrorFlags(registrationStatusDto, object); - } - String moduleId = isTransactionSuccessful - ? PlatformSuccessMessages.RPR_UIN_GENERATOR_STAGE_SUCCESS.getCode() - : description.getCode(); - String moduleName = ModuleName.UIN_GENERATOR.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, registrationId); - - } - - return object; - } - - private void loadDemographicIdentity(Map fieldMap, JSONObject demographicIdentity) throws IOException, JSONException { - for (Map.Entry e : fieldMap.entrySet()) { - if (e.getValue() != null) { - String value = e.getValue().toString(); - if (value != null) { - Object json = new JSONTokener(value).nextValue(); - if (json instanceof org.json.JSONObject) { - HashMap hashMap = objectMapper.readValue(value, HashMap.class); - demographicIdentity.putIfAbsent(e.getKey(), hashMap); - } - else if (json instanceof JSONArray) { - List jsonList = new ArrayList<>(); - JSONArray jsonArray = new JSONArray(value); - for (int i = 0; i < jsonArray.length(); i++) { - Object obj = jsonArray.get(i); - HashMap hashMap = objectMapper.readValue(obj.toString(), HashMap.class); - jsonList.add(hashMap); - } - demographicIdentity.putIfAbsent(e.getKey(), jsonList); - } else - demographicIdentity.putIfAbsent(e.getKey(), value); - } else - demographicIdentity.putIfAbsent(e.getKey(), value); - } - } - } - - /** - * Send id repo with uin. - * - * @param id - * the reg id - * @param uin - * the uin - * @throws ApisResourceAccessException - * @throws IOException - * @throws JsonMappingException - * @throws JsonParseException - * @throws VidCreationException - * @throws io.mosip.kernel.core.exception.IOException - * @throws Exception - */ - private IdResponseDTO sendIdRepoWithUin(String id, String process, JSONObject demographicIdentity, String uin) - throws Exception { - - List documentInfo = getAllDocumentsByRegId(id, process, demographicIdentity); - RequestDto requestDto = new RequestDto(); - requestDto.setIdentity(demographicIdentity); - requestDto.setDocuments(documentInfo); - requestDto.setRegistrationId(id); - requestDto.setStatus(RegistrationType.ACTIVATED.toString()); - requestDto.setBiometricReferenceId(uin); - - IdResponseDTO result = null; - IdRequestDto idRequestDTO = new IdRequestDto(); - idRequestDTO.setId(idRepoUpdate); - idRequestDTO.setRequest(requestDto); - idRequestDTO.setRequesttime(DateUtils.getUTCCurrentDateTimeString()); - idRequestDTO.setVersion(UINConstants.idRepoApiVersion); - idRequestDTO.setMetadata(null); - - try { - - result = idrepoDraftService.idrepoUpdateDraft(id, null, idRequestDTO); - - } catch (ApisResourceAccessException e) { - regProcLogger.error("Execption occured updating draft for id " + id, e); - if (e.getCause() instanceof HttpClientErrorException) { - HttpClientErrorException httpClientException = (HttpClientErrorException) e.getCause(); - throw new ApisResourceAccessException(httpClientException.getResponseBodyAsString(), - httpClientException); - } else if (e.getCause() instanceof HttpServerErrorException) { - HttpServerErrorException httpServerException = (HttpServerErrorException) e.getCause(); - throw new ApisResourceAccessException(httpServerException.getResponseBodyAsString(), - httpServerException); - } else { - throw e; - } - - } - return result; - - } - - /** - * Gets the all documents by reg id. - * - * @param regId - * the reg id - * @return the all documents by reg id - * @throws IOException - * @throws io.mosip.kernel.core.exception.IOException - * @throws ApisResourceAccessException - * @throws JsonMappingException - * @throws JsonParseException - */ - private List getAllDocumentsByRegId(String regId, String process, JSONObject demographicIdentity) throws Exception { - List applicantDocuments = new ArrayList<>(); - - JSONObject idJSON = demographicIdentity; - JSONObject docJson = utility.getRegistrationProcessorMappingJson(MappingJsonConstants.DOCUMENT); - JSONObject identityJson = utility.getRegistrationProcessorMappingJson(MappingJsonConstants.IDENTITY); - - String applicantBiometricLabel = JsonUtil.getJSONValue(JsonUtil.getJSONObject(identityJson, MappingJsonConstants.INDIVIDUAL_BIOMETRICS), MappingJsonConstants.VALUE); - - HashMap applicantBiometric = (HashMap) idJSON.get(applicantBiometricLabel); - - - for (Object doc : docJson.values()) { - Map docMap = (LinkedHashMap) doc; - String docValue = docMap.values().iterator().next().toString(); - HashMap docInIdentityJson = (HashMap) idJSON.get(docValue); - if (docInIdentityJson != null) - applicantDocuments - .add(getIdDocumnet(regId, docValue, process)); - } - - if (applicantBiometric != null) { - applicantDocuments.add(getBiometrics(regId, applicantBiometricLabel, process, applicantBiometricLabel)); - } - return applicantDocuments; - } - - private Documents getIdDocumnet(String registrationId, String dockey, String process) - throws IOException, ApisResourceAccessException, PacketManagerException, io.mosip.kernel.core.util.exception.JsonProcessingException { - Documents documentsInfoDto = new Documents(); - - Document document = - packetManagerService.getDocument(registrationId, dockey, process, ProviderStageName.UIN_GENERATOR); - if (document != null) { - documentsInfoDto.setValue(CryptoUtil.encodeToURLSafeBase64(document.getDocument())); - documentsInfoDto.setCategory(document.getValue()); - return documentsInfoDto; - } - return null; - } - - private Documents getBiometrics(String registrationId, String person, String process, String idDocLabel) throws Exception { - BiometricRecord biometricRecord = packetManagerService.getBiometrics(registrationId, person, process, ProviderStageName.UIN_GENERATOR); - byte[] xml = cbeffutil.createXML(biometricRecord.getSegments()); - Documents documentsInfoDto = new Documents(); - documentsInfoDto.setValue(CryptoUtil.encodeToURLSafeBase64(xml)); - documentsInfoDto.setCategory(utility.getMappingJsonValue(idDocLabel, MappingJsonConstants.IDENTITY)); - return documentsInfoDto; - - } - - /** - * Update id repo wit uin. - * - * @param regId the reg id - * @param uin the uin - * @param object the object - * @param description - * @return the id response DTO - * @throws ApisResourceAccessException the apis resource access - * exception - * @throws IOException Signals that an I/O exception - * has occurred. - * @throws RegistrationProcessorCheckedException - * @throws io.mosip.kernel.core.exception.IOException - */ - private boolean uinUpdate(String regId, String process, String uin, MessageDTO object, JSONObject demographicIdentity, LogDescription description) - throws Exception { - IdResponseDTO result; - boolean isTransactionSuccessful = Boolean.FALSE; - List documentInfo = getAllDocumentsByRegId(regId, process, demographicIdentity); - result = idRepoRequestBuilder(regId, uin, RegistrationType.ACTIVATED.toString().toUpperCase(), documentInfo, - demographicIdentity); - if (null!=result && isIdResponseNotNull(result)) { - - if (IDREPO_STATUS.equalsIgnoreCase(result.getResponse().getStatus())) { - isTransactionSuccessful = true; - description.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); - description.setStatusComment(StatusUtil.UIN_DATA_UPDATION_SUCCESS.getMessage()); - description.setSubStatusCode(StatusUtil.UIN_DATA_UPDATION_SUCCESS.getCode()); - description.setMessage( - StatusUtil.UIN_DATA_UPDATION_SUCCESS.getMessage() + " for registration Id: " + regId); - description.setTransactionStatusCode(RegistrationTransactionStatusCode.PROCESSED.toString()); - object.setIsValid(Boolean.TRUE); - } - } else { - String statusComment = result != null && result.getErrors() != null ? result.getErrors().get(0).getMessage() - : UINConstants.NULL_IDREPO_RESPONSE; - String message = result != null && result.getErrors() != null - ? result.getErrors().get(0).getMessage() - : UINConstants.NULL_IDREPO_RESPONSE; - description.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); - description.setStatusComment(trimExceptionMessage - .trimExceptionMessage(StatusUtil.UIN_DATA_UPDATION_FAILED.getMessage() + statusComment)); - description.setSubStatusCode(StatusUtil.UIN_DATA_UPDATION_FAILED.getCode()); - description - .setMessage(UINConstants.UIN_FAILURE + regId + "::" + message ); - description.setTransactionStatusCode(RegistrationTransactionStatusCode.PROCESSING.toString()); - object.setIsValid(Boolean.FALSE); - } - return isTransactionSuccessful; - } - - /** - * Id repo request builder. - * - * @param status - * the status - * @param id - * the reg id - * @param demographicIdentity - * the JSONObject - * @param documentInfo - * the document info - * @throws ApisResourceAccessException - * the apis resource access exception - * @throws IOException - */ - private IdResponseDTO idRepoRequestBuilder(String id, String uin, String status, List documentInfo, - JSONObject demographicIdentity) throws ApisResourceAccessException, IdrepoDraftException, IOException { - IdResponseDTO idResponseDto; - RequestDto requestDto = new RequestDto(); - - if (documentInfo != null) - requestDto.setDocuments(documentInfo); - - requestDto.setRegistrationId(id); - requestDto.setStatus(status); - requestDto.setIdentity(demographicIdentity); - - IdRequestDto idRequestDTO = new IdRequestDto(); - idRequestDTO.setId(idRepoUpdate); - idRequestDTO.setMetadata(null); - idRequestDTO.setRequest(requestDto); - idRequestDTO.setRequesttime(DateUtils.getUTCCurrentDateTimeString()); - idRequestDTO.setVersion(UINConstants.idRepoApiVersion); - - try { - idResponseDto = idrepoDraftService.idrepoUpdateDraft(id, uin, idRequestDTO); - } catch (ApisResourceAccessException e) { - regProcLogger.error("Execption occured updating draft for id " + id, e); - if (e.getCause() instanceof HttpClientErrorException) { - regProcLogger.error("Exception occured updating draft for id " + id, e); - HttpClientErrorException httpClientException = (HttpClientErrorException) e.getCause(); - throw new ApisResourceAccessException(httpClientException.getResponseBodyAsString(), - httpClientException); - } else if (e.getCause() instanceof HttpServerErrorException) { - HttpServerErrorException httpServerException = (HttpServerErrorException) e.getCause(); - throw new ApisResourceAccessException(httpServerException.getResponseBodyAsString(), - httpServerException); - } else { - throw e; - } - - } - return idResponseDto; - } - - /** - * Re activate uin. - * - * @param id - * the reg id - * @param uin - * the uin - * @param object - * the object - * @param description - * @return the id response DTO - * @throws ApisResourceAccessException - * the apis resource access exception - * @throws IOException - */ - private boolean reActivateUin(IdResponseDTO idResponseDTO, String id, String uin, MessageDTO object, - JSONObject demographicIdentity, LogDescription description) - throws ApisResourceAccessException, IOException, IdrepoDraftException { - IdResponseDTO result = getIdRepoDataByUIN(uin, id, description); - List pathsegments = new ArrayList<>(); - RequestDto requestDto = new RequestDto(); - boolean isTransactionSuccessful = Boolean.FALSE; - - if (isIdResponseNotNull(result)) { - - if ((RegistrationType.ACTIVATED.toString()).equalsIgnoreCase(result.getResponse().getStatus())) { - - description.setStatusCode(RegistrationStatusCode.FAILED.toString()); - description.setStatusComment(StatusUtil.UIN_ALREADY_ACTIVATED.getMessage()); - description.setSubStatusCode(StatusUtil.UIN_ALREADY_ACTIVATED.getCode()); - description.setMessage(PlatformErrorMessages.UIN_ALREADY_ACTIVATED.getMessage()); - description.setCode(PlatformErrorMessages.UIN_ALREADY_ACTIVATED.getCode()); - description.setTransactionStatusCode(RegistrationTransactionStatusCode.FAILED.toString()); - object.setIsValid(Boolean.FALSE); - return isTransactionSuccessful; - - } else { - - requestDto.setRegistrationId(id); - requestDto.setStatus(RegistrationType.ACTIVATED.toString()); - requestDto.setBiometricReferenceId(uin); - requestDto.setIdentity(demographicIdentity); - - IdRequestDto idRequestDTO = new IdRequestDto(); - idRequestDTO.setId(idRepoUpdate); - idRequestDTO.setRequest(requestDto); - idRequestDTO.setMetadata(null); - idRequestDTO.setRequesttime(DateUtils.getUTCCurrentDateTimeString()); - idRequestDTO.setVersion(UINConstants.idRepoApiVersion); - - result = idrepoDraftService.idrepoUpdateDraft(id, uin, idRequestDTO); - - if (isIdResponseNotNull(result)) { - - if ((RegistrationType.ACTIVATED.toString()).equalsIgnoreCase(result.getResponse().getStatus())) { - isTransactionSuccessful = true; - description.setStatusCode(RegistrationStatusCode.PROCESSED.toString()); - description.setStatusComment(StatusUtil.UIN_ACTIVATED_SUCCESS.getMessage()); - description.setSubStatusCode(StatusUtil.UIN_ACTIVATED_SUCCESS.getCode()); - description.setMessage(StatusUtil.UIN_ACTIVATED_SUCCESS.getMessage() + id); - description.setMessage(PlatformSuccessMessages.RPR_UIN_ACTIVATED_SUCCESS.getMessage()); - description.setCode(PlatformSuccessMessages.RPR_UIN_ACTIVATED_SUCCESS.getCode()); - description.setTransactionStatusCode(RegistrationTransactionStatusCode.PROCESSED.toString()); - object.setIsValid(Boolean.TRUE); - } else { - description.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); - description.setStatusComment(StatusUtil.UIN_ACTIVATED_FAILED.getMessage()); - description.setSubStatusCode(StatusUtil.UIN_ACTIVATED_FAILED.getCode()); - description.setMessage(StatusUtil.UIN_ACTIVATED_FAILED.getMessage() + id); - description.setMessage(PlatformErrorMessages.UIN_ACTIVATED_FAILED.getMessage()); - description.setCode(PlatformErrorMessages.UIN_ACTIVATED_FAILED.getCode()); - description.setTransactionStatusCode(RegistrationTransactionStatusCode.REPROCESS.toString()); - object.setIsValid(Boolean.FALSE); - } - } else { - String statusComment = result != null && result.getErrors() != null - ? result.getErrors().get(0).getMessage() - : UINConstants.NULL_IDREPO_RESPONSE; - description.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); - description.setStatusComment(trimExceptionMessage - .trimExceptionMessage(StatusUtil.UIN_REACTIVATION_FAILED.getMessage() + statusComment)); - description.setSubStatusCode(StatusUtil.UIN_REACTIVATION_FAILED.getCode()); - description.setMessage( - UINConstants.UIN_FAILURE + id + "::" + (result != null && result.getErrors() != null - ? result.getErrors().get(0).getMessage() - : UINConstants.NULL_IDREPO_RESPONSE)); - description.setMessage(PlatformErrorMessages.UIN_REACTIVATION_FAILED.getMessage()); - description.setCode(PlatformErrorMessages.UIN_REACTIVATION_FAILED.getCode()); - description.setTransactionStatusCode(RegistrationTransactionStatusCode.REPROCESS.toString()); - object.setIsValid(Boolean.FALSE); - } - - } - - }else { - String statusComment = result != null && result.getErrors() != null - ? result.getErrors().get(0).getMessage() - : UINConstants.NULL_IDREPO_RESPONSE; - description.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); - description.setStatusComment(trimExceptionMessage - .trimExceptionMessage(StatusUtil.UIN_REACTIVATION_FAILED.getMessage() + statusComment)); - description.setSubStatusCode(StatusUtil.UIN_REACTIVATION_FAILED.getCode()); - description.setMessage( - UINConstants.UIN_FAILURE + id + "::" + (result != null && result.getErrors() != null - ? result.getErrors().get(0).getMessage() - : UINConstants.NULL_IDREPO_RESPONSE)); - description.setMessage(PlatformErrorMessages.UIN_REACTIVATION_FAILED.getMessage()); - description.setCode(PlatformErrorMessages.UIN_REACTIVATION_FAILED.getCode()); - description.setTransactionStatusCode(RegistrationTransactionStatusCode.REPROCESS.toString()); - object.setIsValid(Boolean.FALSE); - } - - return isTransactionSuccessful; - } - - private boolean isIdResponseNotNull(IdResponseDTO result) { - return result != null && result.getResponse() != null; - } - - private boolean isUinAlreadyPresent(IdResponseDTO result, String rid) { - if (result != null && result.getErrors() != null && result.getErrors().size() > 0 - && result.getErrors().get(0).getErrorCode().equalsIgnoreCase(RECORD_ALREADY_EXISTS_ERROR)) { - ErrorDTO errorDTO = result.getErrors().get(0); - regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), - LoggerFileConstant.REGISTRATIONID.toString() + rid, - "Record is already present in IDREPO. Error message received : " + errorDTO.getMessage(), - "The stage will ignore this error and try to generate vid for the existing UIN now. " + - "This is to make sure if the packet processing fails while generating VID then re-processor can process the packet again"); - return true; - } - return false; - } - - /** - * Deactivate uin. - * - * @param id - * the reg id - * @param uin - * the uin - * @param object - * the object - * @param description - * @return the id response DTO - * @throws ApisResourceAccessException - * @throws IOException - */ - private IdResponseDTO deactivateUin(String id, String uin, MessageDTO object, JSONObject demographicIdentity, - LogDescription description) throws ApisResourceAccessException, IOException, IdrepoDraftException { - IdResponseDTO idResponseDto; - RequestDto requestDto = new RequestDto(); - String statusComment = ""; - - idResponseDto = getIdRepoDataByUIN(uin, id, description); - - if (idResponseDto.getResponse() != null - && idResponseDto.getResponse().getStatus().equalsIgnoreCase(RegistrationType.DEACTIVATED.toString())) { - description.setStatusCode(RegistrationStatusCode.FAILED.toString()); - description.setStatusComment(StatusUtil.UIN_ALREADY_DEACTIVATED.getMessage()); - description.setSubStatusCode(StatusUtil.UIN_ALREADY_DEACTIVATED.getCode()); - description.setMessage(StatusUtil.UIN_ALREADY_DEACTIVATED.getMessage() + id); - description.setMessage(PlatformErrorMessages.UIN_ALREADY_DEACTIVATED.getMessage()); - description.setCode(PlatformErrorMessages.UIN_ALREADY_DEACTIVATED.getCode()); - description.setTransactionStatusCode(RegistrationTransactionStatusCode.FAILED.toString()); - object.setIsValid(Boolean.FALSE); - return idResponseDto; - - } else { - requestDto.setRegistrationId(id); - requestDto.setStatus(RegistrationType.DEACTIVATED.toString()); - requestDto.setIdentity(demographicIdentity); - requestDto.setBiometricReferenceId(uin); - - IdRequestDto idRequestDTO = new IdRequestDto(); - idRequestDTO.setId(idRepoUpdate); - idRequestDTO.setMetadata(null); - idRequestDTO.setRequest(requestDto); - idRequestDTO.setRequesttime(DateUtils.getUTCCurrentDateTimeString()); - idRequestDTO.setVersion(UINConstants.idRepoApiVersion); - - idResponseDto = idrepoDraftService.idrepoUpdateDraft(id, uin, idRequestDTO); - - if (isIdResponseNotNull(idResponseDto)) { - if (idResponseDto.getResponse().getStatus().equalsIgnoreCase(RegistrationType.DEACTIVATED.toString())) { - description.setStatusCode(RegistrationStatusCode.PROCESSED.toString()); - description.setStatusComment(StatusUtil.UIN_DEACTIVATION_SUCCESS.getMessage()); - description.setSubStatusCode(StatusUtil.UIN_DEACTIVATION_SUCCESS.getCode()); - description.setMessage(StatusUtil.UIN_DEACTIVATION_SUCCESS.getMessage() + id); - description.setMessage(PlatformSuccessMessages.RPR_UIN_DEACTIVATION_SUCCESS.getMessage()); - description.setCode(PlatformSuccessMessages.RPR_UIN_DEACTIVATION_SUCCESS.getCode()); - description.setTransactionStatusCode(RegistrationTransactionStatusCode.PROCESSED.toString()); - object.setIsValid(Boolean.TRUE); - statusComment = idResponseDto.getResponse().getStatus().toString(); - - } - } else { - - statusComment = idResponseDto != null && idResponseDto.getErrors() != null - ? idResponseDto.getErrors().get(0).getMessage() - : UINConstants.NULL_IDREPO_RESPONSE; - description.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); - description.setStatusComment(trimExceptionMessage - .trimExceptionMessage(StatusUtil.UIN_DEACTIVATION_FAILED.getMessage() + statusComment)); - description.setSubStatusCode(StatusUtil.UIN_DEACTIVATION_FAILED.getCode()); - description.setMessage(PlatformErrorMessages.UIN_DEACTIVATION_FAILED.getMessage()); - description.setCode(PlatformErrorMessages.UIN_DEACTIVATION_FAILED.getCode()); - description.setTransactionStatusCode(RegistrationTransactionStatusCode.REPROCESS.toString()); - object.setIsValid(Boolean.FALSE); - } - - } - regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), - LoggerFileConstant.REGISTRATIONID.toString() + id, "Updated Response from IdRepo API", - "is : " + statusComment); - - return idResponseDto; - } - - /** - * Gets the id repo data by UIN. - * - * @param uin - * the uin - * @param description - * @return the id repo data by UIN - * @throws ApisResourceAccessException - * the apis resource access exception - * @throws IOException - */ - private IdResponseDTO getIdRepoDataByUIN(String uin, String regId, LogDescription description) - throws ApisResourceAccessException { - IdResponseDTO response; - - List pathsegments = new ArrayList<>(); - pathsegments.add(uin); - try { - - response = (IdResponseDTO) registrationProcessorRestClientService.getApi(ApiName.IDREPOGETIDBYUIN, - pathsegments, "", "", IdResponseDTO.class); - - } catch (ApisResourceAccessException e) { - if (e.getCause() instanceof HttpClientErrorException) { - HttpClientErrorException httpClientException = (HttpClientErrorException) e.getCause(); - description.setMessage(PlatformErrorMessages.UIN_GENERATION_FAILED.getMessage()); - description.setCode(PlatformErrorMessages.UIN_GENERATION_FAILED.getCode()); - throw new ApisResourceAccessException(httpClientException.getResponseBodyAsString(), - httpClientException); - } else if (e.getCause() instanceof HttpServerErrorException) { - HttpServerErrorException httpServerException = (HttpServerErrorException) e.getCause(); - description.setMessage(PlatformErrorMessages.UIN_GENERATION_FAILED.getMessage()); - description.setCode(PlatformErrorMessages.UIN_GENERATION_FAILED.getCode()); - - throw new ApisResourceAccessException(httpServerException.getResponseBodyAsString(), - httpServerException); - } else { - description.setMessage(PlatformErrorMessages.UIN_GENERATION_FAILED.getMessage()); - description.setCode(PlatformErrorMessages.UIN_GENERATION_FAILED.getCode()); - throw e; - } - } - return response; - } - - /** - * Deploy verticle. - */ - public void deployVerticle() { - - mosipEventBus = this.getEventBus(this, clusterManagerUrl, workerPoolSize); - this.consumeAndSend(mosipEventBus, MessageBusAddress.UIN_GENERATION_BUS_IN, - MessageBusAddress.UIN_GENERATION_BUS_OUT, messageExpiryTimeLimit); - } - - @Override - public void start() { - router.setRoute(this.postUrl(getVertx(), MessageBusAddress.UIN_GENERATION_BUS_IN, - MessageBusAddress.UIN_GENERATION_BUS_OUT)); - this.createServer(router.getRouter(), getPort()); - - } - - @Override - protected String getPropertyPrefix() { - return STAGE_PROPERTY_PREFIX; - } - - /** - * Link reg id wrt uin. - * - * @param lostPacketRegId - * the lost packet reg id - * @param matchedRegId - * the matched reg id - * @param object - * the object - * @param description - * @return the id response DTO - * @throws ApisResourceAccessException - * the apis resource access exception - * @throws IOException - * Signals that an I/O exception has occurred. - */ - @SuppressWarnings("unchecked") - private IdResponseDTO lostAndUpdateUin(String lostPacketRegId, String matchedRegId, String process, MessageDTO object, - LogDescription description) throws ApisResourceAccessException, IOException, io.mosip.kernel.core.util.exception.JsonProcessingException, PacketManagerException, IdrepoDraftException { - - IdResponseDTO idResponse = null; - String uin = idRepoService.getUinByRid(matchedRegId, utility.getGetRegProcessorDemographicIdentity()); - - - RequestDto requestDto = new RequestDto(); - String statusComment = ""; - - if (uin != null) { - - JSONObject regProcessorIdentityJson = utility.getRegistrationProcessorMappingJson(MappingJsonConstants.IDENTITY); - String idschemaversion = JsonUtil.getJSONValue(JsonUtil.getJSONObject(regProcessorIdentityJson, MappingJsonConstants.IDSCHEMA_VERSION), MappingJsonConstants.VALUE); - - JSONObject identityObject = new JSONObject(); - identityObject.put(UINConstants.UIN, uin); - String schemaVersion = packetManagerService.getFieldByMappingJsonKey(lostPacketRegId, MappingJsonConstants.IDSCHEMA_VERSION, process, ProviderStageName.UIN_GENERATOR); - identityObject.put(idschemaversion, convertIdschemaToDouble ? Double.valueOf(schemaVersion) : schemaVersion); - regProcLogger.info("Fields to be updated "+updateInfo); - if (null != updateInfo && !updateInfo.isEmpty()) { - String[] upd = updateInfo.split(","); - for (String infoField : upd) { - String fldValue = packetManagerService.getField(lostPacketRegId, infoField, process, - ProviderStageName.UIN_GENERATOR); - if (null != fldValue) - identityObject.put(infoField, fldValue); - } - } - requestDto.setRegistrationId(lostPacketRegId); - requestDto.setIdentity(identityObject); - - IdRequestDto idRequestDTO = new IdRequestDto(); - idRequestDTO.setId(idRepoUpdate); - idRequestDTO.setRequest(requestDto); - idRequestDTO.setMetadata(null); - idRequestDTO.setRequesttime(DateUtils.getUTCCurrentDateTimeString()); - idRequestDTO.setVersion(UINConstants.idRepoApiVersion); - - idResponse = idrepoDraftService.idrepoUpdateDraft(lostPacketRegId, uin, idRequestDTO); - - if (isIdResponseNotNull(idResponse)) { - description.setStatusCode(RegistrationStatusCode.PROCESSED.toString()); - description.setStatusComment(StatusUtil.LINK_RID_FOR_LOST_PACKET_SUCCESS.getMessage()); - description.setSubStatusCode(StatusUtil.LINK_RID_FOR_LOST_PACKET_SUCCESS.getCode()); - description.setMessage(UinStatusMessage.PACKET_LOST_UIN_UPDATION_SUCCESS_MSG + lostPacketRegId); - description.setTransactionStatusCode(RegistrationTransactionStatusCode.PROCESSED.toString()); - object.setIsValid(Boolean.TRUE); - - regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), - LoggerFileConstant.REGISTRATIONID.toString() + lostPacketRegId, - " UIN LINKED WITH " + matchedRegId, "is : " + description); - } else { - - statusComment = idResponse != null && idResponse.getErrors() != null - && idResponse.getErrors().get(0) != null ? idResponse.getErrors().get(0).getMessage() - : UinStatusMessage.PACKET_LOST_UIN_UPDATION_FAILURE_MSG + " " - + UINConstants.NULL_IDREPO_RESPONSE + "for lostPacketRegId " + lostPacketRegId; - description.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); - description.setStatusComment(StatusUtil.LINK_RID_FOR_LOST_PACKET_SUCCESS.getMessage() + statusComment); - description.setSubStatusCode(StatusUtil.LINK_RID_FOR_LOST_PACKET_SUCCESS.getCode()); - description.setTransactionStatusCode(registrationStatusMapperUtil - .getStatusCode(RegistrationExceptionTypeCode.PACKET_UIN_GENERATION_ID_REPO_ERROR)); - if (idResponse != null - && idResponse.getErrors() != null) - description.setMessage(idResponse.getErrors().get(0).getMessage()); - else - description.setMessage(UINConstants.NULL_IDREPO_RESPONSE); - object.setIsValid(Boolean.FALSE); - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), - LoggerFileConstant.REGISTRATIONID.toString() + lostPacketRegId, - " UIN NOT LINKED WITH " + matchedRegId, "is : " + statusComment); - } - - } else { - statusComment = UinStatusMessage.PACKET_LOST_UIN_UPDATION_FAILURE_MSG + " " - + UINConstants.NULL_IDREPO_RESPONSE + " UIN not available for matchedRegId " + matchedRegId; - description.setStatusComment(StatusUtil.LINK_RID_FOR_LOST_PACKET_FAILED.getMessage()); - description.setSubStatusCode(StatusUtil.LINK_RID_FOR_LOST_PACKET_FAILED.getCode()); - description.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); - description.setTransactionStatusCode(registrationStatusMapperUtil - .getStatusCode(RegistrationExceptionTypeCode.PACKET_UIN_GENERATION_REPROCESS)); - description.setMessage(UinStatusMessage.PACKET_LOST_UIN_UPDATION_FAILURE_MSG + " " - + UINConstants.NULL_IDREPO_RESPONSE + " UIN not available for matchedRegId " + matchedRegId); - - object.setIsValid(Boolean.FALSE); - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), - LoggerFileConstant.REGISTRATIONID.toString() + lostPacketRegId, - " UIN NOT LINKED WITH " + matchedRegId, "is : " + statusComment); - } - - return idResponse; - } - - private void updateErrorFlags(InternalRegistrationStatusDto registrationStatusDto, MessageDTO object) { - object.setInternalError(true); - if (registrationStatusDto.getLatestTransactionStatusCode() - .equalsIgnoreCase(RegistrationTransactionStatusCode.REPROCESS.toString())) { - object.setIsValid(true); - } else { - object.setIsValid(false); - } - } -} +package io.mosip.registration.processor.stages.uingenerator.stage; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import org.apache.commons.lang3.exception.ExceptionUtils; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONTokener; +import org.json.simple.JSONObject; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.cloud.context.config.annotation.RefreshScope; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Service; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.web.client.HttpServerErrorException; + +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +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.StringUtils; +import io.mosip.registration.processor.core.abstractverticle.MessageBusAddress; +import io.mosip.registration.processor.core.abstractverticle.MessageDTO; +import io.mosip.registration.processor.core.abstractverticle.MosipEventBus; +import io.mosip.registration.processor.core.abstractverticle.MosipRouter; +import io.mosip.registration.processor.core.abstractverticle.MosipVerticleAPIManager; +import io.mosip.registration.processor.core.code.ApiName; +import io.mosip.registration.processor.core.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.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.LoggerFileConstant; +import io.mosip.registration.processor.core.constant.MappingJsonConstants; +import io.mosip.registration.processor.core.constant.ProviderStageName; +import io.mosip.registration.processor.core.exception.ApisResourceAccessException; +import io.mosip.registration.processor.core.exception.PacketManagerException; +import io.mosip.registration.processor.core.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.idrepo.dto.Documents; +import io.mosip.registration.processor.core.logger.LogDescription; +import io.mosip.registration.processor.core.logger.RegProcessorLogger; +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.dto.IdRequestDto; +import io.mosip.registration.processor.packet.manager.dto.IdResponseDTO; +import io.mosip.registration.processor.packet.manager.dto.RequestDto; +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.Document; +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.ABISHandlerUtil; +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.stages.uingenerator.constants.UINConstants; +import io.mosip.registration.processor.stages.uingenerator.dto.UinGenResponseDto; +import io.mosip.registration.processor.stages.uingenerator.exception.VidCreationException; +import io.mosip.registration.processor.stages.uingenerator.util.UinStatusMessage; +import io.mosip.registration.processor.status.code.RegistrationStatusCode; +import io.mosip.registration.processor.status.code.RegistrationType; +import io.mosip.registration.processor.status.dto.InternalRegistrationStatusDto; +import io.mosip.registration.processor.status.dto.RegistrationStatusDto; +import io.mosip.registration.processor.status.service.RegistrationStatusService; + +/** + * The Class UinGeneratorStage. + * + * @author Ranjitha Siddegowda + * @author Rishabh Keshari + */ +@RefreshScope +@Service +@Configuration +@ComponentScan(basePackages = { "${mosip.auth.adapter.impl.basepackage}", + "io.mosip.registration.processor.core.config", + "io.mosip.registration.processor.stages.uingenerator.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.stages.config", + "io.mosip.kernel.packetmanager.config", + "io.mosip.registration.processor.packet.manager.config", + "io.mosip.registration.processor.core.kernel.beans"}) +public class UinGeneratorStage extends MosipVerticleAPIManager { + + /** The reg proc logger. */ + private static Logger regProcLogger = RegProcessorLogger.getLogger(UinGeneratorStage.class); + private static final String RECORD_ALREADY_EXISTS_ERROR = "IDR-IDC-012"; + private static final String STAGE_PROPERTY_PREFIX = "mosip.regproc.uin.generator."; + private static final String UIN = "UIN"; + private static final String IDREPO_STATUS = "DRAFTED"; + + @Autowired + private Environment env; + + @Autowired + private IdRepoService idRepoService; + + /** The mosip event bus. */ + MosipEventBus mosipEventBus = null; + + @Value("${registration.processor.id.repo.vidType}") + private String vidType; + + @Value("${mosip.commons.packet.manager.schema.validator.convertIdSchemaToDouble:true}") + private boolean convertIdschemaToDouble; + + /** The cluster manager url. */ + @Value("${vertx.cluster.configuration}") + private String clusterManagerUrl; + + /** The id repo create. */ + @Value("${registration.processor.id.repo.create}") + private String idRepoCreate; + + /** The id repo update. */ + @Value("${registration.processor.id.repo.update}") + private String idRepoUpdate; + + /** worker pool size. */ + @Value("${worker.pool.size}") + private Integer workerPoolSize; + + /** After this time intervel, message should be considered as expired (In seconds). */ + @Value("${mosip.regproc.uin.generator.message.expiry-time-limit}") + private Long messageExpiryTimeLimit; + + @Value("${uingenerator.lost.packet.allowed.update.fields:null}") + private String updateInfo; + + /** The core audit request builder. */ + @Autowired + private AuditLogRequestBuilder auditLogRequestBuilder; + + /** Mosip router for APIs */ + @Autowired + private MosipRouter router; + + @Autowired + private ObjectMapper mapper; + + @Autowired + private IdrepoDraftService idrepoDraftService; + + /** The registration processor rest client service. */ + @Autowired + private RegistrationProcessorRestClientService registrationProcessorRestClientService; + + /** The demographic dedupe repository. */ + @Autowired + private BasePacketRepository regLostUinDetEntity; + + /** The registration status service. */ + @Autowired + private RegistrationStatusService registrationStatusService; + + /** The utility. */ + @Autowired + private Utilities utility; + + @Autowired + private CbeffUtil cbeffutil; + + @Autowired + private RegistrationExceptionMapperUtil registrationStatusMapperUtil; + + @Autowired + private ABISHandlerUtil aBISHandlerUtil; + + @Autowired + private PriorityBasedPacketManagerService packetManagerService; + + @Autowired + private IdSchemaUtil idSchemaUtil; + + @Autowired + private ObjectMapper objectMapper; + + private TrimExceptionMessage trimExceptionMessage = new TrimExceptionMessage(); + + /* + * (non-Javadoc) + * + * @see + * io.mosip.registration.processor.core.spi.eventbus.EventBusManager#process( + * java.lang.Object) + */ + @SuppressWarnings("unchecked") + @Override + public MessageDTO process(MessageDTO object) { + boolean isTransactionSuccessful = Boolean.FALSE; + object.setMessageBusAddress(MessageBusAddress.UIN_GENERATION_BUS_IN); + object.setInternalError(Boolean.FALSE); + object.setIsValid(Boolean.TRUE); + LogDescription description = new LogDescription(); + String registrationId = object.getRid(); + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + registrationId, "UinGeneratorStage::process()::entry"); + UinGenResponseDto uinResponseDto = null; + + InternalRegistrationStatusDto registrationStatusDto = registrationStatusService.getRegistrationStatus( + registrationId, object.getReg_type(), object.getIteration(), object.getWorkflowInstanceId()); + try { + registrationStatusDto + .setLatestTransactionTypeCode(RegistrationTransactionTypeCode.UIN_GENERATOR.toString()); + registrationStatusDto.setRegistrationStageName(getStageName()); + + if ((RegistrationType.LOST.toString()).equalsIgnoreCase(object.getReg_type())) { + String lostPacketRegId = object.getRid(); + String matchedRegId = regLostUinDetEntity.getLostUinMatchedRegIdByWorkflowId(object.getWorkflowInstanceId()); + + if (matchedRegId != null) { + regProcLogger.info("Match for lostPacketRegId"+lostPacketRegId +"is "+matchedRegId); + lostAndUpdateUin(lostPacketRegId, matchedRegId, registrationStatusDto.getRegistrationType(), object, description); + } + + } else { + + IdResponseDTO idResponseDTO = new IdResponseDTO(); + String schemaVersion = packetManagerService.getFieldByMappingJsonKey(registrationId, MappingJsonConstants.IDSCHEMA_VERSION, registrationStatusDto.getRegistrationType(), ProviderStageName.UIN_GENERATOR); + + Map fieldMap = packetManagerService.getFields(registrationId, + idSchemaUtil.getDefaultFields(Double.valueOf(schemaVersion)), registrationStatusDto.getRegistrationType(), ProviderStageName.UIN_GENERATOR); + String uinField = fieldMap.get(utility.getMappingJsonValue(MappingJsonConstants.UIN, MappingJsonConstants.IDENTITY)); + + JSONObject demographicIdentity = new JSONObject(); + demographicIdentity.put(MappingJsonConstants.IDSCHEMA_VERSION, convertIdschemaToDouble ? Double.valueOf(schemaVersion) : schemaVersion); + + loadDemographicIdentity(fieldMap, demographicIdentity); + + if (StringUtils.isEmpty(uinField) || uinField.equalsIgnoreCase("null") ) { + + idResponseDTO = sendIdRepoWithUin(registrationId, registrationStatusDto.getRegistrationType(), demographicIdentity, + uinField); + + boolean isUinAlreadyPresent = isUinAlreadyPresent(idResponseDTO, registrationId); + + if (isIdResponseNotNull(idResponseDTO) || isUinAlreadyPresent) { + registrationStatusDto.setStatusComment(StatusUtil.UIN_GENERATED_SUCCESS.getMessage()); + registrationStatusDto.setSubStatusCode(StatusUtil.UIN_GENERATED_SUCCESS.getCode()); + isTransactionSuccessful = true; + registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); + description.setMessage(PlatformSuccessMessages.RPR_UIN_GENERATOR_STAGE_SUCCESS.getMessage()); + description.setCode(PlatformSuccessMessages.RPR_UIN_GENERATOR_STAGE_SUCCESS.getCode()); + description.setTransactionStatusCode(RegistrationTransactionStatusCode.SUCCESS.toString()); + + } else { + List errors = idResponseDTO != null ? idResponseDTO.getErrors() : null; + String statusComment = errors != null ? errors.get(0).getMessage() + : UINConstants.NULL_IDREPO_RESPONSE; + int unknownErrorCount=0; + for(ErrorDTO dto:errors) { + if(dto.getErrorCode().equalsIgnoreCase("IDR-IDC-004")||dto.getErrorCode().equalsIgnoreCase("IDR-IDC-001")) { + unknownErrorCount++; + } + } + if(unknownErrorCount>0) { + registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); + registrationStatusDto.setLatestTransactionStatusCode(registrationStatusMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.PACKET_UIN_GENERATION_REPROCESS)); + description.setTransactionStatusCode(registrationStatusMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.PACKET_UIN_GENERATION_REPROCESS)); + } + else { + registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.toString()); + registrationStatusDto.setLatestTransactionStatusCode(registrationStatusMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.PACKET_UIN_GENERATION_FAILED)); + description.setTransactionStatusCode(registrationStatusMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.PACKET_UIN_GENERATION_FAILED)); + } + registrationStatusDto.setStatusComment(trimExceptionMessage + .trimExceptionMessage(StatusUtil.UIN_GENERATION_FAILED.getMessage() + statusComment)); + object.setInternalError(Boolean.TRUE); + isTransactionSuccessful = false; + description.setMessage(PlatformErrorMessages.RPR_UGS_UIN_UPDATE_FAILURE.getMessage()); + description.setCode(PlatformErrorMessages.RPR_UGS_UIN_UPDATE_FAILURE.getCode()); + description.setSubStatusCode(StatusUtil.UIN_GENERATION_FAILED.getCode()); + String idres = idResponseDTO != null ? idResponseDTO.toString() + : UINConstants.NULL_IDREPO_RESPONSE; + + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString(), registrationId, + statusComment + " : " + idres); + object.setIsValid(Boolean.FALSE); + } + + } else { + if ((RegistrationType.ACTIVATED.toString()).equalsIgnoreCase(object.getReg_type())) { + isTransactionSuccessful = reActivateUin(idResponseDTO, registrationId, uinField, object, + demographicIdentity, description); + } else if ((RegistrationType.DEACTIVATED.toString()) + .equalsIgnoreCase(object.getReg_type())) { + idResponseDTO = deactivateUin(registrationId, uinField, object, demographicIdentity, + description); + } else if (RegistrationType.UPDATE.toString().equalsIgnoreCase(object.getReg_type()) + || (RegistrationType.RES_UPDATE.toString() + .equalsIgnoreCase(object.getReg_type()))) { + isTransactionSuccessful = uinUpdate(registrationId, registrationStatusDto.getRegistrationType(), uinField, object, demographicIdentity, + description); + } + } + + } + regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + registrationId, description.getMessage()); + registrationStatusDto.setUpdatedBy(UINConstants.USER); + + } catch (io.mosip.kernel.core.util.exception.JsonProcessingException e) { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + registrationId, + RegistrationStatusCode.FAILED.toString() + e.getMessage() + ExceptionUtils.getStackTrace(e)); + registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.toString()); + registrationStatusDto.setStatusComment( + trimExceptionMessage.trimExceptionMessage(StatusUtil.JSON_PARSING_EXCEPTION.getMessage() + e.getMessage())); + registrationStatusDto.setSubStatusCode(StatusUtil.JSON_PARSING_EXCEPTION.getCode()); + registrationStatusDto.setLatestTransactionStatusCode( + registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.JSON_PROCESSING_EXCEPTION)); + isTransactionSuccessful = false; + description.setMessage(PlatformErrorMessages.RPR_SYS_JSON_PARSING_EXCEPTION.getMessage()); + description.setCode(PlatformErrorMessages.RPR_SYS_JSON_PARSING_EXCEPTION.getCode()); + object.setInternalError(Boolean.TRUE); + object.setRid(registrationStatusDto.getRegistrationId()); + } catch (PacketManagerException e) { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + registrationId, + RegistrationStatusCode.PROCESSING.toString() + e.getMessage() + ExceptionUtils.getStackTrace(e)); + registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.name()); + registrationStatusDto.setStatusComment( + trimExceptionMessage.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()); + object.setInternalError(Boolean.TRUE); + object.setRid(registrationStatusDto.getRegistrationId()); + } catch (ApisResourceAccessException ex) { + registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.name()); + registrationStatusDto.setStatusComment(trimExceptionMessage + .trimExceptionMessage(StatusUtil.API_RESOUCE_ACCESS_FAILED.getMessage() + ex.getMessage())); + registrationStatusDto.setSubStatusCode(StatusUtil.API_RESOUCE_ACCESS_FAILED.getCode()); + registrationStatusDto.setLatestTransactionStatusCode(registrationStatusMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.APIS_RESOURCE_ACCESS_EXCEPTION)); + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + registrationId, + RegistrationStatusCode.PROCESSING.toString() + ex.getMessage() + ExceptionUtils.getStackTrace(ex)); + object.setInternalError(Boolean.TRUE); + description.setMessage(trimExceptionMessage + .trimExceptionMessage(StatusUtil.API_RESOUCE_ACCESS_FAILED.getMessage() + ex.getMessage())); + description.setCode(PlatformErrorMessages.RPR_UGS_API_RESOURCE_EXCEPTION.getCode()); + + } catch (IOException e) { + registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.name()); + registrationStatusDto.setStatusComment( + trimExceptionMessage.trimExceptionMessage(StatusUtil.IO_EXCEPTION.getMessage() + e.getMessage())); + registrationStatusDto.setSubStatusCode(StatusUtil.IO_EXCEPTION.getCode()); + registrationStatusDto.setLatestTransactionStatusCode( + registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.PACKET_UIN_GENERATION_REPROCESS)); + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + registrationId, + PlatformErrorMessages.RPR_SYS_IO_EXCEPTION.getMessage() + ExceptionUtils.getStackTrace(e)); + object.setInternalError(Boolean.TRUE); + description.setMessage(PlatformErrorMessages.RPR_SYS_IO_EXCEPTION.getMessage()); + description.setCode(PlatformErrorMessages.RPR_SYS_IO_EXCEPTION.getCode()); + } catch (IdrepoDraftException e) { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + registrationId, + RegistrationStatusCode.PROCESSING.toString() + e.getMessage() + ExceptionUtils.getStackTrace(e)); + registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.name()); + registrationStatusDto.setStatusComment( + trimExceptionMessage.trimExceptionMessage(StatusUtil.IDREPO_DRAFT_EXCEPTION.getMessage() + e.getMessage())); + registrationStatusDto.setSubStatusCode(StatusUtil.IDREPO_DRAFT_EXCEPTION.getCode()); + registrationStatusDto.setLatestTransactionStatusCode( + registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.IDREPO_DRAFT_EXCEPTION)); + description.setMessage(PlatformErrorMessages.IDREPO_DRAFT_EXCEPTION.getMessage()); + description.setCode(PlatformErrorMessages.IDREPO_DRAFT_EXCEPTION.getCode()); + object.setInternalError(Boolean.TRUE); + object.setRid(registrationStatusDto.getRegistrationId()); + } catch (IdrepoDraftReprocessableException e) { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + registrationId, + RegistrationStatusCode.PROCESSING.toString() + e.getMessage() + ExceptionUtils.getStackTrace(e)); + registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.name()); + registrationStatusDto.setStatusComment(trimExceptionMessage + .trimExceptionMessage( + StatusUtil.IDREPO_DRAFT_REPROCESSABLE_EXCEPTION.getMessage() + e.getMessage())); + registrationStatusDto.setSubStatusCode(StatusUtil.IDREPO_DRAFT_REPROCESSABLE_EXCEPTION.getCode()); + registrationStatusDto.setLatestTransactionStatusCode( + registrationStatusMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.IDREPO_DRAFT_REPROCESSABLE_EXCEPTION)); + description.setMessage(PlatformErrorMessages.IDREPO_DRAFT_EXCEPTION.getMessage()); + description.setCode(PlatformErrorMessages.IDREPO_DRAFT_EXCEPTION.getCode()); + object.setInternalError(Boolean.TRUE); + object.setRid(registrationStatusDto.getRegistrationId()); + } catch (Exception ex) { + registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.name()); + registrationStatusDto.setStatusComment( + trimExceptionMessage.trimExceptionMessage(StatusUtil.UNKNOWN_EXCEPTION_OCCURED.getMessage())); + registrationStatusDto.setSubStatusCode(StatusUtil.UNKNOWN_EXCEPTION_OCCURED.getCode()); + registrationStatusDto.setLatestTransactionStatusCode( + registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.PACKET_UIN_GENERATION_REPROCESS)); + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + registrationId, + RegistrationStatusCode.PROCESSING.toString() + ex.getMessage() + ExceptionUtils.getStackTrace(ex)); + object.setInternalError(Boolean.TRUE); + description.setMessage(PlatformErrorMessages.RPR_BDD_UNKNOWN_EXCEPTION.getMessage()); + description.setCode(PlatformErrorMessages.RPR_BDD_UNKNOWN_EXCEPTION.getCode()); + } finally { + if (description.getStatusComment() != null) + registrationStatusDto.setStatusComment(description.getStatusComment()); + if (description.getStatusCode() != null) + registrationStatusDto.setStatusCode(description.getStatusCode()); + if (description.getSubStatusCode() != null) + registrationStatusDto.setSubStatusCode(description.getSubStatusCode()); + if (description.getTransactionStatusCode() != null) + registrationStatusDto.setLatestTransactionStatusCode(description.getTransactionStatusCode()); + + if (object.getInternalError()) { + updateErrorFlags(registrationStatusDto, object); + } + String moduleId = isTransactionSuccessful + ? PlatformSuccessMessages.RPR_UIN_GENERATOR_STAGE_SUCCESS.getCode() + : description.getCode(); + String moduleName = ModuleName.UIN_GENERATOR.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, registrationId); + + } + + return object; + } + + private void loadDemographicIdentity(Map fieldMap, JSONObject demographicIdentity) throws IOException, JSONException { + for (Map.Entry e : fieldMap.entrySet()) { + if (e.getValue() != null) { + String value = e.getValue().toString(); + if (value != null) { + Object json = new JSONTokener(value).nextValue(); + if (json instanceof org.json.JSONObject) { + HashMap hashMap = objectMapper.readValue(value, HashMap.class); + demographicIdentity.putIfAbsent(e.getKey(), hashMap); + } + else if (json instanceof JSONArray) { + List jsonList = new ArrayList<>(); + JSONArray jsonArray = new JSONArray(value); + for (int i = 0; i < jsonArray.length(); i++) { + Object obj = jsonArray.get(i); + HashMap hashMap = objectMapper.readValue(obj.toString(), HashMap.class); + jsonList.add(hashMap); + } + demographicIdentity.putIfAbsent(e.getKey(), jsonList); + } else + demographicIdentity.putIfAbsent(e.getKey(), value); + } else + demographicIdentity.putIfAbsent(e.getKey(), value); + } + } + } + + /** + * Send id repo with uin. + * + * @param id + * the reg id + * @param uin + * the uin + * @throws ApisResourceAccessException + * @throws IOException + * @throws JsonMappingException + * @throws JsonParseException + * @throws VidCreationException + * @throws io.mosip.kernel.core.exception.IOException + * @throws Exception + */ + private IdResponseDTO sendIdRepoWithUin(String id, String process, JSONObject demographicIdentity, String uin) + throws Exception { + + List documentInfo = getAllDocumentsByRegId(id, process, demographicIdentity); + RequestDto requestDto = new RequestDto(); + requestDto.setIdentity(demographicIdentity); + requestDto.setDocuments(documentInfo); + requestDto.setRegistrationId(id); + requestDto.setStatus(RegistrationType.ACTIVATED.toString()); + requestDto.setBiometricReferenceId(uin); + + IdResponseDTO result = null; + IdRequestDto idRequestDTO = new IdRequestDto(); + idRequestDTO.setId(idRepoUpdate); + idRequestDTO.setRequest(requestDto); + idRequestDTO.setRequesttime(DateUtils.getUTCCurrentDateTimeString()); + idRequestDTO.setVersion(UINConstants.idRepoApiVersion); + idRequestDTO.setMetadata(null); + + try { + + result = idrepoDraftService.idrepoUpdateDraft(id, null, idRequestDTO); + + } catch (ApisResourceAccessException e) { + regProcLogger.error("Execption occured updating draft for id " + id, e); + if (e.getCause() instanceof HttpClientErrorException) { + HttpClientErrorException httpClientException = (HttpClientErrorException) e.getCause(); + throw new ApisResourceAccessException(httpClientException.getResponseBodyAsString(), + httpClientException); + } else if (e.getCause() instanceof HttpServerErrorException) { + HttpServerErrorException httpServerException = (HttpServerErrorException) e.getCause(); + throw new ApisResourceAccessException(httpServerException.getResponseBodyAsString(), + httpServerException); + } else { + throw e; + } + + } + return result; + + } + + /** + * Gets the all documents by reg id. + * + * @param regId + * the reg id + * @return the all documents by reg id + * @throws IOException + * @throws io.mosip.kernel.core.exception.IOException + * @throws ApisResourceAccessException + * @throws JsonMappingException + * @throws JsonParseException + */ + private List getAllDocumentsByRegId(String regId, String process, JSONObject demographicIdentity) throws Exception { + List applicantDocuments = new ArrayList<>(); + + JSONObject idJSON = demographicIdentity; + JSONObject docJson = utility.getRegistrationProcessorMappingJson(MappingJsonConstants.DOCUMENT); + JSONObject identityJson = utility.getRegistrationProcessorMappingJson(MappingJsonConstants.IDENTITY); + + String applicantBiometricLabel = JsonUtil.getJSONValue(JsonUtil.getJSONObject(identityJson, MappingJsonConstants.INDIVIDUAL_BIOMETRICS), MappingJsonConstants.VALUE); + + HashMap applicantBiometric = (HashMap) idJSON.get(applicantBiometricLabel); + + + for (Object doc : docJson.values()) { + Map docMap = (LinkedHashMap) doc; + String docValue = docMap.values().iterator().next().toString(); + HashMap docInIdentityJson = (HashMap) idJSON.get(docValue); + if (docInIdentityJson != null) + applicantDocuments + .add(getIdDocumnet(regId, docValue, process)); + } + + if (applicantBiometric != null) { + applicantDocuments.add(getBiometrics(regId, applicantBiometricLabel, process, applicantBiometricLabel)); + } + return applicantDocuments; + } + + private Documents getIdDocumnet(String registrationId, String dockey, String process) + throws IOException, ApisResourceAccessException, PacketManagerException, io.mosip.kernel.core.util.exception.JsonProcessingException { + Documents documentsInfoDto = new Documents(); + + Document document = + packetManagerService.getDocument(registrationId, dockey, process, ProviderStageName.UIN_GENERATOR); + if (document != null) { + documentsInfoDto.setValue(CryptoUtil.encodeToURLSafeBase64(document.getDocument())); + documentsInfoDto.setCategory(document.getValue()); + return documentsInfoDto; + } + return null; + } + + private Documents getBiometrics(String registrationId, String person, String process, String idDocLabel) throws Exception { + BiometricRecord biometricRecord = packetManagerService.getBiometrics(registrationId, person, process, ProviderStageName.UIN_GENERATOR); + byte[] xml = cbeffutil.createXML(biometricRecord.getSegments()); + Documents documentsInfoDto = new Documents(); + documentsInfoDto.setValue(CryptoUtil.encodeToURLSafeBase64(xml)); + documentsInfoDto.setCategory(utility.getMappingJsonValue(idDocLabel, MappingJsonConstants.IDENTITY)); + return documentsInfoDto; + + } + + /** + * Update id repo wit uin. + * + * @param regId the reg id + * @param uin the uin + * @param object the object + * @param description + * @return the id response DTO + * @throws ApisResourceAccessException the apis resource access + * exception + * @throws IOException Signals that an I/O exception + * has occurred. + * @throws RegistrationProcessorCheckedException + * @throws io.mosip.kernel.core.exception.IOException + */ + private boolean uinUpdate(String regId, String process, String uin, MessageDTO object, JSONObject demographicIdentity, LogDescription description) + throws Exception { + IdResponseDTO result; + boolean isTransactionSuccessful = Boolean.FALSE; + List documentInfo = getAllDocumentsByRegId(regId, process, demographicIdentity); + result = idRepoRequestBuilder(regId, uin, RegistrationType.ACTIVATED.toString().toUpperCase(), documentInfo, + demographicIdentity); + if (null!=result && isIdResponseNotNull(result)) { + + if (IDREPO_STATUS.equalsIgnoreCase(result.getResponse().getStatus())) { + isTransactionSuccessful = true; + description.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); + description.setStatusComment(StatusUtil.UIN_DATA_UPDATION_SUCCESS.getMessage()); + description.setSubStatusCode(StatusUtil.UIN_DATA_UPDATION_SUCCESS.getCode()); + description.setMessage( + StatusUtil.UIN_DATA_UPDATION_SUCCESS.getMessage() + " for registration Id: " + regId); + description.setTransactionStatusCode(RegistrationTransactionStatusCode.PROCESSED.toString()); + object.setIsValid(Boolean.TRUE); + } + } else { + String statusComment = result != null && result.getErrors() != null ? result.getErrors().get(0).getMessage() + : UINConstants.NULL_IDREPO_RESPONSE; + String message = result != null && result.getErrors() != null + ? result.getErrors().get(0).getMessage() + : UINConstants.NULL_IDREPO_RESPONSE; + description.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); + description.setStatusComment(trimExceptionMessage + .trimExceptionMessage(StatusUtil.UIN_DATA_UPDATION_FAILED.getMessage() + statusComment)); + description.setSubStatusCode(StatusUtil.UIN_DATA_UPDATION_FAILED.getCode()); + description + .setMessage(UINConstants.UIN_FAILURE + regId + "::" + message ); + description.setTransactionStatusCode(RegistrationTransactionStatusCode.PROCESSING.toString()); + object.setIsValid(Boolean.FALSE); + } + return isTransactionSuccessful; + } + + /** + * Id repo request builder. + * + * @param status the status + * @param id the reg id + * @param demographicIdentity the JSONObject + * @param documentInfo the document info + * @throws ApisResourceAccessException the apis resource access exception + * @throws IOException + * @throws IdrepoDraftReprocessableException + */ + private IdResponseDTO idRepoRequestBuilder(String id, String uin, String status, List documentInfo, + JSONObject demographicIdentity) + throws ApisResourceAccessException, IdrepoDraftException, IOException, IdrepoDraftReprocessableException { + IdResponseDTO idResponseDto; + RequestDto requestDto = new RequestDto(); + + if (documentInfo != null) + requestDto.setDocuments(documentInfo); + + requestDto.setRegistrationId(id); + requestDto.setStatus(status); + requestDto.setIdentity(demographicIdentity); + + IdRequestDto idRequestDTO = new IdRequestDto(); + idRequestDTO.setId(idRepoUpdate); + idRequestDTO.setMetadata(null); + idRequestDTO.setRequest(requestDto); + idRequestDTO.setRequesttime(DateUtils.getUTCCurrentDateTimeString()); + idRequestDTO.setVersion(UINConstants.idRepoApiVersion); + + try { + idResponseDto = idrepoDraftService.idrepoUpdateDraft(id, uin, idRequestDTO); + } catch (ApisResourceAccessException e) { + regProcLogger.error("Execption occured updating draft for id " + id, e); + if (e.getCause() instanceof HttpClientErrorException) { + regProcLogger.error("Exception occured updating draft for id " + id, e); + HttpClientErrorException httpClientException = (HttpClientErrorException) e.getCause(); + throw new ApisResourceAccessException(httpClientException.getResponseBodyAsString(), + httpClientException); + } else if (e.getCause() instanceof HttpServerErrorException) { + HttpServerErrorException httpServerException = (HttpServerErrorException) e.getCause(); + throw new ApisResourceAccessException(httpServerException.getResponseBodyAsString(), + httpServerException); + } else { + throw e; + } + + } + return idResponseDto; + } + + /** + * Re activate uin. + * + * @param id the reg id + * @param uin the uin + * @param object the object + * @param description + * @return the id response DTO + * @throws ApisResourceAccessException the apis resource access exception + * @throws IOException + * @throws IdrepoDraftReprocessableException + */ + private boolean reActivateUin(IdResponseDTO idResponseDTO, String id, String uin, MessageDTO object, + JSONObject demographicIdentity, LogDescription description) + throws ApisResourceAccessException, IOException, IdrepoDraftException, IdrepoDraftReprocessableException { + IdResponseDTO result = getIdRepoDataByUIN(uin, id, description); + List pathsegments = new ArrayList<>(); + RequestDto requestDto = new RequestDto(); + boolean isTransactionSuccessful = Boolean.FALSE; + + if (isIdResponseNotNull(result)) { + + if ((RegistrationType.ACTIVATED.toString()).equalsIgnoreCase(result.getResponse().getStatus())) { + + description.setStatusCode(RegistrationStatusCode.FAILED.toString()); + description.setStatusComment(StatusUtil.UIN_ALREADY_ACTIVATED.getMessage()); + description.setSubStatusCode(StatusUtil.UIN_ALREADY_ACTIVATED.getCode()); + description.setMessage(PlatformErrorMessages.UIN_ALREADY_ACTIVATED.getMessage()); + description.setCode(PlatformErrorMessages.UIN_ALREADY_ACTIVATED.getCode()); + description.setTransactionStatusCode(RegistrationTransactionStatusCode.FAILED.toString()); + object.setIsValid(Boolean.FALSE); + return isTransactionSuccessful; + + } else { + + requestDto.setRegistrationId(id); + requestDto.setStatus(RegistrationType.ACTIVATED.toString()); + requestDto.setBiometricReferenceId(uin); + requestDto.setIdentity(demographicIdentity); + + IdRequestDto idRequestDTO = new IdRequestDto(); + idRequestDTO.setId(idRepoUpdate); + idRequestDTO.setRequest(requestDto); + idRequestDTO.setMetadata(null); + idRequestDTO.setRequesttime(DateUtils.getUTCCurrentDateTimeString()); + idRequestDTO.setVersion(UINConstants.idRepoApiVersion); + + result = idrepoDraftService.idrepoUpdateDraft(id, uin, idRequestDTO); + + if (isIdResponseNotNull(result)) { + + if ((RegistrationType.ACTIVATED.toString()).equalsIgnoreCase(result.getResponse().getStatus())) { + isTransactionSuccessful = true; + description.setStatusCode(RegistrationStatusCode.PROCESSED.toString()); + description.setStatusComment(StatusUtil.UIN_ACTIVATED_SUCCESS.getMessage()); + description.setSubStatusCode(StatusUtil.UIN_ACTIVATED_SUCCESS.getCode()); + description.setMessage(StatusUtil.UIN_ACTIVATED_SUCCESS.getMessage() + id); + description.setMessage(PlatformSuccessMessages.RPR_UIN_ACTIVATED_SUCCESS.getMessage()); + description.setCode(PlatformSuccessMessages.RPR_UIN_ACTIVATED_SUCCESS.getCode()); + description.setTransactionStatusCode(RegistrationTransactionStatusCode.PROCESSED.toString()); + object.setIsValid(Boolean.TRUE); + } else { + description.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); + description.setStatusComment(StatusUtil.UIN_ACTIVATED_FAILED.getMessage()); + description.setSubStatusCode(StatusUtil.UIN_ACTIVATED_FAILED.getCode()); + description.setMessage(StatusUtil.UIN_ACTIVATED_FAILED.getMessage() + id); + description.setMessage(PlatformErrorMessages.UIN_ACTIVATED_FAILED.getMessage()); + description.setCode(PlatformErrorMessages.UIN_ACTIVATED_FAILED.getCode()); + description.setTransactionStatusCode(RegistrationTransactionStatusCode.REPROCESS.toString()); + object.setIsValid(Boolean.FALSE); + } + } else { + String statusComment = result != null && result.getErrors() != null + ? result.getErrors().get(0).getMessage() + : UINConstants.NULL_IDREPO_RESPONSE; + description.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); + description.setStatusComment(trimExceptionMessage + .trimExceptionMessage(StatusUtil.UIN_REACTIVATION_FAILED.getMessage() + statusComment)); + description.setSubStatusCode(StatusUtil.UIN_REACTIVATION_FAILED.getCode()); + description.setMessage( + UINConstants.UIN_FAILURE + id + "::" + (result != null && result.getErrors() != null + ? result.getErrors().get(0).getMessage() + : UINConstants.NULL_IDREPO_RESPONSE)); + description.setMessage(PlatformErrorMessages.UIN_REACTIVATION_FAILED.getMessage()); + description.setCode(PlatformErrorMessages.UIN_REACTIVATION_FAILED.getCode()); + description.setTransactionStatusCode(RegistrationTransactionStatusCode.REPROCESS.toString()); + object.setIsValid(Boolean.FALSE); + } + + } + + }else { + String statusComment = result != null && result.getErrors() != null + ? result.getErrors().get(0).getMessage() + : UINConstants.NULL_IDREPO_RESPONSE; + description.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); + description.setStatusComment(trimExceptionMessage + .trimExceptionMessage(StatusUtil.UIN_REACTIVATION_FAILED.getMessage() + statusComment)); + description.setSubStatusCode(StatusUtil.UIN_REACTIVATION_FAILED.getCode()); + description.setMessage( + UINConstants.UIN_FAILURE + id + "::" + (result != null && result.getErrors() != null + ? result.getErrors().get(0).getMessage() + : UINConstants.NULL_IDREPO_RESPONSE)); + description.setMessage(PlatformErrorMessages.UIN_REACTIVATION_FAILED.getMessage()); + description.setCode(PlatformErrorMessages.UIN_REACTIVATION_FAILED.getCode()); + description.setTransactionStatusCode(RegistrationTransactionStatusCode.REPROCESS.toString()); + object.setIsValid(Boolean.FALSE); + } + + return isTransactionSuccessful; + } + + private boolean isIdResponseNotNull(IdResponseDTO result) { + return result != null && result.getResponse() != null; + } + + private boolean isUinAlreadyPresent(IdResponseDTO result, String rid) { + if (result != null && result.getErrors() != null && result.getErrors().size() > 0 + && result.getErrors().get(0).getErrorCode().equalsIgnoreCase(RECORD_ALREADY_EXISTS_ERROR)) { + ErrorDTO errorDTO = result.getErrors().get(0); + regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString() + rid, + "Record is already present in IDREPO. Error message received : " + errorDTO.getMessage(), + "The stage will ignore this error and try to generate vid for the existing UIN now. " + + "This is to make sure if the packet processing fails while generating VID then re-processor can process the packet again"); + return true; + } + return false; + } + + /** + * Deactivate uin. + * + * @param id the reg id + * @param uin the uin + * @param object the object + * @param description + * @return the id response DTO + * @throws ApisResourceAccessException + * @throws IOException + * @throws IdrepoDraftReprocessableException + */ + private IdResponseDTO deactivateUin(String id, String uin, MessageDTO object, JSONObject demographicIdentity, + LogDescription description) + throws ApisResourceAccessException, IOException, IdrepoDraftException, IdrepoDraftReprocessableException { + IdResponseDTO idResponseDto; + RequestDto requestDto = new RequestDto(); + String statusComment = ""; + + idResponseDto = getIdRepoDataByUIN(uin, id, description); + + if (idResponseDto.getResponse() != null + && idResponseDto.getResponse().getStatus().equalsIgnoreCase(RegistrationType.DEACTIVATED.toString())) { + description.setStatusCode(RegistrationStatusCode.FAILED.toString()); + description.setStatusComment(StatusUtil.UIN_ALREADY_DEACTIVATED.getMessage()); + description.setSubStatusCode(StatusUtil.UIN_ALREADY_DEACTIVATED.getCode()); + description.setMessage(StatusUtil.UIN_ALREADY_DEACTIVATED.getMessage() + id); + description.setMessage(PlatformErrorMessages.UIN_ALREADY_DEACTIVATED.getMessage()); + description.setCode(PlatformErrorMessages.UIN_ALREADY_DEACTIVATED.getCode()); + description.setTransactionStatusCode(RegistrationTransactionStatusCode.FAILED.toString()); + object.setIsValid(Boolean.FALSE); + return idResponseDto; + + } else { + requestDto.setRegistrationId(id); + requestDto.setStatus(RegistrationType.DEACTIVATED.toString()); + requestDto.setIdentity(demographicIdentity); + requestDto.setBiometricReferenceId(uin); + + IdRequestDto idRequestDTO = new IdRequestDto(); + idRequestDTO.setId(idRepoUpdate); + idRequestDTO.setMetadata(null); + idRequestDTO.setRequest(requestDto); + idRequestDTO.setRequesttime(DateUtils.getUTCCurrentDateTimeString()); + idRequestDTO.setVersion(UINConstants.idRepoApiVersion); + + idResponseDto = idrepoDraftService.idrepoUpdateDraft(id, uin, idRequestDTO); + + if (isIdResponseNotNull(idResponseDto)) { + if (idResponseDto.getResponse().getStatus().equalsIgnoreCase(RegistrationType.DEACTIVATED.toString())) { + description.setStatusCode(RegistrationStatusCode.PROCESSED.toString()); + description.setStatusComment(StatusUtil.UIN_DEACTIVATION_SUCCESS.getMessage()); + description.setSubStatusCode(StatusUtil.UIN_DEACTIVATION_SUCCESS.getCode()); + description.setMessage(StatusUtil.UIN_DEACTIVATION_SUCCESS.getMessage() + id); + description.setMessage(PlatformSuccessMessages.RPR_UIN_DEACTIVATION_SUCCESS.getMessage()); + description.setCode(PlatformSuccessMessages.RPR_UIN_DEACTIVATION_SUCCESS.getCode()); + description.setTransactionStatusCode(RegistrationTransactionStatusCode.PROCESSED.toString()); + object.setIsValid(Boolean.TRUE); + statusComment = idResponseDto.getResponse().getStatus().toString(); + + } + } else { + + statusComment = idResponseDto != null && idResponseDto.getErrors() != null + ? idResponseDto.getErrors().get(0).getMessage() + : UINConstants.NULL_IDREPO_RESPONSE; + description.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); + description.setStatusComment(trimExceptionMessage + .trimExceptionMessage(StatusUtil.UIN_DEACTIVATION_FAILED.getMessage() + statusComment)); + description.setSubStatusCode(StatusUtil.UIN_DEACTIVATION_FAILED.getCode()); + description.setMessage(PlatformErrorMessages.UIN_DEACTIVATION_FAILED.getMessage()); + description.setCode(PlatformErrorMessages.UIN_DEACTIVATION_FAILED.getCode()); + description.setTransactionStatusCode(RegistrationTransactionStatusCode.REPROCESS.toString()); + object.setIsValid(Boolean.FALSE); + } + + } + regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString() + id, "Updated Response from IdRepo API", + "is : " + statusComment); + + return idResponseDto; + } + + /** + * Gets the id repo data by UIN. + * + * @param uin + * the uin + * @param description + * @return the id repo data by UIN + * @throws ApisResourceAccessException + * the apis resource access exception + * @throws IOException + */ + private IdResponseDTO getIdRepoDataByUIN(String uin, String regId, LogDescription description) + throws ApisResourceAccessException { + IdResponseDTO response; + + List pathsegments = new ArrayList<>(); + pathsegments.add(uin); + try { + + response = (IdResponseDTO) registrationProcessorRestClientService.getApi(ApiName.IDREPOGETIDBYUIN, + pathsegments, "", "", IdResponseDTO.class); + + } catch (ApisResourceAccessException e) { + if (e.getCause() instanceof HttpClientErrorException) { + HttpClientErrorException httpClientException = (HttpClientErrorException) e.getCause(); + description.setMessage(PlatformErrorMessages.UIN_GENERATION_FAILED.getMessage()); + description.setCode(PlatformErrorMessages.UIN_GENERATION_FAILED.getCode()); + throw new ApisResourceAccessException(httpClientException.getResponseBodyAsString(), + httpClientException); + } else if (e.getCause() instanceof HttpServerErrorException) { + HttpServerErrorException httpServerException = (HttpServerErrorException) e.getCause(); + description.setMessage(PlatformErrorMessages.UIN_GENERATION_FAILED.getMessage()); + description.setCode(PlatformErrorMessages.UIN_GENERATION_FAILED.getCode()); + + throw new ApisResourceAccessException(httpServerException.getResponseBodyAsString(), + httpServerException); + } else { + description.setMessage(PlatformErrorMessages.UIN_GENERATION_FAILED.getMessage()); + description.setCode(PlatformErrorMessages.UIN_GENERATION_FAILED.getCode()); + throw e; + } + } + return response; + } + + /** + * Deploy verticle. + */ + public void deployVerticle() { + + mosipEventBus = this.getEventBus(this, clusterManagerUrl, workerPoolSize); + this.consumeAndSend(mosipEventBus, MessageBusAddress.UIN_GENERATION_BUS_IN, + MessageBusAddress.UIN_GENERATION_BUS_OUT, messageExpiryTimeLimit); + } + + @Override + public void start() { + router.setRoute(this.postUrl(getVertx(), MessageBusAddress.UIN_GENERATION_BUS_IN, + MessageBusAddress.UIN_GENERATION_BUS_OUT)); + this.createServer(router.getRouter(), getPort()); + + } + + @Override + protected String getPropertyPrefix() { + return STAGE_PROPERTY_PREFIX; + } + + /** + * Link reg id wrt uin. + * + * @param lostPacketRegId the lost packet reg id + * @param matchedRegId the matched reg id + * @param object the object + * @param description + * @return the id response DTO + * @throws ApisResourceAccessException the apis resource access exception + * @throws IOException Signals that an I/O exception has + * occurred. + * @throws IdrepoDraftReprocessableException + */ + @SuppressWarnings("unchecked") + private IdResponseDTO lostAndUpdateUin(String lostPacketRegId, String matchedRegId, String process, MessageDTO object, + LogDescription description) throws ApisResourceAccessException, IOException, + io.mosip.kernel.core.util.exception.JsonProcessingException, PacketManagerException, IdrepoDraftException, + IdrepoDraftReprocessableException { + + IdResponseDTO idResponse = null; + String uin = idRepoService.getUinByRid(matchedRegId, utility.getGetRegProcessorDemographicIdentity()); + + + RequestDto requestDto = new RequestDto(); + String statusComment = ""; + + if (uin != null) { + + JSONObject regProcessorIdentityJson = utility.getRegistrationProcessorMappingJson(MappingJsonConstants.IDENTITY); + String idschemaversion = JsonUtil.getJSONValue(JsonUtil.getJSONObject(regProcessorIdentityJson, MappingJsonConstants.IDSCHEMA_VERSION), MappingJsonConstants.VALUE); + + JSONObject identityObject = new JSONObject(); + identityObject.put(UINConstants.UIN, uin); + String schemaVersion = packetManagerService.getFieldByMappingJsonKey(lostPacketRegId, MappingJsonConstants.IDSCHEMA_VERSION, process, ProviderStageName.UIN_GENERATOR); + identityObject.put(idschemaversion, convertIdschemaToDouble ? Double.valueOf(schemaVersion) : schemaVersion); + regProcLogger.info("Fields to be updated "+updateInfo); + if (null != updateInfo && !updateInfo.isEmpty()) { + String[] upd = updateInfo.split(","); + for (String infoField : upd) { + String fldValue = packetManagerService.getField(lostPacketRegId, infoField, process, + ProviderStageName.UIN_GENERATOR); + if (null != fldValue) + identityObject.put(infoField, fldValue); + } + } + requestDto.setRegistrationId(lostPacketRegId); + requestDto.setIdentity(identityObject); + + IdRequestDto idRequestDTO = new IdRequestDto(); + idRequestDTO.setId(idRepoUpdate); + idRequestDTO.setRequest(requestDto); + idRequestDTO.setMetadata(null); + idRequestDTO.setRequesttime(DateUtils.getUTCCurrentDateTimeString()); + idRequestDTO.setVersion(UINConstants.idRepoApiVersion); + + idResponse = idrepoDraftService.idrepoUpdateDraft(lostPacketRegId, uin, idRequestDTO); + + if (isIdResponseNotNull(idResponse)) { + description.setStatusCode(RegistrationStatusCode.PROCESSED.toString()); + description.setStatusComment(StatusUtil.LINK_RID_FOR_LOST_PACKET_SUCCESS.getMessage()); + description.setSubStatusCode(StatusUtil.LINK_RID_FOR_LOST_PACKET_SUCCESS.getCode()); + description.setMessage(UinStatusMessage.PACKET_LOST_UIN_UPDATION_SUCCESS_MSG + lostPacketRegId); + description.setTransactionStatusCode(RegistrationTransactionStatusCode.PROCESSED.toString()); + object.setIsValid(Boolean.TRUE); + + regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString() + lostPacketRegId, + " UIN LINKED WITH " + matchedRegId, "is : " + description); + } else { + + statusComment = idResponse != null && idResponse.getErrors() != null + && idResponse.getErrors().get(0) != null ? idResponse.getErrors().get(0).getMessage() + : UinStatusMessage.PACKET_LOST_UIN_UPDATION_FAILURE_MSG + " " + + UINConstants.NULL_IDREPO_RESPONSE + "for lostPacketRegId " + lostPacketRegId; + description.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); + description.setStatusComment(StatusUtil.LINK_RID_FOR_LOST_PACKET_SUCCESS.getMessage() + statusComment); + description.setSubStatusCode(StatusUtil.LINK_RID_FOR_LOST_PACKET_SUCCESS.getCode()); + description.setTransactionStatusCode(registrationStatusMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.PACKET_UIN_GENERATION_ID_REPO_ERROR)); + if (idResponse != null + && idResponse.getErrors() != null) + description.setMessage(idResponse.getErrors().get(0).getMessage()); + else + description.setMessage(UINConstants.NULL_IDREPO_RESPONSE); + object.setIsValid(Boolean.FALSE); + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString() + lostPacketRegId, + " UIN NOT LINKED WITH " + matchedRegId, "is : " + statusComment); + } + + } else { + statusComment = UinStatusMessage.PACKET_LOST_UIN_UPDATION_FAILURE_MSG + " " + + UINConstants.NULL_IDREPO_RESPONSE + " UIN not available for matchedRegId " + matchedRegId; + description.setStatusComment(StatusUtil.LINK_RID_FOR_LOST_PACKET_FAILED.getMessage()); + description.setSubStatusCode(StatusUtil.LINK_RID_FOR_LOST_PACKET_FAILED.getCode()); + description.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); + description.setTransactionStatusCode(registrationStatusMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.PACKET_UIN_GENERATION_REPROCESS)); + description.setMessage(UinStatusMessage.PACKET_LOST_UIN_UPDATION_FAILURE_MSG + " " + + UINConstants.NULL_IDREPO_RESPONSE + " UIN not available for matchedRegId " + matchedRegId); + + object.setIsValid(Boolean.FALSE); + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString() + lostPacketRegId, + " UIN NOT LINKED WITH " + matchedRegId, "is : " + statusComment); + } + + return idResponse; + } + + private void updateErrorFlags(InternalRegistrationStatusDto registrationStatusDto, MessageDTO object) { + object.setInternalError(true); + if (registrationStatusDto.getLatestTransactionStatusCode() + .equalsIgnoreCase(RegistrationTransactionStatusCode.REPROCESS.toString())) { + object.setIsValid(true); + } else { + object.setIsValid(false); + } + } +} 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 933b45eeb93..b57952a8d2a 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 @@ -85,6 +85,7 @@ 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; @@ -969,7 +970,8 @@ public void testApiResourceExceptionInUpdateIdRepoTest() throws Exception { } @Test - public void deactivateTestSuccess() throws ApisResourceAccessException, IOException, JSONException, JsonProcessingException, PacketManagerException, IdrepoDraftException { + public void deactivateTestSuccess() throws ApisResourceAccessException, IOException, JSONException, + JsonProcessingException, PacketManagerException, IdrepoDraftException, IdrepoDraftReprocessableException { Map fieldMap = new HashMap<>(); fieldMap.put("UIN", "123456"); @@ -1056,7 +1058,8 @@ public void checkIsUinDeactivatedSuccess() throws ApisResourceAccessException, I assertFalse(result.getInternalError()); } @Test - public void deactivateTestWithDeactivate() throws ApisResourceAccessException, IOException, JSONException, JsonProcessingException, PacketManagerException, IdrepoDraftException { + public void deactivateTestWithDeactivate() throws ApisResourceAccessException, IOException, JSONException, + JsonProcessingException, PacketManagerException, IdrepoDraftException, IdrepoDraftReprocessableException { Map fieldMap = new HashMap<>(); fieldMap.put("UIN", "123456"); fieldMap.put("name", "mono"); @@ -1105,7 +1108,9 @@ public void deactivateTestWithDeactivate() throws ApisResourceAccessException, I } @Test - public void deactivateTestWithNullResponseDTO() throws ApisResourceAccessException, PacketManagerException, IOException, JsonProcessingException, JSONException, IdrepoDraftException { + public void deactivateTestWithNullResponseDTO() + throws ApisResourceAccessException, PacketManagerException, IOException, JsonProcessingException, + JSONException, IdrepoDraftException, IdrepoDraftReprocessableException { Map fieldMap = new HashMap<>(); fieldMap.put("UIN", "123456"); fieldMap.put("name", "mono"); @@ -1152,7 +1157,9 @@ public void deactivateTestWithNullResponseDTO() throws ApisResourceAccessExcepti } @Test - public void deactivateTestForExistingUinTestSuccess() throws ApisResourceAccessException, PacketManagerException, IOException, JsonProcessingException, JSONException, IdrepoDraftException { + 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()); @@ -1202,7 +1209,8 @@ public void deactivateTestForExistingUinTestSuccess() throws ApisResourceAccessE } @Test - public void deactivateTestFailure() throws ApisResourceAccessException, PacketManagerException, IOException, JsonProcessingException, JSONException, IdrepoDraftException { + public void deactivateTestFailure() throws ApisResourceAccessException, PacketManagerException, IOException, + JsonProcessingException, JSONException, IdrepoDraftException, IdrepoDraftReprocessableException { Map fieldMap = new HashMap<>(); fieldMap.put("UIN", "123456"); @@ -1262,7 +1270,8 @@ public void deactivateTestFailure() throws ApisResourceAccessException, PacketMa } @Test - public void apisResourceAccessExceptionTest() throws ApisResourceAccessException, IOException, IdrepoDraftException { + public void apisResourceAccessExceptionTest() + throws ApisResourceAccessException, IOException, IdrepoDraftException, IdrepoDraftReprocessableException { ApisResourceAccessException apisResourceAccessException = Mockito.mock(ApisResourceAccessException.class); HttpServerErrorException httpServerErrorException = new HttpServerErrorException( @@ -1379,7 +1388,8 @@ public void testUinGenerationHttpServerErrorException() throws Exception { @Test - public void clientErrorExceptionTest() throws ApisResourceAccessException, IOException, IdrepoDraftException { + public void clientErrorExceptionTest() + throws ApisResourceAccessException, IOException, IdrepoDraftException, IdrepoDraftReprocessableException { ApisResourceAccessException apisResourceAccessException = Mockito.mock(ApisResourceAccessException.class); HttpClientErrorException httpErrorErrorException = new HttpClientErrorException( @@ -1423,7 +1433,8 @@ public void testDeployVerticle() { @Test @Ignore - public void testApiResourceException() throws ApisResourceAccessException, IOException, IdrepoDraftException { + public void testApiResourceException() + throws ApisResourceAccessException, IOException, IdrepoDraftException, IdrepoDraftReprocessableException { MessageDTO messageDTO = new MessageDTO(); messageDTO.setRid("10031100110005020190313110030"); messageDTO.setReg_type(RegistrationType.valueOf("DEACTIVATED").name()); @@ -1451,7 +1462,8 @@ public void testApiResourceException() throws ApisResourceAccessException, IOExc } @Test - public void testApisResourceAccessExceptionPostApi() throws ApisResourceAccessException, IOException, IdrepoDraftException { + public void testApisResourceAccessExceptionPostApi() + throws ApisResourceAccessException, IOException, IdrepoDraftException, IdrepoDraftReprocessableException { ApisResourceAccessException exc = new ApisResourceAccessException(); MessageDTO messageDTO = new MessageDTO(); messageDTO.setRid("27847657360002520181210094052"); @@ -1585,7 +1597,8 @@ public void testLinkSuccessForLostUinAndUpdateContactInfo() throws Exception { } @Test - public void updateTestSuccess() throws ApisResourceAccessException, IOException, JsonProcessingException, PacketManagerException, JSONException, IdrepoDraftException { + public void updateTestSuccess() throws ApisResourceAccessException, IOException, JsonProcessingException, + PacketManagerException, JSONException, IdrepoDraftException, IdrepoDraftReprocessableException { Map fieldMap = new HashMap<>(); fieldMap.put("UIN", "123456"); fieldMap.put("name", "mono"); @@ -1980,7 +1993,8 @@ public void testUinReActivationWithoutIDResponseDTO() throws Exception { @Test public void deactivateTestWithNullResponseDTOBeforeDeactivate() throws ApisResourceAccessException, PacketManagerException, - IOException, JsonProcessingException, JSONException, IdrepoDraftException { + IOException, JsonProcessingException, JSONException, IdrepoDraftException, + IdrepoDraftReprocessableException { Map fieldMap = new HashMap<>(); fieldMap.put("UIN", "123456"); fieldMap.put("name", "mono"); @@ -2029,7 +2043,8 @@ public void deactivateTestWithNullResponseDTOBeforeDeactivate() throws ApisResou @Test public void deactivateTesApiResourceClientException() throws ApisResourceAccessException, PacketManagerException, - IOException, JsonProcessingException, JSONException, IdrepoDraftException { + IOException, JsonProcessingException, JSONException, IdrepoDraftException, + IdrepoDraftReprocessableException { Map fieldMap = new HashMap<>(); fieldMap.put("UIN", "123456"); fieldMap.put("name", "mono"); @@ -2079,7 +2094,8 @@ public void deactivateTesApiResourceClientException() throws ApisResourceAccessE @Test public void deactivateTesApiResourceServerException() throws ApisResourceAccessException, PacketManagerException, - IOException, JsonProcessingException, JSONException, IdrepoDraftException { + IOException, JsonProcessingException, JSONException, IdrepoDraftException, + IdrepoDraftReprocessableException { Map fieldMap = new HashMap<>(); fieldMap.put("UIN", "123456"); fieldMap.put("name", "mono"); @@ -2127,7 +2143,8 @@ public void deactivateTesApiResourceServerException() throws ApisResourceAccessE @Test public void deactivateTesApiResourceException() throws ApisResourceAccessException, PacketManagerException, - IOException, JsonProcessingException, JSONException, IdrepoDraftException { + IOException, JsonProcessingException, JSONException, IdrepoDraftException, + IdrepoDraftReprocessableException { Map fieldMap = new HashMap<>(); fieldMap.put("UIN", "123456"); fieldMap.put("name", "mono"); @@ -2175,7 +2192,8 @@ public void deactivateTesApiResourceException() throws ApisResourceAccessExcepti @Test public void deactivateTestAlreadyDeactivated() throws ApisResourceAccessException, PacketManagerException, - IOException, JsonProcessingException, JSONException, IdrepoDraftException { + IOException, JsonProcessingException, JSONException, IdrepoDraftException, + IdrepoDraftReprocessableException { Map fieldMap = new HashMap<>(); fieldMap.put("UIN", "123456"); fieldMap.put("name", "mono"); @@ -2224,7 +2242,8 @@ public void deactivateTestAlreadyDeactivated() throws ApisResourceAccessExceptio } @Test - public void testUinAlreadyDeactivated() throws ApisResourceAccessException, PacketManagerException, IOException, JsonProcessingException, JSONException, IdrepoDraftException { + public void testUinAlreadyDeactivated() throws ApisResourceAccessException, PacketManagerException, IOException, + JsonProcessingException, JSONException, IdrepoDraftException, IdrepoDraftReprocessableException { Map fieldsMap = new HashMap<>(); fieldsMap.put("UIN", "123456"); fieldsMap.put("name", "mono"); @@ -2394,5 +2413,23 @@ public void testUinUpdationIOExceptionFaliure() throws Exception { 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()); + } } \ No newline at end of file diff --git a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/code/RegistrationExceptionTypeCode.java b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/code/RegistrationExceptionTypeCode.java index eea08d9c6d0..b1f839ff817 100644 --- a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/code/RegistrationExceptionTypeCode.java +++ b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/code/RegistrationExceptionTypeCode.java @@ -301,6 +301,9 @@ public enum RegistrationExceptionTypeCode { NO_RECORDS_ASSIGNED, MANUAL_VERIFICATION_FAILED, - INTRODUCER_BIOMETRIC_ALL_EXCEPTION_IN_PACKET; + INTRODUCER_BIOMETRIC_ALL_EXCEPTION_IN_PACKET, + + + IDREPO_DRAFT_REPROCESSABLE_EXCEPTION; } \ No newline at end of file diff --git a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/status/util/StatusUtil.java b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/status/util/StatusUtil.java index 7d3910b450f..768420770d7 100644 --- a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/status/util/StatusUtil.java +++ b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/status/util/StatusUtil.java @@ -251,18 +251,33 @@ public enum StatusUtil { IDREPO_DRAFT_EXCEPTION(StatusConstants.UIN_GENERATOR_MODULE_FAILED + "008", "Exception occured updating idrepo draft."), + IDREPO_DRAFT_REPROCESSABLE_EXCEPTION(StatusConstants.UIN_GENERATOR_MODULE_FAILED + "009", + "Exception occured updating idrepo draft, which can be reprocessed"), + // Biometric extraction stage BIOMETRIC_EXTRACTION_SUCCESS(StatusConstants.BIOMETRIC_EXTRACTION_MODULE_SUCCESS + "001", "biometric extaction was successful"), BIOMETRIC_EXTRACTION_DRAFT_REQUEST_UNAVAILABLE(StatusConstants.BIOMETRIC_EXTRACTION_MODULE_FAILED + "001", "Draft request is unavaialble in id-repo draft repository."), + BIOMETRIC_EXTRACTION_IDREPO_DRAFT_EXCEPTION(StatusConstants.BIOMETRIC_EXTRACTION_MODULE_FAILED + "002", + "Exception occured updating idrepo draft."), + + BIOMETRIC_EXTRACTION_IDREPO_DRAFT_REPROCESSABLE_EXCEPTION( + StatusConstants.BIOMETRIC_EXTRACTION_MODULE_FAILED + "003", + "Exception occured updating idrepo draft, which can be reprocessed"), FINALIZATION_SUCCESS(StatusConstants.FINALIZATION_MODULE_SUCCESS + "001", "idrepo draft was published successfuly"), FINALIZATION_FAILURE(StatusConstants.FINALIZATION_MODULE_FAILED + "001", "Draft request failed to publish."), - FINALIZATION_DRAFT_REQUEST_UNAVAILABLE(StatusConstants.FINALIZATION_MODULE_FAILED + "001", + FINALIZATION_DRAFT_REQUEST_UNAVAILABLE(StatusConstants.FINALIZATION_MODULE_FAILED + "002", "Draft request is unavaialble in id-repo draft repository."), + FINALIZATION_IDREPO_DRAFT_EXCEPTION(StatusConstants.FINALIZATION_MODULE_FAILED + "003", + "Exception occured updating idrepo draft."), + + FINALIZATION_IDREPO_DRAFT_REPROCESSABLE_EXCEPTION(StatusConstants.FINALIZATION_MODULE_FAILED + "004", + "Exception occured updating idrepo draft, which can be reprocessed"), + // Request handler service // 1)Resident UIN update RESIDENT_UPDATE_SUCCES(StatusConstants.REQUEST_HANDLER_MODULE_SUCCESS + "001", diff --git a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/util/RegistrationExceptionMapperUtil.java b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/util/RegistrationExceptionMapperUtil.java index 88d926adb88..853370d43a1 100644 --- a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/util/RegistrationExceptionMapperUtil.java +++ b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/util/RegistrationExceptionMapperUtil.java @@ -195,6 +195,8 @@ private static Map registrationProcessorRestClientService; - - public boolean idrepoHasDraft(String id) throws ApisResourceAccessException, IdrepoDraftException { - regProcLogger.debug("idrepoHasDraft entry " + id); - - Integer result = registrationProcessorRestClientService.headApi - (ApiName.IDREPOHASDRAFT, Lists.newArrayList(id), null, null); - - if (result == null || (result.intValue() != IDREPO_DRAFT_FOUND && result.intValue() != IDREPO_DRAFT_NOT_FOUND)) { - regProcLogger.error("idrepoHasDraft failed to get result for id " + id + " result received is " + result); - throw new IdrepoDraftException(PlatformErrorMessages.DRAFT_CHECK_FAILED.getCode(), PlatformErrorMessages.DRAFT_CHECK_FAILED.getMessage()); - } - - boolean hasDraft = result != null && result.intValue() == IDREPO_DRAFT_FOUND; - regProcLogger.info("idrepoHasDraft result for id " + id + " is " + hasDraft); - return hasDraft; - } - - public ResponseDTO idrepoGetDraft(String id) throws ApisResourceAccessException { - regProcLogger.debug("idrepoGetDraft entry " + id); - IdResponseDTO idResponseDTO = (IdResponseDTO) registrationProcessorRestClientService.getApi( - ApiName.IDREPOGETDRAFT, Lists.newArrayList(id), Lists.emptyList(), null, IdResponseDTO.class); - - regProcLogger.debug("idrepoGetDraft exit " + id); - return idResponseDTO.getResponse(); - } - - public boolean idrepoCreateDraft(String id, String uin) throws ApisResourceAccessException { - regProcLogger.debug("idrepoCreateDraft entry " + id); - String queryParam = uin != null ? UIN : null; - String queryParamValue = uin != null ? uin : null; - - ResponseWrapper response = (ResponseWrapper) registrationProcessorRestClientService.postApi( - ApiName.IDREPOCREATEDRAFT, Lists.newArrayList(id), queryParam, queryParamValue, null, ResponseWrapper.class); - - return (response.getErrors() == null || response.getErrors().isEmpty()); - } - - public IdResponseDTO idrepoUpdateDraft(String id, String uin, IdRequestDto idRequestDto) throws ApisResourceAccessException, IdrepoDraftException, IOException { - regProcLogger.debug("idrepoUpdateDraft entry " + id); - if (!idrepoHasDraft(id)) { - regProcLogger.info("Existing draft not found for id " + id + ". Creating new draft."); - idrepoCreateDraft(id, uin); - } else { - regProcLogger.info("Existing draft found for id " + id + ". Updating uin in demographic identity."); - ResponseDTO responseDTO = idrepoGetDraft(id); - RequestDto requestDto = new RequestDto(); - requestDto.setAnonymousProfile(responseDTO.getAnonymousProfile()); - requestDto.setBiometricReferenceId(responseDTO.getBiometricReferenceId()); - JSONObject existingIdentity = mapper.readValue(mapper.writeValueAsString(responseDTO.getIdentity()), JSONObject.class); - JSONObject newIdentity = mapper.readValue(mapper.writeValueAsString(idRequestDto.getRequest().getIdentity()), JSONObject.class); - newIdentity.put(UIN, existingIdentity.get(UIN)); - idRequestDto.getRequest().setIdentity(newIdentity); - requestDto.setRegistrationId(responseDTO.getRegistrationId()); - requestDto.setStatus(responseDTO.getStatus()); - requestDto.setUin(responseDTO.getUin()); - idRequestDto.setRequest(requestDto); - - } - - IdResponseDTO response = (IdResponseDTO) registrationProcessorRestClientService.patchApi( - ApiName.IDREPOUPDATEDRAFT, Lists.newArrayList(id), null, null, idRequestDto, IdResponseDTO.class); - if (response.getErrors() != null && !response.getErrors().isEmpty()) { - regProcLogger.error("Error occured while updating draft for id : " + id, response.getErrors().iterator().next().toString()); - throw new IdrepoDraftException(response.getErrors().iterator().next().getErrorCode(), - response.getErrors().iterator().next().getMessage()); - } - - regProcLogger.debug("idrepoUpdateDraft exit " + id); - return response; - } - - public IdResponseDTO idrepoPublishDraft(String id) throws ApisResourceAccessException, IdrepoDraftException { - regProcLogger.debug("idrepoPublishDraft entry " + id); - List pathsegments=new ArrayList(); - pathsegments.add(id); - IdResponseDTO response = (IdResponseDTO) registrationProcessorRestClientService. - getApi(ApiName.IDREPOPUBLISHDRAFT, pathsegments, "", "", IdResponseDTO.class); - if (response.getErrors() != null && !response.getErrors().isEmpty()) { - regProcLogger.error("Error occured while updating draft for id : " + id, response.getErrors().iterator().next().toString()); - throw new IdrepoDraftException(response.getErrors().iterator().next().getErrorCode(), - response.getErrors().iterator().next().getMessage()); - } - - regProcLogger.debug("idrepoPublishDraft exit " + id); - return response; - } -} +package io.mosip.registration.processor.packet.manager.idreposervice; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import org.assertj.core.util.Lists; +import org.json.simple.JSONObject; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import com.fasterxml.jackson.databind.ObjectMapper; + +import io.mosip.kernel.core.logger.spi.Logger; +import io.mosip.registration.processor.core.code.ApiName; +import io.mosip.registration.processor.core.common.rest.dto.ErrorDTO; +import io.mosip.registration.processor.core.exception.ApisResourceAccessException; +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.spi.restclient.RegistrationProcessorRestClientService; +import io.mosip.registration.processor.packet.manager.dto.IdRequestDto; +import io.mosip.registration.processor.packet.manager.dto.IdResponseDTO; +import io.mosip.registration.processor.packet.manager.dto.RequestDto; +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; + +@Service +public class IdrepoDraftService { + + private static final String UIN = "UIN"; + private static final Integer IDREPO_DRAFT_FOUND = 200; + private static final Integer IDREPO_DRAFT_NOT_FOUND = 204; + private static Logger regProcLogger = RegProcessorLogger.getLogger(IdrepoDraftService.class); + private static final String ID_REPO_KEY_MANAGER_ERROR = "IDR-IDS-003"; + + @Autowired + private ObjectMapper mapper; + + /** The registration processor rest client service. */ + @Autowired + private RegistrationProcessorRestClientService registrationProcessorRestClientService; + + public boolean idrepoHasDraft(String id) throws ApisResourceAccessException, IdrepoDraftException { + regProcLogger.debug("idrepoHasDraft entry " + id); + + Integer result = registrationProcessorRestClientService.headApi + (ApiName.IDREPOHASDRAFT, Lists.newArrayList(id), null, null); + + if (result == null || (result.intValue() != IDREPO_DRAFT_FOUND && result.intValue() != IDREPO_DRAFT_NOT_FOUND)) { + regProcLogger.error("idrepoHasDraft failed to get result for id " + id + " result received is " + result); + throw new IdrepoDraftException(PlatformErrorMessages.DRAFT_CHECK_FAILED.getCode(), PlatformErrorMessages.DRAFT_CHECK_FAILED.getMessage()); + } + + boolean hasDraft = result != null && result.intValue() == IDREPO_DRAFT_FOUND; + regProcLogger.info("idrepoHasDraft result for id " + id + " is " + hasDraft); + return hasDraft; + } + + public ResponseDTO idrepoGetDraft(String id) throws ApisResourceAccessException { + regProcLogger.debug("idrepoGetDraft entry " + id); + IdResponseDTO idResponseDTO = (IdResponseDTO) registrationProcessorRestClientService.getApi( + ApiName.IDREPOGETDRAFT, Lists.newArrayList(id), Lists.emptyList(), null, IdResponseDTO.class); + + regProcLogger.debug("idrepoGetDraft exit " + id); + return idResponseDTO.getResponse(); + } + + public boolean idrepoCreateDraft(String id, String uin) throws ApisResourceAccessException { + regProcLogger.debug("idrepoCreateDraft entry " + id); + String queryParam = uin != null ? UIN : null; + String queryParamValue = uin != null ? uin : null; + + ResponseWrapper response = (ResponseWrapper) registrationProcessorRestClientService.postApi( + ApiName.IDREPOCREATEDRAFT, Lists.newArrayList(id), queryParam, queryParamValue, null, ResponseWrapper.class); + + return (response.getErrors() == null || response.getErrors().isEmpty()); + } + + public IdResponseDTO idrepoUpdateDraft(String id, String uin, IdRequestDto idRequestDto) + throws ApisResourceAccessException, IdrepoDraftException, IOException, IdrepoDraftReprocessableException { + regProcLogger.debug("idrepoUpdateDraft entry " + id); + if (!idrepoHasDraft(id)) { + regProcLogger.info("Existing draft not found for id " + id + ". Creating new draft."); + idrepoCreateDraft(id, uin); + } else { + regProcLogger.info("Existing draft found for id " + id + ". Updating uin in demographic identity."); + ResponseDTO responseDTO = idrepoGetDraft(id); + RequestDto requestDto = new RequestDto(); + requestDto.setAnonymousProfile(responseDTO.getAnonymousProfile()); + requestDto.setBiometricReferenceId(responseDTO.getBiometricReferenceId()); + JSONObject existingIdentity = mapper.readValue(mapper.writeValueAsString(responseDTO.getIdentity()), JSONObject.class); + JSONObject newIdentity = mapper.readValue(mapper.writeValueAsString(idRequestDto.getRequest().getIdentity()), JSONObject.class); + newIdentity.put(UIN, existingIdentity.get(UIN)); + idRequestDto.getRequest().setIdentity(newIdentity); + requestDto.setRegistrationId(responseDTO.getRegistrationId()); + requestDto.setStatus(responseDTO.getStatus()); + requestDto.setUin(responseDTO.getUin()); + idRequestDto.setRequest(requestDto); + + } + + IdResponseDTO response = (IdResponseDTO) registrationProcessorRestClientService.patchApi( + ApiName.IDREPOUPDATEDRAFT, Lists.newArrayList(id), null, null, idRequestDto, IdResponseDTO.class); + if (response.getErrors() != null && !response.getErrors().isEmpty()) { + ErrorDTO error = response.getErrors().get(0); + regProcLogger.error("Error occured while updating draft for id : " + id, error.toString()); + if (response.getErrors().get(0).getErrorCode().equalsIgnoreCase(ID_REPO_KEY_MANAGER_ERROR)) { + throw new IdrepoDraftReprocessableException(error.getErrorCode(), error.getMessage()); + } else { + throw new IdrepoDraftException(error.getErrorCode(), error.getMessage()); + } + } + + regProcLogger.debug("idrepoUpdateDraft exit " + id); + return response; + } + + public IdResponseDTO idrepoPublishDraft(String id) + throws ApisResourceAccessException, IdrepoDraftException, IdrepoDraftReprocessableException { + regProcLogger.debug("idrepoPublishDraft entry " + id); + List pathsegments=new ArrayList(); + pathsegments.add(id); + IdResponseDTO response = (IdResponseDTO) registrationProcessorRestClientService. + getApi(ApiName.IDREPOPUBLISHDRAFT, pathsegments, "", "", IdResponseDTO.class); + if (response.getErrors() != null && !response.getErrors().isEmpty()) { + ErrorDTO error = response.getErrors().get(0); + regProcLogger.error("Error occured while updating draft for id : " + id, error.toString()); + if (response.getErrors().get(0).getErrorCode().equalsIgnoreCase(ID_REPO_KEY_MANAGER_ERROR)) { + throw new IdrepoDraftReprocessableException(error.getErrorCode(), error.getMessage()); + } else { + throw new IdrepoDraftException(error.getErrorCode(), error.getMessage()); + } + + } + + regProcLogger.debug("idrepoPublishDraft exit " + id); + return response; + } +} diff --git a/registration-processor/registration-processor-packet-manager/src/test/java/io/mosip/registration/processor/packet/manager/service/impl/test/IdrepoDraftServiceTest.java b/registration-processor/registration-processor-packet-manager/src/test/java/io/mosip/registration/processor/packet/manager/service/impl/test/IdrepoDraftServiceTest.java index f3f5f082658..580e2b3c17d 100644 --- a/registration-processor/registration-processor-packet-manager/src/test/java/io/mosip/registration/processor/packet/manager/service/impl/test/IdrepoDraftServiceTest.java +++ b/registration-processor/registration-processor-packet-manager/src/test/java/io/mosip/registration/processor/packet/manager/service/impl/test/IdrepoDraftServiceTest.java @@ -1,203 +1,231 @@ -package io.mosip.registration.processor.packet.manager.service.impl.test; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.when; - -import java.io.IOException; - -import org.apache.commons.io.IOUtils; -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.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; - -import com.fasterxml.jackson.databind.ObjectMapper; - -import io.mosip.kernel.core.util.HMACUtils2; -import io.mosip.registration.processor.core.code.ApiName; -import io.mosip.registration.processor.core.common.rest.dto.ErrorDTO; -import io.mosip.registration.processor.core.exception.ApisResourceAccessException; -import io.mosip.registration.processor.core.http.ResponseWrapper; -import io.mosip.registration.processor.core.spi.restclient.RegistrationProcessorRestClientService; -import io.mosip.registration.processor.packet.manager.dto.IdRequestDto; -import io.mosip.registration.processor.packet.manager.dto.IdResponseDTO; -import io.mosip.registration.processor.packet.manager.dto.RequestDto; -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.idreposervice.IdrepoDraftService; - -@RunWith(PowerMockRunner.class) -@PrepareForTest({ IOUtils.class, HMACUtils2.class }) -@PowerMockIgnore({"com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "javax.management.*", "javax.net.ssl.*" }) -public class IdrepoDraftServiceTest { - - @InjectMocks - private IdrepoDraftService idrepoDraftService = new IdrepoDraftService(); - - @Mock - private RegistrationProcessorRestClientService registrationProcessorRestClientService; - - @Mock - private ObjectMapper mapper; - - private IdResponseDTO idResponseDTO; - - private String ID = "12345689"; - - @Before - public void setup() throws IOException { - ResponseDTO responseDTO = new ResponseDTO(); - responseDTO.setStatus("ACTIVATED"); - responseDTO.setRegistrationId(ID); - - JSONObject jsonObject = new JSONObject(); - jsonObject.put("UIN", "1234"); - responseDTO.setIdentity(jsonObject); - - idResponseDTO = new IdResponseDTO(); - idResponseDTO.setErrors(null); - idResponseDTO.setId("id.uin.update"); - idResponseDTO.setResponse(responseDTO); - - when(mapper.writeValueAsString(any())).thenReturn("string"); - when(mapper.readValue("string", JSONObject.class)).thenReturn(jsonObject); - - } - - @Test - public void idrepoDraftPresentTest() throws ApisResourceAccessException, IdrepoDraftException { - - when(registrationProcessorRestClientService.headApi - (ApiName.IDREPOHASDRAFT, Lists.newArrayList(ID), null, null)).thenReturn(200); - - boolean result = idrepoDraftService.idrepoHasDraft(ID); - - assertTrue(result); - } - - @Test - public void idrepoDraftNotPresentTest() throws ApisResourceAccessException, IdrepoDraftException { - - when(registrationProcessorRestClientService.headApi - (ApiName.IDREPOHASDRAFT, Lists.newArrayList(ID), null, null)).thenReturn(204); - - boolean result = idrepoDraftService.idrepoHasDraft(ID); - - assertFalse(result); - } - - @Test(expected = IdrepoDraftException.class) - public void idrepoDraftCheckExceptionTest() throws ApisResourceAccessException, IdrepoDraftException { - - when(registrationProcessorRestClientService.headApi - (ApiName.IDREPOHASDRAFT, Lists.newArrayList(ID), null, null)).thenReturn(500); - - idrepoDraftService.idrepoHasDraft(ID); - - } - - @Test - public void idrepoGetDraftSuccessTest() throws ApisResourceAccessException, IdrepoDraftException { - - when(registrationProcessorRestClientService.getApi( - ApiName.IDREPOGETDRAFT, Lists.newArrayList(ID), Lists.emptyList(), null, IdResponseDTO.class)).thenReturn(idResponseDTO); - - ResponseDTO result = idrepoDraftService.idrepoGetDraft(ID); - - assertTrue(result.getRegistrationId().equals(ID)); - } - - @Test - public void idrepoPublishDraftSuccessTest() throws ApisResourceAccessException, IdrepoDraftException { - - when(registrationProcessorRestClientService.getApi( - ApiName.IDREPOPUBLISHDRAFT, Lists.newArrayList(ID), "", "", IdResponseDTO.class)).thenReturn(idResponseDTO); - - IdResponseDTO result = idrepoDraftService.idrepoPublishDraft(ID); - - assertTrue(result.getResponse().getRegistrationId().equals(ID)); - } - - @Test(expected = IdrepoDraftException.class) - public void idrepoPublishDraftExceptionTest() throws ApisResourceAccessException, IdrepoDraftException { - RequestDto requestDto = new RequestDto(); - requestDto.setIdentity(idResponseDTO.getResponse().getIdentity()); - IdRequestDto idRequestDto = new IdRequestDto(); - idRequestDto.setRequest(requestDto); - - ErrorDTO errorDTO = new ErrorDTO(); - errorDTO.setMessage("ERROR"); - errorDTO.setErrorCode("ERROR"); - IdResponseDTO idResponseDTO1 = new IdResponseDTO(); - idResponseDTO1.setErrors(Lists.newArrayList(errorDTO)); - when(registrationProcessorRestClientService.getApi( - ApiName.IDREPOPUBLISHDRAFT, Lists.newArrayList(ID), "", "", IdResponseDTO.class)).thenReturn(idResponseDTO1); - - idrepoDraftService.idrepoPublishDraft(ID); - } - - @Test - public void idrepoCreateDraftSuccessTest() throws ApisResourceAccessException, IdrepoDraftException { - ResponseWrapper responseWrapper = new ResponseWrapper(); - - when(registrationProcessorRestClientService.postApi( - ApiName.IDREPOCREATEDRAFT, Lists.newArrayList(ID), null, null, null, ResponseWrapper.class)).thenReturn(responseWrapper); - - boolean result = idrepoDraftService.idrepoCreateDraft(ID, null); - - assertTrue(result); - } - - @Test - public void idrepoUpdateDraftSuccessTest() throws ApisResourceAccessException, IdrepoDraftException, IOException { - RequestDto requestDto = new RequestDto(); - requestDto.setIdentity(idResponseDTO.getResponse().getIdentity()); - IdRequestDto idRequestDto = new IdRequestDto(); - idRequestDto.setRequest(requestDto); - - when(registrationProcessorRestClientService.headApi - (ApiName.IDREPOHASDRAFT, Lists.newArrayList(ID), null, null)).thenReturn(200); - when(registrationProcessorRestClientService.getApi( - ApiName.IDREPOGETDRAFT, Lists.newArrayList(ID), Lists.emptyList(), null, IdResponseDTO.class)).thenReturn(idResponseDTO); - when(registrationProcessorRestClientService.patchApi( - any(), any(), any(), any(), any(), any())).thenReturn(idResponseDTO); - - IdResponseDTO result = idrepoDraftService.idrepoUpdateDraft(ID, null, idRequestDto); - - assertTrue(result.getResponse().getRegistrationId().equals(ID)); - } - - @Test(expected = IdrepoDraftException.class) - public void idrepoUpdateDraftExceptionTest() throws ApisResourceAccessException, IdrepoDraftException, IOException { - RequestDto requestDto = new RequestDto(); - requestDto.setIdentity(idResponseDTO.getResponse().getIdentity()); - IdRequestDto idRequestDto = new IdRequestDto(); - idRequestDto.setRequest(requestDto); - - ErrorDTO errorDTO = new ErrorDTO(); - errorDTO.setMessage("ERROR"); - errorDTO.setErrorCode("ERROR"); - IdResponseDTO idResponseDTO1 = new IdResponseDTO(); - idResponseDTO1.setErrors(Lists.newArrayList(errorDTO)); - - when(registrationProcessorRestClientService.headApi - (ApiName.IDREPOHASDRAFT, Lists.newArrayList(ID), null, null)).thenReturn(200); - when(registrationProcessorRestClientService.getApi( - ApiName.IDREPOGETDRAFT, Lists.newArrayList(ID), Lists.emptyList(), null, IdResponseDTO.class)).thenReturn(idResponseDTO); - when(registrationProcessorRestClientService.patchApi( - any(), any(), any(), any(), any(), any())).thenReturn(idResponseDTO1); - - idrepoDraftService.idrepoUpdateDraft(ID, null, idRequestDto); - - } - - -} +package io.mosip.registration.processor.packet.manager.service.impl.test; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.when; + +import java.io.IOException; + +import org.apache.commons.io.IOUtils; +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.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import com.fasterxml.jackson.databind.ObjectMapper; + +import io.mosip.kernel.core.util.HMACUtils2; +import io.mosip.registration.processor.core.code.ApiName; +import io.mosip.registration.processor.core.common.rest.dto.ErrorDTO; +import io.mosip.registration.processor.core.exception.ApisResourceAccessException; +import io.mosip.registration.processor.core.http.ResponseWrapper; +import io.mosip.registration.processor.core.spi.restclient.RegistrationProcessorRestClientService; +import io.mosip.registration.processor.packet.manager.dto.IdRequestDto; +import io.mosip.registration.processor.packet.manager.dto.IdResponseDTO; +import io.mosip.registration.processor.packet.manager.dto.RequestDto; +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.IdrepoDraftService; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({ IOUtils.class, HMACUtils2.class }) +@PowerMockIgnore({"com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "javax.management.*", "javax.net.ssl.*" }) +public class IdrepoDraftServiceTest { + + @InjectMocks + private IdrepoDraftService idrepoDraftService = new IdrepoDraftService(); + + @Mock + private RegistrationProcessorRestClientService registrationProcessorRestClientService; + + @Mock + private ObjectMapper mapper; + + private IdResponseDTO idResponseDTO; + + private String ID = "12345689"; + + @Before + public void setup() throws IOException { + ResponseDTO responseDTO = new ResponseDTO(); + responseDTO.setStatus("ACTIVATED"); + responseDTO.setRegistrationId(ID); + + JSONObject jsonObject = new JSONObject(); + jsonObject.put("UIN", "1234"); + responseDTO.setIdentity(jsonObject); + + idResponseDTO = new IdResponseDTO(); + idResponseDTO.setErrors(null); + idResponseDTO.setId("id.uin.update"); + idResponseDTO.setResponse(responseDTO); + + when(mapper.writeValueAsString(any())).thenReturn("string"); + when(mapper.readValue("string", JSONObject.class)).thenReturn(jsonObject); + + } + + @Test + public void idrepoDraftPresentTest() throws ApisResourceAccessException, IdrepoDraftException { + + when(registrationProcessorRestClientService.headApi + (ApiName.IDREPOHASDRAFT, Lists.newArrayList(ID), null, null)).thenReturn(200); + + boolean result = idrepoDraftService.idrepoHasDraft(ID); + + assertTrue(result); + } + + @Test + public void idrepoDraftNotPresentTest() throws ApisResourceAccessException, IdrepoDraftException { + + when(registrationProcessorRestClientService.headApi + (ApiName.IDREPOHASDRAFT, Lists.newArrayList(ID), null, null)).thenReturn(204); + + boolean result = idrepoDraftService.idrepoHasDraft(ID); + + assertFalse(result); + } + + @Test(expected = IdrepoDraftException.class) + public void idrepoDraftCheckExceptionTest() throws ApisResourceAccessException, IdrepoDraftException { + + when(registrationProcessorRestClientService.headApi + (ApiName.IDREPOHASDRAFT, Lists.newArrayList(ID), null, null)).thenReturn(500); + + idrepoDraftService.idrepoHasDraft(ID); + + } + + @Test + public void idrepoGetDraftSuccessTest() throws ApisResourceAccessException, IdrepoDraftException { + + when(registrationProcessorRestClientService.getApi( + ApiName.IDREPOGETDRAFT, Lists.newArrayList(ID), Lists.emptyList(), null, IdResponseDTO.class)).thenReturn(idResponseDTO); + + ResponseDTO result = idrepoDraftService.idrepoGetDraft(ID); + + assertTrue(result.getRegistrationId().equals(ID)); + } + + @Test + public void idrepoPublishDraftSuccessTest() throws ApisResourceAccessException, IdrepoDraftException, IdrepoDraftReprocessableException { + + when(registrationProcessorRestClientService.getApi( + ApiName.IDREPOPUBLISHDRAFT, Lists.newArrayList(ID), "", "", IdResponseDTO.class)).thenReturn(idResponseDTO); + + IdResponseDTO result = idrepoDraftService.idrepoPublishDraft(ID); + + assertTrue(result.getResponse().getRegistrationId().equals(ID)); + } + + @Test(expected = IdrepoDraftException.class) + public void idrepoPublishDraftExceptionTest() + throws ApisResourceAccessException, IdrepoDraftException, IdrepoDraftReprocessableException { + RequestDto requestDto = new RequestDto(); + requestDto.setIdentity(idResponseDTO.getResponse().getIdentity()); + IdRequestDto idRequestDto = new IdRequestDto(); + idRequestDto.setRequest(requestDto); + + ErrorDTO errorDTO = new ErrorDTO(); + errorDTO.setMessage("ERROR"); + errorDTO.setErrorCode("ERROR"); + IdResponseDTO idResponseDTO1 = new IdResponseDTO(); + idResponseDTO1.setErrors(Lists.newArrayList(errorDTO)); + when(registrationProcessorRestClientService.getApi( + ApiName.IDREPOPUBLISHDRAFT, Lists.newArrayList(ID), "", "", IdResponseDTO.class)).thenReturn(idResponseDTO1); + + idrepoDraftService.idrepoPublishDraft(ID); + } + + @Test + public void idrepoCreateDraftSuccessTest() throws ApisResourceAccessException, IdrepoDraftException { + ResponseWrapper responseWrapper = new ResponseWrapper(); + + when(registrationProcessorRestClientService.postApi( + ApiName.IDREPOCREATEDRAFT, Lists.newArrayList(ID), null, null, null, ResponseWrapper.class)).thenReturn(responseWrapper); + + boolean result = idrepoDraftService.idrepoCreateDraft(ID, null); + + assertTrue(result); + } + + @Test + public void idrepoUpdateDraftSuccessTest() + throws ApisResourceAccessException, IdrepoDraftException, IOException, IdrepoDraftReprocessableException { + RequestDto requestDto = new RequestDto(); + requestDto.setIdentity(idResponseDTO.getResponse().getIdentity()); + IdRequestDto idRequestDto = new IdRequestDto(); + idRequestDto.setRequest(requestDto); + + when(registrationProcessorRestClientService.headApi + (ApiName.IDREPOHASDRAFT, Lists.newArrayList(ID), null, null)).thenReturn(200); + when(registrationProcessorRestClientService.getApi( + ApiName.IDREPOGETDRAFT, Lists.newArrayList(ID), Lists.emptyList(), null, IdResponseDTO.class)).thenReturn(idResponseDTO); + when(registrationProcessorRestClientService.patchApi( + any(), any(), any(), any(), any(), any())).thenReturn(idResponseDTO); + + IdResponseDTO result = idrepoDraftService.idrepoUpdateDraft(ID, null, idRequestDto); + + assertTrue(result.getResponse().getRegistrationId().equals(ID)); + } + + @Test(expected = IdrepoDraftException.class) + public void idrepoUpdateDraftExceptionTest() + throws ApisResourceAccessException, IdrepoDraftException, IOException, IdrepoDraftReprocessableException { + RequestDto requestDto = new RequestDto(); + requestDto.setIdentity(idResponseDTO.getResponse().getIdentity()); + IdRequestDto idRequestDto = new IdRequestDto(); + idRequestDto.setRequest(requestDto); + + ErrorDTO errorDTO = new ErrorDTO(); + errorDTO.setMessage("ERROR"); + errorDTO.setErrorCode("ERROR"); + IdResponseDTO idResponseDTO1 = new IdResponseDTO(); + idResponseDTO1.setErrors(Lists.newArrayList(errorDTO)); + + when(registrationProcessorRestClientService.headApi + (ApiName.IDREPOHASDRAFT, Lists.newArrayList(ID), null, null)).thenReturn(200); + when(registrationProcessorRestClientService.getApi( + ApiName.IDREPOGETDRAFT, Lists.newArrayList(ID), Lists.emptyList(), null, IdResponseDTO.class)).thenReturn(idResponseDTO); + when(registrationProcessorRestClientService.patchApi( + any(), any(), any(), any(), any(), any())).thenReturn(idResponseDTO1); + + idrepoDraftService.idrepoUpdateDraft(ID, null, idRequestDto); + + } + + @Test(expected = IdrepoDraftReprocessableException.class) + public void idrepoDraftReprocessableExceptionTest() + throws ApisResourceAccessException, IdrepoDraftException, IOException, IdrepoDraftReprocessableException { + RequestDto requestDto = new RequestDto(); + requestDto.setIdentity(idResponseDTO.getResponse().getIdentity()); + IdRequestDto idRequestDto = new IdRequestDto(); + idRequestDto.setRequest(requestDto); + + ErrorDTO errorDTO = new ErrorDTO(); + errorDTO.setMessage("Failed to either encrypt/decrypt message using Kernel Crypto Manager"); + errorDTO.setErrorCode("IDR-IDS-003"); + IdResponseDTO idResponseDTO1 = new IdResponseDTO(); + idResponseDTO1.setErrors(Lists.newArrayList(errorDTO)); + + when(registrationProcessorRestClientService.headApi(ApiName.IDREPOHASDRAFT, Lists.newArrayList(ID), null, null)) + .thenReturn(200); + when(registrationProcessorRestClientService.getApi(ApiName.IDREPOGETDRAFT, Lists.newArrayList(ID), + Lists.emptyList(), null, IdResponseDTO.class)).thenReturn(idResponseDTO); + when(registrationProcessorRestClientService.patchApi(any(), any(), any(), any(), any(), any())) + .thenReturn(idResponseDTO1); + + idrepoDraftService.idrepoUpdateDraft(ID, null, idRequestDto); + + } + +} From 7981de99266302edcdf0c2f1c1e46ffc94fa195b Mon Sep 17 00:00:00 2001 From: khuddus shariff Date: Wed, 24 Jan 2024 11:53:49 +0530 Subject: [PATCH 123/133] Merge pull request #1819 from Khuddusshariff0022/develop-MOSIP-28440 (#1838) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [Mosip-28440] changes to compare the biometric records only with the … Signed-off-by: khuddus shariff Co-authored-by: Vishwa --- .../packet/storage/dao/PacketInfoDao.java | 7 +- .../packet/storage/utils/ABISHandlerUtil.java | 29 ++- .../storage/utils/ABISHandlerUtilTest.java | 246 +++++++++--------- .../repositary/RegistrationRepositary.java | 6 +- 4 files changed, 148 insertions(+), 140 deletions(-) diff --git a/registration-processor/registration-processor-info-storage-service/src/main/java/io/mosip/registration/processor/packet/storage/dao/PacketInfoDao.java b/registration-processor/registration-processor-info-storage-service/src/main/java/io/mosip/registration/processor/packet/storage/dao/PacketInfoDao.java index af857405162..f19ef8b3379 100644 --- a/registration-processor/registration-processor-info-storage-service/src/main/java/io/mosip/registration/processor/packet/storage/dao/PacketInfoDao.java +++ b/registration-processor/registration-processor-info-storage-service/src/main/java/io/mosip/registration/processor/packet/storage/dao/PacketInfoDao.java @@ -5,6 +5,7 @@ import java.util.List; import java.util.Map; +import io.mosip.registration.processor.status.entity.RegistrationStatusEntity; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @@ -592,12 +593,10 @@ public List getProcessedOrProcessingRegIds(List matchedRegIds, L * the matched reg ids * @param statusCode1 * the status code - * @param statusCode2 - * the status code * @return the processed or processing reg ids */ - public List getWithoutStatusCodes(List matchedRegIds, String statusCode1, String statusCode2) { - return registrationRepositary.getWithoutStatusCodes(matchedRegIds, "REJECTED", "PROCESSED"); + public List getWithoutStatusCode(List matchedRegIds, String statusCode) { + return registrationRepositary.getWithoutStatusCode(matchedRegIds, statusCode); } /** diff --git a/registration-processor/registration-processor-info-storage-service/src/main/java/io/mosip/registration/processor/packet/storage/utils/ABISHandlerUtil.java b/registration-processor/registration-processor-info-storage-service/src/main/java/io/mosip/registration/processor/packet/storage/utils/ABISHandlerUtil.java index d6ad7833d50..898f48a3c36 100644 --- a/registration-processor/registration-processor-info-storage-service/src/main/java/io/mosip/registration/processor/packet/storage/utils/ABISHandlerUtil.java +++ b/registration-processor/registration-processor-info-storage-service/src/main/java/io/mosip/registration/processor/packet/storage/utils/ABISHandlerUtil.java @@ -13,6 +13,8 @@ import io.mosip.registration.processor.core.code.AbisStatusCode; import io.mosip.registration.processor.core.constant.ProviderStageName; import io.mosip.registration.processor.core.exception.PacketManagerException; +import io.mosip.registration.processor.status.code.RegistrationStatusCode; +import io.mosip.registration.processor.status.entity.RegistrationStatusEntity; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.util.CollectionUtils; @@ -99,15 +101,26 @@ public Set getUniqueRegIds(String registrationId, String registrationTyp if (!CollectionUtils.isEmpty(machedRefIds)) { List matchedRegIds = packetInfoDao.getAbisRefRegIdsByMatchedRefIds(machedRefIds); if (!CollectionUtils.isEmpty(matchedRegIds)) { - List processingRegIds = packetInfoDao.getWithoutStatusCodes(matchedRegIds, - RegistrationTransactionStatusCode.REJECTED.toString(), RegistrationTransactionStatusCode.PROCESSED.toString()); - List statusList=new ArrayList<>(); - statusList.add(RegistrationTransactionStatusCode.PROCESSED.toString()); - statusList.add(RegistrationTransactionStatusCode.PROCESSING.toString()); - List processedRegIds = packetInfoDao.getProcessedOrProcessingRegIds(matchedRegIds, - statusList); - uniqueRIDs = getUniqueRegIds(processedRegIds, registrationId, registrationType, stageName); + List matchedRegistrationStatusEntities = packetInfoDao + .getWithoutStatusCode(matchedRegIds, + RegistrationStatusCode.REJECTED.toString()); + List processingRegistrationStatusEntities = matchedRegistrationStatusEntities + .stream() + .filter(e -> RegistrationStatusCode.PROCESSING.toString().equals(e.getStatusCode())) + .collect(Collectors.toList()); + List processingRegIds = processingRegistrationStatusEntities.stream() + .map(RegistrationStatusEntity::getRegId) + .collect(Collectors.toList()); + List matchedProcessedRegIds = matchedRegistrationStatusEntities.stream() + .map(RegistrationStatusEntity::getRegId).collect(Collectors.toList()); uniqueRIDs.addAll(processingRegIds); + Set processedRegIds = getUniqueRegIds(matchedProcessedRegIds, registrationId, + registrationType, + stageName); + for(String rid:processedRegIds) { + if(!uniqueRIDs.contains(rid)) + uniqueRIDs.add(rid); + } } } } diff --git a/registration-processor/registration-processor-info-storage-service/src/test/java/io/mosip/registration/processor/packet/storage/utils/ABISHandlerUtilTest.java b/registration-processor/registration-processor-info-storage-service/src/test/java/io/mosip/registration/processor/packet/storage/utils/ABISHandlerUtilTest.java index dce4b2c684c..3ed2d2edcbc 100644 --- a/registration-processor/registration-processor-info-storage-service/src/test/java/io/mosip/registration/processor/packet/storage/utils/ABISHandlerUtilTest.java +++ b/registration-processor/registration-processor-info-storage-service/src/test/java/io/mosip/registration/processor/packet/storage/utils/ABISHandlerUtilTest.java @@ -15,6 +15,8 @@ import io.mosip.registration.processor.packet.storage.dao.PacketInfoDao; import io.mosip.registration.processor.packet.storage.dto.ApplicantInfoDto; import io.mosip.registration.processor.packet.storage.mapper.PacketInfoMapper; +import io.mosip.registration.processor.status.code.RegistrationStatusCode; +import io.mosip.registration.processor.status.entity.RegistrationStatusEntity; import org.assertj.core.util.Lists; import org.junit.Before; import org.junit.Test; @@ -45,129 +47,125 @@ @PowerMockIgnore({ "javax.management.*", "javax.net.ssl.*","com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "javax.management.*" }) public class ABISHandlerUtilTest { - private static final String registrationId = "10002100820001420210108085956"; - private static final String registrationType = "NEW"; - private static final String latestTransactionId = "123-456-789"; - List matchedRids = new ArrayList<>(); - - - @InjectMocks - private ABISHandlerUtil abisHandlerUtil; - - @Mock - private Utilities utilities; - - @Mock - private PacketInfoManager packetInfoManager; - - @Mock - private PacketInfoDao packetInfoDao; - - @Mock - private IdRepoService idRepoService; - - List lst=new ArrayList<>(); - - @Before - public void setup() throws Exception { - MockitoAnnotations.initMocks(this); - when(utilities.getLatestTransactionId(any(),any(),anyInt(), any())).thenReturn(latestTransactionId); - - List regBioRefIds = new ArrayList<>(); - regBioRefIds.add("cf1c941a-142c-44f1-9543-4606b4a7884e"); - - when(packetInfoDao.getAbisRefIdByWorkflowInstanceId(any())).thenReturn(regBioRefIds); - when(utilities.getGetRegProcessorDemographicIdentity()).thenReturn(new String()); - - List inprogressMatchedIds = new ArrayList<>(); - inprogressMatchedIds.add("10002100820001420210108085100"); - inprogressMatchedIds.add("10002100820001420210108085101"); - inprogressMatchedIds.add("10002100820001420210108085102"); - - List processedMatchedIds = new ArrayList<>(); - processedMatchedIds.add("10002100820001420210108085103"); - processedMatchedIds.add("10002100820001420210108085104"); - - matchedRids.addAll(inprogressMatchedIds); - matchedRids.addAll(processedMatchedIds); - - List abisResponseDtoList = new ArrayList<>(); - matchedRids.forEach(matchedRid -> { - AbisResponseDto abisResponseDto = new AbisResponseDto(); - abisResponseDto.setId(matchedRid); - abisResponseDtoList.add(abisResponseDto); - }); - - - lst.add(RegistrationTransactionStatusCode.PROCESSED.toString());lst.add(RegistrationTransactionStatusCode.PROCESSING.toString()); - - - when(packetInfoManager.getAbisResponseRecords(regBioRefIds.get(0), - latestTransactionId, AbisConstant.IDENTIFY)).thenReturn(abisResponseDtoList); - - List abisResponseDetDtoList = new ArrayList<>(); - - matchedRids.forEach(matchedRid -> { - AbisResponseDetDto abisResponseDto = new AbisResponseDetDto(); - abisResponseDto.setMatchedBioRefId(matchedRid); - abisResponseDetDtoList.add(abisResponseDto); - }); - for (AbisResponseDetDto dto : abisResponseDetDtoList) { - AbisResponseDetDto responseDetDto = new AbisResponseDetDto(); - responseDetDto.setMatchedBioRefId(dto.getMatchedBioRefId()); - when(packetInfoManager.getAbisResponseDetails(dto.getMatchedBioRefId())).thenReturn(Lists.newArrayList(responseDetDto)); - } - - when(packetInfoDao.getAbisRefRegIdsByMatchedRefIds(matchedRids)).thenReturn(matchedRids); - - when(packetInfoDao.getWithoutStatusCodes(matchedRids, RegistrationTransactionStatusCode.REJECTED.toString(), - RegistrationTransactionStatusCode.PROCESSED.toString())).thenReturn(inprogressMatchedIds); - when(packetInfoDao.getProcessedOrProcessingRegIds(matchedRids, - lst)).thenReturn(processedMatchedIds); - - when(idRepoService.getUinByRid(processedMatchedIds.get(0), new String())).thenReturn("123456789"); - when(idRepoService.getUinByRid(processedMatchedIds.get(1), new String())).thenReturn("987654321"); - - } - - @Test - public void testProcesssedWithUniqueUin() throws ApisResourceAccessException, JsonProcessingException, PacketManagerException, IOException, io.mosip.kernel.core.exception.IOException { - - Set uniqueRids = abisHandlerUtil.getUniqueRegIds(registrationId, registrationType, 1, "", ProviderStageName.BIO_DEDUPE); - - assertEquals(matchedRids.size(), uniqueRids.size()); - } - - @Test - public void testProcesssedWithSameUin() throws ApisResourceAccessException, JsonProcessingException, PacketManagerException, IOException, io.mosip.kernel.core.exception.IOException { - - when(idRepoService.getUinByRid(anyString(), anyString())).thenReturn("987654321"); - - Set uniqueRids = abisHandlerUtil.getUniqueRegIds(registrationId, registrationType,1, "", ProviderStageName.BIO_DEDUPE); - // expected to pick only 1 rid from processedMatchedIds list. Total should be 3(inprogress) + 1(processed) - assertEquals(4, uniqueRids.size()); - } - - @Test - public void testDonotReturnRejected() throws ApisResourceAccessException, JsonProcessingException, PacketManagerException, IOException, io.mosip.kernel.core.exception.IOException { - - when(packetInfoDao.getWithoutStatusCodes(matchedRids, RegistrationTransactionStatusCode.REJECTED.toString(), - RegistrationTransactionStatusCode.PROCESSED.toString())).thenReturn(Lists.newArrayList()); - - Set uniqueRids = abisHandlerUtil.getUniqueRegIds(registrationId, registrationType,1, "", ProviderStageName.BIO_DEDUPE); - // expected to pick only rocessedMatchedIds list i.e 2 records. - assertEquals(2, uniqueRids.size()); - } - - @Test - public void testReturnAllInprogress() throws ApisResourceAccessException, JsonProcessingException, PacketManagerException, IOException, io.mosip.kernel.core.exception.IOException { - - when(packetInfoDao.getProcessedOrProcessingRegIds(matchedRids, - lst)).thenReturn(Lists.newArrayList()); - - Set uniqueRids = abisHandlerUtil.getUniqueRegIds(registrationId, registrationType,1, "", ProviderStageName.BIO_DEDUPE); - // expected not to pick rocessedMatchedIds list i.e 3 records. - assertEquals(3, uniqueRids.size()); - } + private static final String registrationId = "10002100820001420210108085956"; + private static final String registrationType = "NEW"; + private static final String latestTransactionId = "123-456-789"; + List matchedRids = new ArrayList<>(); + + + @InjectMocks + private ABISHandlerUtil abisHandlerUtil; + + @Mock + private Utilities utilities; + + @Mock + private PacketInfoManager packetInfoManager; + + @Mock + private PacketInfoDao packetInfoDao; + + @Mock + private IdRepoService idRepoService; + + List lst=new ArrayList<>(); + + @Before + public void setup() throws Exception { + MockitoAnnotations.initMocks(this); + when(utilities.getLatestTransactionId(any(),any(),anyInt(), any())).thenReturn(latestTransactionId); + + List regBioRefIds = new ArrayList<>(); + regBioRefIds.add("cf1c941a-142c-44f1-9543-4606b4a7884e"); + + when(packetInfoDao.getAbisRefIdByWorkflowInstanceId(any())).thenReturn(regBioRefIds); + when(utilities.getGetRegProcessorDemographicIdentity()).thenReturn(new String()); + + List registrationStatusEntityList = new ArrayList<>(); + + RegistrationStatusEntity registrationEntity1 = new RegistrationStatusEntity(); + registrationEntity1.setRegId("10002100820001420210108085103"); + registrationEntity1.setStatusCode(RegistrationStatusCode.PROCESSED.toString()); + registrationStatusEntityList.add(registrationEntity1); + RegistrationStatusEntity registrationEntity2 = new RegistrationStatusEntity(); + registrationEntity2.setRegId("10002100820001420210108085100"); + registrationEntity2.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); + registrationStatusEntityList.add(registrationEntity2); + RegistrationStatusEntity registrationEntity3 = new RegistrationStatusEntity(); + registrationEntity3.setRegId("10002100820001420210108085102"); + registrationEntity3.setStatusCode(RegistrationStatusCode.PROCESSED.toString()); + registrationStatusEntityList.add(registrationEntity3); + matchedRids.add("10002100820001420210108085100"); + matchedRids.add("10002100820001420210108085103"); + matchedRids.add("10002100820001420210108085101");// REJECTED + matchedRids.add("10002100820001420210108085102"); + + List abisResponseDtoList = new ArrayList<>(); + matchedRids.forEach(matchedRid -> { + AbisResponseDto abisResponseDto = new AbisResponseDto(); + abisResponseDto.setId(matchedRid); + abisResponseDtoList.add(abisResponseDto); + }); + + lst.add(RegistrationTransactionStatusCode.PROCESSED.toString());lst.add(RegistrationTransactionStatusCode.PROCESSING.toString()); + + when(packetInfoManager.getAbisResponseRecords(regBioRefIds.get(0), + latestTransactionId, AbisConstant.IDENTIFY)).thenReturn(abisResponseDtoList); + + List abisResponseDetDtoList = new ArrayList<>(); + matchedRids.forEach(matchedRid -> { + AbisResponseDetDto abisResponseDto = new AbisResponseDetDto(); + abisResponseDto.setMatchedBioRefId(matchedRid); + abisResponseDetDtoList.add(abisResponseDto); + }); + for (AbisResponseDetDto dto : abisResponseDetDtoList) { + AbisResponseDetDto responseDetDto = new AbisResponseDetDto(); + responseDetDto.setMatchedBioRefId(dto.getMatchedBioRefId()); + when(packetInfoManager.getAbisResponseDetails(dto.getMatchedBioRefId())).thenReturn(Lists.newArrayList(responseDetDto)); + } + when(packetInfoDao.getAbisRefRegIdsByMatchedRefIds(matchedRids)).thenReturn(matchedRids); + when(packetInfoDao.getWithoutStatusCode(matchedRids, RegistrationStatusCode.REJECTED.toString())) + .thenReturn(registrationStatusEntityList); + when(idRepoService.getUinByRid("10002100820001420210108085103", new String())).thenReturn("123456789"); + when(idRepoService.getUinByRid("10002100820001420210108085102", new String())).thenReturn("987654321"); + } + + @Test + public void testProcesssedWithUniqueUin() throws ApisResourceAccessException, JsonProcessingException, PacketManagerException, IOException, io.mosip.kernel.core.exception.IOException { + + Set uniqueRids = abisHandlerUtil.getUniqueRegIds(registrationId, registrationType, 1, "", ProviderStageName.BIO_DEDUPE); +// expected to pick 2 rids from processedMatchedIds list because different uin. + // Total should be 1(inprogress) + 2(processed) + assertEquals(3, uniqueRids.size()); + } + + @Test + public void testProcesssedWithSameUin() throws ApisResourceAccessException, JsonProcessingException, PacketManagerException, IOException, io.mosip.kernel.core.exception.IOException { + + when(idRepoService.getUinByRid(anyString(), anyString())).thenReturn("987654321"); + + Set uniqueRids = abisHandlerUtil.getUniqueRegIds(registrationId, registrationType,1, "", ProviderStageName.BIO_DEDUPE); + // expected to pick only 1 rid from processedMatchedIds list because same uin. Total should be 1(inprogress) + 1(processed) + assertEquals(2, uniqueRids.size()); + } + + @Test + public void testDonotReturnRejected() throws ApisResourceAccessException, JsonProcessingException, PacketManagerException, IOException, io.mosip.kernel.core.exception.IOException { + +// List uniqueRids = abisHandlerUtil.getUniqueRegIds(registrationId, registrationType, ProviderStageName.BIO_DEDUPE); + Set uniqueRids= abisHandlerUtil.getUniqueRegIds(registrationId,registrationType,1,"",ProviderStageName.BIO_DEDUPE); + // expected to pick only processingandprocessed list i.e 3 records. + assertEquals(3, uniqueRids.size()); + } + + @Test + public void testReturnAllInprogress() throws ApisResourceAccessException, JsonProcessingException, PacketManagerException, IOException, io.mosip.kernel.core.exception.IOException { + + when(idRepoService.getUinByRid(anyString(), anyString())).thenReturn(null); + + Set uniqueRids = abisHandlerUtil.getUniqueRegIds(registrationId, registrationType,1, "", ProviderStageName.BIO_DEDUPE); + // expected not to pick processedMatchedIds list i.e 1 records.. + assertEquals(1, uniqueRids.size()); + } } diff --git a/registration-processor/registration-processor-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/repositary/RegistrationRepositary.java b/registration-processor/registration-processor-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/repositary/RegistrationRepositary.java index 73cacb1a5d7..fc9a51848e0 100644 --- a/registration-processor/registration-processor-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/repositary/RegistrationRepositary.java +++ b/registration-processor/registration-processor-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/repositary/RegistrationRepositary.java @@ -31,10 +31,8 @@ public interface RegistrationRepositary ext public List getProcessedOrProcessingRegIds(@Param("regIds") List regIds, @Param("statusCode") List statusCode); - @Query("SELECT registration.regId FROM RegistrationStatusEntity registration WHERE registration.regId in :regIds AND registration.statusCode !=:statusCode1 AND registration.statusCode !=:statusCode2") - public List getWithoutStatusCodes(@Param("regIds") List regIds, - @Param("statusCode1") String statusCode1, @Param("statusCode2") String statusCode2); - + @Query("SELECT registration FROM RegistrationStatusEntity registration WHERE registration.id in :regIds and registration.statusCode !=:statusCode") + public List getWithoutStatusCode(@Param("regIds") List regIds, @Param("statusCode") String statusCode); @Query("SELECT registration FROM RegistrationStatusEntity registration WHERE registration.regId = :regId AND registration.isDeleted =false AND registration.isActive=true") public List findByRegId(@Param("regId") String regId); From 4137411afe2eb679e67d1f138eb8440d55662709 Mon Sep 17 00:00:00 2001 From: khuddus shariff Date: Wed, 24 Jan 2024 12:28:53 +0530 Subject: [PATCH 124/133] Merge pull request #1804 from Khuddusshariff0022/develop-Mosip_30417 (#1839) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [Mosip-30417] Regproc -Landing zone config property naming convention… Signed-off-by: khuddus shariff Co-authored-by: Vishwa --- .../receiver/service/impl/PacketReceiverServiceImpl.java | 4 ++-- .../uploader/service/impl/PacketUploaderServiceImpl.java | 4 ++-- .../io/mosip/registration/processor/util/LandingZone.java | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) 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 da245522a0b..7964727284c 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 @@ -117,10 +117,10 @@ public class PacketReceiverServiceImpl implements PacketReceiverService Date: Wed, 24 Jan 2024 13:39:26 +0530 Subject: [PATCH 125/133] [Mosip-30240]Release 1.2.0.1 mosip 30240 (#1840) * Merge pull request #1831 from Khuddusshariff0022/develop_Mosip_30241 MOSIP-30241 adding trim functionality based on property. Signed-off-by: khuddus shariff * [Mosip-30241] Merge pull request #1831 from Khuddusshariff0022/develop-Mosip_30241 Signed-off-by: khuddus shariff --------- Signed-off-by: khuddus shariff Co-authored-by: Vishwa --- .../uingenerator/stage/UinGeneratorStage.java | 7 ++- .../uigenerator/UinGeneratorStageTest.java | 63 ++++++++++++++++--- .../storage/mapper/PacketInfoMapper.java | 18 ++++-- .../service/impl/PacketInfoManagerImpl.java | 7 ++- .../storage/PacketInfoManagerImplTest.java | 27 ++++++-- 5 files changed, 99 insertions(+), 23 deletions(-) diff --git a/registration-processor/core-processor/registration-processor-uin-generator-stage/src/main/java/io/mosip/registration/processor/stages/uingenerator/stage/UinGeneratorStage.java b/registration-processor/core-processor/registration-processor-uin-generator-stage/src/main/java/io/mosip/registration/processor/stages/uingenerator/stage/UinGeneratorStage.java index 5d5e8ac4421..63c05ac64ac 100644 --- a/registration-processor/core-processor/registration-processor-uin-generator-stage/src/main/java/io/mosip/registration/processor/stages/uingenerator/stage/UinGeneratorStage.java +++ b/registration-processor/core-processor/registration-processor-uin-generator-stage/src/main/java/io/mosip/registration/processor/stages/uingenerator/stage/UinGeneratorStage.java @@ -152,6 +152,9 @@ public class UinGeneratorStage extends MosipVerticleAPIManager { @Value("${uingenerator.lost.packet.allowed.update.fields:null}") private String updateInfo; + @Value("${mosip.regproc.uin.generator.trim-whitespaces.simpleType-value:false}") + private boolean trimWhitespaces; + /** The core audit request builder. */ @Autowired private AuditLogRequestBuilder auditLogRequestBuilder; @@ -323,7 +326,6 @@ public MessageDTO process(MessageDTO object) { description); } } - } regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), registrationId, description.getMessage()); @@ -477,6 +479,9 @@ else if (json instanceof JSONArray) { for (int i = 0; i < jsonArray.length(); i++) { Object obj = jsonArray.get(i); HashMap hashMap = objectMapper.readValue(obj.toString(), HashMap.class); + if(trimWhitespaces && hashMap.get("value") instanceof String) { + hashMap.put("value",((String)hashMap.get("value")).trim()); + } jsonList.add(hashMap); } demographicIdentity.putIfAbsent(e.getKey(), jsonList); 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 b57952a8d2a..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,12 +1,11 @@ package io.mosip.registration.processor.stages.uigenerator; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +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.when; +import static org.mockito.Mockito.*; import java.io.ByteArrayInputStream; import java.io.File; @@ -15,6 +14,8 @@ 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; @@ -22,6 +23,10 @@ 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; @@ -30,11 +35,7 @@ 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.MockitoAnnotations; -import org.mockito.Spy; +import org.mockito.*; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; @@ -144,13 +145,13 @@ 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 + } @@ -2432,4 +2433,46 @@ public void testUinGenerationIDRepoDraftReprocessableException() throws Exceptio 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/registration-processor-info-storage-service/src/main/java/io/mosip/registration/processor/packet/storage/mapper/PacketInfoMapper.java b/registration-processor/registration-processor-info-storage-service/src/main/java/io/mosip/registration/processor/packet/storage/mapper/PacketInfoMapper.java index ec4dead9cb5..3f8313742fa 100644 --- a/registration-processor/registration-processor-info-storage-service/src/main/java/io/mosip/registration/processor/packet/storage/mapper/PacketInfoMapper.java +++ b/registration-processor/registration-processor-info-storage-service/src/main/java/io/mosip/registration/processor/packet/storage/mapper/PacketInfoMapper.java @@ -71,12 +71,17 @@ private PacketInfoMapper() { * the language * @return the json values */ - private static String getJsonValues(JsonValue[] jsonNode, String language) { + private static String getJsonValues(JsonValue[] jsonNode, String language,Boolean istrim) { String value = null; if (jsonNode != null) { for (int i = 0; i < jsonNode.length; i++) { if (jsonNode[i].getLanguage().equals(language)) { - value = jsonNode[i].getValue(); + if(istrim) + { + value = jsonNode[i].getValue().trim(); + }else { + value = jsonNode[i].getValue(); + } } } } @@ -115,6 +120,11 @@ private static String[] getLanguages(JsonValue[] jsonNode, StringBuilder languag */ public static List converDemographicDedupeDtoToEntity( IndividualDemographicDedupe demoDto, String regId,String process, int iteration, String workflowInstanceId) throws NoSuchAlgorithmException { + + return converDemographicDedupeDtoToEntity(demoDto,regId,process,iteration,workflowInstanceId,false); + } + public static List converDemographicDedupeDtoToEntity( + IndividualDemographicDedupe demoDto, String regId,String process, int iteration, String workflowInstanceId,Boolean istrim) throws NoSuchAlgorithmException { regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), regId, "PacketInfoMapper::converDemographicDedupeDtoToEntity()::entry"); IndividualDemographicDedupeEntity entity; @@ -144,7 +154,7 @@ public static List converDemographicDedupeDto if (demoDto.getName()!=null &&!demoDto.getName().isEmpty()) { for (JsonValue[] jsonValue : demoDto.getName()) { - applicantFullName.append(getJsonValues(jsonValue, languageArray[i])); + applicantFullName.append(getJsonValues(jsonValue, languageArray[i],istrim)); } entity.setName(!applicantFullName.toString().isEmpty() ? getHMACHashCode(applicantFullName.toString().trim().toUpperCase()) @@ -163,7 +173,7 @@ public static List converDemographicDedupeDto throw new DateParseException(PlatformErrorMessages.RPR_SYS_PARSING_DATE_EXCEPTION.getMessage(), e); } } - entity.setGender(getHMACHashCode(getJsonValues(demoDto.getGender(), languageArray[i]))); + entity.setGender(getHMACHashCode(getJsonValues(demoDto.getGender(), languageArray[i],istrim))); entity.setPhone(getHMACHashCode(demoDto.getPhone())); entity.setEmail(getHMACHashCode(demoDto.getEmail())); demogrphicDedupeEntities.add(entity); diff --git a/registration-processor/registration-processor-info-storage-service/src/main/java/io/mosip/registration/processor/packet/storage/service/impl/PacketInfoManagerImpl.java b/registration-processor/registration-processor-info-storage-service/src/main/java/io/mosip/registration/processor/packet/storage/service/impl/PacketInfoManagerImpl.java index 4ea28232ac8..0d434dec81c 100644 --- a/registration-processor/registration-processor-info-storage-service/src/main/java/io/mosip/registration/processor/packet/storage/service/impl/PacketInfoManagerImpl.java +++ b/registration-processor/registration-processor-info-storage-service/src/main/java/io/mosip/registration/processor/packet/storage/service/impl/PacketInfoManagerImpl.java @@ -141,6 +141,9 @@ public class PacketInfoManagerImpl implements PacketInfoManager applicantDemographicEntities = PacketInfoMapper - .converDemographicDedupeDtoToEntity(demographicData, regId,process,iteration, workflowInstanceId); + .converDemographicDedupeDtoToEntity(demographicData, regId,process,iteration, workflowInstanceId,trimWhitespace); for (IndividualDemographicDedupeEntity applicantDemographicEntity : applicantDemographicEntities) { demographicDedupeRepository.save(applicantDemographicEntity); @@ -339,7 +342,7 @@ public void saveIndividualDemographicDedupeUpdatePacket(IndividualDemographicDed try { List applicantDemographicEntities = PacketInfoMapper - .converDemographicDedupeDtoToEntity(demographicData, registrationId,process,iteration, workflowInstanceId); + .converDemographicDedupeDtoToEntity(demographicData, registrationId,process,iteration, workflowInstanceId,trimWhitespace); for (IndividualDemographicDedupeEntity applicantDemographicEntity : applicantDemographicEntities) { demographicDedupeRepository.save(applicantDemographicEntity); diff --git a/registration-processor/registration-processor-info-storage-service/src/test/java/io/mosip/registration/processor/packet/storage/PacketInfoManagerImplTest.java b/registration-processor/registration-processor-info-storage-service/src/test/java/io/mosip/registration/processor/packet/storage/PacketInfoManagerImplTest.java index d6c53205c4a..13d184b70ee 100644 --- a/registration-processor/registration-processor-info-storage-service/src/test/java/io/mosip/registration/processor/packet/storage/PacketInfoManagerImplTest.java +++ b/registration-processor/registration-processor-info-storage-service/src/test/java/io/mosip/registration/processor/packet/storage/PacketInfoManagerImplTest.java @@ -27,10 +27,7 @@ import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; +import org.mockito.*; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; @@ -93,6 +90,7 @@ 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 org.springframework.test.util.ReflectionTestUtils; /** * The Class PacketInfoManagerImplTest. @@ -1057,7 +1055,7 @@ public void testsaveIndividualDemographicDedupe() throws NoSuchAlgorithmExceptio entity.setDob("2019-03-02T06:29:41.011Z"); applicantDemographicEntities.add(entity); PowerMockito.mockStatic(PacketInfoMapper.class); - Mockito.when(PacketInfoMapper.converDemographicDedupeDtoToEntity(Mockito.any(), Mockito.any(),Mockito.any(),Mockito.anyInt(), any())) + Mockito.when(PacketInfoMapper.converDemographicDedupeDtoToEntity(Mockito.any(), Mockito.any(),Mockito.any(),Mockito.anyInt(), any(),any())) .thenReturn(applicantDemographicEntities); Mockito.when(demographicDedupeRepository.save(any())).thenReturn(entity); packetInfoManagerImpl.saveIndividualDemographicDedupeUpdatePacket(demographicData, @@ -1075,7 +1073,7 @@ public void testsaveIndividualDemographicDedupeException() throws NoSuchAlgorith entity.setDob("2019-03-02T06:29:41.011Z"); applicantDemographicEntities.add(entity); PowerMockito.mockStatic(PacketInfoMapper.class); - Mockito.when(PacketInfoMapper.converDemographicDedupeDtoToEntity(Mockito.any(), Mockito.any(),Mockito.any(),Mockito.anyInt(), any())) + Mockito.when(PacketInfoMapper.converDemographicDedupeDtoToEntity(Mockito.any(), Mockito.any(),Mockito.any(),Mockito.anyInt(), any(),any())) .thenReturn(applicantDemographicEntities); Mockito.when(demographicDedupeRepository.save(any())).thenThrow(exp); packetInfoManagerImpl.saveIndividualDemographicDedupeUpdatePacket(demographicData, @@ -1153,4 +1151,21 @@ public void dataAccessLayerExceptionTest() { } + @Test + public void testsaveIndividualDemographicDedupeWithTrim() throws NoSuchAlgorithmException { + ReflectionTestUtils.setField(packetInfoManagerImpl,"trimWhitespace",true); + IndividualDemographicDedupe demographicData = new IndividualDemographicDedupe(); + demographicData.setDateOfBirth("2019-03-02T06:29:41.011Z"); + List applicantDemographicEntities = new ArrayList<>(); + IndividualDemographicDedupeEntity entity = new IndividualDemographicDedupeEntity(); + entity.setDob("2019-03-02T06:29:41.011Z"); + applicantDemographicEntities.add(entity); + PowerMockito.mockStatic(PacketInfoMapper.class); + Mockito.when(PacketInfoMapper.converDemographicDedupeDtoToEntity(Mockito.any(), Mockito.any(),Mockito.any(),Mockito.anyInt(), any(),any())) + .thenReturn(applicantDemographicEntities); + Mockito.when(demographicDedupeRepository.save(any())).thenReturn(entity); + ArgumentCaptor arg2 = ArgumentCaptor.forClass(Integer.class); + packetInfoManagerImpl.saveIndividualDemographicDedupeUpdatePacket(demographicData, + "1001", "","NEW", "",1, ""); + } } From e62e00ebfd948d70d01af50020f5aeee4e73b7db Mon Sep 17 00:00:00 2001 From: Sowmya Ujjappa Banakar Date: Fri, 2 Feb 2024 16:20:00 +0530 Subject: [PATCH 126/133] MOSIP-31387 code fix Signed-off-by: Sowmya Ujjappa Banakar --- .../repositary/RegistrationRepositary.java | 131 +++++++++--------- 1 file changed, 65 insertions(+), 66 deletions(-) diff --git a/registration-processor/registration-processor-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/repositary/RegistrationRepositary.java b/registration-processor/registration-processor-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/repositary/RegistrationRepositary.java index fc9a51848e0..2a53a40c226 100644 --- a/registration-processor/registration-processor-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/repositary/RegistrationRepositary.java +++ b/registration-processor/registration-processor-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/repositary/RegistrationRepositary.java @@ -1,66 +1,65 @@ -/* - * - */ -package io.mosip.registration.processor.status.repositary; - -import java.time.LocalDateTime; -import java.util.List; - -import org.springframework.data.jpa.repository.Query; -import org.springframework.data.repository.query.Param; -import org.springframework.stereotype.Repository; - -import io.mosip.kernel.core.dataaccess.spi.repository.BaseRepository; -import io.mosip.registration.processor.status.entity.BaseRegistrationEntity; -import io.mosip.registration.processor.status.entity.RegistrationStatusEntity; -import io.mosip.registration.processor.status.entity.SyncRegistrationEntity; - -/** - * The Interface RegistrationRepositary. - * - * @param - * the generic type - * @param - * the element type - */ -@Repository -public interface RegistrationRepositary extends BaseRepository { - - - @Query("SELECT registration.regId FROM RegistrationStatusEntity registration WHERE registration.regId in :regIds AND registration.statusCode in :statusCode") - public List getProcessedOrProcessingRegIds(@Param("regIds") List regIds, - @Param("statusCode") List statusCode); - - @Query("SELECT registration FROM RegistrationStatusEntity registration WHERE registration.id in :regIds and registration.statusCode !=:statusCode") - public List getWithoutStatusCode(@Param("regIds") List regIds, @Param("statusCode") String statusCode); - @Query("SELECT registration FROM RegistrationStatusEntity registration WHERE registration.regId = :regId AND registration.isDeleted =false AND registration.isActive=true") - public List findByRegId(@Param("regId") String regId); - - @Query("SELECT registration FROM RegistrationStatusEntity registration WHERE registration.regId IN :regIds AND registration.isDeleted =false AND registration.isActive=true") - public List findByRegIds(@Param("regIds") List regIds); - - @Query("SELECT registration FROM RegistrationStatusEntity registration WHERE registration.regId IN :regIds AND registration.isDeleted =false AND registration.isActive=true order by registration.createDateTime") - public List findByRegIdsOrderbyCreatedDateTime(@Param("regIds") List regIds); - - @Query("SELECT registration FROM RegistrationStatusEntity registration WHERE registration.statusCode = :statusCode AND registration.isDeleted =false AND registration.isActive=true") - public List findByStatusCode(@Param("statusCode") String statusCode); - - @Query("SELECT registration FROM RegistrationStatusEntity registration WHERE registration.regId = :regId AND registration.statusCode = :statusCode ") - public List findByRegIdANDByStatusCode(@Param("regId") String regId,@Param("statusCode") String statusCode); - - @Query("SELECT registration FROM RegistrationStatusEntity registration WHERE registration.id.workflowInstanceId = :workflowInstanceId AND registration.isDeleted =false AND registration.isActive=true") - public List findByWorkflowInstanceId(@Param("workflowInstanceId") String workflowInstanceId); - - @Query(value ="SELECT * FROM registration r WHERE r.latest_trn_status_code IN :status AND r.reg_process_retry_count<=:reprocessCount AND r.latest_trn_dtimes <:timeDifference AND r.status_code NOT IN :statusCodes AND r.reg_stage_name NOT IN :excludeStageNames LIMIT :fetchSize ", nativeQuery = true) - public List getUnProcessedPackets(@Param("status") List status,@Param("reprocessCount") Integer reprocessCount,@Param("timeDifference") LocalDateTime timeDifference,@Param("statusCodes") List statusCodes,@Param("fetchSize") Integer fetchSize,@Param("excludeStageNames") List excludeStageNames); - - @Query("SELECT COUNT(*) FROM RegistrationStatusEntity registration WHERE registration.latestTransactionStatusCode IN :status AND registration.regProcessRetryCount<=:reprocessCount AND registration.latestTransactionTimes<:timeDifference AND registration.statusCode NOT IN :statusCodes AND registration.registrationStageName NOT IN :excludeStageNames") - public int getUnProcessedPacketsCount(@Param("status") List status,@Param("reprocessCount") Integer reprocessCount,@Param("timeDifference") LocalDateTime timeDifference,@Param("statusCodes") List statusCodes,@Param("excludeStageNames") List excludeStageNames); - - @Query(value ="SELECT * FROM registration r WHERE r.status_code IN :statusCodes AND r.resume_timestamp < now() AND r.default_resume_action is NOT NULL order by r.upd_dtimes LIMIT :fetchSize ", nativeQuery = true) - public List getActionablePausedPackets(@Param("statusCodes") List statusCodes,@Param("fetchSize") Integer fetchSize); - - @Query(value ="SELECT * FROM registration r WHERE r.status_code =:statusCode order by r.upd_dtimes LIMIT :fetchSize ", nativeQuery = true) - public List getResumablePackets(@Param("statusCode") String statusCode,@Param("fetchSize") Integer fetchSize); -} - +/* + * + */ +package io.mosip.registration.processor.status.repositary; + +import java.time.LocalDateTime; +import java.util.List; + +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; +import org.springframework.stereotype.Repository; + +import io.mosip.kernel.core.dataaccess.spi.repository.BaseRepository; +import io.mosip.registration.processor.status.entity.BaseRegistrationEntity; +import io.mosip.registration.processor.status.entity.RegistrationStatusEntity; + +/** + * The Interface RegistrationRepositary. + * + * @param + * the generic type + * @param + * the element type + */ +@Repository +public interface RegistrationRepositary extends BaseRepository { + + + @Query("SELECT registration.regId FROM RegistrationStatusEntity registration WHERE registration.regId in :regIds AND registration.statusCode in :statusCode") + public List getProcessedOrProcessingRegIds(@Param("regIds") List regIds, + @Param("statusCode") List statusCode); + + @Query("SELECT registration FROM RegistrationStatusEntity registration WHERE registration.regId in :regIds and registration.statusCode !=:statusCode") + public List getWithoutStatusCode(@Param("regIds") List regIds, @Param("statusCode") String statusCode); + @Query("SELECT registration FROM RegistrationStatusEntity registration WHERE registration.regId = :regId AND registration.isDeleted =false AND registration.isActive=true") + public List findByRegId(@Param("regId") String regId); + + @Query("SELECT registration FROM RegistrationStatusEntity registration WHERE registration.regId IN :regIds AND registration.isDeleted =false AND registration.isActive=true") + public List findByRegIds(@Param("regIds") List regIds); + + @Query("SELECT registration FROM RegistrationStatusEntity registration WHERE registration.regId IN :regIds AND registration.isDeleted =false AND registration.isActive=true order by registration.createDateTime") + public List findByRegIdsOrderbyCreatedDateTime(@Param("regIds") List regIds); + + @Query("SELECT registration FROM RegistrationStatusEntity registration WHERE registration.statusCode = :statusCode AND registration.isDeleted =false AND registration.isActive=true") + public List findByStatusCode(@Param("statusCode") String statusCode); + + @Query("SELECT registration FROM RegistrationStatusEntity registration WHERE registration.regId = :regId AND registration.statusCode = :statusCode ") + public List findByRegIdANDByStatusCode(@Param("regId") String regId,@Param("statusCode") String statusCode); + + @Query("SELECT registration FROM RegistrationStatusEntity registration WHERE registration.id.workflowInstanceId = :workflowInstanceId AND registration.isDeleted =false AND registration.isActive=true") + public List findByWorkflowInstanceId(@Param("workflowInstanceId") String workflowInstanceId); + + @Query(value ="SELECT * FROM registration r WHERE r.latest_trn_status_code IN :status AND r.reg_process_retry_count<=:reprocessCount AND r.latest_trn_dtimes <:timeDifference AND r.status_code NOT IN :statusCodes AND r.reg_stage_name NOT IN :excludeStageNames LIMIT :fetchSize ", nativeQuery = true) + public List getUnProcessedPackets(@Param("status") List status,@Param("reprocessCount") Integer reprocessCount,@Param("timeDifference") LocalDateTime timeDifference,@Param("statusCodes") List statusCodes,@Param("fetchSize") Integer fetchSize,@Param("excludeStageNames") List excludeStageNames); + + @Query("SELECT COUNT(*) FROM RegistrationStatusEntity registration WHERE registration.latestTransactionStatusCode IN :status AND registration.regProcessRetryCount<=:reprocessCount AND registration.latestTransactionTimes<:timeDifference AND registration.statusCode NOT IN :statusCodes AND registration.registrationStageName NOT IN :excludeStageNames") + public int getUnProcessedPacketsCount(@Param("status") List status,@Param("reprocessCount") Integer reprocessCount,@Param("timeDifference") LocalDateTime timeDifference,@Param("statusCodes") List statusCodes,@Param("excludeStageNames") List excludeStageNames); + + @Query(value ="SELECT * FROM registration r WHERE r.status_code IN :statusCodes AND r.resume_timestamp < now() AND r.default_resume_action is NOT NULL order by r.upd_dtimes LIMIT :fetchSize ", nativeQuery = true) + public List getActionablePausedPackets(@Param("statusCodes") List statusCodes,@Param("fetchSize") Integer fetchSize); + + @Query(value ="SELECT * FROM registration r WHERE r.status_code =:statusCode order by r.upd_dtimes LIMIT :fetchSize ", nativeQuery = true) + public List getResumablePackets(@Param("statusCode") String statusCode,@Param("fetchSize") Integer fetchSize); +} + From 44950483288a986f4f7bdaeea06156a2ecdb92b3 Mon Sep 17 00:00:00 2001 From: Sowmya Ujjappa Banakar Date: Tue, 27 Feb 2024 18:51:04 +0530 Subject: [PATCH 127/133] MOSIP-31759 script change Signed-off-by: Sowmya Ujjappa Banakar --- .../mosip_regprc/sql/1.2.0.1-B3_to_1.2.0.1_rollback.sql | 1 + .../mosip_regprc/sql/1.2.0.1-B3_to_1.2.0.1_upgrade.sql | 1 + 2 files changed, 2 insertions(+) create mode 100644 db_upgrade_scripts/mosip_regprc/sql/1.2.0.1-B3_to_1.2.0.1_rollback.sql create mode 100644 db_upgrade_scripts/mosip_regprc/sql/1.2.0.1-B3_to_1.2.0.1_upgrade.sql 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' From 1ddcd5959ad82aecb24d00bfa1bab836066be7f0 Mon Sep 17 00:00:00 2001 From: Sowmya Ujjappa Banakar <43202851+sowmya695@users.noreply.github.com> Date: Mon, 4 Mar 2024 15:57:19 +0530 Subject: [PATCH 128/133] MOSIP-31766 version fix (#1854) Signed-off-by: Sowmya Ujjappa Banakar Co-authored-by: Sowmya Ujjappa Banakar --- .../dependency-reduced-pom.xml | 216 +++++++++--------- 1 file changed, 108 insertions(+), 108 deletions(-) diff --git a/registration-processor/registration-processor-common-camel-bridge/dependency-reduced-pom.xml b/registration-processor/registration-processor-common-camel-bridge/dependency-reduced-pom.xml index 0aa37a8a669..84dcbf07157 100644 --- a/registration-processor/registration-processor-common-camel-bridge/dependency-reduced-pom.xml +++ b/registration-processor/registration-processor-common-camel-bridge/dependency-reduced-pom.xml @@ -1,108 +1,108 @@ - - - - registration-processor - io.mosip.registrationprocessor - 1.2.0.1-B3 - - 4.0.0 - registration-processor-common-camel-bridge - 1.2.0.1-B3-SNAPSHOT - - - - maven-shade-plugin - 2.3 - - - package - - shade - - - - - io.mosip.registration.processor.camel.bridge.MosipCamelBridgeApplication - - - - - - *:* - - META-INF/*.SF - META-INF/*.DSA - META-INF/*.RSA - - - - - - - - - - - - io.vertx - vertx-unit - 3.9.1 - test - - - org.mockito - mockito-core - 3.4.4 - test - - - byte-buddy-agent - net.bytebuddy - - - objenesis - org.objenesis - - - - - org.powermock - powermock-module-junit4 - 2.0.7 - test - - - powermock-module-junit4-common - org.powermock - - - - - org.powermock - powermock-api-mockito2 - 2.0.7 - test - - - powermock-api-support - org.powermock - - - - - - - - com.h2database - h2 - ${h2.version} - - - - - io.mosip.registration.processor.camel.bridge.MosipCamelBridge - 1.0.5 - 1.2.0.1-B3-SNAPSHOT - - - + + + + registration-processor + io.mosip.registrationprocessor + 1.2.0.1-SNAPSHOT + + 4.0.0 + registration-processor-common-camel-bridge + 1.2.0.1-SNAPSHOT + + + + maven-shade-plugin + 2.3 + + + package + + shade + + + + + io.mosip.registration.processor.camel.bridge.MosipCamelBridgeApplication + + + + + + *:* + + META-INF/*.SF + META-INF/*.DSA + META-INF/*.RSA + + + + + + + + + + + + io.vertx + vertx-unit + 3.9.1 + test + + + org.mockito + mockito-core + 3.4.4 + test + + + byte-buddy-agent + net.bytebuddy + + + objenesis + org.objenesis + + + + + org.powermock + powermock-module-junit4 + 2.0.7 + test + + + powermock-module-junit4-common + org.powermock + + + + + org.powermock + powermock-api-mockito2 + 2.0.7 + test + + + powermock-api-support + org.powermock + + + + + + + + com.h2database + h2 + ${h2.version} + + + + + io.mosip.registration.processor.camel.bridge.MosipCamelBridge + 1.0.5 + 1.2.0.1-SNAPSHOT + + + From dec95ebe05b279decdb48111c62907b4f284ab10 Mon Sep 17 00:00:00 2001 From: Chandra Keshav Mishra Date: Mon, 4 Mar 2024 16:43:40 +0530 Subject: [PATCH 129/133] Updated Pom versions for release changes (#1855) Signed-off-by: GitHub Co-authored-by: Prafulrakhade --- .github/workflows/push-trigger.yml | 2 +- registration-processor/core-processor/pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../registration-processor-abis/pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- registration-processor/init/pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../mosip-stage-executor/pom.xml | 4 +- registration-processor/pom.xml | 48 +++++++++---------- registration-processor/post-processor/pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- registration-processor/pre-processor/pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../qc-users-manger/pom.xml | 4 +- .../pom.xml | 4 +- .../dependency-reduced-pom.xml | 6 +-- .../pom.xml | 6 +-- .../registration-processor-core/pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 6 +-- .../pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- registration-processor/stage-groups/pom.xml | 4 +- .../pom.xml | 8 ++-- .../pom.xml | 12 ++--- .../pom.xml | 14 +++--- .../pom.xml | 10 ++-- .../pom.xml | 16 +++---- .../pom.xml | 12 ++--- .../pom.xml | 14 +++--- .../workflow-engine/pom.xml | 4 +- .../pom.xml | 4 +- .../pom.xml | 4 +- 55 files changed, 163 insertions(+), 163 deletions(-) diff --git a/.github/workflows/push-trigger.yml b/.github/workflows/push-trigger.yml index 326df0539bb..6f1a3df3700 100644 --- a/.github/workflows/push-trigger.yml +++ b/.github/workflows/push-trigger.yml @@ -43,7 +43,7 @@ jobs: secrets: OSSRH_USER: ${{ secrets.OSSRH_USER }} OSSRH_SECRET: ${{ secrets.OSSRH_SECRET }} - OSSRH_URL: ${{ secrets.OSSRH_SNAPSHOT_URL }} + OSSRH_URL: ${{ secrets.RELEASE_URL }} OSSRH_TOKEN: ${{ secrets.OSSRH_TOKEN }} GPG_SECRET: ${{ secrets.GPG_SECRET }} SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK }} diff --git a/registration-processor/core-processor/pom.xml b/registration-processor/core-processor/pom.xml index 1e70249927a..fa91c1f0578 100644 --- a/registration-processor/core-processor/pom.xml +++ b/registration-processor/core-processor/pom.xml @@ -5,9 +5,9 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1 - 1.2.0.1-SNAPSHOT + 1.2.0.1 core-processor core-processor diff --git a/registration-processor/core-processor/registration-processor-abis-handler-stage/pom.xml b/registration-processor/core-processor/registration-processor-abis-handler-stage/pom.xml index b993ca03858..a37de58feed 100644 --- a/registration-processor/core-processor/registration-processor-abis-handler-stage/pom.xml +++ b/registration-processor/core-processor/registration-processor-abis-handler-stage/pom.xml @@ -5,11 +5,11 @@ io.mosip.registrationprocessor core-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1 registration-processor-abis-handler-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1 jar UTF-8 diff --git a/registration-processor/core-processor/registration-processor-abis-middleware-stage/pom.xml b/registration-processor/core-processor/registration-processor-abis-middleware-stage/pom.xml index e50a32b7d0d..fa7793ec1ea 100644 --- a/registration-processor/core-processor/registration-processor-abis-middleware-stage/pom.xml +++ b/registration-processor/core-processor/registration-processor-abis-middleware-stage/pom.xml @@ -5,10 +5,10 @@ io.mosip.registrationprocessor core-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1 registration-processor-abis-middleware-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1 jar UTF-8 diff --git a/registration-processor/core-processor/registration-processor-abis/pom.xml b/registration-processor/core-processor/registration-processor-abis/pom.xml index f74c9c31884..6c2b745f082 100644 --- a/registration-processor/core-processor/registration-processor-abis/pom.xml +++ b/registration-processor/core-processor/registration-processor-abis/pom.xml @@ -8,10 +8,10 @@ io.mosip.registrationprocessor core-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1 registration-processor-abis - 1.2.0.1-SNAPSHOT + 1.2.0.1 registration-processor-abis UTF-8 diff --git a/registration-processor/core-processor/registration-processor-bio-dedupe-stage/pom.xml b/registration-processor/core-processor/registration-processor-bio-dedupe-stage/pom.xml index 51b750768e9..56ff425b0df 100644 --- a/registration-processor/core-processor/registration-processor-bio-dedupe-stage/pom.xml +++ b/registration-processor/core-processor/registration-processor-bio-dedupe-stage/pom.xml @@ -5,11 +5,11 @@ io.mosip.registrationprocessor core-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1 registration-processor-bio-dedupe-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1 jar UTF-8 diff --git a/registration-processor/core-processor/registration-processor-biometric-authentication-stage/pom.xml b/registration-processor/core-processor/registration-processor-biometric-authentication-stage/pom.xml index 754cbb84860..23d4521323a 100644 --- a/registration-processor/core-processor/registration-processor-biometric-authentication-stage/pom.xml +++ b/registration-processor/core-processor/registration-processor-biometric-authentication-stage/pom.xml @@ -5,10 +5,10 @@ io.mosip.registrationprocessor core-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1 registration-processor-biometric-authentication-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1 jar UTF-8 diff --git a/registration-processor/core-processor/registration-processor-biometric-extraction-stage/pom.xml b/registration-processor/core-processor/registration-processor-biometric-extraction-stage/pom.xml index c22795794a5..b520f750e72 100644 --- a/registration-processor/core-processor/registration-processor-biometric-extraction-stage/pom.xml +++ b/registration-processor/core-processor/registration-processor-biometric-extraction-stage/pom.xml @@ -5,10 +5,10 @@ io.mosip.registrationprocessor core-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1 registration-processor-biometric-extraction-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1 jar UTF-8 diff --git a/registration-processor/core-processor/registration-processor-demo-dedupe-stage/pom.xml b/registration-processor/core-processor/registration-processor-demo-dedupe-stage/pom.xml index 80e30419cfa..81de309f801 100644 --- a/registration-processor/core-processor/registration-processor-demo-dedupe-stage/pom.xml +++ b/registration-processor/core-processor/registration-processor-demo-dedupe-stage/pom.xml @@ -5,10 +5,10 @@ io.mosip.registrationprocessor core-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1 registration-processor-demo-dedupe-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1 jar UTF-8 diff --git a/registration-processor/core-processor/registration-processor-finalization-stage/pom.xml b/registration-processor/core-processor/registration-processor-finalization-stage/pom.xml index fe52552ff90..adb6556ca2c 100644 --- a/registration-processor/core-processor/registration-processor-finalization-stage/pom.xml +++ b/registration-processor/core-processor/registration-processor-finalization-stage/pom.xml @@ -5,11 +5,11 @@ io.mosip.registrationprocessor core-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1 registration-processor-finalization-stage registration-processor-finalization-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1 jar UTF-8 diff --git a/registration-processor/core-processor/registration-processor-manual-adjudication-stage/pom.xml b/registration-processor/core-processor/registration-processor-manual-adjudication-stage/pom.xml index 796d3317026..b2cb336df8c 100644 --- a/registration-processor/core-processor/registration-processor-manual-adjudication-stage/pom.xml +++ b/registration-processor/core-processor/registration-processor-manual-adjudication-stage/pom.xml @@ -8,11 +8,11 @@ io.mosip.registrationprocessor core-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1 registration-processor-manual-adjudication-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1 UTF-8 diff --git a/registration-processor/core-processor/registration-processor-uin-generator-stage/pom.xml b/registration-processor/core-processor/registration-processor-uin-generator-stage/pom.xml index 3a163267596..f6ffd9f8f5c 100644 --- a/registration-processor/core-processor/registration-processor-uin-generator-stage/pom.xml +++ b/registration-processor/core-processor/registration-processor-uin-generator-stage/pom.xml @@ -4,10 +4,10 @@ io.mosip.registrationprocessor core-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1 registration-processor-uin-generator-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1 jar UTF-8 diff --git a/registration-processor/core-processor/registration-processor-verification-stage/pom.xml b/registration-processor/core-processor/registration-processor-verification-stage/pom.xml index 804ff7f221b..5be0233fbd7 100644 --- a/registration-processor/core-processor/registration-processor-verification-stage/pom.xml +++ b/registration-processor/core-processor/registration-processor-verification-stage/pom.xml @@ -8,11 +8,11 @@ io.mosip.registrationprocessor core-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1 registration-processor-verification-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1 UTF-8 diff --git a/registration-processor/init/pom.xml b/registration-processor/init/pom.xml index e0cab04f77e..3070a69db67 100644 --- a/registration-processor/init/pom.xml +++ b/registration-processor/init/pom.xml @@ -6,10 +6,10 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1 init - 1.2.0.1-SNAPSHOT + 1.2.0.1 UTF-8 diff --git a/registration-processor/init/registration-processor-packet-receiver-stage/pom.xml b/registration-processor/init/registration-processor-packet-receiver-stage/pom.xml index 65c49693beb..dc7fd87d24e 100644 --- a/registration-processor/init/registration-processor-packet-receiver-stage/pom.xml +++ b/registration-processor/init/registration-processor-packet-receiver-stage/pom.xml @@ -7,11 +7,11 @@ io.mosip.registrationprocessor init - 1.2.0.1-SNAPSHOT + 1.2.0.1 registration-processor-packet-receiver-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1 jar registration-processor-packet-receiver-stage diff --git a/registration-processor/init/registration-processor-registration-status-service/pom.xml b/registration-processor/init/registration-processor-registration-status-service/pom.xml index 7d35fa6396c..9ac761be270 100644 --- a/registration-processor/init/registration-processor-registration-status-service/pom.xml +++ b/registration-processor/init/registration-processor-registration-status-service/pom.xml @@ -8,10 +8,10 @@ io.mosip.registrationprocessor init - 1.2.0.1-SNAPSHOT + 1.2.0.1 registration-processor-registration-status-service - 1.2.0.1-SNAPSHOT + 1.2.0.1 registration-processor-registration-status-service diff --git a/registration-processor/mosip-stage-executor/pom.xml b/registration-processor/mosip-stage-executor/pom.xml index 22617e270bd..5253f7e9848 100644 --- a/registration-processor/mosip-stage-executor/pom.xml +++ b/registration-processor/mosip-stage-executor/pom.xml @@ -5,11 +5,11 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1 mosip-stage-executor - 1.2.0.1-SNAPSHOT + 1.2.0.1 diff --git a/registration-processor/pom.xml b/registration-processor/pom.xml index 72b79796186..524bf2405da 100644 --- a/registration-processor/pom.xml +++ b/registration-processor/pom.xml @@ -23,7 +23,7 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1 pom registration-processor @@ -121,31 +121,31 @@ 0.1.55 - 1.2.0.1-SNAPSHOT - 1.2.0.1-SNAPSHOT - 1.2.0.1-SNAPSHOT - 1.2.0.1-SNAPSHOT - 1.2.0.1-SNAPSHOT - 1.2.0.1-SNAPSHOT - 1.2.0.1-SNAPSHOT + 1.2.0.1 + 1.2.0.1 + 1.2.0.1 + 1.2.0.1 + 1.2.0.1 + 1.2.0.1 + 1.2.0.1 - 1.2.0.1-SNAPSHOT - 1.2.0.1-SNAPSHOT - 1.2.0.1-SNAPSHOT - 1.2.0.1-SNAPSHOT - 1.2.0.1-SNAPSHOT - 1.2.0.1-SNAPSHOT - 1.2.0.1-SNAPSHOT - 1.2.0.1-SNAPSHOT - 1.2.0.1-SNAPSHOT - 1.2.0.1-SNAPSHOT - 1.2.0.1-SNAPSHOT - 1.2.0.1-SNAPSHOT - 1.2.0.1-SNAPSHOT - 1.2.0.1-SNAPSHOT - 1.2.0.1-SNAPSHOT - 1.2.0.1-SNAPSHOT + 1.2.0.1 + 1.2.0.1 + 1.2.0.1 + 1.2.0.1 + 1.2.0.1 + 1.2.0.1 + 1.2.0.1 + 1.2.0.1 + 1.2.0.1 + 1.2.0.1 + 1.2.0.1 + 1.2.0.1 + 1.2.0.1 + 1.2.0.1 + 1.2.0.1 + 1.2.0.1 **/dto/**, **/exception/*Exception.java, **/config/*Config.java, diff --git a/registration-processor/post-processor/pom.xml b/registration-processor/post-processor/pom.xml index 73341f5f14d..1cb6d98e72b 100644 --- a/registration-processor/post-processor/pom.xml +++ b/registration-processor/post-processor/pom.xml @@ -6,9 +6,9 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1 - 1.2.0.1-SNAPSHOT + 1.2.0.1 post-processor post-processor diff --git a/registration-processor/post-processor/registration-processor-credential-requestor-stage/pom.xml b/registration-processor/post-processor/registration-processor-credential-requestor-stage/pom.xml index ade795ed3e5..42b6df248be 100644 --- a/registration-processor/post-processor/registration-processor-credential-requestor-stage/pom.xml +++ b/registration-processor/post-processor/registration-processor-credential-requestor-stage/pom.xml @@ -6,10 +6,10 @@ io.mosip.registrationprocessor post-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1 registration-processor-credential-requestor-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1 UTF-8 UTF-8 diff --git a/registration-processor/post-processor/registration-processor-message-sender-stage/pom.xml b/registration-processor/post-processor/registration-processor-message-sender-stage/pom.xml index ddca10912f8..7c564fced35 100644 --- a/registration-processor/post-processor/registration-processor-message-sender-stage/pom.xml +++ b/registration-processor/post-processor/registration-processor-message-sender-stage/pom.xml @@ -7,11 +7,11 @@ io.mosip.registrationprocessor post-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1 registration-processor-message-sender-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1 UTF-8 UTF-8 diff --git a/registration-processor/post-processor/registration-processor-registration-transaction-service/pom.xml b/registration-processor/post-processor/registration-processor-registration-transaction-service/pom.xml index 2e3d4210fe5..035c98fe7e2 100644 --- a/registration-processor/post-processor/registration-processor-registration-transaction-service/pom.xml +++ b/registration-processor/post-processor/registration-processor-registration-transaction-service/pom.xml @@ -5,10 +5,10 @@ io.mosip.registrationprocessor post-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1 registration-processor-registration-transaction-service - 1.2.0.1-SNAPSHOT + 1.2.0.1 registration-processor-registration-transaction-service UTF-8 diff --git a/registration-processor/pre-processor/pom.xml b/registration-processor/pre-processor/pom.xml index 23941368b71..cb84ff3c167 100644 --- a/registration-processor/pre-processor/pom.xml +++ b/registration-processor/pre-processor/pom.xml @@ -7,9 +7,9 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1 - 1.2.0.1-SNAPSHOT + 1.2.0.1 pre-processor pre-processor diff --git a/registration-processor/pre-processor/registration-processor-cmd-validator-stage/pom.xml b/registration-processor/pre-processor/registration-processor-cmd-validator-stage/pom.xml index 099373ee95f..511ddba8e67 100644 --- a/registration-processor/pre-processor/registration-processor-cmd-validator-stage/pom.xml +++ b/registration-processor/pre-processor/registration-processor-cmd-validator-stage/pom.xml @@ -6,10 +6,10 @@ io.mosip.registrationprocessor pre-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1 registration-processor-cmd-validator-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1 registration-processor-cmd-validator-stage UTF-8 diff --git a/registration-processor/pre-processor/registration-processor-introducer-validator-stage/pom.xml b/registration-processor/pre-processor/registration-processor-introducer-validator-stage/pom.xml index 39b9fc3ac83..75dd868d51d 100644 --- a/registration-processor/pre-processor/registration-processor-introducer-validator-stage/pom.xml +++ b/registration-processor/pre-processor/registration-processor-introducer-validator-stage/pom.xml @@ -6,10 +6,10 @@ io.mosip.registrationprocessor pre-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1 registration-processor-introducer-validator-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1 registration-processor-introducer-validator-stage UTF-8 diff --git a/registration-processor/pre-processor/registration-processor-operator-validator-stage/pom.xml b/registration-processor/pre-processor/registration-processor-operator-validator-stage/pom.xml index 6c2fd429574..7fc3d0804fe 100644 --- a/registration-processor/pre-processor/registration-processor-operator-validator-stage/pom.xml +++ b/registration-processor/pre-processor/registration-processor-operator-validator-stage/pom.xml @@ -6,10 +6,10 @@ io.mosip.registrationprocessor pre-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1 registration-processor-operator-validator-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1 registration-processor-operator-validator-stage UTF-8 diff --git a/registration-processor/pre-processor/registration-processor-packet-classifier-stage/pom.xml b/registration-processor/pre-processor/registration-processor-packet-classifier-stage/pom.xml index d0f9e67ba80..d0a172f2f3f 100644 --- a/registration-processor/pre-processor/registration-processor-packet-classifier-stage/pom.xml +++ b/registration-processor/pre-processor/registration-processor-packet-classifier-stage/pom.xml @@ -7,10 +7,10 @@ io.mosip.registrationprocessor pre-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1 registration-processor-packet-classifier-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1 jar UTF-8 diff --git a/registration-processor/pre-processor/registration-processor-packet-uploader-stage/pom.xml b/registration-processor/pre-processor/registration-processor-packet-uploader-stage/pom.xml index d28b27ff418..35cd8db8546 100644 --- a/registration-processor/pre-processor/registration-processor-packet-uploader-stage/pom.xml +++ b/registration-processor/pre-processor/registration-processor-packet-uploader-stage/pom.xml @@ -9,9 +9,9 @@ io.mosip.registrationprocessor pre-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1 - 1.2.0.1-SNAPSHOT + 1.2.0.1 UTF-8 diff --git a/registration-processor/pre-processor/registration-processor-packet-validator-stage/pom.xml b/registration-processor/pre-processor/registration-processor-packet-validator-stage/pom.xml index 9485563f780..d3e4625cc80 100644 --- a/registration-processor/pre-processor/registration-processor-packet-validator-stage/pom.xml +++ b/registration-processor/pre-processor/registration-processor-packet-validator-stage/pom.xml @@ -7,10 +7,10 @@ io.mosip.registrationprocessor pre-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1 registration-processor-packet-validator-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1 jar UTF-8 diff --git a/registration-processor/pre-processor/registration-processor-quality-classifier-stage/pom.xml b/registration-processor/pre-processor/registration-processor-quality-classifier-stage/pom.xml index 6b7b4c50d00..348c648df3d 100644 --- a/registration-processor/pre-processor/registration-processor-quality-classifier-stage/pom.xml +++ b/registration-processor/pre-processor/registration-processor-quality-classifier-stage/pom.xml @@ -5,11 +5,11 @@ io.mosip.registrationprocessor pre-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1 registration-processor-quality-classifier-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1 UTF-8 diff --git a/registration-processor/pre-processor/registration-processor-securezone-notification-stage/pom.xml b/registration-processor/pre-processor/registration-processor-securezone-notification-stage/pom.xml index 5d796c8376a..d3ce4310014 100644 --- a/registration-processor/pre-processor/registration-processor-securezone-notification-stage/pom.xml +++ b/registration-processor/pre-processor/registration-processor-securezone-notification-stage/pom.xml @@ -5,10 +5,10 @@ pre-processor io.mosip.registrationprocessor - 1.2.0.1-SNAPSHOT + 1.2.0.1 4.0.0 - 1.2.0.1-SNAPSHOT + 1.2.0.1 registration-processor-securezone-notification-stage diff --git a/registration-processor/pre-processor/registration-processor-supervisor-validator-stage/pom.xml b/registration-processor/pre-processor/registration-processor-supervisor-validator-stage/pom.xml index 7caa4059e46..78fd91d1ec6 100644 --- a/registration-processor/pre-processor/registration-processor-supervisor-validator-stage/pom.xml +++ b/registration-processor/pre-processor/registration-processor-supervisor-validator-stage/pom.xml @@ -6,10 +6,10 @@ io.mosip.registrationprocessor pre-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1 registration-processor-supervisor-validator-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1 registration-processor-supervisor-validator-stage UTF-8 diff --git a/registration-processor/qc-users-manger/pom.xml b/registration-processor/qc-users-manger/pom.xml index 6f5129d7735..c18da4a005b 100644 --- a/registration-processor/qc-users-manger/pom.xml +++ b/registration-processor/qc-users-manger/pom.xml @@ -5,11 +5,11 @@ qc-users-manger - 1.2.0.1-SNAPSHOT + 1.2.0.1 io.mosip.registrationprocessor registration-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1 diff --git a/registration-processor/registration-processor-bio-dedupe-service-impl/pom.xml b/registration-processor/registration-processor-bio-dedupe-service-impl/pom.xml index 78f76c5951f..46d9250b4f7 100644 --- a/registration-processor/registration-processor-bio-dedupe-service-impl/pom.xml +++ b/registration-processor/registration-processor-bio-dedupe-service-impl/pom.xml @@ -5,11 +5,11 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1 registration-processor-bio-dedupe-service-impl - 1.2.0.1-SNAPSHOT + 1.2.0.1 registration-processor-bio-dedupe-service-impl diff --git a/registration-processor/registration-processor-common-camel-bridge/dependency-reduced-pom.xml b/registration-processor/registration-processor-common-camel-bridge/dependency-reduced-pom.xml index 84dcbf07157..69896df6196 100644 --- a/registration-processor/registration-processor-common-camel-bridge/dependency-reduced-pom.xml +++ b/registration-processor/registration-processor-common-camel-bridge/dependency-reduced-pom.xml @@ -3,11 +3,11 @@ registration-processor io.mosip.registrationprocessor - 1.2.0.1-SNAPSHOT + 1.2.0.1 4.0.0 registration-processor-common-camel-bridge - 1.2.0.1-SNAPSHOT + 1.2.0.1 @@ -102,7 +102,7 @@ io.mosip.registration.processor.camel.bridge.MosipCamelBridge 1.0.5 - 1.2.0.1-SNAPSHOT + 1.2.0.1 diff --git a/registration-processor/registration-processor-common-camel-bridge/pom.xml b/registration-processor/registration-processor-common-camel-bridge/pom.xml index f71a52f5c98..42de8bd5870 100644 --- a/registration-processor/registration-processor-common-camel-bridge/pom.xml +++ b/registration-processor/registration-processor-common-camel-bridge/pom.xml @@ -6,16 +6,16 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1 registration-processor-common-camel-bridge - 1.2.0.1-SNAPSHOT + 1.2.0.1 jar io.mosip.registration.processor.camel.bridge.MosipCamelBridge 1.0.5 - 1.2.0.1-SNAPSHOT + 1.2.0.1 diff --git a/registration-processor/registration-processor-core/pom.xml b/registration-processor/registration-processor-core/pom.xml index 15856637960..3f7ea3481ac 100644 --- a/registration-processor/registration-processor-core/pom.xml +++ b/registration-processor/registration-processor-core/pom.xml @@ -7,10 +7,10 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1 registration-processor-core - 1.2.0.1-SNAPSHOT + 1.2.0.1 org.mockito diff --git a/registration-processor/registration-processor-info-storage-service/pom.xml b/registration-processor/registration-processor-info-storage-service/pom.xml index a96ba4ed241..c2ab483f216 100644 --- a/registration-processor/registration-processor-info-storage-service/pom.xml +++ b/registration-processor/registration-processor-info-storage-service/pom.xml @@ -7,10 +7,10 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1 registration-processor-info-storage-service - 1.2.0.1-SNAPSHOT + 1.2.0.1 registration-processor-info-storage-service UTF-8 diff --git a/registration-processor/registration-processor-landing-zone/pom.xml b/registration-processor/registration-processor-landing-zone/pom.xml index f3d1e06edd0..ed97ba99ef2 100644 --- a/registration-processor/registration-processor-landing-zone/pom.xml +++ b/registration-processor/registration-processor-landing-zone/pom.xml @@ -5,11 +5,11 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1 registration-processor-landing-zone registration-processor-landing-zone - 1.2.0.1-SNAPSHOT + 1.2.0.1 UTF-8 diff --git a/registration-processor/registration-processor-message-sender-impl/pom.xml b/registration-processor/registration-processor-message-sender-impl/pom.xml index 4ec8cd0b4d0..bb35f136232 100644 --- a/registration-processor/registration-processor-message-sender-impl/pom.xml +++ b/registration-processor/registration-processor-message-sender-impl/pom.xml @@ -8,11 +8,11 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1 registration-processor-message-sender-impl - 1.2.0.1-SNAPSHOT + 1.2.0.1 UTF-8 diff --git a/registration-processor/registration-processor-notification-service/pom.xml b/registration-processor/registration-processor-notification-service/pom.xml index 8c37156f16c..de69ecf163a 100644 --- a/registration-processor/registration-processor-notification-service/pom.xml +++ b/registration-processor/registration-processor-notification-service/pom.xml @@ -8,15 +8,15 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1 registration-processor-notification-service - 1.2.0.1-SNAPSHOT + 1.2.0.1 UTF-8 UTF-8 - 1.2.0.1-SNAPSHOT + 1.2.0.1 diff --git a/registration-processor/registration-processor-packet-manager/pom.xml b/registration-processor/registration-processor-packet-manager/pom.xml index c6d8b1600eb..7fc4de5a7a4 100644 --- a/registration-processor/registration-processor-packet-manager/pom.xml +++ b/registration-processor/registration-processor-packet-manager/pom.xml @@ -7,12 +7,12 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1 registration-processor-packet-manager registration-processor-packet-manager - 1.2.0.1-SNAPSHOT + 1.2.0.1 UTF-8 diff --git a/registration-processor/registration-processor-registration-status-service-impl/pom.xml b/registration-processor/registration-processor-registration-status-service-impl/pom.xml index 599d1b7c828..5be0a472f78 100644 --- a/registration-processor/registration-processor-registration-status-service-impl/pom.xml +++ b/registration-processor/registration-processor-registration-status-service-impl/pom.xml @@ -8,10 +8,10 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1 registration-processor-registration-status-service-impl - 1.2.0.1-SNAPSHOT + 1.2.0.1 UTF-8 diff --git a/registration-processor/registration-processor-rest-client/pom.xml b/registration-processor/registration-processor-rest-client/pom.xml index 3d66c5b85ae..9333d20cd69 100644 --- a/registration-processor/registration-processor-rest-client/pom.xml +++ b/registration-processor/registration-processor-rest-client/pom.xml @@ -9,12 +9,12 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1 registration-processor-rest-client registration-processor-rest-client - 1.2.0.1-SNAPSHOT + 1.2.0.1 UTF-8 diff --git a/registration-processor/stage-groups/pom.xml b/registration-processor/stage-groups/pom.xml index 4abd296cb2c..9cd56ab6468 100644 --- a/registration-processor/stage-groups/pom.xml +++ b/registration-processor/stage-groups/pom.xml @@ -7,9 +7,9 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1 - 1.2.0.1-SNAPSHOT + 1.2.0.1 stage-groups stage-groups diff --git a/registration-processor/stage-groups/registration-processor-stage-group-1/pom.xml b/registration-processor/stage-groups/registration-processor-stage-group-1/pom.xml index d2c037eee4a..6fd025521cd 100644 --- a/registration-processor/stage-groups/registration-processor-stage-group-1/pom.xml +++ b/registration-processor/stage-groups/registration-processor-stage-group-1/pom.xml @@ -5,11 +5,11 @@ io.mosip.registrationprocessor stage-groups - 1.2.0.1-SNAPSHOT + 1.2.0.1 registration-processor-stage-group-1 - 1.2.0.1-SNAPSHOT + 1.2.0.1 UTF-8 @@ -21,14 +21,14 @@ io.mosip.registrationprocessor mosip-stage-executor - 1.2.0.1-SNAPSHOT + 1.2.0.1 io.mosip.registrationprocessor registration-processor-packet-receiver-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1 diff --git a/registration-processor/stage-groups/registration-processor-stage-group-2/pom.xml b/registration-processor/stage-groups/registration-processor-stage-group-2/pom.xml index c0cf46343d5..c691dc33a0e 100644 --- a/registration-processor/stage-groups/registration-processor-stage-group-2/pom.xml +++ b/registration-processor/stage-groups/registration-processor-stage-group-2/pom.xml @@ -5,11 +5,11 @@ io.mosip.registrationprocessor stage-groups - 1.2.0.1-SNAPSHOT + 1.2.0.1 registration-processor-stage-group-2 - 1.2.0.1-SNAPSHOT + 1.2.0.1 UTF-8 @@ -21,24 +21,24 @@ io.mosip.registrationprocessor mosip-stage-executor - 1.2.0.1-SNAPSHOT + 1.2.0.1 io.mosip.registrationprocessor registration-processor-quality-classifier-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1 io.mosip.registrationprocessor registration-processor-securezone-notification-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1 io.mosip.registrationprocessor registration-processor-message-sender-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1 diff --git a/registration-processor/stage-groups/registration-processor-stage-group-3/pom.xml b/registration-processor/stage-groups/registration-processor-stage-group-3/pom.xml index e96279087b6..9564721fe7d 100644 --- a/registration-processor/stage-groups/registration-processor-stage-group-3/pom.xml +++ b/registration-processor/stage-groups/registration-processor-stage-group-3/pom.xml @@ -5,11 +5,11 @@ io.mosip.registrationprocessor stage-groups - 1.2.0.1-SNAPSHOT + 1.2.0.1 registration-processor-stage-group-3 - 1.2.0.1-SNAPSHOT + 1.2.0.1 UTF-8 @@ -21,29 +21,29 @@ io.mosip.registrationprocessor mosip-stage-executor - 1.2.0.1-SNAPSHOT + 1.2.0.1 io.mosip.registrationprocessor registration-processor-abis-handler-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1 io.mosip.registrationprocessor registration-processor-abis-middleware-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1 io.mosip.registrationprocessor registration-processor-bio-dedupe-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1 io.mosip.registrationprocessor registration-processor-manual-adjudication-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1 diff --git a/registration-processor/stage-groups/registration-processor-stage-group-4/pom.xml b/registration-processor/stage-groups/registration-processor-stage-group-4/pom.xml index ce1cdc96545..073f75ad8e8 100644 --- a/registration-processor/stage-groups/registration-processor-stage-group-4/pom.xml +++ b/registration-processor/stage-groups/registration-processor-stage-group-4/pom.xml @@ -5,11 +5,11 @@ io.mosip.registrationprocessor stage-groups - 1.2.0.1-SNAPSHOT + 1.2.0.1 registration-processor-stage-group-4 - 1.2.0.1-SNAPSHOT + 1.2.0.1 UTF-8 @@ -21,19 +21,19 @@ io.mosip.registrationprocessor mosip-stage-executor - 1.2.0.1-SNAPSHOT + 1.2.0.1 io.mosip.registrationprocessor registration-processor-biometric-authentication-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1 io.mosip.registrationprocessor registration-processor-demo-dedupe-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1 diff --git a/registration-processor/stage-groups/registration-processor-stage-group-5/pom.xml b/registration-processor/stage-groups/registration-processor-stage-group-5/pom.xml index f167b1d15b3..568b76c0274 100644 --- a/registration-processor/stage-groups/registration-processor-stage-group-5/pom.xml +++ b/registration-processor/stage-groups/registration-processor-stage-group-5/pom.xml @@ -5,11 +5,11 @@ io.mosip.registrationprocessor stage-groups - 1.2.0.1-SNAPSHOT + 1.2.0.1 registration-processor-stage-group-5 - 1.2.0.1-SNAPSHOT + 1.2.0.1 UTF-8 @@ -21,34 +21,34 @@ io.mosip.registrationprocessor mosip-stage-executor - 1.2.0.1-SNAPSHOT + 1.2.0.1 io.mosip.registrationprocessor registration-processor-cmd-validator-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1 io.mosip.registrationprocessor registration-processor-operator-validator-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1 io.mosip.registrationprocessor registration-processor-supervisor-validator-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1 io.mosip.registrationprocessor registration-processor-introducer-validator-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1 io.mosip.registrationprocessor registration-processor-packet-validator-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1 diff --git a/registration-processor/stage-groups/registration-processor-stage-group-6/pom.xml b/registration-processor/stage-groups/registration-processor-stage-group-6/pom.xml index 114783da14d..860cf10a48e 100644 --- a/registration-processor/stage-groups/registration-processor-stage-group-6/pom.xml +++ b/registration-processor/stage-groups/registration-processor-stage-group-6/pom.xml @@ -5,11 +5,11 @@ io.mosip.registrationprocessor stage-groups - 1.2.0.1-SNAPSHOT + 1.2.0.1 registration-processor-stage-group-6 - 1.2.0.1-SNAPSHOT + 1.2.0.1 UTF-8 @@ -21,24 +21,24 @@ io.mosip.registrationprocessor mosip-stage-executor - 1.2.0.1-SNAPSHOT + 1.2.0.1 io.mosip.registrationprocessor registration-processor-packet-uploader-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1 io.mosip.registrationprocessor registration-processor-packet-classifier-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1 io.mosip.registrationprocessor registration-processor-verification-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1 diff --git a/registration-processor/stage-groups/registration-processor-stage-group-7/pom.xml b/registration-processor/stage-groups/registration-processor-stage-group-7/pom.xml index 7ec578c8372..ec539470a35 100644 --- a/registration-processor/stage-groups/registration-processor-stage-group-7/pom.xml +++ b/registration-processor/stage-groups/registration-processor-stage-group-7/pom.xml @@ -5,11 +5,11 @@ io.mosip.registrationprocessor stage-groups - 1.2.0.1-SNAPSHOT + 1.2.0.1 registration-processor-stage-group-7 - 1.2.0.1-SNAPSHOT + 1.2.0.1 UTF-8 @@ -21,29 +21,29 @@ io.mosip.registrationprocessor mosip-stage-executor - 1.2.0.1-SNAPSHOT + 1.2.0.1 io.mosip.registrationprocessor registration-processor-uin-generator-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1 io.mosip.registrationprocessor registration-processor-biometric-extraction-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1 io.mosip.registrationprocessor registration-processor-finalization-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1 io.mosip.registrationprocessor registration-processor-credential-requestor-stage - 1.2.0.1-SNAPSHOT + 1.2.0.1 diff --git a/registration-processor/workflow-engine/pom.xml b/registration-processor/workflow-engine/pom.xml index cebeb084931..49b52d674ad 100644 --- a/registration-processor/workflow-engine/pom.xml +++ b/registration-processor/workflow-engine/pom.xml @@ -5,9 +5,9 @@ io.mosip.registrationprocessor registration-processor - 1.2.0.1-SNAPSHOT + 1.2.0.1 - 1.2.0.1-SNAPSHOT + 1.2.0.1 workflow-engine workflow-engine diff --git a/registration-processor/workflow-engine/registration-processor-reprocessor/pom.xml b/registration-processor/workflow-engine/registration-processor-reprocessor/pom.xml index 8df1096a769..9b76dffed6e 100644 --- a/registration-processor/workflow-engine/registration-processor-reprocessor/pom.xml +++ b/registration-processor/workflow-engine/registration-processor-reprocessor/pom.xml @@ -7,10 +7,10 @@ io.mosip.registrationprocessor workflow-engine - 1.2.0.1-SNAPSHOT + 1.2.0.1 registration-processor-reprocessor - 1.2.0.1-SNAPSHOT + 1.2.0.1 registration-processor-reprocessor UTF-8 diff --git a/registration-processor/workflow-engine/registration-processor-workflow-manager-service/pom.xml b/registration-processor/workflow-engine/registration-processor-workflow-manager-service/pom.xml index c69945fe557..9923d3e4dc1 100644 --- a/registration-processor/workflow-engine/registration-processor-workflow-manager-service/pom.xml +++ b/registration-processor/workflow-engine/registration-processor-workflow-manager-service/pom.xml @@ -5,10 +5,10 @@ io.mosip.registrationprocessor workflow-engine - 1.2.0.1-SNAPSHOT + 1.2.0.1 registration-processor-workflow-manager-service - 1.2.0.1-SNAPSHOT + 1.2.0.1 registration-processor-workflow-manager-service UTF-8 From 08c73bd85f38aba9ad7c406e730e01ea7da6fa3e Mon Sep 17 00:00:00 2001 From: Praful Rakhade <99539100+Prafulrakhade@users.noreply.github.com> Date: Tue, 5 Mar 2024 12:11:57 +0530 Subject: [PATCH 130/133] [MOSIP-31887] (#1856) Signed-off-by: Praful Rakhade <99539100+Prafulrakhade@users.noreply.github.com> --- registration-processor/pom.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/registration-processor/pom.xml b/registration-processor/pom.xml index 524bf2405da..7b0ea730a7a 100644 --- a/registration-processor/pom.xml +++ b/registration-processor/pom.xml @@ -28,6 +28,7 @@ registration-processor Parent project of MOSIP Registration processor + https://github.com/mosip/registration none From 71fcda8b57b81901375b6ee611d8e87e5762ad76 Mon Sep 17 00:00:00 2001 From: Praful Rakhade <99539100+Prafulrakhade@users.noreply.github.com> Date: Tue, 5 Mar 2024 13:38:34 +0530 Subject: [PATCH 131/133] MOSIP-31887added missing pluggins and distribution url (#1857) * [MOSIP-31887] Signed-off-by: Praful Rakhade <99539100+Prafulrakhade@users.noreply.github.com> * MOSIP-31887added missing pluggins and distribution urlk Signed-off-by: Praful Rakhade <99539100+Prafulrakhade@users.noreply.github.com> --------- Signed-off-by: Praful Rakhade <99539100+Prafulrakhade@users.noreply.github.com> --- registration-processor/pom.xml | 52 +++++++++++++++++++++++++++++++++- 1 file changed, 51 insertions(+), 1 deletion(-) diff --git a/registration-processor/pom.xml b/registration-processor/pom.xml index 7b0ea730a7a..108513e41b8 100644 --- a/registration-processor/pom.xml +++ b/registration-processor/pom.xml @@ -297,7 +297,16 @@ - + + + ossrh + https://oss.sonatype.org/content/repositories/snapshots + + + ossrh + https://oss.sonatype.org/service/local/staging/deploy/maven2/ + + @@ -520,6 +529,47 @@ none + + 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 + + From f955167103093c3351598e030317490058be48a2 Mon Sep 17 00:00:00 2001 From: Sowmya Ujjappa Banakar Date: Wed, 6 Mar 2024 15:10:55 +0530 Subject: [PATCH 132/133] merged from release Signed-off-by: Sowmya Ujjappa Banakar --- .../impl/ManualAdjudicationServiceImpl.java | 3 - .../ManualAdjudicationServiceTest.java | 3 - .../service/impl/VerificationServiceImpl.java | 9 - .../test/CredentialRequestorStageTest.java | 956 +++--- .../operatorvalidator/OperatorValidator.java | 9 +- .../SupervisorValidator.java | 9 +- .../exception/util/PlatformErrorMessages.java | 2975 ++++++++--------- .../impl/MessageNotificationServiceImpl.java | 4 - 8 files changed, 1956 insertions(+), 2012 deletions(-) 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 900c6562801..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 @@ -206,9 +206,6 @@ public class ManualAdjudicationServiceImpl implements ManualAdjudicationService @Autowired private ManualVerificationUpdateUtility manualVerificationUpdateUtility; - @Autowired - private ManualVerificationUpdateUtility manualVerificationUpdateUtility; - /** The Constant PROTOCOL. */ public static final String PROTOCOL = "https"; 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 6d731c3a963..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 @@ -123,9 +123,6 @@ public class ManualAdjudicationServiceTest { @Mock AuditLogRequestBuilder auditLogRequestBuilder; - @Mock - private ManualVerificationUpdateUtility manualVerificationUpdateUtility; - @Mock RegistrationStatusService registrationStatusService; 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 34621700eee..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 @@ -3,9 +3,6 @@ import static io.mosip.registration.processor.verification.constants.VerificationConstants.DATETIME_PATTERN; import java.io.IOException; -import java.sql.Timestamp; -import java.time.LocalDateTime; -import java.time.ZoneId; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; @@ -34,7 +31,6 @@ import io.mosip.kernel.biometrics.entities.BiometricRecord; import io.mosip.kernel.biometrics.spi.CbeffUtil; -import io.mosip.kernel.core.dataaccess.exception.DataAccessLayerException; import io.mosip.kernel.core.logger.spi.Logger; import io.mosip.kernel.core.util.CryptoUtil; import io.mosip.kernel.core.util.DateUtils; @@ -73,8 +69,6 @@ import io.mosip.registration.processor.packet.storage.dto.ApplicantInfoDto; import io.mosip.registration.processor.packet.storage.dto.Document; import io.mosip.registration.processor.packet.storage.entity.VerificationEntity; -import io.mosip.registration.processor.packet.storage.entity.VerificationPKEntity; -import io.mosip.registration.processor.packet.storage.exception.UnableToInsertData; import io.mosip.registration.processor.packet.storage.repository.BasePacketRepository; import io.mosip.registration.processor.packet.storage.utils.PriorityBasedPacketManagerService; import io.mosip.registration.processor.packet.storage.utils.Utilities; @@ -196,9 +190,6 @@ public class VerificationServiceImpl implements VerificationService { @Autowired SaveVerificationRecordUtility saveVerificationRecordUtility; - @Autowired - SaveVerificationRecordUtility saveVerificationRecordUtility; - /** The Constant PROTOCOL. */ public static final String PROTOCOL = "https"; 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 fd467db798d..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,485 +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 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 0de71367222..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 @@ -2,7 +2,6 @@ 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; @@ -10,8 +9,6 @@ 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; @@ -24,7 +21,6 @@ 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; @@ -32,7 +28,6 @@ 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; @@ -49,6 +44,7 @@ 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; @@ -81,9 +77,6 @@ public class OperatorValidator { @Autowired private BioSdkUtil bioUtil; - @Autowired - private BioSdkUtil bioUtil; - /** * Checks if is valid Operator. * 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 b5619b3a12d..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 @@ -2,7 +2,6 @@ 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; @@ -10,8 +9,6 @@ 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; @@ -24,7 +21,6 @@ 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; @@ -32,7 +28,6 @@ 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; @@ -49,6 +44,7 @@ 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; @@ -81,9 +77,6 @@ public class SupervisorValidator { @Autowired private BioSdkUtil bioUtil; - @Autowired - private BioSdkUtil bioUtil; - /** * Checks if is valid Supervisor. * 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 d8f1ba556c2..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,1494 +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"), - - 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"), - - /** 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-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 8ec5b021f3f..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 @@ -170,10 +170,6 @@ public class MessageNotificationServiceImpl private JSONObject mapperIdentity=null; - private List mapperJsonKeys = null; - - private JSONObject mapperIdentity=null; - /* * (non-Javadoc) * From 2289e65934b7d8cda00bf3500409a7fc1a6bf303 Mon Sep 17 00:00:00 2001 From: Sowmya Ujjappa Banakar Date: Fri, 15 Mar 2024 17:25:50 +0530 Subject: [PATCH 133/133] Code review comments fixed Signed-off-by: Sowmya Ujjappa Banakar --- .../demodedupe/DemodedupeProcessor.java | 1308 ++++++++--------- .../config/RegistrationStatusConfigTest.java | 109 +- .../StageHealthCheckHandler.java | 2 - .../core/logger/RegProcessorLogger.java | 22 +- .../packet/storage/utils/Utilities.java | 19 +- .../rest/client/utils/RestApiClient.java | 640 ++++---- 6 files changed, 1025 insertions(+), 1075 deletions(-) diff --git a/registration-processor/core-processor/registration-processor-demo-dedupe-stage/src/main/java/io/mosip/registration/processor/stages/demodedupe/DemodedupeProcessor.java b/registration-processor/core-processor/registration-processor-demo-dedupe-stage/src/main/java/io/mosip/registration/processor/stages/demodedupe/DemodedupeProcessor.java index 729d8cc36b2..98750026c1f 100644 --- a/registration-processor/core-processor/registration-processor-demo-dedupe-stage/src/main/java/io/mosip/registration/processor/stages/demodedupe/DemodedupeProcessor.java +++ b/registration-processor/core-processor/registration-processor-demo-dedupe-stage/src/main/java/io/mosip/registration/processor/stages/demodedupe/DemodedupeProcessor.java @@ -1,655 +1,653 @@ -package io.mosip.registration.processor.stages.demodedupe; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Set; - -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.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -import io.mosip.kernel.core.fsadapter.exception.FSAdapterException; -import io.mosip.kernel.core.logger.spi.Logger; -import io.mosip.kernel.core.util.exception.JsonProcessingException; -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.AbisStatusCode; -import io.mosip.registration.processor.core.code.DedupeSourceName; -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.AbisConstant; -import io.mosip.registration.processor.core.constant.LoggerFileConstant; -import io.mosip.registration.processor.core.constant.MappingJsonConstants; -import io.mosip.registration.processor.core.constant.ProviderStageName; -import io.mosip.registration.processor.core.exception.ApisResourceAccessException; -import io.mosip.registration.processor.core.exception.PacketDecryptionFailureException; -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.Identity; -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.abis.RegDemoDedupeListDto; -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.spi.packetmanager.PacketInfoManager; -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.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.stages.app.constants.DemoDedupeConstants; -import io.mosip.registration.processor.stages.dto.DemoDedupeStatusDTO; -import io.mosip.registration.processor.status.code.RegistrationStatusCode; -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 DemodedupeProcessor. - */ -@Service -@Transactional -public class DemodedupeProcessor { - - /** The reg proc logger. */ - private static Logger regProcLogger = RegProcessorLogger.getLogger(DemodedupeProcessor.class); - private static final String MANUAL_VERIFICATION_STATUS = "PENDING"; - - /** The registration status service. */ - @Autowired - private RegistrationStatusService registrationStatusService; - - /** The core audit request builder. */ - @Autowired - private AuditLogRequestBuilder auditLogRequestBuilder; - - /** The demo dedupe. */ - @Autowired - private DemoDedupe demoDedupe; - - /** The packet info manager. */ - @Autowired - private PacketInfoManager packetInfoManager; - - - - /** The registration exception mapper util. */ - RegistrationExceptionMapperUtil registrationExceptionMapperUtil = new RegistrationExceptionMapperUtil(); - - /** The utility. */ - @Autowired - Utilities utility; - - /** The registration status dao. */ - @Autowired - private RegistrationStatusDao registrationStatusDao; - - /** The abis handler util. */ - @Autowired - private ABISHandlerUtil abisHandlerUtil; - - @Autowired - private Environment env; - - /** The is match found. */ - private volatile boolean isMatchFound = false; - - private static final String DEMODEDUPEENABLE = "mosip.registration.processor.demographic.deduplication.enable"; - - private static final String TRUE = "true"; - - private static final String GLOBAL_CONFIG_TRUE_VALUE = "Y"; - - /** The age limit. */ - @Value("${mosip.kernel.applicant.type.age.limit}") - private String ageLimit; - - @Value("${registration.processor.infant.dedupe}") - private String infantDedupe; - - @Value("${registration.processor.demodedupe.manual.adjudication.status}") - private String manualVerificationStatus; - - /** - * Process. - * - * @param object - * the object - * @param stageName - * the stage name - * @return the message DTO - */ - public MessageDTO process(MessageDTO object, String stageName) { - TrimExceptionMessage trimExceptionMessage = new TrimExceptionMessage(); - - String registrationId = object.getRid(); - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - registrationId, "DemoDedupeStage::DemoDedupeProcessor::entry"); - LogDescription description = new LogDescription(); - object.setMessageBusAddress(MessageBusAddress.DEMO_DEDUPE_BUS_IN); - object.setInternalError(Boolean.FALSE); - object.setIsValid(Boolean.FALSE); - isMatchFound = false; - - /** The duplicate dtos. */ - List duplicateDtos = new ArrayList<>(); - - boolean isTransactionSuccessful = false; - boolean isDemoDedupeSkip = true; - String moduleName = ModuleName.DEMO_DEDUPE.toString(); - String moduleId = PlatformSuccessMessages.RPR_PKR_DEMO_DE_DUP.getCode(); - boolean isDuplicateRequestForSameTransactionId = false; - InternalRegistrationStatusDto registrationStatusDto = registrationStatusService - .getRegistrationStatus(registrationId, object.getReg_type(), object.getIteration(), object.getWorkflowInstanceId()); - - try { - - IndividualDemographicDedupe demographicData = packetInfoManager. - getIdentityKeysAndFetchValuesFromJSON(registrationId, registrationStatusDto.getRegistrationType(), ProviderStageName.DEMO_DEDUPE); - - JSONObject regProcessorIdentityJson = utility.getRegistrationProcessorMappingJson(MappingJsonConstants.IDENTITY); - String uinFieldCheck = utility.getUIn(registrationId, registrationStatusDto.getRegistrationType(), ProviderStageName.DEMO_DEDUPE); - JSONObject jsonObject = utility.retrieveIdrepoJson(uinFieldCheck); - if (jsonObject == null) { - DemoDedupeStatusDTO demoDedupeStatusDTO = insertDemodedupDetailsAndPerformDedup(demographicData, registrationStatusDto, - duplicateDtos, object, moduleId, moduleName, isDemoDedupeSkip, description); - isTransactionSuccessful=demoDedupeStatusDTO.isTransactionSuccessful(); - duplicateDtos=demoDedupeStatusDTO.getDuplicateDtos(); - } else { - insertDemodedupDetails(demographicData, regProcessorIdentityJson, jsonObject, registrationStatusDto, - object, moduleId, moduleName); - } - if (abisHandlerUtil.getPacketStatus(registrationStatusDto) - .equalsIgnoreCase(AbisConstant.DUPLICATE_FOR_SAME_TRANSACTION_ID)) - isDuplicateRequestForSameTransactionId = true; - - registrationStatusDto.setRegistrationStageName(stageName); - if (isTransactionSuccessful) { - object.setIsValid(Boolean.TRUE); - } - - } catch (FSAdapterException e) { - registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.name()); - registrationStatusDto.setStatusComment(trimExceptionMessage - .trimExceptionMessage(StatusUtil.OBJECT_STORE_EXCEPTION.getMessage() + e.getMessage())); - registrationStatusDto.setSubStatusCode(StatusUtil.OBJECT_STORE_EXCEPTION.getCode()); - registrationStatusDto.setLatestTransactionStatusCode( - registrationExceptionMapperUtil.getStatusCode(RegistrationExceptionTypeCode.OBJECT_STORE_EXCEPTION)); - description.setCode(PlatformErrorMessages.PACKET_DEMO_PACKET_STORE_NOT_ACCESSIBLE.getCode()); - description.setMessage(PlatformErrorMessages.PACKET_DEMO_PACKET_STORE_NOT_ACCESSIBLE.getMessage()); - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), description.getCode(), registrationId, - description.getMessage() + ExceptionUtils.getStackTrace(e)); - object.setInternalError(Boolean.TRUE); - } catch (IllegalArgumentException e) { - registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.name()); - registrationStatusDto.setStatusComment(trimExceptionMessage - .trimExceptionMessage(StatusUtil.IIEGAL_ARGUMENT_EXCEPTION.getMessage() + e.getMessage())); - registrationStatusDto.setSubStatusCode(StatusUtil.IIEGAL_ARGUMENT_EXCEPTION.getCode()); - registrationStatusDto.setLatestTransactionStatusCode(registrationExceptionMapperUtil - .getStatusCode(RegistrationExceptionTypeCode.ILLEGAL_ARGUMENT_EXCEPTION)); - description.setCode(PlatformErrorMessages.PACKET_DEMO_DEDUPE_FAILED.getCode()); - description.setMessage(PlatformErrorMessages.PACKET_DEMO_DEDUPE_FAILED.getMessage()); - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), description.getCode(), registrationId, - description.getMessage() + ExceptionUtils.getStackTrace(e)); - object.setInternalError(Boolean.TRUE); - } catch (ApisResourceAccessException e) { - registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.name()); - registrationStatusDto.setStatusComment( - trimExceptionMessage.trimExceptionMessage(StatusUtil.API_RESOUCE_ACCESS_FAILED + e.getMessage())); - registrationStatusDto.setSubStatusCode(StatusUtil.API_RESOUCE_ACCESS_FAILED.getCode()); - registrationStatusDto.setLatestTransactionStatusCode(registrationExceptionMapperUtil - .getStatusCode(RegistrationExceptionTypeCode.APIS_RESOURCE_ACCESS_EXCEPTION)); - description.setCode(PlatformErrorMessages.RPR_DEMO_API_RESOUCE_ACCESS_FAILED.getCode()); - description.setMessage(PlatformErrorMessages.RPR_DEMO_API_RESOUCE_ACCESS_FAILED.getMessage()); - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), - description.getCode() + " -- " + LoggerFileConstant.REGISTRATIONID.toString(), registrationId, - description + "\n" + ExceptionUtils.getStackTrace(e)); - object.setInternalError(Boolean.TRUE); - } catch (Exception ex) { - registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.name()); - registrationStatusDto.setStatusComment(trimExceptionMessage - .trimExceptionMessage(StatusUtil.UNKNOWN_EXCEPTION_OCCURED.getMessage() + ex.getMessage())); - registrationStatusDto.setSubStatusCode(StatusUtil.UNKNOWN_EXCEPTION_OCCURED.getCode()); - registrationStatusDto.setLatestTransactionStatusCode( - registrationExceptionMapperUtil.getStatusCode(RegistrationExceptionTypeCode.EXCEPTION)); - description.setCode(PlatformErrorMessages.PACKET_DEMO_DEDUPE_FAILED.getCode()); - description.setMessage(PlatformErrorMessages.PACKET_DEMO_DEDUPE_FAILED.getMessage()); - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), description.getCode(), registrationId, - description.getMessage() + ExceptionUtils.getStackTrace(ex)); - object.setInternalError(Boolean.TRUE); - } finally { - if (!isDuplicateRequestForSameTransactionId) { - registrationStatusDto - .setLatestTransactionTypeCode(RegistrationTransactionTypeCode.DEMOGRAPHIC_VERIFICATION.toString()); - moduleId = isTransactionSuccessful ? PlatformSuccessMessages.RPR_PKR_DEMO_DE_DUP.getCode() - : description.getCode(); - - registrationStatusService.updateRegistrationStatus(registrationStatusDto, moduleId, moduleName); - try { - if (isMatchFound) { - saveDuplicateDtoList(duplicateDtos, registrationStatusDto, object); - } - } catch (Exception e) { - registrationStatusDto.setRegistrationStageName(stageName); - registrationStatusDto - .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.REPROCESS.toString()); - registrationStatusDto.setStatusComment(trimExceptionMessage - .trimExceptionMessage(StatusUtil.UNKNOWN_EXCEPTION_OCCURED.getMessage() + e.getMessage())); - registrationStatusDto.setSubStatusCode(StatusUtil.UNKNOWN_EXCEPTION_OCCURED.getCode()); - description.setMessage(DemoDedupeConstants.NO_DATA_IN_DEMO); - registrationStatusService.updateRegistrationStatus(registrationStatusDto, moduleId, moduleName); - - regProcLogger.error(DemoDedupeConstants.NO_DATA_IN_DEMO, "", "", ExceptionUtils.getStackTrace(e)); - object.setMessageBusAddress(MessageBusAddress.DEMO_DEDUPE_BUS_IN); - object.setInternalError(Boolean.TRUE); - } - - if (object.getInternalError()) { - updateErrorFlags(registrationStatusDto, object); - } - if (object.getIsValid() && !object.getInternalError()) - regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), - LoggerFileConstant.REGISTRATIONID.toString(), registrationId, "DemoDedupeProcessor::success"); - else - regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), - LoggerFileConstant.REGISTRATIONID.toString(), registrationId, "DemoDedupeProcessor::failure"); - - String eventId = isTransactionSuccessful ? EventId.RPR_402.toString() : EventId.RPR_405.toString(); - String eventName = isTransactionSuccessful ? EventName.UPDATE.toString() : EventName.EXCEPTION.toString(); - String eventType = isTransactionSuccessful ? EventType.BUSINESS.toString() : EventType.SYSTEM.toString(); - - auditLogRequestBuilder.createAuditRequestBuilder(description.getMessage(), eventId, eventName, eventType, - moduleId, moduleName, registrationId); - } else { - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - registrationId, "Duplicate request received for same latest transaction id. This will be ignored."); - object.setIsValid(false); - object.setInternalError(true); - } - } - - return object; - } - - - private void insertDemodedupDetails(IndividualDemographicDedupe demographicData, JSONObject regProcessorIdentityJson, - JSONObject jsonObject, InternalRegistrationStatusDto registrationStatusDto, MessageDTO object, - String moduleId, String moduleName) { - IndividualDemographicDedupe demoDedupeData = new IndividualDemographicDedupe(); - List jsonValueList = new ArrayList<>(); - if (demographicData.getName() == null || demographicData.getName().isEmpty()) { - String names = JsonUtil.getJSONValue(JsonUtil.getJSONObject(regProcessorIdentityJson, MappingJsonConstants.NAME), MappingJsonConstants.VALUE); - Arrays.stream(names.split(",")) - .forEach(name -> { - JsonValue[] nameArray = JsonUtil.getJsonValues(jsonObject, name); - if (nameArray != null) - jsonValueList.add(nameArray); - }); - } - if(demographicData.getName() == null || demographicData.getName().isEmpty()) - demoDedupeData.setName(jsonValueList.isEmpty() ? null : jsonValueList); - else - demoDedupeData.setName(demographicData.getName()); - demoDedupeData.setDateOfBirth(demographicData.getDateOfBirth() == null - ? JsonUtil.getJSONValue(jsonObject, JsonUtil.getJSONValue(JsonUtil.getJSONObject(regProcessorIdentityJson, MappingJsonConstants.DOB), MappingJsonConstants.VALUE)) - : demographicData.getDateOfBirth()); - demoDedupeData.setGender(demographicData.getGender() == null - ? JsonUtil.getJsonValues(jsonObject, - JsonUtil.getJSONValue(JsonUtil.getJSONObject(regProcessorIdentityJson, MappingJsonConstants.GENDER), MappingJsonConstants.VALUE)) - : demographicData.getGender()); - demoDedupeData.setPhone(demographicData.getPhone() == null - ? JsonUtil - .getJSONValue(jsonObject, - JsonUtil.getJSONValue(JsonUtil.getJSONObject(regProcessorIdentityJson, - MappingJsonConstants.PHONE), MappingJsonConstants.VALUE)) - : demographicData.getPhone()); - demoDedupeData.setEmail(demographicData.getEmail() == null - ? JsonUtil - .getJSONValue(jsonObject, - JsonUtil.getJSONValue(JsonUtil.getJSONObject(regProcessorIdentityJson, - MappingJsonConstants.EMAIL), MappingJsonConstants.VALUE)) - : demographicData.getEmail()); - - packetInfoManager.saveIndividualDemographicDedupeUpdatePacket(demoDedupeData, registrationStatusDto.getRegistrationId(), moduleId, - registrationStatusDto.getRegistrationType(),moduleName,registrationStatusDto.getIteration(), registrationStatusDto.getWorkflowInstanceId()); - object.setIsValid(Boolean.TRUE); - registrationStatusDto - .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.SUCCESS.toString()); - registrationStatusDto.setStatusComment(StatusUtil.DEMO_DEDUPE_SKIPPED.getMessage()); - registrationStatusDto.setSubStatusCode(StatusUtil.DEMO_DEDUPE_SKIPPED.getCode()); - registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); - - } - - - private DemoDedupeStatusDTO insertDemodedupDetailsAndPerformDedup(IndividualDemographicDedupe demographicData, - InternalRegistrationStatusDto registrationStatusDto, List duplicateDtos, - MessageDTO object, String moduleId, String moduleName, boolean isDemoDedupeSkip, LogDescription description) - throws ApisResourceAccessException, - JsonProcessingException, PacketManagerException, IOException, PacketDecryptionFailureException, io.mosip.kernel.core.exception.IOException, RegistrationProcessorCheckedException { - DemoDedupeStatusDTO demoDedupeStatusDTO=new DemoDedupeStatusDTO(); - boolean isTransactionSuccessful = false; - String packetStatus = abisHandlerUtil.getPacketStatus(registrationStatusDto); - String registrationId=registrationStatusDto.getRegistrationId(); - if (packetStatus.equalsIgnoreCase(AbisConstant.PRE_ABIS_IDENTIFICATION)) { - packetInfoManager.saveIndividualDemographicDedupeUpdatePacket(demographicData, registrationId, moduleId, - registrationStatusDto.getRegistrationType(),moduleName,registrationStatusDto.getIteration(), registrationStatusDto.getWorkflowInstanceId()); - int age = utility.getApplicantAge(registrationId, registrationStatusDto.getRegistrationType(), ProviderStageName.DEMO_DEDUPE); - int ageThreshold = Integer.parseInt(ageLimit); - if (age < ageThreshold) { - if (infantDedupe.equalsIgnoreCase(GLOBAL_CONFIG_TRUE_VALUE)) { - isDemoDedupeSkip = false; - duplicateDtos = performDemoDedupe(registrationStatusDto, object, description); - if (duplicateDtos.isEmpty()) - isTransactionSuccessful = true; - } - } - else { - String demo=env.getProperty(DEMODEDUPEENABLE); - if (demo != null && demo.trim().equalsIgnoreCase(TRUE)) { - isDemoDedupeSkip = false; - duplicateDtos = performDemoDedupe(registrationStatusDto, object, description); - if (duplicateDtos.isEmpty()) - isTransactionSuccessful = true; - } - } - - if (isDemoDedupeSkip) { - object.setIsValid(Boolean.TRUE); - registrationStatusDto - .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.SUCCESS.toString()); - registrationStatusDto.setStatusComment(StatusUtil.DEMO_DEDUPE_SKIPPED.getMessage()); - registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); - registrationStatusDto.setSubStatusCode(StatusUtil.DEMO_DEDUPE_SKIPPED.getCode()); - description.setCode(PlatformSuccessMessages.RPR_PKR_DEMO_DE_DUP_SKIP.getCode()); - description.setMessage(PlatformSuccessMessages.RPR_PKR_DEMO_DE_DUP_SKIP.getMessage() + " -- " - + registrationId); - regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), description.getCode(), - registrationId, description.getMessage()); - registrationStatusDto.setUpdatedBy(DemoDedupeConstants.USER); - regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), - LoggerFileConstant.REGISTRATIONID.toString(), registrationStatusDto.getRegistrationId(), - DemoDedupeConstants.DEMO_SKIP); - } - }else if (packetStatus.equalsIgnoreCase(AbisConstant.POST_ABIS_IDENTIFICATION)) { - isTransactionSuccessful = processDemoDedupeRequesthandler(registrationStatusDto, object, - description); - } - demoDedupeStatusDTO.setTransactionSuccessful(isTransactionSuccessful); - demoDedupeStatusDTO.setDuplicateDtos(duplicateDtos); - return demoDedupeStatusDTO; - - } - - - - - /** - * Perform demo dedupe. - * - * @param registrationStatusDto - * the registration status dto - * @param object - * the object - * @param description - * @return true, if successful - */ - private List performDemoDedupe(InternalRegistrationStatusDto registrationStatusDto, - MessageDTO object, LogDescription description) { - String registrationId = registrationStatusDto.getRegistrationId(); - // Potential Duplicate Ids after performing demo dedupe - List duplicateDtos = demoDedupe.performDedupe(registrationStatusDto.getRegistrationId()); - duplicateDtos.removeIf(dto -> dto.getRegId().equals(registrationStatusDto.getRegistrationId())); - if (!duplicateDtos.isEmpty()) { - isMatchFound = true; - registrationStatusDto - .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.IN_PROGRESS.toString()); - registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); - registrationStatusDto.setStatusComment(StatusUtil.POTENTIAL_MATCH_FOUND.getMessage()); - registrationStatusDto.setSubStatusCode(StatusUtil.POTENTIAL_MATCH_FOUND.getCode()); - object.setMessageBusAddress(MessageBusAddress.ABIS_HANDLER_BUS_IN); - object.setIsValid(Boolean.TRUE); - description.setCode(PlatformSuccessMessages.RPR_PKR_DEMO_DE_DUP.getCode()); - description.setMessage(DemoDedupeConstants.RECORD_INSERTED_FROM_ABIS_HANDLER + " -- " + registrationId); - regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - registrationStatusDto.getRegistrationId(), DemoDedupeConstants.RECORD_INSERTED_FROM_ABIS_HANDLER); - - } else { - object.setIsValid(Boolean.TRUE); - registrationStatusDto.setLatestTransactionStatusCode(RegistrationTransactionStatusCode.SUCCESS.toString()); - registrationStatusDto.setStatusComment(StatusUtil.DEMO_DEDUPE_SUCCESS.getMessage()); - registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); - registrationStatusDto.setSubStatusCode(StatusUtil.DEMO_DEDUPE_SUCCESS.getCode()); - description.setCode(PlatformSuccessMessages.RPR_PKR_DEMO_DE_DUP.getCode()); - description.setMessage(PlatformSuccessMessages.RPR_PKR_DEMO_DE_DUP.getMessage() + " -- " + registrationId); - regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), description.getCode(), registrationId, - description.getMessage()); - registrationStatusDto.setUpdatedBy(DemoDedupeConstants.USER); - regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - registrationStatusDto.getRegistrationId(), DemoDedupeConstants.DEMO_SUCCESS); - } - return duplicateDtos; - } - - /** - * Gets the latest transaction id. - * - * @param registrationId - * the registration id - * @return the latest transaction id - */ - private String getLatestTransactionId(String registrationId, String process, int iteration, String workflowInstanceId) { - RegistrationStatusEntity entity = registrationStatusDao.find(registrationId, process, iteration, workflowInstanceId); - return entity != null ? entity.getLatestRegistrationTransactionId() : null; - } - - /** - * Process demo dedupe requesthandler. - * - * @param registrationStatusDto the registration status dto - * @param object the object - * @param description - * @return true, if successful - * @throws ApisResourceAccessException the apis resource access - * exception - * @throws IOException Signals that an I/O exception - * has occurred. - */ - private boolean processDemoDedupeRequesthandler(InternalRegistrationStatusDto registrationStatusDto, - MessageDTO object, LogDescription description) - throws ApisResourceAccessException, IOException, JsonProcessingException, PacketManagerException { - boolean isTransactionSuccessful = false; - List responsIds = new ArrayList<>(); - - String latestTransactionId = getLatestTransactionId(registrationStatusDto.getRegistrationId(), - registrationStatusDto.getRegistrationType(), registrationStatusDto.getIteration(), registrationStatusDto.getWorkflowInstanceId()); - - List abisResponseDto = packetInfoManager.getAbisResponseRecords(latestTransactionId, - DemoDedupeConstants.IDENTIFY); - - for (AbisResponseDto responseDto : abisResponseDto) { - if (responseDto.getStatusCode().equalsIgnoreCase(AbisStatusCode.SUCCESS.toString())) { - responsIds.add(responseDto.getId()); - } else { - isTransactionSuccessful = true; - int retryCount = registrationStatusDto.getRetryCount() != null - ? registrationStatusDto.getRetryCount() + 1 - : 1; - description.setMessage( - DemoDedupeConstants.SENDING_TO_REPROCESS + " -- " + registrationStatusDto.getRegistrationId()); - registrationStatusDto.setRetryCount(retryCount); - - registrationStatusDto.setLatestTransactionStatusCode(registrationExceptionMapperUtil - .getStatusCode(RegistrationExceptionTypeCode.DEMO_DEDUPE_ABIS_RESPONSE_ERROR)); - registrationStatusDto.setStatusComment(StatusUtil.DEMO_DEDUPE_FAILED_IN_ABIS.getMessage()); - registrationStatusDto.setSubStatusCode(StatusUtil.DEMO_DEDUPE_FAILED_IN_ABIS.getCode()); - registrationStatusDto.setStatusCode(RegistrationStatusCode.REJECTED.toString()); - regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), - LoggerFileConstant.REGISTRATIONID.toString(), registrationStatusDto.getRegistrationId(), - DemoDedupeConstants.SENDING_TO_REPROCESS); - } - } - - if (!responsIds.isEmpty()) { - List abisResponseDetDto = packetInfoManager.getAbisResponseDetRecordsList(responsIds); - if (abisResponseDetDto.isEmpty()) { - object.setIsValid(Boolean.TRUE); - registrationStatusDto - .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.SUCCESS.toString()); - registrationStatusDto.setStatusComment(StatusUtil.DEMO_DEDUPE_SUCCESS.getMessage()); - registrationStatusDto.setSubStatusCode(StatusUtil.DEMO_DEDUPE_SUCCESS.getCode()); - registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); - regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), - LoggerFileConstant.REGISTRATIONID.toString(), registrationStatusDto.getRegistrationId(), - DemoDedupeConstants.NO_DUPLICATES_FOUND); - isTransactionSuccessful = true; - description.setCode(PlatformSuccessMessages.RPR_PKR_DEMO_DE_DUP.getCode()); - description.setMessage(PlatformSuccessMessages.RPR_PKR_DEMO_DE_DUP.getMessage()); - } else { - if (manualVerificationStatus != null && manualVerificationStatus.equalsIgnoreCase(MANUAL_VERIFICATION_STATUS)) { - //send message to manual adjudication - object.setInternalError(Boolean.FALSE); - object.setRid(registrationStatusDto.getRegistrationId()); - object.setIsValid(Boolean.TRUE); - object.setMessageBusAddress(MessageBusAddress.MANUAL_ADJUDICATION_BUS_IN); - registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.toString()); - } else { - object.setIsValid(Boolean.FALSE); - registrationStatusDto.setStatusCode(RegistrationStatusCode.REJECTED.toString()); - } - - registrationStatusDto - .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.FAILED.toString()); - registrationStatusDto.setStatusComment(StatusUtil.POTENTIAL_MATCH_FOUND_IN_ABIS.getMessage()); - registrationStatusDto.setSubStatusCode(StatusUtil.POTENTIAL_MATCH_FOUND_IN_ABIS.getCode()); - description.setCode(PlatformErrorMessages.RPR_DEMO_SENDING_FOR_MANUAL.getCode()); - description.setMessage(PlatformErrorMessages.RPR_DEMO_SENDING_FOR_MANUAL.getMessage()); - saveManualAdjudicationData(registrationStatusDto, object); - regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), - LoggerFileConstant.REGISTRATIONID.toString(), registrationStatusDto.getRegistrationId(), - DemoDedupeConstants.SENDING_FOR_MANUAL); - - } - } - - return isTransactionSuccessful; - } - - /** - * Save duplicate dto list. - * - * @param duplicateDtos - * the duplicate dtos - * @param registrationStatusDto - * the registration status dto - * @return true, if successful - */ - private boolean saveDuplicateDtoList(List duplicateDtos, - InternalRegistrationStatusDto registrationStatusDto, MessageDTO object) { - boolean isDataSaved = false; - int numberOfProcessedPackets = 0; - - String moduleId = PlatformSuccessMessages.RPR_PKR_DEMO_DE_DUP.getCode(); - - String moduleName = ModuleName.DEMO_DEDUPE.toString(); - for (DemographicInfoDto demographicInfoDto : duplicateDtos) { - InternalRegistrationStatusDto potentialMatchRegistrationDto = registrationStatusService - .getRegistrationStatus(demographicInfoDto.getRegId(), - registrationStatusDto.getRegistrationType(), registrationStatusDto.getIteration(), registrationStatusDto.getWorkflowInstanceId()); - if (potentialMatchRegistrationDto.getLatestTransactionStatusCode() - .equalsIgnoreCase(RegistrationTransactionStatusCode.REPROCESS.toString()) - || potentialMatchRegistrationDto.getLatestTransactionStatusCode() - .equalsIgnoreCase(AbisConstant.RE_REGISTER)) { - regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), - LoggerFileConstant.REGISTRATIONID.toString(), registrationStatusDto.getRegistrationId(), - DemoDedupeConstants.REJECTED_OR_REREGISTER); - } else if (potentialMatchRegistrationDto.getLatestTransactionStatusCode() - .equalsIgnoreCase(RegistrationTransactionStatusCode.IN_PROGRESS.toString()) - || potentialMatchRegistrationDto.getLatestTransactionStatusCode() - .equalsIgnoreCase(RegistrationTransactionStatusCode.PROCESSED.toString())) { - String latestTransactionId = getLatestTransactionId(registrationStatusDto.getRegistrationId(), - registrationStatusDto.getRegistrationType(), registrationStatusDto.getIteration(), registrationStatusDto.getWorkflowInstanceId()); - RegDemoDedupeListDto regDemoDedupeListDto = new RegDemoDedupeListDto(); - regDemoDedupeListDto.setRegId(registrationStatusDto.getRegistrationId()); - regDemoDedupeListDto.setMatchedRegId(demographicInfoDto.getRegId()); - regDemoDedupeListDto.setRegtrnId(latestTransactionId); - regDemoDedupeListDto.setIsDeleted(Boolean.FALSE); - regDemoDedupeListDto.setCrBy(DemoDedupeConstants.CREATED_BY); - packetInfoManager.saveDemoDedupePotentialData(regDemoDedupeListDto, moduleId, moduleName); - isDataSaved = true; - numberOfProcessedPackets++; - } else { - regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), - LoggerFileConstant.REGISTRATIONID.toString(), registrationStatusDto.getRegistrationId(), - "The packet status is something different"); - } - if (numberOfProcessedPackets == 0) { - object.setIsValid(Boolean.TRUE); - } - } - return isDataSaved; - } - - /** - * Save manual adjudication data. - * - * @param registrationStatusDto the registration status dto - * @throws ApisResourceAccessException the apis resource access - * exception - * @throws IOException Signals that an I/O exception - * has occurred. - * @throws io.mosip.kernel.core.exception.IOException - * @throws PacketDecryptionFailureException - * @throws RegistrationProcessorCheckedException - */ - private void saveManualAdjudicationData(InternalRegistrationStatusDto registrationStatusDto, MessageDTO messageDTO) - throws ApisResourceAccessException, IOException, JsonProcessingException, PacketManagerException { - Set matchedRegIds = abisHandlerUtil.getUniqueRegIds(registrationStatusDto.getRegistrationId(), - registrationStatusDto.getRegistrationType(), registrationStatusDto.getIteration(), - registrationStatusDto.getWorkflowInstanceId(), ProviderStageName.DEMO_DEDUPE); - if (!matchedRegIds.isEmpty()) { - String moduleId = PlatformErrorMessages.RPR_DEMO_SENDING_FOR_MANUAL.getCode(); - String moduleName = ModuleName.DEMO_DEDUPE.toString(); - packetInfoManager.saveManualAdjudicationData(matchedRegIds, messageDTO, - DedupeSourceName.DEMO, moduleId, moduleName,null,null); - } else { - regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - registrationStatusDto.getRegistrationId(), DemoDedupeConstants.NO_MATCH_FOUND); - } - - } - - private void updateErrorFlags(InternalRegistrationStatusDto registrationStatusDto, MessageDTO object) { - object.setInternalError(true); - if (registrationStatusDto.getLatestTransactionStatusCode() - .equalsIgnoreCase(RegistrationTransactionStatusCode.REPROCESS.toString())) { - object.setIsValid(true); - } else { - object.setIsValid(false); - } - } - -} +package io.mosip.registration.processor.stages.demodedupe; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Set; + +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.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import io.mosip.kernel.core.fsadapter.exception.FSAdapterException; +import io.mosip.kernel.core.logger.spi.Logger; +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.AbisStatusCode; +import io.mosip.registration.processor.core.code.DedupeSourceName; +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.AbisConstant; +import io.mosip.registration.processor.core.constant.LoggerFileConstant; +import io.mosip.registration.processor.core.constant.MappingJsonConstants; +import io.mosip.registration.processor.core.constant.ProviderStageName; +import io.mosip.registration.processor.core.exception.ApisResourceAccessException; +import io.mosip.registration.processor.core.exception.PacketDecryptionFailureException; +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.Identity; +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.abis.RegDemoDedupeListDto; +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.spi.packetmanager.PacketInfoManager; +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.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.stages.app.constants.DemoDedupeConstants; +import io.mosip.registration.processor.stages.dto.DemoDedupeStatusDTO; +import io.mosip.registration.processor.status.code.RegistrationStatusCode; +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 DemodedupeProcessor. + */ +@Service +@Transactional +public class DemodedupeProcessor { + + /** The reg proc logger. */ + private static Logger regProcLogger = RegProcessorLogger.getLogger(DemodedupeProcessor.class); + private static final String MANUAL_VERIFICATION_STATUS = "PENDING"; + + /** The registration status service. */ + @Autowired + private RegistrationStatusService registrationStatusService; + + /** The core audit request builder. */ + @Autowired + private AuditLogRequestBuilder auditLogRequestBuilder; + + /** The demo dedupe. */ + @Autowired + private DemoDedupe demoDedupe; + + /** The packet info manager. */ + @Autowired + private PacketInfoManager packetInfoManager; + + + + /** The registration exception mapper util. */ + RegistrationExceptionMapperUtil registrationExceptionMapperUtil = new RegistrationExceptionMapperUtil(); + + /** The utility. */ + @Autowired + Utilities utility; + + /** The registration status dao. */ + @Autowired + private RegistrationStatusDao registrationStatusDao; + + /** The abis handler util. */ + @Autowired + private ABISHandlerUtil abisHandlerUtil; + + @Autowired + private Environment env; + + /** The is match found. */ + private volatile boolean isMatchFound = false; + + private static final String DEMODEDUPEENABLE = "mosip.registration.processor.demographic.deduplication.enable"; + + private static final String TRUE = "true"; + + private static final String GLOBAL_CONFIG_TRUE_VALUE = "Y"; + + /** The age limit. */ + @Value("${mosip.kernel.applicant.type.age.limit}") + private String ageLimit; + + @Value("${registration.processor.infant.dedupe}") + private String infantDedupe; + + @Value("${registration.processor.demodedupe.manual.adjudication.status}") + private String manualVerificationStatus; + + /** + * Process. + * + * @param object + * the object + * @param stageName + * the stage name + * @return the message DTO + */ + public MessageDTO process(MessageDTO object, String stageName) { + TrimExceptionMessage trimExceptionMessage = new TrimExceptionMessage(); + + String registrationId = object.getRid(); + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + registrationId, "DemoDedupeStage::DemoDedupeProcessor::entry"); + LogDescription description = new LogDescription(); + object.setMessageBusAddress(MessageBusAddress.DEMO_DEDUPE_BUS_IN); + object.setInternalError(Boolean.FALSE); + object.setIsValid(Boolean.FALSE); + isMatchFound = false; + + /** The duplicate dtos. */ + List duplicateDtos = new ArrayList<>(); + + boolean isTransactionSuccessful = false; + boolean isDemoDedupeSkip = true; + String moduleName = ModuleName.DEMO_DEDUPE.toString(); + String moduleId = PlatformSuccessMessages.RPR_PKR_DEMO_DE_DUP.getCode(); + boolean isDuplicateRequestForSameTransactionId = false; + InternalRegistrationStatusDto registrationStatusDto = registrationStatusService + .getRegistrationStatus(registrationId, object.getReg_type(), object.getIteration(), object.getWorkflowInstanceId()); + + try { + + IndividualDemographicDedupe demographicData = packetInfoManager. + getIdentityKeysAndFetchValuesFromJSON(registrationId, registrationStatusDto.getRegistrationType(), ProviderStageName.DEMO_DEDUPE); + + JSONObject regProcessorIdentityJson = utility.getRegistrationProcessorMappingJson(MappingJsonConstants.IDENTITY); + String uinFieldCheck = utility.getUIn(registrationId, registrationStatusDto.getRegistrationType(), ProviderStageName.DEMO_DEDUPE); + JSONObject jsonObject = utility.retrieveIdrepoJson(uinFieldCheck); + if (jsonObject == null) { + DemoDedupeStatusDTO demoDedupeStatusDTO = insertDemodedupDetailsAndPerformDedup(demographicData, registrationStatusDto, + duplicateDtos, object, moduleId, moduleName, isDemoDedupeSkip, description); + isTransactionSuccessful=demoDedupeStatusDTO.isTransactionSuccessful(); + duplicateDtos=demoDedupeStatusDTO.getDuplicateDtos(); + } else { + insertDemodedupDetails(demographicData, regProcessorIdentityJson, jsonObject, registrationStatusDto, + object, moduleId, moduleName); + } + if (abisHandlerUtil.getPacketStatus(registrationStatusDto) + .equalsIgnoreCase(AbisConstant.DUPLICATE_FOR_SAME_TRANSACTION_ID)) + isDuplicateRequestForSameTransactionId = true; + + registrationStatusDto.setRegistrationStageName(stageName); + if (isTransactionSuccessful) { + object.setIsValid(Boolean.TRUE); + } + + } catch (FSAdapterException e) { + registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.name()); + registrationStatusDto.setStatusComment(trimExceptionMessage + .trimExceptionMessage(StatusUtil.OBJECT_STORE_EXCEPTION.getMessage() + e.getMessage())); + registrationStatusDto.setSubStatusCode(StatusUtil.OBJECT_STORE_EXCEPTION.getCode()); + registrationStatusDto.setLatestTransactionStatusCode( + registrationExceptionMapperUtil.getStatusCode(RegistrationExceptionTypeCode.OBJECT_STORE_EXCEPTION)); + description.setCode(PlatformErrorMessages.PACKET_DEMO_PACKET_STORE_NOT_ACCESSIBLE.getCode()); + description.setMessage(PlatformErrorMessages.PACKET_DEMO_PACKET_STORE_NOT_ACCESSIBLE.getMessage()); + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), description.getCode(), registrationId, + description.getMessage() + ExceptionUtils.getStackTrace(e)); + object.setInternalError(Boolean.TRUE); + } catch (IllegalArgumentException e) { + registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.name()); + registrationStatusDto.setStatusComment(trimExceptionMessage + .trimExceptionMessage(StatusUtil.IIEGAL_ARGUMENT_EXCEPTION.getMessage() + e.getMessage())); + registrationStatusDto.setSubStatusCode(StatusUtil.IIEGAL_ARGUMENT_EXCEPTION.getCode()); + registrationStatusDto.setLatestTransactionStatusCode(registrationExceptionMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.ILLEGAL_ARGUMENT_EXCEPTION)); + description.setCode(PlatformErrorMessages.PACKET_DEMO_DEDUPE_FAILED.getCode()); + description.setMessage(PlatformErrorMessages.PACKET_DEMO_DEDUPE_FAILED.getMessage()); + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), description.getCode(), registrationId, + description.getMessage() + ExceptionUtils.getStackTrace(e)); + object.setInternalError(Boolean.TRUE); + } catch (ApisResourceAccessException e) { + registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.name()); + registrationStatusDto.setStatusComment( + trimExceptionMessage.trimExceptionMessage(StatusUtil.API_RESOUCE_ACCESS_FAILED + e.getMessage())); + registrationStatusDto.setSubStatusCode(StatusUtil.API_RESOUCE_ACCESS_FAILED.getCode()); + registrationStatusDto.setLatestTransactionStatusCode(registrationExceptionMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.APIS_RESOURCE_ACCESS_EXCEPTION)); + description.setCode(PlatformErrorMessages.RPR_DEMO_API_RESOUCE_ACCESS_FAILED.getCode()); + description.setMessage(PlatformErrorMessages.RPR_DEMO_API_RESOUCE_ACCESS_FAILED.getMessage()); + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), + description.getCode() + " -- " + LoggerFileConstant.REGISTRATIONID.toString(), registrationId, + description + "\n" + ExceptionUtils.getStackTrace(e)); + object.setInternalError(Boolean.TRUE); + } catch (Exception ex) { + registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.name()); + registrationStatusDto.setStatusComment(trimExceptionMessage + .trimExceptionMessage(StatusUtil.UNKNOWN_EXCEPTION_OCCURED.getMessage() + ex.getMessage())); + registrationStatusDto.setSubStatusCode(StatusUtil.UNKNOWN_EXCEPTION_OCCURED.getCode()); + registrationStatusDto.setLatestTransactionStatusCode( + registrationExceptionMapperUtil.getStatusCode(RegistrationExceptionTypeCode.EXCEPTION)); + description.setCode(PlatformErrorMessages.PACKET_DEMO_DEDUPE_FAILED.getCode()); + description.setMessage(PlatformErrorMessages.PACKET_DEMO_DEDUPE_FAILED.getMessage()); + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), description.getCode(), registrationId, + description.getMessage() + ExceptionUtils.getStackTrace(ex)); + object.setInternalError(Boolean.TRUE); + } finally { + if (!isDuplicateRequestForSameTransactionId) { + registrationStatusDto + .setLatestTransactionTypeCode(RegistrationTransactionTypeCode.DEMOGRAPHIC_VERIFICATION.toString()); + moduleId = isTransactionSuccessful ? PlatformSuccessMessages.RPR_PKR_DEMO_DE_DUP.getCode() + : description.getCode(); + + registrationStatusService.updateRegistrationStatus(registrationStatusDto, moduleId, moduleName); + try { + if (isMatchFound) { + saveDuplicateDtoList(duplicateDtos, registrationStatusDto, object); + } + } catch (Exception e) { + registrationStatusDto.setRegistrationStageName(stageName); + registrationStatusDto + .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.REPROCESS.toString()); + registrationStatusDto.setStatusComment(trimExceptionMessage + .trimExceptionMessage(StatusUtil.UNKNOWN_EXCEPTION_OCCURED.getMessage() + e.getMessage())); + registrationStatusDto.setSubStatusCode(StatusUtil.UNKNOWN_EXCEPTION_OCCURED.getCode()); + description.setMessage(DemoDedupeConstants.NO_DATA_IN_DEMO); + registrationStatusService.updateRegistrationStatus(registrationStatusDto, moduleId, moduleName); + + regProcLogger.error(DemoDedupeConstants.NO_DATA_IN_DEMO, "", "", ExceptionUtils.getStackTrace(e)); + object.setMessageBusAddress(MessageBusAddress.DEMO_DEDUPE_BUS_IN); + object.setInternalError(Boolean.TRUE); + } + + if (object.getInternalError()) { + updateErrorFlags(registrationStatusDto, object); + } + if (object.getIsValid() && !object.getInternalError()) + regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString(), registrationId, "DemoDedupeProcessor::success"); + else + regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString(), registrationId, "DemoDedupeProcessor::failure"); + + String eventId = isTransactionSuccessful ? EventId.RPR_402.toString() : EventId.RPR_405.toString(); + String eventName = isTransactionSuccessful ? EventName.UPDATE.toString() : EventName.EXCEPTION.toString(); + String eventType = isTransactionSuccessful ? EventType.BUSINESS.toString() : EventType.SYSTEM.toString(); + + auditLogRequestBuilder.createAuditRequestBuilder(description.getMessage(), eventId, eventName, eventType, + moduleId, moduleName, registrationId); + } else { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + registrationId, "Duplicate request received for same latest transaction id. This will be ignored."); + object.setIsValid(false); + object.setInternalError(true); + } + } + + return object; + } + + + private void insertDemodedupDetails(IndividualDemographicDedupe demographicData, JSONObject regProcessorIdentityJson, + JSONObject jsonObject, InternalRegistrationStatusDto registrationStatusDto, MessageDTO object, + String moduleId, String moduleName) { + IndividualDemographicDedupe demoDedupeData = new IndividualDemographicDedupe(); + List jsonValueList = new ArrayList<>(); + if (demographicData.getName() == null || demographicData.getName().isEmpty()) { + String names = JsonUtil.getJSONValue(JsonUtil.getJSONObject(regProcessorIdentityJson, MappingJsonConstants.NAME), MappingJsonConstants.VALUE); + Arrays.stream(names.split(",")) + .forEach(name -> { + JsonValue[] nameArray = JsonUtil.getJsonValues(jsonObject, name); + if (nameArray != null) + jsonValueList.add(nameArray); + }); + } + if(demographicData.getName() == null || demographicData.getName().isEmpty()) + demoDedupeData.setName(jsonValueList.isEmpty() ? null : jsonValueList); + else + demoDedupeData.setName(demographicData.getName()); + demoDedupeData.setDateOfBirth(demographicData.getDateOfBirth() == null + ? JsonUtil.getJSONValue(jsonObject, JsonUtil.getJSONValue(JsonUtil.getJSONObject(regProcessorIdentityJson, MappingJsonConstants.DOB), MappingJsonConstants.VALUE)) + : demographicData.getDateOfBirth()); + demoDedupeData.setGender(demographicData.getGender() == null + ? JsonUtil.getJsonValues(jsonObject, + JsonUtil.getJSONValue(JsonUtil.getJSONObject(regProcessorIdentityJson, MappingJsonConstants.GENDER), MappingJsonConstants.VALUE)) + : demographicData.getGender()); + demoDedupeData.setPhone(demographicData.getPhone() == null + ? JsonUtil + .getJSONValue(jsonObject, + JsonUtil.getJSONValue(JsonUtil.getJSONObject(regProcessorIdentityJson, + MappingJsonConstants.PHONE), MappingJsonConstants.VALUE)) + : demographicData.getPhone()); + demoDedupeData.setEmail(demographicData.getEmail() == null + ? JsonUtil + .getJSONValue(jsonObject, + JsonUtil.getJSONValue(JsonUtil.getJSONObject(regProcessorIdentityJson, + MappingJsonConstants.EMAIL), MappingJsonConstants.VALUE)) + : demographicData.getEmail()); + + packetInfoManager.saveIndividualDemographicDedupeUpdatePacket(demoDedupeData, registrationStatusDto.getRegistrationId(), moduleId, + registrationStatusDto.getRegistrationType(),moduleName,registrationStatusDto.getIteration(), registrationStatusDto.getWorkflowInstanceId()); + object.setIsValid(Boolean.TRUE); + registrationStatusDto + .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.SUCCESS.toString()); + registrationStatusDto.setStatusComment(StatusUtil.DEMO_DEDUPE_SKIPPED.getMessage()); + registrationStatusDto.setSubStatusCode(StatusUtil.DEMO_DEDUPE_SKIPPED.getCode()); + registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); + + } + + + private DemoDedupeStatusDTO insertDemodedupDetailsAndPerformDedup(IndividualDemographicDedupe demographicData, + InternalRegistrationStatusDto registrationStatusDto, List duplicateDtos, + MessageDTO object, String moduleId, String moduleName, boolean isDemoDedupeSkip, LogDescription description) + throws ApisResourceAccessException, + JsonProcessingException, PacketManagerException, IOException, PacketDecryptionFailureException, io.mosip.kernel.core.exception.IOException, RegistrationProcessorCheckedException { + DemoDedupeStatusDTO demoDedupeStatusDTO=new DemoDedupeStatusDTO(); + boolean isTransactionSuccessful = false; + String packetStatus = abisHandlerUtil.getPacketStatus(registrationStatusDto); + String registrationId=registrationStatusDto.getRegistrationId(); + if (packetStatus.equalsIgnoreCase(AbisConstant.PRE_ABIS_IDENTIFICATION)) { + packetInfoManager.saveIndividualDemographicDedupeUpdatePacket(demographicData, registrationId, moduleId, + registrationStatusDto.getRegistrationType(),moduleName,registrationStatusDto.getIteration(), registrationStatusDto.getWorkflowInstanceId()); + int age = utility.getApplicantAge(registrationId, registrationStatusDto.getRegistrationType(), ProviderStageName.DEMO_DEDUPE); + int ageThreshold = Integer.parseInt(ageLimit); + if (age < ageThreshold) { + if (infantDedupe.equalsIgnoreCase(GLOBAL_CONFIG_TRUE_VALUE)) { + isDemoDedupeSkip = false; + duplicateDtos = performDemoDedupe(registrationStatusDto, object, description); + if (duplicateDtos.isEmpty()) + isTransactionSuccessful = true; + } + } + else { + String demo=env.getProperty(DEMODEDUPEENABLE); + if (demo != null && demo.trim().equalsIgnoreCase(TRUE)) { + isDemoDedupeSkip = false; + duplicateDtos = performDemoDedupe(registrationStatusDto, object, description); + if (duplicateDtos.isEmpty()) + isTransactionSuccessful = true; + } + } + + if (isDemoDedupeSkip) { + object.setIsValid(Boolean.TRUE); + registrationStatusDto + .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.SUCCESS.toString()); + registrationStatusDto.setStatusComment(StatusUtil.DEMO_DEDUPE_SKIPPED.getMessage()); + registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); + registrationStatusDto.setSubStatusCode(StatusUtil.DEMO_DEDUPE_SKIPPED.getCode()); + description.setCode(PlatformSuccessMessages.RPR_PKR_DEMO_DE_DUP_SKIP.getCode()); + description.setMessage(PlatformSuccessMessages.RPR_PKR_DEMO_DE_DUP_SKIP.getMessage() + " -- " + + registrationId); + regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), description.getCode(), + registrationId, description.getMessage()); + registrationStatusDto.setUpdatedBy(DemoDedupeConstants.USER); + regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString(), registrationStatusDto.getRegistrationId(), + DemoDedupeConstants.DEMO_SKIP); + } + }else if (packetStatus.equalsIgnoreCase(AbisConstant.POST_ABIS_IDENTIFICATION)) { + isTransactionSuccessful = processDemoDedupeRequesthandler(registrationStatusDto, object, + description); + } + demoDedupeStatusDTO.setTransactionSuccessful(isTransactionSuccessful); + demoDedupeStatusDTO.setDuplicateDtos(duplicateDtos); + return demoDedupeStatusDTO; + + } + + + + + /** + * Perform demo dedupe. + * + * @param registrationStatusDto + * the registration status dto + * @param object + * the object + * @param description + * @return true, if successful + */ + private List performDemoDedupe(InternalRegistrationStatusDto registrationStatusDto, + MessageDTO object, LogDescription description) { + String registrationId = registrationStatusDto.getRegistrationId(); + // Potential Duplicate Ids after performing demo dedupe + List duplicateDtos = demoDedupe.performDedupe(registrationStatusDto.getRegistrationId()); + duplicateDtos.removeIf(dto -> dto.getRegId().equals(registrationStatusDto.getRegistrationId())); + if (!duplicateDtos.isEmpty()) { + isMatchFound = true; + registrationStatusDto + .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.IN_PROGRESS.toString()); + registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); + registrationStatusDto.setStatusComment(StatusUtil.POTENTIAL_MATCH_FOUND.getMessage()); + registrationStatusDto.setSubStatusCode(StatusUtil.POTENTIAL_MATCH_FOUND.getCode()); + object.setMessageBusAddress(MessageBusAddress.ABIS_HANDLER_BUS_IN); + object.setIsValid(Boolean.TRUE); + description.setCode(PlatformSuccessMessages.RPR_PKR_DEMO_DE_DUP.getCode()); + description.setMessage(DemoDedupeConstants.RECORD_INSERTED_FROM_ABIS_HANDLER + " -- " + registrationId); + regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + registrationStatusDto.getRegistrationId(), DemoDedupeConstants.RECORD_INSERTED_FROM_ABIS_HANDLER); + + } else { + object.setIsValid(Boolean.TRUE); + registrationStatusDto.setLatestTransactionStatusCode(RegistrationTransactionStatusCode.SUCCESS.toString()); + registrationStatusDto.setStatusComment(StatusUtil.DEMO_DEDUPE_SUCCESS.getMessage()); + registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); + registrationStatusDto.setSubStatusCode(StatusUtil.DEMO_DEDUPE_SUCCESS.getCode()); + description.setCode(PlatformSuccessMessages.RPR_PKR_DEMO_DE_DUP.getCode()); + description.setMessage(PlatformSuccessMessages.RPR_PKR_DEMO_DE_DUP.getMessage() + " -- " + registrationId); + regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), description.getCode(), registrationId, + description.getMessage()); + registrationStatusDto.setUpdatedBy(DemoDedupeConstants.USER); + regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + registrationStatusDto.getRegistrationId(), DemoDedupeConstants.DEMO_SUCCESS); + } + return duplicateDtos; + } + + /** + * Gets the latest transaction id. + * + * @param registrationId + * the registration id + * @return the latest transaction id + */ + private String getLatestTransactionId(String registrationId, String process, int iteration, String workflowInstanceId) { + RegistrationStatusEntity entity = registrationStatusDao.find(registrationId, process, iteration, workflowInstanceId); + return entity != null ? entity.getLatestRegistrationTransactionId() : null; + } + + /** + * Process demo dedupe requesthandler. + * + * @param registrationStatusDto the registration status dto + * @param object the object + * @param description + * @return true, if successful + * @throws ApisResourceAccessException the apis resource access + * exception + * @throws IOException Signals that an I/O exception + * has occurred. + */ + private boolean processDemoDedupeRequesthandler(InternalRegistrationStatusDto registrationStatusDto, + MessageDTO object, LogDescription description) + throws ApisResourceAccessException, IOException, JsonProcessingException, PacketManagerException { + boolean isTransactionSuccessful = false; + List responsIds = new ArrayList<>(); + + String latestTransactionId = getLatestTransactionId(registrationStatusDto.getRegistrationId(), + registrationStatusDto.getRegistrationType(), registrationStatusDto.getIteration(), registrationStatusDto.getWorkflowInstanceId()); + + List abisResponseDto = packetInfoManager.getAbisResponseRecords(latestTransactionId, + DemoDedupeConstants.IDENTIFY); + + for (AbisResponseDto responseDto : abisResponseDto) { + if (responseDto.getStatusCode().equalsIgnoreCase(AbisStatusCode.SUCCESS.toString())) { + responsIds.add(responseDto.getId()); + } else { + isTransactionSuccessful = true; + int retryCount = registrationStatusDto.getRetryCount() != null + ? registrationStatusDto.getRetryCount() + 1 + : 1; + description.setMessage( + DemoDedupeConstants.SENDING_TO_REPROCESS + " -- " + registrationStatusDto.getRegistrationId()); + registrationStatusDto.setRetryCount(retryCount); + + registrationStatusDto.setLatestTransactionStatusCode(registrationExceptionMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.DEMO_DEDUPE_ABIS_RESPONSE_ERROR)); + registrationStatusDto.setStatusComment(StatusUtil.DEMO_DEDUPE_FAILED_IN_ABIS.getMessage()); + registrationStatusDto.setSubStatusCode(StatusUtil.DEMO_DEDUPE_FAILED_IN_ABIS.getCode()); + registrationStatusDto.setStatusCode(RegistrationStatusCode.REJECTED.toString()); + regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString(), registrationStatusDto.getRegistrationId(), + DemoDedupeConstants.SENDING_TO_REPROCESS); + } + } + + if (!responsIds.isEmpty()) { + List abisResponseDetDto = packetInfoManager.getAbisResponseDetRecordsList(responsIds); + if (abisResponseDetDto.isEmpty()) { + object.setIsValid(Boolean.TRUE); + registrationStatusDto + .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.SUCCESS.toString()); + registrationStatusDto.setStatusComment(StatusUtil.DEMO_DEDUPE_SUCCESS.getMessage()); + registrationStatusDto.setSubStatusCode(StatusUtil.DEMO_DEDUPE_SUCCESS.getCode()); + registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); + regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString(), registrationStatusDto.getRegistrationId(), + DemoDedupeConstants.NO_DUPLICATES_FOUND); + isTransactionSuccessful = true; + description.setCode(PlatformSuccessMessages.RPR_PKR_DEMO_DE_DUP.getCode()); + description.setMessage(PlatformSuccessMessages.RPR_PKR_DEMO_DE_DUP.getMessage()); + } else { + if (manualVerificationStatus != null && manualVerificationStatus.equalsIgnoreCase(MANUAL_VERIFICATION_STATUS)) { + //send message to manual adjudication + object.setInternalError(Boolean.FALSE); + object.setRid(registrationStatusDto.getRegistrationId()); + object.setIsValid(Boolean.TRUE); + object.setMessageBusAddress(MessageBusAddress.MANUAL_ADJUDICATION_BUS_IN); + registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.toString()); + } else { + object.setIsValid(Boolean.FALSE); + registrationStatusDto.setStatusCode(RegistrationStatusCode.REJECTED.toString()); + } + + registrationStatusDto + .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.FAILED.toString()); + registrationStatusDto.setStatusComment(StatusUtil.POTENTIAL_MATCH_FOUND_IN_ABIS.getMessage()); + registrationStatusDto.setSubStatusCode(StatusUtil.POTENTIAL_MATCH_FOUND_IN_ABIS.getCode()); + description.setCode(PlatformErrorMessages.RPR_DEMO_SENDING_FOR_MANUAL.getCode()); + description.setMessage(PlatformErrorMessages.RPR_DEMO_SENDING_FOR_MANUAL.getMessage()); + saveManualAdjudicationData(registrationStatusDto, object); + regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString(), registrationStatusDto.getRegistrationId(), + DemoDedupeConstants.SENDING_FOR_MANUAL); + + } + } + + return isTransactionSuccessful; + } + + /** + * Save duplicate dto list. + * + * @param duplicateDtos + * the duplicate dtos + * @param registrationStatusDto + * the registration status dto + * @return true, if successful + */ + private boolean saveDuplicateDtoList(List duplicateDtos, + InternalRegistrationStatusDto registrationStatusDto, MessageDTO object) { + boolean isDataSaved = false; + int numberOfProcessedPackets = 0; + + String moduleId = PlatformSuccessMessages.RPR_PKR_DEMO_DE_DUP.getCode(); + + String moduleName = ModuleName.DEMO_DEDUPE.toString(); + for (DemographicInfoDto demographicInfoDto : duplicateDtos) { + InternalRegistrationStatusDto potentialMatchRegistrationDto = registrationStatusService + .getRegistrationStatus(demographicInfoDto.getRegId(), + registrationStatusDto.getRegistrationType(), registrationStatusDto.getIteration(), registrationStatusDto.getWorkflowInstanceId()); + if (potentialMatchRegistrationDto.getLatestTransactionStatusCode() + .equalsIgnoreCase(RegistrationTransactionStatusCode.REPROCESS.toString()) + || potentialMatchRegistrationDto.getLatestTransactionStatusCode() + .equalsIgnoreCase(AbisConstant.RE_REGISTER)) { + regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString(), registrationStatusDto.getRegistrationId(), + DemoDedupeConstants.REJECTED_OR_REREGISTER); + } else if (potentialMatchRegistrationDto.getLatestTransactionStatusCode() + .equalsIgnoreCase(RegistrationTransactionStatusCode.IN_PROGRESS.toString()) + || potentialMatchRegistrationDto.getLatestTransactionStatusCode() + .equalsIgnoreCase(RegistrationTransactionStatusCode.PROCESSED.toString())) { + String latestTransactionId = getLatestTransactionId(registrationStatusDto.getRegistrationId(), + registrationStatusDto.getRegistrationType(), registrationStatusDto.getIteration(), registrationStatusDto.getWorkflowInstanceId()); + RegDemoDedupeListDto regDemoDedupeListDto = new RegDemoDedupeListDto(); + regDemoDedupeListDto.setRegId(registrationStatusDto.getRegistrationId()); + regDemoDedupeListDto.setMatchedRegId(demographicInfoDto.getRegId()); + regDemoDedupeListDto.setRegtrnId(latestTransactionId); + regDemoDedupeListDto.setIsDeleted(Boolean.FALSE); + regDemoDedupeListDto.setCrBy(DemoDedupeConstants.CREATED_BY); + packetInfoManager.saveDemoDedupePotentialData(regDemoDedupeListDto, moduleId, moduleName); + isDataSaved = true; + numberOfProcessedPackets++; + } else { + regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString(), registrationStatusDto.getRegistrationId(), + "The packet status is something different"); + } + if (numberOfProcessedPackets == 0) { + object.setIsValid(Boolean.TRUE); + } + } + return isDataSaved; + } + + /** + * Save manual adjudication data. + * + * @param registrationStatusDto the registration status dto + * @throws ApisResourceAccessException the apis resource access + * exception + * @throws IOException Signals that an I/O exception + * has occurred. + * @throws io.mosip.kernel.core.exception.IOException + * @throws PacketDecryptionFailureException + * @throws RegistrationProcessorCheckedException + */ + private void saveManualAdjudicationData(InternalRegistrationStatusDto registrationStatusDto, MessageDTO messageDTO) + throws ApisResourceAccessException, IOException, JsonProcessingException, PacketManagerException { + Set matchedRegIds = abisHandlerUtil.getUniqueRegIds(registrationStatusDto.getRegistrationId(), + registrationStatusDto.getRegistrationType(), registrationStatusDto.getIteration(), + registrationStatusDto.getWorkflowInstanceId(), ProviderStageName.DEMO_DEDUPE); + if (!matchedRegIds.isEmpty()) { + String moduleId = PlatformErrorMessages.RPR_DEMO_SENDING_FOR_MANUAL.getCode(); + String moduleName = ModuleName.DEMO_DEDUPE.toString(); + packetInfoManager.saveManualAdjudicationData(matchedRegIds, messageDTO, + DedupeSourceName.DEMO, moduleId, moduleName,null,null); + } else { + regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + registrationStatusDto.getRegistrationId(), DemoDedupeConstants.NO_MATCH_FOUND); + } + + } + + private void updateErrorFlags(InternalRegistrationStatusDto registrationStatusDto, MessageDTO object) { + object.setInternalError(true); + if (registrationStatusDto.getLatestTransactionStatusCode() + .equalsIgnoreCase(RegistrationTransactionStatusCode.REPROCESS.toString())) { + object.setIsValid(true); + } else { + object.setIsValid(false); + } + } + +} 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 7c6b35978b5..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,55 +1,54 @@ -package io.mosip.registration.processor.status.api.config; - -import io.mosip.kernel.core.authmanager.authadapter.spi.VertxAuthenticationProvider; -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; -import org.springframework.boot.test.mock.mockito.MockBean; -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.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 { - - @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; - } - }; - } - -} - +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/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 7edb0ae8188..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; @@ -330,7 +329,6 @@ public void senderHealthHandler(Promise promise, Vertx vertx, MosipEvent .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)); 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 e66780810c5..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 @@ -3,31 +3,13 @@ import java.util.HashMap; import java.util.Map; import java.util.stream.Collectors; -import org.slf4j.LoggerFactory; -import io.mosip.kernel.core.logger.spi.Logger; import org.slf4j.LoggerFactory; -import io.mosip.kernel.logger.logback.factory.Logfactory; -import ch.qos.logback.classic.Level; -import ch.qos.logback.classic.LoggerContext; - - - -import java.util.stream.Collectors; -import java.util.HashMap; -import java.util.Map; - -import ch.qos.logback.classic.Level; -import ch.qos.logback.classic.LoggerContext; - - - -import java.util.stream.Collectors; -import java.util.HashMap; -import java.util.Map; 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; /** 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 97ab7a4f414..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 @@ -24,6 +24,7 @@ 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; @@ -60,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. 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 447554f17de..7990dc059dd 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 @@ -1,325 +1,315 @@ -package io.mosip.registration.processor.rest.client.utils; - -import java.io.IOException; -import java.net.URI; -import java.util.Iterator; -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; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.entity.StringEntity; -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.util.EntityUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.web.client.RestTemplateBuilder; -import org.springframework.context.annotation.Lazy; -import org.springframework.core.env.Environment; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpMethod; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.stereotype.Component; -import org.springframework.util.LinkedMultiValueMap; -import org.springframework.util.MultiValueMap; -import org.springframework.web.client.HttpStatusCodeException; -import org.springframework.web.client.RestTemplate; - -import com.fasterxml.jackson.databind.ObjectMapper; - -import io.mosip.kernel.core.logger.spi.Logger; -import io.mosip.kernel.core.util.DateUtils; -import io.mosip.kernel.core.util.StringUtils; -import io.mosip.kernel.core.util.TokenHandlerUtil; -import io.mosip.registration.processor.core.constant.LoggerFileConstant; -import io.mosip.registration.processor.core.logger.RegProcessorLogger; -import io.mosip.registration.processor.core.tracing.ContextualData; -import io.mosip.registration.processor.core.tracing.TracingConstant; -import io.mosip.registration.processor.rest.client.audit.dto.Metadata; -import io.mosip.registration.processor.rest.client.audit.dto.SecretKeyRequest; -import io.mosip.registration.processor.rest.client.audit.dto.TokenRequestDTO; -import io.mosip.registration.processor.rest.client.exception.TokenGenerationFailedException; - -/** - * The Class RestApiClient. - * - * @author Rishabh Keshari - */ -@Component -public class RestApiClient { - - /** The logger. */ - private final Logger logger = RegProcessorLogger.getLogger(RestApiClient.class); - - @Value("${registration.processor.httpclient.connections.max.per.host:20}") - private int maxConnectionPerRoute; - - @Value("${registration.processor.httpclient.connections.max:100}") - private int totalMaxConnection; - - /** The builder. */ - @Autowired - RestTemplateBuilder builder; - - @Autowired - Environment environment; - - private static final String AUTHORIZATION = "Authorization="; - - @Autowired - @Qualifier("selfTokenRestTemplate") - RestTemplate localRestTemplate; - - @Autowired - ObjectMapper objMp; - - /** - * Gets the api. * - * - * @param the generic type - * @param uri the get URI - * @param responseType the response type - * @return the api - * @throws Exception - */ - @SuppressWarnings("unchecked") - public T getApi(URI uri, Class responseType) throws Exception { - T result = null; - - try { - result = (T) localRestTemplate.exchange(uri, HttpMethod.GET, setRequestHeader(null, null), responseType) - .getBody(); - } catch (Exception e) { - logger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), - LoggerFileConstant.APPLICATIONID.toString(), e.getMessage() + ExceptionUtils.getStackTrace(e)); - tokenExceptionHandler(e); - throw e; - } - return result; - } - - /** - * Post api. - * - * @param the generic type - * @param uri the uri - * @param requestType the request type - * @param responseClass the response class - * @return the t - */ - @SuppressWarnings("unchecked") - public T postApi(String uri, MediaType mediaType, Object requestType, Class responseClass) throws Exception { - - T result = null; - try { - logger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), - LoggerFileConstant.APPLICATIONID.toString(), uri); - result = (T) localRestTemplate.postForObject(uri, setRequestHeader(requestType, mediaType), responseClass); - - } catch (Exception e) { - logger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), - LoggerFileConstant.APPLICATIONID.toString(), e.getMessage() + ExceptionUtils.getStackTrace(e)); - tokenExceptionHandler(e); - throw e; - } - return result; - } - - /** - * Patch api. - * - * @param the generic type - * @param uri the uri - * @param requestType the request type - * @param responseClass the response class - * @return the t - */ - @SuppressWarnings("unchecked") - public T patchApi(String uri, MediaType mediaType, Object requestType, Class responseClass) - throws Exception { - - T result = null; - try { - logger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), - LoggerFileConstant.APPLICATIONID.toString(), uri); - result = (T) localRestTemplate.patchForObject(uri, setRequestHeader(requestType, mediaType), responseClass); - - } catch (Exception e) { - logger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), - LoggerFileConstant.APPLICATIONID.toString(), e.getMessage() + ExceptionUtils.getStackTrace(e)); - tokenExceptionHandler(e); - throw e; - } - return result; - } - - public T patchApi(String uri, Object requestType, Class responseClass) throws Exception { - return patchApi(uri, null, requestType, responseClass); - } - - /** - * Put api. - * - * @param the generic type - * @param uri the uri - * @param requestType the request type - * @param responseClass the response class - * @param mediaType - * @return the t - * @throws Exception the exception - */ - @SuppressWarnings("unchecked") - public T putApi(String uri, Object requestType, Class responseClass, MediaType mediaType) throws Exception { - - T result = null; - ResponseEntity response = null; - try { - logger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), - LoggerFileConstant.APPLICATIONID.toString(), uri); - - response = (ResponseEntity) localRestTemplate.exchange(uri, HttpMethod.PUT, - setRequestHeader(requestType, mediaType), responseClass); - result = response.getBody(); - } catch (Exception e) { - logger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), - LoggerFileConstant.APPLICATIONID.toString(), e.getMessage() + ExceptionUtils.getStackTrace(e)); - tokenExceptionHandler(e); - throw e; - } - return result; - } - - public int headApi(URI uri) throws Exception { - try { - HttpStatus httpStatus = localRestTemplate - .exchange(uri, HttpMethod.HEAD, setRequestHeader(null, null), Object.class).getStatusCode(); - return httpStatus.value(); - } catch (Exception e) { - logger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), - LoggerFileConstant.APPLICATIONID.toString(), e.getMessage() + ExceptionUtils.getStackTrace(e)); - tokenExceptionHandler(e); - throw e; - } - } - - public RestTemplate getRestTemplate() { - return localRestTemplate; - } - - /** - * this method sets token to header of the request - * - * @param requestType - * @param mediaType - * @return - * @throws IOException - */ - @SuppressWarnings("unchecked") - private HttpEntity setRequestHeader(Object requestType, MediaType mediaType) throws IOException { - MultiValueMap headers = new LinkedMultiValueMap(); - // headers.add("Cookie", getToken()); - headers.add(TracingConstant.TRACE_HEADER, (String) ContextualData.getOrDefault(TracingConstant.TRACE_ID_KEY)); - if (mediaType != null) { - headers.add("Content-Type", mediaType.toString()); - } - if (requestType != null) { - try { - HttpEntity httpEntity = (HttpEntity) requestType; - HttpHeaders httpHeader = httpEntity.getHeaders(); - Iterator iterator = httpHeader.keySet().iterator(); - while (iterator.hasNext()) { - String key = iterator.next(); - List collection = httpHeader.get(key); - if ((collection != null && !collection.isEmpty()) - && !(headers.containsKey("Content-Type") && key.equalsIgnoreCase("Content-Type"))) - headers.add(key, collection.get(0)); - - } - return new HttpEntity(httpEntity.getBody(), headers); - } catch (ClassCastException e) { - return new HttpEntity(requestType, headers); - } - } else - return new HttpEntity(headers); - } - - /** - * This method gets the token for the user details present in config server. - * - * @return - * @throws IOException - */ - public String getToken() throws IOException { - String token = System.getProperty("token"); - boolean isValid = false; - - if (StringUtils.isNotEmpty(token)) { - - isValid = TokenHandlerUtil.isValidBearerToken(token, environment.getProperty("token.request.issuerUrl"), - environment.getProperty("token.request.clientId")); - - } - if (!isValid) { - TokenRequestDTO tokenRequestDTO = new TokenRequestDTO(); - tokenRequestDTO.setId(environment.getProperty("token.request.id")); - tokenRequestDTO.setMetadata(new Metadata()); - - tokenRequestDTO.setRequesttime(DateUtils.getUTCCurrentDateTimeString()); - // tokenRequestDTO.setRequest(setPasswordRequestDTO()); - tokenRequestDTO.setRequest(setSecretKeyRequestDTO()); - tokenRequestDTO.setVersion(environment.getProperty("token.request.version")); - - HttpClient httpClient = HttpClientBuilder.create().build(); - HttpPost post = new HttpPost(environment.getProperty("KEYBASEDTOKENAPI")); - try { - StringEntity postingString = new StringEntity(objMp.writeValueAsString(tokenRequestDTO)); - post.setEntity(postingString); - post.setHeader("Content-type", "application/json"); - post.setHeader(TracingConstant.TRACE_HEADER, - (String) ContextualData.getOrDefault(TracingConstant.TRACE_ID_KEY)); - HttpResponse response = httpClient.execute(post); - org.apache.http.HttpEntity entity = response.getEntity(); - String responseBody = EntityUtils.toString(entity, "UTF-8"); - Header[] cookie = response.getHeaders("Set-Cookie"); - if (cookie.length == 0) - throw new TokenGenerationFailedException(); - token = response.getHeaders("Set-Cookie")[0].getValue(); - System.setProperty("token", token.substring(14, token.indexOf(';'))); - return token.substring(0, token.indexOf(';')); - } catch (IOException e) { - logger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), - LoggerFileConstant.APPLICATIONID.toString(), e.getMessage() + ExceptionUtils.getStackTrace(e)); - throw e; - } - } - return AUTHORIZATION + token; - } - - private SecretKeyRequest setSecretKeyRequestDTO() { - SecretKeyRequest request = new SecretKeyRequest(); - request.setAppId(environment.getProperty("token.request.appid")); - request.setClientId(environment.getProperty("token.request.clientId")); - request.setSecretKey(environment.getProperty("token.request.secretKey")); - return request; - } - - public void tokenExceptionHandler(Exception e) { - if (e instanceof HttpStatusCodeException) { - HttpStatusCodeException ex = (HttpStatusCodeException) e; - if (ex.getRawStatusCode() == 401) { - logger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), - LoggerFileConstant.APPLICATIONID.toString(), "Authentication failed. Resetting auth token."); - System.setProperty("token", ""); - } - } - } - -} +package io.mosip.registration.processor.rest.client.utils; + +import java.io.IOException; +import java.net.URI; +import java.util.Iterator; +import java.util.List; + +import org.apache.commons.lang3.exception.ExceptionUtils; +import org.apache.http.Header; +import org.apache.http.HttpResponse; +import org.apache.http.client.HttpClient; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.util.EntityUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.boot.web.client.RestTemplateBuilder; +import org.springframework.core.env.Environment; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Component; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.client.HttpStatusCodeException; +import org.springframework.web.client.RestTemplate; + +import com.fasterxml.jackson.databind.ObjectMapper; + +import io.mosip.kernel.core.logger.spi.Logger; +import io.mosip.kernel.core.util.DateUtils; +import io.mosip.kernel.core.util.StringUtils; +import io.mosip.kernel.core.util.TokenHandlerUtil; +import io.mosip.registration.processor.core.constant.LoggerFileConstant; +import io.mosip.registration.processor.core.logger.RegProcessorLogger; +import io.mosip.registration.processor.core.tracing.ContextualData; +import io.mosip.registration.processor.core.tracing.TracingConstant; +import io.mosip.registration.processor.rest.client.audit.dto.Metadata; +import io.mosip.registration.processor.rest.client.audit.dto.SecretKeyRequest; +import io.mosip.registration.processor.rest.client.audit.dto.TokenRequestDTO; +import io.mosip.registration.processor.rest.client.exception.TokenGenerationFailedException; + +/** + * The Class RestApiClient. + * + * @author Rishabh Keshari + */ +@Component +public class RestApiClient { + + /** The logger. */ + private final Logger logger = RegProcessorLogger.getLogger(RestApiClient.class); + + /** The builder. */ + @Autowired + RestTemplateBuilder builder; + + @Autowired + Environment environment; + + private static final String AUTHORIZATION = "Authorization="; + + @Autowired + @Qualifier("selfTokenRestTemplate") + RestTemplate localRestTemplate; + + @Autowired + ObjectMapper objMp; + + /** + * Gets the api. * + * + * @param the generic type + * @param uri the get URI + * @param responseType the response type + * @return the api + * @throws Exception + */ + @SuppressWarnings("unchecked") + public T getApi(URI uri, Class responseType) throws Exception { + T result = null; + + try { + result = (T) localRestTemplate.exchange(uri, HttpMethod.GET, setRequestHeader(null, null), responseType) + .getBody(); + } catch (Exception e) { + logger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), + LoggerFileConstant.APPLICATIONID.toString(), e.getMessage() + ExceptionUtils.getStackTrace(e)); + tokenExceptionHandler(e); + throw e; + } + return result; + } + + /** + * Post api. + * + * @param the generic type + * @param uri the uri + * @param requestType the request type + * @param responseClass the response class + * @return the t + */ + @SuppressWarnings("unchecked") + public T postApi(String uri, MediaType mediaType, Object requestType, Class responseClass) throws Exception { + + T result = null; + try { + logger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), + LoggerFileConstant.APPLICATIONID.toString(), uri); + result = (T) localRestTemplate.postForObject(uri, setRequestHeader(requestType, mediaType), responseClass); + + } catch (Exception e) { + logger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), + LoggerFileConstant.APPLICATIONID.toString(), e.getMessage() + ExceptionUtils.getStackTrace(e)); + tokenExceptionHandler(e); + throw e; + } + return result; + } + + /** + * Patch api. + * + * @param the generic type + * @param uri the uri + * @param requestType the request type + * @param responseClass the response class + * @return the t + */ + @SuppressWarnings("unchecked") + public T patchApi(String uri, MediaType mediaType, Object requestType, Class responseClass) + throws Exception { + + T result = null; + try { + logger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), + LoggerFileConstant.APPLICATIONID.toString(), uri); + result = (T) localRestTemplate.patchForObject(uri, setRequestHeader(requestType, mediaType), responseClass); + + } catch (Exception e) { + logger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), + LoggerFileConstant.APPLICATIONID.toString(), e.getMessage() + ExceptionUtils.getStackTrace(e)); + tokenExceptionHandler(e); + throw e; + } + return result; + } + + public T patchApi(String uri, Object requestType, Class responseClass) throws Exception { + return patchApi(uri, null, requestType, responseClass); + } + + /** + * Put api. + * + * @param the generic type + * @param uri the uri + * @param requestType the request type + * @param responseClass the response class + * @param mediaType + * @return the t + * @throws Exception the exception + */ + @SuppressWarnings("unchecked") + public T putApi(String uri, Object requestType, Class responseClass, MediaType mediaType) throws Exception { + + T result = null; + ResponseEntity response = null; + try { + logger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), + LoggerFileConstant.APPLICATIONID.toString(), uri); + + response = (ResponseEntity) localRestTemplate.exchange(uri, HttpMethod.PUT, + setRequestHeader(requestType, mediaType), responseClass); + result = response.getBody(); + } catch (Exception e) { + logger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), + LoggerFileConstant.APPLICATIONID.toString(), e.getMessage() + ExceptionUtils.getStackTrace(e)); + tokenExceptionHandler(e); + throw e; + } + return result; + } + + public int headApi(URI uri) throws Exception { + try { + HttpStatus httpStatus = localRestTemplate + .exchange(uri, HttpMethod.HEAD, setRequestHeader(null, null), Object.class).getStatusCode(); + return httpStatus.value(); + } catch (Exception e) { + logger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), + LoggerFileConstant.APPLICATIONID.toString(), e.getMessage() + ExceptionUtils.getStackTrace(e)); + tokenExceptionHandler(e); + throw e; + } + } + + public RestTemplate getRestTemplate() { + return localRestTemplate; + } + + /** + * this method sets token to header of the request + * + * @param requestType + * @param mediaType + * @return + * @throws IOException + */ + @SuppressWarnings("unchecked") + private HttpEntity setRequestHeader(Object requestType, MediaType mediaType) throws IOException { + MultiValueMap headers = new LinkedMultiValueMap(); + // headers.add("Cookie", getToken()); + headers.add(TracingConstant.TRACE_HEADER, (String) ContextualData.getOrDefault(TracingConstant.TRACE_ID_KEY)); + if (mediaType != null) { + headers.add("Content-Type", mediaType.toString()); + } + if (requestType != null) { + try { + HttpEntity httpEntity = (HttpEntity) requestType; + HttpHeaders httpHeader = httpEntity.getHeaders(); + Iterator iterator = httpHeader.keySet().iterator(); + while (iterator.hasNext()) { + String key = iterator.next(); + List collection = httpHeader.get(key); + if ((collection != null && !collection.isEmpty()) + && !(headers.containsKey("Content-Type") && key.equalsIgnoreCase("Content-Type"))) + headers.add(key, collection.get(0)); + + } + return new HttpEntity(httpEntity.getBody(), headers); + } catch (ClassCastException e) { + return new HttpEntity(requestType, headers); + } + } else + return new HttpEntity(headers); + } + + /** + * This method gets the token for the user details present in config server. + * + * @return + * @throws IOException + */ + public String getToken() throws IOException { + String token = System.getProperty("token"); + boolean isValid = false; + + if (StringUtils.isNotEmpty(token)) { + + isValid = TokenHandlerUtil.isValidBearerToken(token, environment.getProperty("token.request.issuerUrl"), + environment.getProperty("token.request.clientId")); + + } + if (!isValid) { + TokenRequestDTO tokenRequestDTO = new TokenRequestDTO(); + tokenRequestDTO.setId(environment.getProperty("token.request.id")); + tokenRequestDTO.setMetadata(new Metadata()); + + tokenRequestDTO.setRequesttime(DateUtils.getUTCCurrentDateTimeString()); + // tokenRequestDTO.setRequest(setPasswordRequestDTO()); + tokenRequestDTO.setRequest(setSecretKeyRequestDTO()); + tokenRequestDTO.setVersion(environment.getProperty("token.request.version")); + + HttpClient httpClient = HttpClientBuilder.create().build(); + HttpPost post = new HttpPost(environment.getProperty("KEYBASEDTOKENAPI")); + try { + StringEntity postingString = new StringEntity(objMp.writeValueAsString(tokenRequestDTO)); + post.setEntity(postingString); + post.setHeader("Content-type", "application/json"); + post.setHeader(TracingConstant.TRACE_HEADER, + (String) ContextualData.getOrDefault(TracingConstant.TRACE_ID_KEY)); + HttpResponse response = httpClient.execute(post); + org.apache.http.HttpEntity entity = response.getEntity(); + String responseBody = EntityUtils.toString(entity, "UTF-8"); + Header[] cookie = response.getHeaders("Set-Cookie"); + if (cookie.length == 0) + throw new TokenGenerationFailedException(); + token = response.getHeaders("Set-Cookie")[0].getValue(); + System.setProperty("token", token.substring(14, token.indexOf(';'))); + return token.substring(0, token.indexOf(';')); + } catch (IOException e) { + logger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), + LoggerFileConstant.APPLICATIONID.toString(), e.getMessage() + ExceptionUtils.getStackTrace(e)); + throw e; + } + } + return AUTHORIZATION + token; + } + + private SecretKeyRequest setSecretKeyRequestDTO() { + SecretKeyRequest request = new SecretKeyRequest(); + request.setAppId(environment.getProperty("token.request.appid")); + request.setClientId(environment.getProperty("token.request.clientId")); + request.setSecretKey(environment.getProperty("token.request.secretKey")); + return request; + } + + public void tokenExceptionHandler(Exception e) { + if (e instanceof HttpStatusCodeException) { + HttpStatusCodeException ex = (HttpStatusCodeException) e; + if (ex.getRawStatusCode() == 401) { + logger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), + LoggerFileConstant.APPLICATIONID.toString(), "Authentication failed. Resetting auth token."); + System.setProperty("token", ""); + } + } + } + +}