diff --git a/registration-processor/core-processor/registration-processor-abis-handler-stage/src/main/java/io/mosip/registration/processor/abis/handler/dto/DataShareResponseDto.java b/registration-processor/core-processor/registration-processor-abis-handler-stage/src/main/java/io/mosip/registration/processor/abis/handler/dto/DataShareResponseDto.java index b35bea22693..5f4c8557b4d 100644 --- a/registration-processor/core-processor/registration-processor-abis-handler-stage/src/main/java/io/mosip/registration/processor/abis/handler/dto/DataShareResponseDto.java +++ b/registration-processor/core-processor/registration-processor-abis-handler-stage/src/main/java/io/mosip/registration/processor/abis/handler/dto/DataShareResponseDto.java @@ -1,21 +1,22 @@ -package io.mosip.registration.processor.abis.handler.dto; - -import io.mosip.registration.processor.core.common.rest.dto.BaseRestResponseDTO; -import io.mosip.registration.processor.core.common.rest.dto.ErrorDTO; -import lombok.Data; -import lombok.EqualsAndHashCode; - -import java.util.List; - -@Data -@EqualsAndHashCode(callSuper = true) -public class DataShareResponseDto extends BaseRestResponseDTO { - - private static final long serialVersionUID = 1L; - - - private DataShare dataShare; - - - private List errors; -} +package io.mosip.registration.processor.abis.handler.dto; + +import java.util.List; + +import io.mosip.registration.processor.core.common.rest.dto.BaseRestResponseDTO; +import io.mosip.registration.processor.core.common.rest.dto.ErrorDTO; +import io.mosip.registration.processor.core.packet.dto.abis.DataShare; +import lombok.Data; +import lombok.EqualsAndHashCode; + +@Data +@EqualsAndHashCode(callSuper = true) +public class DataShareResponseDto extends BaseRestResponseDTO { + + private static final long serialVersionUID = 1L; + + + private DataShare dataShare; + + + private List errors; +} 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 4562d40fc24..fd3fb3329d0 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,12 +1,8 @@ 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.UUID; import org.apache.commons.lang3.exception.ExceptionUtils; @@ -21,13 +17,6 @@ import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; -import com.fasterxml.jackson.core.JsonParseException; -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.core.cbeffutil.spi.CbeffUtil; import io.mosip.kernel.core.logger.spi.Logger; @@ -36,12 +25,7 @@ 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.dto.Filter; -import io.mosip.registration.processor.abis.handler.dto.ShareableAttributes; -import io.mosip.registration.processor.abis.handler.dto.Source; import io.mosip.registration.processor.abis.handler.exception.AbisHandlerException; -import io.mosip.registration.processor.abis.handler.exception.BiometricRecordValidationException; -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; @@ -57,12 +41,11 @@ 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.BiometricRecordValidationException; +import io.mosip.registration.processor.core.exception.DataShareException; 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; @@ -80,6 +63,7 @@ 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.ABISHandlerUtil; import io.mosip.registration.processor.packet.storage.utils.BIRConverter; import io.mosip.registration.processor.packet.storage.utils.PriorityBasedPacketManagerService; import io.mosip.registration.processor.packet.storage.utils.Utilities; @@ -168,6 +152,10 @@ public class AbisHandlerStage extends MosipVerticleAPIManager { private static final String DATASHARECREATEURL = "DATASHARECREATEURL"; private static final String DATETIME_PATTERN = "mosip.registration.processor.datetime.pattern"; + + @Autowired + private ABISHandlerUtil abisHandlerUtil; + /** * Deploy verticle. */ @@ -556,7 +544,7 @@ private String getUUID() { } private String getDataShareUrl(String id, String process) throws Exception { - Map> typeAndSubtypMap=createTypeSubtypeMapping(); + Map> typeAndSubtypMap = abisHandlerUtil.createBiometricTypeSubtypeMappingFromAbispolicy(); List modalities=new ArrayList<>(); for(Map.Entry> entry:typeAndSubtypMap.entrySet()) { if(entry.getValue()==null) { @@ -571,7 +559,7 @@ private String getDataShareUrl(String id, String process) throws Exception { MappingJsonConstants.VALUE); BiometricRecord biometricRecord = priorityBasedPacketManagerService.getBiometrics( id, individualBiometricsLabel, modalities, process, ProviderStageName.BIO_DEDUPE); - validateBiometricRecord(biometricRecord, modalities); + abisHandlerUtil.validateBiometricRecord(biometricRecord, modalities); byte[] content = cbeffutil.createXML(BIRConverter.convertSegmentsToBIRList(biometricRecord.getSegments())); MultiValueMap map = new LinkedMultiValueMap<>(); @@ -596,77 +584,6 @@ public String getFilename() { return response.getDataShare().getUrl(); } - public Map> createTypeSubtypeMapping() throws ApisResourceAccessException, DataShareException, JsonParseException, JsonMappingException, com.fasterxml.jackson.core.JsonProcessingException, IOException{ - Map> typeAndSubTypeMap = new HashMap<>(); - 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); - ObjectMapper mapper = new ObjectMapper(); - 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 validateBiometricRecord(BiometricRecord biometricRecord, List modalities) - throws BiometricRecordValidationException, JsonParseException, JsonMappingException, IOException { - if (modalities == null || modalities.isEmpty()) { - throw new BiometricRecordValidationException(PlatformErrorMessages.RPR_DATASHARE_MODALITIES_EMPTY.getCode(),PlatformErrorMessages.RPR_DATASHARE_MODALITIES_EMPTY.getMessage()); - } - if (biometricRecord == null || biometricRecord.getSegments() == null - || biometricRecord.getSegments().isEmpty()) { - throw new BiometricRecordValidationException(PlatformErrorMessages.RPR_NO_BIOMETRICS_FOUND_WITH_DATASHARE.getCode(),PlatformErrorMessages.RPR_NO_BIOMETRICS_FOUND_WITH_DATASHARE.getMessage()); - } - for (String segment : modalities) { - 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(); - if (bir.getBdb() != null) { - return; - } - } - } - throw new BiometricRecordValidationException( - PlatformErrorMessages.RPR_NO_BIOMETRIC_MATCH_WTIH_DATASAHRE.getCode(), - PlatformErrorMessages.RPR_NO_BIOMETRIC_MATCH_WTIH_DATASAHRE.getMessage()); - } } 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 0783f5dbc6b..41a9cd9b596 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 @@ -3,19 +3,14 @@ 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.ArgumentMatchers.anyList; 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.Ignore; import org.junit.Test; @@ -32,8 +27,6 @@ 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; @@ -43,11 +36,7 @@ import io.mosip.kernel.core.cbeffutil.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.dto.Filter; -import io.mosip.registration.processor.abis.handler.dto.ShareableAttributes; -import io.mosip.registration.processor.abis.handler.dto.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; @@ -55,8 +44,8 @@ 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.constant.PolicyConstant; import io.mosip.registration.processor.core.exception.ApisResourceAccessException; +import io.mosip.registration.processor.core.exception.BiometricRecordValidationException; import io.mosip.registration.processor.core.exception.PacketManagerException; import io.mosip.registration.processor.core.exception.RegistrationProcessorCheckedException; import io.mosip.registration.processor.core.http.ResponseWrapper; @@ -66,12 +55,14 @@ 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.DataShare; 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.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; @@ -126,6 +117,9 @@ public class AbisHandlerStageTest { @Mock private CbeffUtil cbeffutil; + @Mock + private ABISHandlerUtil abisHandlerUtil; + @InjectMocks private AbisHandlerStage abisHandlerStage = new AbisHandlerStage() { @Override @@ -171,10 +165,6 @@ public void setUp() throws Exception { ReflectionTestUtils.setField(abisHandlerStage, "workerPoolSize", 10); ReflectionTestUtils.setField(abisHandlerStage, "messageExpiryTimeLimit", Long.valueOf(0)); ReflectionTestUtils.setField(abisHandlerStage, "clusterManagerUrl", "/dummyPath"); - Map> biometricModalitySegmentsMap = new HashMap(); - biometricModalitySegmentsMap.put("Finger", getFingerList()); - biometricModalitySegmentsMap.put("Iris", getIrisList()); - biometricModalitySegmentsMap.put("Face", getFaceList()); ReflectionTestUtils.setField(abisHandlerStage, "insufficentBiometricsStatusCode", "REJECTED"); Mockito.when(env.getProperty("mosip.registration.processor.datetime.pattern")) .thenReturn("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); @@ -216,11 +206,10 @@ public void setUp() throws Exception { DataShare dataShare = new DataShare(); dataShare.setUrl("http://localhost"); dataShareResponseDto.setDataShare(dataShare); - - mockDataSharePolicy(Lists.newArrayList(BiometricType.FACE, BiometricType.FINGER, BiometricType.IRIS)); Mockito.doNothing().when(description).setMessage(any()); Mockito.when(description.getMessage()).thenReturn("description"); Mockito.when(registrationProcessorRestClientService.postApi(any(ApiName.class), any(MediaType.class), any(),any(),any(), any(), any())).thenReturn(dataShareResponseDto); + } @Test @@ -467,21 +456,6 @@ public void testIdentifyRequestException() throws JsonProcessingException { assertTrue(result.getInternalError()); } - 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 List getFaceList() { - return Arrays.asList("Face"); - } - private BiometricRecord getBiometricRecord(List bioAttributes, boolean isBdbEmpty) { BiometricRecord biometricRecord = new BiometricRecord(); @@ -522,65 +496,6 @@ private BiometricRecord getBiometricRecord(List bioAttributes, boolean i return biometricRecord; } - private void mockDataSharePolicy(List shareableBiometricList) throws ApisResourceAccessException { - when(registrationProcessorRestClientService.getApi(any(), any(), anyString(), anyString(), any())) - .thenReturn(getMockDataSharePolicy(shareableBiometricList)); - } - - private ResponseWrapper> getMockDataSharePolicy( - List shareableBiometricList) { - - ObjectMapper mapper = new ObjectMapper(); - - List attr = new LinkedList<>(); - if (shareableBiometricList != null && !shareableBiometricList.isEmpty()) { - - ShareableAttributes shareableAttributes = new ShareableAttributes(); - List sourceList = new ArrayList<>(); - - for (BiometricType bioType : shareableBiometricList) { - Filter filter = new Filter(); - filter.setType(bioType.value()); - if (BiometricType.FINGER.equals(bioType)) { - filter.setSubType(getFingerList()); - } else if (BiometricType.FINGER.equals(bioType)) { - filter.setSubType(getIrisList()); - } - - 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 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); - assertFalse(result.getIsValid()); - assertTrue(result.getInternalError()); - } - private void defaultMockToProcess() { Mockito.when(registrationStatusDto.getLatestTransactionTypeCode()).thenReturn("BIOGRAPHIC_VERIFICATION"); Mockito.when(registrationStatusDto.getLatestRegistrationTransactionId()) @@ -604,52 +519,17 @@ private void defaultMockToProcess() { } - @Test - public void emptyBdbFound() - throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { - - defaultMockToProcess(); - - Mockito.when(packetManagerService.getBiometrics(any(), any(), any(), any(), any())) - .thenReturn(getBiometricRecord(Arrays.asList("Left RingFinger"), true)); - mockDataSharePolicy(Lists.newArrayList(BiometricType.FINGER)); - - MessageDTO dto = new MessageDTO(); - dto.setRid("10003100030001520190422074511"); - MessageDTO result = abisHandlerStage.process(dto); - - assertFalse(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)); - mockDataSharePolicy(Lists.newArrayList(BiometricType.IRIS)); - - MessageDTO dto = new MessageDTO(); - dto.setRid("10003100030001520190422074511"); - MessageDTO result = abisHandlerStage.process(dto); - - assertFalse(result.getIsValid()); - assertTrue(result.getInternalError()); - } @Test public void bioRecordDataNotFound() - throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { + throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException, BiometricRecordValidationException { defaultMockToProcess(); Mockito.when(packetManagerService.getBiometrics(any(), any(), any(), any(), any())).thenReturn(null); - mockDataSharePolicy(Lists.newArrayList(BiometricType.IRIS, BiometricType.FINGER, BiometricType.FACE)); - + BiometricRecordValidationException e = new BiometricRecordValidationException("Biometirc validation failed"); + Mockito.doThrow(e).when(abisHandlerUtil).validateBiometricRecord(any(), anyList()); MessageDTO dto = new MessageDTO(); dto.setRid("10003100030001520190422074511"); MessageDTO result = abisHandlerStage.process(dto); diff --git a/registration-processor/core-processor/registration-processor-demo-dedupe-stage/src/main/java/io/mosip/registration/processor/stages/app/constants/DemoDedupeConstants.java b/registration-processor/core-processor/registration-processor-demo-dedupe-stage/src/main/java/io/mosip/registration/processor/stages/app/constants/DemoDedupeConstants.java index 3ab86f2d55f..806b3231f42 100644 --- a/registration-processor/core-processor/registration-processor-demo-dedupe-stage/src/main/java/io/mosip/registration/processor/stages/app/constants/DemoDedupeConstants.java +++ b/registration-processor/core-processor/registration-processor-demo-dedupe-stage/src/main/java/io/mosip/registration/processor/stages/app/constants/DemoDedupeConstants.java @@ -1,28 +1,34 @@ -package io.mosip.registration.processor.stages.app.constants; - -public class DemoDedupeConstants { - - public static final String FINGERTYPE = "fingerType"; - - /** The Constant FILE_SEPARATOR. */ - public static final String FILE_SEPARATOR = "\\"; - - /** The Constant USER. */ - public static final String USER = "MOSIP_SYSTEM"; - - /** The Constant CREATED_BY. */ - public static final String CREATED_BY = "MOSIP"; - - /** The Constant IDENTIFY. */ - public static final String IDENTIFY = "IDENTIFY"; - - public static final String NO_DATA_IN_DEMO = "Duplicate data not saved in demo list table"; - public static final String RECORD_INSERTED_FROM_ABIS_HANDLER = "Record is inserted in demo dedupe potential match, destination stage is abis handler"; - public static final String DEMO_SUCCESS = "Demo dedupe successful. No duplicates found"; - public static final String SENDING_TO_REPROCESS = "Failed in Abis. Hence sending to Reprocess"; - public static final String NO_DUPLICATES_FOUND = "ABIS response Details null, hence no duplicates found"; - public static final String SENDING_FOR_MANUAL = "ABIS response Details found. Hence sending to manual adjudication"; - public static final String REJECTED_OR_REREGISTER = "The packet status is Rejected or Re-Register. Hence ignoring Registration Id"; - public static final String NO_MATCH_FOUND = "No matched RegistrationId's found. Hence data is not inserting in manual adjudication table"; - public static final String DEMO_SKIP = "Demographic Deduplication Skipped"; -} +package io.mosip.registration.processor.stages.app.constants; + +public class DemoDedupeConstants { + + public static final String FINGERTYPE = "fingerType"; + + /** The Constant FILE_SEPARATOR. */ + public static final String FILE_SEPARATOR = "\\"; + + /** The Constant USER. */ + public static final String USER = "MOSIP_SYSTEM"; + + /** The Constant CREATED_BY. */ + public static final String CREATED_BY = "MOSIP"; + + /** The Constant IDENTIFY. */ + public static final String IDENTIFY = "IDENTIFY"; + + public static final String NO_DATA_IN_DEMO = "Duplicate data not saved in demo list table"; + public static final String RECORD_INSERTED_FROM_ABIS_HANDLER = "Record is inserted in demo dedupe potential match, destination stage is abis handler"; + public static final String DEMO_SUCCESS = "Demo dedupe successful. No duplicates found"; + public static final String SENDING_TO_REPROCESS = "Failed in Abis. Hence sending to Reprocess"; + public static final String NO_DUPLICATES_FOUND = "ABIS response Details null, hence no duplicates found"; + public static final String SENDING_FOR_MANUAL = "ABIS response Details found. Hence sending to manual adjudication"; + public static final String REJECTED_OR_REREGISTER = "The packet status is Rejected or Re-Register. Hence ignoring Registration Id"; + public static final String NO_MATCH_FOUND = "No matched RegistrationId's found. Hence data is not inserting in manual adjudication table"; + public static final String DEMO_SKIP = "Demographic Deduplication Skipped"; + public static final String BIOMETRIC_VALIDATION_FAILED_SENDING_FOR_MANUAL = "Potential duplicates found and biometric validation failed. Hence sending to manual adjudication"; + public static final String REDIRECT_TO_MANUAL_VERIFICATION = "RedirectToManualVerification"; + public static final String MARK_AS_DEMODEDUPE_REJECTED = "MarkAsDemodedupeRejected"; + public static final String MARK_AS_DEMODEDUPE_SUCCESS = "MarkAsDemodedupeSuccess"; + public static final String BIOMETRIC_VALIDATION_FAILED_PACKET_REJECTED = "Potential duplicates found and biometric validation failed. Hence demodedupe Rejected"; + public static final String BIOMETRIC_VALIDATION_FAILED_PACKET_SUCCESS = "Potential Demo Match was Found and Biometric record validation failed.Hence demodedupe success"; +} 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 52ddd8aaa40..ea0513a1ce0 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,609 +1,763 @@ -package io.mosip.registration.processor.stages.demodedupe; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -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; -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.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.exception.ApisResourceAccessException; -import io.mosip.registration.processor.core.exception.PacketDecryptionFailureException; -import io.mosip.registration.processor.core.exception.RegistrationProcessorCheckedException; -import io.mosip.registration.processor.core.exception.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.exception.IdRepoAppException; -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.status.code.RegistrationStatusCode; -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.dto.SyncTypeDto; -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); - - /** 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; - - /** - * 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); - - try { - // Persist Demographic packet Data if packet Registration type is NEW - if (registrationStatusDto.getRegistrationType().equals(RegistrationType.NEW.name())) { - - String packetStatus = abisHandlerUtil.getPacketStatus(registrationStatusDto); - - if (packetStatus.equalsIgnoreCase(AbisConstant.PRE_ABIS_IDENTIFICATION)) { - - packetInfoManager.saveDemographicInfoJson(registrationId, - registrationStatusDto.getRegistrationType(), moduleId, moduleName); - 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 { - if (env.getProperty(DEMODEDUPEENABLE).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); - } - - } else if (registrationStatusDto.getRegistrationType().equals(RegistrationType.UPDATE.name()) - || registrationStatusDto.getRegistrationType().equals(RegistrationType.RES_UPDATE.name())) { - IndividualDemographicDedupe demoDedupeData = new IndividualDemographicDedupe(); - - - 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) { - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), - LoggerFileConstant.REGISTRATIONID.toString(), registrationId, - PlatformErrorMessages.RPR_PIS_IDENTITY_NOT_FOUND.getMessage()); - throw new IdRepoAppException(PlatformErrorMessages.RPR_PIS_IDENTITY_NOT_FOUND.getMessage()); - } - 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, registrationId, moduleId, - moduleName); - 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()); - - } - if (abisHandlerUtil.getPacketStatus(registrationStatusDto).equalsIgnoreCase(AbisConstant.DUPLICATE_FOR_SAME_TRANSACTION_ID)) - isDuplicateRequestForSameTransactionId = true; - - registrationStatusDto.setRegistrationStageName(stageName); - - } 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); - object.setIsValid(Boolean.FALSE); - } 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); - object.setIsValid(Boolean.FALSE); - } 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); - object.setIsValid(Boolean.FALSE); - } 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); - object.setIsValid(Boolean.FALSE); - } 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.setIsValid(Boolean.FALSE); - object.setMessageBusAddress(MessageBusAddress.DEMO_DEDUPE_BUS_IN); - object.setInternalError(Boolean.TRUE); - } - if (object.getIsValid()) - 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; - } - - - /** - * 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()); - - 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); - 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) { - RegistrationStatusEntity entity = registrationStatusDao.findById(registrationId); - 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. - * @throws io.mosip.kernel.core.exception.IOException - * @throws PacketDecryptionFailureException - * @throws RegistrationProcessorCheckedException - */ - private boolean processDemoDedupeRequesthandler(InternalRegistrationStatusDto registrationStatusDto, - MessageDTO object, LogDescription description) throws ApisResourceAccessException, IOException, - PacketDecryptionFailureException, io.mosip.kernel.core.exception.IOException, - RegistrationProcessorCheckedException, JsonProcessingException, PacketManagerException { - boolean isTransactionSuccessful = false; - List responsIds = new ArrayList<>(); - - String latestTransactionId = getLatestTransactionId(registrationStatusDto.getRegistrationId()); - - 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 { - object.setIsValid(Boolean.FALSE); - registrationStatusDto - .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.FAILED.toString()); - registrationStatusDto.setStatusCode(RegistrationStatusCode.REJECTED.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); - 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()); - 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()); - 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) - throws ApisResourceAccessException, IOException, JsonProcessingException, PacketManagerException { - List matchedRegIds = abisHandlerUtil.getUniqueRegIds(registrationStatusDto.getRegistrationId(), - SyncTypeDto.NEW.toString(), ProviderStageName.DEMO_DEDUPE); - if (!matchedRegIds.isEmpty()) { - String moduleId = PlatformErrorMessages.RPR_DEMO_SENDING_FOR_MANUAL.getCode(); - String moduleName = ModuleName.DEMO_DEDUPE.toString(); - packetInfoManager.saveManualAdjudicationData(matchedRegIds, registrationStatusDto.getRegistrationId(), - DedupeSourceName.DEMO, moduleId, moduleName,null,null); - } else { - regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - registrationStatusDto.getRegistrationId(), DemoDedupeConstants.NO_MATCH_FOUND); - } - - } - +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.Map; +import java.util.stream.Collectors; + +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.biometrics.entities.BiometricRecord; +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.BiometricRecordValidationException; +import io.mosip.registration.processor.core.exception.DataShareException; +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.exception.IdRepoAppException; +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.stages.app.constants.DemoDedupeConstants; +import io.mosip.registration.processor.status.code.RegistrationStatusCode; +import io.mosip.registration.processor.status.code.RegistrationType; +import io.mosip.registration.processor.status.dao.RegistrationStatusDao; +import io.mosip.registration.processor.status.dto.InternalRegistrationStatusDto; +import io.mosip.registration.processor.status.dto.RegistrationStatusDto; +import io.mosip.registration.processor.status.entity.RegistrationStatusEntity; +import io.mosip.registration.processor.status.service.RegistrationStatusService; + +/** + * The Class DemodedupeProcessor. + */ +@Service +@Transactional +public class DemodedupeProcessor { + + /** The reg proc logger. */ + private static Logger regProcLogger = RegProcessorLogger.getLogger(DemodedupeProcessor.class); + + /** 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; + + @Autowired + private PriorityBasedPacketManagerService priorityBasedPacketManagerService; + + /** 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("${mosip.regproc.demo.dedupe.invalid-biometrics-action}") + private String demodedupeInvalidBiometricAction; + + @Value("${mosip.regproc.demo.dedupe.infant.invalid-biometrics-action}") + private String demodedupeInfantInvalidBiometricAction; + + /** + * 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); + + try { + // Persist Demographic packet Data if packet Registration type is NEW + if (registrationStatusDto.getRegistrationType().equals(RegistrationType.NEW.name())) { + + String packetStatus = abisHandlerUtil.getPacketStatus(registrationStatusDto); + + if (packetStatus.equalsIgnoreCase(AbisConstant.PRE_ABIS_IDENTIFICATION)) { + + packetInfoManager.saveDemographicInfoJson(registrationId, + registrationStatusDto.getRegistrationType(), moduleId, moduleName); + 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, + trimExceptionMessage, true); + if (duplicateDtos.isEmpty()) + isTransactionSuccessful = true; + } + } + else { + if (env.getProperty(DEMODEDUPEENABLE).trim().equalsIgnoreCase(TRUE)) { + isDemoDedupeSkip = false; + duplicateDtos = performDemoDedupe(registrationStatusDto, object, description, + trimExceptionMessage, false); + 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); + } + + } else if (registrationStatusDto.getRegistrationType().equals(RegistrationType.UPDATE.name()) + || registrationStatusDto.getRegistrationType().equals(RegistrationType.RES_UPDATE.name())) { + IndividualDemographicDedupe demoDedupeData = new IndividualDemographicDedupe(); + + + 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) { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString(), registrationId, + PlatformErrorMessages.RPR_PIS_IDENTITY_NOT_FOUND.getMessage()); + throw new IdRepoAppException(PlatformErrorMessages.RPR_PIS_IDENTITY_NOT_FOUND.getMessage()); + } + 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, registrationId, moduleId, + moduleName); + 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()); + + } + if (abisHandlerUtil.getPacketStatus(registrationStatusDto).equalsIgnoreCase(AbisConstant.DUPLICATE_FOR_SAME_TRANSACTION_ID)) + isDuplicateRequestForSameTransactionId = true; + + registrationStatusDto.setRegistrationStageName(stageName); + + }catch (PacketManagerException e) { + registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.name()); + registrationStatusDto.setStatusComment( + trimExceptionMessage + .trimExceptionMessage( + StatusUtil.DEMO_DEDUPE_PACKET_MANAGER_EXCEPTION.getMessage() + e.getMessage())); + registrationStatusDto.setSubStatusCode(StatusUtil.DEMO_DEDUPE_PACKET_MANAGER_EXCEPTION.getCode()); + registrationStatusDto.setLatestTransactionStatusCode(registrationExceptionMapperUtil.getStatusCode(RegistrationExceptionTypeCode.PACKET_MANAGER_EXCEPTION)); + description.setCode(PlatformErrorMessages.PACKET_MANAGER_EXCEPTION.getCode()); + description.setMessage(PlatformErrorMessages.PACKET_MANAGER_EXCEPTION.getMessage()); + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), + description.getCode() + " -- " + LoggerFileConstant.REGISTRATIONID.toString(), registrationId, + description + "\n" + ExceptionUtils.getStackTrace(e)); + object.setInternalError(Boolean.TRUE); + object.setIsValid(Boolean.FALSE); + } + 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); + object.setIsValid(Boolean.FALSE); + } 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); + object.setIsValid(Boolean.FALSE); + } 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); + object.setIsValid(Boolean.FALSE); + } 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); + object.setIsValid(Boolean.FALSE); + } finally { + if (!isDuplicateRequestForSameTransactionId) { + registrationStatusDto + .setLatestTransactionTypeCode(RegistrationTransactionTypeCode.DEMOGRAPHIC_VERIFICATION.toString()); + moduleId = isTransactionSuccessful ? PlatformSuccessMessages.RPR_PKR_DEMO_DE_DUP.getCode() + : description.getCode(); + registrationStatusDto.setUpdatedBy(DemoDedupeConstants.USER); + 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.setIsValid(Boolean.FALSE); + object.setMessageBusAddress(MessageBusAddress.DEMO_DEDUPE_BUS_IN); + object.setInternalError(Boolean.TRUE); + } + if (object.getIsValid()) + 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; + } + + + /** + * Perform demo dedupe. + * + * @param registrationStatusDto the registration status dto + * @param object the object + * @param description + * @return true, if successful + * @throws IOException + * @throws DataShareException + * @throws JsonProcessingException + * @throws PacketManagerException + * @throws ApisResourceAccessException + */ + private List performDemoDedupe(InternalRegistrationStatusDto registrationStatusDto, + MessageDTO object, LogDescription description, TrimExceptionMessage trimExceptionMessage, boolean isInfant) + throws ApisResourceAccessException, PacketManagerException, + JsonProcessingException, DataShareException, IOException { + String registrationId = registrationStatusDto.getRegistrationId(); + // Potential Duplicate Ids after performing demo dedupe + List duplicateDtos = demoDedupe.performDedupe(registrationStatusDto.getRegistrationId()); + List matchedRidsWithoutRejected = new ArrayList<>(); + List matchedRegIds; + if (!duplicateDtos.isEmpty()) { + duplicateDtos.removeIf(duplicateDto -> duplicateDto.getRegId().equals(registrationId)); + matchedRegIds = duplicateDtos.stream().map(DemographicInfoDto::getRegId) + .collect(Collectors.toList()); + matchedRidsWithoutRejected = abisHandlerUtil.removeRejectedIds(matchedRegIds); + for (DemographicInfoDto demographicInfoDto : new ArrayList(duplicateDtos)) { + if (!matchedRidsWithoutRejected.contains(demographicInfoDto.getRegId())) { + duplicateDtos.remove(demographicInfoDto); + } + } + } + if (!duplicateDtos.isEmpty()) { + try { + biometricValidation(registrationStatusDto); + 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); + 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); + } catch (BiometricRecordValidationException e) { + isMatchFound = true; + handleInvalidBiometricAction(registrationStatusDto, object, description, trimExceptionMessage, + registrationId, matchedRidsWithoutRejected, e, isInfant); + + } + + } 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; + } + + + private void handleInvalidBiometricAction(InternalRegistrationStatusDto registrationStatusDto, MessageDTO object, + LogDescription description, TrimExceptionMessage trimExceptionMessage, String registrationId, + List matchedRidsWithoutRejected, BiometricRecordValidationException e, boolean isInfant) + throws ApisResourceAccessException, IOException, JsonProcessingException, PacketManagerException { + if ((!isInfant + && demodedupeInvalidBiometricAction.equalsIgnoreCase(DemoDedupeConstants.MARK_AS_DEMODEDUPE_SUCCESS)) + || (isInfant && demodedupeInfantInvalidBiometricAction + .equalsIgnoreCase(DemoDedupeConstants.MARK_AS_DEMODEDUPE_SUCCESS))) { + object.setIsValid(Boolean.TRUE); + registrationStatusDto + .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.SUCCESS.toString()); + registrationStatusDto.setStatusComment( + StatusUtil.DEMO_DEDUPE_BIOMTERIC_RECORD_VALIDAITON_FAILED_AND_PACKET_SUCCESS.getMessage()); + registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); + registrationStatusDto.setSubStatusCode( + StatusUtil.DEMO_DEDUPE_BIOMTERIC_RECORD_VALIDAITON_FAILED_AND_PACKET_SUCCESS.getCode()); + description + .setCode(PlatformSuccessMessages.RPR_PKR_DEMO_DE_DUP_POTENTIAL_DUPLICATION_SUCCESS.getCode()); + description + .setMessage( + PlatformSuccessMessages.RPR_PKR_DEMO_DE_DUP_POTENTIAL_DUPLICATION_SUCCESS.getMessage() + + " -- " + registrationId); + regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString(), registrationStatusDto.getRegistrationId(), + DemoDedupeConstants.DEMO_SUCCESS); + } else if ((!isInfant && demodedupeInvalidBiometricAction + .equalsIgnoreCase(DemoDedupeConstants.REDIRECT_TO_MANUAL_VERIFICATION)) + || (isInfant && demodedupeInfantInvalidBiometricAction + .equalsIgnoreCase(DemoDedupeConstants.REDIRECT_TO_MANUAL_VERIFICATION))) { + handleRedirectToManualVerification(registrationStatusDto, object, description, trimExceptionMessage, + matchedRidsWithoutRejected, e); + } else if ((!isInfant && demodedupeInvalidBiometricAction + .equalsIgnoreCase(DemoDedupeConstants.MARK_AS_DEMODEDUPE_REJECTED)) + || (isInfant && demodedupeInfantInvalidBiometricAction + .equalsIgnoreCase(DemoDedupeConstants.MARK_AS_DEMODEDUPE_REJECTED))) { + registrationStatusDto + .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.FAILED.toString()); + registrationStatusDto.setStatusCode(RegistrationStatusCode.REJECTED.toString()); + registrationStatusDto.setStatusComment(trimExceptionMessage.trimExceptionMessage( + StatusUtil.DEMO_DEDUPE_BIOMTERIC_RECORD_VALIDAITON_FAILED_AND_PACKET_REJECTED.getMessage() + + " -> " + e.getErrorText())); + registrationStatusDto + .setSubStatusCode(StatusUtil.DEMO_DEDUPE_BIOMTERIC_RECORD_VALIDAITON_FAILED_AND_PACKET_REJECTED + .getCode()); + description.setCode(PlatformErrorMessages.RPR_DEMO_POTENTIAL_PACKET_REJECTED.getCode()); + description.setMessage(PlatformErrorMessages.RPR_DEMO_POTENTIAL_PACKET_REJECTED.getMessage()); + regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString(), registrationStatusDto.getRegistrationId(), + DemoDedupeConstants.BIOMETRIC_VALIDATION_FAILED_PACKET_REJECTED); + } else { + handleRedirectToManualVerification(registrationStatusDto, object, description, trimExceptionMessage, + matchedRidsWithoutRejected, e); + } + } + + + private void handleRedirectToManualVerification(InternalRegistrationStatusDto registrationStatusDto, + MessageDTO object, LogDescription description, TrimExceptionMessage trimExceptionMessage, + List matchedRidsWithoutRejected, BiometricRecordValidationException e) + throws ApisResourceAccessException, IOException, JsonProcessingException, PacketManagerException { + registrationStatusDto + .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.FAILED.toString()); + registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); + registrationStatusDto.setStatusComment(trimExceptionMessage.trimExceptionMessage( + StatusUtil.DEMO_DEDUPE_BIOMTERIC_RECORD_VALIDAITON_FAILED.getMessage() + " -> " + + e.getErrorText())); + registrationStatusDto + .setSubStatusCode(StatusUtil.DEMO_DEDUPE_BIOMTERIC_RECORD_VALIDAITON_FAILED.getCode()); + description.setCode(PlatformErrorMessages.RPR_DEMO_POTENTIAL_SENDING_FOR_MANUAL.getCode()); + description.setMessage(PlatformErrorMessages.RPR_DEMO_POTENTIAL_SENDING_FOR_MANUAL.getMessage()); + object.setMessageBusAddress(MessageBusAddress.MANUAL_VERIFICATION_BUS_IN); + saveManualAdjudicationData(registrationStatusDto, matchedRidsWithoutRejected); + regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString(), registrationStatusDto.getRegistrationId(), + DemoDedupeConstants.BIOMETRIC_VALIDATION_FAILED_SENDING_FOR_MANUAL); + } + + /** + * Gets the latest transaction id. + * + * @param registrationId + * the registration id + * @return the latest transaction id + */ + private String getLatestTransactionId(String registrationId) { + RegistrationStatusEntity entity = registrationStatusDao.findById(registrationId); + 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. + * @throws io.mosip.kernel.core.exception.IOException + * @throws PacketDecryptionFailureException + * @throws RegistrationProcessorCheckedException + */ + private boolean processDemoDedupeRequesthandler(InternalRegistrationStatusDto registrationStatusDto, + MessageDTO object, LogDescription description) throws ApisResourceAccessException, IOException, + PacketDecryptionFailureException, io.mosip.kernel.core.exception.IOException, + RegistrationProcessorCheckedException, JsonProcessingException, PacketManagerException { + boolean isTransactionSuccessful = false; + List responsIds = new ArrayList<>(); + + String latestTransactionId = getLatestTransactionId(registrationStatusDto.getRegistrationId()); + + 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.PROCESSING.toString()); + regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString(), registrationStatusDto.getRegistrationId(), + DemoDedupeConstants.SENDING_TO_REPROCESS); + } + } + + if (!responsIds.isEmpty()) { + List abisResponseDetDto = packetInfoManager.getAbisResponseDetRecordsList(responsIds); + List uniqueRids = abisHandlerUtil.getUniqueRegIds(registrationStatusDto.getRegistrationId(), + registrationStatusDto.getRegistrationType(), ProviderStageName.DEMO_DEDUPE); + if (abisResponseDetDto.isEmpty() || uniqueRids.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 { + object.setIsValid(Boolean.FALSE); + registrationStatusDto + .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.FAILED.toString()); + registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.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()); + object.setMessageBusAddress(MessageBusAddress.MANUAL_VERIFICATION_BUS_IN); + saveManualAdjudicationData(registrationStatusDto, uniqueRids); + 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()); + 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()); + 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, + List matchedRegIds) + throws ApisResourceAccessException, IOException, JsonProcessingException, PacketManagerException { + String moduleId = PlatformErrorMessages.RPR_DEMO_SENDING_FOR_MANUAL.getCode(); + String moduleName = ModuleName.DEMO_DEDUPE.toString(); + packetInfoManager.saveManualAdjudicationData(matchedRegIds, registrationStatusDto.getRegistrationId(), + DedupeSourceName.DEMO, moduleId, moduleName,null,null); + } + + private void biometricValidation(InternalRegistrationStatusDto registrationStatusDto) + throws IOException, ApisResourceAccessException, PacketManagerException, JsonProcessingException, + BiometricRecordValidationException, DataShareException { + Map> typeAndSubtypMap = abisHandlerUtil.createBiometricTypeSubtypeMappingFromAbispolicy(); + List segments = new ArrayList<>(); + for (Map.Entry> entry : typeAndSubtypMap.entrySet()) { + if (entry.getValue() == null) { + segments.add(entry.getKey()); + } else { + segments.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( + registrationStatusDto.getRegistrationId(), individualBiometricsLabel, segments, + registrationStatusDto.getRegistrationType(), ProviderStageName.DEMO_DEDUPE); + abisHandlerUtil.validateBiometricRecord(biometricRecord, segments); + + } } \ No newline at end of file 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 5f714fe879c..7d542280aa9 100644 --- a/registration-processor/core-processor/registration-processor-demo-dedupe-stage/src/test/java/io/mosip/registrationprocessor/stages/demodedupe/DemodedupeProcessorTest.java +++ b/registration-processor/core-processor/registration-processor-demo-dedupe-stage/src/test/java/io/mosip/registrationprocessor/stages/demodedupe/DemodedupeProcessorTest.java @@ -1,851 +1,1258 @@ -package io.mosip.registrationprocessor.stages.demodedupe; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyList; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.doNothing; -import static org.mockito.Mockito.when; - -import java.beans.IntrospectionException; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.lang.reflect.InvocationTargetException; -import java.text.ParseException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import io.mosip.registration.processor.core.exception.PacketManagerException; -import org.apache.commons.io.IOUtils; -import org.json.simple.JSONArray; -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.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; -import org.springframework.core.env.Environment; -import org.springframework.test.util.ReflectionTestUtils; - -import com.fasterxml.jackson.databind.ObjectMapper; - -import io.mosip.kernel.core.fsadapter.exception.FSAdapterException; -import io.mosip.kernel.core.util.HMACUtils2; -import io.mosip.kernel.core.util.exception.JsonProcessingException; -import io.mosip.registration.processor.core.abstractverticle.MessageDTO; -import io.mosip.registration.processor.core.code.AbisStatusCode; -import io.mosip.registration.processor.core.code.ApiName; -import io.mosip.registration.processor.core.code.EventId; -import io.mosip.registration.processor.core.code.EventName; -import io.mosip.registration.processor.core.code.EventType; -import io.mosip.registration.processor.core.constant.AbisConstant; -import io.mosip.registration.processor.core.constant.MappingJsonConstants; -import io.mosip.registration.processor.core.constant.PacketFiles; -import io.mosip.registration.processor.core.exception.ApisResourceAccessException; -import io.mosip.registration.processor.core.exception.RegistrationProcessorCheckedException; -import io.mosip.registration.processor.core.http.ResponseWrapper; -import io.mosip.registration.processor.core.logger.LogDescription; -import io.mosip.registration.processor.core.packet.dto.FieldValue; -import io.mosip.registration.processor.core.packet.dto.FieldValueArray; -import io.mosip.registration.processor.core.packet.dto.Identity; -import io.mosip.registration.processor.core.packet.dto.PacketMetaInfo; -import io.mosip.registration.processor.core.packet.dto.abis.AbisResponseDetDto; -import io.mosip.registration.processor.core.packet.dto.abis.AbisResponseDto; -import io.mosip.registration.processor.core.packet.dto.demographicinfo.DemographicInfoDto; -import io.mosip.registration.processor.core.packet.dto.demographicinfo.IndividualDemographicDedupe; -import io.mosip.registration.processor.core.packet.dto.demographicinfo.JsonValue; -import io.mosip.registration.processor.core.packet.dto.demographicinfo.identify.IdentityJsonValues; -import io.mosip.registration.processor.core.packet.dto.idjson.Document; -import io.mosip.registration.processor.core.spi.packetmanager.PacketInfoManager; -import io.mosip.registration.processor.core.util.JsonUtil; -import io.mosip.registration.processor.core.util.RegistrationExceptionMapperUtil; -import io.mosip.registration.processor.packet.storage.dto.ApplicantInfoDto; -import io.mosip.registration.processor.packet.storage.entity.IndividualDemographicDedupeEntity; -import io.mosip.registration.processor.packet.storage.entity.ManualVerificationEntity; -import io.mosip.registration.processor.packet.storage.exception.IdRepoAppException; -import io.mosip.registration.processor.packet.storage.repository.BasePacketRepository; -import io.mosip.registration.processor.packet.storage.utils.ABISHandlerUtil; -import io.mosip.registration.processor.packet.storage.utils.Utilities; -import io.mosip.registration.processor.rest.client.audit.builder.AuditLogRequestBuilder; -import io.mosip.registration.processor.rest.client.audit.dto.AuditResponseDto; -import io.mosip.registration.processor.stages.demodedupe.DemoDedupe; -import io.mosip.registration.processor.stages.demodedupe.DemodedupeProcessor; -import io.mosip.registration.processor.status.code.RegistrationType; -import io.mosip.registration.processor.status.dao.RegistrationStatusDao; -import io.mosip.registration.processor.status.dto.InternalRegistrationStatusDto; -import io.mosip.registration.processor.status.dto.RegistrationStatusDto; -import io.mosip.registration.processor.status.entity.RegistrationStatusEntity; -import io.mosip.registration.processor.status.service.RegistrationStatusService; - -/** - * The Class DemodedupeStageTest. - */ -@RunWith(PowerMockRunner.class) -@PowerMockIgnore({ "javax.management.*", "javax.net.ssl.*","com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", }) -@PrepareForTest({ JsonUtil.class, IOUtils.class, HMACUtils2.class }) -public class DemodedupeProcessorTest { - - /** The registration status service. */ - @Mock - private RegistrationStatusService registrationStatusService; - - @Mock - private PacketInfoManager packetInfoManager; - - /** The manual verfication repository. */ - @Mock - private BasePacketRepository manualVerficationRepository; - - /** The demographic dedupe repository. */ - @Mock - private BasePacketRepository demographicDedupeRepository; - - /** The demo dedupe. */ - @Mock - private DemoDedupe demoDedupe; - - @Mock - private InputStream inputStream; - - private static final String source = "reg_client"; - - - - /** The dto. */ - private MessageDTO dto = new MessageDTO(); - - /** The duplicate dtos. */ - private List duplicateDtos = new ArrayList<>(); - - /** The audit log request builder. */ - @Mock - private AuditLogRequestBuilder auditLogRequestBuilder; - - @Mock - RegistrationExceptionMapperUtil registrationStatusMapperUtil; - - @InjectMocks - private DemodedupeProcessor demodedupeProcessor; - - @Mock - private ABISHandlerUtil abisHandlerUtil; - - @Mock - private RegistrationStatusDao registrationStatusDao; - - @Mock - private Utilities utility; - - private InternalRegistrationStatusDto registrationStatusDto; - - private Identity identity = new Identity(); - - private PacketMetaInfo packetMetaInfo; - - RegistrationStatusEntity entity = new RegistrationStatusEntity(); - - private String stageName = "DemoDedupeStage"; - - private IndividualDemographicDedupe individualDemoDedupe; - - @Mock - LogDescription description; - - @Mock - private Environment env; - - private static final String DEMODEDUPEENABLE = "mosip.registration.processor.demographic.deduplication.enable"; - - - - - /** - * Sets the up. - * - * @throws Exception - * the exception - */ - @Before - public void setUp() throws Exception { - when(utility.getDefaultSource(any(), any())).thenReturn(source); - ReflectionTestUtils.setField(demodedupeProcessor, "infantDedupe", "Y"); - ReflectionTestUtils.setField(demodedupeProcessor, "ageLimit", "4"); - dto.setRid("2018701130000410092018110735"); - - MockitoAnnotations.initMocks(this); - - DemographicInfoDto dto1 = new DemographicInfoDto(); - DemographicInfoDto dto2 = new DemographicInfoDto(); - - duplicateDtos.add(dto1); - duplicateDtos.add(dto2); - - registrationStatusDto = new InternalRegistrationStatusDto(); - registrationStatusDto.setRegistrationType("NEW"); - registrationStatusDto.setRegistrationId("2018701130000410092018110735"); - - packetMetaInfo = new PacketMetaInfo(); - - FieldValue registrationType = new FieldValue(); - registrationType.setLabel("registrationType"); - registrationType.setValue("New"); - - FieldValue applicantType = new FieldValue(); - applicantType.setLabel("applicantType"); - applicantType.setValue("Child"); - - FieldValue isVerified = new FieldValue(); - isVerified.setLabel("isVerified"); - isVerified.setValue("Verified"); - - FieldValue preRegistrationId = new FieldValue(); - preRegistrationId.setLabel("preRegistrationId"); - preRegistrationId.setValue("2018701130000410092018110736"); - - entity.setLatestRegistrationTransactionId("5d936385-7ee6-4b51-b21f-c20b0cfbcc11"); - - identity.setMetaData(Arrays.asList(registrationType, applicantType, isVerified, preRegistrationId)); - - Document documentPob = new Document(); - documentPob.setDocumentCategory("PROOFOFDATEOFBIRTH"); - documentPob.setDocumentName("ProofOfBirth"); - Document document = new Document(); - document.setDocumentCategory("PROOFOFRELATIONSHIP"); - document.setDocumentName("ProofOfRelation"); - List documents = new ArrayList(); - documents.add(documentPob); - documents.add(document); - individualDemoDedupe = new IndividualDemographicDedupe(); - - JsonValue[] jsonArray = new JsonValue[1]; - JsonValue[] jsonArray1 = new JsonValue[1]; - - JsonValue jsonValue1 = new JsonValue(); - JsonValue jsonValue2 = new JsonValue(); - - jsonValue1.setLanguage("eng"); - jsonValue1.setValue("name"); - jsonArray[0] = jsonValue1; - - jsonValue2.setLanguage("eng"); - jsonValue2.setValue("gender"); - jsonArray1[0] = jsonValue2; - List jsonArrayList = new ArrayList<>(); - jsonArrayList.add(jsonArray); - - individualDemoDedupe.setName(jsonArrayList); - individualDemoDedupe.setDateOfBirth("dateOfBirth"); - individualDemoDedupe.setPhone("phone"); - individualDemoDedupe.setEmail("email"); - individualDemoDedupe.setGender(jsonArray1); - List fieldValueArrayList = new ArrayList(); - - FieldValueArray applicantBiometric = new FieldValueArray(); - applicantBiometric.setLabel(PacketFiles.APPLICANTBIOMETRICSEQUENCE.name()); - List applicantBiometricValues = new ArrayList(); - applicantBiometricValues.add(PacketFiles.BOTHTHUMBS.name()); - applicantBiometric.setValue(applicantBiometricValues); - fieldValueArrayList.add(applicantBiometric); - FieldValueArray introducerBiometric = new FieldValueArray(); - introducerBiometric.setLabel(PacketFiles.INTRODUCERBIOMETRICSEQUENCE.name()); - List introducerBiometricValues = new ArrayList(); - introducerBiometricValues.add("introducerLeftThumb"); - introducerBiometric.setValue(introducerBiometricValues); - fieldValueArrayList.add(introducerBiometric); - FieldValueArray applicantDemographic = new FieldValueArray(); - applicantDemographic.setLabel(PacketFiles.APPLICANTDEMOGRAPHICSEQUENCE.name()); - List applicantDemographicValues = new ArrayList(); - applicantDemographicValues.add(PacketFiles.APPLICANTPHOTO.name()); - applicantDemographicValues.add("ProofOfBirth"); - applicantDemographicValues.add("ProofOfRelation"); - applicantDemographicValues.add("ProofOfAddress"); - applicantDemographicValues.add("ProofOfIdentity"); - applicantDemographic.setValue(applicantDemographicValues); - fieldValueArrayList.add(applicantDemographic); - identity.setHashSequence(fieldValueArrayList); - List sequence2 = new ArrayList<>(); - sequence2.add("audit"); - List fieldValueArrayListSequence = new ArrayList(); - FieldValueArray hashsequence2 = new FieldValueArray(); - hashsequence2.setValue(sequence2); - fieldValueArrayListSequence.add(hashsequence2); - identity.setHashSequence2(fieldValueArrayListSequence); - packetMetaInfo.setIdentity(identity); - - Mockito.when(registrationStatusMapperUtil.getStatusCode(any())).thenReturn("ERROR"); - - AuditResponseDto auditResponseDto = new AuditResponseDto(); - ResponseWrapper responseWrapper = new ResponseWrapper<>(); - responseWrapper.setResponse(auditResponseDto); - Mockito.doReturn(responseWrapper).when(auditLogRequestBuilder).createAuditRequestBuilder( - "test case description", EventId.RPR_405.toString(), EventName.UPDATE.toString(), - EventType.BUSINESS.toString(), "1234testcase", ApiName.AUDIT); - Mockito.doNothing().when(description).setMessage(any()); - InternalRegistrationStatusDto registrationStatusDto = new InternalRegistrationStatusDto(); - - registrationStatusDto.setRetryCount(null); - Mockito.when(registrationStatusService.getRegistrationStatus(anyString())).thenReturn(registrationStatusDto); - Mockito.doNothing().when(registrationStatusService).updateRegistrationStatus(any(), any(), any()); - ClassLoader classLoader = getClass().getClassLoader(); - File file = new File(classLoader.getResource("RegistrationProcessorIdentity.json").getFile()); - inputStream = new FileInputStream(file); - String mappingJsonString = IOUtils.toString(inputStream,"UTF-8"); - JSONObject mappingJsonObj= new ObjectMapper().readValue(mappingJsonString, JSONObject.class); - - Mockito.when(utility.getRegistrationProcessorMappingJson(anyString())).thenReturn(JsonUtil.getJSONObject(mappingJsonObj, MappingJsonConstants.IDENTITY)); - - - } - - /** - * Test demo dedupe success. - * - * @throws Exception - */ - @Test - public void testDemoDedupeNewPacketSuccess() throws Exception { - when(env.getProperty(DEMODEDUPEENABLE)).thenReturn("true"); - byte[] b = "sds".getBytes(); - List emptyDuplicateDtoSet = new ArrayList<>(); - Mockito.when(utility.getApplicantAge(anyString(),anyString(), any())).thenReturn(20); - PowerMockito.mockStatic(JsonUtil.class); - PowerMockito.mockStatic(IOUtils.class); - PowerMockito.when(JsonUtil.class, "inputStreamtoJavaObject", inputStream, PacketMetaInfo.class) - .thenReturn(packetMetaInfo); - PowerMockito.when(IOUtils.class, "toByteArray", inputStream).thenReturn(b); - Mockito.when(registrationStatusService.getRegistrationStatus(any())).thenReturn(registrationStatusDto); - Mockito.when(abisHandlerUtil.getPacketStatus(any())).thenReturn(AbisConstant.PRE_ABIS_IDENTIFICATION); - Mockito.when(demoDedupe.performDedupe(anyString())).thenReturn(emptyDuplicateDtoSet); - - MessageDTO messageDto = demodedupeProcessor.process(dto, stageName); - assertTrue(messageDto.getIsValid()); - - } - - @SuppressWarnings("unchecked") - @Test - public void testDemoDedupeUpdatePacketSuccess() throws Exception { - InternalRegistrationStatusDto registrationStatus = new InternalRegistrationStatusDto(); - registrationStatus.setRegistrationId("2018701130000410092018110736"); - registrationStatus.setRegistrationType(RegistrationType.UPDATE.name()); - - IdentityJsonValues identityJsonValues = new IdentityJsonValues(); - identityJsonValues.setValue("fullName"); - when(utility.getDefaultSource(any(), any())).thenReturn(source); - Mockito.when(utility.getUIn(anyString(), anyString(), any())).thenReturn("2345"); - - JSONArray arr = new JSONArray(); - arr.add("name"); - - JSONObject obj = new JSONObject(); - obj.put("fullName", arr); - Mockito.when(utility.retrieveIdrepoJson(anyString())).thenReturn(obj); - - byte[] b = "sds".getBytes(); - List emptyDuplicateDtoSet = new ArrayList<>(); - - PowerMockito.mockStatic(JsonUtil.class); - PowerMockito.mockStatic(IOUtils.class); - PowerMockito.when(JsonUtil.class, "inputStreamtoJavaObject", inputStream, PacketMetaInfo.class) - .thenReturn(packetMetaInfo); - PowerMockito.when(IOUtils.class, "toByteArray", inputStream).thenReturn(b); - Mockito.when(registrationStatusService.getRegistrationStatus(any())).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()); - } - - @Test - public void testDemoDedupeUpdatePacketException() throws Exception { - InternalRegistrationStatusDto registrationStatus = new InternalRegistrationStatusDto(); - registrationStatus.setRegistrationId("2018701130000410092018110736"); - registrationStatus.setRegistrationType(RegistrationType.UPDATE.name()); - - IdentityJsonValues identityJsonValues = new IdentityJsonValues(); - identityJsonValues.setValue("fullName"); - when(utility.getDefaultSource(any(),any())).thenReturn(source); - Mockito.when(utility.getUIn(anyString(), anyString(), any())).thenReturn("2345"); - - Mockito.when(utility.retrieveIdrepoJson(any())).thenReturn(null); - - byte[] b = "sds".getBytes(); - List emptyDuplicateDtoSet = new ArrayList<>(); - - PowerMockito.mockStatic(JsonUtil.class); - PowerMockito.mockStatic(IOUtils.class); - PowerMockito.when(JsonUtil.class, "inputStreamtoJavaObject", inputStream, PacketMetaInfo.class) - .thenReturn(packetMetaInfo); - PowerMockito.when(IOUtils.class, "toByteArray", inputStream).thenReturn(b); - Mockito.when(registrationStatusService.getRegistrationStatus(any())).thenReturn(registrationStatus); - Mockito.when(demoDedupe.performDedupe(anyString())).thenReturn(emptyDuplicateDtoSet); - Mockito.when(packetInfoManager.getIdentityKeysAndFetchValuesFromJSON(any(),any(),any())).thenReturn(individualDemoDedupe); - MessageDTO messageDto = demodedupeProcessor.process(dto, stageName); - assertFalse(messageDto.getIsValid()); - } - - @SuppressWarnings("unchecked") - @Test - public void testDemoDedupeResUpdatePacketSuccess() throws Exception { - InternalRegistrationStatusDto registrationStatus = new InternalRegistrationStatusDto(); - registrationStatus.setRegistrationId("2018701130000410092018110736"); - registrationStatus.setRegistrationType(RegistrationType.RES_UPDATE.name()); - - IdentityJsonValues identityJsonValues = new IdentityJsonValues(); - identityJsonValues.setValue("fullName"); - when(utility.getDefaultSource(any(),any())).thenReturn(source); - Mockito.when(utility.getUIn(anyString(), anyString(), any())).thenReturn("2345"); - - JSONArray arr = new JSONArray(); - arr.add("name"); - - JSONObject obj = new JSONObject(); - obj.put("fullName", arr); - Mockito.when(utility.retrieveIdrepoJson(anyString())).thenReturn(obj); - - byte[] b = "sds".getBytes(); - List emptyDuplicateDtoSet = new ArrayList<>(); - - PowerMockito.mockStatic(JsonUtil.class); - PowerMockito.mockStatic(IOUtils.class); - PowerMockito.when(JsonUtil.getJSONValue(any(), any())).thenReturn("Test1,Test2"); - PowerMockito.when(JsonUtil.getJSONObject(any(), any())).thenReturn(obj); - JsonValue[] nameArray = new JsonValue[1]; - JsonValue jsonValue = new JsonValue(); - jsonValue.setLanguage("eng"); - jsonValue.setValue("test"); - nameArray[0] = jsonValue; - PowerMockito.when(JsonUtil.getJsonValues(any(),any())).thenReturn(nameArray); - PowerMockito.when(JsonUtil.class, "inputStreamtoJavaObject", inputStream, PacketMetaInfo.class) - .thenReturn(packetMetaInfo); - PowerMockito.when(IOUtils.class, "toByteArray", inputStream).thenReturn(b); - Mockito.when(registrationStatusService.getRegistrationStatus(any())).thenReturn(registrationStatus); - Mockito.when(demoDedupe.performDedupe(anyString())).thenReturn(emptyDuplicateDtoSet); - IndividualDemographicDedupe demographicData = individualDemoDedupe; - demographicData.setName(null); - demographicData.setDateOfBirth(null); - demographicData.setGender(null); - demographicData.setPhone(null); - demographicData.setEmail(null); - Mockito.when(packetInfoManager.getIdentityKeysAndFetchValuesFromJSON(any(),any(), any())).thenReturn(demographicData); - Mockito.when(abisHandlerUtil.getPacketStatus(any())).thenReturn(AbisConstant.POST_ABIS_IDENTIFICATION); - MessageDTO messageDto = demodedupeProcessor.process(dto, stageName); - assertTrue(messageDto.getIsValid()); - } - - @SuppressWarnings("unchecked") - @Test - public void testDemoDedupeSuccessNotDuplicateAfterAuth() throws Exception { - - byte[] b = "sds".getBytes(); - Mockito.when(utility.getApplicantAge(anyString(),anyString(), any())).thenReturn(20); - PowerMockito.mockStatic(JsonUtil.class); - PowerMockito.mockStatic(IOUtils.class); - PowerMockito.when(JsonUtil.class, "inputStreamtoJavaObject", inputStream, PacketMetaInfo.class) - .thenReturn(packetMetaInfo); - PowerMockito.when(IOUtils.class, "toByteArray", inputStream).thenReturn(b); - Mockito.when(registrationStatusService.getRegistrationStatus(any())).thenReturn(registrationStatusDto); - Mockito.when(abisHandlerUtil.getPacketStatus(any())).thenReturn(AbisConstant.PRE_ABIS_IDENTIFICATION); - Mockito.when(demoDedupe.performDedupe(anyString())).thenReturn(duplicateDtos); - registrationStatusDto.setRegistrationType(RegistrationType.NEW.toString()); - Mockito.when(registrationStatusDao.findById(any())).thenReturn(entity); - MessageDTO messageDto = demodedupeProcessor.process(dto, stageName); - assertFalse(messageDto.getIsValid()); - - } - - /** - * Test demo dedupe potential match. - * - * @throws Exception - */ - @SuppressWarnings("unchecked") - @Test - public void testDemoDedupePotentialMatchSuccess() throws Exception { - List abisResponseDtos = new ArrayList<>(); - AbisResponseDto abisResponseDto = new AbisResponseDto(); - abisResponseDto.setId("100"); - abisResponseDto.setStatusCode(AbisStatusCode.SUCCESS.toString()); - abisResponseDto.setLangCode("eng"); - abisResponseDtos.add(abisResponseDto); - - byte[] b = "sds".getBytes(); - - PowerMockito.mockStatic(JsonUtil.class); - PowerMockito.mockStatic(IOUtils.class); - PowerMockito.when(JsonUtil.class, "inputStreamtoJavaObject", inputStream, PacketMetaInfo.class) - .thenReturn(packetMetaInfo); - PowerMockito.when(IOUtils.class, "toByteArray", inputStream).thenReturn(b); - Mockito.when(registrationStatusService.getRegistrationStatus(any())).thenReturn(registrationStatusDto); - Mockito.when(abisHandlerUtil.getPacketStatus(any())).thenReturn(AbisConstant.POST_ABIS_IDENTIFICATION); - Mockito.when(demoDedupe.performDedupe(anyString())).thenReturn(duplicateDtos); - registrationStatusDto.setRegistrationType(RegistrationType.NEW.toString()); - Mockito.when(registrationStatusDao.findById(any())).thenReturn(entity); - Mockito.when(packetInfoManager.getAbisResponseRecords(anyString(), anyString())).thenReturn(abisResponseDtos); - Mockito.when(utility.getApplicantAge(anyString(),anyString(), any())).thenReturn(20); - MessageDTO messageDto = demodedupeProcessor.process(dto, stageName); - - assertTrue(messageDto.getIsValid()); - - } - - @SuppressWarnings("unchecked") - @Test - @Ignore - public void testDemoDedupePotentialMatchWithEmpty() throws Exception { - List abisResponseDtos = new ArrayList<>(); - List abisResponseDetDtos = new ArrayList<>(); - List matchedRegIds = new ArrayList<>(); - AbisResponseDto abisResponseDto = new AbisResponseDto(); - abisResponseDto.setId("100"); - abisResponseDto.setStatusCode(AbisStatusCode.SUCCESS.toString()); - abisResponseDto.setLangCode("eng"); - abisResponseDtos.add(abisResponseDto); - - AbisResponseDetDto abisResponseDetDto = new AbisResponseDetDto(); - abisResponseDetDto.setAbiRespId("100"); - abisResponseDetDtos.add(abisResponseDetDto); - - matchedRegIds.add("2018701130000410092018110735"); - byte[] b = "sds".getBytes(); - - PowerMockito.mockStatic(JsonUtil.class); - PowerMockito.mockStatic(IOUtils.class); - PowerMockito.when(JsonUtil.class, "inputStreamtoJavaObject", inputStream, PacketMetaInfo.class) - .thenReturn(packetMetaInfo); - PowerMockito.when(IOUtils.class, "toByteArray", inputStream).thenReturn(b); - Mockito.when(registrationStatusService.getRegistrationStatus(any())).thenReturn(registrationStatusDto); - Mockito.when(abisHandlerUtil.getPacketStatus(any())).thenReturn(AbisConstant.POST_ABIS_IDENTIFICATION); - Mockito.when(demoDedupe.performDedupe(anyString())).thenReturn(duplicateDtos); - registrationStatusDto.setRegistrationType(RegistrationType.NEW.toString()); - Mockito.when(registrationStatusDao.findById(any())).thenReturn(entity); - Mockito.when(packetInfoManager.getAbisResponseRecords(anyString(), anyString())).thenReturn(abisResponseDtos); - Mockito.when(packetInfoManager.getAbisResponseDetRecordsList(any())).thenReturn(abisResponseDetDtos); - Mockito.when(abisHandlerUtil.getUniqueRegIds(any(), any(), any())).thenReturn(matchedRegIds); - doNothing().when(packetInfoManager).saveManualAdjudicationData(anyList(), anyString(), any(), any(), any(),null,null); - Mockito.when(utility.getApplicantAge(anyString(),anyString(), any())).thenReturn(20); - MessageDTO messageDto = demodedupeProcessor.process(dto, stageName); - - assertFalse(messageDto.getIsValid()); - - } - - @Test - @Ignore - public void testDemoDedupeEmptyMatch() throws Exception { - List abisResponseDtos = new ArrayList<>(); - List abisResponseDetDtos = new ArrayList<>(); - List matchedRegIds = new ArrayList<>(); - AbisResponseDto abisResponseDto = new AbisResponseDto(); - abisResponseDto.setId("100"); - abisResponseDto.setStatusCode(AbisStatusCode.SUCCESS.toString()); - abisResponseDto.setLangCode("eng"); - abisResponseDtos.add(abisResponseDto); - - AbisResponseDetDto abisResponseDetDto = new AbisResponseDetDto(); - abisResponseDetDto.setAbiRespId("100"); - abisResponseDetDtos.add(abisResponseDetDto); - - byte[] b = "sds".getBytes(); - - PowerMockito.mockStatic(JsonUtil.class); - PowerMockito.mockStatic(IOUtils.class); - PowerMockito.when(JsonUtil.class, "inputStreamtoJavaObject", inputStream, PacketMetaInfo.class) - .thenReturn(packetMetaInfo); - PowerMockito.when(IOUtils.class, "toByteArray", inputStream).thenReturn(b); - Mockito.when(registrationStatusService.getRegistrationStatus(any())).thenReturn(registrationStatusDto); - Mockito.when(abisHandlerUtil.getPacketStatus(any())).thenReturn(AbisConstant.POST_ABIS_IDENTIFICATION); - Mockito.when(demoDedupe.performDedupe(anyString())).thenReturn(duplicateDtos); - registrationStatusDto.setRegistrationType(RegistrationType.NEW.toString()); - Mockito.when(registrationStatusDao.findById(any())).thenReturn(entity); - Mockito.when(packetInfoManager.getAbisResponseRecords(anyString(), anyString())).thenReturn(abisResponseDtos); - Mockito.when(packetInfoManager.getAbisResponseDetRecordsList(any())).thenReturn(abisResponseDetDtos); - Mockito.when(abisHandlerUtil.getUniqueRegIds(any(), any(), any())).thenReturn(matchedRegIds); - doNothing().when(packetInfoManager).saveManualAdjudicationData(anyList(), anyString(), any(), any(), any(),null,null); - Mockito.when(utility.getApplicantAge(anyString(),anyString(), any())).thenReturn(20); - MessageDTO messageDto = demodedupeProcessor.process(dto, stageName); - - assertFalse(messageDto.getIsValid()); - - } - - @SuppressWarnings("unchecked") - @Test - public void testDemoDedupePotentialMatchAbisResponseNotProcessed() throws Exception { - List abisResponseDtos = new ArrayList<>(); - AbisResponseDto abisResponseDto = new AbisResponseDto(); - abisResponseDto.setId("100"); - abisResponseDto.setStatusCode("ERROR"); - abisResponseDto.setLangCode("eng"); - abisResponseDtos.add(abisResponseDto); - - byte[] b = "sds".getBytes(); - - PowerMockito.mockStatic(JsonUtil.class); - PowerMockito.mockStatic(IOUtils.class); - PowerMockito.when(JsonUtil.class, "inputStreamtoJavaObject", inputStream, PacketMetaInfo.class) - .thenReturn(packetMetaInfo); - PowerMockito.when(IOUtils.class, "toByteArray", inputStream).thenReturn(b); - Mockito.when(registrationStatusService.getRegistrationStatus(any())).thenReturn(registrationStatusDto); - Mockito.when(abisHandlerUtil.getPacketStatus(any())).thenReturn(AbisConstant.POST_ABIS_IDENTIFICATION); - Mockito.when(demoDedupe.performDedupe(anyString())).thenReturn(duplicateDtos); - registrationStatusDto.setRegistrationType(RegistrationType.NEW.toString()); - Mockito.when(registrationStatusDao.findById(any())).thenReturn(entity); - Mockito.when(packetInfoManager.getAbisResponseRecords(anyString(), anyString())).thenReturn(abisResponseDtos); - Mockito.when(utility.getApplicantAge(anyString(),anyString(), any())).thenReturn(20); - MessageDTO messageDto = demodedupeProcessor.process(dto, stageName); - - assertFalse(messageDto.getIsValid()); - - } - - /** - * Test demo dedupe failure. - * - * @throws ApisResourceAccessException the apis resource access - * exception - * @throws IOException Signals that an I/O exception - * has occurred. - * @throws IntrospectionException - * @throws ParseException - * @throws InvocationTargetException - * @throws IllegalArgumentException - * @throws IllegalAccessException - * @throws io.mosip.kernel.core.exception.IOException - * @throws RegistrationProcessorCheckedException - */ - @SuppressWarnings("unchecked") - @Test - public void testDemoDedupeFailure() throws ApisResourceAccessException, IOException, JsonProcessingException, PacketManagerException, PacketManagerException { - InternalRegistrationStatusDto registrationStatusDto = new InternalRegistrationStatusDto(); - - Mockito.when(demoDedupe.performDedupe(anyString())).thenReturn(duplicateDtos); - Mockito.when(abisHandlerUtil.getPacketStatus(any())).thenReturn(RegistrationType.NEW.toString()); - Mockito.when(registrationStatusService.getRegistrationStatus(anyString())).thenReturn(registrationStatusDto); - registrationStatusDto.setRetryCount(3); - Mockito.when(utility.getApplicantAge(anyString(),anyString(), any())).thenReturn(20); - demodedupeProcessor.process(dto, stageName); - - } - - /** - * Test resource exception. - * - * @throws ApisResourceAccessException the apis resource access - * exception - * @throws IOException Signals that an I/O exception - * has occurred. - * @throws IntrospectionException - * @throws ParseException - * @throws InvocationTargetException - * @throws IllegalArgumentException - * @throws IllegalAccessException - * @throws io.mosip.kernel.core.exception.IOException - * @throws RegistrationProcessorCheckedException - */ - @SuppressWarnings("unchecked") - @Test - public void testResourceException() throws ApisResourceAccessException, IOException, JsonProcessingException, PacketManagerException { - when(env.getProperty(DEMODEDUPEENABLE)).thenReturn("true"); - - List emptyDuplicateDtoSet = new ArrayList<>(); - when(utility.getDefaultSource(any(),any())).thenReturn(source); - Mockito.when(utility.getApplicantAge(anyString(),anyString(), any())).thenReturn(20); - - Mockito.when(registrationStatusService.getRegistrationStatus(any())).thenReturn(registrationStatusDto); - Mockito.when(abisHandlerUtil.getPacketStatus(any())).thenReturn(AbisConstant.PRE_ABIS_IDENTIFICATION); - Mockito.when(demoDedupe.performDedupe(anyString())).thenReturn(emptyDuplicateDtoSet); - when(utility.getDefaultSource(any(), any())).thenReturn(source); - ApisResourceAccessException exp = new ApisResourceAccessException("errorMessage"); - Mockito.doThrow(exp).when(utility).getApplicantAge(anyString(),anyString(), any()); - - - MessageDTO messageDto = demodedupeProcessor.process(dto, stageName); - assertEquals(true, messageDto.getInternalError()); - } - - @Test - public void testFSAdapterExceptionException() - throws ApisResourceAccessException, IOException, JsonProcessingException, PacketManagerException { - Mockito.when(demoDedupe.performDedupe(anyString())).thenReturn(duplicateDtos); - - FSAdapterException exp = new FSAdapterException("errorMessage", "test"); - Mockito.doThrow(exp).when(abisHandlerUtil).getPacketStatus(any()); - registrationStatusDto.setRegistrationType(RegistrationType.NEW.toString()); - Mockito.when(registrationStatusService.getRegistrationStatus(anyString())).thenReturn(registrationStatusDto); - Mockito.when(utility.getApplicantAge(anyString(),anyString(), any())).thenReturn(20); - MessageDTO messageDto = demodedupeProcessor.process(dto, stageName); - assertEquals(true, messageDto.getInternalError()); - } - - @Test - public void testIllegalArgumentException() throws ApisResourceAccessException, IOException, JsonProcessingException, PacketManagerException { - Mockito.when(demoDedupe.performDedupe(anyString())).thenReturn(duplicateDtos); - IllegalArgumentException exp = new IllegalArgumentException("errorMessage"); - Mockito.doThrow(exp).when(abisHandlerUtil).getPacketStatus(any()); - registrationStatusDto.setRegistrationType(RegistrationType.NEW.toString()); - Mockito.when(registrationStatusService.getRegistrationStatus(anyString())).thenReturn(registrationStatusDto); - Mockito.when(utility.getApplicantAge(anyString(),anyString(), any())).thenReturn(20); - MessageDTO messageDto = demodedupeProcessor.process(dto, stageName); - assertEquals(true, messageDto.getInternalError()); - } - - /** - * Test demo dedupe success. - * - * @throws Exception - */ - @Test - public void testDemoDedupeNewPacketSkipped() throws Exception { - when(env.getProperty(DEMODEDUPEENABLE)).thenReturn("false"); - byte[] b = "sds".getBytes(); - - - PowerMockito.mockStatic(JsonUtil.class); - PowerMockito.mockStatic(IOUtils.class); - PowerMockito.when(JsonUtil.class, "inputStreamtoJavaObject", inputStream, PacketMetaInfo.class) - .thenReturn(packetMetaInfo); - PowerMockito.when(IOUtils.class, "toByteArray", inputStream).thenReturn(b); - Mockito.when(registrationStatusService.getRegistrationStatus(any())).thenReturn(registrationStatusDto); - Mockito.when(abisHandlerUtil.getPacketStatus(any())).thenReturn(AbisConstant.PRE_ABIS_IDENTIFICATION); - Mockito.when(utility.getApplicantAge(anyString(),anyString(), any())).thenReturn(20); - MessageDTO messageDto = demodedupeProcessor.process(dto, stageName); - assertTrue(messageDto.getIsValid()); - - } - /** - * Test demo dedupe success. - * - * @throws Exception - */ - @Test - public void testDemoDedupeNewPacketSuccessWithDuplicates() throws Exception { - when(env.getProperty(DEMODEDUPEENABLE)).thenReturn("true"); - byte[] b = "sds".getBytes(); - - - PowerMockito.mockStatic(JsonUtil.class); - PowerMockito.mockStatic(IOUtils.class); - PowerMockito.when(JsonUtil.class, "inputStreamtoJavaObject", inputStream, PacketMetaInfo.class) - .thenReturn(packetMetaInfo); - PowerMockito.when(IOUtils.class, "toByteArray", inputStream).thenReturn(b); - Mockito.when(registrationStatusService.getRegistrationStatus(any())).thenReturn(registrationStatusDto); - Mockito.when(abisHandlerUtil.getPacketStatus(any())).thenReturn(AbisConstant.PRE_ABIS_IDENTIFICATION); - Mockito.when(demoDedupe.performDedupe(anyString())).thenReturn(duplicateDtos); - Mockito.when(utility.getApplicantAge(anyString(),anyString(), any())).thenReturn(20); - MessageDTO messageDto = demodedupeProcessor.process(dto, stageName); - assertFalse(messageDto.getIsValid()); - - } - /** - * Test demo dedupe success. - * - * @throws Exception - */ - @Test - public void testDemoDedupeNewPacketSuccessWithDuplicatesWithException() throws Exception { - when(env.getProperty(DEMODEDUPEENABLE)).thenReturn("true"); - byte[] b = "sds".getBytes(); - - - PowerMockito.mockStatic(JsonUtil.class); - PowerMockito.mockStatic(IOUtils.class); - PowerMockito.when(JsonUtil.class, "inputStreamtoJavaObject", inputStream, PacketMetaInfo.class) - .thenReturn(packetMetaInfo); - PowerMockito.when(IOUtils.class, "toByteArray", inputStream).thenReturn(b); - Mockito.when(registrationStatusService.getRegistrationStatus(any())).thenReturn(registrationStatusDto); - Mockito.when(abisHandlerUtil.getPacketStatus(any())).thenReturn(AbisConstant.PRE_ABIS_IDENTIFICATION); - Mockito.when(demoDedupe.performDedupe(anyString())).thenReturn(duplicateDtos); - NullPointerException exp=new NullPointerException(); - Mockito.doThrow(exp).when(packetInfoManager).saveDemoDedupePotentialData(any(),anyString(),anyString()); - Mockito.when(utility.getApplicantAge(anyString(),anyString(), any())).thenReturn(20); - MessageDTO messageDto = demodedupeProcessor.process(dto, stageName); - assertFalse(messageDto.getIsValid()); - - } - - @Test - public void testDemoDedupeNewChildPacketSuccess() throws Exception { - when(env.getProperty(DEMODEDUPEENABLE)).thenReturn("true"); - byte[] b = "sds".getBytes(); - List emptyDuplicateDtoSet = new ArrayList<>(); - Mockito.when(utility.getApplicantAge(anyString(),anyString(), any())).thenReturn(2); - PowerMockito.mockStatic(JsonUtil.class); - PowerMockito.mockStatic(IOUtils.class); - PowerMockito.when(JsonUtil.class, "inputStreamtoJavaObject", inputStream, PacketMetaInfo.class) - .thenReturn(packetMetaInfo); - PowerMockito.when(IOUtils.class, "toByteArray", inputStream).thenReturn(b); - Mockito.when(registrationStatusService.getRegistrationStatus(any())).thenReturn(registrationStatusDto); - Mockito.when(abisHandlerUtil.getPacketStatus(any())).thenReturn(AbisConstant.PRE_ABIS_IDENTIFICATION); - Mockito.when(demoDedupe.performDedupe(anyString())).thenReturn(emptyDuplicateDtoSet); - - MessageDTO messageDto = demodedupeProcessor.process(dto, stageName); - assertTrue(messageDto.getIsValid()); - - } - - @Test - public void testDemoDedupeDisabledSuccess() throws Exception { - when(env.getProperty(DEMODEDUPEENABLE)).thenReturn("false"); - byte[] b = "sds".getBytes(); - List emptyDuplicateDtoSet = new ArrayList<>(); - Mockito.when(utility.getApplicantAge(any(),any(), any())).thenReturn(20); - PowerMockito.mockStatic(JsonUtil.class); - PowerMockito.mockStatic(IOUtils.class); - PowerMockito.when(JsonUtil.class, "inputStreamtoJavaObject", inputStream, PacketMetaInfo.class) - .thenReturn(packetMetaInfo); - PowerMockito.when(IOUtils.class, "toByteArray", inputStream).thenReturn(b); - Mockito.when(registrationStatusService.getRegistrationStatus(any())).thenReturn(registrationStatusDto); - Mockito.when(abisHandlerUtil.getPacketStatus(any())).thenReturn(AbisConstant.PRE_ABIS_IDENTIFICATION); - Mockito.when(demoDedupe.performDedupe(anyString())).thenReturn(emptyDuplicateDtoSet); - - MessageDTO messageDto = demodedupeProcessor.process(dto, stageName); - assertTrue(messageDto.getIsValid()); - - } - - @Test - public void testDemoDedupeSuccess() throws Exception { - when(env.getProperty(DEMODEDUPEENABLE)).thenReturn("true"); - byte[] b = "sds".getBytes(); - List emptyDuplicateDtoSet = new ArrayList<>(); - Mockito.when(utility.getApplicantAge(any(), any(), any())).thenReturn(20); - PowerMockito.mockStatic(JsonUtil.class); - PowerMockito.mockStatic(IOUtils.class); - PowerMockito.when(JsonUtil.class, "inputStreamtoJavaObject", inputStream, PacketMetaInfo.class) - .thenReturn(packetMetaInfo); - PowerMockito.when(IOUtils.class, "toByteArray", inputStream).thenReturn(b); - Mockito.when(registrationStatusService.getRegistrationStatus(any())).thenReturn(registrationStatusDto); - Mockito.when(abisHandlerUtil.getPacketStatus(any())).thenReturn(AbisConstant.PRE_ABIS_IDENTIFICATION); - Mockito.when(demoDedupe.performDedupe(anyString())).thenReturn(emptyDuplicateDtoSet); - - MessageDTO messageDto = demodedupeProcessor.process(dto, stageName); - assertTrue(messageDto.getIsValid()); - - } - @Test - public void testDemoDedupeNewDuplicatePacketSuccess() throws Exception { - when(env.getProperty(DEMODEDUPEENABLE)).thenReturn("true"); - - Mockito.when(registrationStatusService.getRegistrationStatus(any())).thenReturn(registrationStatusDto); - Mockito.when(abisHandlerUtil.getPacketStatus(any())).thenReturn(AbisConstant.DUPLICATE_FOR_SAME_TRANSACTION_ID); - - MessageDTO messageDto = demodedupeProcessor.process(dto, stageName); - assertTrue(messageDto.getInternalError()); - - } - +package io.mosip.registrationprocessor.stages.demodedupe; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyList; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.when; + +import java.beans.IntrospectionException; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.lang.reflect.InvocationTargetException; +import java.text.ParseException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.apache.commons.io.IOUtils; +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.springframework.core.env.Environment; +import org.springframework.test.util.ReflectionTestUtils; + +import com.fasterxml.jackson.databind.ObjectMapper; + +import io.mosip.kernel.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.fsadapter.exception.FSAdapterException; +import io.mosip.kernel.core.util.HMACUtils2; +import io.mosip.kernel.core.util.exception.JsonProcessingException; +import io.mosip.registration.processor.core.abstractverticle.MessageBusAddress; +import io.mosip.registration.processor.core.abstractverticle.MessageDTO; +import io.mosip.registration.processor.core.code.AbisStatusCode; +import io.mosip.registration.processor.core.code.ApiName; +import io.mosip.registration.processor.core.code.EventId; +import io.mosip.registration.processor.core.code.EventName; +import io.mosip.registration.processor.core.code.EventType; +import io.mosip.registration.processor.core.code.RegistrationTransactionStatusCode; +import io.mosip.registration.processor.core.constant.AbisConstant; +import io.mosip.registration.processor.core.constant.MappingJsonConstants; +import io.mosip.registration.processor.core.constant.PacketFiles; +import io.mosip.registration.processor.core.exception.ApisResourceAccessException; +import io.mosip.registration.processor.core.exception.BiometricRecordValidationException; +import io.mosip.registration.processor.core.exception.PacketManagerException; +import io.mosip.registration.processor.core.exception.RegistrationProcessorCheckedException; +import io.mosip.registration.processor.core.http.ResponseWrapper; +import io.mosip.registration.processor.core.logger.LogDescription; +import io.mosip.registration.processor.core.packet.dto.FieldValue; +import io.mosip.registration.processor.core.packet.dto.FieldValueArray; +import io.mosip.registration.processor.core.packet.dto.Identity; +import io.mosip.registration.processor.core.packet.dto.PacketMetaInfo; +import io.mosip.registration.processor.core.packet.dto.abis.AbisResponseDetDto; +import io.mosip.registration.processor.core.packet.dto.abis.AbisResponseDto; +import io.mosip.registration.processor.core.packet.dto.demographicinfo.DemographicInfoDto; +import io.mosip.registration.processor.core.packet.dto.demographicinfo.IndividualDemographicDedupe; +import io.mosip.registration.processor.core.packet.dto.demographicinfo.JsonValue; +import io.mosip.registration.processor.core.packet.dto.demographicinfo.identify.IdentityJsonValues; +import io.mosip.registration.processor.core.packet.dto.idjson.Document; +import io.mosip.registration.processor.core.spi.packetmanager.PacketInfoManager; +import io.mosip.registration.processor.core.util.JsonUtil; +import io.mosip.registration.processor.core.util.RegistrationExceptionMapperUtil; +import io.mosip.registration.processor.packet.storage.dto.ApplicantInfoDto; +import io.mosip.registration.processor.packet.storage.entity.IndividualDemographicDedupeEntity; +import io.mosip.registration.processor.packet.storage.entity.ManualVerificationEntity; +import io.mosip.registration.processor.packet.storage.repository.BasePacketRepository; +import io.mosip.registration.processor.packet.storage.utils.ABISHandlerUtil; +import io.mosip.registration.processor.packet.storage.utils.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.demodedupe.DemoDedupe; +import io.mosip.registration.processor.stages.demodedupe.DemodedupeProcessor; +import io.mosip.registration.processor.status.code.RegistrationStatusCode; +import io.mosip.registration.processor.status.code.RegistrationType; +import io.mosip.registration.processor.status.dao.RegistrationStatusDao; +import io.mosip.registration.processor.status.dto.InternalRegistrationStatusDto; +import io.mosip.registration.processor.status.dto.RegistrationStatusDto; +import io.mosip.registration.processor.status.entity.RegistrationStatusEntity; +import io.mosip.registration.processor.status.service.RegistrationStatusService; + +/** + * The Class DemodedupeStageTest. + */ +@RunWith(PowerMockRunner.class) +@PowerMockIgnore({ "javax.management.*", "javax.net.ssl.*","com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", }) +@PrepareForTest({ JsonUtil.class, IOUtils.class, HMACUtils2.class }) +public class DemodedupeProcessorTest { + + /** The registration status service. */ + @Mock + private RegistrationStatusService registrationStatusService; + + @Mock + private PacketInfoManager packetInfoManager; + + /** The manual verfication repository. */ + @Mock + private BasePacketRepository manualVerficationRepository; + + /** The demographic dedupe repository. */ + @Mock + private BasePacketRepository demographicDedupeRepository; + + /** The demo dedupe. */ + @Mock + private DemoDedupe demoDedupe; + + @Mock + private InputStream inputStream; + + private static final String source = "reg_client"; + + + + /** The dto. */ + private MessageDTO dto = new MessageDTO(); + + /** The duplicate dtos. */ + private List duplicateDtos = new ArrayList<>(); + + /** The audit log request builder. */ + @Mock + private AuditLogRequestBuilder auditLogRequestBuilder; + + @Mock + RegistrationExceptionMapperUtil registrationStatusMapperUtil; + + @InjectMocks + private DemodedupeProcessor demodedupeProcessor; + + @Mock + private ABISHandlerUtil abisHandlerUtil; + + @Mock + private RegistrationStatusDao registrationStatusDao; + + @Mock + private Utilities utility; + + private InternalRegistrationStatusDto registrationStatusDto; + + private InternalRegistrationStatusDto registrationStatusDto1; + + private InternalRegistrationStatusDto registrationStatusDto2; + + private Identity identity = new Identity(); + + private PacketMetaInfo packetMetaInfo; + + RegistrationStatusEntity entity = new RegistrationStatusEntity(); + + private String stageName = "DemoDedupeStage"; + + private IndividualDemographicDedupe individualDemoDedupe; + + @Mock + LogDescription description; + + @Mock + private Environment env; + + private static final String DEMODEDUPEENABLE = "mosip.registration.processor.demographic.deduplication.enable"; + + + @Mock + private PriorityBasedPacketManagerService packetManagerService; + + /** + * Sets the up. + * + * @throws Exception + * the exception + */ + @Before + public void setUp() throws Exception { + when(utility.getDefaultSource(any(), any())).thenReturn(source); + ReflectionTestUtils.setField(demodedupeProcessor, "infantDedupe", "Y"); + ReflectionTestUtils.setField(demodedupeProcessor, "ageLimit", "4"); + ReflectionTestUtils.setField(demodedupeProcessor, "demodedupeInvalidBiometricAction", "RedirectToManualVerification"); + ReflectionTestUtils.setField(demodedupeProcessor, "demodedupeInfantInvalidBiometricAction", "RedirectToManualVerification"); + dto.setRid("2018701130000410092018110735"); + + MockitoAnnotations.initMocks(this); + + DemographicInfoDto dto1 = new DemographicInfoDto(); + DemographicInfoDto dto2 = new DemographicInfoDto(); + dto1.setRegId("2018701130000410092018110731"); + dto2.setRegId("2018701130000410092018110732"); + duplicateDtos.add(dto1); + duplicateDtos.add(dto2); + + registrationStatusDto = new InternalRegistrationStatusDto(); + registrationStatusDto.setRegistrationType("NEW"); + registrationStatusDto.setRegistrationId("2018701130000410092018110735"); + + registrationStatusDto1 = new InternalRegistrationStatusDto(); + registrationStatusDto1.setRegistrationType("NEW"); + registrationStatusDto1.setRegistrationId("2018701130000410092018110732"); + registrationStatusDto1.setLatestTransactionStatusCode(RegistrationTransactionStatusCode.IN_PROGRESS.toString()); + registrationStatusDto1.setStatusCode("PROCESSING"); + registrationStatusDto2 = new InternalRegistrationStatusDto(); + registrationStatusDto2.setRegistrationType("NEW"); + registrationStatusDto2.setRegistrationId("2018701130000410092018110731"); + registrationStatusDto2.setLatestTransactionStatusCode(RegistrationTransactionStatusCode.REJECTED.toString()); + registrationStatusDto2.setStatusCode("REJECTED"); + packetMetaInfo = new PacketMetaInfo(); + + FieldValue registrationType = new FieldValue(); + registrationType.setLabel("registrationType"); + registrationType.setValue("New"); + + FieldValue applicantType = new FieldValue(); + applicantType.setLabel("applicantType"); + applicantType.setValue("Child"); + + FieldValue isVerified = new FieldValue(); + isVerified.setLabel("isVerified"); + isVerified.setValue("Verified"); + + FieldValue preRegistrationId = new FieldValue(); + preRegistrationId.setLabel("preRegistrationId"); + preRegistrationId.setValue("2018701130000410092018110736"); + + entity.setLatestRegistrationTransactionId("5d936385-7ee6-4b51-b21f-c20b0cfbcc11"); + + identity.setMetaData(Arrays.asList(registrationType, applicantType, isVerified, preRegistrationId)); + + Document documentPob = new Document(); + documentPob.setDocumentCategory("PROOFOFDATEOFBIRTH"); + documentPob.setDocumentName("ProofOfBirth"); + Document document = new Document(); + document.setDocumentCategory("PROOFOFRELATIONSHIP"); + document.setDocumentName("ProofOfRelation"); + List documents = new ArrayList(); + documents.add(documentPob); + documents.add(document); + individualDemoDedupe = new IndividualDemographicDedupe(); + + JsonValue[] jsonArray = new JsonValue[1]; + JsonValue[] jsonArray1 = new JsonValue[1]; + + JsonValue jsonValue1 = new JsonValue(); + JsonValue jsonValue2 = new JsonValue(); + + jsonValue1.setLanguage("eng"); + jsonValue1.setValue("name"); + jsonArray[0] = jsonValue1; + + jsonValue2.setLanguage("eng"); + jsonValue2.setValue("gender"); + jsonArray1[0] = jsonValue2; + List jsonArrayList = new ArrayList<>(); + jsonArrayList.add(jsonArray); + + individualDemoDedupe.setName(jsonArrayList); + individualDemoDedupe.setDateOfBirth("dateOfBirth"); + individualDemoDedupe.setPhone("phone"); + individualDemoDedupe.setEmail("email"); + individualDemoDedupe.setGender(jsonArray1); + List fieldValueArrayList = new ArrayList(); + + FieldValueArray applicantBiometric = new FieldValueArray(); + applicantBiometric.setLabel(PacketFiles.APPLICANTBIOMETRICSEQUENCE.name()); + List applicantBiometricValues = new ArrayList(); + applicantBiometricValues.add(PacketFiles.BOTHTHUMBS.name()); + applicantBiometric.setValue(applicantBiometricValues); + fieldValueArrayList.add(applicantBiometric); + FieldValueArray introducerBiometric = new FieldValueArray(); + introducerBiometric.setLabel(PacketFiles.INTRODUCERBIOMETRICSEQUENCE.name()); + List introducerBiometricValues = new ArrayList(); + introducerBiometricValues.add("introducerLeftThumb"); + introducerBiometric.setValue(introducerBiometricValues); + fieldValueArrayList.add(introducerBiometric); + FieldValueArray applicantDemographic = new FieldValueArray(); + applicantDemographic.setLabel(PacketFiles.APPLICANTDEMOGRAPHICSEQUENCE.name()); + List applicantDemographicValues = new ArrayList(); + applicantDemographicValues.add(PacketFiles.APPLICANTPHOTO.name()); + applicantDemographicValues.add("ProofOfBirth"); + applicantDemographicValues.add("ProofOfRelation"); + applicantDemographicValues.add("ProofOfAddress"); + applicantDemographicValues.add("ProofOfIdentity"); + applicantDemographic.setValue(applicantDemographicValues); + fieldValueArrayList.add(applicantDemographic); + identity.setHashSequence(fieldValueArrayList); + List sequence2 = new ArrayList<>(); + sequence2.add("audit"); + List fieldValueArrayListSequence = new ArrayList(); + FieldValueArray hashsequence2 = new FieldValueArray(); + hashsequence2.setValue(sequence2); + fieldValueArrayListSequence.add(hashsequence2); + identity.setHashSequence2(fieldValueArrayListSequence); + packetMetaInfo.setIdentity(identity); + + Mockito.when(registrationStatusMapperUtil.getStatusCode(any())).thenReturn("ERROR"); + + AuditResponseDto auditResponseDto = new AuditResponseDto(); + ResponseWrapper responseWrapper = new ResponseWrapper<>(); + responseWrapper.setResponse(auditResponseDto); + Mockito.doReturn(responseWrapper).when(auditLogRequestBuilder).createAuditRequestBuilder( + "test case description", EventId.RPR_405.toString(), EventName.UPDATE.toString(), + EventType.BUSINESS.toString(), "1234testcase", ApiName.AUDIT); + Mockito.doNothing().when(description).setMessage(any()); + InternalRegistrationStatusDto registrationStatusDto = new InternalRegistrationStatusDto(); + + registrationStatusDto.setRetryCount(null); + Mockito.when(registrationStatusService.getRegistrationStatus(anyString())).thenReturn(registrationStatusDto); + Mockito.doNothing().when(registrationStatusService).updateRegistrationStatus(any(), any(), any()); + ClassLoader classLoader = getClass().getClassLoader(); + File file = new File(classLoader.getResource("RegistrationProcessorIdentity.json").getFile()); + inputStream = new FileInputStream(file); + String mappingJsonString = IOUtils.toString(inputStream,"UTF-8"); + JSONObject mappingJsonObj= new ObjectMapper().readValue(mappingJsonString, JSONObject.class); + + Mockito.when(utility.getRegistrationProcessorMappingJson(anyString())).thenReturn(JsonUtil.getJSONObject(mappingJsonObj, MappingJsonConstants.IDENTITY)); + 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)); + } + + /** + * Test demo dedupe success. + * + * @throws Exception + */ + @Test + public void testDemoDedupeNewPacketSuccess() throws Exception { + when(env.getProperty(DEMODEDUPEENABLE)).thenReturn("true"); + byte[] b = "sds".getBytes(); + List emptyDuplicateDtoSet = new ArrayList<>(); + Mockito.when(utility.getApplicantAge(anyString(),anyString(), any())).thenReturn(20); + PowerMockito.mockStatic(JsonUtil.class); + PowerMockito.mockStatic(IOUtils.class); + PowerMockito.when(JsonUtil.class, "inputStreamtoJavaObject", inputStream, PacketMetaInfo.class) + .thenReturn(packetMetaInfo); + PowerMockito.when(IOUtils.class, "toByteArray", inputStream).thenReturn(b); + Mockito.when(registrationStatusService.getRegistrationStatus(any())).thenReturn(registrationStatusDto); + Mockito.when(abisHandlerUtil.getPacketStatus(any())).thenReturn(AbisConstant.PRE_ABIS_IDENTIFICATION); + Mockito.when(demoDedupe.performDedupe(anyString())).thenReturn(emptyDuplicateDtoSet); + + MessageDTO messageDto = demodedupeProcessor.process(dto, stageName); + assertTrue(messageDto.getIsValid()); + ArgumentCaptor argument = ArgumentCaptor + .forClass(InternalRegistrationStatusDto.class); + Mockito.verify(registrationStatusService,Mockito.atLeastOnce()).updateRegistrationStatus(argument.capture(),any(),any()); + assertEquals(RegistrationTransactionStatusCode.SUCCESS.toString(), argument.getAllValues().get(0).getLatestTransactionStatusCode()); + assertEquals(RegistrationStatusCode.PROCESSING.toString(), argument.getAllValues().get(0).getStatusCode()); + + } + + @SuppressWarnings("unchecked") + @Test + public void testDemoDedupeUpdatePacketSuccess() throws Exception { + InternalRegistrationStatusDto registrationStatus = new InternalRegistrationStatusDto(); + registrationStatus.setRegistrationId("2018701130000410092018110736"); + registrationStatus.setRegistrationType(RegistrationType.UPDATE.name()); + + IdentityJsonValues identityJsonValues = new IdentityJsonValues(); + identityJsonValues.setValue("fullName"); + when(utility.getDefaultSource(any(), any())).thenReturn(source); + Mockito.when(utility.getUIn(anyString(), anyString(), any())).thenReturn("2345"); + + JSONArray arr = new JSONArray(); + arr.add("name"); + + JSONObject obj = new JSONObject(); + obj.put("fullName", arr); + Mockito.when(utility.retrieveIdrepoJson(anyString())).thenReturn(obj); + + byte[] b = "sds".getBytes(); + List emptyDuplicateDtoSet = new ArrayList<>(); + + PowerMockito.mockStatic(JsonUtil.class); + PowerMockito.mockStatic(IOUtils.class); + PowerMockito.when(JsonUtil.class, "inputStreamtoJavaObject", inputStream, PacketMetaInfo.class) + .thenReturn(packetMetaInfo); + PowerMockito.when(IOUtils.class, "toByteArray", inputStream).thenReturn(b); + Mockito.when(registrationStatusService.getRegistrationStatus(any())).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()); + ArgumentCaptor argument = ArgumentCaptor + .forClass(InternalRegistrationStatusDto.class); + Mockito.verify(registrationStatusService, Mockito.atLeastOnce()).updateRegistrationStatus(argument.capture(), + any(), any()); + assertEquals(RegistrationTransactionStatusCode.SUCCESS.toString(), + argument.getAllValues().get(0).getLatestTransactionStatusCode()); + assertEquals(RegistrationStatusCode.PROCESSING.toString(), argument.getAllValues().get(0).getStatusCode()); + + } + + @Test + public void testDemoDedupeUpdatePacketException() throws Exception { + InternalRegistrationStatusDto registrationStatus = new InternalRegistrationStatusDto(); + registrationStatus.setRegistrationId("2018701130000410092018110736"); + registrationStatus.setRegistrationType(RegistrationType.UPDATE.name()); + + IdentityJsonValues identityJsonValues = new IdentityJsonValues(); + identityJsonValues.setValue("fullName"); + when(utility.getDefaultSource(any(),any())).thenReturn(source); + Mockito.when(utility.getUIn(anyString(), anyString(), any())).thenReturn("2345"); + + Mockito.when(utility.retrieveIdrepoJson(any())).thenReturn(null); + + byte[] b = "sds".getBytes(); + List emptyDuplicateDtoSet = new ArrayList<>(); + + PowerMockito.mockStatic(JsonUtil.class); + PowerMockito.mockStatic(IOUtils.class); + PowerMockito.when(JsonUtil.class, "inputStreamtoJavaObject", inputStream, PacketMetaInfo.class) + .thenReturn(packetMetaInfo); + PowerMockito.when(IOUtils.class, "toByteArray", inputStream).thenReturn(b); + Mockito.when(registrationStatusService.getRegistrationStatus(any())).thenReturn(registrationStatus); + Mockito.when(demoDedupe.performDedupe(anyString())).thenReturn(emptyDuplicateDtoSet); + Mockito.when(packetInfoManager.getIdentityKeysAndFetchValuesFromJSON(any(),any(),any())).thenReturn(individualDemoDedupe); + MessageDTO messageDto = demodedupeProcessor.process(dto, stageName); + assertFalse(messageDto.getIsValid()); + ArgumentCaptor argument = ArgumentCaptor + .forClass(InternalRegistrationStatusDto.class); + Mockito.verify(registrationStatusService, Mockito.atLeastOnce()).updateRegistrationStatus(argument.capture(), + any(), any()); + assertEquals(RegistrationTransactionStatusCode.ERROR.toString(), + argument.getAllValues().get(0).getLatestTransactionStatusCode()); + assertEquals(RegistrationStatusCode.FAILED.toString(), argument.getAllValues().get(0).getStatusCode()); + } + + @SuppressWarnings("unchecked") + @Test + public void testDemoDedupeResUpdatePacketSuccess() throws Exception { + InternalRegistrationStatusDto registrationStatus = new InternalRegistrationStatusDto(); + registrationStatus.setRegistrationId("2018701130000410092018110736"); + registrationStatus.setRegistrationType(RegistrationType.RES_UPDATE.name()); + + IdentityJsonValues identityJsonValues = new IdentityJsonValues(); + identityJsonValues.setValue("fullName"); + when(utility.getDefaultSource(any(),any())).thenReturn(source); + Mockito.when(utility.getUIn(anyString(), anyString(), any())).thenReturn("2345"); + + JSONArray arr = new JSONArray(); + arr.add("name"); + + JSONObject obj = new JSONObject(); + obj.put("fullName", arr); + Mockito.when(utility.retrieveIdrepoJson(anyString())).thenReturn(obj); + + byte[] b = "sds".getBytes(); + List emptyDuplicateDtoSet = new ArrayList<>(); + + PowerMockito.mockStatic(JsonUtil.class); + PowerMockito.mockStatic(IOUtils.class); + PowerMockito.when(JsonUtil.getJSONValue(any(), any())).thenReturn("Test1,Test2"); + PowerMockito.when(JsonUtil.getJSONObject(any(), any())).thenReturn(obj); + JsonValue[] nameArray = new JsonValue[1]; + JsonValue jsonValue = new JsonValue(); + jsonValue.setLanguage("eng"); + jsonValue.setValue("test"); + nameArray[0] = jsonValue; + PowerMockito.when(JsonUtil.getJsonValues(any(),any())).thenReturn(nameArray); + PowerMockito.when(JsonUtil.class, "inputStreamtoJavaObject", inputStream, PacketMetaInfo.class) + .thenReturn(packetMetaInfo); + PowerMockito.when(IOUtils.class, "toByteArray", inputStream).thenReturn(b); + Mockito.when(registrationStatusService.getRegistrationStatus(any())).thenReturn(registrationStatus); + Mockito.when(demoDedupe.performDedupe(anyString())).thenReturn(emptyDuplicateDtoSet); + IndividualDemographicDedupe demographicData = individualDemoDedupe; + demographicData.setName(null); + demographicData.setDateOfBirth(null); + demographicData.setGender(null); + demographicData.setPhone(null); + demographicData.setEmail(null); + Mockito.when(packetInfoManager.getIdentityKeysAndFetchValuesFromJSON(any(),any(), any())).thenReturn(demographicData); + Mockito.when(abisHandlerUtil.getPacketStatus(any())).thenReturn(AbisConstant.POST_ABIS_IDENTIFICATION); + MessageDTO messageDto = demodedupeProcessor.process(dto, stageName); + assertTrue(messageDto.getIsValid()); + ArgumentCaptor argument = ArgumentCaptor + .forClass(InternalRegistrationStatusDto.class); + Mockito.verify(registrationStatusService, Mockito.atLeastOnce()).updateRegistrationStatus(argument.capture(), + any(), any()); + assertEquals(RegistrationTransactionStatusCode.SUCCESS.toString(), + argument.getAllValues().get(0).getLatestTransactionStatusCode()); + assertEquals(RegistrationStatusCode.PROCESSING.toString(), argument.getAllValues().get(0).getStatusCode()); + } + + @SuppressWarnings("unchecked") + @Test + public void testDemoDedupeSuccessNotDuplicateAfterAuth() throws Exception { + when(env.getProperty(DEMODEDUPEENABLE)).thenReturn("true"); + byte[] b = "sds".getBytes(); + Mockito.when(utility.getApplicantAge(anyString(),anyString(), any())).thenReturn(20); + PowerMockito.mockStatic(JsonUtil.class); + PowerMockito.mockStatic(IOUtils.class); + PowerMockito.when(JsonUtil.class, "inputStreamtoJavaObject", inputStream, PacketMetaInfo.class) + .thenReturn(packetMetaInfo); + PowerMockito.when(IOUtils.class, "toByteArray", inputStream).thenReturn(b); + Mockito.when(registrationStatusService.getRegistrationStatus(any())).thenReturn(registrationStatusDto); + Mockito.when(abisHandlerUtil.getPacketStatus(any())).thenReturn(AbisConstant.PRE_ABIS_IDENTIFICATION); + Mockito.when(demoDedupe.performDedupe(anyString())).thenReturn(duplicateDtos); + registrationStatusDto.setRegistrationType(RegistrationType.NEW.toString()); + Mockito.when(registrationStatusDao.findById(any())).thenReturn(entity); + MessageDTO messageDto = demodedupeProcessor.process(dto, stageName); + assertTrue(messageDto.getIsValid()); + ArgumentCaptor argument = ArgumentCaptor + .forClass(InternalRegistrationStatusDto.class); + Mockito.verify(registrationStatusService, Mockito.atLeastOnce()).updateRegistrationStatus(argument.capture(), + any(), any()); + assertEquals(RegistrationTransactionStatusCode.SUCCESS.toString(), + argument.getAllValues().get(0).getLatestTransactionStatusCode()); + assertEquals(RegistrationStatusCode.PROCESSING.toString(), argument.getAllValues().get(0).getStatusCode()); + + } + + /** + * Test demo dedupe potential match. + * + * @throws Exception + */ + @SuppressWarnings("unchecked") + @Test + public void testDemoDedupePotentialMatchWithEmpty() throws Exception { + when(env.getProperty(DEMODEDUPEENABLE)).thenReturn("true"); + List abisResponseDtos = new ArrayList<>(); + AbisResponseDto abisResponseDto = new AbisResponseDto(); + abisResponseDto.setId("100"); + abisResponseDto.setStatusCode(AbisStatusCode.SUCCESS.toString()); + abisResponseDto.setLangCode("eng"); + abisResponseDtos.add(abisResponseDto); + + byte[] b = "sds".getBytes(); + + PowerMockito.mockStatic(JsonUtil.class); + PowerMockito.mockStatic(IOUtils.class); + PowerMockito.when(JsonUtil.class, "inputStreamtoJavaObject", inputStream, PacketMetaInfo.class) + .thenReturn(packetMetaInfo); + PowerMockito.when(IOUtils.class, "toByteArray", inputStream).thenReturn(b); + Mockito.when(registrationStatusService.getRegistrationStatus(any())).thenReturn(registrationStatusDto); + Mockito.when(abisHandlerUtil.getPacketStatus(any())).thenReturn(AbisConstant.POST_ABIS_IDENTIFICATION); + Mockito.when(demoDedupe.performDedupe(anyString())).thenReturn(duplicateDtos); + registrationStatusDto.setRegistrationType(RegistrationType.NEW.toString()); + Mockito.when(registrationStatusDao.findById(any())).thenReturn(entity); + Mockito.when(packetInfoManager.getAbisResponseRecords(anyString(), anyString())).thenReturn(abisResponseDtos); + Mockito.when(utility.getApplicantAge(anyString(),anyString(), any())).thenReturn(20); + MessageDTO messageDto = demodedupeProcessor.process(dto, stageName); + + assertTrue(messageDto.getIsValid()); + ArgumentCaptor argument = ArgumentCaptor + .forClass(InternalRegistrationStatusDto.class); + Mockito.verify(registrationStatusService, Mockito.atLeastOnce()).updateRegistrationStatus(argument.capture(), + any(), any()); + assertEquals(RegistrationTransactionStatusCode.SUCCESS.toString(), + argument.getAllValues().get(0).getLatestTransactionStatusCode()); + assertEquals(RegistrationStatusCode.PROCESSING.toString(), argument.getAllValues().get(0).getStatusCode()); + + } + + @SuppressWarnings("unchecked") + @Test + public void testDemoDedupePotentialMatchSuccess() throws Exception { + List abisResponseDtos = new ArrayList<>(); + List abisResponseDetDtos = new ArrayList<>(); + List matchedRegIds = new ArrayList<>(); + AbisResponseDto abisResponseDto = new AbisResponseDto(); + abisResponseDto.setId("100"); + abisResponseDto.setStatusCode(AbisStatusCode.SUCCESS.toString()); + abisResponseDto.setLangCode("eng"); + abisResponseDtos.add(abisResponseDto); + + AbisResponseDetDto abisResponseDetDto = new AbisResponseDetDto(); + abisResponseDetDto.setAbiRespId("100"); + abisResponseDetDtos.add(abisResponseDetDto); + + matchedRegIds.add("2018701130000410092018110735"); + byte[] b = "sds".getBytes(); + + PowerMockito.mockStatic(JsonUtil.class); + PowerMockito.mockStatic(IOUtils.class); + PowerMockito.when(JsonUtil.class, "inputStreamtoJavaObject", inputStream, PacketMetaInfo.class) + .thenReturn(packetMetaInfo); + PowerMockito.when(IOUtils.class, "toByteArray", inputStream).thenReturn(b); + Mockito.when(registrationStatusService.getRegistrationStatus(any())).thenReturn(registrationStatusDto); + Mockito.when(abisHandlerUtil.getPacketStatus(any())).thenReturn(AbisConstant.POST_ABIS_IDENTIFICATION); + Mockito.when(demoDedupe.performDedupe(anyString())).thenReturn(duplicateDtos); + registrationStatusDto.setRegistrationType(RegistrationType.NEW.toString()); + Mockito.when(registrationStatusDao.findById(any())).thenReturn(entity); + Mockito.when(packetInfoManager.getAbisResponseRecords(anyString(), anyString())).thenReturn(abisResponseDtos); + Mockito.when(packetInfoManager.getAbisResponseDetRecordsList(any())).thenReturn(abisResponseDetDtos); + Mockito.when(abisHandlerUtil.getUniqueRegIds(any(), any(), any())).thenReturn(matchedRegIds); + doNothing().when(packetInfoManager).saveManualAdjudicationData(anyList(), anyString(), any(), any(), any(), + any(), any()); + Mockito.when(utility.getApplicantAge(anyString(),anyString(), any())).thenReturn(20); + MessageDTO messageDto = demodedupeProcessor.process(dto, stageName); + + assertFalse(messageDto.getIsValid()); + assertEquals(MessageBusAddress.MANUAL_VERIFICATION_BUS_IN, messageDto.getMessageBusAddress()); + ArgumentCaptor argument = ArgumentCaptor + .forClass(InternalRegistrationStatusDto.class); + Mockito.verify(registrationStatusService, Mockito.atLeastOnce()).updateRegistrationStatus(argument.capture(), + any(), any()); + assertEquals(RegistrationTransactionStatusCode.FAILED.toString(), + argument.getAllValues().get(0).getLatestTransactionStatusCode()); + assertEquals(RegistrationStatusCode.PROCESSING.toString(), argument.getAllValues().get(0).getStatusCode()); + } + + @Test + public void testDemoDedupeEmptyMatch() throws Exception { + List abisResponseDtos = new ArrayList<>(); + List abisResponseDetDtos = new ArrayList<>(); + List matchedRegIds = new ArrayList<>(); + AbisResponseDto abisResponseDto = new AbisResponseDto(); + abisResponseDto.setId("100"); + abisResponseDto.setStatusCode(AbisStatusCode.SUCCESS.toString()); + abisResponseDto.setLangCode("eng"); + abisResponseDtos.add(abisResponseDto); + + AbisResponseDetDto abisResponseDetDto = new AbisResponseDetDto(); + abisResponseDetDto.setAbiRespId("100"); + abisResponseDetDtos.add(abisResponseDetDto); + + byte[] b = "sds".getBytes(); + + PowerMockito.mockStatic(JsonUtil.class); + PowerMockito.mockStatic(IOUtils.class); + PowerMockito.when(JsonUtil.class, "inputStreamtoJavaObject", inputStream, PacketMetaInfo.class) + .thenReturn(packetMetaInfo); + PowerMockito.when(IOUtils.class, "toByteArray", inputStream).thenReturn(b); + Mockito.when(registrationStatusService.getRegistrationStatus(any())).thenReturn(registrationStatusDto); + Mockito.when(abisHandlerUtil.getPacketStatus(any())).thenReturn(AbisConstant.POST_ABIS_IDENTIFICATION); + Mockito.when(demoDedupe.performDedupe(anyString())).thenReturn(duplicateDtos); + registrationStatusDto.setRegistrationType(RegistrationType.NEW.toString()); + Mockito.when(registrationStatusDao.findById(any())).thenReturn(entity); + Mockito.when(packetInfoManager.getAbisResponseRecords(anyString(), anyString())).thenReturn(abisResponseDtos); + Mockito.when(packetInfoManager.getAbisResponseDetRecordsList(any())).thenReturn(abisResponseDetDtos); + Mockito.when(abisHandlerUtil.getUniqueRegIds(any(), any(), any())).thenReturn(matchedRegIds); + doNothing().when(packetInfoManager).saveManualAdjudicationData(anyList(), anyString(), any(), any(), any(), + any(), any()); + Mockito.when(utility.getApplicantAge(anyString(),anyString(), any())).thenReturn(20); + MessageDTO messageDto = demodedupeProcessor.process(dto, stageName); + + assertTrue(messageDto.getIsValid()); + ArgumentCaptor argument = ArgumentCaptor + .forClass(InternalRegistrationStatusDto.class); + Mockito.verify(registrationStatusService, Mockito.atLeastOnce()).updateRegistrationStatus(argument.capture(), + any(), any()); + assertEquals(RegistrationTransactionStatusCode.SUCCESS.toString(), + argument.getAllValues().get(0).getLatestTransactionStatusCode()); + assertEquals(RegistrationStatusCode.PROCESSING.toString(), argument.getAllValues().get(0).getStatusCode()); + + } + + @SuppressWarnings("unchecked") + @Test + public void testDemoDedupePotentialMatchAbisResponseNotProcessed() throws Exception { + List abisResponseDtos = new ArrayList<>(); + AbisResponseDto abisResponseDto = new AbisResponseDto(); + abisResponseDto.setId("100"); + abisResponseDto.setStatusCode("ERROR"); + abisResponseDto.setLangCode("eng"); + abisResponseDtos.add(abisResponseDto); + + byte[] b = "sds".getBytes(); + + PowerMockito.mockStatic(JsonUtil.class); + PowerMockito.mockStatic(IOUtils.class); + PowerMockito.when(JsonUtil.class, "inputStreamtoJavaObject", inputStream, PacketMetaInfo.class) + .thenReturn(packetMetaInfo); + PowerMockito.when(IOUtils.class, "toByteArray", inputStream).thenReturn(b); + Mockito.when(registrationStatusService.getRegistrationStatus(any())).thenReturn(registrationStatusDto); + Mockito.when(abisHandlerUtil.getPacketStatus(any())).thenReturn(AbisConstant.POST_ABIS_IDENTIFICATION); + Mockito.when(demoDedupe.performDedupe(anyString())).thenReturn(duplicateDtos); + registrationStatusDto.setRegistrationType(RegistrationType.NEW.toString()); + Mockito.when(registrationStatusDao.findById(any())).thenReturn(entity); + Mockito.when(packetInfoManager.getAbisResponseRecords(anyString(), anyString())).thenReturn(abisResponseDtos); + Mockito.when(utility.getApplicantAge(anyString(),anyString(), any())).thenReturn(20); + Mockito.when(registrationStatusMapperUtil.getStatusCode(any())).thenReturn("REPROCESS"); + MessageDTO messageDto = demodedupeProcessor.process(dto, stageName); + + assertFalse(messageDto.getIsValid()); + ArgumentCaptor argument = ArgumentCaptor + .forClass(InternalRegistrationStatusDto.class); + Mockito.verify(registrationStatusService, Mockito.atLeastOnce()).updateRegistrationStatus(argument.capture(), + any(), any()); + assertEquals(RegistrationTransactionStatusCode.REPROCESS.toString(), + argument.getAllValues().get(0).getLatestTransactionStatusCode()); + assertEquals(RegistrationStatusCode.PROCESSING.toString(), argument.getAllValues().get(0).getStatusCode()); + + } + + /** + * Test demo dedupe failure. + * + * @throws ApisResourceAccessException the apis resource access + * exception + * @throws IOException Signals that an I/O exception + * has occurred. + * @throws IntrospectionException + * @throws ParseException + * @throws InvocationTargetException + * @throws IllegalArgumentException + * @throws IllegalAccessException + * @throws io.mosip.kernel.core.exception.IOException + * @throws RegistrationProcessorCheckedException + */ + @SuppressWarnings("unchecked") + @Test + public void testDemoDedupeFailure() throws ApisResourceAccessException, IOException, JsonProcessingException, PacketManagerException, PacketManagerException { + InternalRegistrationStatusDto registrationStatusDto = new InternalRegistrationStatusDto(); + + Mockito.when(demoDedupe.performDedupe(anyString())).thenReturn(duplicateDtos); + Mockito.when(abisHandlerUtil.getPacketStatus(any())).thenReturn(RegistrationType.NEW.toString()); + Mockito.when(registrationStatusService.getRegistrationStatus(anyString())).thenReturn(registrationStatusDto); + registrationStatusDto.setRetryCount(3); + Mockito.when(utility.getApplicantAge(anyString(),anyString(), any())).thenReturn(20); + MessageDTO messageDto = demodedupeProcessor.process(dto, stageName); + assertTrue(messageDto.getInternalError()); + ArgumentCaptor argument = ArgumentCaptor + .forClass(InternalRegistrationStatusDto.class); + Mockito.verify(registrationStatusService, Mockito.atLeastOnce()).updateRegistrationStatus(argument.capture(), + any(), any()); + assertEquals(RegistrationTransactionStatusCode.ERROR.toString(), + argument.getAllValues().get(0).getLatestTransactionStatusCode()); + assertEquals(RegistrationStatusCode.FAILED.toString(), argument.getAllValues().get(0).getStatusCode()); + + } + + /** + * Test resource exception. + * + * @throws ApisResourceAccessException the apis resource access + * exception + * @throws IOException Signals that an I/O exception + * has occurred. + * @throws IntrospectionException + * @throws ParseException + * @throws InvocationTargetException + * @throws IllegalArgumentException + * @throws IllegalAccessException + * @throws io.mosip.kernel.core.exception.IOException + * @throws RegistrationProcessorCheckedException + */ + @SuppressWarnings("unchecked") + @Test + public void testResourceException() throws ApisResourceAccessException, IOException, JsonProcessingException, PacketManagerException { + when(env.getProperty(DEMODEDUPEENABLE)).thenReturn("true"); + + List emptyDuplicateDtoSet = new ArrayList<>(); + when(utility.getDefaultSource(any(),any())).thenReturn(source); + Mockito.when(utility.getApplicantAge(anyString(),anyString(), any())).thenReturn(20); + + Mockito.when(registrationStatusService.getRegistrationStatus(any())).thenReturn(registrationStatusDto); + Mockito.when(abisHandlerUtil.getPacketStatus(any())).thenReturn(AbisConstant.PRE_ABIS_IDENTIFICATION); + Mockito.when(demoDedupe.performDedupe(anyString())).thenReturn(emptyDuplicateDtoSet); + when(utility.getDefaultSource(any(), any())).thenReturn(source); + ApisResourceAccessException exp = new ApisResourceAccessException("errorMessage"); + Mockito.doThrow(exp).when(utility).getApplicantAge(anyString(),anyString(), any()); + Mockito.when(registrationStatusMapperUtil.getStatusCode(any())).thenReturn("REPROCESS"); + + MessageDTO messageDto = demodedupeProcessor.process(dto, stageName); + assertEquals(true, messageDto.getInternalError()); + ArgumentCaptor argument = ArgumentCaptor + .forClass(InternalRegistrationStatusDto.class); + Mockito.verify(registrationStatusService, Mockito.atLeastOnce()).updateRegistrationStatus(argument.capture(), + any(), any()); + assertEquals(RegistrationTransactionStatusCode.REPROCESS.toString(), + argument.getAllValues().get(0).getLatestTransactionStatusCode()); + assertEquals(RegistrationStatusCode.PROCESSING.toString(), argument.getAllValues().get(0).getStatusCode()); + } + + @Test + public void testFSAdapterExceptionException() + throws ApisResourceAccessException, IOException, JsonProcessingException, PacketManagerException { + Mockito.when(demoDedupe.performDedupe(anyString())).thenReturn(duplicateDtos); + + FSAdapterException exp = new FSAdapterException("errorMessage", "test"); + Mockito.doThrow(exp).when(abisHandlerUtil).getPacketStatus(any()); + registrationStatusDto.setRegistrationType(RegistrationType.NEW.toString()); + Mockito.when(registrationStatusService.getRegistrationStatus(anyString())).thenReturn(registrationStatusDto); + Mockito.when(utility.getApplicantAge(anyString(),anyString(), any())).thenReturn(20); + Mockito.when(registrationStatusMapperUtil.getStatusCode(any())).thenReturn("REPROCESS"); + MessageDTO messageDto = demodedupeProcessor.process(dto, stageName); + assertEquals(true, messageDto.getInternalError()); + ArgumentCaptor argument = ArgumentCaptor + .forClass(InternalRegistrationStatusDto.class); + Mockito.verify(registrationStatusService, Mockito.atLeastOnce()).updateRegistrationStatus(argument.capture(), + any(), any()); + assertEquals(RegistrationTransactionStatusCode.REPROCESS.toString(), + argument.getAllValues().get(0).getLatestTransactionStatusCode()); + assertEquals(RegistrationStatusCode.PROCESSING.toString(), argument.getAllValues().get(0).getStatusCode()); + } + + @Test + public void testIllegalArgumentException() throws ApisResourceAccessException, IOException, JsonProcessingException, PacketManagerException { + Mockito.when(demoDedupe.performDedupe(anyString())).thenReturn(duplicateDtos); + IllegalArgumentException exp = new IllegalArgumentException("errorMessage"); + Mockito.doThrow(exp).when(abisHandlerUtil).getPacketStatus(any()); + registrationStatusDto.setRegistrationType(RegistrationType.NEW.toString()); + Mockito.when(registrationStatusService.getRegistrationStatus(anyString())).thenReturn(registrationStatusDto); + Mockito.when(utility.getApplicantAge(anyString(),anyString(), any())).thenReturn(20); + MessageDTO messageDto = demodedupeProcessor.process(dto, stageName); + assertEquals(true, messageDto.getInternalError()); + ArgumentCaptor argument = ArgumentCaptor + .forClass(InternalRegistrationStatusDto.class); + Mockito.verify(registrationStatusService, Mockito.atLeastOnce()).updateRegistrationStatus(argument.capture(), + any(), any()); + assertEquals(RegistrationTransactionStatusCode.ERROR.toString(), + argument.getAllValues().get(0).getLatestTransactionStatusCode()); + assertEquals(RegistrationStatusCode.FAILED.toString(), argument.getAllValues().get(0).getStatusCode()); + } + + /** + * Test demo dedupe success. + * + * @throws Exception + */ + @Test + public void testDemoDedupeNewPacketSkipped() throws Exception { + when(env.getProperty(DEMODEDUPEENABLE)).thenReturn("false"); + byte[] b = "sds".getBytes(); + + + PowerMockito.mockStatic(JsonUtil.class); + PowerMockito.mockStatic(IOUtils.class); + PowerMockito.when(JsonUtil.class, "inputStreamtoJavaObject", inputStream, PacketMetaInfo.class) + .thenReturn(packetMetaInfo); + PowerMockito.when(IOUtils.class, "toByteArray", inputStream).thenReturn(b); + Mockito.when(registrationStatusService.getRegistrationStatus(any())).thenReturn(registrationStatusDto); + Mockito.when(abisHandlerUtil.getPacketStatus(any())).thenReturn(AbisConstant.PRE_ABIS_IDENTIFICATION); + Mockito.when(utility.getApplicantAge(anyString(),anyString(), any())).thenReturn(20); + MessageDTO messageDto = demodedupeProcessor.process(dto, stageName); + assertTrue(messageDto.getIsValid()); + ArgumentCaptor argument = ArgumentCaptor + .forClass(InternalRegistrationStatusDto.class); + Mockito.verify(registrationStatusService, Mockito.atLeastOnce()).updateRegistrationStatus(argument.capture(), + any(), any()); + assertEquals(RegistrationTransactionStatusCode.SUCCESS.toString(), + argument.getAllValues().get(0).getLatestTransactionStatusCode()); + assertEquals(RegistrationStatusCode.PROCESSING.toString(), argument.getAllValues().get(0).getStatusCode()); + + } + /** + * Test demo dedupe success. + * + * @throws Exception + */ + @Test + public void testDemoDedupeNewPacketSuccessWithDuplicates() throws Exception { + when(env.getProperty(DEMODEDUPEENABLE)).thenReturn("true"); + byte[] b = "sds".getBytes(); + + + PowerMockito.mockStatic(JsonUtil.class); + PowerMockito.mockStatic(IOUtils.class); + PowerMockito.when(JsonUtil.class, "inputStreamtoJavaObject", inputStream, PacketMetaInfo.class) + .thenReturn(packetMetaInfo); + PowerMockito.when(IOUtils.class, "toByteArray", inputStream).thenReturn(b); + Mockito.when(registrationStatusService.getRegistrationStatus(any())).thenReturn(registrationStatusDto).thenReturn(registrationStatusDto1).thenReturn(registrationStatusDto2); + Mockito.when(abisHandlerUtil.getPacketStatus(any())).thenReturn(AbisConstant.PRE_ABIS_IDENTIFICATION); + Mockito.when(demoDedupe.performDedupe(anyString())).thenReturn(duplicateDtos); + Mockito.when(utility.getApplicantAge(anyString(),anyString(), any())).thenReturn(20); + List matchedRidsWithoutRejected = new ArrayList<>(); + matchedRidsWithoutRejected.add("2018701130000410092018110731"); + Mockito.when(abisHandlerUtil.removeRejectedIds(anyList())) + .thenReturn(matchedRidsWithoutRejected); + MessageDTO messageDto = demodedupeProcessor.process(dto, stageName); + assertFalse(messageDto.getIsValid()); + ArgumentCaptor argument = ArgumentCaptor + .forClass(InternalRegistrationStatusDto.class); + Mockito.verify(registrationStatusService, Mockito.atLeastOnce()).updateRegistrationStatus(argument.capture(), + any(), any()); + assertEquals(RegistrationTransactionStatusCode.IN_PROGRESS.toString(), + argument.getAllValues().get(0).getLatestTransactionStatusCode()); + assertEquals(RegistrationStatusCode.PROCESSING.toString(), argument.getAllValues().get(0).getStatusCode()); + + } + /** + * Test demo dedupe success. + * + * @throws Exception + */ + @Test + public void testDemoDedupeNewPacketSuccessWithDuplicatesWithException() throws Exception { + when(env.getProperty(DEMODEDUPEENABLE)).thenReturn("true"); + byte[] b = "sds".getBytes(); + + + PowerMockito.mockStatic(JsonUtil.class); + PowerMockito.mockStatic(IOUtils.class); + PowerMockito.when(JsonUtil.class, "inputStreamtoJavaObject", inputStream, PacketMetaInfo.class) + .thenReturn(packetMetaInfo); + PowerMockito.when(IOUtils.class, "toByteArray", inputStream).thenReturn(b); + Mockito.when(registrationStatusService.getRegistrationStatus(any())).thenReturn(registrationStatusDto); + Mockito.when(abisHandlerUtil.getPacketStatus(any())).thenReturn(AbisConstant.PRE_ABIS_IDENTIFICATION); + Mockito.when(demoDedupe.performDedupe(anyString())).thenReturn(duplicateDtos); + List matchedRidsWithoutRejected = new ArrayList<>(); + matchedRidsWithoutRejected.add("2018701130000410092018110731"); + Mockito.when(abisHandlerUtil.removeRejectedIds(anyList())) + .thenReturn(matchedRidsWithoutRejected); + NullPointerException exp=new NullPointerException(); + Mockito.doThrow(exp).when(packetInfoManager).saveDemoDedupePotentialData(any(),anyString(),anyString()); + Mockito.when(utility.getApplicantAge(anyString(),anyString(), any())).thenReturn(20); + MessageDTO messageDto = demodedupeProcessor.process(dto, stageName); + assertFalse(messageDto.getIsValid()); + ArgumentCaptor argument = ArgumentCaptor + .forClass(InternalRegistrationStatusDto.class); + Mockito.verify(registrationStatusService, Mockito.atLeastOnce()).updateRegistrationStatus(argument.capture(), + any(), any()); + assertEquals(RegistrationTransactionStatusCode.REPROCESS.toString(), + argument.getAllValues().get(0).getLatestTransactionStatusCode()); + assertEquals(RegistrationStatusCode.PROCESSING.toString(), argument.getAllValues().get(0).getStatusCode()); + + + } + + @Test + public void testDemoDedupeNewChildPacketSuccess() throws Exception { + when(env.getProperty(DEMODEDUPEENABLE)).thenReturn("true"); + byte[] b = "sds".getBytes(); + List emptyDuplicateDtoSet = new ArrayList<>(); + Mockito.when(utility.getApplicantAge(anyString(),anyString(), any())).thenReturn(2); + PowerMockito.mockStatic(JsonUtil.class); + PowerMockito.mockStatic(IOUtils.class); + PowerMockito.when(JsonUtil.class, "inputStreamtoJavaObject", inputStream, PacketMetaInfo.class) + .thenReturn(packetMetaInfo); + PowerMockito.when(IOUtils.class, "toByteArray", inputStream).thenReturn(b); + Mockito.when(registrationStatusService.getRegistrationStatus(any())).thenReturn(registrationStatusDto); + Mockito.when(abisHandlerUtil.getPacketStatus(any())).thenReturn(AbisConstant.PRE_ABIS_IDENTIFICATION); + Mockito.when(demoDedupe.performDedupe(anyString())).thenReturn(emptyDuplicateDtoSet); + + MessageDTO messageDto = demodedupeProcessor.process(dto, stageName); + assertTrue(messageDto.getIsValid()); + ArgumentCaptor argument = ArgumentCaptor + .forClass(InternalRegistrationStatusDto.class); + Mockito.verify(registrationStatusService, Mockito.atLeastOnce()).updateRegistrationStatus(argument.capture(), + any(), any()); + assertEquals(RegistrationTransactionStatusCode.SUCCESS.toString(), + argument.getAllValues().get(0).getLatestTransactionStatusCode()); + assertEquals(RegistrationStatusCode.PROCESSING.toString(), argument.getAllValues().get(0).getStatusCode()); + + + } + + @Test + public void testDemoDedupeDisabledSuccess() throws Exception { + when(env.getProperty(DEMODEDUPEENABLE)).thenReturn("false"); + byte[] b = "sds".getBytes(); + List emptyDuplicateDtoSet = new ArrayList<>(); + Mockito.when(utility.getApplicantAge(any(),any(), any())).thenReturn(20); + PowerMockito.mockStatic(JsonUtil.class); + PowerMockito.mockStatic(IOUtils.class); + PowerMockito.when(JsonUtil.class, "inputStreamtoJavaObject", inputStream, PacketMetaInfo.class) + .thenReturn(packetMetaInfo); + PowerMockito.when(IOUtils.class, "toByteArray", inputStream).thenReturn(b); + Mockito.when(registrationStatusService.getRegistrationStatus(any())).thenReturn(registrationStatusDto); + Mockito.when(abisHandlerUtil.getPacketStatus(any())).thenReturn(AbisConstant.PRE_ABIS_IDENTIFICATION); + Mockito.when(demoDedupe.performDedupe(anyString())).thenReturn(emptyDuplicateDtoSet); + + MessageDTO messageDto = demodedupeProcessor.process(dto, stageName); + assertTrue(messageDto.getIsValid()); + ArgumentCaptor argument = ArgumentCaptor + .forClass(InternalRegistrationStatusDto.class); + Mockito.verify(registrationStatusService, Mockito.atLeastOnce()).updateRegistrationStatus(argument.capture(), + any(), any()); + assertEquals(RegistrationTransactionStatusCode.SUCCESS.toString(), + argument.getAllValues().get(0).getLatestTransactionStatusCode()); + assertEquals(RegistrationStatusCode.PROCESSING.toString(), argument.getAllValues().get(0).getStatusCode()); + + } + + @Test + public void testDemoDedupeSuccess() throws Exception { + when(env.getProperty(DEMODEDUPEENABLE)).thenReturn("true"); + byte[] b = "sds".getBytes(); + List emptyDuplicateDtoSet = new ArrayList<>(); + Mockito.when(utility.getApplicantAge(any(), any(), any())).thenReturn(20); + PowerMockito.mockStatic(JsonUtil.class); + PowerMockito.mockStatic(IOUtils.class); + PowerMockito.when(JsonUtil.class, "inputStreamtoJavaObject", inputStream, PacketMetaInfo.class) + .thenReturn(packetMetaInfo); + PowerMockito.when(IOUtils.class, "toByteArray", inputStream).thenReturn(b); + Mockito.when(registrationStatusService.getRegistrationStatus(any())).thenReturn(registrationStatusDto); + Mockito.when(abisHandlerUtil.getPacketStatus(any())).thenReturn(AbisConstant.PRE_ABIS_IDENTIFICATION); + Mockito.when(demoDedupe.performDedupe(anyString())).thenReturn(emptyDuplicateDtoSet); + + MessageDTO messageDto = demodedupeProcessor.process(dto, stageName); + assertTrue(messageDto.getIsValid()); + ArgumentCaptor argument = ArgumentCaptor + .forClass(InternalRegistrationStatusDto.class); + Mockito.verify(registrationStatusService, Mockito.atLeastOnce()).updateRegistrationStatus(argument.capture(), + any(), any()); + assertEquals(RegistrationTransactionStatusCode.SUCCESS.toString(), + argument.getAllValues().get(0).getLatestTransactionStatusCode()); + assertEquals(RegistrationStatusCode.PROCESSING.toString(), argument.getAllValues().get(0).getStatusCode()); + + } + @Test + public void testDemoDedupeNewDuplicatePacketSuccess() throws Exception { + when(env.getProperty(DEMODEDUPEENABLE)).thenReturn("true"); + + Mockito.when(registrationStatusService.getRegistrationStatus(any())).thenReturn(registrationStatusDto); + Mockito.when(abisHandlerUtil.getPacketStatus(any())).thenReturn(AbisConstant.DUPLICATE_FOR_SAME_TRANSACTION_ID); + + MessageDTO messageDto = demodedupeProcessor.process(dto, stageName); + assertTrue(messageDto.getInternalError()); + + } + + 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); + + biometricRecord.getSegments().add(birType1); + } + + return biometricRecord; + } + + @Test + public void testDemoDedupeNewPacketWithDuplicatesWithNoBiometrics() throws Exception { + when(env.getProperty(DEMODEDUPEENABLE)).thenReturn("true"); + byte[] b = "sds".getBytes(); + + PowerMockito.mockStatic(JsonUtil.class); + PowerMockito.mockStatic(IOUtils.class); + PowerMockito.when(JsonUtil.class, "inputStreamtoJavaObject", inputStream, PacketMetaInfo.class) + .thenReturn(packetMetaInfo); + PowerMockito.when(IOUtils.class, "toByteArray", inputStream).thenReturn(b); + Mockito.when(registrationStatusService.getRegistrationStatus(any())).thenReturn(registrationStatusDto).thenReturn(registrationStatusDto1).thenReturn(registrationStatusDto2); + Mockito.when(abisHandlerUtil.getPacketStatus(any())).thenReturn(AbisConstant.PRE_ABIS_IDENTIFICATION); + Mockito.when(demoDedupe.performDedupe(anyString())).thenReturn(duplicateDtos); + Mockito.when(packetManagerService.getBiometrics(any(), any(), any(), any(), any())).thenReturn(null); + BiometricRecordValidationException e = new BiometricRecordValidationException("Biometirc validation failed"); + Mockito.doThrow(e).when(abisHandlerUtil).validateBiometricRecord(any(), anyList()); + List matchedRidsWithoutRejected = new ArrayList<>(); + matchedRidsWithoutRejected.add("2018701130000410092018110731"); + Mockito.when(abisHandlerUtil.removeRejectedIds(anyList())) + .thenReturn(matchedRidsWithoutRejected); + Mockito.when(utility.getApplicantAge(anyString(), anyString(), any())).thenReturn(20); + MessageDTO messageDto = demodedupeProcessor.process(dto, stageName); + assertEquals(MessageBusAddress.MANUAL_VERIFICATION_BUS_IN, messageDto.getMessageBusAddress()); + assertEquals(false, messageDto.getIsValid()); + assertEquals(false, messageDto.getInternalError()); + ArgumentCaptor argument = ArgumentCaptor + .forClass(InternalRegistrationStatusDto.class); + Mockito.verify(registrationStatusService,Mockito.atLeastOnce()).updateRegistrationStatus(argument.capture(),any(),any()); + assertEquals(RegistrationTransactionStatusCode.FAILED.toString(), argument.getAllValues().get(0).getLatestTransactionStatusCode()); + assertEquals(RegistrationStatusCode.PROCESSING.toString(), argument.getAllValues().get(0).getStatusCode()); + + } + + @Test + public void testDemoDedupeNewPacketWithDuplicatesWithNoBiometricsWithDemodedupeSuccess() throws Exception { + when(env.getProperty(DEMODEDUPEENABLE)).thenReturn("true"); + byte[] b = "sds".getBytes(); + ReflectionTestUtils.setField(demodedupeProcessor, "demodedupeInvalidBiometricAction", + "MarkAsDemodedupeSuccess"); + ReflectionTestUtils.setField(demodedupeProcessor, "demodedupeInfantInvalidBiometricAction", "MarkAsDemodedupeSuccess"); + PowerMockito.mockStatic(JsonUtil.class); + PowerMockito.mockStatic(IOUtils.class); + PowerMockito.when(JsonUtil.class, "inputStreamtoJavaObject", inputStream, PacketMetaInfo.class) + .thenReturn(packetMetaInfo); + PowerMockito.when(IOUtils.class, "toByteArray", inputStream).thenReturn(b); + Mockito.when(registrationStatusService.getRegistrationStatus(any())).thenReturn(registrationStatusDto).thenReturn(registrationStatusDto1).thenReturn(registrationStatusDto2); + Mockito.when(abisHandlerUtil.getPacketStatus(any())).thenReturn(AbisConstant.PRE_ABIS_IDENTIFICATION); + Mockito.when(demoDedupe.performDedupe(anyString())).thenReturn(duplicateDtos); + Mockito.when(packetManagerService.getBiometrics(any(), any(), any(), any(), any())).thenReturn(null); + BiometricRecordValidationException e = new BiometricRecordValidationException("Biometirc validation failed"); + Mockito.doThrow(e).when(abisHandlerUtil).validateBiometricRecord(any(), anyList()); + List matchedRidsWithoutRejected = new ArrayList<>(); + matchedRidsWithoutRejected.add("2018701130000410092018110731"); + Mockito.when(abisHandlerUtil.removeRejectedIds(anyList())) + .thenReturn(matchedRidsWithoutRejected); + Mockito.when(utility.getApplicantAge(anyString(), anyString(), any())).thenReturn(20); + MessageDTO messageDto = demodedupeProcessor.process(dto, stageName); + assertTrue(messageDto.getIsValid()); + assertEquals(false, messageDto.getInternalError()); + ArgumentCaptor argument = ArgumentCaptor + .forClass(InternalRegistrationStatusDto.class); + Mockito.verify(registrationStatusService,Mockito.atLeastOnce()).updateRegistrationStatus(argument.capture(),any(),any()); + assertEquals(RegistrationTransactionStatusCode.SUCCESS.toString(), argument.getAllValues().get(0).getLatestTransactionStatusCode()); + assertEquals(RegistrationStatusCode.PROCESSING.toString(), argument.getAllValues().get(0).getStatusCode()); + + } + + @Test + public void testDemoDedupeNewPacketWithDuplicatesWithNoBiometricsWithDemodedupeRejected() throws Exception { + when(env.getProperty(DEMODEDUPEENABLE)).thenReturn("true"); + byte[] b = "sds".getBytes(); + ReflectionTestUtils.setField(demodedupeProcessor, "demodedupeInvalidBiometricAction", + "MarkAsDemodedupeRejected"); + ReflectionTestUtils.setField(demodedupeProcessor, "demodedupeInfantInvalidBiometricAction", "MarkAsDemodedupeRejected"); + PowerMockito.mockStatic(JsonUtil.class); + PowerMockito.mockStatic(IOUtils.class); + PowerMockito.when(JsonUtil.class, "inputStreamtoJavaObject", inputStream, PacketMetaInfo.class) + .thenReturn(packetMetaInfo); + PowerMockito.when(IOUtils.class, "toByteArray", inputStream).thenReturn(b); + Mockito.when(registrationStatusService.getRegistrationStatus(any())).thenReturn(registrationStatusDto).thenReturn(registrationStatusDto1).thenReturn(registrationStatusDto2); + Mockito.when(abisHandlerUtil.getPacketStatus(any())).thenReturn(AbisConstant.PRE_ABIS_IDENTIFICATION); + Mockito.when(demoDedupe.performDedupe(anyString())).thenReturn(duplicateDtos); + Mockito.when(packetManagerService.getBiometrics(any(), any(), any(), any(), any())).thenReturn(null); + BiometricRecordValidationException e = new BiometricRecordValidationException("Biometirc validation failed"); + Mockito.doThrow(e).when(abisHandlerUtil).validateBiometricRecord(any(), anyList()); + List matchedRidsWithoutRejected = new ArrayList<>(); + matchedRidsWithoutRejected.add("2018701130000410092018110731"); + Mockito.when(abisHandlerUtil.removeRejectedIds(anyList())) + .thenReturn(matchedRidsWithoutRejected); + Mockito.when(utility.getApplicantAge(anyString(), anyString(), any())).thenReturn(20); + MessageDTO messageDto = demodedupeProcessor.process(dto, stageName); + assertFalse(messageDto.getIsValid()); + assertEquals(false, messageDto.getInternalError()); + ArgumentCaptor argument = ArgumentCaptor + .forClass(InternalRegistrationStatusDto.class); + Mockito.verify(registrationStatusService,Mockito.atLeastOnce()).updateRegistrationStatus(argument.capture(),any(),any()); + assertEquals(RegistrationTransactionStatusCode.FAILED.toString(), argument.getAllValues().get(0).getLatestTransactionStatusCode()); + assertEquals(RegistrationStatusCode.REJECTED.toString(), argument.getAllValues().get(0).getStatusCode()); + } + + @Test + public void testDemoDedupeNewInfantPacketWithDuplicatesWithNoBiometrics() throws Exception { + byte[] b = "sds".getBytes(); + PowerMockito.mockStatic(JsonUtil.class); + PowerMockito.mockStatic(IOUtils.class); + PowerMockito.when(JsonUtil.class, "inputStreamtoJavaObject", inputStream, PacketMetaInfo.class) + .thenReturn(packetMetaInfo); + PowerMockito.when(IOUtils.class, "toByteArray", inputStream).thenReturn(b); + Mockito.when(registrationStatusService.getRegistrationStatus(any())).thenReturn(registrationStatusDto).thenReturn(registrationStatusDto1).thenReturn(registrationStatusDto2); + Mockito.when(abisHandlerUtil.getPacketStatus(any())).thenReturn(AbisConstant.PRE_ABIS_IDENTIFICATION); + Mockito.when(demoDedupe.performDedupe(anyString())).thenReturn(duplicateDtos); + Mockito.when(packetManagerService.getBiometrics(any(), any(), any(), any(), any())).thenReturn(null); + BiometricRecordValidationException e = new BiometricRecordValidationException("Biometirc validation failed"); + Mockito.doThrow(e).when(abisHandlerUtil).validateBiometricRecord(any(), anyList()); + List matchedRidsWithoutRejected = new ArrayList<>(); + matchedRidsWithoutRejected.add("2018701130000410092018110731"); + Mockito.when(abisHandlerUtil.removeRejectedIds(anyList())) + .thenReturn(matchedRidsWithoutRejected); + Mockito.when(utility.getApplicantAge(anyString(), anyString(), any())).thenReturn(1); + MessageDTO messageDto1 = demodedupeProcessor.process(dto, stageName); + assertEquals(MessageBusAddress.MANUAL_VERIFICATION_BUS_IN, messageDto1.getMessageBusAddress()); + assertEquals(false, messageDto1.getIsValid()); + assertEquals(false, messageDto1.getInternalError()); + ArgumentCaptor argument1 = ArgumentCaptor + .forClass(InternalRegistrationStatusDto.class); + Mockito.verify(registrationStatusService,Mockito.atLeastOnce()).updateRegistrationStatus(argument1.capture(),any(),any()); + assertEquals(RegistrationTransactionStatusCode.FAILED.toString(), argument1.getAllValues().get(0).getLatestTransactionStatusCode()); + assertEquals(RegistrationStatusCode.PROCESSING.toString(), argument1.getAllValues().get(0).getStatusCode()); + + } + + @Test + public void testDemoDedupeNewInfantPacketWithDuplicatesWithNoBiometricsWithDemodedupeSuccess() throws Exception { + byte[] b = "sds".getBytes(); + ReflectionTestUtils.setField(demodedupeProcessor, "demodedupeInfantInvalidBiometricAction", "MarkAsDemodedupeSuccess"); + PowerMockito.mockStatic(JsonUtil.class); + PowerMockito.mockStatic(IOUtils.class); + PowerMockito.when(JsonUtil.class, "inputStreamtoJavaObject", inputStream, PacketMetaInfo.class) + .thenReturn(packetMetaInfo); + PowerMockito.when(IOUtils.class, "toByteArray", inputStream).thenReturn(b); + Mockito.when(registrationStatusService.getRegistrationStatus(any())).thenReturn(registrationStatusDto).thenReturn(registrationStatusDto1).thenReturn(registrationStatusDto2); + Mockito.when(abisHandlerUtil.getPacketStatus(any())).thenReturn(AbisConstant.PRE_ABIS_IDENTIFICATION); + Mockito.when(demoDedupe.performDedupe(anyString())).thenReturn(duplicateDtos); + Mockito.when(packetManagerService.getBiometrics(any(), any(), any(), any(), any())).thenReturn(null); + BiometricRecordValidationException e = new BiometricRecordValidationException("Biometirc validation failed"); + Mockito.doThrow(e).when(abisHandlerUtil).validateBiometricRecord(any(), anyList()); + List matchedRidsWithoutRejected = new ArrayList<>(); + matchedRidsWithoutRejected.add("2018701130000410092018110731"); + Mockito.when(abisHandlerUtil.removeRejectedIds(anyList())).thenReturn(matchedRidsWithoutRejected); + Mockito.when(utility.getApplicantAge(anyString(), anyString(), any())).thenReturn(1); + MessageDTO messageDto1 = demodedupeProcessor.process(dto, stageName); + assertTrue(messageDto1.getIsValid()); + assertEquals(false, messageDto1.getInternalError()); + ArgumentCaptor argument1 = ArgumentCaptor + .forClass(InternalRegistrationStatusDto.class); + Mockito.verify(registrationStatusService,Mockito.atLeastOnce()).updateRegistrationStatus(argument1.capture(),any(),any()); + assertEquals(RegistrationTransactionStatusCode.SUCCESS.toString(), argument1.getAllValues().get(0).getLatestTransactionStatusCode()); + assertEquals(RegistrationStatusCode.PROCESSING.toString(), argument1.getAllValues().get(0).getStatusCode()); + + } + + @Test + public void testDemoDedupeNewInfantPacketWithDuplicatesWithNoBiometricsWithDemodedupeRejected() throws Exception { + byte[] b = "sds".getBytes(); + ReflectionTestUtils.setField(demodedupeProcessor, "demodedupeInfantInvalidBiometricAction", "MarkAsDemodedupeRejected"); + PowerMockito.mockStatic(JsonUtil.class); + PowerMockito.mockStatic(IOUtils.class); + PowerMockito.when(JsonUtil.class, "inputStreamtoJavaObject", inputStream, PacketMetaInfo.class) + .thenReturn(packetMetaInfo); + PowerMockito.when(IOUtils.class, "toByteArray", inputStream).thenReturn(b); + Mockito.when(registrationStatusService.getRegistrationStatus(any())).thenReturn(registrationStatusDto).thenReturn(registrationStatusDto1).thenReturn(registrationStatusDto2); + Mockito.when(abisHandlerUtil.getPacketStatus(any())).thenReturn(AbisConstant.PRE_ABIS_IDENTIFICATION); + Mockito.when(demoDedupe.performDedupe(anyString())).thenReturn(duplicateDtos); + Mockito.when(packetManagerService.getBiometrics(any(), any(), any(), any(), any())).thenReturn(null); + BiometricRecordValidationException e = new BiometricRecordValidationException("Biometirc validation failed"); + Mockito.doThrow(e).when(abisHandlerUtil).validateBiometricRecord(any(), anyList()); + List matchedRidsWithoutRejected = new ArrayList<>(); + matchedRidsWithoutRejected.add("2018701130000410092018110731"); + Mockito.when(abisHandlerUtil.removeRejectedIds(anyList())).thenReturn(matchedRidsWithoutRejected); + Mockito.when(utility.getApplicantAge(anyString(), anyString(), any())).thenReturn(1); + MessageDTO messageDto1 = demodedupeProcessor.process(dto, stageName); + assertFalse(messageDto1.getIsValid()); + assertEquals(false, messageDto1.getInternalError()); + ArgumentCaptor argument1 = ArgumentCaptor + .forClass(InternalRegistrationStatusDto.class); + Mockito.verify(registrationStatusService,Mockito.atLeastOnce()).updateRegistrationStatus(argument1.capture(),any(),any()); + assertEquals(RegistrationTransactionStatusCode.FAILED.toString(), argument1.getAllValues().get(0).getLatestTransactionStatusCode()); + assertEquals(RegistrationStatusCode.REJECTED.toString(), argument1.getAllValues().get(0).getStatusCode()); + + } } \ No newline at end of file diff --git a/registration-processor/core-processor/registration-processor-abis-handler-stage/src/main/java/io/mosip/registration/processor/abis/handler/exception/BiometricRecordValidationException.java b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/exception/BiometricRecordValidationException.java similarity index 85% rename from registration-processor/core-processor/registration-processor-abis-handler-stage/src/main/java/io/mosip/registration/processor/abis/handler/exception/BiometricRecordValidationException.java rename to registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/exception/BiometricRecordValidationException.java index 41ff609995d..a022e8915e2 100644 --- a/registration-processor/core-processor/registration-processor-abis-handler-stage/src/main/java/io/mosip/registration/processor/abis/handler/exception/BiometricRecordValidationException.java +++ b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/exception/BiometricRecordValidationException.java @@ -1,4 +1,4 @@ -package io.mosip.registration.processor.abis.handler.exception; +package io.mosip.registration.processor.core.exception; import io.mosip.kernel.core.exception.BaseCheckedException; import io.mosip.registration.processor.core.exception.util.PlatformErrorMessages; diff --git a/registration-processor/core-processor/registration-processor-abis-handler-stage/src/main/java/io/mosip/registration/processor/abis/handler/exception/DataShareException.java b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/exception/DataShareException.java similarity index 83% rename from registration-processor/core-processor/registration-processor-abis-handler-stage/src/main/java/io/mosip/registration/processor/abis/handler/exception/DataShareException.java rename to registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/exception/DataShareException.java index 705879d1c1d..d1f5e2a776f 100644 --- a/registration-processor/core-processor/registration-processor-abis-handler-stage/src/main/java/io/mosip/registration/processor/abis/handler/exception/DataShareException.java +++ b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/exception/DataShareException.java @@ -1,11 +1,11 @@ -package io.mosip.registration.processor.abis.handler.exception; - -import io.mosip.kernel.core.exception.BaseCheckedException; -import io.mosip.registration.processor.core.exception.util.PlatformErrorMessages; - -public class DataShareException extends BaseCheckedException { - - public DataShareException(String message) { - super(PlatformErrorMessages.DATASHARE_ERROR.getCode(), message); - } -} +package io.mosip.registration.processor.core.exception; + +import io.mosip.kernel.core.exception.BaseCheckedException; +import io.mosip.registration.processor.core.exception.util.PlatformErrorMessages; + +public class DataShareException extends BaseCheckedException { + + public DataShareException(String message) { + super(PlatformErrorMessages.DATASHARE_ERROR.getCode(), message); + } +} 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 a5d3c27eb10..731a59a8f31 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 @@ -1279,6 +1279,14 @@ public enum PlatformErrorMessages { RPR_DEMO_API_RESOUCE_ACCESS_FAILED(PlatformConstants.RPR_DEMO_DEDUPE_MODULE + "002", "Unable to Access API Resource"), + RPR_DEMO_BIOMETRIC_RECORD_VALIDATION_FAILED(PlatformConstants.RPR_DEMO_DEDUPE_MODULE + "003", + "Biometric record validation error"), + + RPR_DEMO_POTENTIAL_SENDING_FOR_MANUAL(PlatformConstants.RPR_DEMO_DEDUPE_MODULE + "004", + "Potential Demo Match was Found and Biometric record validation failed. Hence sending to manual adjudication"), + + RPR_DEMO_POTENTIAL_PACKET_REJECTED(PlatformConstants.RPR_DEMO_DEDUPE_MODULE + "004", + "Potential Demo Match was Found and Biometric record validation failed. Hence packet Rejected"), RPR_SECUREZONE_FAILURE(PlatformConstants.RPR_SECUREZONE_NOTIFICATION_MODULE + "001", "Exception occured in securezone notification stage. Check logs for more info"), 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 d9990f26f17..5da6b5cf193 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 @@ -50,6 +50,9 @@ public enum PlatformSuccessMessages { RPR_PKR_DEMO_DE_DUP_SKIP(PlatformConstants.RPR_DEMO_DEDUPE_MODULE + "002", "Demographic Deduplication Skipped"), + RPR_PKR_DEMO_DE_DUP_POTENTIAL_DUPLICATION_SUCCESS(PlatformConstants.RPR_DEMO_DEDUPE_MODULE + "003", + "Potential Demo Match was Found and Biometric record validation failed.Hence demodedupe success"), + // Biometric Authentication Success Messages RPR_PKR_BIOMETRIC_AUTHENTICATION(PlatformConstants.RPR_BIOMETRIC_AUTHENTICATION_MODULE + "000", "Biometric Authentication Success"), diff --git a/registration-processor/core-processor/registration-processor-abis-handler-stage/src/main/java/io/mosip/registration/processor/abis/handler/dto/DataShare.java b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/packet/dto/abis/DataShare.java similarity index 83% rename from registration-processor/core-processor/registration-processor-abis-handler-stage/src/main/java/io/mosip/registration/processor/abis/handler/dto/DataShare.java rename to registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/packet/dto/abis/DataShare.java index a640a494c30..b5bd66dc686 100644 --- a/registration-processor/core-processor/registration-processor-abis-handler-stage/src/main/java/io/mosip/registration/processor/abis/handler/dto/DataShare.java +++ b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/packet/dto/abis/DataShare.java @@ -1,25 +1,25 @@ -package io.mosip.registration.processor.abis.handler.dto; - -import lombok.Data; - -@Data -public class DataShare { - /** The url. */ - private String url; - - /** The valid for in minutes. */ - private int validForInMinutes; - - /** The transactions allowed. */ - private int transactionsAllowed; - - - /** The policy id. */ - private String policyId; - - /** The subscriber id. */ - private String subscriberId; - - /** The signature. */ - private String signature; -} +package io.mosip.registration.processor.core.packet.dto.abis; + +import lombok.Data; + +@Data +public class DataShare { + /** The url. */ + private String url; + + /** The valid for in minutes. */ + private int validForInMinutes; + + /** The transactions allowed. */ + private int transactionsAllowed; + + + /** The policy id. */ + private String policyId; + + /** The subscriber id. */ + private String subscriberId; + + /** The signature. */ + private String signature; +} diff --git a/registration-processor/core-processor/registration-processor-abis-handler-stage/src/main/java/io/mosip/registration/processor/abis/handler/dto/Filter.java b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/packet/dto/abis/Filter.java similarity index 67% rename from registration-processor/core-processor/registration-processor-abis-handler-stage/src/main/java/io/mosip/registration/processor/abis/handler/dto/Filter.java rename to registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/packet/dto/abis/Filter.java index ed88c7477e8..814ded4efe7 100644 --- a/registration-processor/core-processor/registration-processor-abis-handler-stage/src/main/java/io/mosip/registration/processor/abis/handler/dto/Filter.java +++ b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/packet/dto/abis/Filter.java @@ -1,12 +1,12 @@ -package io.mosip.registration.processor.abis.handler.dto; - -import java.util.List; - -import lombok.Data; - -@Data -public class Filter { - public String language; - public String type; - public List subType; -} +package io.mosip.registration.processor.core.packet.dto.abis; + +import java.util.List; + +import lombok.Data; + +@Data +public class Filter { + public String language; + public String type; + public List subType; +} diff --git a/registration-processor/core-processor/registration-processor-abis-handler-stage/src/main/java/io/mosip/registration/processor/abis/handler/dto/ShareableAttributes.java b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/packet/dto/abis/ShareableAttributes.java similarity index 73% rename from registration-processor/core-processor/registration-processor-abis-handler-stage/src/main/java/io/mosip/registration/processor/abis/handler/dto/ShareableAttributes.java rename to registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/packet/dto/abis/ShareableAttributes.java index a47b2b3deee..2ab110246eb 100644 --- a/registration-processor/core-processor/registration-processor-abis-handler-stage/src/main/java/io/mosip/registration/processor/abis/handler/dto/ShareableAttributes.java +++ b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/packet/dto/abis/ShareableAttributes.java @@ -1,18 +1,18 @@ -package io.mosip.registration.processor.abis.handler.dto; - -import java.util.List; - -import lombok.Data; - -@Data -public class ShareableAttributes { - public boolean encrypted; - - public String format; - - public String attributeName; - - public List source; - - public String group; -} +package io.mosip.registration.processor.core.packet.dto.abis; + +import java.util.List; + +import lombok.Data; + +@Data +public class ShareableAttributes { + public boolean encrypted; + + public String format; + + public String attributeName; + + public List source; + + public String group; +} diff --git a/registration-processor/core-processor/registration-processor-abis-handler-stage/src/main/java/io/mosip/registration/processor/abis/handler/dto/Source.java b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/packet/dto/abis/Source.java similarity index 64% rename from registration-processor/core-processor/registration-processor-abis-handler-stage/src/main/java/io/mosip/registration/processor/abis/handler/dto/Source.java rename to registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/packet/dto/abis/Source.java index 3041940e4d9..122e95d7ffb 100644 --- a/registration-processor/core-processor/registration-processor-abis-handler-stage/src/main/java/io/mosip/registration/processor/abis/handler/dto/Source.java +++ b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/packet/dto/abis/Source.java @@ -1,12 +1,12 @@ -package io.mosip.registration.processor.abis.handler.dto; - -import java.util.List; - -import lombok.Data; - -@Data -public class Source { - public String attribute; - - public List filter; -} +package io.mosip.registration.processor.core.packet.dto.abis; + +import java.util.List; + +import lombok.Data; + +@Data +public class Source { + public String attribute; + + public List filter; +} 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 13cbe9b7c45..e71411cfc49 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 @@ -128,6 +128,15 @@ public enum StatusUtil { 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"), + DEMO_DEDUPE_BIOMTERIC_RECORD_VALIDAITON_FAILED(StatusConstants.DEMO_DEDUPE_MODULE_FAILED + "004", + "Potential Demo Match was Found and Biometric record validation failed. Hence sending to manual adjudication"), + DEMO_DEDUPE_PACKET_MANAGER_EXCEPTION(StatusConstants.DEMO_DEDUPE_MODULE_FAILED + "005", + "Exception occured in packet manager."), + DEMO_DEDUPE_BIOMTERIC_RECORD_VALIDAITON_FAILED_AND_PACKET_REJECTED( + StatusConstants.DEMO_DEDUPE_MODULE_FAILED + "006", + "Potential Demo Match was Found and Biometric record validation failed.Hence packet rejected"), + DEMO_DEDUPE_BIOMTERIC_RECORD_VALIDAITON_FAILED_AND_PACKET_SUCCESS(StatusConstants.DEMO_DEDUPE_MODULE_FAILED + "007", + "Potential Demo Match was Found and Biometric record validation failed.Hence packet success"), // Manual verification stage MANUAL_VERIFIER_APPROVED_PACKET(StatusConstants.MANUAL_VERIFICATION_MODULE_SUCCESS + "001", "Match Not Found by Manual Verifier"), 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 577ad33ac9c..f97985005fe 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 @@ -2,29 +2,50 @@ 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.stream.Collectors; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import org.springframework.util.CollectionUtils; +import com.fasterxml.jackson.core.JsonParseException; +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.core.logger.spi.Logger; import io.mosip.kernel.core.util.exception.JsonProcessingException; import io.mosip.registration.processor.core.code.AbisStatusCode; +import io.mosip.registration.processor.core.code.ApiName; import io.mosip.registration.processor.core.constant.AbisConstant; import io.mosip.registration.processor.core.constant.LoggerFileConstant; +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.BiometricRecordValidationException; +import io.mosip.registration.processor.core.exception.DataShareException; import io.mosip.registration.processor.core.exception.PacketManagerException; +import io.mosip.registration.processor.core.exception.util.PlatformErrorMessages; +import io.mosip.registration.processor.core.http.ResponseWrapper; import io.mosip.registration.processor.core.logger.RegProcessorLogger; import io.mosip.registration.processor.core.packet.dto.Identity; import io.mosip.registration.processor.core.packet.dto.abis.AbisRequestDto; 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.Filter; +import io.mosip.registration.processor.core.packet.dto.abis.ShareableAttributes; +import io.mosip.registration.processor.core.packet.dto.abis.Source; import io.mosip.registration.processor.core.spi.packetmanager.PacketInfoManager; +import io.mosip.registration.processor.core.spi.restclient.RegistrationProcessorRestClientService; 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; @@ -60,6 +81,15 @@ public class ABISHandlerUtil { @Autowired private IdRepoService idRepoService; + @Value("${registration.processor.policy.id}") + private String policyId; + + @Value("${registration.processor.subscriber.id}") + private String subscriberId; + + @Autowired + private RegistrationProcessorRestClientService registrationProcessorRestClientService; + /** * Gets the unique reg ids. * @@ -97,26 +127,8 @@ public List getUniqueRegIds(String registrationId, String registrationTy if (!CollectionUtils.isEmpty(machedRefIds)) { List matchedRegIds = packetInfoDao.getAbisRefRegIdsByMatchedRefIds(machedRefIds); if (!CollectionUtils.isEmpty(matchedRegIds)) { - 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::getId) - .collect(Collectors.toList()); - List matchedProcessedRegIds = matchedRegistrationStatusEntities.stream() - .map(RegistrationStatusEntity::getId).collect(Collectors.toList()); - uniqueRIDs.addAll(processingRegIds); - List processedRegIds = getUniqueRegIds(matchedProcessedRegIds, registrationId, - registrationType, - stageName); - for(String rid:processedRegIds) { - if(!uniqueRIDs.contains(rid)) - uniqueRIDs.add(rid); - } + uniqueRIDs = getUniqueProcessedRecords(registrationId, registrationType, stageName, + matchedRegIds); } } @@ -129,6 +141,34 @@ public List getUniqueRegIds(String registrationId, String registrationTy } + public List getUniqueProcessedRecords(String registrationId, String registrationType, + ProviderStageName stageName, + List matchedRegIds) + throws ApisResourceAccessException, IOException, JsonProcessingException, PacketManagerException { + List uniqueRIDs = new ArrayList<>(); + 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::getId) + .collect(Collectors.toList()); + List matchedProcessedRegIds = matchedRegistrationStatusEntities.stream() + .map(RegistrationStatusEntity::getId).collect(Collectors.toList()); + uniqueRIDs.addAll(processingRegIds); + List processedRegIds = getUniqueRegIds(matchedProcessedRegIds, registrationId, + registrationType, + stageName); + for(String rid:processedRegIds) { + if(!uniqueRIDs.contains(rid)) + uniqueRIDs.add(rid); + } + return uniqueRIDs; + } + /** * Gets the packet status. * @@ -235,4 +275,90 @@ public List getUniqueRegIds(List matchedRegistrationIds, String } + public void validateBiometricRecord(BiometricRecord biometricRecord, List modalities) + throws BiometricRecordValidationException, JsonParseException, JsonMappingException, IOException { + if (modalities == null || modalities.isEmpty()) { + throw new BiometricRecordValidationException(PlatformErrorMessages.RPR_DATASHARE_MODALITIES_EMPTY.getCode(), + PlatformErrorMessages.RPR_DATASHARE_MODALITIES_EMPTY.getMessage()); + } + if (biometricRecord == null || biometricRecord.getSegments() == null + || biometricRecord.getSegments().isEmpty()) { + throw new BiometricRecordValidationException( + PlatformErrorMessages.RPR_NO_BIOMETRICS_FOUND_WITH_DATASHARE.getCode(), + PlatformErrorMessages.RPR_NO_BIOMETRICS_FOUND_WITH_DATASHARE.getMessage()); + } + + for (String segment : modalities) { + 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(); + if (bir.getBdb() != null) { + return; + } + } + } + + throw new BiometricRecordValidationException( + PlatformErrorMessages.RPR_NO_BIOMETRIC_MATCH_WTIH_DATASAHRE.getCode(), + PlatformErrorMessages.RPR_NO_BIOMETRIC_MATCH_WTIH_DATASAHRE.getMessage()); + } + + public Map> createBiometricTypeSubtypeMappingFromAbispolicy() throws ApisResourceAccessException, DataShareException, + JsonParseException, JsonMappingException, com.fasterxml.jackson.core.JsonProcessingException, IOException { + Map> typeAndSubTypeMap = new HashMap<>(); + 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); + ObjectMapper mapper = new ObjectMapper(); + 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; + + } + + public List removeRejectedIds(List matchedRegIds) { + List matchedRidsWithoutRejected = new ArrayList<>(); + List matchedRegistrationStatusEntities = packetInfoDao + .getWithoutStatusCode(matchedRegIds, RegistrationStatusCode.REJECTED.toString()); + matchedRidsWithoutRejected.addAll((matchedRegistrationStatusEntities).stream() + .map(RegistrationStatusEntity::getId).collect(Collectors.toList())); + return matchedRidsWithoutRejected; + } } 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 3da51acf45c..79696b745f1 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 @@ -2,12 +2,17 @@ package io.mosip.registration.processor.packet.storage.utils; import static org.junit.Assert.assertEquals; +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.LinkedHashMap; +import java.util.LinkedList; import java.util.List; +import java.util.Map; import org.assertj.core.util.Lists; import org.junit.Before; @@ -20,15 +25,33 @@ import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.databind.JsonMappingException; +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.core.util.exception.JsonProcessingException; import io.mosip.registration.processor.core.constant.AbisConstant; +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.BiometricRecordValidationException; +import io.mosip.registration.processor.core.exception.DataShareException; import io.mosip.registration.processor.core.exception.PacketManagerException; +import io.mosip.registration.processor.core.http.ResponseWrapper; 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.Filter; +import io.mosip.registration.processor.core.packet.dto.abis.ShareableAttributes; +import io.mosip.registration.processor.core.packet.dto.abis.Source; import io.mosip.registration.processor.core.spi.packetmanager.PacketInfoManager; +import io.mosip.registration.processor.core.spi.restclient.RegistrationProcessorRestClientService; 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; @@ -66,6 +89,8 @@ public class ABISHandlerUtilTest { @Mock private IdRepoService idRepoService; + @Mock + private RegistrationProcessorRestClientService registrationProcessorRestClientService; @Before @@ -167,4 +192,148 @@ public void testReturnAllInprogress() throws ApisResourceAccessException, JsonPr assertEquals(1, uniqueRids.size()); } + 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 List getFaceList() { + return Arrays.asList("Face"); + } + + 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); + + biometricRecord.getSegments().add(birType1); + } + + return biometricRecord; + } + + private void mockDataSharePolicy(List shareableBiometricList) throws ApisResourceAccessException { + when(registrationProcessorRestClientService.getApi(any(), any(), anyString(), anyString(), any())) + .thenReturn(getMockDataSharePolicy(shareableBiometricList)); + } + + private ResponseWrapper> getMockDataSharePolicy( + List shareableBiometricList) { + + ObjectMapper mapper = new ObjectMapper(); + + List attr = new LinkedList<>(); + if (shareableBiometricList != null && !shareableBiometricList.isEmpty()) { + + ShareableAttributes shareableAttributes = new ShareableAttributes(); + List sourceList = new ArrayList<>(); + + for (BiometricType bioType : shareableBiometricList) { + Filter filter = new Filter(); + filter.setType(bioType.value()); + if (BiometricType.FINGER.equals(bioType)) { + filter.setSubType(getFingerList()); + } else if (BiometricType.FINGER.equals(bioType)) { + filter.setSubType(getIrisList()); + } + + 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 testcreateTypeSubtypeMapping() throws ApisResourceAccessException, JsonParseException, + JsonMappingException, DataShareException, com.fasterxml.jackson.core.JsonProcessingException, IOException { + mockDataSharePolicy(Lists.newArrayList(BiometricType.FACE, BiometricType.FINGER, BiometricType.IRIS)); + Map> typeAndSubtypMap = abisHandlerUtil.createBiometricTypeSubtypeMappingFromAbispolicy(); + assertEquals(3, typeAndSubtypMap.size()); + + } + + @Test(expected = BiometricRecordValidationException.class) + public void testValidateBiomtericWithModalitiesNull() + throws JsonParseException, JsonMappingException, BiometricRecordValidationException, IOException { + abisHandlerUtil.validateBiometricRecord(null, null); + + } + + @Test(expected = BiometricRecordValidationException.class) + public void testValidateBiomtericWithBiometricRecordNull() + throws JsonParseException, JsonMappingException, BiometricRecordValidationException, IOException { + List modalities = 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"); + abisHandlerUtil.validateBiometricRecord(null, modalities); + + } + + @Test(expected = BiometricRecordValidationException.class) + public void testValidateBiometricWithEmptyBDB() + throws JsonParseException, JsonMappingException, BiometricRecordValidationException, IOException { + List modalities=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"); + abisHandlerUtil.validateBiometricRecord(getBiometricRecord(modalities, true), modalities); + + } + + @Test + public void testValidateBiometricSuccess() + throws JsonParseException, JsonMappingException, BiometricRecordValidationException, IOException { + List modalities = 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"); + abisHandlerUtil.validateBiometricRecord(getBiometricRecord(modalities, false), modalities); + + } }