From a127eb7f6960e179fc10566a77003fc245f42803 Mon Sep 17 00:00:00 2001 From: Vishwa Date: Thu, 13 Jul 2023 11:48:50 +0530 Subject: [PATCH 01/38] Merge pull request #1752 from sowmya695/health_check_camel MOSIP-28445 Removed DB health check for camel --- .../core/abstractverticle/MosipVerticleAPIManager.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/abstractverticle/MosipVerticleAPIManager.java b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/abstractverticle/MosipVerticleAPIManager.java index 79211878324..680a7ca63ae 100644 --- a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/abstractverticle/MosipVerticleAPIManager.java +++ b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/abstractverticle/MosipVerticleAPIManager.java @@ -162,7 +162,9 @@ public void configureHealthCheckEndpoint(Vertx vertx, Router router, final Strin } healthCheckHandler.register("diskSpace", healthCheckTimeOut, healthCheckHandler::dispSpaceHealthChecker); + if (!servletPath.contains("camel")) { healthCheckHandler.register("db", healthCheckTimeOut, healthCheckHandler::databaseHealthChecker); + } } private boolean checkServletPath(String servletPath) { From 2b7da59156d6af77703fda8e38dc590e02b97d0e Mon Sep 17 00:00:00 2001 From: Vishwa Date: Mon, 17 Jul 2023 15:11:51 +0530 Subject: [PATCH 02/38] Merge pull request #1753 from sowmya695/MOSIP-28478 MOSIP-28478 Code fix --- .../abis/handler/stage/AbisHandlerStage.java | 58 +- .../stage/test/AbisHandlerStageTest.java | 2052 +++++++++-------- 2 files changed, 1075 insertions(+), 1035 deletions(-) diff --git a/registration-processor/core-processor/registration-processor-abis-handler-stage/src/main/java/io/mosip/registration/processor/abis/handler/stage/AbisHandlerStage.java b/registration-processor/core-processor/registration-processor-abis-handler-stage/src/main/java/io/mosip/registration/processor/abis/handler/stage/AbisHandlerStage.java index 54468359d26..d92a2c2e35d 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,7 +1,6 @@ package io.mosip.registration.processor.abis.handler.stage; import java.io.IOException; -import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashMap; @@ -12,9 +11,9 @@ import java.util.UUID; import java.util.stream.Collectors; -import io.mosip.kernel.core.util.StringUtils; -import io.mosip.registration.processor.packet.storage.utils.PacketManagerService; import org.apache.commons.lang3.exception.ExceptionUtils; +import org.json.JSONArray; +import org.json.JSONException; import org.json.simple.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; @@ -42,12 +41,10 @@ import io.mosip.kernel.core.logger.spi.Logger; import io.mosip.kernel.core.util.DateUtils; import io.mosip.kernel.core.util.JsonUtils; +import io.mosip.kernel.core.util.StringUtils; import io.mosip.kernel.core.util.exception.JsonProcessingException; import io.mosip.registration.processor.abis.handler.constant.AbisHandlerStageConstant; import io.mosip.registration.processor.abis.handler.dto.DataShareResponseDto; -import io.mosip.registration.processor.core.packet.dto.datashare.Filter; -import io.mosip.registration.processor.core.packet.dto.datashare.ShareableAttributes; -import io.mosip.registration.processor.core.packet.dto.datashare.Source; import io.mosip.registration.processor.abis.handler.exception.AbisHandlerException; import io.mosip.registration.processor.abis.handler.exception.DataShareException; import io.mosip.registration.processor.abis.queue.dto.AbisQueueDetails; @@ -63,16 +60,19 @@ import io.mosip.registration.processor.core.code.EventType; import io.mosip.registration.processor.core.code.ModuleName; import io.mosip.registration.processor.core.code.RegistrationTransactionStatusCode; +import io.mosip.registration.processor.core.constant.JsonConstant; import io.mosip.registration.processor.core.constant.LoggerFileConstant; import io.mosip.registration.processor.core.constant.MappingJsonConstants; import io.mosip.registration.processor.core.constant.PolicyConstant; import io.mosip.registration.processor.core.constant.ProviderStageName; import io.mosip.registration.processor.core.exception.ApisResourceAccessException; +import io.mosip.registration.processor.core.exception.PacketManagerException; import io.mosip.registration.processor.core.exception.util.PlatformErrorMessages; import io.mosip.registration.processor.core.exception.util.PlatformSuccessMessages; import io.mosip.registration.processor.core.http.ResponseWrapper; import io.mosip.registration.processor.core.logger.LogDescription; import io.mosip.registration.processor.core.logger.RegProcessorLogger; +import io.mosip.registration.processor.core.packet.dto.FieldValue; import io.mosip.registration.processor.core.packet.dto.Identity; import io.mosip.registration.processor.core.packet.dto.abis.AbisIdentifyRequestDto; import io.mosip.registration.processor.core.packet.dto.abis.AbisIdentifyRequestGalleryDto; @@ -82,12 +82,16 @@ import io.mosip.registration.processor.core.packet.dto.abis.ReferenceIdDto; import io.mosip.registration.processor.core.packet.dto.abis.RegBioRefDto; import io.mosip.registration.processor.core.packet.dto.abis.RegDemoDedupeListDto; +import io.mosip.registration.processor.core.packet.dto.datashare.Filter; +import io.mosip.registration.processor.core.packet.dto.datashare.ShareableAttributes; +import io.mosip.registration.processor.core.packet.dto.datashare.Source; import io.mosip.registration.processor.core.spi.packetmanager.PacketInfoManager; import io.mosip.registration.processor.core.spi.restclient.RegistrationProcessorRestClientService; import io.mosip.registration.processor.core.status.util.StatusUtil; import io.mosip.registration.processor.core.status.util.TrimExceptionMessage; import io.mosip.registration.processor.core.util.JsonUtil; import io.mosip.registration.processor.packet.storage.dto.ApplicantInfoDto; +import io.mosip.registration.processor.packet.storage.utils.PacketManagerService; import io.mosip.registration.processor.packet.storage.utils.PriorityBasedPacketManagerService; import io.mosip.registration.processor.packet.storage.utils.Utilities; import io.mosip.registration.processor.rest.client.audit.builder.AuditLogRequestBuilder; @@ -208,6 +212,9 @@ public class AbisHandlerStage extends MosipVerticleAPIManager { private static final String DATETIME_PATTERN = "mosip.registration.processor.datetime.pattern"; + @Value("#{T(java.util.Arrays).asList('${mosip.regproc.common.before-cbeff-others-attibute.reg-client-versions:}')}") + private List regClientVersionsBeforeCbeffOthersAttritube; + /** * Deploy verticle. */ @@ -502,7 +509,7 @@ private void createInsertRequest(List abisQueueDetails, String abisRequestDto.setReqBatchId(batchId); abisRequestDto.setRefRegtrnId(transactionId); - + abisRequestDto.setStatusCode(AbisStatusCode.IN_PROGRESS.toString()); abisRequestDto.setStatusComment(null); abisRequestDto.setLangCode(AbisHandlerStageConstant.ENG); @@ -539,7 +546,7 @@ private void createInsertRequest(List abisQueueDetails, String * @param id the id * @param bioRefId the bio ref id * @param description - * @param status + * @param status * @return the insert request bytes */ private byte[] getInsertRequestBytes(String regId, String id, String process, String bioRefId, @@ -608,7 +615,7 @@ private String getDataShareUrl(String id, String process) throws Exception { priorityBasedPacketManagerService.getMetaInfo(id, process, ProviderStageName.BIO_DEDUPE)); } - byte[] content = cbeffutil.createXML(filterExceptionBiometrics(biometricRecord).getSegments()); + byte[] content = cbeffutil.createXML(filterExceptionBiometrics(biometricRecord,id,process).getSegments()); MultiValueMap map = new LinkedMultiValueMap<>(); map.add("name", individualBiometricsLabel); @@ -711,18 +718,47 @@ private void validateBiometricRecord(BiometricRecord biometricRecord, List segments = biometricRecord.getSegments().stream().filter(bio -> { Map othersMap = bio.getOthers().entrySet().stream() .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue())); return (othersMap == null || !othersMap.containsKey("EXCEPTION")) ? true : !(Boolean.parseBoolean(othersMap.get("EXCEPTION"))); - }).collect(Collectors.toList()); + }).collect(Collectors.toList()); BiometricRecord biorecord = new BiometricRecord(); biorecord.setSegments(segments); return biorecord; } + private String getRegClientVersionFromMetaInfo(String id, String process, Map metaInfoMap) + throws ApisResourceAccessException, PacketManagerException, IOException, JSONException { + String metadata = metaInfoMap.get(JsonConstant.METADATA); + String version = null; + if (StringUtils.isNotEmpty(metadata)) { + JSONArray jsonArray = new JSONArray(metadata); + + for (int i = 0; i < jsonArray.length(); i++) { + if (!jsonArray.isNull(i)) { + org.json.JSONObject jsonObject = (org.json.JSONObject) jsonArray.get(i); + FieldValue fieldValue = mapper.readValue(jsonObject.toString(), FieldValue.class); + if (fieldValue.getLabel().equalsIgnoreCase(JsonConstant.REGCLIENTVERSION)) { + version = fieldValue.getValue(); + break; + } + } + } + } + return version; + } + public Map> createTypeSubtypeMapping() throws ApisResourceAccessException, DataShareException, IOException { 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 74e9066d17c..7cf1e4e112c 100644 --- a/registration-processor/core-processor/registration-processor-abis-handler-stage/src/test/java/io/mosip/registration/processor/abis/handler/stage/test/AbisHandlerStageTest.java +++ b/registration-processor/core-processor/registration-processor-abis-handler-stage/src/test/java/io/mosip/registration/processor/abis/handler/stage/test/AbisHandlerStageTest.java @@ -1,1025 +1,1029 @@ -package io.mosip.registration.processor.abis.handler.stage.test; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.when; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; - -import org.assertj.core.util.Lists; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.ArgumentMatchers; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.Spy; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; -import org.springframework.core.env.Environment; -import org.springframework.http.MediaType; -import org.springframework.test.util.ReflectionTestUtils; - -import com.fasterxml.jackson.databind.ObjectMapper; - -import io.mosip.kernel.biometrics.constant.BiometricType; -import io.mosip.kernel.biometrics.constant.QualityType; -import io.mosip.kernel.biometrics.entities.BDBInfo; -import io.mosip.kernel.biometrics.entities.BIR; -import io.mosip.kernel.biometrics.entities.BiometricRecord; -import io.mosip.kernel.biometrics.entities.RegistryIDType; -import io.mosip.kernel.biometrics.spi.CbeffUtil; -import io.mosip.kernel.core.util.JsonUtils; -import io.mosip.kernel.core.util.exception.JsonProcessingException; -import io.mosip.registration.processor.abis.handler.dto.DataShare; -import io.mosip.registration.processor.abis.handler.dto.DataShareResponseDto; -import io.mosip.registration.processor.abis.handler.stage.AbisHandlerStage; -import io.mosip.registration.processor.abis.queue.dto.AbisQueueDetails; -import io.mosip.registration.processor.core.abstractverticle.EventDTO; -import io.mosip.registration.processor.core.abstractverticle.HealthCheckDTO; -import io.mosip.registration.processor.core.abstractverticle.MessageBusAddress; -import io.mosip.registration.processor.core.abstractverticle.MessageDTO; -import io.mosip.registration.processor.core.abstractverticle.MosipEventBus; -import io.mosip.registration.processor.core.common.rest.dto.ErrorDTO; -import io.mosip.registration.processor.core.constant.PolicyConstant; -import io.mosip.registration.processor.core.exception.ApisResourceAccessException; -import io.mosip.registration.processor.core.exception.PacketManagerException; -import io.mosip.registration.processor.core.exception.RegistrationProcessorCheckedException; -import io.mosip.registration.processor.core.http.ResponseWrapper; -import io.mosip.registration.processor.core.logger.LogDescription; -import io.mosip.registration.processor.core.packet.dto.Identity; -import io.mosip.registration.processor.core.packet.dto.abis.AbisApplicationDto; -import io.mosip.registration.processor.core.packet.dto.abis.AbisIdentifyRequestDto; -import io.mosip.registration.processor.core.packet.dto.abis.AbisInsertRequestDto; -import io.mosip.registration.processor.core.packet.dto.abis.AbisRequestDto; -import io.mosip.registration.processor.core.packet.dto.abis.RegBioRefDto; -import io.mosip.registration.processor.core.packet.dto.abis.RegDemoDedupeListDto; -import io.mosip.registration.processor.core.packet.dto.datashare.Filter; -import io.mosip.registration.processor.core.packet.dto.datashare.ShareableAttributes; -import io.mosip.registration.processor.core.packet.dto.datashare.Source; -import io.mosip.registration.processor.core.spi.eventbus.EventHandler; -import io.mosip.registration.processor.core.spi.packetmanager.PacketInfoManager; -import io.mosip.registration.processor.core.spi.restclient.RegistrationProcessorRestClientService; -import io.mosip.registration.processor.packet.storage.dto.ApplicantInfoDto; -import io.mosip.registration.processor.packet.storage.utils.PacketManagerService; -import io.mosip.registration.processor.packet.storage.utils.PriorityBasedPacketManagerService; -import io.mosip.registration.processor.packet.storage.utils.Utilities; -import io.mosip.registration.processor.rest.client.audit.builder.AuditLogRequestBuilder; -import io.mosip.registration.processor.rest.client.audit.dto.AuditResponseDto; -import io.mosip.registration.processor.status.dto.InternalRegistrationStatusDto; -import io.mosip.registration.processor.status.dto.RegistrationStatusDto; -import io.mosip.registration.processor.status.service.RegistrationStatusService; -import io.vertx.core.AsyncResult; -import io.vertx.core.Handler; -import io.vertx.core.Vertx; - -@RunWith(PowerMockRunner.class) -@PrepareForTest({ JsonUtils.class }) -@PowerMockIgnore({ "com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "javax.management.*", "javax.net.ssl.*" }) -public class AbisHandlerStageTest { - - @Mock - private AuditLogRequestBuilder auditLogRequestBuilder; - - @Mock - private RegistrationStatusService registrationStatusService; - - @Mock - private PacketInfoManager packetInfoManager; - - private InternalRegistrationStatusDto registrationStatusDto = new InternalRegistrationStatusDto(); - - @Mock - private Utilities utility; - - @Spy - private ObjectMapper mapper = new ObjectMapper(); - - @Mock - private PriorityBasedPacketManagerService packetManagerService; - - @Mock - private PacketManagerService packetService; - - @Mock - private LogDescription description; - - List abisApplicationDtos = new ArrayList<>(); - - List bioRefDtos = new ArrayList<>(); - - List regDemoDedupeListDtoList = new ArrayList<>(); - - List abisRequestDtoList = new ArrayList<>(); - - Map tags = new HashMap(); - - @Mock - private Environment env; - - @Mock - private RegistrationProcessorRestClientService registrationProcessorRestClientService; - - @Mock - private CbeffUtil cbeffutil; - - @InjectMocks - private AbisHandlerStage abisHandlerStage = new AbisHandlerStage() { - @Override - public MosipEventBus getEventBus(Object verticleName, String url, int instanceNumber) { - vertx = Vertx.vertx(); - - return new MosipEventBus() { - - @Override - public Vertx getEventbus() { - return vertx; - } - - @Override - public void consume(MessageBusAddress fromAddress, - EventHandler>> eventHandler) { - - } - - @Override - public void consumeAndSend(MessageBusAddress fromAddress, MessageBusAddress toAddress, - EventHandler>> eventHandler) { - - } - - @Override - public void send(MessageBusAddress toAddress, MessageDTO message) { - - } - - @Override - public void consumerHealthCheck(Handler eventHandler, String address) { - // TODO Auto-generated method stub - - } - - @Override - public void senderHealthCheck(Handler eventHandler, String address) { - // TODO Auto-generated method stub - - } - - }; - } - - @Override - public void consumeAndSend(MosipEventBus mosipEventBus, MessageBusAddress fromAddress, - MessageBusAddress toAddress, long messageExpiryTimeLimit) { - } - - @Override - public Integer getPort() { - return 8080; - }; - }; - - @Before - public void setUp() throws Exception { - ReflectionTestUtils.setField(abisHandlerStage, "maxResults", "30"); - ReflectionTestUtils.setField(abisHandlerStage, "targetFPIR", "30"); - ReflectionTestUtils.setField(abisHandlerStage, "workerPoolSize", 10); - ReflectionTestUtils.setField(abisHandlerStage, "messageExpiryTimeLimit", Long.valueOf(0)); - ReflectionTestUtils.setField(abisHandlerStage, "clusterManagerUrl", "/dummyPath"); - ReflectionTestUtils.setField(abisHandlerStage, "httpProtocol", "http"); - ReflectionTestUtils.setField(abisHandlerStage, "internalDomainName", "localhost"); - Mockito.when(env.getProperty("mosip.registration.processor.datetime.pattern")) - .thenReturn("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); - - Map> biometricModalitySegmentsMap = new HashMap(); - Map> biometricModalitySegmentsMapInfant = new HashMap(); - biometricModalitySegmentsMapInfant.put("Face", getFaceList()); - biometricModalitySegmentsMap.put("Finger", getFingerList()); - biometricModalitySegmentsMap.put("Iris", getIrisList()); - biometricModalitySegmentsMap.put("Face", getFaceList()); - ReflectionTestUtils.setField(abisHandlerStage, "biometricModalitySegmentsMapInfant", biometricModalitySegmentsMapInfant); - ReflectionTestUtils.setField(abisHandlerStage, "biometricModalitySegmentsMapMinor", biometricModalitySegmentsMap); - ReflectionTestUtils.setField(abisHandlerStage, "biometricModalitySegmentsMapAdult", biometricModalitySegmentsMap); - ReflectionTestUtils.setField(abisHandlerStage, "exceptionSegmentsMap", getExceptionModalityMap()); - - Mockito.when(env.getProperty("DATASHARECREATEURL")).thenReturn("/v1/datashare/create"); - AbisApplicationDto dto = new AbisApplicationDto(); - dto.setCode("ABIS1"); - abisApplicationDtos.add(dto); - - Mockito.doNothing().when(description).setMessage(any()); - Mockito.when(description.getMessage()).thenReturn("description"); - - - Mockito.when(packetManagerService.getBiometrics(any(), any(), any(), any(), any())).thenReturn(getBiometricRecord(Arrays.asList("Left Thumb" ,"Right Thumb" , "Left MiddleFinger" , - "Left RingFinger" ,"Left LittleFinger" ,"Left IndexFinger" ,"Right MiddleFinger" , - "Right RingFinger" ,"Right LittleFinger" ,"Right IndexFinger" , - "Left" ,"Right","Face"),false)); - mockDataSharePolicy(Lists.newArrayList(BiometricType.FINGER,BiometricType.IRIS,BiometricType.FACE)); - - List list = new LinkedList<>(); - setMetaInfoMap(list); - - //Mockito.doNothing().when(registrationStatusDto).setLatestTransactionStatusCode(any()); - Mockito.doNothing().when(registrationStatusService).updateRegistrationStatus(any(), any(), any()); - - Mockito.when(packetInfoManager.getAbisRequestsByBioRefId(any())).thenReturn(abisRequestDtoList); - - AbisQueueDetails abisQueueDetails = new AbisQueueDetails(); - abisQueueDetails.setName("ABIS1"); - List abisQueueDetailsList = new ArrayList<>(); - abisQueueDetailsList.add(abisQueueDetails); - Mockito.when(utility.getAbisQueueDetails()).thenReturn(abisQueueDetailsList); - - AuditResponseDto auditResponseDto = new AuditResponseDto(); - ResponseWrapper responseWrapper = new ResponseWrapper<>(); - responseWrapper.setResponse(auditResponseDto); - Mockito.when(auditLogRequestBuilder.createAuditRequestBuilder(any(), any(), any(), any(), any(), any(), any())) - .thenReturn(responseWrapper); - - DataShareResponseDto dataShareResponseDto = new DataShareResponseDto(); - DataShare dataShare = new DataShare(); - dataShare.setUrl("http://localhost"); - dataShareResponseDto.setDataShare(dataShare); - - mockDataSharePolicy(Lists.newArrayList(BiometricType.FACE, BiometricType.FINGER)); - - Mockito.when(registrationProcessorRestClientService.postApi(anyString(), any(MediaType.class), any(), any(), - any(), any(), any())).thenReturn(dataShareResponseDto); - - Mockito.when(cbeffutil.createXML(any())).thenReturn(new byte[2048]); - } - - private Map getExceptionModalityMap() { - Map exceptionMap = new HashMap(); - exceptionMap.put("Left Thumb" , "leftThumb"); - exceptionMap.put("Right Thumb" , "rightThumb"); - exceptionMap.put("Left MiddleFinger" , "leftMiddle"); - exceptionMap.put("Left RingFinger" , "leftRing"); - exceptionMap.put("Left LittleFinger" , "leftLittle"); - exceptionMap.put("Left IndexFinger" , "leftIndex"); - exceptionMap.put("Right MiddleFinger" , "rightMiddle"); - exceptionMap.put("Right RingFinger" , "rightRing"); - exceptionMap.put("Right LittleFinger" , "rightLittle"); - exceptionMap.put("Right IndexFinger" , "rightIndex"); - exceptionMap.put("Left" , "leftEye"); - exceptionMap.put("Right" , "rightEye"); - exceptionMap.put("Face" , "face"); - - return exceptionMap; - } - - private List getFaceList() { - return Arrays.asList("Face"); - } - - private List getIrisList() { - return Arrays.asList("Left", "Right"); - - } - - private List getFingerList() { - return Arrays.asList("Left Thumb", "Left LittleFinger", "Left IndexFinger", "Left MiddleFinger", - "Left RingFinger", "Right Thumb", "Right LittleFinger", - "Right IndexFinger", "Right MiddleFinger", - "Right RingFinger"); - } - - private void mockDataSharePolicy(List sherableBiometricList) throws ApisResourceAccessException { - when(registrationProcessorRestClientService.getApi(any(), any(), anyString(), anyString(), any())) - .thenReturn(getMockDataSharePolicy(sherableBiometricList)); - } - - private ResponseWrapper> getMockDataSharePolicy( - List sherableBiometricList) { - - ObjectMapper mapper = new ObjectMapper(); - - List attr = new LinkedList<>(); - if (sherableBiometricList != null && !sherableBiometricList.isEmpty()) { - - ShareableAttributes shareableAttributes = new ShareableAttributes(); - List sourceList = new ArrayList<>(); - - for (BiometricType bioType : sherableBiometricList) { - Filter filter = new Filter(); - filter.setType(bioType.value()); - Source src = new Source(); - src.setFilter(Lists.newArrayList(filter)); - sourceList.add(src); - } - - shareableAttributes.setSource(sourceList); - attr = Lists.newArrayList(shareableAttributes); - } - - ResponseWrapper> policy = new ResponseWrapper<>(); - LinkedHashMap policies = new LinkedHashMap<>(); - LinkedHashMap sharableAttributes = new LinkedHashMap<>(); - sharableAttributes.put(PolicyConstant.SHAREABLE_ATTRIBUTES, attr); - policies.put(PolicyConstant.POLICIES, sharableAttributes); - policy.setResponse(policies); - - return policy; - } - - @Test - public void testDeployVerticle() { - abisHandlerStage.deployVerticle(); - } - - @Test - public void testDemoToAbisHandlerTOMiddlewareSuccess() throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { - registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); - registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); - Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); - Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); - Mockito.when(packetInfoManager.getAllAbisDetails()).thenReturn(abisApplicationDtos); - - mockDataSharePolicy(Lists.newArrayList(BiometricType.IRIS, BiometricType.FINGER, BiometricType.FACE)); - Mockito.when(packetInfoManager.getBioRefIdByRegId(any())).thenReturn(bioRefDtos); - tags.put("AGE_GROUP", "ADULT"); - Mockito.when(packetService.getAllTags(any())).thenReturn(tags); - - Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); - Mockito.doNothing().when(packetInfoManager).saveAbisRequest(any(), any(), any()); - - RegDemoDedupeListDto regDemoDedupeListDto = new RegDemoDedupeListDto(); - regDemoDedupeListDto.setMatchedRegId("10003100030001520190422074511"); - regDemoDedupeListDtoList.add(regDemoDedupeListDto); - Mockito.when(packetInfoManager.getDemoListByTransactionId(any())).thenReturn(regDemoDedupeListDtoList); - - MessageDTO dto = new MessageDTO(); - dto.setRid("10003100030001520190422074511"); - MessageDTO result = abisHandlerStage.process(dto); - - assertTrue(result.getMessageBusAddress().getAddress().equalsIgnoreCase("abis-middle-ware-bus-in")); - } - - @Test - public void testBioToAbisHandlerToMiddlewareSuccess() throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { - registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); - registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); - Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); - Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); - Mockito.when(packetInfoManager.getAllAbisDetails()).thenReturn(abisApplicationDtos); - - mockDataSharePolicy(Lists.newArrayList(BiometricType.IRIS, BiometricType.FINGER, BiometricType.FACE)); - RegBioRefDto regBioRefDto = new RegBioRefDto(); - regBioRefDto.setBioRefId("1234567890"); - bioRefDtos.add(regBioRefDto); - Mockito.when(packetInfoManager.getBioRefIdByRegId(any())).thenReturn(bioRefDtos); - tags.put("AGE_GROUP", "ADULT"); - Mockito.when(packetService.getAllTags(any())).thenReturn(tags); - - Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); - Mockito.doNothing().when(packetInfoManager).saveAbisRequest(any(), any(), any()); - - RegDemoDedupeListDto regDemoDedupeListDto = new RegDemoDedupeListDto(); - regDemoDedupeListDto.setMatchedRegId("10003100030001520190422074511"); - regDemoDedupeListDtoList.add(regDemoDedupeListDto); - Mockito.when(packetInfoManager.getDemoListByTransactionId(any())).thenReturn(regDemoDedupeListDtoList); - - MessageDTO dto = new MessageDTO(); - dto.setRid("10003100030001520190422074511"); - MessageDTO result = abisHandlerStage.process(dto); - - assertTrue(result.getMessageBusAddress().getAddress().equalsIgnoreCase("abis-middle-ware-bus-in")); - } - - @Test - public void testMiddlewareToAbisHandlerToDemoSuccess() { - registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); - registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); - Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); - Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.TRUE); - - MessageDTO dto = new MessageDTO(); - dto.setRid("10003100030001520190422074511"); - MessageDTO result = abisHandlerStage.process(dto); - - assertTrue(result.getMessageBusAddress().getAddress().equalsIgnoreCase("demo-dedupe-bus-in")); - } - - @Test - public void testMiddlewareToAbisHandlerToBioSuccess() { - registrationStatusDto.setLatestTransactionTypeCode("BIOGRAPHIC_VERIFICATION"); - registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); - Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); - Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.TRUE); - - MessageDTO dto = new MessageDTO(); - dto.setRid("10003100030001520190422074511"); - MessageDTO result = abisHandlerStage.process(dto); - - assertTrue(result.getMessageBusAddress().getAddress().equalsIgnoreCase("bio-dedupe-bus-in")); - } - - @Test - public void testDemoDedupeDataNotFound() { - registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); - registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); - Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); - Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); - Mockito.when(packetInfoManager.getAllAbisDetails()).thenReturn(abisApplicationDtos); - - Mockito.when(packetInfoManager.getBioRefIdByRegId(any())).thenReturn(bioRefDtos); - - Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); - Mockito.doNothing().when(packetInfoManager).saveAbisRequest(any(), any(), any()); - - Mockito.when(packetInfoManager.getDemoListByTransactionId(any())).thenReturn(regDemoDedupeListDtoList); - - MessageDTO dto = new MessageDTO(); - dto.setRid("10003100030001520190422074511"); - MessageDTO result = abisHandlerStage.process(dto); - - assertTrue(result.getInternalError()); - assertTrue(result.getIsValid()); - } - - @Test - public void testReprocessInsert() throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { - registrationStatusDto.setLatestTransactionTypeCode("BIOGRAPHIC_VERIFICATION"); - registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); - Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); - Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); - List appCodeList = new ArrayList<>(); - appCodeList.add("ABIS1"); - Mockito.when(packetInfoManager.getAbisProcessedRequestsAppCodeByBioRefId(any(), any(), any())) - .thenReturn(appCodeList); - - Mockito.when(packetInfoManager.getAllAbisDetails()).thenReturn(abisApplicationDtos); - - RegBioRefDto bioRefDto = new RegBioRefDto(); - bioRefDtos.add(bioRefDto); - Mockito.when(packetInfoManager.getBioRefIdByRegId(any())).thenReturn(bioRefDtos); - - Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); - - AbisRequestDto abisRequestDto = new AbisRequestDto(); - abisRequestDto.setAbisAppCode("ABIS1"); - abisRequestDto.setStatusCode("IN-PROGRESS"); - abisRequestDtoList.add(abisRequestDto); - Mockito.when(packetInfoManager.getAbisRequestsByBioRefId(any())).thenReturn(abisRequestDtoList); - tags.put("AGE_GROUP", "ADULT"); - Mockito.when(packetService.getAllTags(any())).thenReturn(tags); - - Mockito.doNothing().when(packetInfoManager).saveAbisRequest(any(), any(), any()); - - Mockito.when(packetInfoManager.getDemoListByTransactionId(any())).thenReturn(regDemoDedupeListDtoList); - - MessageDTO dto = new MessageDTO(); - dto.setRid("10003100030001520190422074511"); - MessageDTO result = abisHandlerStage.process(dto); - - assertFalse(result.getInternalError()); - assertTrue(result.getIsValid()); - } - - @Test - public void testAbisDetailsNotFound() throws RegistrationProcessorCheckedException { - registrationStatusDto.setLatestTransactionTypeCode("BIOGRAPHIC_VERIFICATION"); - registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); - Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); - Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); - - List abisQueueDetails = new ArrayList<>(); - Mockito.when(utility.getAbisQueueDetails()).thenReturn(abisQueueDetails); - - MessageDTO dto = new MessageDTO(); - dto.setRid("10003100030001520190422074511"); - MessageDTO result = abisHandlerStage.process(dto); - - assertTrue(result.getInternalError()); - } - - @Test - public void testPotentialMatchNotFound() throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { - registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); - registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); - Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); - Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); - - mockDataSharePolicy(Lists.newArrayList(BiometricType.IRIS, BiometricType.FINGER, BiometricType.FACE)); - tags.put("AGE_GROUP", "ADULT"); - Mockito.when(packetService.getAllTags(any())).thenReturn(tags); - - Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); - Mockito.doNothing().when(packetInfoManager).saveAbisRequest(any(), any(), any()); - - Mockito.when(packetInfoManager.getDemoListByTransactionId(any())).thenReturn(Arrays.asList()); - - MessageDTO dto = new MessageDTO(); - dto.setRid("10003100030001520190422074511"); - MessageDTO result = abisHandlerStage.process(dto); - - assertTrue(result.getInternalError()); - } - - @Test - public void testIdentifyRequestJsonProcessingException() throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { - registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); - registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); - Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); - Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); - - mockDataSharePolicy(Lists.newArrayList(BiometricType.IRIS, BiometricType.FINGER, BiometricType.FACE)); - Mockito.when(packetInfoManager.getBioRefIdByRegId(any())).thenReturn(bioRefDtos); - tags.put("AGE_GROUP", "ADULT"); - Mockito.when(packetService.getAllTags(any())).thenReturn(tags); - - Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); - Mockito.doNothing().when(packetInfoManager).saveAbisRequest(any(), any(), any()); - - RegDemoDedupeListDto regDemoDedupeListDto = new RegDemoDedupeListDto(); - regDemoDedupeListDto.setMatchedRegId("10003100030001520190422074511"); - regDemoDedupeListDtoList.add(regDemoDedupeListDto); - Mockito.when(packetInfoManager.getDemoListByTransactionId(any())).thenReturn(regDemoDedupeListDtoList); - - PowerMockito.mockStatic(JsonUtils.class); - PowerMockito.when(JsonUtils.javaObjectToJsonString(any())).thenReturn("value").thenThrow(JsonProcessingException.class); - MessageDTO dto = new MessageDTO(); - dto.setRid("10003100030001520190422074511"); - MessageDTO result = abisHandlerStage.process(dto); - - assertTrue(result.getInternalError()); - } - - @Test - public void testInsertRequestJsonProcessingException() throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { - registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); - registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); - Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); - Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); - - mockDataSharePolicy(Lists.newArrayList(BiometricType.IRIS, BiometricType.FINGER, BiometricType.FACE)); - tags.put("AGE_GROUP", "MINOR"); - Mockito.when(packetService.getAllTags(any())).thenReturn(tags); - - Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); - - PowerMockito.mockStatic(JsonUtils.class); - PowerMockito.when(JsonUtils.javaObjectToJsonString(any())).thenThrow(JsonProcessingException.class); - MessageDTO dto = new MessageDTO(); - dto.setRid("10003100030001520190422074511"); - MessageDTO result = abisHandlerStage.process(dto); - - assertTrue(result.getInternalError()); - } - - @Test - public void testDataShareResponseNullException() throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { - registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); - registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); - Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); - Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); - - mockDataSharePolicy(Lists.newArrayList(BiometricType.IRIS, BiometricType.FINGER, BiometricType.FACE)); - tags.put("AGE_GROUP", "MINOR"); - Mockito.when(packetService.getAllTags(any())).thenReturn(tags); - - Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); - - DataShareResponseDto dataShareResponseDto = new DataShareResponseDto(); - ErrorDTO error = new ErrorDTO("ERR-001", "exception occured"); - dataShareResponseDto.setDataShare(null); - dataShareResponseDto.setErrors(Arrays.asList(error)); - Mockito.when(registrationProcessorRestClientService.postApi(anyString(), any(MediaType.class), any(), any(), - any(), any(), any())).thenReturn(dataShareResponseDto); - MessageDTO dto = new MessageDTO(); - dto.setRid("10003100030001520190422074511"); - MessageDTO result = abisHandlerStage.process(dto); - - assertTrue(result.getInternalError()); - } - - @Test - public void testCreateTypeSubtypeMappingResponseNullException() - throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { - registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); - registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); - Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())) - .thenReturn(registrationStatusDto); - Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); - ErrorDTO error = new ErrorDTO("ERR-001", "exception occured"); - ResponseWrapper> policyResponse = new ResponseWrapper<>(); - - policyResponse.setErrors(Arrays.asList(error)); - - Mockito.when(registrationProcessorRestClientService.getApi(any(), any(), anyString(), - anyString(), any())).thenReturn(policyResponse); - Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); - - MessageDTO dto = new MessageDTO(); - dto.setRid("10003100030001520190422074511"); - MessageDTO result = abisHandlerStage.process(dto); - - assertTrue(result.getInternalError()); - } - - @Test - public void testvalidateBiometricRecordModalitiesEmptyException() - throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { - registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); - registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); - Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())) - .thenReturn(registrationStatusDto); - Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); - - mockDataSharePolicy(Lists.newArrayList(BiometricType.IRIS, BiometricType.FINGER, BiometricType.FACE)); - tags.put("AGE_GROUP", "MINOR"); - Mockito.when(packetService.getAllTags(any())).thenReturn(tags); - - Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); - - ResponseWrapper> policyResponse = new ResponseWrapper<>(); - LinkedHashMap response = new LinkedHashMap(); - LinkedHashMap attributes = new LinkedHashMap(); - ShareableAttributes shareableAttributes = new ShareableAttributes(); - shareableAttributes.setSource(Arrays.asList()); - attributes.put(PolicyConstant.SHAREABLE_ATTRIBUTES, Arrays.asList(shareableAttributes)); - response.put(PolicyConstant.POLICIES, attributes); - policyResponse.setResponse(response); - - Mockito.when(registrationProcessorRestClientService.getApi(any(), any(), anyString(), anyString(), any())) - .thenReturn(policyResponse); - - MessageDTO dto = new MessageDTO(); - dto.setRid("10003100030001520190422074511"); - MessageDTO result = abisHandlerStage.process(dto); - - assertTrue(result.getInternalError()); - } - - @Test - public void testvalidateBiometricRecordSegmentEmptyException() - throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { - registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); - registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); - Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())) - .thenReturn(registrationStatusDto); - Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); - - mockDataSharePolicy(Lists.newArrayList(BiometricType.IRIS, BiometricType.FINGER, BiometricType.FACE)); - tags.put("AGE_GROUP", "ADULT"); - Mockito.when(packetService.getAllTags(any())).thenReturn(tags); - BiometricRecord biometricRecord = new BiometricRecord(); - biometricRecord.setSegments(null); - Mockito.when(packetManagerService.getBiometrics(any(), any(), any(), any(), any())).thenReturn(biometricRecord); - Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); - - MessageDTO dto = new MessageDTO(); - dto.setRid("10003100030001520190422074511"); - MessageDTO result = abisHandlerStage.process(dto); - - assertTrue(result.getInternalError()); - } - - @Test - public void testvalidateBiometricRecordOthersMapNullException() - throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { - registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); - registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); - Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())) - .thenReturn(registrationStatusDto); - Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); - - mockDataSharePolicy(Lists.newArrayList(BiometricType.IRIS, BiometricType.FINGER, BiometricType.FACE)); - tags.put("AGE_GROUP", "ADULT"); - Mockito.when(packetService.getAllTags(any())).thenReturn(tags); - BiometricRecord biometricRecord = new BiometricRecord(); - BIR bir = new BIR.BIRBuilder().build(); - BDBInfo bdbInfo = new BDBInfo.BDBInfoBuilder().build(); - bdbInfo.setSubtype(Arrays.asList("Left")); - bdbInfo.setType(Arrays.asList(BiometricType.IRIS)); - bir.setOthers(null); - bir.setBdbInfo(bdbInfo); - biometricRecord.setSegments(Arrays.asList(bir)); - Mockito.when(packetManagerService.getBiometrics(any(), any(), any(), any(), any())).thenReturn(biometricRecord); - Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); - - MessageDTO dto = new MessageDTO(); - dto.setRid("10003100030001520190422074511"); - MessageDTO result = abisHandlerStage.process(dto); - - assertTrue(result.getInternalError()); - } - - @Test - public void testCreateRequestException() throws JsonProcessingException { - registrationStatusDto.setLatestTransactionTypeCode("BIOGRAPHIC_VERIFICATION"); - registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); - Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); - Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); - - Mockito.when(packetInfoManager.getAllAbisDetails()).thenReturn(abisApplicationDtos); - - RegBioRefDto bioRefDto = new RegBioRefDto(); - bioRefDtos.add(bioRefDto); - Mockito.when(packetInfoManager.getBioRefIdByRegId(any())).thenReturn(bioRefDtos); - - Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); - - AbisRequestDto abisRequestDto = new AbisRequestDto(); - abisRequestDto.setAbisAppCode("ABIS1"); - abisRequestDto.setStatusCode("IN-PROGRESS"); - abisRequestDtoList.add(abisRequestDto); - Mockito.when(packetInfoManager.getAbisRequestsByBioRefId(any())).thenReturn(abisRequestDtoList); - - Mockito.doNothing().when(packetInfoManager).saveAbisRequest(any(), any(), any()); - - Mockito.when(packetInfoManager.getDemoListByTransactionId(any())).thenReturn(regDemoDedupeListDtoList); - - PowerMockito.mockStatic(JsonUtils.class); - PowerMockito.when(JsonUtils.javaObjectToJsonString(any(AbisInsertRequestDto.class))) - .thenThrow(JsonProcessingException.class); - - MessageDTO dto = new MessageDTO(); - dto.setRid("10003100030001520190422074511"); - MessageDTO result = abisHandlerStage.process(dto); - - assertTrue(result.getInternalError()); - assertTrue(result.getIsValid()); - } - - @Test - public void testIdentifyRequestException() throws JsonProcessingException { - registrationStatusDto.setLatestTransactionTypeCode("BIOGRAPHIC_VERIFICATION"); - registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); - Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); - Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); - - Mockito.when(packetInfoManager.getAllAbisDetails()).thenReturn(abisApplicationDtos); - - RegBioRefDto bioRefDto = new RegBioRefDto(); - bioRefDtos.add(bioRefDto); - Mockito.when(packetInfoManager.getBioRefIdByRegId(any())).thenReturn(bioRefDtos); - - Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); - - AbisRequestDto abisRequestDto = new AbisRequestDto(); - abisRequestDto.setAbisAppCode("ABIS1"); - abisRequestDto.setStatusCode("IN-PROGRESS"); - abisRequestDtoList.add(abisRequestDto); - Mockito.when(packetInfoManager.getAbisRequestsByBioRefId(any())).thenReturn(abisRequestDtoList); - - Mockito.doNothing().when(packetInfoManager).saveAbisRequest(any(), any(), any()); - - Mockito.when(packetInfoManager.getDemoListByTransactionId(any())).thenReturn(regDemoDedupeListDtoList); - - PowerMockito.mockStatic(JsonUtils.class); - PowerMockito.when(JsonUtils.javaObjectToJsonString(any(AbisInsertRequestDto.class))) - .thenReturn("AbisInsertRequestDto"); - PowerMockito.when(JsonUtils.javaObjectToJsonString(ArgumentMatchers.any(AbisIdentifyRequestDto.class))) - .thenThrow(JsonProcessingException.class); - - MessageDTO dto = new MessageDTO(); - dto.setRid("10003100030001520190422074511"); - MessageDTO result = abisHandlerStage.process(dto); - - assertTrue(result.getInternalError()); - assertTrue(result.getIsValid()); - } - - - @Test - public void bioRecordDataNotFound() - throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { - - defaultMockToProcess(); - - Mockito.when(packetManagerService.getBiometrics(any(), any(), any(), any(), any())).thenReturn(null); - mockDataSharePolicy(Lists.newArrayList(BiometricType.IRIS, BiometricType.FINGER, BiometricType.FACE)); - - setMetaInfoMap(new LinkedList<>(getExceptionModalityMap().values())); - MessageDTO dto = new MessageDTO(); - dto.setRid("10003100030001520190422074511"); - MessageDTO result = abisHandlerStage.process(dto); - - assertTrue(result.getIsValid()); - assertTrue(result.getInternalError()); - } - - @Test - public void biometricsNotFoundWithSegmentConfig() - throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { - - defaultMockToProcess(); - - Mockito.when(packetManagerService.getBiometrics(any(), any(), any(), any(), any())).thenReturn(getBiometricRecord(Arrays.asList("Left Thumb" ,"Right Thumb","Face"),false)); - - - setMetaInfoMap(Arrays.asList("leftEye")); - MessageDTO dto = new MessageDTO(); - dto.setRid("10003100030001520190422074511"); - MessageDTO result = abisHandlerStage.process(dto); - - assertTrue(result.getIsValid()); - assertTrue(result.getInternalError()); - } - - @Test - public void biometricsTypeNotFoundConfig() - throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { - - defaultMockToProcess(); - - Map> biometricModalitySegmentsMap = new HashMap(); - biometricModalitySegmentsMap.put("Finger", getFingerList()); - biometricModalitySegmentsMap.put("Iris", getIrisList()); - ReflectionTestUtils.setField(abisHandlerStage, "biometricModalitySegmentsMapAdult", biometricModalitySegmentsMap); - ReflectionTestUtils.setField(abisHandlerStage, "exceptionSegmentsMap", getExceptionModalityMap()); - - MessageDTO dto = new MessageDTO(); - dto.setRid("10003100030001520190422074511"); - MessageDTO result = abisHandlerStage.process(dto); - - assertTrue(result.getIsValid()); - assertTrue(result.getInternalError()); - } - - @Test - public void testBiometricSegmentNotConfiguredInfant() throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { - registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); - registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); - Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); - Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); - Mockito.when(packetInfoManager.getAllAbisDetails()).thenReturn(abisApplicationDtos); - - Mockito.when(packetInfoManager.getBioRefIdByRegId(any())).thenReturn(bioRefDtos); - tags.put("AGE_GROUP", "INFANT"); - Mockito.when(packetService.getAllTags(any())).thenReturn(tags); - - Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); - Mockito.doNothing().when(packetInfoManager).saveAbisRequest(any(), any(), any()); - - RegDemoDedupeListDto regDemoDedupeListDto = new RegDemoDedupeListDto(); - regDemoDedupeListDto.setMatchedRegId("10003100030001520190422074511"); - regDemoDedupeListDtoList.add(regDemoDedupeListDto); - Mockito.when(packetInfoManager.getDemoListByTransactionId(any())).thenReturn(regDemoDedupeListDtoList); - - MessageDTO dto = new MessageDTO(); - dto.setRid("10003100030001520190422074511"); - MessageDTO result = abisHandlerStage.process(dto); - - assertTrue(result.getIsValid()); - assertFalse(result.getInternalError()); - } - - - - @Test - public void emptyBdbFound() - throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { - - defaultMockToProcess(); - - boolean isBdbEmpty = true; - Mockito.when(packetManagerService.getBiometrics(any(), any(), any(), any(), any())).thenReturn(getBiometricRecord(Arrays.asList("Left RingFinger"), isBdbEmpty )); - mockDataSharePolicy(Lists.newArrayList(BiometricType.FINGER)); - - List list = new ArrayList(getExceptionModalityMap().values()); - list.remove("leftRing"); - setMetaInfoMap(list); - - MessageDTO dto = new MessageDTO(); - dto.setRid("10003100030001520190422074511"); - MessageDTO result = abisHandlerStage.process(dto); - - assertTrue(result.getIsValid()); - assertTrue(result.getInternalError()); - } - - @Test - public void noBdbInAnyBiometric() - throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { - - defaultMockToProcess(); - - Mockito.when(packetManagerService.getBiometrics(any(), any(), any(), any(), any())).thenReturn(getBiometricRecord(Arrays.asList("Left Thumb" ,"Right Thumb" , "Left MiddleFinger" , - "Left RingFinger" ,"Left LittleFinger" ,"Left IndexFinger" ,"Right MiddleFinger" , - "Right RingFinger" ,"Right LittleFinger" ,"Right IndexFinger" , - "Left" ,"Right","Face"),true)); - - MessageDTO dto = new MessageDTO(); - dto.setRid("10003100030001520190422074511"); - MessageDTO result = abisHandlerStage.process(dto); - - assertTrue(result.getIsValid()); - assertTrue(result.getInternalError()); - } - - private void defaultMockToProcess() { - registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); - registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); - Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); - Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); - Mockito.when(packetInfoManager.getAllAbisDetails()).thenReturn(abisApplicationDtos); - - RegBioRefDto regBioRefDto = new RegBioRefDto(); - regBioRefDto.setBioRefId("1234567890"); - bioRefDtos.add(regBioRefDto); - Mockito.when(packetInfoManager.getBioRefIdByRegId(any())).thenReturn(bioRefDtos); - - Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); - Mockito.doNothing().when(packetInfoManager).saveAbisRequest(any(), any(), any()); - - RegDemoDedupeListDto regDemoDedupeListDto = new RegDemoDedupeListDto(); - regDemoDedupeListDto.setMatchedRegId("10003100030001520190422074511"); - regDemoDedupeListDtoList.add(regDemoDedupeListDto); - Mockito.when(packetInfoManager.getDemoListByTransactionId(any())).thenReturn(regDemoDedupeListDtoList); - - } - - private void setMetaInfoMap(List exceptionAttributes) throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException{ - - Map metaInfoMap = new HashMap<>(); - - Map> exceptionBiometrcisMap = new HashMap<>(); - - Map applicantExceptionBiometrcisMap = new HashMap(); - - if(exceptionAttributes!=null) { - for(String exceptionAttribute : exceptionAttributes) { - - Map detailMap = new HashMap(); - detailMap.put("missingBiometric", exceptionAttribute); - detailMap.put("reason", "Temporary"); - detailMap.put("individualType", "applicant"); - - applicantExceptionBiometrcisMap.put(exceptionAttribute, detailMap); - - } - } - - - exceptionBiometrcisMap.put("applicant", applicantExceptionBiometrcisMap); - String gsonString =mapper.writeValueAsString(exceptionBiometrcisMap); - - metaInfoMap.put("exceptionBiometrics", gsonString); - Mockito.when(packetManagerService.getMetaInfo(any(), any(), any())).thenReturn(metaInfoMap); - } - - private BiometricRecord getBiometricRecord(List bioAttributes, boolean isBdbEmpty) { - BiometricRecord biometricRecord = new BiometricRecord(); - - byte[] bdb = isBdbEmpty ? null : new byte[2048]; - for(String bioAttribute : bioAttributes) { - BIR birType1 = new BIR.BIRBuilder().build(); - BDBInfo bdbInfoType1 = new BDBInfo.BDBInfoBuilder().build(); - io.mosip.kernel.biometrics.entities.RegistryIDType registryIDType = new RegistryIDType(); - registryIDType.setOrganization("Mosip"); - registryIDType.setType("257"); - io.mosip.kernel.biometrics.constant.QualityType quality = new QualityType(); - quality.setAlgorithm(registryIDType); - quality.setScore(90l); - bdbInfoType1.setQuality(quality); - - BiometricType singleType1 = bioAttribute.equalsIgnoreCase("face") ? BiometricType.FACE : - bioAttribute.equalsIgnoreCase("left") || bioAttribute.equalsIgnoreCase("right") ? BiometricType.IRIS : BiometricType.FINGER ; - List singleTypeList1 = new ArrayList<>(); - singleTypeList1.add(singleType1); - bdbInfoType1.setType(singleTypeList1); - - - - String[] bioAttributeArray = bioAttribute.split(" "); - - List subtype = new ArrayList<>(); - for(String attribute : bioAttributeArray) { - subtype.add(attribute); - } - bdbInfoType1.setSubtype(subtype); - - birType1.setBdbInfo(bdbInfoType1); - birType1.setBdb(bdb); - - if(bdb==null) { - Map others = new HashMap<>(); - others.put("EXCEPTION", true); - HashMap entry = new HashMap<>(); - entry.put("EXCEPTION", "true"); - birType1.setOthers(entry); - - } - - biometricRecord.getSegments().add(birType1); - } - - return biometricRecord; - } - +package io.mosip.registration.processor.abis.handler.stage.test; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.when; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +import org.assertj.core.util.Lists; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentMatchers; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.Spy; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.springframework.core.env.Environment; +import org.springframework.http.MediaType; +import org.springframework.test.util.ReflectionTestUtils; + +import com.fasterxml.jackson.databind.ObjectMapper; + +import io.mosip.kernel.biometrics.constant.BiometricType; +import io.mosip.kernel.biometrics.constant.QualityType; +import io.mosip.kernel.biometrics.entities.BDBInfo; +import io.mosip.kernel.biometrics.entities.BIR; +import io.mosip.kernel.biometrics.entities.BiometricRecord; +import io.mosip.kernel.biometrics.entities.RegistryIDType; +import io.mosip.kernel.biometrics.spi.CbeffUtil; +import io.mosip.kernel.core.util.JsonUtils; +import io.mosip.kernel.core.util.exception.JsonProcessingException; +import io.mosip.registration.processor.abis.handler.dto.DataShare; +import io.mosip.registration.processor.abis.handler.dto.DataShareResponseDto; +import io.mosip.registration.processor.abis.handler.stage.AbisHandlerStage; +import io.mosip.registration.processor.abis.queue.dto.AbisQueueDetails; +import io.mosip.registration.processor.core.abstractverticle.EventDTO; +import io.mosip.registration.processor.core.abstractverticle.HealthCheckDTO; +import io.mosip.registration.processor.core.abstractverticle.MessageBusAddress; +import io.mosip.registration.processor.core.abstractverticle.MessageDTO; +import io.mosip.registration.processor.core.abstractverticle.MosipEventBus; +import io.mosip.registration.processor.core.common.rest.dto.ErrorDTO; +import io.mosip.registration.processor.core.constant.JsonConstant; +import io.mosip.registration.processor.core.constant.PolicyConstant; +import io.mosip.registration.processor.core.exception.ApisResourceAccessException; +import io.mosip.registration.processor.core.exception.PacketManagerException; +import io.mosip.registration.processor.core.exception.RegistrationProcessorCheckedException; +import io.mosip.registration.processor.core.http.ResponseWrapper; +import io.mosip.registration.processor.core.logger.LogDescription; +import io.mosip.registration.processor.core.packet.dto.Identity; +import io.mosip.registration.processor.core.packet.dto.abis.AbisApplicationDto; +import io.mosip.registration.processor.core.packet.dto.abis.AbisIdentifyRequestDto; +import io.mosip.registration.processor.core.packet.dto.abis.AbisInsertRequestDto; +import io.mosip.registration.processor.core.packet.dto.abis.AbisRequestDto; +import io.mosip.registration.processor.core.packet.dto.abis.RegBioRefDto; +import io.mosip.registration.processor.core.packet.dto.abis.RegDemoDedupeListDto; +import io.mosip.registration.processor.core.packet.dto.datashare.Filter; +import io.mosip.registration.processor.core.packet.dto.datashare.ShareableAttributes; +import io.mosip.registration.processor.core.packet.dto.datashare.Source; +import io.mosip.registration.processor.core.spi.eventbus.EventHandler; +import io.mosip.registration.processor.core.spi.packetmanager.PacketInfoManager; +import io.mosip.registration.processor.core.spi.restclient.RegistrationProcessorRestClientService; +import io.mosip.registration.processor.packet.storage.dto.ApplicantInfoDto; +import io.mosip.registration.processor.packet.storage.utils.PacketManagerService; +import io.mosip.registration.processor.packet.storage.utils.PriorityBasedPacketManagerService; +import io.mosip.registration.processor.packet.storage.utils.Utilities; +import io.mosip.registration.processor.rest.client.audit.builder.AuditLogRequestBuilder; +import io.mosip.registration.processor.rest.client.audit.dto.AuditResponseDto; +import io.mosip.registration.processor.status.dto.InternalRegistrationStatusDto; +import io.mosip.registration.processor.status.dto.RegistrationStatusDto; +import io.mosip.registration.processor.status.service.RegistrationStatusService; +import io.vertx.core.AsyncResult; +import io.vertx.core.Handler; +import io.vertx.core.Vertx; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({ JsonUtils.class }) +@PowerMockIgnore({ "com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "javax.management.*", "javax.net.ssl.*" }) +public class AbisHandlerStageTest { + + @Mock + private AuditLogRequestBuilder auditLogRequestBuilder; + + @Mock + private RegistrationStatusService registrationStatusService; + + @Mock + private PacketInfoManager packetInfoManager; + + private InternalRegistrationStatusDto registrationStatusDto = new InternalRegistrationStatusDto(); + + @Mock + private Utilities utility; + + @Spy + private ObjectMapper mapper = new ObjectMapper(); + + @Mock + private PriorityBasedPacketManagerService packetManagerService; + + @Mock + private PacketManagerService packetService; + + @Mock + private LogDescription description; + + List abisApplicationDtos = new ArrayList<>(); + + List bioRefDtos = new ArrayList<>(); + + List regDemoDedupeListDtoList = new ArrayList<>(); + + List abisRequestDtoList = new ArrayList<>(); + + Map tags = new HashMap(); + + @Mock + private Environment env; + + @Mock + private RegistrationProcessorRestClientService registrationProcessorRestClientService; + + @Mock + private CbeffUtil cbeffutil; + + @InjectMocks + private AbisHandlerStage abisHandlerStage = new AbisHandlerStage() { + @Override + public MosipEventBus getEventBus(Object verticleName, String url, int instanceNumber) { + vertx = Vertx.vertx(); + + return new MosipEventBus() { + + @Override + public Vertx getEventbus() { + return vertx; + } + + @Override + public void consume(MessageBusAddress fromAddress, + EventHandler>> eventHandler) { + + } + + @Override + public void consumeAndSend(MessageBusAddress fromAddress, MessageBusAddress toAddress, + EventHandler>> eventHandler) { + + } + + @Override + public void send(MessageBusAddress toAddress, MessageDTO message) { + + } + + @Override + public void consumerHealthCheck(Handler eventHandler, String address) { + // TODO Auto-generated method stub + + } + + @Override + public void senderHealthCheck(Handler eventHandler, String address) { + // TODO Auto-generated method stub + + } + + }; + } + + @Override + public void consumeAndSend(MosipEventBus mosipEventBus, MessageBusAddress fromAddress, + MessageBusAddress toAddress, long messageExpiryTimeLimit) { + } + + @Override + public Integer getPort() { + return 8080; + }; + }; + + @Before + public void setUp() throws Exception { + ReflectionTestUtils.setField(abisHandlerStage, "maxResults", "30"); + ReflectionTestUtils.setField(abisHandlerStage, "targetFPIR", "30"); + ReflectionTestUtils.setField(abisHandlerStage, "workerPoolSize", 10); + ReflectionTestUtils.setField(abisHandlerStage, "messageExpiryTimeLimit", Long.valueOf(0)); + ReflectionTestUtils.setField(abisHandlerStage, "clusterManagerUrl", "/dummyPath"); + ReflectionTestUtils.setField(abisHandlerStage, "httpProtocol", "http"); + ReflectionTestUtils.setField(abisHandlerStage, "internalDomainName", "localhost"); + Mockito.when(env.getProperty("mosip.registration.processor.datetime.pattern")) + .thenReturn("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); + + Map> biometricModalitySegmentsMap = new HashMap(); + Map> biometricModalitySegmentsMapInfant = new HashMap(); + biometricModalitySegmentsMapInfant.put("Face", getFaceList()); + biometricModalitySegmentsMap.put("Finger", getFingerList()); + biometricModalitySegmentsMap.put("Iris", getIrisList()); + biometricModalitySegmentsMap.put("Face", getFaceList()); + ReflectionTestUtils.setField(abisHandlerStage, "biometricModalitySegmentsMapInfant", biometricModalitySegmentsMapInfant); + ReflectionTestUtils.setField(abisHandlerStage, "biometricModalitySegmentsMapMinor", biometricModalitySegmentsMap); + ReflectionTestUtils.setField(abisHandlerStage, "biometricModalitySegmentsMapAdult", biometricModalitySegmentsMap); + ReflectionTestUtils.setField(abisHandlerStage, "exceptionSegmentsMap", getExceptionModalityMap()); + ReflectionTestUtils.setField(abisHandlerStage, "regClientVersionsBeforeCbeffOthersAttritube", + Arrays.asList("1.1.3")); + Mockito.when(env.getProperty("DATASHARECREATEURL")).thenReturn("/v1/datashare/create"); + AbisApplicationDto dto = new AbisApplicationDto(); + dto.setCode("ABIS1"); + abisApplicationDtos.add(dto); + + Mockito.doNothing().when(description).setMessage(any()); + Mockito.when(description.getMessage()).thenReturn("description"); + + + Mockito.when(packetManagerService.getBiometrics(any(), any(), any(), any(), any())).thenReturn(getBiometricRecord(Arrays.asList("Left Thumb" ,"Right Thumb" , "Left MiddleFinger" , + "Left RingFinger" ,"Left LittleFinger" ,"Left IndexFinger" ,"Right MiddleFinger" , + "Right RingFinger" ,"Right LittleFinger" ,"Right IndexFinger" , + "Left" ,"Right","Face"),false)); + mockDataSharePolicy(Lists.newArrayList(BiometricType.FINGER,BiometricType.IRIS,BiometricType.FACE)); + + List list = new LinkedList<>(); + setMetaInfoMap(list); + + //Mockito.doNothing().when(registrationStatusDto).setLatestTransactionStatusCode(any()); + Mockito.doNothing().when(registrationStatusService).updateRegistrationStatus(any(), any(), any()); + + Mockito.when(packetInfoManager.getAbisRequestsByBioRefId(any())).thenReturn(abisRequestDtoList); + + AbisQueueDetails abisQueueDetails = new AbisQueueDetails(); + abisQueueDetails.setName("ABIS1"); + List abisQueueDetailsList = new ArrayList<>(); + abisQueueDetailsList.add(abisQueueDetails); + Mockito.when(utility.getAbisQueueDetails()).thenReturn(abisQueueDetailsList); + + AuditResponseDto auditResponseDto = new AuditResponseDto(); + ResponseWrapper responseWrapper = new ResponseWrapper<>(); + responseWrapper.setResponse(auditResponseDto); + Mockito.when(auditLogRequestBuilder.createAuditRequestBuilder(any(), any(), any(), any(), any(), any(), any())) + .thenReturn(responseWrapper); + + DataShareResponseDto dataShareResponseDto = new DataShareResponseDto(); + DataShare dataShare = new DataShare(); + dataShare.setUrl("http://localhost"); + dataShareResponseDto.setDataShare(dataShare); + + mockDataSharePolicy(Lists.newArrayList(BiometricType.FACE, BiometricType.FINGER)); + + Mockito.when(registrationProcessorRestClientService.postApi(anyString(), any(MediaType.class), any(), any(), + any(), any(), any())).thenReturn(dataShareResponseDto); + + Mockito.when(cbeffutil.createXML(any())).thenReturn(new byte[2048]); + } + + private Map getExceptionModalityMap() { + Map exceptionMap = new HashMap(); + exceptionMap.put("Left Thumb" , "leftThumb"); + exceptionMap.put("Right Thumb" , "rightThumb"); + exceptionMap.put("Left MiddleFinger" , "leftMiddle"); + exceptionMap.put("Left RingFinger" , "leftRing"); + exceptionMap.put("Left LittleFinger" , "leftLittle"); + exceptionMap.put("Left IndexFinger" , "leftIndex"); + exceptionMap.put("Right MiddleFinger" , "rightMiddle"); + exceptionMap.put("Right RingFinger" , "rightRing"); + exceptionMap.put("Right LittleFinger" , "rightLittle"); + exceptionMap.put("Right IndexFinger" , "rightIndex"); + exceptionMap.put("Left" , "leftEye"); + exceptionMap.put("Right" , "rightEye"); + exceptionMap.put("Face" , "face"); + + return exceptionMap; + } + + private List getFaceList() { + return Arrays.asList("Face"); + } + + private List getIrisList() { + return Arrays.asList("Left", "Right"); + + } + + private List getFingerList() { + return Arrays.asList("Left Thumb", "Left LittleFinger", "Left IndexFinger", "Left MiddleFinger", + "Left RingFinger", "Right Thumb", "Right LittleFinger", + "Right IndexFinger", "Right MiddleFinger", + "Right RingFinger"); + } + + private void mockDataSharePolicy(List sherableBiometricList) throws ApisResourceAccessException { + when(registrationProcessorRestClientService.getApi(any(), any(), anyString(), anyString(), any())) + .thenReturn(getMockDataSharePolicy(sherableBiometricList)); + } + + private ResponseWrapper> getMockDataSharePolicy( + List sherableBiometricList) { + + ObjectMapper mapper = new ObjectMapper(); + + List attr = new LinkedList<>(); + if (sherableBiometricList != null && !sherableBiometricList.isEmpty()) { + + ShareableAttributes shareableAttributes = new ShareableAttributes(); + List sourceList = new ArrayList<>(); + + for (BiometricType bioType : sherableBiometricList) { + Filter filter = new Filter(); + filter.setType(bioType.value()); + Source src = new Source(); + src.setFilter(Lists.newArrayList(filter)); + sourceList.add(src); + } + + shareableAttributes.setSource(sourceList); + attr = Lists.newArrayList(shareableAttributes); + } + + ResponseWrapper> policy = new ResponseWrapper<>(); + LinkedHashMap policies = new LinkedHashMap<>(); + LinkedHashMap sharableAttributes = new LinkedHashMap<>(); + sharableAttributes.put(PolicyConstant.SHAREABLE_ATTRIBUTES, attr); + policies.put(PolicyConstant.POLICIES, sharableAttributes); + policy.setResponse(policies); + + return policy; + } + + @Test + public void testDeployVerticle() { + abisHandlerStage.deployVerticle(); + } + + @Test + public void testDemoToAbisHandlerTOMiddlewareSuccess() throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { + registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); + registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); + Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); + Mockito.when(packetInfoManager.getAllAbisDetails()).thenReturn(abisApplicationDtos); + + mockDataSharePolicy(Lists.newArrayList(BiometricType.IRIS, BiometricType.FINGER, BiometricType.FACE)); + Mockito.when(packetInfoManager.getBioRefIdByRegId(any())).thenReturn(bioRefDtos); + tags.put("AGE_GROUP", "ADULT"); + Mockito.when(packetService.getAllTags(any())).thenReturn(tags); + + Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); + Mockito.doNothing().when(packetInfoManager).saveAbisRequest(any(), any(), any()); + + RegDemoDedupeListDto regDemoDedupeListDto = new RegDemoDedupeListDto(); + regDemoDedupeListDto.setMatchedRegId("10003100030001520190422074511"); + regDemoDedupeListDtoList.add(regDemoDedupeListDto); + Mockito.when(packetInfoManager.getDemoListByTransactionId(any())).thenReturn(regDemoDedupeListDtoList); + + MessageDTO dto = new MessageDTO(); + dto.setRid("10003100030001520190422074511"); + MessageDTO result = abisHandlerStage.process(dto); + + assertTrue(result.getMessageBusAddress().getAddress().equalsIgnoreCase("abis-middle-ware-bus-in")); + } + + @Test + public void testBioToAbisHandlerToMiddlewareSuccess() throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { + registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); + registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); + Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); + Mockito.when(packetInfoManager.getAllAbisDetails()).thenReturn(abisApplicationDtos); + + mockDataSharePolicy(Lists.newArrayList(BiometricType.IRIS, BiometricType.FINGER, BiometricType.FACE)); + RegBioRefDto regBioRefDto = new RegBioRefDto(); + regBioRefDto.setBioRefId("1234567890"); + bioRefDtos.add(regBioRefDto); + Mockito.when(packetInfoManager.getBioRefIdByRegId(any())).thenReturn(bioRefDtos); + tags.put("AGE_GROUP", "ADULT"); + Mockito.when(packetService.getAllTags(any())).thenReturn(tags); + + Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); + Mockito.doNothing().when(packetInfoManager).saveAbisRequest(any(), any(), any()); + + RegDemoDedupeListDto regDemoDedupeListDto = new RegDemoDedupeListDto(); + regDemoDedupeListDto.setMatchedRegId("10003100030001520190422074511"); + regDemoDedupeListDtoList.add(regDemoDedupeListDto); + Mockito.when(packetInfoManager.getDemoListByTransactionId(any())).thenReturn(regDemoDedupeListDtoList); + + MessageDTO dto = new MessageDTO(); + dto.setRid("10003100030001520190422074511"); + MessageDTO result = abisHandlerStage.process(dto); + + assertTrue(result.getMessageBusAddress().getAddress().equalsIgnoreCase("abis-middle-ware-bus-in")); + } + + @Test + public void testMiddlewareToAbisHandlerToDemoSuccess() { + registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); + registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); + Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.TRUE); + + MessageDTO dto = new MessageDTO(); + dto.setRid("10003100030001520190422074511"); + MessageDTO result = abisHandlerStage.process(dto); + + assertTrue(result.getMessageBusAddress().getAddress().equalsIgnoreCase("demo-dedupe-bus-in")); + } + + @Test + public void testMiddlewareToAbisHandlerToBioSuccess() { + registrationStatusDto.setLatestTransactionTypeCode("BIOGRAPHIC_VERIFICATION"); + registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); + Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.TRUE); + + MessageDTO dto = new MessageDTO(); + dto.setRid("10003100030001520190422074511"); + MessageDTO result = abisHandlerStage.process(dto); + + assertTrue(result.getMessageBusAddress().getAddress().equalsIgnoreCase("bio-dedupe-bus-in")); + } + + @Test + public void testDemoDedupeDataNotFound() { + registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); + registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); + Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); + Mockito.when(packetInfoManager.getAllAbisDetails()).thenReturn(abisApplicationDtos); + + Mockito.when(packetInfoManager.getBioRefIdByRegId(any())).thenReturn(bioRefDtos); + + Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); + Mockito.doNothing().when(packetInfoManager).saveAbisRequest(any(), any(), any()); + + Mockito.when(packetInfoManager.getDemoListByTransactionId(any())).thenReturn(regDemoDedupeListDtoList); + + MessageDTO dto = new MessageDTO(); + dto.setRid("10003100030001520190422074511"); + MessageDTO result = abisHandlerStage.process(dto); + + assertTrue(result.getInternalError()); + assertTrue(result.getIsValid()); + } + + @Test + public void testReprocessInsert() throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { + registrationStatusDto.setLatestTransactionTypeCode("BIOGRAPHIC_VERIFICATION"); + registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); + Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); + List appCodeList = new ArrayList<>(); + appCodeList.add("ABIS1"); + Mockito.when(packetInfoManager.getAbisProcessedRequestsAppCodeByBioRefId(any(), any(), any())) + .thenReturn(appCodeList); + + Mockito.when(packetInfoManager.getAllAbisDetails()).thenReturn(abisApplicationDtos); + + RegBioRefDto bioRefDto = new RegBioRefDto(); + bioRefDtos.add(bioRefDto); + Mockito.when(packetInfoManager.getBioRefIdByRegId(any())).thenReturn(bioRefDtos); + + Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); + + AbisRequestDto abisRequestDto = new AbisRequestDto(); + abisRequestDto.setAbisAppCode("ABIS1"); + abisRequestDto.setStatusCode("IN-PROGRESS"); + abisRequestDtoList.add(abisRequestDto); + Mockito.when(packetInfoManager.getAbisRequestsByBioRefId(any())).thenReturn(abisRequestDtoList); + tags.put("AGE_GROUP", "ADULT"); + Mockito.when(packetService.getAllTags(any())).thenReturn(tags); + + Mockito.doNothing().when(packetInfoManager).saveAbisRequest(any(), any(), any()); + + Mockito.when(packetInfoManager.getDemoListByTransactionId(any())).thenReturn(regDemoDedupeListDtoList); + + MessageDTO dto = new MessageDTO(); + dto.setRid("10003100030001520190422074511"); + MessageDTO result = abisHandlerStage.process(dto); + + assertFalse(result.getInternalError()); + assertTrue(result.getIsValid()); + } + + @Test + public void testAbisDetailsNotFound() throws RegistrationProcessorCheckedException { + registrationStatusDto.setLatestTransactionTypeCode("BIOGRAPHIC_VERIFICATION"); + registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); + Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); + + List abisQueueDetails = new ArrayList<>(); + Mockito.when(utility.getAbisQueueDetails()).thenReturn(abisQueueDetails); + + MessageDTO dto = new MessageDTO(); + dto.setRid("10003100030001520190422074511"); + MessageDTO result = abisHandlerStage.process(dto); + + assertTrue(result.getInternalError()); + } + + @Test + public void testPotentialMatchNotFound() throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { + registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); + registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); + Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); + + mockDataSharePolicy(Lists.newArrayList(BiometricType.IRIS, BiometricType.FINGER, BiometricType.FACE)); + tags.put("AGE_GROUP", "ADULT"); + Mockito.when(packetService.getAllTags(any())).thenReturn(tags); + + Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); + Mockito.doNothing().when(packetInfoManager).saveAbisRequest(any(), any(), any()); + + Mockito.when(packetInfoManager.getDemoListByTransactionId(any())).thenReturn(Arrays.asList()); + + MessageDTO dto = new MessageDTO(); + dto.setRid("10003100030001520190422074511"); + MessageDTO result = abisHandlerStage.process(dto); + + assertTrue(result.getInternalError()); + } + + @Test + public void testIdentifyRequestJsonProcessingException() throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { + registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); + registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); + Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); + + mockDataSharePolicy(Lists.newArrayList(BiometricType.IRIS, BiometricType.FINGER, BiometricType.FACE)); + Mockito.when(packetInfoManager.getBioRefIdByRegId(any())).thenReturn(bioRefDtos); + tags.put("AGE_GROUP", "ADULT"); + Mockito.when(packetService.getAllTags(any())).thenReturn(tags); + + Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); + Mockito.doNothing().when(packetInfoManager).saveAbisRequest(any(), any(), any()); + + RegDemoDedupeListDto regDemoDedupeListDto = new RegDemoDedupeListDto(); + regDemoDedupeListDto.setMatchedRegId("10003100030001520190422074511"); + regDemoDedupeListDtoList.add(regDemoDedupeListDto); + Mockito.when(packetInfoManager.getDemoListByTransactionId(any())).thenReturn(regDemoDedupeListDtoList); + + PowerMockito.mockStatic(JsonUtils.class); + PowerMockito.when(JsonUtils.javaObjectToJsonString(any())).thenReturn("value").thenThrow(JsonProcessingException.class); + MessageDTO dto = new MessageDTO(); + dto.setRid("10003100030001520190422074511"); + MessageDTO result = abisHandlerStage.process(dto); + + assertTrue(result.getInternalError()); + } + + @Test + public void testInsertRequestJsonProcessingException() throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { + registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); + registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); + Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); + + mockDataSharePolicy(Lists.newArrayList(BiometricType.IRIS, BiometricType.FINGER, BiometricType.FACE)); + tags.put("AGE_GROUP", "MINOR"); + Mockito.when(packetService.getAllTags(any())).thenReturn(tags); + + Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); + + PowerMockito.mockStatic(JsonUtils.class); + PowerMockito.when(JsonUtils.javaObjectToJsonString(any())).thenThrow(JsonProcessingException.class); + MessageDTO dto = new MessageDTO(); + dto.setRid("10003100030001520190422074511"); + MessageDTO result = abisHandlerStage.process(dto); + + assertTrue(result.getInternalError()); + } + + @Test + public void testDataShareResponseNullException() throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { + registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); + registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); + Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); + + mockDataSharePolicy(Lists.newArrayList(BiometricType.IRIS, BiometricType.FINGER, BiometricType.FACE)); + tags.put("AGE_GROUP", "MINOR"); + Mockito.when(packetService.getAllTags(any())).thenReturn(tags); + + Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); + + DataShareResponseDto dataShareResponseDto = new DataShareResponseDto(); + ErrorDTO error = new ErrorDTO("ERR-001", "exception occured"); + dataShareResponseDto.setDataShare(null); + dataShareResponseDto.setErrors(Arrays.asList(error)); + Mockito.when(registrationProcessorRestClientService.postApi(anyString(), any(MediaType.class), any(), any(), + any(), any(), any())).thenReturn(dataShareResponseDto); + MessageDTO dto = new MessageDTO(); + dto.setRid("10003100030001520190422074511"); + MessageDTO result = abisHandlerStage.process(dto); + + assertTrue(result.getInternalError()); + } + + @Test + public void testCreateTypeSubtypeMappingResponseNullException() + throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { + registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); + registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())) + .thenReturn(registrationStatusDto); + Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); + ErrorDTO error = new ErrorDTO("ERR-001", "exception occured"); + ResponseWrapper> policyResponse = new ResponseWrapper<>(); + + policyResponse.setErrors(Arrays.asList(error)); + + Mockito.when(registrationProcessorRestClientService.getApi(any(), any(), anyString(), + anyString(), any())).thenReturn(policyResponse); + Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); + + MessageDTO dto = new MessageDTO(); + dto.setRid("10003100030001520190422074511"); + MessageDTO result = abisHandlerStage.process(dto); + + assertTrue(result.getInternalError()); + } + + @Test + public void testvalidateBiometricRecordModalitiesEmptyException() + throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { + registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); + registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())) + .thenReturn(registrationStatusDto); + Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); + + mockDataSharePolicy(Lists.newArrayList(BiometricType.IRIS, BiometricType.FINGER, BiometricType.FACE)); + tags.put("AGE_GROUP", "MINOR"); + Mockito.when(packetService.getAllTags(any())).thenReturn(tags); + + Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); + + ResponseWrapper> policyResponse = new ResponseWrapper<>(); + LinkedHashMap response = new LinkedHashMap(); + LinkedHashMap attributes = new LinkedHashMap(); + ShareableAttributes shareableAttributes = new ShareableAttributes(); + shareableAttributes.setSource(Arrays.asList()); + attributes.put(PolicyConstant.SHAREABLE_ATTRIBUTES, Arrays.asList(shareableAttributes)); + response.put(PolicyConstant.POLICIES, attributes); + policyResponse.setResponse(response); + + Mockito.when(registrationProcessorRestClientService.getApi(any(), any(), anyString(), anyString(), any())) + .thenReturn(policyResponse); + + MessageDTO dto = new MessageDTO(); + dto.setRid("10003100030001520190422074511"); + MessageDTO result = abisHandlerStage.process(dto); + + assertTrue(result.getInternalError()); + } + + @Test + public void testvalidateBiometricRecordSegmentEmptyException() + throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { + registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); + registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())) + .thenReturn(registrationStatusDto); + Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); + + mockDataSharePolicy(Lists.newArrayList(BiometricType.IRIS, BiometricType.FINGER, BiometricType.FACE)); + tags.put("AGE_GROUP", "ADULT"); + Mockito.when(packetService.getAllTags(any())).thenReturn(tags); + BiometricRecord biometricRecord = new BiometricRecord(); + biometricRecord.setSegments(null); + Mockito.when(packetManagerService.getBiometrics(any(), any(), any(), any(), any())).thenReturn(biometricRecord); + Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); + + MessageDTO dto = new MessageDTO(); + dto.setRid("10003100030001520190422074511"); + MessageDTO result = abisHandlerStage.process(dto); + + assertTrue(result.getInternalError()); + } + + @Test + public void testvalidateBiometricRecordOthersMapNullException() + throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { + registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); + registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())) + .thenReturn(registrationStatusDto); + Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); + + mockDataSharePolicy(Lists.newArrayList(BiometricType.IRIS, BiometricType.FINGER, BiometricType.FACE)); + tags.put("AGE_GROUP", "ADULT"); + Mockito.when(packetService.getAllTags(any())).thenReturn(tags); + BiometricRecord biometricRecord = new BiometricRecord(); + BIR bir = new BIR.BIRBuilder().build(); + BDBInfo bdbInfo = new BDBInfo.BDBInfoBuilder().build(); + bdbInfo.setSubtype(Arrays.asList("Left")); + bdbInfo.setType(Arrays.asList(BiometricType.IRIS)); + bir.setOthers(null); + bir.setBdbInfo(bdbInfo); + biometricRecord.setSegments(Arrays.asList(bir)); + Mockito.when(packetManagerService.getBiometrics(any(), any(), any(), any(), any())).thenReturn(biometricRecord); + Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); + + MessageDTO dto = new MessageDTO(); + dto.setRid("10003100030001520190422074511"); + MessageDTO result = abisHandlerStage.process(dto); + + assertTrue(result.getInternalError()); + } + + @Test + public void testCreateRequestException() throws JsonProcessingException { + registrationStatusDto.setLatestTransactionTypeCode("BIOGRAPHIC_VERIFICATION"); + registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); + Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); + + Mockito.when(packetInfoManager.getAllAbisDetails()).thenReturn(abisApplicationDtos); + + RegBioRefDto bioRefDto = new RegBioRefDto(); + bioRefDtos.add(bioRefDto); + Mockito.when(packetInfoManager.getBioRefIdByRegId(any())).thenReturn(bioRefDtos); + + Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); + + AbisRequestDto abisRequestDto = new AbisRequestDto(); + abisRequestDto.setAbisAppCode("ABIS1"); + abisRequestDto.setStatusCode("IN-PROGRESS"); + abisRequestDtoList.add(abisRequestDto); + Mockito.when(packetInfoManager.getAbisRequestsByBioRefId(any())).thenReturn(abisRequestDtoList); + + Mockito.doNothing().when(packetInfoManager).saveAbisRequest(any(), any(), any()); + + Mockito.when(packetInfoManager.getDemoListByTransactionId(any())).thenReturn(regDemoDedupeListDtoList); + + PowerMockito.mockStatic(JsonUtils.class); + PowerMockito.when(JsonUtils.javaObjectToJsonString(any(AbisInsertRequestDto.class))) + .thenThrow(JsonProcessingException.class); + + MessageDTO dto = new MessageDTO(); + dto.setRid("10003100030001520190422074511"); + MessageDTO result = abisHandlerStage.process(dto); + + assertTrue(result.getInternalError()); + assertTrue(result.getIsValid()); + } + + @Test + public void testIdentifyRequestException() throws JsonProcessingException { + registrationStatusDto.setLatestTransactionTypeCode("BIOGRAPHIC_VERIFICATION"); + registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); + Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); + + Mockito.when(packetInfoManager.getAllAbisDetails()).thenReturn(abisApplicationDtos); + + RegBioRefDto bioRefDto = new RegBioRefDto(); + bioRefDtos.add(bioRefDto); + Mockito.when(packetInfoManager.getBioRefIdByRegId(any())).thenReturn(bioRefDtos); + + Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); + + AbisRequestDto abisRequestDto = new AbisRequestDto(); + abisRequestDto.setAbisAppCode("ABIS1"); + abisRequestDto.setStatusCode("IN-PROGRESS"); + abisRequestDtoList.add(abisRequestDto); + Mockito.when(packetInfoManager.getAbisRequestsByBioRefId(any())).thenReturn(abisRequestDtoList); + + Mockito.doNothing().when(packetInfoManager).saveAbisRequest(any(), any(), any()); + + Mockito.when(packetInfoManager.getDemoListByTransactionId(any())).thenReturn(regDemoDedupeListDtoList); + + PowerMockito.mockStatic(JsonUtils.class); + PowerMockito.when(JsonUtils.javaObjectToJsonString(any(AbisInsertRequestDto.class))) + .thenReturn("AbisInsertRequestDto"); + PowerMockito.when(JsonUtils.javaObjectToJsonString(ArgumentMatchers.any(AbisIdentifyRequestDto.class))) + .thenThrow(JsonProcessingException.class); + + MessageDTO dto = new MessageDTO(); + dto.setRid("10003100030001520190422074511"); + MessageDTO result = abisHandlerStage.process(dto); + + assertTrue(result.getInternalError()); + assertTrue(result.getIsValid()); + } + + + @Test + public void bioRecordDataNotFound() + throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { + + defaultMockToProcess(); + + Mockito.when(packetManagerService.getBiometrics(any(), any(), any(), any(), any())).thenReturn(null); + mockDataSharePolicy(Lists.newArrayList(BiometricType.IRIS, BiometricType.FINGER, BiometricType.FACE)); + + setMetaInfoMap(new LinkedList<>(getExceptionModalityMap().values())); + MessageDTO dto = new MessageDTO(); + dto.setRid("10003100030001520190422074511"); + MessageDTO result = abisHandlerStage.process(dto); + + assertTrue(result.getIsValid()); + assertTrue(result.getInternalError()); + } + + @Test + public void biometricsNotFoundWithSegmentConfig() + throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { + + defaultMockToProcess(); + + Mockito.when(packetManagerService.getBiometrics(any(), any(), any(), any(), any())).thenReturn(getBiometricRecord(Arrays.asList("Left Thumb" ,"Right Thumb","Face"),false)); + + + setMetaInfoMap(Arrays.asList("leftEye")); + MessageDTO dto = new MessageDTO(); + dto.setRid("10003100030001520190422074511"); + MessageDTO result = abisHandlerStage.process(dto); + + assertTrue(result.getIsValid()); + assertTrue(result.getInternalError()); + } + + @Test + public void biometricsTypeNotFoundConfig() + throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { + + defaultMockToProcess(); + + Map> biometricModalitySegmentsMap = new HashMap(); + biometricModalitySegmentsMap.put("Finger", getFingerList()); + biometricModalitySegmentsMap.put("Iris", getIrisList()); + ReflectionTestUtils.setField(abisHandlerStage, "biometricModalitySegmentsMapAdult", biometricModalitySegmentsMap); + ReflectionTestUtils.setField(abisHandlerStage, "exceptionSegmentsMap", getExceptionModalityMap()); + + MessageDTO dto = new MessageDTO(); + dto.setRid("10003100030001520190422074511"); + MessageDTO result = abisHandlerStage.process(dto); + + assertTrue(result.getIsValid()); + assertTrue(result.getInternalError()); + } + + @Test + public void testBiometricSegmentNotConfiguredInfant() throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { + registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); + registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); + Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); + Mockito.when(packetInfoManager.getAllAbisDetails()).thenReturn(abisApplicationDtos); + + Mockito.when(packetInfoManager.getBioRefIdByRegId(any())).thenReturn(bioRefDtos); + tags.put("AGE_GROUP", "INFANT"); + Mockito.when(packetService.getAllTags(any())).thenReturn(tags); + + Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); + Mockito.doNothing().when(packetInfoManager).saveAbisRequest(any(), any(), any()); + + RegDemoDedupeListDto regDemoDedupeListDto = new RegDemoDedupeListDto(); + regDemoDedupeListDto.setMatchedRegId("10003100030001520190422074511"); + regDemoDedupeListDtoList.add(regDemoDedupeListDto); + Mockito.when(packetInfoManager.getDemoListByTransactionId(any())).thenReturn(regDemoDedupeListDtoList); + + MessageDTO dto = new MessageDTO(); + dto.setRid("10003100030001520190422074511"); + MessageDTO result = abisHandlerStage.process(dto); + + assertTrue(result.getIsValid()); + assertFalse(result.getInternalError()); + } + + + + @Test + public void emptyBdbFound() + throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { + + defaultMockToProcess(); + + boolean isBdbEmpty = true; + Mockito.when(packetManagerService.getBiometrics(any(), any(), any(), any(), any())).thenReturn(getBiometricRecord(Arrays.asList("Left RingFinger"), isBdbEmpty )); + mockDataSharePolicy(Lists.newArrayList(BiometricType.FINGER)); + + List list = new ArrayList(getExceptionModalityMap().values()); + list.remove("leftRing"); + setMetaInfoMap(list); + + MessageDTO dto = new MessageDTO(); + dto.setRid("10003100030001520190422074511"); + MessageDTO result = abisHandlerStage.process(dto); + + assertTrue(result.getIsValid()); + assertTrue(result.getInternalError()); + } + + @Test + public void noBdbInAnyBiometric() + throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { + + defaultMockToProcess(); + + Mockito.when(packetManagerService.getBiometrics(any(), any(), any(), any(), any())).thenReturn(getBiometricRecord(Arrays.asList("Left Thumb" ,"Right Thumb" , "Left MiddleFinger" , + "Left RingFinger" ,"Left LittleFinger" ,"Left IndexFinger" ,"Right MiddleFinger" , + "Right RingFinger" ,"Right LittleFinger" ,"Right IndexFinger" , + "Left" ,"Right","Face"),true)); + + MessageDTO dto = new MessageDTO(); + dto.setRid("10003100030001520190422074511"); + MessageDTO result = abisHandlerStage.process(dto); + + assertTrue(result.getIsValid()); + assertTrue(result.getInternalError()); + } + + private void defaultMockToProcess() { + registrationStatusDto.setLatestTransactionTypeCode("DEMOGRAPHIC_VERIFICATION"); + registrationStatusDto.setLatestRegistrationTransactionId("dd7b7d20-910a-4b84-be21-c9f211318563"); + Mockito.when(registrationStatusService.getRegistrationStatus(any(), any(), any(), any())).thenReturn(registrationStatusDto); + Mockito.when(packetInfoManager.getIdentifyByTransactionId(any(), any())).thenReturn(Boolean.FALSE); + Mockito.when(packetInfoManager.getAllAbisDetails()).thenReturn(abisApplicationDtos); + + RegBioRefDto regBioRefDto = new RegBioRefDto(); + regBioRefDto.setBioRefId("1234567890"); + bioRefDtos.add(regBioRefDto); + Mockito.when(packetInfoManager.getBioRefIdByRegId(any())).thenReturn(bioRefDtos); + + Mockito.doNothing().when(packetInfoManager).saveBioRef(any(), any(), any()); + Mockito.doNothing().when(packetInfoManager).saveAbisRequest(any(), any(), any()); + + RegDemoDedupeListDto regDemoDedupeListDto = new RegDemoDedupeListDto(); + regDemoDedupeListDto.setMatchedRegId("10003100030001520190422074511"); + regDemoDedupeListDtoList.add(regDemoDedupeListDto); + Mockito.when(packetInfoManager.getDemoListByTransactionId(any())).thenReturn(regDemoDedupeListDtoList); + + } + + private void setMetaInfoMap(List exceptionAttributes) throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException{ + + Map metaInfoMap = new HashMap<>(); + + Map> exceptionBiometrcisMap = new HashMap<>(); + + Map applicantExceptionBiometrcisMap = new HashMap(); + + if(exceptionAttributes!=null) { + for(String exceptionAttribute : exceptionAttributes) { + + Map detailMap = new HashMap(); + detailMap.put("missingBiometric", exceptionAttribute); + detailMap.put("reason", "Temporary"); + detailMap.put("individualType", "applicant"); + + applicantExceptionBiometrcisMap.put(exceptionAttribute, detailMap); + + } + } + + + exceptionBiometrcisMap.put("applicant", applicantExceptionBiometrcisMap); + String gsonString =mapper.writeValueAsString(exceptionBiometrcisMap); + + metaInfoMap.put("exceptionBiometrics", gsonString); + metaInfoMap.put(JsonConstant.METADATA, + "[{\n \"label\" : \"Registration Client Version Number\",\n \"value\" : \"1.2.0\"\n}]"); + Mockito.when(packetManagerService.getMetaInfo(any(), any(), any())).thenReturn(metaInfoMap); + } + + private BiometricRecord getBiometricRecord(List bioAttributes, boolean isBdbEmpty) { + BiometricRecord biometricRecord = new BiometricRecord(); + + byte[] bdb = isBdbEmpty ? null : new byte[2048]; + for(String bioAttribute : bioAttributes) { + BIR birType1 = new BIR.BIRBuilder().build(); + BDBInfo bdbInfoType1 = new BDBInfo.BDBInfoBuilder().build(); + io.mosip.kernel.biometrics.entities.RegistryIDType registryIDType = new RegistryIDType(); + registryIDType.setOrganization("Mosip"); + registryIDType.setType("257"); + io.mosip.kernel.biometrics.constant.QualityType quality = new QualityType(); + quality.setAlgorithm(registryIDType); + quality.setScore(90l); + bdbInfoType1.setQuality(quality); + + BiometricType singleType1 = bioAttribute.equalsIgnoreCase("face") ? BiometricType.FACE : + bioAttribute.equalsIgnoreCase("left") || bioAttribute.equalsIgnoreCase("right") ? BiometricType.IRIS : BiometricType.FINGER ; + List singleTypeList1 = new ArrayList<>(); + singleTypeList1.add(singleType1); + bdbInfoType1.setType(singleTypeList1); + + + + String[] bioAttributeArray = bioAttribute.split(" "); + + List subtype = new ArrayList<>(); + for(String attribute : bioAttributeArray) { + subtype.add(attribute); + } + bdbInfoType1.setSubtype(subtype); + + birType1.setBdbInfo(bdbInfoType1); + birType1.setBdb(bdb); + + if(bdb==null) { + Map others = new HashMap<>(); + others.put("EXCEPTION", true); + HashMap entry = new HashMap<>(); + entry.put("EXCEPTION", "true"); + birType1.setOthers(entry); + + } + + biometricRecord.getSegments().add(birType1); + } + + return biometricRecord; + } + } \ No newline at end of file From ddbfe8847677c243476e4c8f4db64850e3221315 Mon Sep 17 00:00:00 2001 From: Rakshitha650 <76676196+Rakshitha650@users.noreply.github.com> Date: Tue, 5 Sep 2023 19:47:03 +0530 Subject: [PATCH 03/38] [DSD-3341]Updated Dockerfile (#1769) --- .../registration-processor-stage-group-1/Dockerfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/registration-processor/stage-groups/registration-processor-stage-group-1/Dockerfile b/registration-processor/stage-groups/registration-processor-stage-group-1/Dockerfile index ec2ac197d25..2392ed16e5e 100644 --- a/registration-processor/stage-groups/registration-processor-stage-group-1/Dockerfile +++ b/registration-processor/stage-groups/registration-processor-stage-group-1/Dockerfile @@ -86,7 +86,7 @@ ADD ./target/${group_name}-*.jar ${group_name}.jar RUN chown -R ${container_user}:${container_user} /home/${container_user} # select container user for all tasks -#USER ${container_user_uid}:${container_user_gid} +USER ${container_user_uid}:${container_user_gid} CMD if [ "$is_glowroot_env" = "present" ]; then \ wget "${iam_adapter_url_env}" -O "${loader_path_env}"/kernel-auth-adapter.jar; \ From fd5cda080543862aecc1a438a224c8ad465ced51 Mon Sep 17 00:00:00 2001 From: Sowmya Ujjappa Banakar <43202851+sowmya695@users.noreply.github.com> Date: Mon, 11 Sep 2023 12:52:22 +0530 Subject: [PATCH 04/38] MOSIP-28559 trying one approach (#1772) Co-authored-by: Sowmya Ujjappa Banakar --- .../notification/stage/SecurezoneNotificationStage.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/registration-processor/pre-processor/registration-processor-securezone-notification-stage/src/main/java/io/mosip/registration/processor/securezone/notification/stage/SecurezoneNotificationStage.java b/registration-processor/pre-processor/registration-processor-securezone-notification-stage/src/main/java/io/mosip/registration/processor/securezone/notification/stage/SecurezoneNotificationStage.java index 7059daa8f37..0164a57152f 100644 --- a/registration-processor/pre-processor/registration-processor-securezone-notification-stage/src/main/java/io/mosip/registration/processor/securezone/notification/stage/SecurezoneNotificationStage.java +++ b/registration-processor/pre-processor/registration-processor-securezone-notification-stage/src/main/java/io/mosip/registration/processor/securezone/notification/stage/SecurezoneNotificationStage.java @@ -132,7 +132,7 @@ protected String getPropertyPrefix() { @Override public void start() { - router.setRoute(this.postUrl(vertx, MessageBusAddress.SECUREZONE_NOTIFICATION_IN, + router.setRoute(this.postUrl(getVertx(), MessageBusAddress.SECUREZONE_NOTIFICATION_IN, MessageBusAddress.SECUREZONE_NOTIFICATION_OUT)); this.routes(router); this.createServer(router.getRouter(), getPort()); From d82ae2991975d0f5c657087ff0428f19ecdbae36 Mon Sep 17 00:00:00 2001 From: Khuddus shariff Date: Thu, 14 Sep 2023 11:12:36 +0530 Subject: [PATCH 05/38] quality checker level tags more specific --- .../quality/classifier/stage/QualityClassifierStage.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/registration-processor/pre-processor/registration-processor-quality-classifier-stage/src/main/java/io/mosip/registration/processor/quality/classifier/stage/QualityClassifierStage.java b/registration-processor/pre-processor/registration-processor-quality-classifier-stage/src/main/java/io/mosip/registration/processor/quality/classifier/stage/QualityClassifierStage.java index e4fa5d32738..b307ce4707e 100644 --- a/registration-processor/pre-processor/registration-processor-quality-classifier-stage/src/main/java/io/mosip/registration/processor/quality/classifier/stage/QualityClassifierStage.java +++ b/registration-processor/pre-processor/registration-processor-quality-classifier-stage/src/main/java/io/mosip/registration/processor/quality/classifier/stage/QualityClassifierStage.java @@ -461,7 +461,7 @@ private Map getQualityTags(List birs) throws BiometricExcep for (Entry qualityRangeEntry : parsedQualityRangeMap.entrySet()) { if (bioTypeMinEntry.getValue() >= qualityRangeEntry.getValue()[0] - && bioTypeMinEntry.getValue() <= qualityRangeEntry.getValue()[1]) { + && bioTypeMinEntry.getValue() < qualityRangeEntry.getValue()[1]) { tags.put( qualityTagPrefix.concat(bioTypeMinEntry.getKey()), qualityRangeEntry.getKey()); break; From 8c6f4404516339a76171ae76f02333a1c841513c Mon Sep 17 00:00:00 2001 From: Khuddus shariff Date: Fri, 15 Sep 2023 13:07:34 +0530 Subject: [PATCH 06/38] Added levels to test MOSIP-29419 --- .../test/QualityClassifierStageTest.java | 43 +++++++++++++++---- 1 file changed, 34 insertions(+), 9 deletions(-) diff --git a/registration-processor/pre-processor/registration-processor-quality-classifier-stage/src/test/java/io/mosip/registration/processor/quality/qualifier/stage/test/QualityClassifierStageTest.java b/registration-processor/pre-processor/registration-processor-quality-classifier-stage/src/test/java/io/mosip/registration/processor/quality/qualifier/stage/test/QualityClassifierStageTest.java index 7c3dbc180e6..f2188758fd7 100644 --- a/registration-processor/pre-processor/registration-processor-quality-classifier-stage/src/test/java/io/mosip/registration/processor/quality/qualifier/stage/test/QualityClassifierStageTest.java +++ b/registration-processor/pre-processor/registration-processor-quality-classifier-stage/src/test/java/io/mosip/registration/processor/quality/qualifier/stage/test/QualityClassifierStageTest.java @@ -111,7 +111,16 @@ public class QualityClassifierStageTest { private String POOR = "Poor"; - private String GOOD = "Good"; + private String level_1 = "level-1"; + private String level_2 = "level-2"; + private String level_3 = "level-3"; + private String level_4 = "level-4"; + private String level_5 = "level-5"; + private String level_6 = "level-6"; + private String level_7 = "level-7"; + private String level_8 = "level-8"; + private String level_9 = "level-9"; + private String level_10 = "level-10"; // JSONObject mappingJSONObject; @@ -184,17 +193,33 @@ public void setUp() throws Exception { ReflectionTestUtils.setField(qualityClassifierStage, "qualityTagPrefix", qualityPrefixTag); Map qualityClassificationRangeMap = new HashMap(); - qualityClassificationRangeMap.put(POOR, "0-29"); - qualityClassificationRangeMap.put(AVERAGE, "30-69"); - qualityClassificationRangeMap.put(GOOD, "70-100"); + qualityClassificationRangeMap.put(level_1, "0-10"); + qualityClassificationRangeMap.put(level_2, "10-20"); + qualityClassificationRangeMap.put(level_3, "20-30"); + qualityClassificationRangeMap.put(level_4, "30-40"); + qualityClassificationRangeMap.put(level_5, "40-50"); + qualityClassificationRangeMap.put(level_6, "50-60"); + qualityClassificationRangeMap.put(level_7, "60-70"); + qualityClassificationRangeMap.put(level_8, "70-80"); + qualityClassificationRangeMap.put(level_9, "80-90"); + qualityClassificationRangeMap.put(level_10, "90-101"); + ReflectionTestUtils.setField(qualityClassifierStage, "qualityClassificationRangeMap", qualityClassificationRangeMap); Map parsedMap = new HashMap(); - parsedMap.put(POOR, new int[] { 0, 29 }); - parsedMap.put(AVERAGE, new int[] { 30, 69 }); - parsedMap.put(GOOD, new int[] { 70, 100 }); + parsedMap.put(level_1, new int[] { 0, 10 }); + parsedMap.put(level_2, new int[] { 10, 20 }); + parsedMap.put(level_3, new int[] { 20, 30 }); + parsedMap.put(level_4, new int[] { 30, 40 }); + parsedMap.put(level_5, new int[] { 40, 50 }); + parsedMap.put(level_6, new int[] { 50, 60 }); + parsedMap.put(level_7, new int[] { 60, 70 }); + parsedMap.put(level_8, new int[] { 70, 80 }); + parsedMap.put(level_9, new int[] { 80, 90 }); + parsedMap.put(level_10, new int[] { 90, 101 }); + ReflectionTestUtils.setField(qualityClassifierStage, "parsedQualityRangeMap", parsedMap); ReflectionTestUtils.setField(qualityClassifierStage, "modalities", Arrays.asList("Iris", "Finger", "Face")); @@ -327,7 +352,7 @@ public void testQualityClassifierMixTags() throws Exception { verify(packetManagerService, atLeastOnce()).addOrUpdateTags(any(), argument.capture()); - assertQualityTags(argument.getAllValues().get(0), AVERAGE, POOR, GOOD); + assertQualityTags(argument.getAllValues().get(0), level_5, level_3, level_10); } @@ -350,7 +375,7 @@ public void testQualityClassifierAllGoodTags() throws ApisResourceAccessExceptio verify(packetManagerService, atLeastOnce()).addOrUpdateTags(any(), argument.capture()); - assertQualityTags(argument.getAllValues().get(0), GOOD, GOOD, GOOD); + assertQualityTags(argument.getAllValues().get(0), level_10, level_10, level_10); } From 26415a9a201e52ca0e5f7d836ba390e09e47d25b Mon Sep 17 00:00:00 2001 From: Khuddus shariff Date: Fri, 15 Sep 2023 13:22:01 +0530 Subject: [PATCH 07/38] Added levels to test MOSIP-29419 --- .../qualifier/stage/test/QualityClassifierStageTest.java | 4 ---- 1 file changed, 4 deletions(-) diff --git a/registration-processor/pre-processor/registration-processor-quality-classifier-stage/src/test/java/io/mosip/registration/processor/quality/qualifier/stage/test/QualityClassifierStageTest.java b/registration-processor/pre-processor/registration-processor-quality-classifier-stage/src/test/java/io/mosip/registration/processor/quality/qualifier/stage/test/QualityClassifierStageTest.java index f2188758fd7..37972938e79 100644 --- a/registration-processor/pre-processor/registration-processor-quality-classifier-stage/src/test/java/io/mosip/registration/processor/quality/qualifier/stage/test/QualityClassifierStageTest.java +++ b/registration-processor/pre-processor/registration-processor-quality-classifier-stage/src/test/java/io/mosip/registration/processor/quality/qualifier/stage/test/QualityClassifierStageTest.java @@ -107,10 +107,6 @@ public class QualityClassifierStageTest { private String qualityPrefixTag = "Biometric_Quality-"; - private String AVERAGE = "Average"; - - private String POOR = "Poor"; - private String level_1 = "level-1"; private String level_2 = "level-2"; private String level_3 = "level-3"; From 6603262555326e39c3239f0c41bb5e90d5f556e6 Mon Sep 17 00:00:00 2001 From: Khuddus shariff Date: Fri, 15 Sep 2023 16:01:27 +0530 Subject: [PATCH 08/38] quality checker level tags more specific MOSIP-29419 --- .../quality/classifier/stage/QualityClassifierStage.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/registration-processor/pre-processor/registration-processor-quality-classifier-stage/src/main/java/io/mosip/registration/processor/quality/classifier/stage/QualityClassifierStage.java b/registration-processor/pre-processor/registration-processor-quality-classifier-stage/src/main/java/io/mosip/registration/processor/quality/classifier/stage/QualityClassifierStage.java index b307ce4707e..88ada0f55da 100644 --- a/registration-processor/pre-processor/registration-processor-quality-classifier-stage/src/main/java/io/mosip/registration/processor/quality/classifier/stage/QualityClassifierStage.java +++ b/registration-processor/pre-processor/registration-processor-quality-classifier-stage/src/main/java/io/mosip/registration/processor/quality/classifier/stage/QualityClassifierStage.java @@ -137,7 +137,7 @@ public class QualityClassifierStage extends MosipVerticleAPIManager { * inclusive. */ - @Value("#{${mosip.regproc.quality.classifier.tagging.quality.ranges:{'Poor':'0-29','Average':'30-69','Good':'70-100'}}}") + @Value("#{${mosip.regproc.quality.classifier.tagging.quality.ranges:{'level-1':'0-10','level-2':'10-20','level-3':'20-30','level-4':'30-40','level-5':'40-50','level-6':'50-60','level-7':'60-70','level-8':'70-80','level-9':'80-90','level-10':'90-101',}}}") private Map qualityClassificationRangeMap; /** Quality Tag Prefix */ From 0830b18896e913ba0ad95bb9adbb9aa520aea773 Mon Sep 17 00:00:00 2001 From: Rakshitha650 <76676196+Rakshitha650@users.noreply.github.com> Date: Fri, 22 Sep 2023 17:32:26 +0530 Subject: [PATCH 09/38] [MOSIP-29167]added reusable workflow (#1777) * [MOSIP-29167]added reusable workflow * [MOSIP-29167]added reusable workflow * [MOSIP-29167]added reusable workflow * [MOSIP-29167]added reusable workflow * [MOSIP-29167]added reusable workflow * [MOSIP-29167]added reusable workflow --- .github/workflows/clear-artifacts.yml | 8 + .github/workflows/clear_artifacts.yml | 13 - .github/workflows/mavenpublish.yml | 60 - .github/workflows/postgres-init_trigger.yml | 83 -- .github/workflows/push-trigger.yml | 131 ++ .github/workflows/push_trigger.yml | 1060 ----------------- .github/workflows/release-changes.yml | 29 + .github/workflows/release_changes.yml | 56 - .github/workflows/release_trigger.yml | 739 ------------ .github/workflows/tag.yml | 35 + pom.xml | 308 ++--- .../pom.xml | 1 + .../pom.xml | 1 + registration-processor/init/pom.xml | 1 + registration-processor/pom.xml | 374 +++--- .../qc-users-manger/pom.xml | 1 + 16 files changed, 581 insertions(+), 2319 deletions(-) create mode 100644 .github/workflows/clear-artifacts.yml delete mode 100644 .github/workflows/clear_artifacts.yml delete mode 100644 .github/workflows/mavenpublish.yml delete mode 100644 .github/workflows/postgres-init_trigger.yml create mode 100644 .github/workflows/push-trigger.yml delete mode 100644 .github/workflows/push_trigger.yml create mode 100644 .github/workflows/release-changes.yml delete mode 100644 .github/workflows/release_changes.yml delete mode 100644 .github/workflows/release_trigger.yml create mode 100644 .github/workflows/tag.yml diff --git a/.github/workflows/clear-artifacts.yml b/.github/workflows/clear-artifacts.yml new file mode 100644 index 00000000000..b98fd748405 --- /dev/null +++ b/.github/workflows/clear-artifacts.yml @@ -0,0 +1,8 @@ +name: 'Delete old artifacts' +on: + schedule: + - cron: '0 * * * *' # every hour + +jobs: + delete-artifacts: + uses: mosip/kattu/.github/workflows/clear-artifacts.yml@master diff --git a/.github/workflows/clear_artifacts.yml b/.github/workflows/clear_artifacts.yml deleted file mode 100644 index 75b8aa96454..00000000000 --- a/.github/workflows/clear_artifacts.yml +++ /dev/null @@ -1,13 +0,0 @@ -name: 'Delete old artifacts' -on: - schedule: - - cron: '0 * * * *' # every hour - -jobs: - delete-artifacts: - runs-on: ubuntu-latest - steps: - - uses: kolpav/purge-artifacts-action@v1 - with: - token: ${{ secrets. access_token }} - expire-in: 2days # Setting this to 0 will delete all artifacts diff --git a/.github/workflows/mavenpublish.yml b/.github/workflows/mavenpublish.yml deleted file mode 100644 index a8f46091724..00000000000 --- a/.github/workflows/mavenpublish.yml +++ /dev/null @@ -1,60 +0,0 @@ -# This workflow will build a package using Maven and then publish it nexus when a pull request is merged -# For more information see: https://github.com/actions/setup-java#apache-maven-with-a-settings-path - -name: Maven Package upon a pull request - -on: - pull_request: - types: [closed] - -jobs: - build: - - runs-on: ubuntu-latest - - if: github.event.pull_request.merged == true - - steps: - - uses: actions/checkout@v2 - - name: Set up JDK 11 - uses: actions/setup-java@v1 - with: - ref: ${{ github.ref }} - java-version: 11 - server-id: ossrh # Value of the distributionManagement/repository/id field of the pom.xml - settings-path: ${{ github.workspace }} # location for the settings.xml file - - - name: Setup branch and env - run: | - # Strip git ref prefix from version - echo "BRANCH_NAME=$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')" >> $GITHUB_ENV - echo "GPG_TTY=$(tty)" >> $GITHUB_ENV - - - name: Setup branch and GPG public key - run: | - # Strip git ref prefix from version - echo ${{ env.BRANCH_NAME }} - echo ${{ env.GPG_TTY }} - sudo apt-get --yes install gnupg2 - gpg2 --import ./.github/keys/mosipgpgkey_pub.gpg - gpg2 --quiet --batch --passphrase=${{secrets.gpg_secret}} --allow-secret-key-import --import ./.github/keys/mosipgpgkey_sec.gpg - - uses: actions/cache@v1 - with: - path: ~/.m2/repository - key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }} - restore-keys: | - ${{ runner.os }}-maven-${{ env.BRANCH_NAME }} - - - name: Setup the settings file for ossrh server - run: echo " ossrh ${{secrets.ossrh_user}} ${{secrets.ossrh_secret}} ossrh true gpg2 ${{secrets.gpg_secret}} allow-snapshots true snapshots-repo https://oss.sonatype.org/content/repositories/snapshots false true releases-repo https://oss.sonatype.org/service/local/staging/deploy/maven2 true false sonar . https://sonarcloud.io false " > $GITHUB_WORKSPACE/settings.xml - - - name: Build with Maven - run: mvn -B package -s $GITHUB_WORKSPACE/settings.xml -DskipTests --file pom.xml - - - name: Publish to GitHub Packages Apache Maven - run: | - chmod +x ./deploy.sh - ./deploy.sh registration-processor $GITHUB_WORKSPACE/settings.xml SNAPSHOT - env: - GPG_TTY: $(tty) - diff --git a/.github/workflows/postgres-init_trigger.yml b/.github/workflows/postgres-init_trigger.yml deleted file mode 100644 index 3de4c6f32c5..00000000000 --- a/.github/workflows/postgres-init_trigger.yml +++ /dev/null @@ -1,83 +0,0 @@ -name: Trigger postgres-init repo upon db scripts updates - -on: - push: - branches: - - master - - 1.* - - develop - - release* - paths: - - db_release_scripts/** - - db_scripts/** - -jobs: - paths-filter: - runs-on: ubuntu-latest - outputs: - db_release_scripts: ${{ steps.filter.outputs.db_release_scripts }} - db_scripts: ${{ steps.filter.outputs.db_scripts }} - steps: - - uses: actions/checkout@v2 - - uses: dorny/paths-filter@v2 - id: filter - with: - base: ${{ github.ref }} - filters: | - db_release_scripts: - - 'db_release_scripts/**' - db_scripts: - - 'db_scripts/**' - - # run only if 'db_release_scripts' files were changed - db_release_scripts_updates: - needs: paths-filter - if: needs.paths-filter.outputs.db_release_scripts == 'true' - runs-on: ubuntu-latest - steps: - - name: Check for updates - run: echo "Updates are present in db_release_scripts directory, Triggering postgres-init repo" - - uses: 8398a7/action-slack@v3 - with: - status: ${{ job.status }} - fields: repo,message,commit,author,job,took,ref # selectable (default: repo,message) - env: - SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_DEVOPS }} # required - if: success() # Pick up events when the job is successful. - - # run only if not 'db_release_scripts' files were changed - - name: Check for no updates - if: needs.paths-filter.outputs.db_release_scripts != 'true' - run: echo "Updates are not present in db_release_scripts directory" - - # run only if 'db_scripts' files were changed - db_scripts_updates: - needs: paths-filter - if: needs.paths-filter.outputs.db_scripts == 'true' - runs-on: ubuntu-latest - steps: - - name: Check for updates - run: echo "Updates are present in db_scripts directory, Triggering postgres-init repo" - - uses: 8398a7/action-slack@v3 - with: - status: ${{ job.status }} - fields: repo,message,commit,author,job,took,ref # selectable (default: repo,message) - env: - SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_DEVOPS }} # required - if: success() # Pick up events when the job is successful. - - # run only if not 'db_scripts' files were changed - - name: Check for no updates - if: needs.paths-filter.outputs.db_scripts != 'true' - run: echo "Updates are not present in db_scripts directory" - - # This job is to trigger postgres-init repo. - trigger-postgres_init_repo: - runs-on: ubuntu-latest - steps: - - uses: peter-evans/repository-dispatch@v2 - with: - token: ${{ secrets.ACTION_PAT }} - repository: mosip/postgres-init - base: ${{ github.ref }} - event-type: db-event diff --git a/.github/workflows/push-trigger.yml b/.github/workflows/push-trigger.yml new file mode 100644 index 00000000000..ab05c642dcc --- /dev/null +++ b/.github/workflows/push-trigger.yml @@ -0,0 +1,131 @@ +name: Maven Package upon a push + +on: + release: + types: [published] + pull_request: + types: [opened] + + workflow_dispatch: + inputs: + message: + description: 'Message for manually triggering' + required: false + default: 'Triggered for Updates' + type: string + push: + branches: + - '!release-branch' + - release-1* + - master + - 1.* + - develop + +jobs: + build-maven-registration: + uses: mosip/kattu/.github/workflows/maven-build.yml@master + with: + SERVICE_LOCATION: ./registration-processor + BUILD_ARTIFACT: registration + secrets: + OSSRH_USER: ${{ secrets.OSSRH_USER }} + OSSRH_SECRET: ${{ secrets.OSSRH_SECRET }} + OSSRH_TOKEN: ${{ secrets.OSSRH_TOKEN }} + GPG_SECRET: ${{ secrets.GPG_SECRET }} + SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK }} + + publish_to_nexus: + if: "${{ !contains(github.ref, 'master') && github.event_name != 'pull_request' }}" + needs: build-maven-registration + uses: mosip/kattu/.github/workflows/maven-publish-to-nexus.yml@master + with: + SERVICE_LOCATION: ./registration-processor + secrets: + OSSRH_USER: ${{ secrets.OSSRH_USER }} + OSSRH_SECRET: ${{ secrets.OSSRH_SECRET }} + OSSRH_URL: ${{ secrets.OSSRH_SNAPSHOT_URL }} + OSSRH_TOKEN: ${{ secrets.OSSRH_TOKEN }} + GPG_SECRET: ${{ secrets.GPG_SECRET }} + SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK }} + + build-dockers: + needs: build-maven-registration + strategy: + matrix: + include: + - SERVICE_LOCATION: 'registration-processor/post-processor/registration-processor-registration-transaction-service' + SERVICE_NAME: 'registration-processor-registration-transaction-service' + BUILD_ARTIFACT: 'registration' + - SERVICE_LOCATION: 'registration-processor/stage-groups/registration-processor-stage-group-1' + SERVICE_NAME: 'registration-processor-stage-group-1' + BUILD_ARTIFACT: 'registration' + - SERVICE_LOCATION: 'registration-processor/stage-groups/registration-processor-stage-group-2' + SERVICE_NAME: 'registration-processor-stage-group-2' + BUILD_ARTIFACT: 'registration' + - SERVICE_LOCATION: 'registration-processor/stage-groups/registration-processor-stage-group-3' + SERVICE_NAME: 'registration-processor-stage-group-3' + BUILD_ARTIFACT: 'registration' + - SERVICE_LOCATION: 'registration-processor/stage-groups/registration-processor-stage-group-4' + SERVICE_NAME: 'registration-processor-stage-group-4' + BUILD_ARTIFACT: 'registration' + - SERVICE_LOCATION: 'registration-processor/stage-groups/registration-processor-stage-group-5' + SERVICE_NAME: 'registration-processor-stage-group-5' + BUILD_ARTIFACT: 'registration' + - SERVICE_LOCATION: 'registration-processor/stage-groups/registration-processor-stage-group-6' + SERVICE_NAME: 'registration-processor-stage-group-6' + BUILD_ARTIFACT: 'registration' + - SERVICE_LOCATION: 'registration-processor/stage-groups/registration-processor-stage-group-7' + SERVICE_NAME: 'registration-processor-stage-group-7' + BUILD_ARTIFACT: 'registration' + - SERVICE_LOCATION: 'registration-processor/core-processor/registration-processor-abis' + SERVICE_NAME: 'registration-processor-abis' + BUILD_ARTIFACT: 'registration' + - SERVICE_LOCATION: 'registration-processor/workflow-engine/registration-processor-reprocessor' + SERVICE_NAME: 'registration-processor-reprocessor' + BUILD_ARTIFACT: 'registration' + - SERVICE_LOCATION: 'registration-processor/init/registration-processor-dmz-packet-server' + SERVICE_NAME: 'registration-processor-dmz-packet-server' + - SERVICE_LOCATION: 'registration-processor/init/registration-processor-registration-status-service' + SERVICE_NAME: 'registration-processor-registration-status-service' + BUILD_ARTIFACT: 'registration' + - SERVICE_LOCATION: 'registration-processor/registration-processor-notification-service' + SERVICE_NAME: 'registration-processor-notification-service' + BUILD_ARTIFACT: 'registration' + - SERVICE_LOCATION: 'registration-processor/registration-processor-landing-zone' + SERVICE_NAME: 'registration-processor-landing-zone' + BUILD_ARTIFACT: 'registration' + - SERVICE_LOCATION: 'registration-processor/workflow-engine/registration-processor-workflow-manager-service' + SERVICE_NAME: 'registration-processor-workflow-manager-service' + BUILD_ARTIFACT: 'registration' + - SERVICE_LOCATION: 'registration-processor/registration-processor-common-camel-bridge' + SERVICE_NAME: 'registration-processor-common-camel-bridge' + BUILD_ARTIFACT: 'registration' + + fail-fast: false + name: ${{ matrix.SERVICE_NAME }} + uses: mosip/kattu/.github/workflows/docker-build.yml@master + with: + SERVICE_LOCATION: ${{ matrix.SERVICE_LOCATION }} + SERVICE_NAME: ${{ matrix.SERVICE_NAME }} + BUILD_ARTIFACT: ${{ matrix.BUILD_ARTIFACT || false }} + secrets: + DEV_NAMESPACE_DOCKER_HUB: ${{ secrets.DEV_NAMESPACE_DOCKER_HUB }} + ACTOR_DOCKER_HUB: ${{ secrets.ACTOR_DOCKER_HUB }} + RELEASE_DOCKER_HUB: ${{ secrets.RELEASE_DOCKER_HUB }} + SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK }} + + + sonar_analysis: + needs: build-maven-registration + if: "${{ github.event_name != 'pull_request' }}" + uses: mosip/kattu/.github/workflows/maven-sonar-analysis.yml@master + with: + SERVICE_LOCATION: ./registration-processor + secrets: + SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} + ORG_KEY: ${{ secrets.ORG_KEY }} + OSSRH_USER: ${{ secrets.OSSRH_USER }} + OSSRH_SECRET: ${{ secrets.OSSRH_SECRET }} + OSSRH_TOKEN: ${{ secrets.OSSRH_TOKEN }} + GPG_SECRET: ${{ secrets.GPG_SECRET }} + SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK }} \ No newline at end of file diff --git a/.github/workflows/push_trigger.yml b/.github/workflows/push_trigger.yml deleted file mode 100644 index f9610ca2c03..00000000000 --- a/.github/workflows/push_trigger.yml +++ /dev/null @@ -1,1060 +0,0 @@ -name: Maven Package upon a push - -on: - pull_request: - types: [closed] - push: - branches: - - '!release-branch' - - release-1* - - master - - 1.* - - develop -jobs: - build: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v2 - - name: Set up JDK 11 - uses: actions/setup-java@v1 - with: - ref: ${{ github.ref }} - java-version: 11 - server-id: ossrh # Value of the distributionManagement/repository/id field of the pom.xml - settings-path: ${{ github.workspace }} # location for the settings.xml file - - - name: Setup branch and env - run: | - # Strip git ref prefix from version - echo "BRANCH_NAME=$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')" >> $GITHUB_ENV - echo "GPG_TTY=$(tty)" >> $GITHUB_ENV - - name: Setup branch and GPG public key - run: | - # Strip git ref prefix from version - echo ${{ env.BRANCH_NAME }} - echo ${{ env.GPG_TTY }} - sudo apt-get --yes install gnupg2 - gpg2 --import ./.github/keys/mosipgpgkey_pub.gpg - gpg2 --quiet --batch --passphrase=${{secrets.gpg_secret}} --allow-secret-key-import --import ./.github/keys/mosipgpgkey_sec.gpg - - uses: actions/cache@v1 - with: - path: ~/.m2/repository - key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }} - restore-keys: | - ${{ runner.os }}-maven-${{ env.BRANCH_NAME }} - - name: Setup the settings file for ossrh server - run: echo " ossrh ${{secrets.ossrh_user}} ${{secrets.ossrh_secret}} ossrh true gpg2 ${{secrets.gpg_secret}} allow-snapshots true snapshots-repo https://oss.sonatype.org/content/repositories/snapshots false true releases-repo https://oss.sonatype.org/service/local/staging/deploy/maven2 true false sonar . https://sonarcloud.io false " > $GITHUB_WORKSPACE/settings.xml - - - name: Build with Maven - run: | - cd registration-processor - mvn -B package -s $GITHUB_WORKSPACE/settings.xml --file pom.xml - - name: Ready the springboot artifacts - run: find -name '*.jar' -executable -type f -exec zip release.zip {} + - - - - name: Upload the springboot jars - uses: actions/upload-artifact@v1 - with: - name: release - path: ./release.zip - - publish_to_nexus: - if: "!contains(github.ref, 'master')" - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v2 - - name: Set up JDK 11 - uses: actions/setup-java@v1 - with: - ref: ${{ github.ref }} - java-version: 11 - server-id: ossrh # Value of the distributionManagement/repository/id field of the pom.xml - settings-path: ${{ github.workspace }} # location for the settings.xml file - - uses: actions/checkout@v2 - - - name: Setup branch and env - run: | - # Strip git ref prefix from version - echo "BRANCH_NAME=$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')" >> $GITHUB_ENV - echo "GPG_TTY=$(tty)" >> $GITHUB_ENV - - name: Setup branch and GPG public key - run: | - # Strip git ref prefix from version - echo ${{ env.BRANCH_NAME }} - echo ${{ env.GPG_TTY }} - sudo apt-get --yes install gnupg2 - gpg2 --import ./.github/keys/mosipgpgkey_pub.gpg - gpg2 --quiet --batch --passphrase=${{secrets.gpg_secret}} --allow-secret-key-import --import ./.github/keys/mosipgpgkey_sec.gpg - - - uses: actions/cache@v1 - with: - path: ~/.m2/repository - key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }} - restore-keys: | - ${{ runner.os }}-maven-${{ env.BRANCH_NAME }} - - name: Install xmllint - run: | - sudo apt-get update - sudo apt-get install libxml2-utils - - name: Setup the settings file for ossrh server - run: echo " ossrh ${{secrets.RELEASE_USER}} ${{secrets.RELEASE_TOKEN}} ossrh true gpg2 ${{secrets.gpg_secret}} allow-snapshots true snapshots-repo https://oss.sonatype.org/content/repositories/snapshots false true releases-repo https://oss.sonatype.org/service/local/staging/deploy/maven2 true false sonar . https://sonarcloud.io false " > $GITHUB_WORKSPACE/settings.xml - - - name: Publish the maven package - run: | - mvn deploy -DaltDeploymentRepository=ossrh::default::${{ secrets.RELEASE_URL }} -s $GITHUB_WORKSPACE/settings.xml -f pom.xml - env: - GITHUB_TOKEN: ${{ secrets.RELEASE_TOKEN }} - GPG_TTY: $(tty) - - docker-registration-processor-registration-transaction-service: - needs: build - runs-on: ubuntu-latest - env: - NAMESPACE: ${{ secrets.dev_namespace_docker_hub }} - SERVICE_NAME: registration-processor-registration-transaction-service - SERVICE_LOCATION: registration-processor/post-processor/registration-processor-registration-transaction-service - steps: - - uses: actions/checkout@v2 - - uses: actions/download-artifact@v1 - with: - name: release - path: ./ - - - name: Setup branch name - run: | - # Strip git ref prefix from version - echo "BRANCH_NAME=$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')" >> $GITHUB_ENV - - name: Get version info from pom - id: getPomVersion - uses: mavrosxristoforos/get-xml-info@1.0 - with: - xml-file: ./${{ env.SERVICE_LOCATION }}/pom.xml - xpath: /*[local-name()="project"]/*[local-name()="version"] - - - name: Unzip and extract the ${{ env.SERVICE_NAME }} - run: unzip -uj "release.zip" "${{ env.SERVICE_LOCATION }}/target/*" -d "./${{ env.SERVICE_LOCATION }}/target" - - - name: Get current date - id: date - run: echo "::set-output name=date::$(date +'%Y-%m-%d')" - - - name: Build image - run: | - cd "./${{env.SERVICE_LOCATION}}" - docker build . --build-arg SOURCE=mosip --build-arg COMMIT_HASH=$(git rev-parse HEAD) --build-arg COMMIT_ID=$(git rev-parse --short HEAD) --build-arg BUILD_TIME=${{steps.date.outputs.date}} --file Dockerfile --tag ${{ env.SERVICE_NAME }} - - name: Log into registry - run: echo "${{ secrets.release_docker_hub }}" | docker login -u ${{ secrets.actor_docker_hub }} --password-stdin - - - name: Push image - run: | - IMAGE_ID=$NAMESPACE/$SERVICE_NAME - - # Change all uppercase to lowercase - IMAGE_ID=$(echo $IMAGE_ID | tr '[A-Z]' '[a-z]') - echo "push version ${{steps.getPomVersion.outputs.info}}" - if [[ $BRANCH_NAME == master ]]; then - VERSION=latest - else - VERSION=$BRANCH_NAME - fi - echo IMAGE_ID=$IMAGE_ID - echo VERSION=$VERSION - docker tag $SERVICE_NAME $IMAGE_ID:$VERSION - docker push $IMAGE_ID:$VERSION - - docker-registration-processor-stage-group-1: - needs: build - - runs-on: ubuntu-latest - env: - NAMESPACE: ${{ secrets.dev_namespace_docker_hub }} - SERVICE_NAME: registration-processor-stage-group-1 - SERVICE_LOCATION: registration-processor/stage-groups/registration-processor-stage-group-1 - - steps: - - uses: actions/checkout@v2 - - uses: actions/download-artifact@v1 - with: - name: release - path: ./ - - - name: Setup branch name - run: | - # Strip git ref prefix from version - echo "BRANCH_NAME=$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')" >> $GITHUB_ENV - - name: Get version info from pom - id: getPomVersion - uses: mavrosxristoforos/get-xml-info@1.0 - with: - xml-file: ./${{ env.SERVICE_LOCATION }}/pom.xml - xpath: /*[local-name()="project"]/*[local-name()="version"] - - - name: Unzip and extract the ${{ env.SERVICE_NAME }} - run: unzip -uj "release.zip" "${{ env.SERVICE_LOCATION }}/target/*" -d "./${{ env.SERVICE_LOCATION }}/target" - - - name: Get current date - id: date - run: echo "::set-output name=date::$(date +'%Y-%m-%d')" - - - name: Build image - run: | - cd "./${{env.SERVICE_LOCATION}}" - docker build . --build-arg SOURCE=mosip --build-arg COMMIT_HASH=$(git rev-parse HEAD) --build-arg COMMIT_ID=$(git rev-parse --short HEAD) --build-arg BUILD_TIME=${{steps.date.outputs.date}} --file Dockerfile --tag ${{ env.SERVICE_NAME }} - - name: Log into registry - run: echo "${{ secrets.release_docker_hub }}" | docker login -u ${{ secrets.actor_docker_hub }} --password-stdin - - - name: Push image - run: | - IMAGE_ID=$NAMESPACE/$SERVICE_NAME - # Change all uppercase to lowercase - IMAGE_ID=$(echo $IMAGE_ID | tr '[A-Z]' '[a-z]') - echo "push version ${{steps.getPomVersion.outputs.info}}" - if [[ $BRANCH_NAME == master ]]; then - VERSION=latest - else - VERSION=$BRANCH_NAME - fi - echo IMAGE_ID=$IMAGE_ID - echo VERSION=$VERSION - docker tag $SERVICE_NAME $IMAGE_ID:$VERSION - docker push $IMAGE_ID:$VERSION - - docker-registration-processor-stage-group-2: - needs: build - - runs-on: ubuntu-latest - env: - NAMESPACE: ${{ secrets.dev_namespace_docker_hub }} - SERVICE_NAME: registration-processor-stage-group-2 - SERVICE_LOCATION: registration-processor/stage-groups/registration-processor-stage-group-2 - - steps: - - uses: actions/checkout@v2 - - uses: actions/download-artifact@v1 - with: - name: release - path: ./ - - - name: Setup branch name - run: | - # Strip git ref prefix from version - echo "BRANCH_NAME=$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')" >> $GITHUB_ENV - - name: Get version info from pom - id: getPomVersion - uses: mavrosxristoforos/get-xml-info@1.0 - with: - xml-file: ./${{ env.SERVICE_LOCATION }}/pom.xml - xpath: /*[local-name()="project"]/*[local-name()="version"] - - - name: Unzip and extract the ${{ env.SERVICE_NAME }} - run: unzip -uj "release.zip" "${{ env.SERVICE_LOCATION }}/target/*" -d "./${{ env.SERVICE_LOCATION }}/target" - - - name: Get current date - id: date - run: echo "::set-output name=date::$(date +'%Y-%m-%d')" - - - name: Build image - run: | - cd "./${{env.SERVICE_LOCATION}}" - docker build . --build-arg SOURCE=mosip --build-arg COMMIT_HASH=$(git rev-parse HEAD) --build-arg COMMIT_ID=$(git rev-parse --short HEAD) --build-arg BUILD_TIME=${{steps.date.outputs.date}} --file Dockerfile --tag ${{ env.SERVICE_NAME }} - - name: Log into registry - run: echo "${{ secrets.release_docker_hub }}" | docker login -u ${{ secrets.actor_docker_hub }} --password-stdin - - - name: Push image - run: | - IMAGE_ID=$NAMESPACE/$SERVICE_NAME - # Change all uppercase to lowercase - IMAGE_ID=$(echo $IMAGE_ID | tr '[A-Z]' '[a-z]') - echo "push version ${{steps.getPomVersion.outputs.info}}" - if [[ $BRANCH_NAME == master ]]; then - VERSION=latest - else - VERSION=$BRANCH_NAME - fi - echo IMAGE_ID=$IMAGE_ID - echo VERSION=$VERSION - docker tag $SERVICE_NAME $IMAGE_ID:$VERSION - docker push $IMAGE_ID:$VERSION - - docker-registration-processor-stage-group-3: - needs: build - - runs-on: ubuntu-latest - env: - NAMESPACE: ${{ secrets.dev_namespace_docker_hub }} - SERVICE_NAME: registration-processor-stage-group-3 - SERVICE_LOCATION: registration-processor/stage-groups/registration-processor-stage-group-3 - - steps: - - uses: actions/checkout@v2 - - uses: actions/download-artifact@v1 - with: - name: release - path: ./ - - - name: Setup branch name - run: | - # Strip git ref prefix from version - echo "BRANCH_NAME=$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')" >> $GITHUB_ENV - - name: Get version info from pom - id: getPomVersion - uses: mavrosxristoforos/get-xml-info@1.0 - with: - xml-file: ./${{ env.SERVICE_LOCATION }}/pom.xml - xpath: /*[local-name()="project"]/*[local-name()="version"] - - - name: Unzip and extract the ${{ env.SERVICE_NAME }} - run: unzip -uj "release.zip" "${{ env.SERVICE_LOCATION }}/target/*" -d "./${{ env.SERVICE_LOCATION }}/target" - - - name: Get current date - id: date - run: echo "::set-output name=date::$(date +'%Y-%m-%d')" - - - name: Build image - run: | - cd "./${{env.SERVICE_LOCATION}}" - docker build . --build-arg SOURCE=mosip --build-arg COMMIT_HASH=$(git rev-parse HEAD) --build-arg COMMIT_ID=$(git rev-parse --short HEAD) --build-arg BUILD_TIME=${{steps.date.outputs.date}} --file Dockerfile --tag ${{ env.SERVICE_NAME }} - - name: Log into registry - run: echo "${{ secrets.release_docker_hub }}" | docker login -u ${{ secrets.actor_docker_hub }} --password-stdin - - - name: Push image - run: | - IMAGE_ID=$NAMESPACE/$SERVICE_NAME - # Change all uppercase to lowercase - IMAGE_ID=$(echo $IMAGE_ID | tr '[A-Z]' '[a-z]') - echo "push version ${{steps.getPomVersion.outputs.info}}" - if [[ $BRANCH_NAME == master ]]; then - VERSION=latest - else - VERSION=$BRANCH_NAME - fi - echo IMAGE_ID=$IMAGE_ID - echo VERSION=$VERSION - docker tag $SERVICE_NAME $IMAGE_ID:$VERSION - docker push $IMAGE_ID:$VERSION - - docker-registration-processor-stage-group-4: - needs: build - - runs-on: ubuntu-latest - env: - NAMESPACE: ${{ secrets.dev_namespace_docker_hub }} - SERVICE_NAME: registration-processor-stage-group-4 - SERVICE_LOCATION: registration-processor/stage-groups/registration-processor-stage-group-4 - - steps: - - uses: actions/checkout@v2 - - uses: actions/download-artifact@v1 - with: - name: release - path: ./ - - - name: Setup branch name - run: | - # Strip git ref prefix from version - echo "BRANCH_NAME=$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')" >> $GITHUB_ENV - - name: Get version info from pom - id: getPomVersion - uses: mavrosxristoforos/get-xml-info@1.0 - with: - xml-file: ./${{ env.SERVICE_LOCATION }}/pom.xml - xpath: /*[local-name()="project"]/*[local-name()="version"] - - - name: Unzip and extract the ${{ env.SERVICE_NAME }} - run: unzip -uj "release.zip" "${{ env.SERVICE_LOCATION }}/target/*" -d "./${{ env.SERVICE_LOCATION }}/target" - - - name: Get current date - id: date - run: echo "::set-output name=date::$(date +'%Y-%m-%d')" - - - name: Build image - run: | - cd "./${{env.SERVICE_LOCATION}}" - docker build . --build-arg SOURCE=mosip --build-arg COMMIT_HASH=$(git rev-parse HEAD) --build-arg COMMIT_ID=$(git rev-parse --short HEAD) --build-arg BUILD_TIME=${{steps.date.outputs.date}} --file Dockerfile --tag ${{ env.SERVICE_NAME }} - - name: Log into registry - run: echo "${{ secrets.release_docker_hub }}" | docker login -u ${{ secrets.actor_docker_hub }} --password-stdin - - - name: Push image - run: | - IMAGE_ID=$NAMESPACE/$SERVICE_NAME - # Change all uppercase to lowercase - IMAGE_ID=$(echo $IMAGE_ID | tr '[A-Z]' '[a-z]') - echo "push version ${{steps.getPomVersion.outputs.info}}" - if [[ $BRANCH_NAME == master ]]; then - VERSION=latest - else - VERSION=$BRANCH_NAME - fi - echo IMAGE_ID=$IMAGE_ID - echo VERSION=$VERSION - docker tag $SERVICE_NAME $IMAGE_ID:$VERSION - docker push $IMAGE_ID:$VERSION - - docker-registration-processor-stage-group-5: - needs: build - - runs-on: ubuntu-latest - env: - NAMESPACE: ${{ secrets.dev_namespace_docker_hub }} - SERVICE_NAME: registration-processor-stage-group-5 - SERVICE_LOCATION: registration-processor/stage-groups/registration-processor-stage-group-5 - - steps: - - uses: actions/checkout@v2 - - uses: actions/download-artifact@v1 - with: - name: release - path: ./ - - - name: Setup branch name - run: | - # Strip git ref prefix from version - echo "BRANCH_NAME=$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')" >> $GITHUB_ENV - - name: Get version info from pom - id: getPomVersion - uses: mavrosxristoforos/get-xml-info@1.0 - with: - xml-file: ./${{ env.SERVICE_LOCATION }}/pom.xml - xpath: /*[local-name()="project"]/*[local-name()="version"] - - - name: Unzip and extract the ${{ env.SERVICE_NAME }} - run: unzip -uj "release.zip" "${{ env.SERVICE_LOCATION }}/target/*" -d "./${{ env.SERVICE_LOCATION }}/target" - - - name: Get current date - id: date - run: echo "::set-output name=date::$(date +'%Y-%m-%d')" - - - name: Build image - run: | - cd "./${{env.SERVICE_LOCATION}}" - docker build . --build-arg SOURCE=mosip --build-arg COMMIT_HASH=$(git rev-parse HEAD) --build-arg COMMIT_ID=$(git rev-parse --short HEAD) --build-arg BUILD_TIME=${{steps.date.outputs.date}} --file Dockerfile --tag ${{ env.SERVICE_NAME }} - - name: Log into registry - run: echo "${{ secrets.release_docker_hub }}" | docker login -u ${{ secrets.actor_docker_hub }} --password-stdin - - - name: Push image - run: | - IMAGE_ID=$NAMESPACE/$SERVICE_NAME - # Change all uppercase to lowercase - IMAGE_ID=$(echo $IMAGE_ID | tr '[A-Z]' '[a-z]') - echo "push version ${{steps.getPomVersion.outputs.info}}" - if [[ $BRANCH_NAME == master ]]; then - VERSION=latest - else - VERSION=$BRANCH_NAME - fi - echo IMAGE_ID=$IMAGE_ID - echo VERSION=$VERSION - docker tag $SERVICE_NAME $IMAGE_ID:$VERSION - docker push $IMAGE_ID:$VERSION - - docker-registration-processor-stage-group-6: - needs: build - - runs-on: ubuntu-latest - env: - NAMESPACE: ${{ secrets.dev_namespace_docker_hub }} - SERVICE_NAME: registration-processor-stage-group-6 - SERVICE_LOCATION: registration-processor/stage-groups/registration-processor-stage-group-6 - - steps: - - uses: actions/checkout@v2 - - uses: actions/download-artifact@v1 - with: - name: release - path: ./ - - - name: Setup branch name - run: | - # Strip git ref prefix from version - echo "BRANCH_NAME=$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')" >> $GITHUB_ENV - - name: Get version info from pom - id: getPomVersion - uses: mavrosxristoforos/get-xml-info@1.0 - with: - xml-file: ./${{ env.SERVICE_LOCATION }}/pom.xml - xpath: /*[local-name()="project"]/*[local-name()="version"] - - - name: Unzip and extract the ${{ env.SERVICE_NAME }} - run: unzip -uj "release.zip" "${{ env.SERVICE_LOCATION }}/target/*" -d "./${{ env.SERVICE_LOCATION }}/target" - - - name: Get current date - id: date - run: echo "::set-output name=date::$(date +'%Y-%m-%d')" - - - name: Build image - run: | - cd "./${{env.SERVICE_LOCATION}}" - docker build . --build-arg SOURCE=mosip --build-arg COMMIT_HASH=$(git rev-parse HEAD) --build-arg COMMIT_ID=$(git rev-parse --short HEAD) --build-arg BUILD_TIME=${{steps.date.outputs.date}} --file Dockerfile --tag ${{ env.SERVICE_NAME }} - - name: Log into registry - run: echo "${{ secrets.release_docker_hub }}" | docker login -u ${{ secrets.actor_docker_hub }} --password-stdin - - - name: Push image - run: | - IMAGE_ID=$NAMESPACE/$SERVICE_NAME - # Change all uppercase to lowercase - IMAGE_ID=$(echo $IMAGE_ID | tr '[A-Z]' '[a-z]') - echo "push version ${{steps.getPomVersion.outputs.info}}" - if [[ $BRANCH_NAME == master ]]; then - VERSION=latest - else - VERSION=$BRANCH_NAME - fi - echo IMAGE_ID=$IMAGE_ID - echo VERSION=$VERSION - docker tag $SERVICE_NAME $IMAGE_ID:$VERSION - docker push $IMAGE_ID:$VERSION - - docker-registration-processor-stage-group-7: - needs: build - - runs-on: ubuntu-latest - env: - NAMESPACE: ${{ secrets.dev_namespace_docker_hub }} - SERVICE_NAME: registration-processor-stage-group-7 - SERVICE_LOCATION: registration-processor/stage-groups/registration-processor-stage-group-7 - - steps: - - uses: actions/checkout@v2 - - uses: actions/download-artifact@v1 - with: - name: release - path: ./ - - - name: Setup branch name - run: | - # Strip git ref prefix from version - echo "BRANCH_NAME=$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')" >> $GITHUB_ENV - - name: Get version info from pom - id: getPomVersion - uses: mavrosxristoforos/get-xml-info@1.0 - with: - xml-file: ./${{ env.SERVICE_LOCATION }}/pom.xml - xpath: /*[local-name()="project"]/*[local-name()="version"] - - - name: Unzip and extract the ${{ env.SERVICE_NAME }} - run: unzip -uj "release.zip" "${{ env.SERVICE_LOCATION }}/target/*" -d "./${{ env.SERVICE_LOCATION }}/target" - - - name: Get current date - id: date - run: echo "::set-output name=date::$(date +'%Y-%m-%d')" - - - name: Build image - run: | - cd "./${{env.SERVICE_LOCATION}}" - docker build . --build-arg SOURCE=mosip --build-arg COMMIT_HASH=$(git rev-parse HEAD) --build-arg COMMIT_ID=$(git rev-parse --short HEAD) --build-arg BUILD_TIME=${{steps.date.outputs.date}} --file Dockerfile --tag ${{ env.SERVICE_NAME }} - - name: Log into registry - run: echo "${{ secrets.release_docker_hub }}" | docker login -u ${{ secrets.actor_docker_hub }} --password-stdin - - - name: Push image - run: | - IMAGE_ID=$NAMESPACE/$SERVICE_NAME - # Change all uppercase to lowercase - IMAGE_ID=$(echo $IMAGE_ID | tr '[A-Z]' '[a-z]') - echo "push version ${{steps.getPomVersion.outputs.info}}" - if [[ $BRANCH_NAME == master ]]; then - VERSION=latest - else - VERSION=$BRANCH_NAME - fi - echo IMAGE_ID=$IMAGE_ID - echo VERSION=$VERSION - docker tag $SERVICE_NAME $IMAGE_ID:$VERSION - docker push $IMAGE_ID:$VERSION - - docker-registration-processor-abis: - needs: build - - runs-on: ubuntu-latest - env: - NAMESPACE: ${{ secrets.dev_namespace_docker_hub }} - SERVICE_NAME: registration-processor-abis - SERVICE_LOCATION: registration-processor/core-processor/registration-processor-abis - - steps: - - uses: actions/checkout@v2 - - uses: actions/download-artifact@v1 - with: - name: release - path: ./ - - - name: Setup branch name - run: | - # Strip git ref prefix from version - echo "BRANCH_NAME=$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')" >> $GITHUB_ENV - - name: Get version info from pom - id: getPomVersion - uses: mavrosxristoforos/get-xml-info@1.0 - with: - xml-file: ./${{ env.SERVICE_LOCATION }}/pom.xml - xpath: /*[local-name()="project"]/*[local-name()="version"] - - - name: Unzip and extract the ${{ env.SERVICE_NAME }} - run: unzip -uj "release.zip" "${{ env.SERVICE_LOCATION }}/target/*" -d "./${{ env.SERVICE_LOCATION }}/target" - - - name: Get current date - id: date - run: echo "::set-output name=date::$(date +'%Y-%m-%d')" - - - name: Build image - run: | - cd "./${{env.SERVICE_LOCATION}}" - docker build . --build-arg SOURCE=mosip --build-arg COMMIT_HASH=$(git rev-parse HEAD) --build-arg COMMIT_ID=$(git rev-parse --short HEAD) --build-arg BUILD_TIME=${{steps.date.outputs.date}} --file Dockerfile --tag ${{ env.SERVICE_NAME }} - - name: Log into registry - run: echo "${{ secrets.release_docker_hub }}" | docker login -u ${{ secrets.actor_docker_hub }} --password-stdin - - - name: Push image - run: | - IMAGE_ID=$NAMESPACE/$SERVICE_NAME - - # Change all uppercase to lowercase - IMAGE_ID=$(echo $IMAGE_ID | tr '[A-Z]' '[a-z]') - echo "push version ${{steps.getPomVersion.outputs.info}}" - if [[ $BRANCH_NAME == master ]]; then - VERSION=latest - else - VERSION=$BRANCH_NAME - fi - echo IMAGE_ID=$IMAGE_ID - echo VERSION=$VERSION - docker tag $SERVICE_NAME $IMAGE_ID:$VERSION - docker push $IMAGE_ID:$VERSION - - docker-registration-processor-reprocessor: - needs: build - - runs-on: ubuntu-latest - env: - NAMESPACE: ${{ secrets.dev_namespace_docker_hub }} - SERVICE_NAME: registration-processor-reprocessor - SERVICE_LOCATION: registration-processor/workflow-engine/registration-processor-reprocessor - - steps: - - uses: actions/checkout@v2 - - uses: actions/download-artifact@v1 - with: - name: release - path: ./ - - - name: Setup branch name - run: | - # Strip git ref prefix from version - echo "BRANCH_NAME=$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')" >> $GITHUB_ENV - - name: Get version info from pom - id: getPomVersion - uses: mavrosxristoforos/get-xml-info@1.0 - with: - xml-file: ./${{ env.SERVICE_LOCATION }}/pom.xml - xpath: /*[local-name()="project"]/*[local-name()="version"] - - - name: Unzip and extract the ${{ env.SERVICE_NAME }} - run: unzip -uj "release.zip" "${{ env.SERVICE_LOCATION }}/target/*" -d "./${{ env.SERVICE_LOCATION }}/target" - - - name: Get current date - id: date - run: echo "::set-output name=date::$(date +'%Y-%m-%d')" - - - name: Build image - run: | - cd "./${{env.SERVICE_LOCATION}}" - docker build . --build-arg SOURCE=mosip --build-arg COMMIT_HASH=$(git rev-parse HEAD) --build-arg COMMIT_ID=$(git rev-parse --short HEAD) --build-arg BUILD_TIME=${{steps.date.outputs.date}} --file Dockerfile --tag ${{ env.SERVICE_NAME }} - - name: Log into registry - run: echo "${{ secrets.release_docker_hub }}" | docker login -u ${{ secrets.actor_docker_hub }} --password-stdin - - - name: Push image - run: | - IMAGE_ID=$NAMESPACE/$SERVICE_NAME - - # Change all uppercase to lowercase - IMAGE_ID=$(echo $IMAGE_ID | tr '[A-Z]' '[a-z]') - echo "push version ${{steps.getPomVersion.outputs.info}}" - if [[ $BRANCH_NAME == master ]]; then - VERSION=latest - else - VERSION=$BRANCH_NAME - fi - echo IMAGE_ID=$IMAGE_ID - echo VERSION=$VERSION - docker tag $SERVICE_NAME $IMAGE_ID:$VERSION - docker push $IMAGE_ID:$VERSION - docker-registration-processor-dmz-packet-server: - needs: build - - runs-on: ubuntu-latest - env: - NAMESPACE: ${{ secrets.dev_namespace_docker_hub }} - SERVICE_NAME: registration-processor-dmz-packet-server - SERVICE_LOCATION: registration-processor/init/registration-processor-dmz-packet-server - - steps: - - uses: actions/checkout@v2 - - - name: Setup branch name - run: | - # Strip git ref prefix from version - echo "BRANCH_NAME=$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')" >> $GITHUB_ENV - - name: Get version info - id: getVersion - uses: mavrosxristoforos/get-xml-info@1.0 - with: - xml-file: ./${{ env.SERVICE_LOCATION }}/version.xml - xpath: version - - - name: Get current date - id: date - run: echo "::set-output name=date::$(date +'%Y-%m-%d')" - - - name: Build image - run: | - cd "./${{env.SERVICE_LOCATION}}" - docker build . --build-arg SOURCE=mosip --build-arg COMMIT_HASH=$(git rev-parse HEAD) --build-arg COMMIT_ID=$(git rev-parse --short HEAD) --build-arg BUILD_TIME=${{steps.date.outputs.date}} --file Dockerfile --tag ${{ env.SERVICE_NAME }} - - name: Log into registry - run: echo "${{ secrets.release_docker_hub }}" | docker login -u ${{ secrets.actor_docker_hub }} --password-stdin - - - name: Push image - run: | - IMAGE_ID=$NAMESPACE/$SERVICE_NAME - - # Change all uppercase to lowercase - IMAGE_ID=$(echo $IMAGE_ID | tr '[A-Z]' '[a-z]') - echo "push version ${{steps.getVersion.outputs.info}}" - VERSION=${{steps.getVersion.outputs.info}} - echo IMAGE_ID=$IMAGE_ID - echo VERSION=$VERSION - docker tag $SERVICE_NAME $IMAGE_ID:$VERSION - docker push $IMAGE_ID:$VERSION - docker-registration-processor-registration-status-service: - needs: build - - runs-on: ubuntu-latest - env: - NAMESPACE: ${{ secrets.dev_namespace_docker_hub }} - SERVICE_NAME: registration-processor-registration-status-service - SERVICE_LOCATION: registration-processor/init/registration-processor-registration-status-service - - steps: - - uses: actions/checkout@v2 - - uses: actions/download-artifact@v1 - with: - name: release - path: ./ - - - name: Setup branch name - run: | - # Strip git ref prefix from version - echo "BRANCH_NAME=$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')" >> $GITHUB_ENV - - name: Get version info from pom - id: getPomVersion - uses: mavrosxristoforos/get-xml-info@1.0 - with: - xml-file: ./${{ env.SERVICE_LOCATION }}/pom.xml - xpath: /*[local-name()="project"]/*[local-name()="version"] - - - name: Unzip and extract the ${{ env.SERVICE_NAME }} - run: unzip -uj "release.zip" "${{ env.SERVICE_LOCATION }}/target/*" -d "./${{ env.SERVICE_LOCATION }}/target" - - - name: Get current date - id: date - run: echo "::set-output name=date::$(date +'%Y-%m-%d')" - - - name: Build image - run: | - cd "./${{env.SERVICE_LOCATION}}" - docker build . --build-arg SOURCE=mosip --build-arg COMMIT_HASH=$(git rev-parse HEAD) --build-arg COMMIT_ID=$(git rev-parse --short HEAD) --build-arg BUILD_TIME=${{steps.date.outputs.date}} --file Dockerfile --tag ${{ env.SERVICE_NAME }} - - name: Log into registry - run: echo "${{ secrets.release_docker_hub }}" | docker login -u ${{ secrets.actor_docker_hub }} --password-stdin - - - name: Push image - run: | - IMAGE_ID=$NAMESPACE/$SERVICE_NAME - - # Change all uppercase to lowercase - IMAGE_ID=$(echo $IMAGE_ID | tr '[A-Z]' '[a-z]') - echo "push version ${{steps.getPomVersion.outputs.info}}" - if [[ $BRANCH_NAME == master ]]; then - VERSION=latest - else - VERSION=$BRANCH_NAME - fi - echo IMAGE_ID=$IMAGE_ID - echo VERSION=$VERSION - docker tag $SERVICE_NAME $IMAGE_ID:$VERSION - docker push $IMAGE_ID:$VERSION - docker-registration-processor-notification-service: - needs: build - - runs-on: ubuntu-latest - env: - NAMESPACE: ${{ secrets.dev_namespace_docker_hub }} - SERVICE_NAME: registration-processor-notification-service - SERVICE_LOCATION: registration-processor/registration-processor-notification-service - - steps: - - uses: actions/checkout@v2 - - uses: actions/download-artifact@v1 - with: - name: release - path: ./ - - - name: Setup branch name - run: | - # Strip git ref prefix from version - echo "BRANCH_NAME=$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')" >> $GITHUB_ENV - - name: Get version info from pom - id: getPomVersion - uses: mavrosxristoforos/get-xml-info@1.0 - with: - xml-file: ./${{ env.SERVICE_LOCATION }}/pom.xml - xpath: /*[local-name()="project"]/*[local-name()="version"] - - - name: Unzip and extract the ${{ env.SERVICE_NAME }} - run: unzip -uj "release.zip" "${{ env.SERVICE_LOCATION }}/target/*" -d "./${{ env.SERVICE_LOCATION }}/target" - - - name: Get current date - id: date - run: echo "::set-output name=date::$(date +'%Y-%m-%d')" - - - name: Build image - run: | - cd "./${{env.SERVICE_LOCATION}}" - docker build . --build-arg SOURCE=mosip --build-arg COMMIT_HASH=$(git rev-parse HEAD) --build-arg COMMIT_ID=$(git rev-parse --short HEAD) --build-arg BUILD_TIME=${{steps.date.outputs.date}} --file Dockerfile --tag ${{ env.SERVICE_NAME }} - - name: Log into registry - run: echo "${{ secrets.release_docker_hub }}" | docker login -u ${{ secrets.actor_docker_hub }} --password-stdin - - - name: Push image - run: | - IMAGE_ID=$NAMESPACE/$SERVICE_NAME - # Change all uppercase to lowercase - IMAGE_ID=$(echo $IMAGE_ID | tr '[A-Z]' '[a-z]') - echo "push version ${{steps.getPomVersion.outputs.info}}" - if [[ $BRANCH_NAME == master ]]; then - VERSION=latest - else - VERSION=$BRANCH_NAME - fi - echo IMAGE_ID=$IMAGE_ID - echo VERSION=$VERSION - docker tag $SERVICE_NAME $IMAGE_ID:$VERSION - docker push $IMAGE_ID:$VERSION - docker-registration-processor-landing-zone: - needs: build - - runs-on: ubuntu-latest - env: - NAMESPACE: ${{ secrets.dev_namespace_docker_hub }} - SERVICE_NAME: registration-processor-landing-zone - SERVICE_LOCATION: registration-processor/registration-processor-landing-zone - - steps: - - uses: actions/checkout@v2 - - uses: actions/download-artifact@v1 - with: - name: release - path: ./ - - - name: Setup branch name - run: | - # Strip git ref prefix from version - echo "BRANCH_NAME=$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')" >> $GITHUB_ENV - - name: Get version info from pom - id: getPomVersion - uses: mavrosxristoforos/get-xml-info@1.0 - with: - xml-file: ./${{ env.SERVICE_LOCATION }}/pom.xml - xpath: /*[local-name()="project"]/*[local-name()="version"] - - - name: Unzip and extract the ${{ env.SERVICE_NAME }} - run: unzip -uj "release.zip" "${{ env.SERVICE_LOCATION }}/target/*" -d "./${{ env.SERVICE_LOCATION }}/target" - - - name: Get current date - id: date - run: echo "::set-output name=date::$(date +'%Y-%m-%d')" - - - name: Build image - run: | - cd "./${{env.SERVICE_LOCATION}}" - docker build . --build-arg SOURCE=mosip --build-arg COMMIT_HASH=$(git rev-parse HEAD) --build-arg COMMIT_ID=$(git rev-parse --short HEAD) --build-arg BUILD_TIME=${{steps.date.outputs.date}} --file Dockerfile --tag ${{ env.SERVICE_NAME }} - - name: Log into registry - run: echo "${{ secrets.release_docker_hub }}" | docker login -u ${{ secrets.actor_docker_hub }} --password-stdin - - - name: Push image - run: | - IMAGE_ID=$NAMESPACE/$SERVICE_NAME - # Change all uppercase to lowercase - IMAGE_ID=$(echo $IMAGE_ID | tr '[A-Z]' '[a-z]') - echo "push version ${{steps.getPomVersion.outputs.info}}" - if [[ $BRANCH_NAME == master ]]; then - VERSION=latest - else - VERSION=$BRANCH_NAME - fi - echo IMAGE_ID=$IMAGE_ID - echo VERSION=$VERSION - docker tag $SERVICE_NAME $IMAGE_ID:$VERSION - docker push $IMAGE_ID:$VERSION - - docker-registration-processor-workflow-manager-service: - needs: build - - runs-on: ubuntu-latest - env: - NAMESPACE: ${{ secrets.dev_namespace_docker_hub }} - SERVICE_NAME: registration-processor-workflow-manager-service - SERVICE_LOCATION: registration-processor/workflow-engine/registration-processor-workflow-manager-service - - steps: - - uses: actions/checkout@v2 - - uses: actions/download-artifact@v1 - with: - name: release - path: ./ - - - name: Setup branch name - run: | - # Strip git ref prefix from version - echo "BRANCH_NAME=$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')" >> $GITHUB_ENV - - name: Get version info from pom - id: getPomVersion - uses: mavrosxristoforos/get-xml-info@1.0 - with: - xml-file: ./${{ env.SERVICE_LOCATION }}/pom.xml - xpath: /*[local-name()="project"]/*[local-name()="version"] - - - name: Unzip and extract the ${{ env.SERVICE_NAME }} - run: unzip -uj "release.zip" "${{ env.SERVICE_LOCATION }}/target/*" -d "./${{ env.SERVICE_LOCATION }}/target" - - - name: Get current date - id: date - run: echo "::set-output name=date::$(date +'%Y-%m-%d')" - - - name: Build image - run: | - cd "./${{env.SERVICE_LOCATION}}" - docker build . --build-arg SOURCE=mosip --build-arg COMMIT_HASH=$(git rev-parse HEAD) --build-arg COMMIT_ID=$(git rev-parse --short HEAD) --build-arg BUILD_TIME=${{steps.date.outputs.date}} --file Dockerfile --tag ${{ env.SERVICE_NAME }} - - name: Log into registry - run: echo "${{ secrets.release_docker_hub }}" | docker login -u ${{ secrets.actor_docker_hub }} --password-stdin - - - name: Push image - run: | - IMAGE_ID=$NAMESPACE/$SERVICE_NAME - # Change all uppercase to lowercase - IMAGE_ID=$(echo $IMAGE_ID | tr '[A-Z]' '[a-z]') - echo "push version ${{steps.getPomVersion.outputs.info}}" - if [[ $BRANCH_NAME == master ]]; then - VERSION=latest - else - VERSION=$BRANCH_NAME - fi - echo IMAGE_ID=$IMAGE_ID - echo VERSION=$VERSION - docker tag $SERVICE_NAME $IMAGE_ID:$VERSION - docker push $IMAGE_ID:$VERSION - registration-processor-common-camel-bridge: - needs: build - - runs-on: ubuntu-latest - env: - NAMESPACE: ${{ secrets.dev_namespace_docker_hub }} - SERVICE_NAME: registration-processor-common-camel-bridge - SERVICE_LOCATION: registration-processor/registration-processor-common-camel-bridge - - steps: - - uses: actions/checkout@v2 - - uses: actions/download-artifact@v1 - with: - name: release - path: ./ - - - name: Setup branch name - run: | - # Strip git ref prefix from version - echo "BRANCH_NAME=$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')" >> $GITHUB_ENV - - name: Get version info from pom - id: getPomVersion - uses: mavrosxristoforos/get-xml-info@1.0 - with: - xml-file: ./${{ env.SERVICE_LOCATION }}/pom.xml - xpath: /*[local-name()="project"]/*[local-name()="version"] - - - name: Unzip and extract the ${{ env.SERVICE_NAME }} - run: unzip -uj "release.zip" "${{ env.SERVICE_LOCATION }}/target/*" -d "./${{ env.SERVICE_LOCATION }}/target" - - - name: Get current date - id: date - run: echo "::set-output name=date::$(date +'%Y-%m-%d')" - - - name: Build image - run: | - cd "./${{env.SERVICE_LOCATION}}" - docker build . --build-arg SOURCE=mosip --build-arg COMMIT_HASH=$(git rev-parse HEAD) --build-arg COMMIT_ID=$(git rev-parse --short HEAD) --build-arg BUILD_TIME=${{steps.date.outputs.date}} --file Dockerfile --tag ${{ env.SERVICE_NAME }} - - name: Log into registry - run: echo "${{ secrets.release_docker_hub }}" | docker login -u ${{ secrets.actor_docker_hub }} --password-stdin - - - name: Push image - run: | - IMAGE_ID=$NAMESPACE/$SERVICE_NAME - - # Change all uppercase to lowercase - IMAGE_ID=$(echo $IMAGE_ID | tr '[A-Z]' '[a-z]') - echo "push version ${{steps.getPomVersion.outputs.info}}" - if [[ $BRANCH_NAME == master ]]; then - VERSION=latest - else - VERSION=$BRANCH_NAME - fi - echo IMAGE_ID=$IMAGE_ID - echo VERSION=$VERSION - docker tag $SERVICE_NAME $IMAGE_ID:$VERSION - docker push $IMAGE_ID:$VERSION - - sonar_analysis: - runs-on: ubuntu-latest - env: - NAMESPACE: ${{ secrets.dev_namespace_docker_hub }} - SERVICE_NAME: registration-client - SERVICE_LOCATION: registration - steps: - - uses: actions/checkout@v2 - - name: Set up JDK 11 - uses: actions/setup-java@v1 - with: - ref: ${{ github.ref }} - java-version: 11 - server-id: ossrh # Value of the distributionManagement/repository/id field of the pom.xml - settings-path: ${{ github.workspace }} # location for the settings.xml file - - - name: Setup branch and env - run: | - # Strip git ref prefix from version - echo "BRANCH_NAME=$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')" >> $GITHUB_ENV - echo "GPG_TTY=$(tty)" >> $GITHUB_ENV - - - uses: actions/cache@v1 - with: - path: ~/.m2/repository - key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }} - restore-keys: | - ${{ runner.os }}-maven-${{ env.BRANCH_NAME }} - - name: Setup the settings file for ossrh server - run: echo " ossrh ${{secrets.ossrh_user}} ${{secrets.ossrh_secret}} ossrh true gpg2 ${{secrets.gpg_secret}} allow-snapshots true snapshots-repo https://oss.sonatype.org/content/repositories/snapshots false true releases-repo https://oss.sonatype.org/service/local/staging/deploy/maven2 true false staged-releases https://oss.sonatype.org/service/local/staging/deploy/maven2/ sonar . https://sonarcloud.io false " > $GITHUB_WORKSPACE/settings.xml - - - name: Install xmllint - run: | - sudo apt-get update - sudo apt-get install libxml2-utils - - - name: Analyze with SonarCloud - run: | - cd registration-processor - mvn -B -Dgpg.skip verify sonar:sonar -Dsonar.projectKey=mosip_${{ github.event.repository.name }} -Dsonar.organization=${{ secrets.ORG_KEY }} -Dsonar.host.url=https://sonarcloud.io -Dsonar.login=${{ secrets.SONAR_TOKEN }} - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} - - - uses: 8398a7/action-slack@v3 - with: - status: ${{ job.status }} - fields: repo,message,author,ref,job # selectable (default: repo,message) - env: - SLACK_WEBHOOK_URL: ${{ secrets.SLACK_DEVOPS_WEBHOOK }} # required - if: failure() # Pick up events even if the job fails or is canceled. diff --git a/.github/workflows/release-changes.yml b/.github/workflows/release-changes.yml new file mode 100644 index 00000000000..783d4896a2a --- /dev/null +++ b/.github/workflows/release-changes.yml @@ -0,0 +1,29 @@ +name: Release/pre-release Preparation. + +on: + workflow_dispatch: + inputs: + MESSAGE: + description: 'Triggered for release or pe-release' + required: false + default: 'Release Preparation' + RELEASE_TAG: + description: 'tag to update' + required: true + SNAPSHOT_TAG: + description: 'tag to be replaced' + required: true + BASE: + description: 'base branch for PR' + required: true +jobs: + maven-release-preparation: + uses: mosip/kattu/.github/workflows/release-changes.yml@master + with: + MESSAGE: ${{ inputs.MESSAGE }} + RELEASE_TAG: ${{ inputs.RELEASE_TAG }} + SNAPSHOT_TAG: ${{ inputs.SNAPSHOT_TAG }} + BASE: ${{ inputs.BASE }} + secrets: + SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK }} + ACTION_PAT: ${{ secrets.ACTION_PAT }} \ No newline at end of file diff --git a/.github/workflows/release_changes.yml b/.github/workflows/release_changes.yml deleted file mode 100644 index cc9c2956d9e..00000000000 --- a/.github/workflows/release_changes.yml +++ /dev/null @@ -1,56 +0,0 @@ -name: Release/pre-release Preparation. - -on: - workflow_dispatch: - inputs: - message: - description: 'Triggered for release or pe-release' - required: false - default: 'Release Preparation' - releaseTags: - description: 'tag to update' - required: true - snapshotTags: - description: 'tag to be replaced' - required: true - base: - description: 'base branch for PR' - required: true -jobs: - build: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v2 - - name: Setup branch and env - run: | - # Strip git ref prefix from version - echo "BRANCH_NAME=$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')" >> $GITHUB_ENV - echo "GPG_TTY=$(tty)" >> $GITHUB_ENV - - - name: Mannualy changing the pom versions - run: find . -type f -name "*pom.xml" -print0 | xargs -0 sed -i "s/${{ github.event.inputs.snapshotTags }}/${{ github.event.inputs.releaseTags }}/g" - - - name: Updating the Release URL in POM - run: | - cd .github/workflows - sed -i 's/OSSRH_SNAPSHOT_URL/RELEASE_URL/g' push_trigger.yml - - - name: Updating libs-snapshot-local to libs-release local for artifactory URL's. - run: find . -type f -name "*Dockerfile" -print0 | xargs -0 sed -i "s/libs-snapshot-local/libs-release-local/g" - - - name: removing -DskipTests - run: find . -type f -name "*push_trigger.yml" -print0 | xargs -0 sed -i "s/"-DskipTests"//g" - -# - name: removing --Dgpg.skip -# run: find . -type f -name "*push_trigger.yml" -print0 | xargs -0 sed -i "s/"-Dgpg.skip"//g" - - - name: Create Pull Request - uses: peter-evans/create-pull-request@v3 - with: - token: ${{ secrets.ACTION_PAT }} - commit-message: Updated Pom versions for release changes - title: Release changes - body: Automated PR for ${{ github.event.inputs.releaseTags }} release. - branch: release-branch - delete-branch: true - base: ${{ github.event.inputs.base }} diff --git a/.github/workflows/release_trigger.yml b/.github/workflows/release_trigger.yml deleted file mode 100644 index 08bef64e9a0..00000000000 --- a/.github/workflows/release_trigger.yml +++ /dev/null @@ -1,739 +0,0 @@ - -name: Release maven packages and docker upon a release - -on: - release: - types: [published] - -jobs: - build: - - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v2 - - name: Set up JDK 11 - uses: actions/setup-java@v1 - with: - ref: ${{ github.ref }} - java-version: 11 - server-id: ossrh # Value of the distributionManagement/repository/id field of the pom.xml - settings-path: ${{ github.workspace }} # location for the settings.xml file - - - name: Setup branch and GPG public key - run: | - # Strip git ref prefix from version - echo "::set-env name=BRANCH_NAME::$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')" - echo ${{ env.BRANCH_NAME }} - echo "::set-env name=GPG_TTY::$(tty)" - echo ${{ env.GPG_TTY }} - sudo apt-get --yes install gnupg2 - gpg2 --import ./.github/keys/mosipgpgkey_pub.gpg - gpg2 --quiet --batch --passphrase=${{secrets.gpg_secret}} --allow-secret-key-import --import ./.github/keys/mosipgpgkey_sec.gpg - - - uses: actions/cache@v1 - with: - path: ~/.m2/repository - key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }} - restore-keys: | - ${{ runner.os }}-maven-${{ env.BRANCH_NAME }} - - - name: Setup the settings file for ossrh server - run: echo " ossrh ${{secrets.ossrh_user}} ${{secrets.ossrh_secret}} ossrh true gpg2 ${{secrets.gpg_secret}} allow-snapshots true snapshots-repo https://oss.sonatype.org/content/repositories/snapshots false true releases-repo https://oss.sonatype.org/service/local/staging/deploy/maven2 true false sonar . https://sonarcloud.io false " > $GITHUB_WORKSPACE/settings.xml - - - name: Build with Maven - run: | - cd registration-processor - mvn -B package -s $GITHUB_WORKSPACE/settings.xml --file pom.xml - - - name: Ready the springboot artifacts - run: find -name '*.jar' -executable -type f -exec zip release.zip {} + - - - - name: Upload the springboot jars - uses: actions/upload-artifact@v1 - with: - name: release - path: ./release.zip - - - name: Build registration-processor-stage-group-1 image - run: | - # The Mosip Stage Executor is not packaged as part of release.zip - cd "./$SERVICE_LOCATION" - docker build . --file Dockerfile --tag $SERVICE_NAME - env: - SERVICE_NAME: registration-processor-stage-group-1 - SERVICE_LOCATION: registration-processor/stage-groups/registration-processor-stage-group-1 - - name: Log into registry - run: echo "${{ secrets.release_docker_hub }}" | docker login -u ${{ secrets.actor_docker_hub }} --password-stdin - - - name: Push image - run: | - IMAGE_ID=$NAMESPACE/$SERVICE_NAME - - # Change all uppercase to lowercase - IMAGE_ID=$(echo $IMAGE_ID | tr '[A-Z]' '[a-z]') - VERSION=$BRANCH_NAME - echo IMAGE_ID=$IMAGE_ID - echo VERSION=$VERSION - docker tag $SERVICE_NAME $IMAGE_ID:$VERSION - docker push $IMAGE_ID:$VERSION - env: - NAMESPACE: ${{ secrets.dev_namespace_docker_hub }} - SERVICE_NAME: registration-processor-stage-group-1 - SERVICE_LOCATION: registration-processor/stage-groups/registration-processor-stage-group-1 - - - name: Build registration-processor-stage-group-2 image - run: | - # The Mosip Stage Executor is not packaged as part of release.zip - cd "./$SERVICE_LOCATION" - docker build . --file Dockerfile --tag $SERVICE_NAME - env: - SERVICE_NAME: registration-processor-stage-group-2 - SERVICE_LOCATION: registration-processor/stage-groups/registration-processor-stage-group-2 - - name: Log into registry - run: echo "${{ secrets.release_docker_hub }}" | docker login -u ${{ secrets.actor_docker_hub }} --password-stdin - - - name: Push image - run: | - IMAGE_ID=$NAMESPACE/$SERVICE_NAME - - # Change all uppercase to lowercase - IMAGE_ID=$(echo $IMAGE_ID | tr '[A-Z]' '[a-z]') - VERSION=$BRANCH_NAME - echo IMAGE_ID=$IMAGE_ID - echo VERSION=$VERSION - docker tag $SERVICE_NAME $IMAGE_ID:$VERSION - docker push $IMAGE_ID:$VERSION - env: - NAMESPACE: ${{ secrets.dev_namespace_docker_hub }} - SERVICE_NAME: registration-processor-stage-group-2 - SERVICE_LOCATION: registration-processor/stage-groups/registration-processor-stage-group-2 - - - name: Build registration-processor-stage-group-3 image - run: | - # The Mosip Stage Executor is not packaged as part of release.zip - cd "./$SERVICE_LOCATION" - docker build . --file Dockerfile --tag $SERVICE_NAME - env: - SERVICE_NAME: registration-processor-stage-group-3 - SERVICE_LOCATION: registration-processor/stage-groups/registration-processor-stage-group-3 - - name: Log into registry - run: echo "${{ secrets.release_docker_hub }}" | docker login -u ${{ secrets.actor_docker_hub }} --password-stdin - - - name: Push image - run: | - IMAGE_ID=$NAMESPACE/$SERVICE_NAME - - # Change all uppercase to lowercase - IMAGE_ID=$(echo $IMAGE_ID | tr '[A-Z]' '[a-z]') - VERSION=$BRANCH_NAME - echo IMAGE_ID=$IMAGE_ID - echo VERSION=$VERSION - docker tag $SERVICE_NAME $IMAGE_ID:$VERSION - docker push $IMAGE_ID:$VERSION - env: - NAMESPACE: ${{ secrets.dev_namespace_docker_hub }} - SERVICE_NAME: registration-processor-stage-group-3 - SERVICE_LOCATION: registration-processor/stage-groups/registration-processor-stage-group-3 - - - name: Build registration-processor-stage-group-4 image - run: | - # The Mosip Stage Executor is not packaged as part of release.zip - cd "./$SERVICE_LOCATION" - docker build . --file Dockerfile --tag $SERVICE_NAME - env: - SERVICE_NAME: registration-processor-stage-group-4 - SERVICE_LOCATION: registration-processor/stage-groups/registration-processor-stage-group-4 - - name: Log into registry - run: echo "${{ secrets.release_docker_hub }}" | docker login -u ${{ secrets.actor_docker_hub }} --password-stdin - - - name: Push image - run: | - IMAGE_ID=$NAMESPACE/$SERVICE_NAME - - # Change all uppercase to lowercase - IMAGE_ID=$(echo $IMAGE_ID | tr '[A-Z]' '[a-z]') - VERSION=$BRANCH_NAME - echo IMAGE_ID=$IMAGE_ID - echo VERSION=$VERSION - docker tag $SERVICE_NAME $IMAGE_ID:$VERSION - docker push $IMAGE_ID:$VERSION - env: - NAMESPACE: ${{ secrets.dev_namespace_docker_hub }} - SERVICE_NAME: registration-processor-stage-group-4 - SERVICE_LOCATION: registration-processor/stage-groups/registration-processor-stage-group-4 - - - name: Build registration-processor-stage-group-5 image - run: | - # The Mosip Stage Executor is not packaged as part of release.zip - cd "./$SERVICE_LOCATION" - docker build . --file Dockerfile --tag $SERVICE_NAME - env: - SERVICE_NAME: registration-processor-stage-group-5 - SERVICE_LOCATION: registration-processor/stage-groups/registration-processor-stage-group-5 - - name: Log into registry - run: echo "${{ secrets.release_docker_hub }}" | docker login -u ${{ secrets.actor_docker_hub }} --password-stdin - - - name: Push image - run: | - IMAGE_ID=$NAMESPACE/$SERVICE_NAME - - # Change all uppercase to lowercase - IMAGE_ID=$(echo $IMAGE_ID | tr '[A-Z]' '[a-z]') - VERSION=$BRANCH_NAME - echo IMAGE_ID=$IMAGE_ID - echo VERSION=$VERSION - docker tag $SERVICE_NAME $IMAGE_ID:$VERSION - docker push $IMAGE_ID:$VERSION - env: - NAMESPACE: ${{ secrets.dev_namespace_docker_hub }} - SERVICE_NAME: registration-processor-stage-group-5 - SERVICE_LOCATION: registration-processor/stage-groups/registration-processor-stage-group-5 - - - name: Build registration-processor-stage-group-6 image - run: | - # The Mosip Stage Executor is not packaged as part of release.zip - cd "./$SERVICE_LOCATION" - docker build . --file Dockerfile --tag $SERVICE_NAME - env: - SERVICE_NAME: registration-processor-stage-group-6 - SERVICE_LOCATION: registration-processor/stage-groups/registration-processor-stage-group-6 - - name: Log into registry - run: echo "${{ secrets.release_docker_hub }}" | docker login -u ${{ secrets.actor_docker_hub }} --password-stdin - - - name: Push image - run: | - IMAGE_ID=$NAMESPACE/$SERVICE_NAME - - # Change all uppercase to lowercase - IMAGE_ID=$(echo $IMAGE_ID | tr '[A-Z]' '[a-z]') - VERSION=$BRANCH_NAME - echo IMAGE_ID=$IMAGE_ID - echo VERSION=$VERSION - docker tag $SERVICE_NAME $IMAGE_ID:$VERSION - docker push $IMAGE_ID:$VERSION - env: - NAMESPACE: ${{ secrets.dev_namespace_docker_hub }} - SERVICE_NAME: registration-processor-stage-group-6 - SERVICE_LOCATION: registration-processor/stage-groups/registration-processor-stage-group-6 - - - - name: Build registration-processor-stage-group-7 image - run: | - # The Mosip Stage Executor is not packaged as part of release.zip - cd "./$SERVICE_LOCATION" - docker build . --file Dockerfile --tag $SERVICE_NAME - env: - SERVICE_NAME: registration-processor-stage-group-7 - SERVICE_LOCATION: registration-processor/stage-groups/registration-processor-stage-group-7 - - name: Log into registry - run: echo "${{ secrets.release_docker_hub }}" | docker login -u ${{ secrets.actor_docker_hub }} --password-stdin - - - name: Push image - run: | - IMAGE_ID=$NAMESPACE/$SERVICE_NAME - - # Change all uppercase to lowercase - IMAGE_ID=$(echo $IMAGE_ID | tr '[A-Z]' '[a-z]') - VERSION=$BRANCH_NAME - echo IMAGE_ID=$IMAGE_ID - echo VERSION=$VERSION - docker tag $SERVICE_NAME $IMAGE_ID:$VERSION - docker push $IMAGE_ID:$VERSION - env: - NAMESPACE: ${{ secrets.dev_namespace_docker_hub }} - SERVICE_NAME: registration-processor-stage-group-7 - SERVICE_LOCATION: registration-processor/stage-groups/registration-processor-stage-group-7 - - - - - name: Build camel bridge image - run: | - # The camel bridge is not packaged as part of release.zip - cd "./registration-processor/registration-processor-common-camel-bridge" - docker build . --file Dockerfile --tag registration-processor-common-camel-bridge - - name: Log into registry - run: echo "${{ secrets.release_docker_hub }}" | docker login -u ${{ secrets.actor_docker_hub }} --password-stdin - - - name: Push image - run: | - IMAGE_ID=$NAMESPACE/$SERVICE_NAME - - # Change all uppercase to lowercase - IMAGE_ID=$(echo $IMAGE_ID | tr '[A-Z]' '[a-z]') - VERSION=$BRANCH_NAME - echo IMAGE_ID=$IMAGE_ID - echo VERSION=$VERSION - docker tag $SERVICE_NAME $IMAGE_ID:$VERSION - docker push $IMAGE_ID:$VERSION - env: - NAMESPACE: ${{ secrets.dev_namespace_docker_hub }} - SERVICE_NAME: registration-processor-common-camel-bridge - SERVICE_LOCATION: registration-processor/registration-processor-common-camel-bridge - - publish_to_nexus: - - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v2 - - name: Set up JDK 11 - uses: actions/setup-java@v1 - with: - ref: ${{ github.ref }} - java-version: 11 - server-id: ossrh # Value of the distributionManagement/repository/id field of the pom.xml - settings-path: ${{ github.workspace }} # location for the settings.xml file - - uses: actions/checkout@v2 - - - - name: Setup branch and GPG public key - run: | - # Strip git ref prefix from version - echo "::set-env name=BRANCH_NAME::$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')" - echo ${{ env.BRANCH_NAME }} - echo "::set-env name=GPG_TTY::$(tty)" - echo ${{ env.GPG_TTY }} - sudo apt-get --yes install gnupg2 - gpg2 --import ./.github/keys/mosipgpgkey_pub.gpg - gpg2 --quiet --batch --passphrase=${{secrets.gpg_secret}} --allow-secret-key-import --import ./.github/keys/mosipgpgkey_sec.gpg - - - uses: actions/cache@v1 - with: - path: ~/.m2/repository - key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }} - restore-keys: | - ${{ runner.os }}-maven-${{ env.BRANCH_NAME }} - - - name: Install xmllint - run: | - sudo apt-get update - sudo apt-get install libxml2-utils - - - name: Setup the settings file for ossrh server - run: echo " ossrh ${{secrets.ossrh_user}} ${{secrets.ossrh_secret}} ossrh true gpg2 ${{secrets.gpg_secret}} allow-snapshots true snapshots-repo https://oss.sonatype.org/content/repositories/snapshots false true releases-repo https://oss.sonatype.org/service/local/staging/deploy/maven2 true false sonar . https://sonarcloud.io false " > $GITHUB_WORKSPACE/settings.xml - - - name: Build with Maven - run: | - cd registration-processor - mvn -B package --file pom.xml -s $GITHUB_WORKSPACE/settings.xml - - - name: Publish the maven package - run: | - chmod +x ./deploy.sh - ./deploy.sh registration-processor $GITHUB_WORKSPACE/settings.xml .* - env: - GITHUB_TOKEN: ${{ secrets.access_token }} - GPG_TTY: $(tty) - - name: Analyze with SonarCloud - run: | - cd registration-processor - mvn -B verify sonar:sonar -Dsonar.projectKey=${{ secrets.PROJECT_KEY }} -Dsonar.organization=${{ secrets.ORG_KEY }} -Dsonar.host.url=https://sonarcloud.io -Dsonar.login=${{ secrets.SONAR_TOKEN }} - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} - docker-registration-processor-registration-transaction-service: - needs: build - - runs-on: ubuntu-latest - env: - NAMESPACE: mosipdev - SERVICE_NAME: registration-processor-registration-transaction-service - SERVICE_LOCATION: registration-processor/post-processor/registration-processor-registration-transaction-service - - steps: - - uses: actions/checkout@v2 - - uses: actions/download-artifact@v1 - with: - name: release - path: ./ - - - name: Setup branch name - run: | - # Strip git ref prefix from version - echo "::set-env name=BRANCH_NAME::$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')" - echo ${{ env.BRANCH_NAME }} - - - name: Get version info from pom - id: getPomVersion - uses: mavrosxristoforos/get-xml-info@1.0 - with: - xml-file: ./${{ env.SERVICE_LOCATION }}/pom.xml - xpath: /*[local-name()="project"]/*[local-name()="version"] - - - name: Unzip and extract the ${{ env.SERVICE_NAME }} - run: unzip -uj "release.zip" "${{ env.SERVICE_LOCATION }}/target/*" -d "./${{ env.SERVICE_LOCATION }}/target" - - - name: Build image - run: | - cd "./${{env.SERVICE_LOCATION}}" - docker build . --file Dockerfile --tag ${{ env.SERVICE_NAME }} - - name: Log into registry - run: echo "${{ secrets.release_docker_hub }}" | docker login -u ${{ secrets.actor_docker_hub }} --password-stdin - - - name: Push image - run: | - IMAGE_ID=$NAMESPACE/$SERVICE_NAME - - # Change all uppercase to lowercase - IMAGE_ID=$(echo $IMAGE_ID | tr '[A-Z]' '[a-z]') - echo "push version ${{steps.getPomVersion.outputs.info}}" - VERSION=$BRANCH_NAME - echo IMAGE_ID=$IMAGE_ID - echo VERSION=$VERSION - docker tag $SERVICE_NAME $IMAGE_ID:$VERSION - docker push $IMAGE_ID:$VERSION - - docker-registration-processor-abis: - needs: build - - runs-on: ubuntu-latest - env: - NAMESPACE: mosipdev - SERVICE_NAME: registration-processor-abis - SERVICE_LOCATION: registration-processor/core-processor/registration-processor-abis - - steps: - - uses: actions/checkout@v2 - - uses: actions/download-artifact@v1 - with: - name: release - path: ./ - - - name: Setup branch name - run: | - # Strip git ref prefix from version - echo "::set-env name=BRANCH_NAME::$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')" - - - name: Get version info from pom - id: getPomVersion - uses: mavrosxristoforos/get-xml-info@1.0 - with: - xml-file: ./${{ env.SERVICE_LOCATION }}/pom.xml - xpath: /*[local-name()="project"]/*[local-name()="version"] - - - name: Unzip and extract the ${{ env.SERVICE_NAME }} - run: unzip -uj "release.zip" "${{ env.SERVICE_LOCATION }}/target/*" -d "./${{ env.SERVICE_LOCATION }}/target" - - - name: Build image - run: | - cd "./${{env.SERVICE_LOCATION}}" - docker build . --file Dockerfile --tag ${{ env.SERVICE_NAME }} - - name: Log into registry - run: echo "${{ secrets.release_docker_hub }}" | docker login -u ${{ secrets.actor_docker_hub }} --password-stdin - - - name: Push image - run: | - IMAGE_ID=$NAMESPACE/$SERVICE_NAME - - # Change all uppercase to lowercase - IMAGE_ID=$(echo $IMAGE_ID | tr '[A-Z]' '[a-z]') - echo "push version ${{steps.getPomVersion.outputs.info}}" - VERSION=$BRANCH_NAME - echo IMAGE_ID=$IMAGE_ID - echo VERSION=$VERSION - docker tag $SERVICE_NAME $IMAGE_ID:$VERSION - docker push $IMAGE_ID:$VERSION - - docker-registration-processor-reprocessor: - needs: build - - runs-on: ubuntu-latest - env: - NAMESPACE: mosipdev - SERVICE_NAME: registration-processor-reprocessor - SERVICE_LOCATION: registration-processor/workflow-engine/registration-processor-reprocessor - - steps: - - uses: actions/checkout@v2 - - uses: actions/download-artifact@v1 - with: - name: release - path: ./ - - - name: Setup branch name - run: | - # Strip git ref prefix from version - echo "::set-env name=BRANCH_NAME::$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')" - - - name: Get version info from pom - id: getPomVersion - uses: mavrosxristoforos/get-xml-info@1.0 - with: - xml-file: ./${{ env.SERVICE_LOCATION }}/pom.xml - xpath: /*[local-name()="project"]/*[local-name()="version"] - - - name: Unzip and extract the ${{ env.SERVICE_NAME }} - run: unzip -uj "release.zip" "${{ env.SERVICE_LOCATION }}/target/*" -d "./${{ env.SERVICE_LOCATION }}/target" - - - name: Build image - run: | - cd "./${{env.SERVICE_LOCATION}}" - docker build . --file Dockerfile --tag ${{ env.SERVICE_NAME }} - - name: Log into registry - run: echo "${{ secrets.release_docker_hub }}" | docker login -u ${{ secrets.actor_docker_hub }} --password-stdin - - - name: Push image - run: | - IMAGE_ID=$NAMESPACE/$SERVICE_NAME - - # Change all uppercase to lowercase - IMAGE_ID=$(echo $IMAGE_ID | tr '[A-Z]' '[a-z]') - echo "push version ${{steps.getPomVersion.outputs.info}}" - VERSION=$BRANCH_NAME - echo IMAGE_ID=$IMAGE_ID - echo VERSION=$VERSION - docker tag $SERVICE_NAME $IMAGE_ID:$VERSION - docker push $IMAGE_ID:$VERSION - - docker-registration-processor-dmz-packet-server: - needs: build - - runs-on: ubuntu-latest - env: - NAMESPACE: mosipdev - SERVICE_NAME: registration-processor-dmz-packet-server - SERVICE_LOCATION: registration-processor/init/registration-processor-dmz-packet-server - - steps: - - uses: actions/checkout@v2 - - - name: Setup branch name - run: | - # Strip git ref prefix from version - echo "::set-env name=BRANCH_NAME::$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')" - echo ${{ env.BRANCH_NAME }} - - - name: Get version info - id: getVersion - uses: mavrosxristoforos/get-xml-info@1.0 - with: - xml-file: ./${{ env.SERVICE_LOCATION }}/version.xml - xpath: version - - - name: Build image - run: | - cd "./${{env.SERVICE_LOCATION}}" - docker build . --file Dockerfile --tag ${{ env.SERVICE_NAME }} - - name: Log into registry - run: echo "${{ secrets.release_docker_hub }}" | docker login -u ${{ secrets.actor_docker_hub }} --password-stdin - - - name: Push image - run: | - IMAGE_ID=$NAMESPACE/$SERVICE_NAME - - # Change all uppercase to lowercase - IMAGE_ID=$(echo $IMAGE_ID | tr '[A-Z]' '[a-z]') - echo "push version ${{steps.getVersion.outputs.info}}" - VERSION=${{steps.getVersion.outputs.info}} - echo IMAGE_ID=$IMAGE_ID - echo VERSION=$VERSION - docker tag $SERVICE_NAME $IMAGE_ID:$VERSION - docker push $IMAGE_ID:$VERSION - - docker-registration-processor-registration-status-service: - needs: build - - runs-on: ubuntu-latest - env: - NAMESPACE: mosipdev - SERVICE_NAME: registration-processor-registration-status-service - SERVICE_LOCATION: registration-processor/init/registration-processor-registration-status-service - - steps: - - uses: actions/checkout@v2 - - uses: actions/download-artifact@v1 - with: - name: release - path: ./ - - - name: Setup branch name - run: | - # Strip git ref prefix from version - echo "::set-env name=BRANCH_NAME::$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')" - echo ${{ env.BRANCH_NAME }} - - - name: Get version info from pom - id: getPomVersion - uses: mavrosxristoforos/get-xml-info@1.0 - with: - xml-file: ./${{ env.SERVICE_LOCATION }}/pom.xml - xpath: /*[local-name()="project"]/*[local-name()="version"] - - - name: Unzip and extract the ${{ env.SERVICE_NAME }} - run: unzip -uj "release.zip" "${{ env.SERVICE_LOCATION }}/target/*" -d "./${{ env.SERVICE_LOCATION }}/target" - - - name: Build image - run: | - cd "./${{env.SERVICE_LOCATION}}" - docker build . --file Dockerfile --tag ${{ env.SERVICE_NAME }} - - name: Log into registry - run: echo "${{ secrets.release_docker_hub }}" | docker login -u ${{ secrets.actor_docker_hub }} --password-stdin - - - name: Push image - run: | - IMAGE_ID=$NAMESPACE/$SERVICE_NAME - - # Change all uppercase to lowercase - IMAGE_ID=$(echo $IMAGE_ID | tr '[A-Z]' '[a-z]') - echo "push version ${{steps.getPomVersion.outputs.info}}" - VERSION=$BRANCH_NAME - echo IMAGE_ID=$IMAGE_ID - echo VERSION=$VERSION - docker tag $SERVICE_NAME $IMAGE_ID:$VERSION - docker push $IMAGE_ID:$VERSION - - docker-registration-processor-notification-service: - needs: build - - runs-on: ubuntu-latest - env: - NAMESPACE: mosipdev - SERVICE_NAME: registration-processor-notification-service - SERVICE_LOCATION: registration-processor/registration-processor-notification-service - - steps: - - uses: actions/checkout@v2 - - uses: actions/download-artifact@v1 - with: - name: release - path: ./ - - - name: Setup branch name - run: | - # Strip git ref prefix from version - echo "::set-env name=BRANCH_NAME::$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')" - echo ${{ env.BRANCH_NAME }} - - - name: Get version info from pom - id: getPomVersion - uses: mavrosxristoforos/get-xml-info@1.0 - with: - xml-file: ./${{ env.SERVICE_LOCATION }}/pom.xml - xpath: /*[local-name()="project"]/*[local-name()="version"] - - - name: Unzip and extract the ${{ env.SERVICE_NAME }} - run: unzip -uj "release.zip" "${{ env.SERVICE_LOCATION }}/target/*" -d "./${{ env.SERVICE_LOCATION }}/target" - - - name: Build image - run: | - cd "./${{env.SERVICE_LOCATION}}" - docker build . --file Dockerfile --tag ${{ env.SERVICE_NAME }} - - name: Log into registry - run: echo "${{ secrets.release_docker_hub }}" | docker login -u ${{ secrets.actor_docker_hub }} --password-stdin - - - name: Push image - run: | - IMAGE_ID=$NAMESPACE/$SERVICE_NAME - - # Change all uppercase to lowercase - IMAGE_ID=$(echo $IMAGE_ID | tr '[A-Z]' '[a-z]') - echo "push version ${{steps.getPomVersion.outputs.info}}" - VERSION=$BRANCH_NAME - echo IMAGE_ID=$IMAGE_ID - echo VERSION=$VERSION - docker tag $SERVICE_NAME $IMAGE_ID:$VERSION - docker push $IMAGE_ID:$VERSION - - docker-registration-processor-landing-zone: - needs: build - - runs-on: ubuntu-latest - env: - NAMESPACE: mosipdev - SERVICE_NAME: registration-processor-landing-zone - SERVICE_LOCATION: registration-processor/registration-processor-landing-zone - - steps: - - uses: actions/checkout@v2 - - uses: actions/download-artifact@v1 - with: - name: release - path: ./ - - - name: Setup branch name - run: | - # Strip git ref prefix from version - echo "::set-env name=BRANCH_NAME::$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')" - echo ${{ env.BRANCH_NAME }} - - - name: Get version info from pom - id: getPomVersion - uses: mavrosxristoforos/get-xml-info@1.0 - with: - xml-file: ./${{ env.SERVICE_LOCATION }}/pom.xml - xpath: /*[local-name()="project"]/*[local-name()="version"] - - - name: Unzip and extract the ${{ env.SERVICE_NAME }} - run: unzip -uj "release.zip" "${{ env.SERVICE_LOCATION }}/target/*" -d "./${{ env.SERVICE_LOCATION }}/target" - - - name: Build image - run: | - cd "./${{env.SERVICE_LOCATION}}" - docker build . --file Dockerfile --tag ${{ env.SERVICE_NAME }} - - name: Log into registry - run: echo "${{ secrets.release_docker_hub }}" | docker login -u ${{ secrets.actor_docker_hub }} --password-stdin - - - name: Push image - run: | - IMAGE_ID=$NAMESPACE/$SERVICE_NAME - - # Change all uppercase to lowercase - IMAGE_ID=$(echo $IMAGE_ID | tr '[A-Z]' '[a-z]') - echo "push version ${{steps.getPomVersion.outputs.info}}" - VERSION=$BRANCH_NAME - echo IMAGE_ID=$IMAGE_ID - echo VERSION=$VERSION - docker tag $SERVICE_NAME $IMAGE_ID:$VERSION - docker push $IMAGE_ID:$VERSION - - docker-registration-processor-workflow-manager-service: - needs: build - - runs-on: ubuntu-latest - env: - NAMESPACE: mosipdev - SERVICE_NAME: registration-processor-workflow-manager-service - SERVICE_LOCATION: registration-processor/workflow-engine/registration-processor-workflow-manager-service - - steps: - - uses: actions/checkout@v2 - - uses: actions/download-artifact@v1 - with: - name: release - path: ./ - - - name: Setup branch name - run: | - # Strip git ref prefix from version - echo "::set-env name=BRANCH_NAME::$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')" - echo ${{ env.BRANCH_NAME }} - - - name: Get version info from pom - id: getPomVersion - uses: mavrosxristoforos/get-xml-info@1.0 - with: - xml-file: ./${{ env.SERVICE_LOCATION }}/pom.xml - xpath: /*[local-name()="project"]/*[local-name()="version"] - - - name: Unzip and extract the ${{ env.SERVICE_NAME }} - run: unzip -uj "release.zip" "${{ env.SERVICE_LOCATION }}/target/*" -d "./${{ env.SERVICE_LOCATION }}/target" - - - name: Build image - run: | - cd "./${{env.SERVICE_LOCATION}}" - docker build . --file Dockerfile --tag ${{ env.SERVICE_NAME }} - - name: Log into registry - run: echo "${{ secrets.release_docker_hub }}" | docker login -u ${{ secrets.actor_docker_hub }} --password-stdin - - - name: Push image - run: | - IMAGE_ID=$NAMESPACE/$SERVICE_NAME - - # Change all uppercase to lowercase - IMAGE_ID=$(echo $IMAGE_ID | tr '[A-Z]' '[a-z]') - echo "push version ${{steps.getPomVersion.outputs.info}}" - VERSION=$BRANCH_NAME - echo IMAGE_ID=$IMAGE_ID - echo VERSION=$VERSION - docker tag $SERVICE_NAME $IMAGE_ID:$VERSION - docker push $IMAGE_ID:$VERSION \ No newline at end of file diff --git a/.github/workflows/tag.yml b/.github/workflows/tag.yml new file mode 100644 index 00000000000..9a5b079ffdf --- /dev/null +++ b/.github/workflows/tag.yml @@ -0,0 +1,35 @@ +name: Tagging of repos + +on: + workflow_dispatch: + inputs: + TAG: + description: 'Tag to be published' + required: true + type: string + BODY: + description: 'Release body message' + required: true + default: 'Changes in this Release' + type: string + PRE_RELEASE: + description: 'Pre-release? True/False' + required: true + default: False + type: string + DRAFT: + description: 'Draft? True/False' + required: false + default: False + type: string + +jobs: + tag-branch: + uses: mosip/kattu/.github/workflows/tag.yml@master + with: + TAG: ${{ inputs.TAG }} + BODY: ${{ inputs.BODY }} + PRE_RELEASE: ${{ inputs.PRE_RELEASE }} + DRAFT: ${{ inputs.DRAFT }} + secrets: + SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK }} \ No newline at end of file diff --git a/pom.xml b/pom.xml index 5e308d4df3f..4f5637a884d 100644 --- a/pom.xml +++ b/pom.xml @@ -1,162 +1,162 @@ - - 4.0.0 - io.mosip - registration - 1.2.1-SNAPSHOT - pom - - MOSIP Registration Parent POM - Mosip Registration Project - https://github.com/mosip/registration - - - MPL 2.0 - https://www.mozilla.org/en-US/MPL/2.0/ - - - - scm:git:git://github.com/mosip/registration.git - scm:git:ssh://github.com:mosip/registration.git - https://github.com/mosip/registration - HEAD - - - - Mosip - mosip.emailnotifier@gmail.com - io.mosip - https://github.com/mosip/registration - - - - - ossrh - Central Repository - https://oss.sonatype.org/content/repositories/snapshots - default - - true - - - - central - Maven Central - default - https://repo1.maven.org/maven2 - - false - - - + 4.0.0 + io.mosip + registration + 1.2.1-SNAPSHOT + pom + MOSIP Registration Parent POM + Mosip Registration Project + https://github.com/mosip/registration + + + MPL 2.0 + https://www.mozilla.org/en-US/MPL/2.0/ + + + + scm:git:git://github.com/mosip/registration.git + scm:git:ssh://github.com:mosip/registration.git + https://github.com/mosip/registration + HEAD + + + + Mosip + mosip.emailnotifier@gmail.com + io.mosip + https://github.com/mosip/registration + + - - - ossrh - https://oss.sonatype.org/content/repositories/snapshots - - - ossrh - https://oss.sonatype.org/service/local/staging/deploy/maven2/ - - - - - - org.sonatype.plugins - nexus-staging-maven-plugin - 1.6.7 - true - - ossrh - https://oss.sonatype.org/ - false - - + + + ossrh + Central Repository + https://oss.sonatype.org/content/repositories/snapshots + default + + true + + + + central + Maven Central + default + https://repo1.maven.org/maven2 + + false + + + - - org.apache.maven.plugins - maven-source-plugin - 2.2.1 - - - attach-sources - - jar-no-fork - - - - - - org.apache.maven.plugins - maven-javadoc-plugin - 3.2.0 - - - attach-javadocs - - jar - - - - - none - - - - - org.apache.maven.plugins - maven-gpg-plugin - 1.5 - - - sign-artifacts - verify - - sign - - - - --pinentry-mode - loopback - - - - - - - pl.project13.maven - git-commit-id-plugin - 3.0.1 - - - get-the-git-infos - - revision - - validate - - - - true - ${project.build.outputDirectory}/git.properties - - ^git.build.(time|version)$ - ^git.commit.id.(abbrev|full)$ - - full - ${project.basedir}/.git - - - - - + + + ossrh + https://oss.sonatype.org/content/repositories/snapshots + + + ossrh + https://oss.sonatype.org/service/local/staging/deploy/maven2/ + + + + + + org.sonatype.plugins + nexus-staging-maven-plugin + 1.6.7 + true + + ossrh + https://oss.sonatype.org/ + false + + - - registration-processor - - + + org.apache.maven.plugins + maven-source-plugin + 2.2.1 + + + attach-sources + + jar-no-fork + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + 3.2.0 + + + attach-javadocs + + jar + + + + + none + + + + + org.apache.maven.plugins + maven-gpg-plugin + 1.5 + + + sign-artifacts + verify + + sign + + + + --pinentry-mode + loopback + + + + + + + pl.project13.maven + git-commit-id-plugin + 3.0.1 + + + get-the-git-infos + + revision + + validate + + + + true + ${project.build.outputDirectory}/git.properties + + ^git.build.(time|version)$ + ^git.commit.id.(abbrev|full)$ + + full + ${project.basedir}/.git + + + + + + + + + registration-processor + + \ No newline at end of file diff --git a/registration-processor/core-processor/registration-processor-biometric-extraction-stage/pom.xml b/registration-processor/core-processor/registration-processor-biometric-extraction-stage/pom.xml index ec855c0a36e..8315f465b9a 100644 --- a/registration-processor/core-processor/registration-processor-biometric-extraction-stage/pom.xml +++ b/registration-processor/core-processor/registration-processor-biometric-extraction-stage/pom.xml @@ -8,6 +8,7 @@ 1.2.1-SNAPSHOT registration-processor-biometric-extraction-stage + 1.2.1-SNAPSHOT jar UTF-8 diff --git a/registration-processor/core-processor/registration-processor-finalization-stage/pom.xml b/registration-processor/core-processor/registration-processor-finalization-stage/pom.xml index efec0b9437b..7c17b49d64c 100644 --- a/registration-processor/core-processor/registration-processor-finalization-stage/pom.xml +++ b/registration-processor/core-processor/registration-processor-finalization-stage/pom.xml @@ -9,6 +9,7 @@ registration-processor-finalization-stage registration-processor-finalization-stage + 1.2.1-SNAPSHOT jar UTF-8 diff --git a/registration-processor/init/pom.xml b/registration-processor/init/pom.xml index 1d6f8d0bab9..ab854dde10c 100644 --- a/registration-processor/init/pom.xml +++ b/registration-processor/init/pom.xml @@ -9,6 +9,7 @@ 1.2.1-SNAPSHOT init + 1.2.1-SNAPSHOT UTF-8 diff --git a/registration-processor/pom.xml b/registration-processor/pom.xml index a3be3369d60..d173fd0641b 100644 --- a/registration-processor/pom.xml +++ b/registration-processor/pom.xml @@ -8,6 +8,27 @@ 1.2.1-SNAPSHOT + + + MPL 2.0 + https://www.mozilla.org/en-US/MPL/2.0/ + + + + scm:git:git://github.com/mosip/registration.git + scm:git:ssh://github.com:mosip/registration.git + https://github.com/mosip/registration + HEAD + + + + Mosip + mosip.emailnotifier@gmail.com + io.mosip + https://github.com/mosip/registration + + + io.mosip.registrationprocessor registration-processor 1.2.1-SNAPSHOT @@ -101,10 +122,10 @@ 1.1.1 - + 2.8.1 - + 0.1.55 @@ -132,9 +153,9 @@ 1.2.1-SNAPSHOT 1.2.1-SNAPSHOT 1.2.1-SNAPSHOT - 1.2.1-SNAPSHOT - 1.2.1-SNAPSHOT - **/dto/**, + 1.2.1-SNAPSHOT + 1.2.1-SNAPSHOT + **/dto/**, **/exception/*Exception.java, **/config/*Config.java, **/handler/*ExceptionHandler.java, @@ -208,7 +229,7 @@ **/registration/processor/abis/handler/*.java, **/registration/processor/abis/handler/config/*.java, - **/registration/processor/packet/service/**/*.java, + **/registration/processor/packet/service/**/*.java, **/registration/processor/packet/upload/**/*.java, **/registration/processor/status/code/*.java, @@ -266,29 +287,29 @@ **/dto/**,**/entity/**,**/config/**,**/handler/**,**/utilities/**, **/validator/**, **/utils/**,**/util/**,**/code/** - none + none - - - ossrh - CentralRepository - https://oss.sonatype.org/content/repositories/snapshots - default - - true - - - - central - MavenCentral - default - https://repo1.maven.org/maven2 - - false - - - + + + ossrh + CentralRepository + https://oss.sonatype.org/content/repositories/snapshots + default + + true + + + + central + MavenCentral + default + https://repo1.maven.org/maven2 + + false + + + @@ -300,9 +321,9 @@ - net.bytebuddy - byte-buddy - 1.10.13 + net.bytebuddy + byte-buddy + 1.10.13 org.springframework.boot @@ -312,42 +333,42 @@ import - org.projectlombok - lombok - 1.18.8 - provided + org.projectlombok + lombok + 1.18.8 + provided + + + org.powermock + powermock-core + 2.0.7 + test - org.powermock - powermock-core - 2.0.7 - test - + javax.xml.bind + jaxb-api + 2.3.1 + - javax.xml.bind - jaxb-api - 2.3.1 - - - org.javassist - javassist - 3.27.0-GA - - - com.fasterxml.jackson.core - jackson-databind - ${jackson.version} - - - com.fasterxml.jackson.core - jackson-core - ${jackson.version} - - - com.fasterxml.jackson.core - jackson-annotations - ${jackson.version} - + org.javassist + javassist + 3.27.0-GA + + + com.fasterxml.jackson.core + jackson-databind + ${jackson.version} + + + com.fasterxml.jackson.core + jackson-core + ${jackson.version} + + + com.fasterxml.jackson.core + jackson-annotations + ${jackson.version} + @@ -367,97 +388,97 @@ post-processor mosip-stage-executor stage-groups - workflow-engine - registration-processor-landing-zone - + workflow-engine + registration-processor-landing-zone + - - - org.apache.maven.plugins - maven-surefire-plugin - ${maven.surefire.plugin.version} - - ${skipTests} - false - - ${argLine} --add-opens java.xml/jdk.xml.internal=ALL-UNNAMED --illegal-access=permit - - - - - org.jacoco - jacoco-maven-plugin - ${maven.jacoco.version} - - - - prepare-agent - - - - report - prepare-package - - report - - - - - - org.apache.maven.plugins - maven-compiler-plugin - ${maven.compiler.version} - - ${maven.compiler.source} - ${maven.compiler.target} - - - - org.apache.maven.plugins - maven-jar-plugin - ${maven.jar.plugin.version} - - - - true - true - - - ${project.name} - ${project.version} - ${user.name} - ${os.name} - ${maven.build.timestamp} - ${env.BUILD_NUMBER} - ${env.BUILD_ID} - ${env.BUILD_URL} - - - - - - org.apache.maven.plugins - maven-war-plugin - ${maven.war.plugin.version} - - - - true - true - - - ${project.name} - ${project.version} - ${user.name} - ${os.name} - ${maven.build.timestamp} - ${env.BUILD_NUMBER} - ${env.BUILD_ID} - ${env.BUILD_URL} - - - - + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven.surefire.plugin.version} + + ${skipTests} + false + + ${argLine} --add-opens java.xml/jdk.xml.internal=ALL-UNNAMED --illegal-access=permit + + + + + org.jacoco + jacoco-maven-plugin + ${maven.jacoco.version} + + + + prepare-agent + + + + report + prepare-package + + report + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven.compiler.version} + + ${maven.compiler.source} + ${maven.compiler.target} + + + + org.apache.maven.plugins + maven-jar-plugin + ${maven.jar.plugin.version} + + + + true + true + + + ${project.name} + ${project.version} + ${user.name} + ${os.name} + ${maven.build.timestamp} + ${env.BUILD_NUMBER} + ${env.BUILD_ID} + ${env.BUILD_URL} + + + + + + org.apache.maven.plugins + maven-war-plugin + ${maven.war.plugin.version} + + + + true + true + + + ${project.name} + ${project.version} + ${user.name} + ${os.name} + ${maven.build.timestamp} + ${env.BUILD_NUMBER} + ${env.BUILD_ID} + ${env.BUILD_URL} + + + + org.apache.maven.plugins maven-javadoc-plugin @@ -467,6 +488,51 @@ none + + pl.project13.maven + git-commit-id-plugin + 3.0.1 + + + get-the-git-infos + + revision + + validate + + + + true + ${project.build.outputDirectory}/git.properties + + ^git.build.(time|version)$ + ^git.commit.id.(abbrev|full)$ + + full + ${project.basedir}/.git + + + + + org.apache.maven.plugins + maven-gpg-plugin + 1.5 + + + sign-artifacts + verify + + sign + + + + --pinentry-mode + loopback + + + + + @@ -476,7 +542,7 @@ . src/main/java/**,src/main/resources/** **/registration/processor/core/queue/factory/*.java, - ${sonar.coverage.exclusions} + ${sonar.coverage.exclusions} https://sonarcloud.io diff --git a/registration-processor/qc-users-manger/pom.xml b/registration-processor/qc-users-manger/pom.xml index b78cbbf8a14..189d76e6bac 100644 --- a/registration-processor/qc-users-manger/pom.xml +++ b/registration-processor/qc-users-manger/pom.xml @@ -5,6 +5,7 @@ qc-users-manger + 1.2.1-SNAPSHOT io.mosip.registrationprocessor registration-processor From cc8aadb339e6336c25ae33d23e1436ccd7e48302 Mon Sep 17 00:00:00 2001 From: Sowmya Ujjappa Banakar <43202851+sowmya695@users.noreply.github.com> Date: Sat, 21 Oct 2023 14:45:52 +0530 Subject: [PATCH 10/38] MOSIP-28185 Code fix for notification (#1782) Co-authored-by: Sowmya Ujjappa Banakar --- .../impl/MessageNotificationServiceImpl.java | 40 ++++++++++++------- 1 file changed, 26 insertions(+), 14 deletions(-) diff --git a/registration-processor/registration-processor-message-sender-impl/src/main/java/io/mosip/registration/processor/message/sender/service/impl/MessageNotificationServiceImpl.java b/registration-processor/registration-processor-message-sender-impl/src/main/java/io/mosip/registration/processor/message/sender/service/impl/MessageNotificationServiceImpl.java index 4473c45c5a3..bd728d00455 100644 --- a/registration-processor/registration-processor-message-sender-impl/src/main/java/io/mosip/registration/processor/message/sender/service/impl/MessageNotificationServiceImpl.java +++ b/registration-processor/registration-processor-message-sender-impl/src/main/java/io/mosip/registration/processor/message/sender/service/impl/MessageNotificationServiceImpl.java @@ -7,6 +7,7 @@ import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; +import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; @@ -15,11 +16,6 @@ import java.util.Map.Entry; import java.util.Set; -import io.mosip.kernel.core.exception.BaseUncheckedException; -import io.mosip.kernel.core.exception.ServiceError; -import io.mosip.registration.processor.core.constant.*; -import io.mosip.registration.processor.core.idrepo.dto.VidInfoDTO; -import io.mosip.registration.processor.core.idrepo.dto.VidsInfosDTO; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.exception.ExceptionUtils; @@ -38,6 +34,8 @@ import com.fasterxml.jackson.databind.ObjectMapper; +import io.mosip.kernel.core.exception.BaseUncheckedException; +import io.mosip.kernel.core.exception.ServiceError; import io.mosip.kernel.core.logger.spi.Logger; import io.mosip.kernel.core.util.DateUtils; import io.mosip.kernel.core.util.JsonUtils; @@ -45,6 +43,11 @@ import io.mosip.kernel.core.util.exception.JsonParseException; import io.mosip.kernel.core.util.exception.JsonProcessingException; import io.mosip.registration.processor.core.code.ApiName; +import io.mosip.registration.processor.core.constant.IdType; +import io.mosip.registration.processor.core.constant.LoggerFileConstant; +import io.mosip.registration.processor.core.constant.MappingJsonConstants; +import io.mosip.registration.processor.core.constant.ProviderStageName; +import io.mosip.registration.processor.core.constant.VidType; import io.mosip.registration.processor.core.exception.ApisResourceAccessException; import io.mosip.registration.processor.core.exception.PacketDecryptionFailureException; import io.mosip.registration.processor.core.exception.PacketManagerException; @@ -54,6 +57,8 @@ import io.mosip.registration.processor.core.http.RequestWrapper; import io.mosip.registration.processor.core.http.ResponseWrapper; import io.mosip.registration.processor.core.idrepo.dto.IdResponseDTO; +import io.mosip.registration.processor.core.idrepo.dto.VidInfoDTO; +import io.mosip.registration.processor.core.idrepo.dto.VidsInfosDTO; import io.mosip.registration.processor.core.logger.RegProcessorLogger; import io.mosip.registration.processor.core.notification.template.generator.dto.ResponseDto; import io.mosip.registration.processor.core.notification.template.generator.dto.SmsRequestDto; @@ -70,7 +75,6 @@ import io.mosip.registration.processor.message.sender.exception.TemplateNotFoundException; import io.mosip.registration.processor.message.sender.template.TemplateGenerator; import io.mosip.registration.processor.packet.manager.decryptor.Decryptor; -import io.mosip.registration.processor.packet.storage.dto.ConfigEnum; import io.mosip.registration.processor.packet.storage.exception.IdRepoAppException; import io.mosip.registration.processor.packet.storage.utils.PriorityBasedPacketManagerService; import io.mosip.registration.processor.packet.storage.utils.Utilities; @@ -556,7 +560,7 @@ private Map setAttributes(String idJsonString, Map setAttributesFromIdJson(String id, String process, M String regType, String lang, StringBuilder phoneNumber, StringBuilder emailId) throws IOException, ApisResourceAccessException, PacketManagerException, JsonProcessingException, JSONException, PacketDecryptionFailureException, JsonParseException, JsonMappingException, io.mosip.kernel.core.exception.IOException { - JSONObject mapperIdentity = utility.getRegistrationProcessorMappingJson(MappingJsonConstants.IDENTITY); - + if (mapperJsonKeys == null) { + String mapperJsonString = Utilities.getJson(utility.getConfigServerFileStorageURL(), + utility.getGetRegProcessorIdentityJson()); + JSONObject mapperJson = JsonUtil.objectMapperReadValue(mapperJsonString, JSONObject.class); + mapperIdentity = JsonUtil.getJSONObject(mapperJson, utility.getGetRegProcessorDemographicIdentity()); + mapperJsonKeys = new ArrayList<>(mapperIdentity.keySet()); + } List mapperJsonValues = new ArrayList<>(); - JsonUtil.getJSONValue(JsonUtil.getJSONObject(mapperIdentity, MappingJsonConstants.INDIVIDUAL_BIOMETRICS), VALUE); - mapperIdentity.keySet().forEach(key -> mapperJsonValues.add(JsonUtil.getJSONValue(JsonUtil.getJSONObject(mapperIdentity, key), VALUE))); - - String source = utility.getDefaultSource(process, ConfigEnum.READER); + for (String key : mapperJsonKeys) { + JSONObject jsonValue = JsonUtil.getJSONObject(mapperIdentity, key); + if (jsonValue.get(VALUE) != null && !jsonValue.get(VALUE).toString().isBlank()) { + String[] valueArray = jsonValue.get(VALUE).toString().split(","); + mapperJsonValues.addAll(new ArrayList(Arrays.asList(valueArray))); + } + } Map fieldMap =null; try { fieldMap = packetManagerService.getFields(id, mapperJsonValues, process, ProviderStageName.MESSAGE_SENDER); @@ -636,7 +648,7 @@ else if (json instanceof org.json.JSONArray) { Object obj = jsonArray.get(i); JsonValue jsonValue = mapper.readValue(obj.toString(), JsonValue.class); if(jsonValue.getLanguage().equalsIgnoreCase(lang)) { - attribute.putIfAbsent(e.getKey().toString(), jsonValue.getValue()); + attribute.putIfAbsent(e.getKey().toString() + "_" + lang, jsonValue.getValue()); } } } else From 85d34925889c9f60b560ee3912248388511919cf Mon Sep 17 00:00:00 2001 From: Sowmya Ujjappa Banakar <43202851+sowmya695@users.noreply.github.com> Date: Tue, 31 Oct 2023 13:54:22 +0530 Subject: [PATCH 11/38] MOSIP-29118 Code fix (#1763) Co-authored-by: Sowmya Ujjappa Banakar --- .../stage/BiometricAuthenticationStage.java | 781 +++++++++--------- .../BiometricAuthenticationStageTest.java | 8 + 2 files changed, 396 insertions(+), 393 deletions(-) diff --git a/registration-processor/core-processor/registration-processor-biometric-authentication-stage/src/main/java/io/mosip/registration/processor/biometric/authentication/stage/BiometricAuthenticationStage.java b/registration-processor/core-processor/registration-processor-biometric-authentication-stage/src/main/java/io/mosip/registration/processor/biometric/authentication/stage/BiometricAuthenticationStage.java index 7483f58a274..836c0b35b81 100644 --- a/registration-processor/core-processor/registration-processor-biometric-authentication-stage/src/main/java/io/mosip/registration/processor/biometric/authentication/stage/BiometricAuthenticationStage.java +++ b/registration-processor/core-processor/registration-processor-biometric-authentication-stage/src/main/java/io/mosip/registration/processor/biometric/authentication/stage/BiometricAuthenticationStage.java @@ -1,394 +1,389 @@ -package io.mosip.registration.processor.biometric.authentication.stage; - -import java.io.IOException; -import java.security.NoSuchAlgorithmException; -import java.security.cert.CertificateException; -import java.util.List; -import java.util.stream.Collectors; - -import org.apache.commons.lang.StringUtils; -import org.apache.commons.lang3.exception.ExceptionUtils; -import org.json.simple.JSONObject; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.cloud.context.config.annotation.RefreshScope; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.stereotype.Service; -import org.springframework.util.CollectionUtils; - -import io.mosip.kernel.biometrics.entities.BIR; -import io.mosip.kernel.biometrics.entities.BiometricRecord; -import io.mosip.kernel.core.logger.spi.Logger; -import io.mosip.kernel.core.util.exception.JsonProcessingException; -import io.mosip.registration.processor.biometric.authentication.constants.BiometricAuthenticationConstants; -import io.mosip.registration.processor.core.abstractverticle.MessageBusAddress; -import io.mosip.registration.processor.core.abstractverticle.MessageDTO; -import io.mosip.registration.processor.core.abstractverticle.MosipEventBus; -import io.mosip.registration.processor.core.abstractverticle.MosipRouter; -import io.mosip.registration.processor.core.abstractverticle.MosipVerticleAPIManager; -import io.mosip.registration.processor.core.auth.dto.AuthResponseDTO; -import io.mosip.registration.processor.core.code.EventId; -import io.mosip.registration.processor.core.code.EventName; -import io.mosip.registration.processor.core.code.EventType; -import io.mosip.registration.processor.core.code.ModuleName; -import io.mosip.registration.processor.core.code.RegistrationExceptionTypeCode; -import io.mosip.registration.processor.core.code.RegistrationTransactionStatusCode; -import io.mosip.registration.processor.core.code.RegistrationTransactionTypeCode; -import io.mosip.registration.processor.core.constant.LoggerFileConstant; -import io.mosip.registration.processor.core.constant.MappingJsonConstants; -import io.mosip.registration.processor.core.constant.ProviderStageName; -import io.mosip.registration.processor.core.constant.RegistrationType; -import io.mosip.registration.processor.core.exception.ApisResourceAccessException; -import io.mosip.registration.processor.core.exception.AuthSystemException; -import io.mosip.registration.processor.core.exception.BioTypeException; -import io.mosip.registration.processor.core.exception.PacketManagerException; -import io.mosip.registration.processor.core.exception.ValidationFailedException; -import io.mosip.registration.processor.core.exception.util.PlatformErrorMessages; -import io.mosip.registration.processor.core.exception.util.PlatformSuccessMessages; -import io.mosip.registration.processor.core.logger.RegProcessorLogger; -import io.mosip.registration.processor.core.status.util.StatusUtil; -import io.mosip.registration.processor.core.status.util.TrimExceptionMessage; -import io.mosip.registration.processor.core.util.JsonUtil; -import io.mosip.registration.processor.core.util.RegistrationExceptionMapperUtil; -import io.mosip.registration.processor.packet.storage.utils.BioSdkUtil; -import io.mosip.registration.processor.packet.storage.utils.PriorityBasedPacketManagerService; -import io.mosip.registration.processor.packet.storage.utils.Utilities; -import io.mosip.registration.processor.rest.client.audit.builder.AuditLogRequestBuilder; -import io.mosip.registration.processor.status.code.RegistrationStatusCode; -import io.mosip.registration.processor.status.dto.InternalRegistrationStatusDto; -import io.mosip.registration.processor.status.dto.RegistrationStatusDto; -import io.mosip.registration.processor.status.dto.SyncRegistrationDto; -import io.mosip.registration.processor.status.dto.SyncResponseDto; -import io.mosip.registration.processor.status.dto.SyncTypeDto; -import io.mosip.registration.processor.status.entity.SyncRegistrationEntity; -import io.mosip.registration.processor.status.service.RegistrationStatusService; -import io.mosip.registration.processor.status.service.SyncRegistrationService; - -@RefreshScope -@Service -@Configuration -@ComponentScan(basePackages = { "${mosip.auth.adapter.impl.basepackage}", - "io.mosip.registration.processor.biometric.authentication.config", - "io.mosip.registration.processor.status.config", "io.mosip.registration.processor.rest.client.config", - "io.mosip.registration.processor.packet.storage.config", "io.mosip.registration.processor.core.config", - "io.mosip.registration.processor.core.kernel.beans", "io.mosip.kernel.packetmanager.config", - "io.mosip.kernel.biosdk.provider.impl" }) -public class BiometricAuthenticationStage extends MosipVerticleAPIManager { - private static Logger regProcLogger = RegProcessorLogger.getLogger(BiometricAuthenticationStage.class); - private static final String STAGE_PROPERTY_PREFIX = "mosip.regproc.biometric.authentication."; - private static final String ADULT_BIOMETRIC_UPDATE = "as adult has come for biometric update"; - @Autowired - AuditLogRequestBuilder auditLogRequestBuilder; - - @Autowired - private Utilities utility; - - /** The registration status service. */ - @Autowired - RegistrationStatusService registrationStatusService; - - @Autowired - private BioSdkUtil bioUtil; - - @Autowired - private PriorityBasedPacketManagerService packetManagerService; - - @Autowired - RegistrationExceptionMapperUtil registrationStatusMapperUtil; - - @Value("${vertx.cluster.configuration}") - private String clusterManagerUrl; - - @Value("${mosip.kernel.applicant.type.age.limit}") - private String ageLimit; - - /** worker pool size. */ - @Value("${worker.pool.size}") - private Integer workerPoolSize; - - /** - * After this time intervel, message should be considered as expired (In - * seconds). - */ - @Value("${mosip.regproc.biometric.authentication.message.expiry-time-limit}") - private Long messageExpiryTimeLimit; - - /** The mosip event bus. */ - MosipEventBus mosipEventBus = null; - - /** Mosip router for APIs */ - @Autowired - MosipRouter router; - - @Autowired - private SyncRegistrationService syncRegistrationservice; - - public void deployVerticle() { - mosipEventBus = this.getEventBus(this, clusterManagerUrl, workerPoolSize); - this.consumeAndSend(mosipEventBus, MessageBusAddress.BIOMETRIC_AUTHENTICATION_BUS_IN, - MessageBusAddress.BIOMETRIC_AUTHENTICATION_BUS_OUT, messageExpiryTimeLimit); - } - - @Override - public void start() { - router.setRoute(this.postUrl(getVertx(), MessageBusAddress.BIOMETRIC_AUTHENTICATION_BUS_IN, - MessageBusAddress.BIOMETRIC_AUTHENTICATION_BUS_OUT)); - this.createServer(router.getRouter(), getPort()); - } - - @Override - protected String getPropertyPrefix() { - return STAGE_PROPERTY_PREFIX; - } - - @Override - public MessageDTO process(MessageDTO object) { - TrimExceptionMessage trimExceptionMessage = new TrimExceptionMessage(); - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), "", - "BiometricAuthenticationStage::BiometricAuthenticationStage::entry"); - String registrationId = object.getRid(); - object.setMessageBusAddress(MessageBusAddress.BIOMETRIC_AUTHENTICATION_BUS_IN); - object.setIsValid(Boolean.FALSE); - object.setInternalError(Boolean.FALSE); - InternalRegistrationStatusDto registrationStatusDto = registrationStatusService.getRegistrationStatus( - registrationId, object.getReg_type(), object.getIteration(), object.getWorkflowInstanceId()); - - registrationStatusDto - .setLatestTransactionTypeCode(RegistrationTransactionTypeCode.BIOMETRIC_AUTHENTICATION.toString()); - registrationStatusDto.setRegistrationStageName(getStageName()); - SyncRegistrationEntity regEntity = syncRegistrationservice - .findByWorkflowInstanceId(object.getWorkflowInstanceId()); - String description = ""; - String code = ""; - boolean isBioAuthSkipped = false; - boolean isTransactionSuccessful = false; - - try { - String process = registrationStatusDto.getRegistrationType(); - String registartionType = regEntity.getRegistrationType(); - int applicantAge = utility.getApplicantAge(registrationId, process, ProviderStageName.BIO_AUTH); - int childAgeLimit = Integer.parseInt(ageLimit); - String applicantType = BiometricAuthenticationConstants.ADULT; - if (applicantAge <= childAgeLimit && applicantAge > 0) { - applicantType = BiometricAuthenticationConstants.CHILD; - } - if (isUpdateAdultPacket(registartionType, applicantType)) { - - String biometricsLabel = packetManagerService.getFieldByMappingJsonKey(registrationId, - MappingJsonConstants.INDIVIDUAL_BIOMETRICS, registrationStatusDto.getRegistrationType(), - ProviderStageName.BIO_AUTH); - if (StringUtils.isEmpty(biometricsLabel)) { - isTransactionSuccessful = checkIndividualAuthentication(registrationId, process, - registrationStatusDto); - description = isTransactionSuccessful - ? PlatformSuccessMessages.RPR_PKR_BIOMETRIC_AUTHENTICATION.getMessage() - : PlatformErrorMessages.BIOMETRIC_AUTHENTICATION_FAILED.getMessage(); - } else { - String individualBiometricsFileName = JsonUtil.getJSONValue( - JsonUtil.readValueWithUnknownProperties(biometricsLabel, JSONObject.class), - MappingJsonConstants.VALUE); - if (individualBiometricsFileName != null && !individualBiometricsFileName.isEmpty()) { - BiometricRecord biometricRecord = packetManagerService.getBiometricsByMappingJsonKey( - registrationId, MappingJsonConstants.INDIVIDUAL_BIOMETRICS, process, - ProviderStageName.BIO_AUTH); - if (biometricRecord == null || biometricRecord.getSegments() == null - || biometricRecord.getSegments().isEmpty()) { - isTransactionSuccessful = false; - description = StatusUtil.BIOMETRIC_FILE_NOT_FOUND.getMessage(); - regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), - LoggerFileConstant.REGISTRATIONID.toString(), registrationId, description); - registrationStatusDto.setStatusComment(description); - registrationStatusDto.setSubStatusCode(StatusUtil.BIOMETRIC_FILE_NOT_FOUND.getCode()); - } else { - isBioAuthSkipped = true; - regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), - LoggerFileConstant.REGISTRATIONID.toString(), registrationId, - "BiometricAuthenticationStage::skipped"); - isTransactionSuccessful = true; - description = StatusUtil.BIOMETRIC_AUTHENTICATION_SKIPPED.getMessage() - + ADULT_BIOMETRIC_UPDATE; - } - } else { - isTransactionSuccessful = true; - description = PlatformSuccessMessages.RPR_PKR_BIOMETRIC_AUTHENTICATION.getMessage(); - } - } - } - - else { - isBioAuthSkipped = true; - isTransactionSuccessful = true; - regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), - LoggerFileConstant.REGISTRATIONID.toString(), registrationId, - "BiometricAuthenticationStage::success"); - if (applicantType.equals(BiometricAuthenticationConstants.CHILD)) { - description = BiometricAuthenticationConstants.CHILD_PACKET_DESCRIPTION; - - } else - description = StatusUtil.BIOMETRIC_AUTHENTICATION_SKIPPED.getMessage(); - } - - if (isTransactionSuccessful) { - object.setIsValid(Boolean.TRUE); - registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.name()); - registrationStatusDto - .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.SUCCESS.toString()); - if (isBioAuthSkipped) { - registrationStatusDto.setSubStatusCode(StatusUtil.BIOMETRIC_AUTHENTICATION_SKIPPED.getCode()); - registrationStatusDto - .setStatusComment(StatusUtil.BIOMETRIC_AUTHENTICATION_SKIPPED.getMessage() + description); - } else { - registrationStatusDto.setSubStatusCode(StatusUtil.BIOMETRIC_AUTHENTICATION_SUCCESS.getCode()); - registrationStatusDto.setStatusComment(StatusUtil.BIOMETRIC_AUTHENTICATION_SUCCESS.getMessage()); - } - } else { - registrationStatusDto - .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.FAILED.toString()); - registrationStatusDto.setStatusCode(RegistrationTransactionStatusCode.FAILED.toString()); - } - - } catch (IOException | NoSuchAlgorithmException e) { - registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.name()); - registrationStatusDto.setSubStatusCode(StatusUtil.IO_EXCEPTION.getCode()); - registrationStatusDto.setStatusComment( - trimExceptionMessage.trimExceptionMessage(StatusUtil.IO_EXCEPTION.getMessage() + e.getMessage())); - object.setInternalError(Boolean.TRUE); - registrationStatusDto.setLatestTransactionStatusCode( - registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.IOEXCEPTION)); - code = PlatformErrorMessages.BIOMETRIC_AUTHENTICATION_IOEXCEPTION.getCode(); - description = PlatformErrorMessages.BIOMETRIC_AUTHENTICATION_IOEXCEPTION.getMessage(); - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), code, registrationId, - description + e.getMessage() + ExceptionUtils.getStackTrace(e)); - } catch (JsonProcessingException e) { - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - registrationId, - RegistrationStatusCode.FAILED.toString() + e.getMessage() + ExceptionUtils.getStackTrace(e)); - registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.toString()); - registrationStatusDto.setStatusComment(trimExceptionMessage - .trimExceptionMessage(StatusUtil.JSON_PARSING_EXCEPTION.getMessage() + e.getMessage())); - registrationStatusDto.setSubStatusCode(StatusUtil.JSON_PARSING_EXCEPTION.getCode()); - registrationStatusDto.setLatestTransactionStatusCode(registrationStatusMapperUtil - .getStatusCode(RegistrationExceptionTypeCode.JSON_PROCESSING_EXCEPTION)); - isTransactionSuccessful = false; - description = (PlatformErrorMessages.RPR_SYS_JSON_PARSING_EXCEPTION.getMessage()); - code = (PlatformErrorMessages.RPR_SYS_JSON_PARSING_EXCEPTION.getCode()); - object.setInternalError(Boolean.TRUE); - object.setRid(registrationStatusDto.getRegistrationId()); - } catch (PacketManagerException e) { - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - registrationId, - RegistrationStatusCode.FAILED.toString() + e.getMessage() + ExceptionUtils.getStackTrace(e)); - registrationStatusDto.setStatusComment(trimExceptionMessage - .trimExceptionMessage(StatusUtil.PACKET_MANAGER_EXCEPTION.getMessage() + e.getMessage())); - registrationStatusDto.setSubStatusCode(StatusUtil.PACKET_MANAGER_EXCEPTION.getCode()); - registrationStatusDto.setLatestTransactionStatusCode( - registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.PACKET_MANAGER_EXCEPTION)); - registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.name()); - description = (PlatformErrorMessages.PACKET_MANAGER_EXCEPTION.getMessage()); - code = (PlatformErrorMessages.PACKET_MANAGER_EXCEPTION.getCode()); - object.setInternalError(Boolean.TRUE); - object.setRid(registrationStatusDto.getRegistrationId()); - } catch (ApisResourceAccessException e) { - registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.name()); - registrationStatusDto.setSubStatusCode(StatusUtil.API_RESOUCE_ACCESS_FAILED.getCode()); - registrationStatusDto.setStatusComment(trimExceptionMessage - .trimExceptionMessage(StatusUtil.API_RESOUCE_ACCESS_FAILED.getMessage() + e.getMessage())); - registrationStatusDto.setLatestTransactionStatusCode(registrationStatusMapperUtil - .getStatusCode(RegistrationExceptionTypeCode.APIS_RESOURCE_ACCESS_EXCEPTION)); - code = PlatformErrorMessages.BIOMETRIC_AUTHENTICATION_API_RESOURCE_EXCEPTION.getCode(); - description = PlatformErrorMessages.BIOMETRIC_AUTHENTICATION_API_RESOURCE_EXCEPTION.getMessage(); - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), code, registrationId, - description + e.getMessage() + ExceptionUtils.getStackTrace(e)); - object.setInternalError(Boolean.TRUE); - } catch (AuthSystemException e) { - registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.name()); - registrationStatusDto.setSubStatusCode(StatusUtil.AUTH_SYSTEM_EXCEPTION.getCode()); - registrationStatusDto.setStatusComment(trimExceptionMessage - .trimExceptionMessage(StatusUtil.AUTH_SYSTEM_EXCEPTION.getMessage() + e.getMessage())); - registrationStatusDto.setLatestTransactionStatusCode( - registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.AUTH_SYSTEM_EXCEPTION)); - code = PlatformErrorMessages.BIOMETRIC_AUTHENTICATION_AUTH_SYSTEM_EXCEPTION.getCode(); - description = PlatformErrorMessages.BIOMETRIC_AUTHENTICATION_AUTH_SYSTEM_EXCEPTION.getMessage(); - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), code, registrationId, - description + e.getMessage() + ExceptionUtils.getStackTrace(e)); - object.setInternalError(Boolean.TRUE); - } catch (ValidationFailedException e) { - isTransactionSuccessful=false; - description=PlatformErrorMessages.INDIVIDUAL_BIOMETRIC_AUTHENTICATION_FAILED.getMessage(); - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), code, registrationId, - description + e.getMessage() + ExceptionUtils.getStackTrace(e)); - object.setInternalError(Boolean.TRUE); - - } catch (Exception ex) { - registrationStatusDto.setSubStatusCode(StatusUtil.UNKNOWN_EXCEPTION_OCCURED.getCode()); - registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.name()); - registrationStatusDto.setStatusComment(trimExceptionMessage - .trimExceptionMessage(StatusUtil.UNKNOWN_EXCEPTION_OCCURED.getMessage() + ex.getMessage())); - registrationStatusDto.setLatestTransactionStatusCode( - registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.EXCEPTION)); - code = PlatformErrorMessages.BIOMETRIC_AUTHENTICATION_FAILED.getCode(); - description = PlatformErrorMessages.BIOMETRIC_AUTHENTICATION_FAILED.getMessage(); - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), code, registrationId, - description + ex.getMessage() + ExceptionUtils.getStackTrace(ex)); - object.setInternalError(Boolean.TRUE); - } finally { - if (object.getInternalError()) { - updateErrorFlags(registrationStatusDto, object); - } - /** Module-Id can be Both Success/Error code */ - String moduleId = isTransactionSuccessful - ? PlatformSuccessMessages.RPR_PKR_BIOMETRIC_AUTHENTICATION.getCode() - : code; - String moduleName = ModuleName.BIOMETRIC_AUTHENTICATION.toString(); - registrationStatusService.updateRegistrationStatus(registrationStatusDto, moduleId, moduleName); - description = isTransactionSuccessful - ? PlatformSuccessMessages.RPR_PKR_BIOMETRIC_AUTHENTICATION.getMessage() - : description; - String eventId = isTransactionSuccessful ? EventId.RPR_402.toString() : EventId.RPR_405.toString(); - String eventName = isTransactionSuccessful ? EventName.UPDATE.toString() : EventName.EXCEPTION.toString(); - String eventType = isTransactionSuccessful ? EventType.BUSINESS.toString() : EventType.SYSTEM.toString(); - - auditLogRequestBuilder.createAuditRequestBuilder(description, eventId, eventName, eventType, moduleId, - moduleName, registrationId); - } - - return object; - } - - private boolean isUpdateAdultPacket(String registartionType, String applicantType) { - return (registartionType.equalsIgnoreCase(RegistrationType.UPDATE.name()) - || registartionType.equalsIgnoreCase(RegistrationType.RES_UPDATE.name())) - && applicantType.equalsIgnoreCase(BiometricAuthenticationConstants.ADULT); - } - - private boolean checkIndividualAuthentication(String registrationId, String process, - InternalRegistrationStatusDto registrationStatusDto) throws IOException, BioTypeException, - AuthSystemException, ApisResourceAccessException, PacketManagerException, JsonProcessingException, CertificateException, NoSuchAlgorithmException,ValidationFailedException,Exception { - - BiometricRecord biometricRecord = packetManagerService.getBiometricsByMappingJsonKey(registrationId, - MappingJsonConstants.AUTHENTICATION_BIOMETRICS, process, ProviderStageName.BIO_AUTH); - if (biometricRecord == null || CollectionUtils.isEmpty(biometricRecord.getSegments())) { - registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.toString()); - registrationStatusDto - .setStatusComment(StatusUtil.BIOMETRIC_AUTHENTICATION_FAILED_FILE_NOT_FOUND.getMessage()); - registrationStatusDto.setSubStatusCode(StatusUtil.BIOMETRIC_AUTHENTICATION_FAILED_FILE_NOT_FOUND.getCode()); - return false; - } - String uin = utility.getUIn(registrationId, process, ProviderStageName.BIO_AUTH); - - bioUtil.authenticateBiometrics(uin,BiometricAuthenticationConstants.INDIVIDUAL_TYPE_UIN,biometricRecord.getSegments(),registrationStatusDto,StatusUtil.INTRODUCER_AUTHENTICATION_FAILED.getMessage(),StatusUtil.INTRODUCER_AUTHENTICATION_FAILED.getCode()); - return true; - } - - private void updateErrorFlags(InternalRegistrationStatusDto registrationStatusDto, MessageDTO object) { - object.setInternalError(true); - if (registrationStatusDto.getLatestTransactionStatusCode() - .equalsIgnoreCase(RegistrationTransactionStatusCode.REPROCESS.toString())) { - object.setIsValid(true); - } else { - object.setIsValid(false); - } - } - +package io.mosip.registration.processor.biometric.authentication.stage; + +import java.io.IOException; +import java.security.NoSuchAlgorithmException; +import java.security.cert.CertificateException; + +import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang3.exception.ExceptionUtils; +import org.json.simple.JSONObject; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.cloud.context.config.annotation.RefreshScope; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.stereotype.Service; +import org.springframework.util.CollectionUtils; + +import io.mosip.kernel.biometrics.entities.BiometricRecord; +import io.mosip.kernel.core.logger.spi.Logger; +import io.mosip.kernel.core.util.exception.JsonProcessingException; +import io.mosip.registration.processor.biometric.authentication.constants.BiometricAuthenticationConstants; +import io.mosip.registration.processor.core.abstractverticle.MessageBusAddress; +import io.mosip.registration.processor.core.abstractverticle.MessageDTO; +import io.mosip.registration.processor.core.abstractverticle.MosipEventBus; +import io.mosip.registration.processor.core.abstractverticle.MosipRouter; +import io.mosip.registration.processor.core.abstractverticle.MosipVerticleAPIManager; +import io.mosip.registration.processor.core.code.EventId; +import io.mosip.registration.processor.core.code.EventName; +import io.mosip.registration.processor.core.code.EventType; +import io.mosip.registration.processor.core.code.ModuleName; +import io.mosip.registration.processor.core.code.RegistrationExceptionTypeCode; +import io.mosip.registration.processor.core.code.RegistrationTransactionStatusCode; +import io.mosip.registration.processor.core.code.RegistrationTransactionTypeCode; +import io.mosip.registration.processor.core.constant.LoggerFileConstant; +import io.mosip.registration.processor.core.constant.MappingJsonConstants; +import io.mosip.registration.processor.core.constant.ProviderStageName; +import io.mosip.registration.processor.core.constant.RegistrationType; +import io.mosip.registration.processor.core.exception.ApisResourceAccessException; +import io.mosip.registration.processor.core.exception.AuthSystemException; +import io.mosip.registration.processor.core.exception.BioTypeException; +import io.mosip.registration.processor.core.exception.PacketManagerException; +import io.mosip.registration.processor.core.exception.ValidationFailedException; +import io.mosip.registration.processor.core.exception.util.PlatformErrorMessages; +import io.mosip.registration.processor.core.exception.util.PlatformSuccessMessages; +import io.mosip.registration.processor.core.logger.RegProcessorLogger; +import io.mosip.registration.processor.core.status.util.StatusUtil; +import io.mosip.registration.processor.core.status.util.TrimExceptionMessage; +import io.mosip.registration.processor.core.util.JsonUtil; +import io.mosip.registration.processor.core.util.RegistrationExceptionMapperUtil; +import io.mosip.registration.processor.packet.storage.utils.BioSdkUtil; +import io.mosip.registration.processor.packet.storage.utils.PriorityBasedPacketManagerService; +import io.mosip.registration.processor.packet.storage.utils.Utilities; +import io.mosip.registration.processor.rest.client.audit.builder.AuditLogRequestBuilder; +import io.mosip.registration.processor.status.code.RegistrationStatusCode; +import io.mosip.registration.processor.status.dto.InternalRegistrationStatusDto; +import io.mosip.registration.processor.status.dto.RegistrationStatusDto; +import io.mosip.registration.processor.status.dto.SyncRegistrationDto; +import io.mosip.registration.processor.status.dto.SyncResponseDto; +import io.mosip.registration.processor.status.entity.SyncRegistrationEntity; +import io.mosip.registration.processor.status.service.RegistrationStatusService; +import io.mosip.registration.processor.status.service.SyncRegistrationService; + +@RefreshScope +@Service +@Configuration +@ComponentScan(basePackages = { "${mosip.auth.adapter.impl.basepackage}", + "io.mosip.registration.processor.biometric.authentication.config", + "io.mosip.registration.processor.status.config", "io.mosip.registration.processor.rest.client.config", + "io.mosip.registration.processor.packet.storage.config", "io.mosip.registration.processor.core.config", + "io.mosip.registration.processor.core.kernel.beans", "io.mosip.kernel.packetmanager.config", + "io.mosip.kernel.biosdk.provider.impl" }) +public class BiometricAuthenticationStage extends MosipVerticleAPIManager { + private static Logger regProcLogger = RegProcessorLogger.getLogger(BiometricAuthenticationStage.class); + private static final String STAGE_PROPERTY_PREFIX = "mosip.regproc.biometric.authentication."; + private static final String ADULT_BIOMETRIC_UPDATE = "as adult has come for biometric update"; + @Autowired + AuditLogRequestBuilder auditLogRequestBuilder; + + @Autowired + private Utilities utility; + + /** The registration status service. */ + @Autowired + RegistrationStatusService registrationStatusService; + + @Autowired + private BioSdkUtil bioUtil; + + @Autowired + private PriorityBasedPacketManagerService packetManagerService; + + @Autowired + RegistrationExceptionMapperUtil registrationStatusMapperUtil; + + @Value("${vertx.cluster.configuration}") + private String clusterManagerUrl; + + @Value("${mosip.kernel.applicant.type.age.limit}") + private String ageLimit; + + /** worker pool size. */ + @Value("${worker.pool.size}") + private Integer workerPoolSize; + + /** + * After this time intervel, message should be considered as expired (In + * seconds). + */ + @Value("${mosip.regproc.biometric.authentication.message.expiry-time-limit}") + private Long messageExpiryTimeLimit; + + /** The mosip event bus. */ + MosipEventBus mosipEventBus = null; + + /** Mosip router for APIs */ + @Autowired + MosipRouter router; + + @Autowired + private SyncRegistrationService syncRegistrationservice; + + public void deployVerticle() { + mosipEventBus = this.getEventBus(this, clusterManagerUrl, workerPoolSize); + this.consumeAndSend(mosipEventBus, MessageBusAddress.BIOMETRIC_AUTHENTICATION_BUS_IN, + MessageBusAddress.BIOMETRIC_AUTHENTICATION_BUS_OUT, messageExpiryTimeLimit); + } + + @Override + public void start() { + router.setRoute(this.postUrl(getVertx(), MessageBusAddress.BIOMETRIC_AUTHENTICATION_BUS_IN, + MessageBusAddress.BIOMETRIC_AUTHENTICATION_BUS_OUT)); + this.createServer(router.getRouter(), getPort()); + } + + @Override + protected String getPropertyPrefix() { + return STAGE_PROPERTY_PREFIX; + } + + @Override + public MessageDTO process(MessageDTO object) { + TrimExceptionMessage trimExceptionMessage = new TrimExceptionMessage(); + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), "", + "BiometricAuthenticationStage::BiometricAuthenticationStage::entry"); + String registrationId = object.getRid(); + object.setMessageBusAddress(MessageBusAddress.BIOMETRIC_AUTHENTICATION_BUS_IN); + object.setIsValid(Boolean.FALSE); + object.setInternalError(Boolean.FALSE); + InternalRegistrationStatusDto registrationStatusDto = registrationStatusService.getRegistrationStatus( + registrationId, object.getReg_type(), object.getIteration(), object.getWorkflowInstanceId()); + + registrationStatusDto + .setLatestTransactionTypeCode(RegistrationTransactionTypeCode.BIOMETRIC_AUTHENTICATION.toString()); + registrationStatusDto.setRegistrationStageName(getStageName()); + SyncRegistrationEntity regEntity = syncRegistrationservice + .findByWorkflowInstanceId(object.getWorkflowInstanceId()); + String description = ""; + String code = ""; + boolean isBioAuthSkipped = false; + boolean isTransactionSuccessful = false; + + try { + String process = registrationStatusDto.getRegistrationType(); + String registartionType = regEntity.getRegistrationType(); + int applicantAge = utility.getApplicantAge(registrationId, process, ProviderStageName.BIO_AUTH); + int childAgeLimit = Integer.parseInt(ageLimit); + String applicantType = BiometricAuthenticationConstants.ADULT; + if (applicantAge <= childAgeLimit && applicantAge >= 0) { + applicantType = BiometricAuthenticationConstants.CHILD; + } + if (isUpdateAdultPacket(registartionType, applicantType)) { + + String biometricsLabel = packetManagerService.getFieldByMappingJsonKey(registrationId, + MappingJsonConstants.INDIVIDUAL_BIOMETRICS, registrationStatusDto.getRegistrationType(), + ProviderStageName.BIO_AUTH); + if (StringUtils.isEmpty(biometricsLabel)) { + isTransactionSuccessful = checkIndividualAuthentication(registrationId, process, + registrationStatusDto); + description = isTransactionSuccessful + ? PlatformSuccessMessages.RPR_PKR_BIOMETRIC_AUTHENTICATION.getMessage() + : PlatformErrorMessages.BIOMETRIC_AUTHENTICATION_FAILED.getMessage(); + } else { + String individualBiometricsFileName = JsonUtil.getJSONValue( + JsonUtil.readValueWithUnknownProperties(biometricsLabel, JSONObject.class), + MappingJsonConstants.VALUE); + if (individualBiometricsFileName != null && !individualBiometricsFileName.isEmpty()) { + BiometricRecord biometricRecord = packetManagerService.getBiometricsByMappingJsonKey( + registrationId, MappingJsonConstants.INDIVIDUAL_BIOMETRICS, process, + ProviderStageName.BIO_AUTH); + if (biometricRecord == null || biometricRecord.getSegments() == null + || biometricRecord.getSegments().isEmpty()) { + isTransactionSuccessful = false; + description = StatusUtil.BIOMETRIC_FILE_NOT_FOUND.getMessage(); + regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString(), registrationId, description); + registrationStatusDto.setStatusComment(description); + registrationStatusDto.setSubStatusCode(StatusUtil.BIOMETRIC_FILE_NOT_FOUND.getCode()); + } else { + isBioAuthSkipped = true; + regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString(), registrationId, + "BiometricAuthenticationStage::skipped"); + isTransactionSuccessful = true; + description = StatusUtil.BIOMETRIC_AUTHENTICATION_SKIPPED.getMessage() + + ADULT_BIOMETRIC_UPDATE; + } + } else { + isTransactionSuccessful = true; + description = PlatformSuccessMessages.RPR_PKR_BIOMETRIC_AUTHENTICATION.getMessage(); + } + } + } + + else { + isBioAuthSkipped = true; + isTransactionSuccessful = true; + regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString(), registrationId, + "BiometricAuthenticationStage::success"); + if (applicantType.equals(BiometricAuthenticationConstants.CHILD)) { + description = BiometricAuthenticationConstants.CHILD_PACKET_DESCRIPTION; + + } else + description = StatusUtil.BIOMETRIC_AUTHENTICATION_SKIPPED.getMessage(); + } + + if (isTransactionSuccessful) { + object.setIsValid(Boolean.TRUE); + registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.name()); + registrationStatusDto + .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.SUCCESS.toString()); + if (isBioAuthSkipped) { + registrationStatusDto.setSubStatusCode(StatusUtil.BIOMETRIC_AUTHENTICATION_SKIPPED.getCode()); + registrationStatusDto + .setStatusComment(StatusUtil.BIOMETRIC_AUTHENTICATION_SKIPPED.getMessage() + description); + } else { + registrationStatusDto.setSubStatusCode(StatusUtil.BIOMETRIC_AUTHENTICATION_SUCCESS.getCode()); + registrationStatusDto.setStatusComment(StatusUtil.BIOMETRIC_AUTHENTICATION_SUCCESS.getMessage()); + } + } else { + registrationStatusDto + .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.FAILED.toString()); + registrationStatusDto.setStatusCode(RegistrationTransactionStatusCode.FAILED.toString()); + } + + } catch (IOException | NoSuchAlgorithmException e) { + registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.name()); + registrationStatusDto.setSubStatusCode(StatusUtil.IO_EXCEPTION.getCode()); + registrationStatusDto.setStatusComment( + trimExceptionMessage.trimExceptionMessage(StatusUtil.IO_EXCEPTION.getMessage() + e.getMessage())); + object.setInternalError(Boolean.TRUE); + registrationStatusDto.setLatestTransactionStatusCode( + registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.IOEXCEPTION)); + code = PlatformErrorMessages.BIOMETRIC_AUTHENTICATION_IOEXCEPTION.getCode(); + description = PlatformErrorMessages.BIOMETRIC_AUTHENTICATION_IOEXCEPTION.getMessage(); + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), code, registrationId, + description + e.getMessage() + ExceptionUtils.getStackTrace(e)); + } catch (JsonProcessingException e) { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + registrationId, + RegistrationStatusCode.FAILED.toString() + e.getMessage() + ExceptionUtils.getStackTrace(e)); + registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.toString()); + registrationStatusDto.setStatusComment(trimExceptionMessage + .trimExceptionMessage(StatusUtil.JSON_PARSING_EXCEPTION.getMessage() + e.getMessage())); + registrationStatusDto.setSubStatusCode(StatusUtil.JSON_PARSING_EXCEPTION.getCode()); + registrationStatusDto.setLatestTransactionStatusCode(registrationStatusMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.JSON_PROCESSING_EXCEPTION)); + isTransactionSuccessful = false; + description = (PlatformErrorMessages.RPR_SYS_JSON_PARSING_EXCEPTION.getMessage()); + code = (PlatformErrorMessages.RPR_SYS_JSON_PARSING_EXCEPTION.getCode()); + object.setInternalError(Boolean.TRUE); + object.setRid(registrationStatusDto.getRegistrationId()); + } catch (PacketManagerException e) { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + registrationId, + RegistrationStatusCode.FAILED.toString() + e.getMessage() + ExceptionUtils.getStackTrace(e)); + registrationStatusDto.setStatusComment(trimExceptionMessage + .trimExceptionMessage(StatusUtil.PACKET_MANAGER_EXCEPTION.getMessage() + e.getMessage())); + registrationStatusDto.setSubStatusCode(StatusUtil.PACKET_MANAGER_EXCEPTION.getCode()); + registrationStatusDto.setLatestTransactionStatusCode( + registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.PACKET_MANAGER_EXCEPTION)); + registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.name()); + description = (PlatformErrorMessages.PACKET_MANAGER_EXCEPTION.getMessage()); + code = (PlatformErrorMessages.PACKET_MANAGER_EXCEPTION.getCode()); + object.setInternalError(Boolean.TRUE); + object.setRid(registrationStatusDto.getRegistrationId()); + } catch (ApisResourceAccessException e) { + registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.name()); + registrationStatusDto.setSubStatusCode(StatusUtil.API_RESOUCE_ACCESS_FAILED.getCode()); + registrationStatusDto.setStatusComment(trimExceptionMessage + .trimExceptionMessage(StatusUtil.API_RESOUCE_ACCESS_FAILED.getMessage() + e.getMessage())); + registrationStatusDto.setLatestTransactionStatusCode(registrationStatusMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.APIS_RESOURCE_ACCESS_EXCEPTION)); + code = PlatformErrorMessages.BIOMETRIC_AUTHENTICATION_API_RESOURCE_EXCEPTION.getCode(); + description = PlatformErrorMessages.BIOMETRIC_AUTHENTICATION_API_RESOURCE_EXCEPTION.getMessage(); + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), code, registrationId, + description + e.getMessage() + ExceptionUtils.getStackTrace(e)); + object.setInternalError(Boolean.TRUE); + } catch (AuthSystemException e) { + registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.name()); + registrationStatusDto.setSubStatusCode(StatusUtil.AUTH_SYSTEM_EXCEPTION.getCode()); + registrationStatusDto.setStatusComment(trimExceptionMessage + .trimExceptionMessage(StatusUtil.AUTH_SYSTEM_EXCEPTION.getMessage() + e.getMessage())); + registrationStatusDto.setLatestTransactionStatusCode( + registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.AUTH_SYSTEM_EXCEPTION)); + code = PlatformErrorMessages.BIOMETRIC_AUTHENTICATION_AUTH_SYSTEM_EXCEPTION.getCode(); + description = PlatformErrorMessages.BIOMETRIC_AUTHENTICATION_AUTH_SYSTEM_EXCEPTION.getMessage(); + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), code, registrationId, + description + e.getMessage() + ExceptionUtils.getStackTrace(e)); + object.setInternalError(Boolean.TRUE); + } catch (ValidationFailedException e) { + isTransactionSuccessful=false; + description=PlatformErrorMessages.INDIVIDUAL_BIOMETRIC_AUTHENTICATION_FAILED.getMessage(); + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), code, registrationId, + description + e.getMessage() + ExceptionUtils.getStackTrace(e)); + object.setInternalError(Boolean.TRUE); + + } catch (Exception ex) { + registrationStatusDto.setSubStatusCode(StatusUtil.UNKNOWN_EXCEPTION_OCCURED.getCode()); + registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.name()); + registrationStatusDto.setStatusComment(trimExceptionMessage + .trimExceptionMessage(StatusUtil.UNKNOWN_EXCEPTION_OCCURED.getMessage() + ex.getMessage())); + registrationStatusDto.setLatestTransactionStatusCode( + registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.EXCEPTION)); + code = PlatformErrorMessages.BIOMETRIC_AUTHENTICATION_FAILED.getCode(); + description = PlatformErrorMessages.BIOMETRIC_AUTHENTICATION_FAILED.getMessage(); + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), code, registrationId, + description + ex.getMessage() + ExceptionUtils.getStackTrace(ex)); + object.setInternalError(Boolean.TRUE); + } finally { + if (object.getInternalError()) { + updateErrorFlags(registrationStatusDto, object); + } + /** Module-Id can be Both Success/Error code */ + String moduleId = isTransactionSuccessful + ? PlatformSuccessMessages.RPR_PKR_BIOMETRIC_AUTHENTICATION.getCode() + : code; + String moduleName = ModuleName.BIOMETRIC_AUTHENTICATION.toString(); + registrationStatusService.updateRegistrationStatus(registrationStatusDto, moduleId, moduleName); + description = isTransactionSuccessful + ? PlatformSuccessMessages.RPR_PKR_BIOMETRIC_AUTHENTICATION.getMessage() + : description; + String eventId = isTransactionSuccessful ? EventId.RPR_402.toString() : EventId.RPR_405.toString(); + String eventName = isTransactionSuccessful ? EventName.UPDATE.toString() : EventName.EXCEPTION.toString(); + String eventType = isTransactionSuccessful ? EventType.BUSINESS.toString() : EventType.SYSTEM.toString(); + + auditLogRequestBuilder.createAuditRequestBuilder(description, eventId, eventName, eventType, moduleId, + moduleName, registrationId); + } + + return object; + } + + private boolean isUpdateAdultPacket(String registartionType, String applicantType) { + return (registartionType.equalsIgnoreCase(RegistrationType.UPDATE.name()) + || registartionType.equalsIgnoreCase(RegistrationType.RES_UPDATE.name())) + && applicantType.equalsIgnoreCase(BiometricAuthenticationConstants.ADULT); + } + + private boolean checkIndividualAuthentication(String registrationId, String process, + InternalRegistrationStatusDto registrationStatusDto) throws IOException, BioTypeException, + AuthSystemException, ApisResourceAccessException, PacketManagerException, JsonProcessingException, CertificateException, NoSuchAlgorithmException,ValidationFailedException,Exception { + + BiometricRecord biometricRecord = packetManagerService.getBiometricsByMappingJsonKey(registrationId, + MappingJsonConstants.AUTHENTICATION_BIOMETRICS, process, ProviderStageName.BIO_AUTH); + if (biometricRecord == null || CollectionUtils.isEmpty(biometricRecord.getSegments())) { + registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.toString()); + registrationStatusDto + .setStatusComment(StatusUtil.BIOMETRIC_AUTHENTICATION_FAILED_FILE_NOT_FOUND.getMessage()); + registrationStatusDto.setSubStatusCode(StatusUtil.BIOMETRIC_AUTHENTICATION_FAILED_FILE_NOT_FOUND.getCode()); + return false; + } + String uin = utility.getUIn(registrationId, process, ProviderStageName.BIO_AUTH); + + bioUtil.authenticateBiometrics(uin,BiometricAuthenticationConstants.INDIVIDUAL_TYPE_UIN,biometricRecord.getSegments(),registrationStatusDto,StatusUtil.INTRODUCER_AUTHENTICATION_FAILED.getMessage(),StatusUtil.INTRODUCER_AUTHENTICATION_FAILED.getCode()); + return true; + } + + private void updateErrorFlags(InternalRegistrationStatusDto registrationStatusDto, MessageDTO object) { + object.setInternalError(true); + if (registrationStatusDto.getLatestTransactionStatusCode() + .equalsIgnoreCase(RegistrationTransactionStatusCode.REPROCESS.toString())) { + object.setIsValid(true); + } else { + object.setIsValid(false); + } + } + } \ No newline at end of file diff --git a/registration-processor/core-processor/registration-processor-biometric-authentication-stage/src/test/java/io/mosip/registration/processor/biometric/authentication/stage/BiometricAuthenticationStageTest.java b/registration-processor/core-processor/registration-processor-biometric-authentication-stage/src/test/java/io/mosip/registration/processor/biometric/authentication/stage/BiometricAuthenticationStageTest.java index 4476e6d3ab6..6b1ae621272 100644 --- a/registration-processor/core-processor/registration-processor-biometric-authentication-stage/src/test/java/io/mosip/registration/processor/biometric/authentication/stage/BiometricAuthenticationStageTest.java +++ b/registration-processor/core-processor/registration-processor-biometric-authentication-stage/src/test/java/io/mosip/registration/processor/biometric/authentication/stage/BiometricAuthenticationStageTest.java @@ -618,4 +618,12 @@ public void testPacketManagerException() throws ApisResourceAccessException, IOE assertTrue(messageDto.getInternalError()); assertTrue(messageDto.getIsValid()); } + + @Test + public void testChildPacketWithLessThanOneYear() throws ApisResourceAccessException, JsonProcessingException, io.mosip.kernel.core.exception.IOException, PacketManagerException, IOException { + when(regentity.getRegistrationType()).thenReturn("UPDATE"); + when(utility.getApplicantAge(anyString(),anyString(), any())).thenReturn(0); + MessageDTO messageDto = biometricAuthenticationStage.process(dto); + assertTrue(messageDto.getIsValid()); + } } From 39220769be1b36f2b9c5240079f253bf219ed743 Mon Sep 17 00:00:00 2001 From: Sowmya Ujjappa Banakar Date: Mon, 6 Nov 2023 11:34:11 +0530 Subject: [PATCH 12/38] MOSIP-29780 code fix Signed-off-by: Sowmya Ujjappa Banakar --- .../stage/BiometricExtractionStage.java | 44 +- .../finalization/stage/FinalizationStage.java | 23 +- .../uingenerator/stage/UinGeneratorStage.java | 2229 +++++++++-------- .../uigenerator/UinGeneratorStageTest.java | 51 +- .../code/RegistrationExceptionTypeCode.java | 5 +- .../core/status/util/StatusUtil.java | 17 +- .../util/RegistrationExceptionMapperUtil.java | 2 + .../IdrepoDraftReprocessableException.java | 10 + .../idreposervice/IdrepoDraftService.java | 268 +- .../impl/test/IdrepoDraftServiceTest.java | 410 +-- 10 files changed, 1587 insertions(+), 1472 deletions(-) create mode 100644 registration-processor/registration-processor-packet-manager/src/main/java/io/mosip/registration/processor/packet/manager/exception/IdrepoDraftReprocessableException.java diff --git a/registration-processor/core-processor/registration-processor-biometric-extraction-stage/src/main/java/io/mosip/registration/processor/stages/biometric/extraction/stage/BiometricExtractionStage.java b/registration-processor/core-processor/registration-processor-biometric-extraction-stage/src/main/java/io/mosip/registration/processor/stages/biometric/extraction/stage/BiometricExtractionStage.java index bd355ca1600..893abfcee5a 100644 --- a/registration-processor/core-processor/registration-processor-biometric-extraction-stage/src/main/java/io/mosip/registration/processor/stages/biometric/extraction/stage/BiometricExtractionStage.java +++ b/registration-processor/core-processor/registration-processor-biometric-extraction-stage/src/main/java/io/mosip/registration/processor/stages/biometric/extraction/stage/BiometricExtractionStage.java @@ -4,8 +4,6 @@ import java.util.ArrayList; import java.util.List; -import javax.ws.rs.core.MediaType; - import org.apache.commons.lang3.exception.ExceptionUtils; import org.json.JSONArray; import org.json.JSONException; @@ -52,6 +50,7 @@ import io.mosip.registration.processor.core.util.RegistrationExceptionMapperUtil; import io.mosip.registration.processor.packet.manager.dto.IdResponseDTO; import io.mosip.registration.processor.packet.manager.exception.IdrepoDraftException; +import io.mosip.registration.processor.packet.manager.exception.IdrepoDraftReprocessableException; import io.mosip.registration.processor.packet.manager.idreposervice.IdrepoDraftService; import io.mosip.registration.processor.rest.client.audit.builder.AuditLogRequestBuilder; import io.mosip.registration.processor.status.code.RegistrationStatusCode; @@ -76,6 +75,7 @@ public class BiometricExtractionStage extends MosipVerticleAPIManager{ /** stage properties prefix */ private static final String STAGE_PROPERTY_PREFIX = "mosip.regproc.biometric.extraction."; private static final String USER = "MOSIP_SYSTEM"; + private static final String ID_REPO_KEY_MANAGER_ERROR = "IDR-IDS-003"; /** The mosip event bus. */ MosipEventBus mosipEventBus = null; @@ -267,14 +267,31 @@ public MessageDTO process(MessageDTO object) { RegistrationStatusCode.FAILED.toString() + e.getMessage() + ExceptionUtils.getStackTrace(e)); registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.name()); registrationStatusDto.setStatusComment( - trimExceptionMessage.trimExceptionMessage(StatusUtil.IDREPO_DRAFT_EXCEPTION.getMessage() + e.getMessage())); - registrationStatusDto.setSubStatusCode(StatusUtil.IDREPO_DRAFT_EXCEPTION.getCode()); + trimExceptionMessage.trimExceptionMessage( + StatusUtil.BIOMETRIC_EXTRACTION_IDREPO_DRAFT_EXCEPTION.getMessage() + e.getMessage())); + registrationStatusDto.setSubStatusCode(StatusUtil.BIOMETRIC_EXTRACTION_IDREPO_DRAFT_EXCEPTION.getCode()); registrationStatusDto.setLatestTransactionStatusCode( registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.IDREPO_DRAFT_EXCEPTION)); description.setMessage(PlatformErrorMessages.IDREPO_DRAFT_EXCEPTION.getMessage()); description.setCode(PlatformErrorMessages.IDREPO_DRAFT_EXCEPTION.getCode()); object.setInternalError(Boolean.TRUE); object.setRid(registrationStatusDto.getRegistrationId()); + } catch (IdrepoDraftReprocessableException e) { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + registrationId, + RegistrationStatusCode.PROCESSING.toString() + e.getMessage() + ExceptionUtils.getStackTrace(e)); + registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.name()); + registrationStatusDto.setStatusComment(trimExceptionMessage.trimExceptionMessage( + StatusUtil.BIOMETRIC_EXTRACTION_IDREPO_DRAFT_REPROCESSABLE_EXCEPTION.getMessage() + + e.getMessage())); + registrationStatusDto + .setSubStatusCode(StatusUtil.BIOMETRIC_EXTRACTION_IDREPO_DRAFT_REPROCESSABLE_EXCEPTION.getCode()); + registrationStatusDto.setLatestTransactionStatusCode(registrationStatusMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.IDREPO_DRAFT_REPROCESSABLE_EXCEPTION)); + description.setMessage(PlatformErrorMessages.IDREPO_DRAFT_EXCEPTION.getMessage()); + description.setCode(PlatformErrorMessages.IDREPO_DRAFT_EXCEPTION.getCode()); + object.setInternalError(Boolean.TRUE); + object.setRid(registrationStatusDto.getRegistrationId()); }catch (Exception ex) { registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.name()); registrationStatusDto.setStatusComment( @@ -323,13 +340,17 @@ public MessageDTO process(MessageDTO object) { /** * add biometric extractions to id repo + * * @param dto * @param registrationId * @throws ApisResourceAccessException - * @throws RegistrationProcessorCheckedException + * @throws IdrepoDraftReprocessableException + * @throws IdrepoDraftException + * */ private IdResponseDTO addBiometricExtractiontoIdRepository(ExtractorDto dto, - String registrationId) throws ApisResourceAccessException, RegistrationProcessorCheckedException { + String registrationId) + throws ApisResourceAccessException, IdrepoDraftReprocessableException, IdrepoDraftException { String extractionFormat = ""; if(dto.getBiometric().equals("iris")) { extractionFormat="irisExtractionFormat"; @@ -340,10 +361,15 @@ private IdResponseDTO addBiometricExtractiontoIdRepository(ExtractorDto dto, } List segments=List.of(registrationId); IdResponseDTO response= (IdResponseDTO) registrationProcessorRestClientService.putApi(ApiName.IDREPOEXTRACTBIOMETRICS, segments, extractionFormat, dto.getAttributeName(), null, IdResponseDTO.class, null); + if (response.getErrors() != null && !response.getErrors().isEmpty()) { - regProcLogger.error("Error occured while updating draft for id : " + registrationId, response.getErrors().iterator().next().toString()); - throw new RegistrationProcessorCheckedException(response.getErrors().iterator().next().getErrorCode(), - response.getErrors().iterator().next().getMessage()); + ErrorDTO error = response.getErrors().get(0); + regProcLogger.error("Error occured while updating draft for id : " + registrationId, error.toString()); + if (response.getErrors().get(0).getErrorCode().equalsIgnoreCase(ID_REPO_KEY_MANAGER_ERROR)) { + throw new IdrepoDraftReprocessableException(error.getErrorCode(), error.getMessage()); + } else { + throw new IdrepoDraftException(error.getErrorCode(), error.getMessage()); + } } return response; } diff --git a/registration-processor/core-processor/registration-processor-finalization-stage/src/main/java/io/mosip/registration/processor/stages/finalization/stage/FinalizationStage.java b/registration-processor/core-processor/registration-processor-finalization-stage/src/main/java/io/mosip/registration/processor/stages/finalization/stage/FinalizationStage.java index 38c81750354..c4236fde362 100644 --- a/registration-processor/core-processor/registration-processor-finalization-stage/src/main/java/io/mosip/registration/processor/stages/finalization/stage/FinalizationStage.java +++ b/registration-processor/core-processor/registration-processor-finalization-stage/src/main/java/io/mosip/registration/processor/stages/finalization/stage/FinalizationStage.java @@ -32,6 +32,7 @@ import io.mosip.registration.processor.core.util.RegistrationExceptionMapperUtil; import io.mosip.registration.processor.packet.manager.dto.IdResponseDTO; import io.mosip.registration.processor.packet.manager.exception.IdrepoDraftException; +import io.mosip.registration.processor.packet.manager.exception.IdrepoDraftReprocessableException; import io.mosip.registration.processor.packet.manager.idreposervice.IdrepoDraftService; import io.mosip.registration.processor.rest.client.audit.builder.AuditLogRequestBuilder; import io.mosip.registration.processor.status.code.RegistrationStatusCode; @@ -199,14 +200,32 @@ public MessageDTO process(MessageDTO object) { RegistrationStatusCode.FAILED.toString() + e.getMessage() + ExceptionUtils.getStackTrace(e)); registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.name()); registrationStatusDto.setStatusComment( - trimExceptionMessage.trimExceptionMessage(StatusUtil.IDREPO_DRAFT_EXCEPTION.getMessage() + e.getMessage())); - registrationStatusDto.setSubStatusCode(StatusUtil.IDREPO_DRAFT_EXCEPTION.getCode()); + trimExceptionMessage.trimExceptionMessage( + StatusUtil.FINALIZATION_IDREPO_DRAFT_EXCEPTION.getMessage() + e.getMessage())); + registrationStatusDto.setSubStatusCode(StatusUtil.FINALIZATION_IDREPO_DRAFT_EXCEPTION.getCode()); registrationStatusDto.setLatestTransactionStatusCode( registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.IDREPO_DRAFT_EXCEPTION)); description.setMessage(PlatformErrorMessages.IDREPO_DRAFT_EXCEPTION.getMessage()); description.setCode(PlatformErrorMessages.IDREPO_DRAFT_EXCEPTION.getCode()); object.setInternalError(Boolean.TRUE); object.setRid(registrationStatusDto.getRegistrationId()); + } catch (IdrepoDraftReprocessableException e) { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + registrationId, + RegistrationStatusCode.PROCESSING.toString() + e.getMessage() + ExceptionUtils.getStackTrace(e)); + registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.name()); + registrationStatusDto.setStatusComment(trimExceptionMessage + .trimExceptionMessage( + StatusUtil.FINALIZATION_IDREPO_DRAFT_REPROCESSABLE_EXCEPTION.getMessage() + + e.getMessage())); + registrationStatusDto + .setSubStatusCode(StatusUtil.FINALIZATION_IDREPO_DRAFT_REPROCESSABLE_EXCEPTION.getCode()); + registrationStatusDto.setLatestTransactionStatusCode(registrationStatusMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.IDREPO_DRAFT_REPROCESSABLE_EXCEPTION)); + description.setMessage(PlatformErrorMessages.IDREPO_DRAFT_EXCEPTION.getMessage()); + description.setCode(PlatformErrorMessages.IDREPO_DRAFT_EXCEPTION.getCode()); + object.setInternalError(Boolean.TRUE); + object.setRid(registrationStatusDto.getRegistrationId()); }catch (Exception ex) { registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.name()); registrationStatusDto.setStatusComment( diff --git a/registration-processor/core-processor/registration-processor-uin-generator-stage/src/main/java/io/mosip/registration/processor/stages/uingenerator/stage/UinGeneratorStage.java b/registration-processor/core-processor/registration-processor-uin-generator-stage/src/main/java/io/mosip/registration/processor/stages/uingenerator/stage/UinGeneratorStage.java index e0fa2df1f34..5d5e8ac4421 100644 --- a/registration-processor/core-processor/registration-processor-uin-generator-stage/src/main/java/io/mosip/registration/processor/stages/uingenerator/stage/UinGeneratorStage.java +++ b/registration-processor/core-processor/registration-processor-uin-generator-stage/src/main/java/io/mosip/registration/processor/stages/uingenerator/stage/UinGeneratorStage.java @@ -1,1113 +1,1116 @@ -package io.mosip.registration.processor.stages.uingenerator.stage; - -import java.io.IOException; -import java.time.LocalDateTime; -import java.time.format.DateTimeFormatter; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -import io.mosip.registration.processor.packet.manager.exception.IdrepoDraftException; -import io.mosip.registration.processor.packet.manager.idreposervice.IdrepoDraftService; -import org.apache.commons.lang3.exception.ExceptionUtils; -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONTokener; -import org.json.simple.JSONObject; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.cloud.context.config.annotation.RefreshScope; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.core.env.Environment; -import org.springframework.stereotype.Service; -import org.springframework.web.client.HttpClientErrorException; -import org.springframework.web.client.HttpServerErrorException; - -import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.databind.JsonMappingException; -import com.fasterxml.jackson.databind.ObjectMapper; - -import io.mosip.kernel.biometrics.entities.BiometricRecord; -import io.mosip.kernel.biometrics.spi.CbeffUtil; -import io.mosip.kernel.core.http.RequestWrapper; -import io.mosip.kernel.core.logger.spi.Logger; -import io.mosip.kernel.core.util.CryptoUtil; -import io.mosip.kernel.core.util.DateUtils; -import io.mosip.kernel.core.util.StringUtils; -import io.mosip.registration.processor.core.abstractverticle.MessageBusAddress; -import io.mosip.registration.processor.core.abstractverticle.MessageDTO; -import io.mosip.registration.processor.core.abstractverticle.MosipEventBus; -import io.mosip.registration.processor.core.abstractverticle.MosipRouter; -import io.mosip.registration.processor.core.abstractverticle.MosipVerticleAPIManager; -import io.mosip.registration.processor.core.code.ApiName; -import io.mosip.registration.processor.core.code.ModuleName; -import io.mosip.registration.processor.core.code.RegistrationExceptionTypeCode; -import io.mosip.registration.processor.core.code.RegistrationTransactionStatusCode; -import io.mosip.registration.processor.core.code.RegistrationTransactionTypeCode; -import io.mosip.registration.processor.core.common.rest.dto.ErrorDTO; -import io.mosip.registration.processor.core.constant.EventId; -import io.mosip.registration.processor.core.constant.EventName; -import io.mosip.registration.processor.core.constant.EventType; -import io.mosip.registration.processor.core.constant.LoggerFileConstant; -import io.mosip.registration.processor.core.constant.MappingJsonConstants; -import io.mosip.registration.processor.core.constant.ProviderStageName; -import io.mosip.registration.processor.core.exception.ApisResourceAccessException; -import io.mosip.registration.processor.core.exception.PacketManagerException; -import io.mosip.registration.processor.core.exception.RegistrationProcessorCheckedException; -import io.mosip.registration.processor.core.exception.util.PlatformErrorMessages; -import io.mosip.registration.processor.core.exception.util.PlatformSuccessMessages; -import io.mosip.registration.processor.core.http.ResponseWrapper; -import io.mosip.registration.processor.core.idrepo.dto.Documents; -import io.mosip.registration.processor.core.logger.LogDescription; -import io.mosip.registration.processor.core.logger.RegProcessorLogger; -import io.mosip.registration.processor.core.spi.restclient.RegistrationProcessorRestClientService; -import io.mosip.registration.processor.core.status.util.StatusUtil; -import io.mosip.registration.processor.core.status.util.TrimExceptionMessage; -import io.mosip.registration.processor.core.util.JsonUtil; -import io.mosip.registration.processor.core.util.RegistrationExceptionMapperUtil; -import io.mosip.registration.processor.packet.manager.idreposervice.IdRepoService; -import io.mosip.registration.processor.packet.storage.dto.Document; -import io.mosip.registration.processor.packet.storage.entity.RegLostUinDetEntity; -import io.mosip.registration.processor.packet.storage.repository.BasePacketRepository; -import io.mosip.registration.processor.packet.storage.utils.ABISHandlerUtil; -import io.mosip.registration.processor.packet.storage.utils.IdSchemaUtil; -import io.mosip.registration.processor.packet.storage.utils.PriorityBasedPacketManagerService; -import io.mosip.registration.processor.packet.storage.utils.Utilities; -import io.mosip.registration.processor.rest.client.audit.builder.AuditLogRequestBuilder; -import io.mosip.registration.processor.stages.uingenerator.constants.UINConstants; -import io.mosip.registration.processor.stages.uingenerator.dto.UinGenResponseDto; -import io.mosip.registration.processor.stages.uingenerator.dto.VidRequestDto; -import io.mosip.registration.processor.stages.uingenerator.dto.VidResponseDto; -import io.mosip.registration.processor.stages.uingenerator.exception.VidCreationException; -import io.mosip.registration.processor.packet.manager.dto.IdRequestDto; -import io.mosip.registration.processor.packet.manager.dto.IdResponseDTO; -import io.mosip.registration.processor.packet.manager.dto.RequestDto; -import io.mosip.registration.processor.stages.uingenerator.util.UinStatusMessage; -import io.mosip.registration.processor.status.code.RegistrationStatusCode; -import io.mosip.registration.processor.status.code.RegistrationType; -import io.mosip.registration.processor.status.dto.InternalRegistrationStatusDto; -import io.mosip.registration.processor.status.dto.RegistrationStatusDto; -import io.mosip.registration.processor.status.service.RegistrationStatusService; - -/** - * The Class UinGeneratorStage. - * - * @author Ranjitha Siddegowda - * @author Rishabh Keshari - */ -@RefreshScope -@Service -@Configuration -@ComponentScan(basePackages = { "${mosip.auth.adapter.impl.basepackage}", - "io.mosip.registration.processor.core.config", - "io.mosip.registration.processor.stages.uingenerator.config", - "io.mosip.registration.processor.status.config", "io.mosip.registration.processor.rest.client.config", - "io.mosip.registration.processor.packet.storage.config", - "io.mosip.registration.processor.stages.config", - "io.mosip.kernel.packetmanager.config", - "io.mosip.registration.processor.packet.manager.config", - "io.mosip.registration.processor.core.kernel.beans"}) -public class UinGeneratorStage extends MosipVerticleAPIManager { - - /** The reg proc logger. */ - private static Logger regProcLogger = RegProcessorLogger.getLogger(UinGeneratorStage.class); - private static final String RECORD_ALREADY_EXISTS_ERROR = "IDR-IDC-012"; - private static final String STAGE_PROPERTY_PREFIX = "mosip.regproc.uin.generator."; - private static final String UIN = "UIN"; - private static final String IDREPO_STATUS = "DRAFTED"; - - @Autowired - private Environment env; - - @Autowired - private IdRepoService idRepoService; - - /** The mosip event bus. */ - MosipEventBus mosipEventBus = null; - - @Value("${registration.processor.id.repo.vidType}") - private String vidType; - - @Value("${mosip.commons.packet.manager.schema.validator.convertIdSchemaToDouble:true}") - private boolean convertIdschemaToDouble; - - /** The cluster manager url. */ - @Value("${vertx.cluster.configuration}") - private String clusterManagerUrl; - - /** The id repo create. */ - @Value("${registration.processor.id.repo.create}") - private String idRepoCreate; - - /** The id repo update. */ - @Value("${registration.processor.id.repo.update}") - private String idRepoUpdate; - - /** worker pool size. */ - @Value("${worker.pool.size}") - private Integer workerPoolSize; - - /** After this time intervel, message should be considered as expired (In seconds). */ - @Value("${mosip.regproc.uin.generator.message.expiry-time-limit}") - private Long messageExpiryTimeLimit; - - @Value("${uingenerator.lost.packet.allowed.update.fields:null}") - private String updateInfo; - - /** The core audit request builder. */ - @Autowired - private AuditLogRequestBuilder auditLogRequestBuilder; - - /** Mosip router for APIs */ - @Autowired - private MosipRouter router; - - @Autowired - private ObjectMapper mapper; - - @Autowired - private IdrepoDraftService idrepoDraftService; - - /** The registration processor rest client service. */ - @Autowired - private RegistrationProcessorRestClientService registrationProcessorRestClientService; - - /** The demographic dedupe repository. */ - @Autowired - private BasePacketRepository regLostUinDetEntity; - - /** The registration status service. */ - @Autowired - private RegistrationStatusService registrationStatusService; - - /** The utility. */ - @Autowired - private Utilities utility; - - @Autowired - private CbeffUtil cbeffutil; - - @Autowired - private RegistrationExceptionMapperUtil registrationStatusMapperUtil; - - @Autowired - private ABISHandlerUtil aBISHandlerUtil; - - @Autowired - private PriorityBasedPacketManagerService packetManagerService; - - @Autowired - private IdSchemaUtil idSchemaUtil; - - @Autowired - private ObjectMapper objectMapper; - - private TrimExceptionMessage trimExceptionMessage = new TrimExceptionMessage(); - - /* - * (non-Javadoc) - * - * @see - * io.mosip.registration.processor.core.spi.eventbus.EventBusManager#process( - * java.lang.Object) - */ - @SuppressWarnings("unchecked") - @Override - public MessageDTO process(MessageDTO object) { - boolean isTransactionSuccessful = Boolean.FALSE; - object.setMessageBusAddress(MessageBusAddress.UIN_GENERATION_BUS_IN); - object.setInternalError(Boolean.FALSE); - object.setIsValid(Boolean.TRUE); - LogDescription description = new LogDescription(); - String registrationId = object.getRid(); - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - registrationId, "UinGeneratorStage::process()::entry"); - UinGenResponseDto uinResponseDto = null; - - InternalRegistrationStatusDto registrationStatusDto = registrationStatusService.getRegistrationStatus( - registrationId, object.getReg_type(), object.getIteration(), object.getWorkflowInstanceId()); - try { - registrationStatusDto - .setLatestTransactionTypeCode(RegistrationTransactionTypeCode.UIN_GENERATOR.toString()); - registrationStatusDto.setRegistrationStageName(getStageName()); - - if ((RegistrationType.LOST.toString()).equalsIgnoreCase(object.getReg_type())) { - String lostPacketRegId = object.getRid(); - String matchedRegId = regLostUinDetEntity.getLostUinMatchedRegIdByWorkflowId(object.getWorkflowInstanceId()); - - if (matchedRegId != null) { - regProcLogger.info("Match for lostPacketRegId"+lostPacketRegId +"is "+matchedRegId); - lostAndUpdateUin(lostPacketRegId, matchedRegId, registrationStatusDto.getRegistrationType(), object, description); - } - - } else { - - IdResponseDTO idResponseDTO = new IdResponseDTO(); - String schemaVersion = packetManagerService.getFieldByMappingJsonKey(registrationId, MappingJsonConstants.IDSCHEMA_VERSION, registrationStatusDto.getRegistrationType(), ProviderStageName.UIN_GENERATOR); - - Map fieldMap = packetManagerService.getFields(registrationId, - idSchemaUtil.getDefaultFields(Double.valueOf(schemaVersion)), registrationStatusDto.getRegistrationType(), ProviderStageName.UIN_GENERATOR); - String uinField = fieldMap.get(utility.getMappingJsonValue(MappingJsonConstants.UIN, MappingJsonConstants.IDENTITY)); - - JSONObject demographicIdentity = new JSONObject(); - demographicIdentity.put(MappingJsonConstants.IDSCHEMA_VERSION, convertIdschemaToDouble ? Double.valueOf(schemaVersion) : schemaVersion); - - loadDemographicIdentity(fieldMap, demographicIdentity); - - if (StringUtils.isEmpty(uinField) || uinField.equalsIgnoreCase("null") ) { - - idResponseDTO = sendIdRepoWithUin(registrationId, registrationStatusDto.getRegistrationType(), demographicIdentity, - uinField); - - boolean isUinAlreadyPresent = isUinAlreadyPresent(idResponseDTO, registrationId); - - if (isIdResponseNotNull(idResponseDTO) || isUinAlreadyPresent) { - registrationStatusDto.setStatusComment(StatusUtil.UIN_GENERATED_SUCCESS.getMessage()); - registrationStatusDto.setSubStatusCode(StatusUtil.UIN_GENERATED_SUCCESS.getCode()); - isTransactionSuccessful = true; - registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); - description.setMessage(PlatformSuccessMessages.RPR_UIN_GENERATOR_STAGE_SUCCESS.getMessage()); - description.setCode(PlatformSuccessMessages.RPR_UIN_GENERATOR_STAGE_SUCCESS.getCode()); - description.setTransactionStatusCode(RegistrationTransactionStatusCode.SUCCESS.toString()); - - } else { - List errors = idResponseDTO != null ? idResponseDTO.getErrors() : null; - String statusComment = errors != null ? errors.get(0).getMessage() - : UINConstants.NULL_IDREPO_RESPONSE; - int unknownErrorCount=0; - for(ErrorDTO dto:errors) { - if(dto.getErrorCode().equalsIgnoreCase("IDR-IDC-004")||dto.getErrorCode().equalsIgnoreCase("IDR-IDC-001")) { - unknownErrorCount++; - } - } - if(unknownErrorCount>0) { - registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); - registrationStatusDto.setLatestTransactionStatusCode(registrationStatusMapperUtil - .getStatusCode(RegistrationExceptionTypeCode.PACKET_UIN_GENERATION_REPROCESS)); - description.setTransactionStatusCode(registrationStatusMapperUtil - .getStatusCode(RegistrationExceptionTypeCode.PACKET_UIN_GENERATION_REPROCESS)); - } - else { - registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.toString()); - registrationStatusDto.setLatestTransactionStatusCode(registrationStatusMapperUtil - .getStatusCode(RegistrationExceptionTypeCode.PACKET_UIN_GENERATION_FAILED)); - description.setTransactionStatusCode(registrationStatusMapperUtil - .getStatusCode(RegistrationExceptionTypeCode.PACKET_UIN_GENERATION_FAILED)); - } - registrationStatusDto.setStatusComment(trimExceptionMessage - .trimExceptionMessage(StatusUtil.UIN_GENERATION_FAILED.getMessage() + statusComment)); - object.setInternalError(Boolean.TRUE); - isTransactionSuccessful = false; - description.setMessage(PlatformErrorMessages.RPR_UGS_UIN_UPDATE_FAILURE.getMessage()); - description.setCode(PlatformErrorMessages.RPR_UGS_UIN_UPDATE_FAILURE.getCode()); - description.setSubStatusCode(StatusUtil.UIN_GENERATION_FAILED.getCode()); - String idres = idResponseDTO != null ? idResponseDTO.toString() - : UINConstants.NULL_IDREPO_RESPONSE; - - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), - LoggerFileConstant.REGISTRATIONID.toString(), registrationId, - statusComment + " : " + idres); - object.setIsValid(Boolean.FALSE); - } - - } else { - if ((RegistrationType.ACTIVATED.toString()).equalsIgnoreCase(object.getReg_type())) { - isTransactionSuccessful = reActivateUin(idResponseDTO, registrationId, uinField, object, - demographicIdentity, description); - } else if ((RegistrationType.DEACTIVATED.toString()) - .equalsIgnoreCase(object.getReg_type())) { - idResponseDTO = deactivateUin(registrationId, uinField, object, demographicIdentity, - description); - } else if (RegistrationType.UPDATE.toString().equalsIgnoreCase(object.getReg_type()) - || (RegistrationType.RES_UPDATE.toString() - .equalsIgnoreCase(object.getReg_type()))) { - isTransactionSuccessful = uinUpdate(registrationId, registrationStatusDto.getRegistrationType(), uinField, object, demographicIdentity, - description); - } - } - - } - regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - registrationId, description.getMessage()); - registrationStatusDto.setUpdatedBy(UINConstants.USER); - - } catch (io.mosip.kernel.core.util.exception.JsonProcessingException e) { - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - registrationId, - RegistrationStatusCode.FAILED.toString() + e.getMessage() + ExceptionUtils.getStackTrace(e)); - registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.toString()); - registrationStatusDto.setStatusComment( - trimExceptionMessage.trimExceptionMessage(StatusUtil.JSON_PARSING_EXCEPTION.getMessage() + e.getMessage())); - registrationStatusDto.setSubStatusCode(StatusUtil.JSON_PARSING_EXCEPTION.getCode()); - registrationStatusDto.setLatestTransactionStatusCode( - registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.JSON_PROCESSING_EXCEPTION)); - isTransactionSuccessful = false; - description.setMessage(PlatformErrorMessages.RPR_SYS_JSON_PARSING_EXCEPTION.getMessage()); - description.setCode(PlatformErrorMessages.RPR_SYS_JSON_PARSING_EXCEPTION.getCode()); - object.setInternalError(Boolean.TRUE); - object.setRid(registrationStatusDto.getRegistrationId()); - } catch (PacketManagerException e) { - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - registrationId, - RegistrationStatusCode.PROCESSING.toString() + e.getMessage() + ExceptionUtils.getStackTrace(e)); - registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.name()); - registrationStatusDto.setStatusComment( - trimExceptionMessage.trimExceptionMessage(StatusUtil.PACKET_MANAGER_EXCEPTION.getMessage() + e.getMessage())); - registrationStatusDto.setSubStatusCode(StatusUtil.PACKET_MANAGER_EXCEPTION.getCode()); - registrationStatusDto.setLatestTransactionStatusCode( - registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.PACKET_MANAGER_EXCEPTION)); - description.setMessage(PlatformErrorMessages.PACKET_MANAGER_EXCEPTION.getMessage()); - description.setCode(PlatformErrorMessages.PACKET_MANAGER_EXCEPTION.getCode()); - object.setInternalError(Boolean.TRUE); - object.setRid(registrationStatusDto.getRegistrationId()); - } catch (ApisResourceAccessException ex) { - registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.name()); - registrationStatusDto.setStatusComment(trimExceptionMessage - .trimExceptionMessage(StatusUtil.API_RESOUCE_ACCESS_FAILED.getMessage() + ex.getMessage())); - registrationStatusDto.setSubStatusCode(StatusUtil.API_RESOUCE_ACCESS_FAILED.getCode()); - registrationStatusDto.setLatestTransactionStatusCode(registrationStatusMapperUtil - .getStatusCode(RegistrationExceptionTypeCode.APIS_RESOURCE_ACCESS_EXCEPTION)); - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - registrationId, - RegistrationStatusCode.PROCESSING.toString() + ex.getMessage() + ExceptionUtils.getStackTrace(ex)); - object.setInternalError(Boolean.TRUE); - description.setMessage(trimExceptionMessage - .trimExceptionMessage(StatusUtil.API_RESOUCE_ACCESS_FAILED.getMessage() + ex.getMessage())); - description.setCode(PlatformErrorMessages.RPR_UGS_API_RESOURCE_EXCEPTION.getCode()); - - } catch (IOException e) { - registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.name()); - registrationStatusDto.setStatusComment( - trimExceptionMessage.trimExceptionMessage(StatusUtil.IO_EXCEPTION.getMessage() + e.getMessage())); - registrationStatusDto.setSubStatusCode(StatusUtil.IO_EXCEPTION.getCode()); - registrationStatusDto.setLatestTransactionStatusCode( - registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.PACKET_UIN_GENERATION_REPROCESS)); - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - registrationId, - PlatformErrorMessages.RPR_SYS_IO_EXCEPTION.getMessage() + ExceptionUtils.getStackTrace(e)); - object.setInternalError(Boolean.TRUE); - description.setMessage(PlatformErrorMessages.RPR_SYS_IO_EXCEPTION.getMessage()); - description.setCode(PlatformErrorMessages.RPR_SYS_IO_EXCEPTION.getCode()); - } catch (IdrepoDraftException e) { - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - registrationId, - RegistrationStatusCode.PROCESSING.toString() + e.getMessage() + ExceptionUtils.getStackTrace(e)); - registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.name()); - registrationStatusDto.setStatusComment( - trimExceptionMessage.trimExceptionMessage(StatusUtil.IDREPO_DRAFT_EXCEPTION.getMessage() + e.getMessage())); - registrationStatusDto.setSubStatusCode(StatusUtil.IDREPO_DRAFT_EXCEPTION.getCode()); - registrationStatusDto.setLatestTransactionStatusCode( - registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.IDREPO_DRAFT_EXCEPTION)); - description.setMessage(PlatformErrorMessages.IDREPO_DRAFT_EXCEPTION.getMessage()); - description.setCode(PlatformErrorMessages.IDREPO_DRAFT_EXCEPTION.getCode()); - object.setInternalError(Boolean.TRUE); - object.setRid(registrationStatusDto.getRegistrationId()); - } catch (Exception ex) { - registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.name()); - registrationStatusDto.setStatusComment( - trimExceptionMessage.trimExceptionMessage(StatusUtil.UNKNOWN_EXCEPTION_OCCURED.getMessage())); - registrationStatusDto.setSubStatusCode(StatusUtil.UNKNOWN_EXCEPTION_OCCURED.getCode()); - registrationStatusDto.setLatestTransactionStatusCode( - registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.PACKET_UIN_GENERATION_REPROCESS)); - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - registrationId, - RegistrationStatusCode.PROCESSING.toString() + ex.getMessage() + ExceptionUtils.getStackTrace(ex)); - object.setInternalError(Boolean.TRUE); - description.setMessage(PlatformErrorMessages.RPR_BDD_UNKNOWN_EXCEPTION.getMessage()); - description.setCode(PlatformErrorMessages.RPR_BDD_UNKNOWN_EXCEPTION.getCode()); - } finally { - if (description.getStatusComment() != null) - registrationStatusDto.setStatusComment(description.getStatusComment()); - if (description.getStatusCode() != null) - registrationStatusDto.setStatusCode(description.getStatusCode()); - if (description.getSubStatusCode() != null) - registrationStatusDto.setSubStatusCode(description.getSubStatusCode()); - if (description.getTransactionStatusCode() != null) - registrationStatusDto.setLatestTransactionStatusCode(description.getTransactionStatusCode()); - - if (object.getInternalError()) { - updateErrorFlags(registrationStatusDto, object); - } - String moduleId = isTransactionSuccessful - ? PlatformSuccessMessages.RPR_UIN_GENERATOR_STAGE_SUCCESS.getCode() - : description.getCode(); - String moduleName = ModuleName.UIN_GENERATOR.toString(); - registrationStatusService.updateRegistrationStatus(registrationStatusDto, moduleId, moduleName); - String eventId = isTransactionSuccessful ? EventId.RPR_402.toString() : EventId.RPR_405.toString(); - String eventName = eventId.equalsIgnoreCase(EventId.RPR_402.toString()) ? EventName.UPDATE.toString() - : EventName.EXCEPTION.toString(); - String eventType = eventId.equalsIgnoreCase(EventId.RPR_402.toString()) ? EventType.BUSINESS.toString() - : EventType.SYSTEM.toString(); - - auditLogRequestBuilder.createAuditRequestBuilder(description.getMessage(), eventId, eventName, eventType, - moduleId, moduleName, registrationId); - - } - - return object; - } - - private void loadDemographicIdentity(Map fieldMap, JSONObject demographicIdentity) throws IOException, JSONException { - for (Map.Entry e : fieldMap.entrySet()) { - if (e.getValue() != null) { - String value = e.getValue().toString(); - if (value != null) { - Object json = new JSONTokener(value).nextValue(); - if (json instanceof org.json.JSONObject) { - HashMap hashMap = objectMapper.readValue(value, HashMap.class); - demographicIdentity.putIfAbsent(e.getKey(), hashMap); - } - else if (json instanceof JSONArray) { - List jsonList = new ArrayList<>(); - JSONArray jsonArray = new JSONArray(value); - for (int i = 0; i < jsonArray.length(); i++) { - Object obj = jsonArray.get(i); - HashMap hashMap = objectMapper.readValue(obj.toString(), HashMap.class); - jsonList.add(hashMap); - } - demographicIdentity.putIfAbsent(e.getKey(), jsonList); - } else - demographicIdentity.putIfAbsent(e.getKey(), value); - } else - demographicIdentity.putIfAbsent(e.getKey(), value); - } - } - } - - /** - * Send id repo with uin. - * - * @param id - * the reg id - * @param uin - * the uin - * @throws ApisResourceAccessException - * @throws IOException - * @throws JsonMappingException - * @throws JsonParseException - * @throws VidCreationException - * @throws io.mosip.kernel.core.exception.IOException - * @throws Exception - */ - private IdResponseDTO sendIdRepoWithUin(String id, String process, JSONObject demographicIdentity, String uin) - throws Exception { - - List documentInfo = getAllDocumentsByRegId(id, process, demographicIdentity); - RequestDto requestDto = new RequestDto(); - requestDto.setIdentity(demographicIdentity); - requestDto.setDocuments(documentInfo); - requestDto.setRegistrationId(id); - requestDto.setStatus(RegistrationType.ACTIVATED.toString()); - requestDto.setBiometricReferenceId(uin); - - IdResponseDTO result = null; - IdRequestDto idRequestDTO = new IdRequestDto(); - idRequestDTO.setId(idRepoUpdate); - idRequestDTO.setRequest(requestDto); - idRequestDTO.setRequesttime(DateUtils.getUTCCurrentDateTimeString()); - idRequestDTO.setVersion(UINConstants.idRepoApiVersion); - idRequestDTO.setMetadata(null); - - try { - - result = idrepoDraftService.idrepoUpdateDraft(id, null, idRequestDTO); - - } catch (ApisResourceAccessException e) { - regProcLogger.error("Execption occured updating draft for id " + id, e); - if (e.getCause() instanceof HttpClientErrorException) { - HttpClientErrorException httpClientException = (HttpClientErrorException) e.getCause(); - throw new ApisResourceAccessException(httpClientException.getResponseBodyAsString(), - httpClientException); - } else if (e.getCause() instanceof HttpServerErrorException) { - HttpServerErrorException httpServerException = (HttpServerErrorException) e.getCause(); - throw new ApisResourceAccessException(httpServerException.getResponseBodyAsString(), - httpServerException); - } else { - throw e; - } - - } - return result; - - } - - /** - * Gets the all documents by reg id. - * - * @param regId - * the reg id - * @return the all documents by reg id - * @throws IOException - * @throws io.mosip.kernel.core.exception.IOException - * @throws ApisResourceAccessException - * @throws JsonMappingException - * @throws JsonParseException - */ - private List getAllDocumentsByRegId(String regId, String process, JSONObject demographicIdentity) throws Exception { - List applicantDocuments = new ArrayList<>(); - - JSONObject idJSON = demographicIdentity; - JSONObject docJson = utility.getRegistrationProcessorMappingJson(MappingJsonConstants.DOCUMENT); - JSONObject identityJson = utility.getRegistrationProcessorMappingJson(MappingJsonConstants.IDENTITY); - - String applicantBiometricLabel = JsonUtil.getJSONValue(JsonUtil.getJSONObject(identityJson, MappingJsonConstants.INDIVIDUAL_BIOMETRICS), MappingJsonConstants.VALUE); - - HashMap applicantBiometric = (HashMap) idJSON.get(applicantBiometricLabel); - - - for (Object doc : docJson.values()) { - Map docMap = (LinkedHashMap) doc; - String docValue = docMap.values().iterator().next().toString(); - HashMap docInIdentityJson = (HashMap) idJSON.get(docValue); - if (docInIdentityJson != null) - applicantDocuments - .add(getIdDocumnet(regId, docValue, process)); - } - - if (applicantBiometric != null) { - applicantDocuments.add(getBiometrics(regId, applicantBiometricLabel, process, applicantBiometricLabel)); - } - return applicantDocuments; - } - - private Documents getIdDocumnet(String registrationId, String dockey, String process) - throws IOException, ApisResourceAccessException, PacketManagerException, io.mosip.kernel.core.util.exception.JsonProcessingException { - Documents documentsInfoDto = new Documents(); - - Document document = - packetManagerService.getDocument(registrationId, dockey, process, ProviderStageName.UIN_GENERATOR); - if (document != null) { - documentsInfoDto.setValue(CryptoUtil.encodeToURLSafeBase64(document.getDocument())); - documentsInfoDto.setCategory(document.getValue()); - return documentsInfoDto; - } - return null; - } - - private Documents getBiometrics(String registrationId, String person, String process, String idDocLabel) throws Exception { - BiometricRecord biometricRecord = packetManagerService.getBiometrics(registrationId, person, process, ProviderStageName.UIN_GENERATOR); - byte[] xml = cbeffutil.createXML(biometricRecord.getSegments()); - Documents documentsInfoDto = new Documents(); - documentsInfoDto.setValue(CryptoUtil.encodeToURLSafeBase64(xml)); - documentsInfoDto.setCategory(utility.getMappingJsonValue(idDocLabel, MappingJsonConstants.IDENTITY)); - return documentsInfoDto; - - } - - /** - * Update id repo wit uin. - * - * @param regId the reg id - * @param uin the uin - * @param object the object - * @param description - * @return the id response DTO - * @throws ApisResourceAccessException the apis resource access - * exception - * @throws IOException Signals that an I/O exception - * has occurred. - * @throws RegistrationProcessorCheckedException - * @throws io.mosip.kernel.core.exception.IOException - */ - private boolean uinUpdate(String regId, String process, String uin, MessageDTO object, JSONObject demographicIdentity, LogDescription description) - throws Exception { - IdResponseDTO result; - boolean isTransactionSuccessful = Boolean.FALSE; - List documentInfo = getAllDocumentsByRegId(regId, process, demographicIdentity); - result = idRepoRequestBuilder(regId, uin, RegistrationType.ACTIVATED.toString().toUpperCase(), documentInfo, - demographicIdentity); - if (null!=result && isIdResponseNotNull(result)) { - - if (IDREPO_STATUS.equalsIgnoreCase(result.getResponse().getStatus())) { - isTransactionSuccessful = true; - description.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); - description.setStatusComment(StatusUtil.UIN_DATA_UPDATION_SUCCESS.getMessage()); - description.setSubStatusCode(StatusUtil.UIN_DATA_UPDATION_SUCCESS.getCode()); - description.setMessage( - StatusUtil.UIN_DATA_UPDATION_SUCCESS.getMessage() + " for registration Id: " + regId); - description.setTransactionStatusCode(RegistrationTransactionStatusCode.PROCESSED.toString()); - object.setIsValid(Boolean.TRUE); - } - } else { - String statusComment = result != null && result.getErrors() != null ? result.getErrors().get(0).getMessage() - : UINConstants.NULL_IDREPO_RESPONSE; - String message = result != null && result.getErrors() != null - ? result.getErrors().get(0).getMessage() - : UINConstants.NULL_IDREPO_RESPONSE; - description.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); - description.setStatusComment(trimExceptionMessage - .trimExceptionMessage(StatusUtil.UIN_DATA_UPDATION_FAILED.getMessage() + statusComment)); - description.setSubStatusCode(StatusUtil.UIN_DATA_UPDATION_FAILED.getCode()); - description - .setMessage(UINConstants.UIN_FAILURE + regId + "::" + message ); - description.setTransactionStatusCode(RegistrationTransactionStatusCode.PROCESSING.toString()); - object.setIsValid(Boolean.FALSE); - } - return isTransactionSuccessful; - } - - /** - * Id repo request builder. - * - * @param status - * the status - * @param id - * the reg id - * @param demographicIdentity - * the JSONObject - * @param documentInfo - * the document info - * @throws ApisResourceAccessException - * the apis resource access exception - * @throws IOException - */ - private IdResponseDTO idRepoRequestBuilder(String id, String uin, String status, List documentInfo, - JSONObject demographicIdentity) throws ApisResourceAccessException, IdrepoDraftException, IOException { - IdResponseDTO idResponseDto; - RequestDto requestDto = new RequestDto(); - - if (documentInfo != null) - requestDto.setDocuments(documentInfo); - - requestDto.setRegistrationId(id); - requestDto.setStatus(status); - requestDto.setIdentity(demographicIdentity); - - IdRequestDto idRequestDTO = new IdRequestDto(); - idRequestDTO.setId(idRepoUpdate); - idRequestDTO.setMetadata(null); - idRequestDTO.setRequest(requestDto); - idRequestDTO.setRequesttime(DateUtils.getUTCCurrentDateTimeString()); - idRequestDTO.setVersion(UINConstants.idRepoApiVersion); - - try { - idResponseDto = idrepoDraftService.idrepoUpdateDraft(id, uin, idRequestDTO); - } catch (ApisResourceAccessException e) { - regProcLogger.error("Execption occured updating draft for id " + id, e); - if (e.getCause() instanceof HttpClientErrorException) { - regProcLogger.error("Exception occured updating draft for id " + id, e); - HttpClientErrorException httpClientException = (HttpClientErrorException) e.getCause(); - throw new ApisResourceAccessException(httpClientException.getResponseBodyAsString(), - httpClientException); - } else if (e.getCause() instanceof HttpServerErrorException) { - HttpServerErrorException httpServerException = (HttpServerErrorException) e.getCause(); - throw new ApisResourceAccessException(httpServerException.getResponseBodyAsString(), - httpServerException); - } else { - throw e; - } - - } - return idResponseDto; - } - - /** - * Re activate uin. - * - * @param id - * the reg id - * @param uin - * the uin - * @param object - * the object - * @param description - * @return the id response DTO - * @throws ApisResourceAccessException - * the apis resource access exception - * @throws IOException - */ - private boolean reActivateUin(IdResponseDTO idResponseDTO, String id, String uin, MessageDTO object, - JSONObject demographicIdentity, LogDescription description) - throws ApisResourceAccessException, IOException, IdrepoDraftException { - IdResponseDTO result = getIdRepoDataByUIN(uin, id, description); - List pathsegments = new ArrayList<>(); - RequestDto requestDto = new RequestDto(); - boolean isTransactionSuccessful = Boolean.FALSE; - - if (isIdResponseNotNull(result)) { - - if ((RegistrationType.ACTIVATED.toString()).equalsIgnoreCase(result.getResponse().getStatus())) { - - description.setStatusCode(RegistrationStatusCode.FAILED.toString()); - description.setStatusComment(StatusUtil.UIN_ALREADY_ACTIVATED.getMessage()); - description.setSubStatusCode(StatusUtil.UIN_ALREADY_ACTIVATED.getCode()); - description.setMessage(PlatformErrorMessages.UIN_ALREADY_ACTIVATED.getMessage()); - description.setCode(PlatformErrorMessages.UIN_ALREADY_ACTIVATED.getCode()); - description.setTransactionStatusCode(RegistrationTransactionStatusCode.FAILED.toString()); - object.setIsValid(Boolean.FALSE); - return isTransactionSuccessful; - - } else { - - requestDto.setRegistrationId(id); - requestDto.setStatus(RegistrationType.ACTIVATED.toString()); - requestDto.setBiometricReferenceId(uin); - requestDto.setIdentity(demographicIdentity); - - IdRequestDto idRequestDTO = new IdRequestDto(); - idRequestDTO.setId(idRepoUpdate); - idRequestDTO.setRequest(requestDto); - idRequestDTO.setMetadata(null); - idRequestDTO.setRequesttime(DateUtils.getUTCCurrentDateTimeString()); - idRequestDTO.setVersion(UINConstants.idRepoApiVersion); - - result = idrepoDraftService.idrepoUpdateDraft(id, uin, idRequestDTO); - - if (isIdResponseNotNull(result)) { - - if ((RegistrationType.ACTIVATED.toString()).equalsIgnoreCase(result.getResponse().getStatus())) { - isTransactionSuccessful = true; - description.setStatusCode(RegistrationStatusCode.PROCESSED.toString()); - description.setStatusComment(StatusUtil.UIN_ACTIVATED_SUCCESS.getMessage()); - description.setSubStatusCode(StatusUtil.UIN_ACTIVATED_SUCCESS.getCode()); - description.setMessage(StatusUtil.UIN_ACTIVATED_SUCCESS.getMessage() + id); - description.setMessage(PlatformSuccessMessages.RPR_UIN_ACTIVATED_SUCCESS.getMessage()); - description.setCode(PlatformSuccessMessages.RPR_UIN_ACTIVATED_SUCCESS.getCode()); - description.setTransactionStatusCode(RegistrationTransactionStatusCode.PROCESSED.toString()); - object.setIsValid(Boolean.TRUE); - } else { - description.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); - description.setStatusComment(StatusUtil.UIN_ACTIVATED_FAILED.getMessage()); - description.setSubStatusCode(StatusUtil.UIN_ACTIVATED_FAILED.getCode()); - description.setMessage(StatusUtil.UIN_ACTIVATED_FAILED.getMessage() + id); - description.setMessage(PlatformErrorMessages.UIN_ACTIVATED_FAILED.getMessage()); - description.setCode(PlatformErrorMessages.UIN_ACTIVATED_FAILED.getCode()); - description.setTransactionStatusCode(RegistrationTransactionStatusCode.REPROCESS.toString()); - object.setIsValid(Boolean.FALSE); - } - } else { - String statusComment = result != null && result.getErrors() != null - ? result.getErrors().get(0).getMessage() - : UINConstants.NULL_IDREPO_RESPONSE; - description.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); - description.setStatusComment(trimExceptionMessage - .trimExceptionMessage(StatusUtil.UIN_REACTIVATION_FAILED.getMessage() + statusComment)); - description.setSubStatusCode(StatusUtil.UIN_REACTIVATION_FAILED.getCode()); - description.setMessage( - UINConstants.UIN_FAILURE + id + "::" + (result != null && result.getErrors() != null - ? result.getErrors().get(0).getMessage() - : UINConstants.NULL_IDREPO_RESPONSE)); - description.setMessage(PlatformErrorMessages.UIN_REACTIVATION_FAILED.getMessage()); - description.setCode(PlatformErrorMessages.UIN_REACTIVATION_FAILED.getCode()); - description.setTransactionStatusCode(RegistrationTransactionStatusCode.REPROCESS.toString()); - object.setIsValid(Boolean.FALSE); - } - - } - - }else { - String statusComment = result != null && result.getErrors() != null - ? result.getErrors().get(0).getMessage() - : UINConstants.NULL_IDREPO_RESPONSE; - description.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); - description.setStatusComment(trimExceptionMessage - .trimExceptionMessage(StatusUtil.UIN_REACTIVATION_FAILED.getMessage() + statusComment)); - description.setSubStatusCode(StatusUtil.UIN_REACTIVATION_FAILED.getCode()); - description.setMessage( - UINConstants.UIN_FAILURE + id + "::" + (result != null && result.getErrors() != null - ? result.getErrors().get(0).getMessage() - : UINConstants.NULL_IDREPO_RESPONSE)); - description.setMessage(PlatformErrorMessages.UIN_REACTIVATION_FAILED.getMessage()); - description.setCode(PlatformErrorMessages.UIN_REACTIVATION_FAILED.getCode()); - description.setTransactionStatusCode(RegistrationTransactionStatusCode.REPROCESS.toString()); - object.setIsValid(Boolean.FALSE); - } - - return isTransactionSuccessful; - } - - private boolean isIdResponseNotNull(IdResponseDTO result) { - return result != null && result.getResponse() != null; - } - - private boolean isUinAlreadyPresent(IdResponseDTO result, String rid) { - if (result != null && result.getErrors() != null && result.getErrors().size() > 0 - && result.getErrors().get(0).getErrorCode().equalsIgnoreCase(RECORD_ALREADY_EXISTS_ERROR)) { - ErrorDTO errorDTO = result.getErrors().get(0); - regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), - LoggerFileConstant.REGISTRATIONID.toString() + rid, - "Record is already present in IDREPO. Error message received : " + errorDTO.getMessage(), - "The stage will ignore this error and try to generate vid for the existing UIN now. " + - "This is to make sure if the packet processing fails while generating VID then re-processor can process the packet again"); - return true; - } - return false; - } - - /** - * Deactivate uin. - * - * @param id - * the reg id - * @param uin - * the uin - * @param object - * the object - * @param description - * @return the id response DTO - * @throws ApisResourceAccessException - * @throws IOException - */ - private IdResponseDTO deactivateUin(String id, String uin, MessageDTO object, JSONObject demographicIdentity, - LogDescription description) throws ApisResourceAccessException, IOException, IdrepoDraftException { - IdResponseDTO idResponseDto; - RequestDto requestDto = new RequestDto(); - String statusComment = ""; - - idResponseDto = getIdRepoDataByUIN(uin, id, description); - - if (idResponseDto.getResponse() != null - && idResponseDto.getResponse().getStatus().equalsIgnoreCase(RegistrationType.DEACTIVATED.toString())) { - description.setStatusCode(RegistrationStatusCode.FAILED.toString()); - description.setStatusComment(StatusUtil.UIN_ALREADY_DEACTIVATED.getMessage()); - description.setSubStatusCode(StatusUtil.UIN_ALREADY_DEACTIVATED.getCode()); - description.setMessage(StatusUtil.UIN_ALREADY_DEACTIVATED.getMessage() + id); - description.setMessage(PlatformErrorMessages.UIN_ALREADY_DEACTIVATED.getMessage()); - description.setCode(PlatformErrorMessages.UIN_ALREADY_DEACTIVATED.getCode()); - description.setTransactionStatusCode(RegistrationTransactionStatusCode.FAILED.toString()); - object.setIsValid(Boolean.FALSE); - return idResponseDto; - - } else { - requestDto.setRegistrationId(id); - requestDto.setStatus(RegistrationType.DEACTIVATED.toString()); - requestDto.setIdentity(demographicIdentity); - requestDto.setBiometricReferenceId(uin); - - IdRequestDto idRequestDTO = new IdRequestDto(); - idRequestDTO.setId(idRepoUpdate); - idRequestDTO.setMetadata(null); - idRequestDTO.setRequest(requestDto); - idRequestDTO.setRequesttime(DateUtils.getUTCCurrentDateTimeString()); - idRequestDTO.setVersion(UINConstants.idRepoApiVersion); - - idResponseDto = idrepoDraftService.idrepoUpdateDraft(id, uin, idRequestDTO); - - if (isIdResponseNotNull(idResponseDto)) { - if (idResponseDto.getResponse().getStatus().equalsIgnoreCase(RegistrationType.DEACTIVATED.toString())) { - description.setStatusCode(RegistrationStatusCode.PROCESSED.toString()); - description.setStatusComment(StatusUtil.UIN_DEACTIVATION_SUCCESS.getMessage()); - description.setSubStatusCode(StatusUtil.UIN_DEACTIVATION_SUCCESS.getCode()); - description.setMessage(StatusUtil.UIN_DEACTIVATION_SUCCESS.getMessage() + id); - description.setMessage(PlatformSuccessMessages.RPR_UIN_DEACTIVATION_SUCCESS.getMessage()); - description.setCode(PlatformSuccessMessages.RPR_UIN_DEACTIVATION_SUCCESS.getCode()); - description.setTransactionStatusCode(RegistrationTransactionStatusCode.PROCESSED.toString()); - object.setIsValid(Boolean.TRUE); - statusComment = idResponseDto.getResponse().getStatus().toString(); - - } - } else { - - statusComment = idResponseDto != null && idResponseDto.getErrors() != null - ? idResponseDto.getErrors().get(0).getMessage() - : UINConstants.NULL_IDREPO_RESPONSE; - description.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); - description.setStatusComment(trimExceptionMessage - .trimExceptionMessage(StatusUtil.UIN_DEACTIVATION_FAILED.getMessage() + statusComment)); - description.setSubStatusCode(StatusUtil.UIN_DEACTIVATION_FAILED.getCode()); - description.setMessage(PlatformErrorMessages.UIN_DEACTIVATION_FAILED.getMessage()); - description.setCode(PlatformErrorMessages.UIN_DEACTIVATION_FAILED.getCode()); - description.setTransactionStatusCode(RegistrationTransactionStatusCode.REPROCESS.toString()); - object.setIsValid(Boolean.FALSE); - } - - } - regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), - LoggerFileConstant.REGISTRATIONID.toString() + id, "Updated Response from IdRepo API", - "is : " + statusComment); - - return idResponseDto; - } - - /** - * Gets the id repo data by UIN. - * - * @param uin - * the uin - * @param description - * @return the id repo data by UIN - * @throws ApisResourceAccessException - * the apis resource access exception - * @throws IOException - */ - private IdResponseDTO getIdRepoDataByUIN(String uin, String regId, LogDescription description) - throws ApisResourceAccessException { - IdResponseDTO response; - - List pathsegments = new ArrayList<>(); - pathsegments.add(uin); - try { - - response = (IdResponseDTO) registrationProcessorRestClientService.getApi(ApiName.IDREPOGETIDBYUIN, - pathsegments, "", "", IdResponseDTO.class); - - } catch (ApisResourceAccessException e) { - if (e.getCause() instanceof HttpClientErrorException) { - HttpClientErrorException httpClientException = (HttpClientErrorException) e.getCause(); - description.setMessage(PlatformErrorMessages.UIN_GENERATION_FAILED.getMessage()); - description.setCode(PlatformErrorMessages.UIN_GENERATION_FAILED.getCode()); - throw new ApisResourceAccessException(httpClientException.getResponseBodyAsString(), - httpClientException); - } else if (e.getCause() instanceof HttpServerErrorException) { - HttpServerErrorException httpServerException = (HttpServerErrorException) e.getCause(); - description.setMessage(PlatformErrorMessages.UIN_GENERATION_FAILED.getMessage()); - description.setCode(PlatformErrorMessages.UIN_GENERATION_FAILED.getCode()); - - throw new ApisResourceAccessException(httpServerException.getResponseBodyAsString(), - httpServerException); - } else { - description.setMessage(PlatformErrorMessages.UIN_GENERATION_FAILED.getMessage()); - description.setCode(PlatformErrorMessages.UIN_GENERATION_FAILED.getCode()); - throw e; - } - } - return response; - } - - /** - * Deploy verticle. - */ - public void deployVerticle() { - - mosipEventBus = this.getEventBus(this, clusterManagerUrl, workerPoolSize); - this.consumeAndSend(mosipEventBus, MessageBusAddress.UIN_GENERATION_BUS_IN, - MessageBusAddress.UIN_GENERATION_BUS_OUT, messageExpiryTimeLimit); - } - - @Override - public void start() { - router.setRoute(this.postUrl(getVertx(), MessageBusAddress.UIN_GENERATION_BUS_IN, - MessageBusAddress.UIN_GENERATION_BUS_OUT)); - this.createServer(router.getRouter(), getPort()); - - } - - @Override - protected String getPropertyPrefix() { - return STAGE_PROPERTY_PREFIX; - } - - /** - * Link reg id wrt uin. - * - * @param lostPacketRegId - * the lost packet reg id - * @param matchedRegId - * the matched reg id - * @param object - * the object - * @param description - * @return the id response DTO - * @throws ApisResourceAccessException - * the apis resource access exception - * @throws IOException - * Signals that an I/O exception has occurred. - */ - @SuppressWarnings("unchecked") - private IdResponseDTO lostAndUpdateUin(String lostPacketRegId, String matchedRegId, String process, MessageDTO object, - LogDescription description) throws ApisResourceAccessException, IOException, io.mosip.kernel.core.util.exception.JsonProcessingException, PacketManagerException, IdrepoDraftException { - - IdResponseDTO idResponse = null; - String uin = idRepoService.getUinByRid(matchedRegId, utility.getGetRegProcessorDemographicIdentity()); - - - RequestDto requestDto = new RequestDto(); - String statusComment = ""; - - if (uin != null) { - - JSONObject regProcessorIdentityJson = utility.getRegistrationProcessorMappingJson(MappingJsonConstants.IDENTITY); - String idschemaversion = JsonUtil.getJSONValue(JsonUtil.getJSONObject(regProcessorIdentityJson, MappingJsonConstants.IDSCHEMA_VERSION), MappingJsonConstants.VALUE); - - JSONObject identityObject = new JSONObject(); - identityObject.put(UINConstants.UIN, uin); - String schemaVersion = packetManagerService.getFieldByMappingJsonKey(lostPacketRegId, MappingJsonConstants.IDSCHEMA_VERSION, process, ProviderStageName.UIN_GENERATOR); - identityObject.put(idschemaversion, convertIdschemaToDouble ? Double.valueOf(schemaVersion) : schemaVersion); - regProcLogger.info("Fields to be updated "+updateInfo); - if (null != updateInfo && !updateInfo.isEmpty()) { - String[] upd = updateInfo.split(","); - for (String infoField : upd) { - String fldValue = packetManagerService.getField(lostPacketRegId, infoField, process, - ProviderStageName.UIN_GENERATOR); - if (null != fldValue) - identityObject.put(infoField, fldValue); - } - } - requestDto.setRegistrationId(lostPacketRegId); - requestDto.setIdentity(identityObject); - - IdRequestDto idRequestDTO = new IdRequestDto(); - idRequestDTO.setId(idRepoUpdate); - idRequestDTO.setRequest(requestDto); - idRequestDTO.setMetadata(null); - idRequestDTO.setRequesttime(DateUtils.getUTCCurrentDateTimeString()); - idRequestDTO.setVersion(UINConstants.idRepoApiVersion); - - idResponse = idrepoDraftService.idrepoUpdateDraft(lostPacketRegId, uin, idRequestDTO); - - if (isIdResponseNotNull(idResponse)) { - description.setStatusCode(RegistrationStatusCode.PROCESSED.toString()); - description.setStatusComment(StatusUtil.LINK_RID_FOR_LOST_PACKET_SUCCESS.getMessage()); - description.setSubStatusCode(StatusUtil.LINK_RID_FOR_LOST_PACKET_SUCCESS.getCode()); - description.setMessage(UinStatusMessage.PACKET_LOST_UIN_UPDATION_SUCCESS_MSG + lostPacketRegId); - description.setTransactionStatusCode(RegistrationTransactionStatusCode.PROCESSED.toString()); - object.setIsValid(Boolean.TRUE); - - regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), - LoggerFileConstant.REGISTRATIONID.toString() + lostPacketRegId, - " UIN LINKED WITH " + matchedRegId, "is : " + description); - } else { - - statusComment = idResponse != null && idResponse.getErrors() != null - && idResponse.getErrors().get(0) != null ? idResponse.getErrors().get(0).getMessage() - : UinStatusMessage.PACKET_LOST_UIN_UPDATION_FAILURE_MSG + " " - + UINConstants.NULL_IDREPO_RESPONSE + "for lostPacketRegId " + lostPacketRegId; - description.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); - description.setStatusComment(StatusUtil.LINK_RID_FOR_LOST_PACKET_SUCCESS.getMessage() + statusComment); - description.setSubStatusCode(StatusUtil.LINK_RID_FOR_LOST_PACKET_SUCCESS.getCode()); - description.setTransactionStatusCode(registrationStatusMapperUtil - .getStatusCode(RegistrationExceptionTypeCode.PACKET_UIN_GENERATION_ID_REPO_ERROR)); - if (idResponse != null - && idResponse.getErrors() != null) - description.setMessage(idResponse.getErrors().get(0).getMessage()); - else - description.setMessage(UINConstants.NULL_IDREPO_RESPONSE); - object.setIsValid(Boolean.FALSE); - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), - LoggerFileConstant.REGISTRATIONID.toString() + lostPacketRegId, - " UIN NOT LINKED WITH " + matchedRegId, "is : " + statusComment); - } - - } else { - statusComment = UinStatusMessage.PACKET_LOST_UIN_UPDATION_FAILURE_MSG + " " - + UINConstants.NULL_IDREPO_RESPONSE + " UIN not available for matchedRegId " + matchedRegId; - description.setStatusComment(StatusUtil.LINK_RID_FOR_LOST_PACKET_FAILED.getMessage()); - description.setSubStatusCode(StatusUtil.LINK_RID_FOR_LOST_PACKET_FAILED.getCode()); - description.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); - description.setTransactionStatusCode(registrationStatusMapperUtil - .getStatusCode(RegistrationExceptionTypeCode.PACKET_UIN_GENERATION_REPROCESS)); - description.setMessage(UinStatusMessage.PACKET_LOST_UIN_UPDATION_FAILURE_MSG + " " - + UINConstants.NULL_IDREPO_RESPONSE + " UIN not available for matchedRegId " + matchedRegId); - - object.setIsValid(Boolean.FALSE); - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), - LoggerFileConstant.REGISTRATIONID.toString() + lostPacketRegId, - " UIN NOT LINKED WITH " + matchedRegId, "is : " + statusComment); - } - - return idResponse; - } - - private void updateErrorFlags(InternalRegistrationStatusDto registrationStatusDto, MessageDTO object) { - object.setInternalError(true); - if (registrationStatusDto.getLatestTransactionStatusCode() - .equalsIgnoreCase(RegistrationTransactionStatusCode.REPROCESS.toString())) { - object.setIsValid(true); - } else { - object.setIsValid(false); - } - } -} +package io.mosip.registration.processor.stages.uingenerator.stage; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import org.apache.commons.lang3.exception.ExceptionUtils; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONTokener; +import org.json.simple.JSONObject; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.cloud.context.config.annotation.RefreshScope; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Service; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.web.client.HttpServerErrorException; + +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +import io.mosip.kernel.biometrics.entities.BiometricRecord; +import io.mosip.kernel.biometrics.spi.CbeffUtil; +import io.mosip.kernel.core.logger.spi.Logger; +import io.mosip.kernel.core.util.CryptoUtil; +import io.mosip.kernel.core.util.DateUtils; +import io.mosip.kernel.core.util.StringUtils; +import io.mosip.registration.processor.core.abstractverticle.MessageBusAddress; +import io.mosip.registration.processor.core.abstractverticle.MessageDTO; +import io.mosip.registration.processor.core.abstractverticle.MosipEventBus; +import io.mosip.registration.processor.core.abstractverticle.MosipRouter; +import io.mosip.registration.processor.core.abstractverticle.MosipVerticleAPIManager; +import io.mosip.registration.processor.core.code.ApiName; +import io.mosip.registration.processor.core.code.ModuleName; +import io.mosip.registration.processor.core.code.RegistrationExceptionTypeCode; +import io.mosip.registration.processor.core.code.RegistrationTransactionStatusCode; +import io.mosip.registration.processor.core.code.RegistrationTransactionTypeCode; +import io.mosip.registration.processor.core.common.rest.dto.ErrorDTO; +import io.mosip.registration.processor.core.constant.EventId; +import io.mosip.registration.processor.core.constant.EventName; +import io.mosip.registration.processor.core.constant.EventType; +import io.mosip.registration.processor.core.constant.LoggerFileConstant; +import io.mosip.registration.processor.core.constant.MappingJsonConstants; +import io.mosip.registration.processor.core.constant.ProviderStageName; +import io.mosip.registration.processor.core.exception.ApisResourceAccessException; +import io.mosip.registration.processor.core.exception.PacketManagerException; +import io.mosip.registration.processor.core.exception.RegistrationProcessorCheckedException; +import io.mosip.registration.processor.core.exception.util.PlatformErrorMessages; +import io.mosip.registration.processor.core.exception.util.PlatformSuccessMessages; +import io.mosip.registration.processor.core.idrepo.dto.Documents; +import io.mosip.registration.processor.core.logger.LogDescription; +import io.mosip.registration.processor.core.logger.RegProcessorLogger; +import io.mosip.registration.processor.core.spi.restclient.RegistrationProcessorRestClientService; +import io.mosip.registration.processor.core.status.util.StatusUtil; +import io.mosip.registration.processor.core.status.util.TrimExceptionMessage; +import io.mosip.registration.processor.core.util.JsonUtil; +import io.mosip.registration.processor.core.util.RegistrationExceptionMapperUtil; +import io.mosip.registration.processor.packet.manager.dto.IdRequestDto; +import io.mosip.registration.processor.packet.manager.dto.IdResponseDTO; +import io.mosip.registration.processor.packet.manager.dto.RequestDto; +import io.mosip.registration.processor.packet.manager.exception.IdrepoDraftException; +import io.mosip.registration.processor.packet.manager.exception.IdrepoDraftReprocessableException; +import io.mosip.registration.processor.packet.manager.idreposervice.IdRepoService; +import io.mosip.registration.processor.packet.manager.idreposervice.IdrepoDraftService; +import io.mosip.registration.processor.packet.storage.dto.Document; +import io.mosip.registration.processor.packet.storage.entity.RegLostUinDetEntity; +import io.mosip.registration.processor.packet.storage.repository.BasePacketRepository; +import io.mosip.registration.processor.packet.storage.utils.ABISHandlerUtil; +import io.mosip.registration.processor.packet.storage.utils.IdSchemaUtil; +import io.mosip.registration.processor.packet.storage.utils.PriorityBasedPacketManagerService; +import io.mosip.registration.processor.packet.storage.utils.Utilities; +import io.mosip.registration.processor.rest.client.audit.builder.AuditLogRequestBuilder; +import io.mosip.registration.processor.stages.uingenerator.constants.UINConstants; +import io.mosip.registration.processor.stages.uingenerator.dto.UinGenResponseDto; +import io.mosip.registration.processor.stages.uingenerator.exception.VidCreationException; +import io.mosip.registration.processor.stages.uingenerator.util.UinStatusMessage; +import io.mosip.registration.processor.status.code.RegistrationStatusCode; +import io.mosip.registration.processor.status.code.RegistrationType; +import io.mosip.registration.processor.status.dto.InternalRegistrationStatusDto; +import io.mosip.registration.processor.status.dto.RegistrationStatusDto; +import io.mosip.registration.processor.status.service.RegistrationStatusService; + +/** + * The Class UinGeneratorStage. + * + * @author Ranjitha Siddegowda + * @author Rishabh Keshari + */ +@RefreshScope +@Service +@Configuration +@ComponentScan(basePackages = { "${mosip.auth.adapter.impl.basepackage}", + "io.mosip.registration.processor.core.config", + "io.mosip.registration.processor.stages.uingenerator.config", + "io.mosip.registration.processor.status.config", "io.mosip.registration.processor.rest.client.config", + "io.mosip.registration.processor.packet.storage.config", + "io.mosip.registration.processor.stages.config", + "io.mosip.kernel.packetmanager.config", + "io.mosip.registration.processor.packet.manager.config", + "io.mosip.registration.processor.core.kernel.beans"}) +public class UinGeneratorStage extends MosipVerticleAPIManager { + + /** The reg proc logger. */ + private static Logger regProcLogger = RegProcessorLogger.getLogger(UinGeneratorStage.class); + private static final String RECORD_ALREADY_EXISTS_ERROR = "IDR-IDC-012"; + private static final String STAGE_PROPERTY_PREFIX = "mosip.regproc.uin.generator."; + private static final String UIN = "UIN"; + private static final String IDREPO_STATUS = "DRAFTED"; + + @Autowired + private Environment env; + + @Autowired + private IdRepoService idRepoService; + + /** The mosip event bus. */ + MosipEventBus mosipEventBus = null; + + @Value("${registration.processor.id.repo.vidType}") + private String vidType; + + @Value("${mosip.commons.packet.manager.schema.validator.convertIdSchemaToDouble:true}") + private boolean convertIdschemaToDouble; + + /** The cluster manager url. */ + @Value("${vertx.cluster.configuration}") + private String clusterManagerUrl; + + /** The id repo create. */ + @Value("${registration.processor.id.repo.create}") + private String idRepoCreate; + + /** The id repo update. */ + @Value("${registration.processor.id.repo.update}") + private String idRepoUpdate; + + /** worker pool size. */ + @Value("${worker.pool.size}") + private Integer workerPoolSize; + + /** After this time intervel, message should be considered as expired (In seconds). */ + @Value("${mosip.regproc.uin.generator.message.expiry-time-limit}") + private Long messageExpiryTimeLimit; + + @Value("${uingenerator.lost.packet.allowed.update.fields:null}") + private String updateInfo; + + /** The core audit request builder. */ + @Autowired + private AuditLogRequestBuilder auditLogRequestBuilder; + + /** Mosip router for APIs */ + @Autowired + private MosipRouter router; + + @Autowired + private ObjectMapper mapper; + + @Autowired + private IdrepoDraftService idrepoDraftService; + + /** The registration processor rest client service. */ + @Autowired + private RegistrationProcessorRestClientService registrationProcessorRestClientService; + + /** The demographic dedupe repository. */ + @Autowired + private BasePacketRepository regLostUinDetEntity; + + /** The registration status service. */ + @Autowired + private RegistrationStatusService registrationStatusService; + + /** The utility. */ + @Autowired + private Utilities utility; + + @Autowired + private CbeffUtil cbeffutil; + + @Autowired + private RegistrationExceptionMapperUtil registrationStatusMapperUtil; + + @Autowired + private ABISHandlerUtil aBISHandlerUtil; + + @Autowired + private PriorityBasedPacketManagerService packetManagerService; + + @Autowired + private IdSchemaUtil idSchemaUtil; + + @Autowired + private ObjectMapper objectMapper; + + private TrimExceptionMessage trimExceptionMessage = new TrimExceptionMessage(); + + /* + * (non-Javadoc) + * + * @see + * io.mosip.registration.processor.core.spi.eventbus.EventBusManager#process( + * java.lang.Object) + */ + @SuppressWarnings("unchecked") + @Override + public MessageDTO process(MessageDTO object) { + boolean isTransactionSuccessful = Boolean.FALSE; + object.setMessageBusAddress(MessageBusAddress.UIN_GENERATION_BUS_IN); + object.setInternalError(Boolean.FALSE); + object.setIsValid(Boolean.TRUE); + LogDescription description = new LogDescription(); + String registrationId = object.getRid(); + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + registrationId, "UinGeneratorStage::process()::entry"); + UinGenResponseDto uinResponseDto = null; + + InternalRegistrationStatusDto registrationStatusDto = registrationStatusService.getRegistrationStatus( + registrationId, object.getReg_type(), object.getIteration(), object.getWorkflowInstanceId()); + try { + registrationStatusDto + .setLatestTransactionTypeCode(RegistrationTransactionTypeCode.UIN_GENERATOR.toString()); + registrationStatusDto.setRegistrationStageName(getStageName()); + + if ((RegistrationType.LOST.toString()).equalsIgnoreCase(object.getReg_type())) { + String lostPacketRegId = object.getRid(); + String matchedRegId = regLostUinDetEntity.getLostUinMatchedRegIdByWorkflowId(object.getWorkflowInstanceId()); + + if (matchedRegId != null) { + regProcLogger.info("Match for lostPacketRegId"+lostPacketRegId +"is "+matchedRegId); + lostAndUpdateUin(lostPacketRegId, matchedRegId, registrationStatusDto.getRegistrationType(), object, description); + } + + } else { + + IdResponseDTO idResponseDTO = new IdResponseDTO(); + String schemaVersion = packetManagerService.getFieldByMappingJsonKey(registrationId, MappingJsonConstants.IDSCHEMA_VERSION, registrationStatusDto.getRegistrationType(), ProviderStageName.UIN_GENERATOR); + + Map fieldMap = packetManagerService.getFields(registrationId, + idSchemaUtil.getDefaultFields(Double.valueOf(schemaVersion)), registrationStatusDto.getRegistrationType(), ProviderStageName.UIN_GENERATOR); + String uinField = fieldMap.get(utility.getMappingJsonValue(MappingJsonConstants.UIN, MappingJsonConstants.IDENTITY)); + + JSONObject demographicIdentity = new JSONObject(); + demographicIdentity.put(MappingJsonConstants.IDSCHEMA_VERSION, convertIdschemaToDouble ? Double.valueOf(schemaVersion) : schemaVersion); + + loadDemographicIdentity(fieldMap, demographicIdentity); + + if (StringUtils.isEmpty(uinField) || uinField.equalsIgnoreCase("null") ) { + + idResponseDTO = sendIdRepoWithUin(registrationId, registrationStatusDto.getRegistrationType(), demographicIdentity, + uinField); + + boolean isUinAlreadyPresent = isUinAlreadyPresent(idResponseDTO, registrationId); + + if (isIdResponseNotNull(idResponseDTO) || isUinAlreadyPresent) { + registrationStatusDto.setStatusComment(StatusUtil.UIN_GENERATED_SUCCESS.getMessage()); + registrationStatusDto.setSubStatusCode(StatusUtil.UIN_GENERATED_SUCCESS.getCode()); + isTransactionSuccessful = true; + registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); + description.setMessage(PlatformSuccessMessages.RPR_UIN_GENERATOR_STAGE_SUCCESS.getMessage()); + description.setCode(PlatformSuccessMessages.RPR_UIN_GENERATOR_STAGE_SUCCESS.getCode()); + description.setTransactionStatusCode(RegistrationTransactionStatusCode.SUCCESS.toString()); + + } else { + List errors = idResponseDTO != null ? idResponseDTO.getErrors() : null; + String statusComment = errors != null ? errors.get(0).getMessage() + : UINConstants.NULL_IDREPO_RESPONSE; + int unknownErrorCount=0; + for(ErrorDTO dto:errors) { + if(dto.getErrorCode().equalsIgnoreCase("IDR-IDC-004")||dto.getErrorCode().equalsIgnoreCase("IDR-IDC-001")) { + unknownErrorCount++; + } + } + if(unknownErrorCount>0) { + registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); + registrationStatusDto.setLatestTransactionStatusCode(registrationStatusMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.PACKET_UIN_GENERATION_REPROCESS)); + description.setTransactionStatusCode(registrationStatusMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.PACKET_UIN_GENERATION_REPROCESS)); + } + else { + registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.toString()); + registrationStatusDto.setLatestTransactionStatusCode(registrationStatusMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.PACKET_UIN_GENERATION_FAILED)); + description.setTransactionStatusCode(registrationStatusMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.PACKET_UIN_GENERATION_FAILED)); + } + registrationStatusDto.setStatusComment(trimExceptionMessage + .trimExceptionMessage(StatusUtil.UIN_GENERATION_FAILED.getMessage() + statusComment)); + object.setInternalError(Boolean.TRUE); + isTransactionSuccessful = false; + description.setMessage(PlatformErrorMessages.RPR_UGS_UIN_UPDATE_FAILURE.getMessage()); + description.setCode(PlatformErrorMessages.RPR_UGS_UIN_UPDATE_FAILURE.getCode()); + description.setSubStatusCode(StatusUtil.UIN_GENERATION_FAILED.getCode()); + String idres = idResponseDTO != null ? idResponseDTO.toString() + : UINConstants.NULL_IDREPO_RESPONSE; + + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString(), registrationId, + statusComment + " : " + idres); + object.setIsValid(Boolean.FALSE); + } + + } else { + if ((RegistrationType.ACTIVATED.toString()).equalsIgnoreCase(object.getReg_type())) { + isTransactionSuccessful = reActivateUin(idResponseDTO, registrationId, uinField, object, + demographicIdentity, description); + } else if ((RegistrationType.DEACTIVATED.toString()) + .equalsIgnoreCase(object.getReg_type())) { + idResponseDTO = deactivateUin(registrationId, uinField, object, demographicIdentity, + description); + } else if (RegistrationType.UPDATE.toString().equalsIgnoreCase(object.getReg_type()) + || (RegistrationType.RES_UPDATE.toString() + .equalsIgnoreCase(object.getReg_type()))) { + isTransactionSuccessful = uinUpdate(registrationId, registrationStatusDto.getRegistrationType(), uinField, object, demographicIdentity, + description); + } + } + + } + regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + registrationId, description.getMessage()); + registrationStatusDto.setUpdatedBy(UINConstants.USER); + + } catch (io.mosip.kernel.core.util.exception.JsonProcessingException e) { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + registrationId, + RegistrationStatusCode.FAILED.toString() + e.getMessage() + ExceptionUtils.getStackTrace(e)); + registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.toString()); + registrationStatusDto.setStatusComment( + trimExceptionMessage.trimExceptionMessage(StatusUtil.JSON_PARSING_EXCEPTION.getMessage() + e.getMessage())); + registrationStatusDto.setSubStatusCode(StatusUtil.JSON_PARSING_EXCEPTION.getCode()); + registrationStatusDto.setLatestTransactionStatusCode( + registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.JSON_PROCESSING_EXCEPTION)); + isTransactionSuccessful = false; + description.setMessage(PlatformErrorMessages.RPR_SYS_JSON_PARSING_EXCEPTION.getMessage()); + description.setCode(PlatformErrorMessages.RPR_SYS_JSON_PARSING_EXCEPTION.getCode()); + object.setInternalError(Boolean.TRUE); + object.setRid(registrationStatusDto.getRegistrationId()); + } catch (PacketManagerException e) { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + registrationId, + RegistrationStatusCode.PROCESSING.toString() + e.getMessage() + ExceptionUtils.getStackTrace(e)); + registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.name()); + registrationStatusDto.setStatusComment( + trimExceptionMessage.trimExceptionMessage(StatusUtil.PACKET_MANAGER_EXCEPTION.getMessage() + e.getMessage())); + registrationStatusDto.setSubStatusCode(StatusUtil.PACKET_MANAGER_EXCEPTION.getCode()); + registrationStatusDto.setLatestTransactionStatusCode( + registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.PACKET_MANAGER_EXCEPTION)); + description.setMessage(PlatformErrorMessages.PACKET_MANAGER_EXCEPTION.getMessage()); + description.setCode(PlatformErrorMessages.PACKET_MANAGER_EXCEPTION.getCode()); + object.setInternalError(Boolean.TRUE); + object.setRid(registrationStatusDto.getRegistrationId()); + } catch (ApisResourceAccessException ex) { + registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.name()); + registrationStatusDto.setStatusComment(trimExceptionMessage + .trimExceptionMessage(StatusUtil.API_RESOUCE_ACCESS_FAILED.getMessage() + ex.getMessage())); + registrationStatusDto.setSubStatusCode(StatusUtil.API_RESOUCE_ACCESS_FAILED.getCode()); + registrationStatusDto.setLatestTransactionStatusCode(registrationStatusMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.APIS_RESOURCE_ACCESS_EXCEPTION)); + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + registrationId, + RegistrationStatusCode.PROCESSING.toString() + ex.getMessage() + ExceptionUtils.getStackTrace(ex)); + object.setInternalError(Boolean.TRUE); + description.setMessage(trimExceptionMessage + .trimExceptionMessage(StatusUtil.API_RESOUCE_ACCESS_FAILED.getMessage() + ex.getMessage())); + description.setCode(PlatformErrorMessages.RPR_UGS_API_RESOURCE_EXCEPTION.getCode()); + + } catch (IOException e) { + registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.name()); + registrationStatusDto.setStatusComment( + trimExceptionMessage.trimExceptionMessage(StatusUtil.IO_EXCEPTION.getMessage() + e.getMessage())); + registrationStatusDto.setSubStatusCode(StatusUtil.IO_EXCEPTION.getCode()); + registrationStatusDto.setLatestTransactionStatusCode( + registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.PACKET_UIN_GENERATION_REPROCESS)); + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + registrationId, + PlatformErrorMessages.RPR_SYS_IO_EXCEPTION.getMessage() + ExceptionUtils.getStackTrace(e)); + object.setInternalError(Boolean.TRUE); + description.setMessage(PlatformErrorMessages.RPR_SYS_IO_EXCEPTION.getMessage()); + description.setCode(PlatformErrorMessages.RPR_SYS_IO_EXCEPTION.getCode()); + } catch (IdrepoDraftException e) { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + registrationId, + RegistrationStatusCode.PROCESSING.toString() + e.getMessage() + ExceptionUtils.getStackTrace(e)); + registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.name()); + registrationStatusDto.setStatusComment( + trimExceptionMessage.trimExceptionMessage(StatusUtil.IDREPO_DRAFT_EXCEPTION.getMessage() + e.getMessage())); + registrationStatusDto.setSubStatusCode(StatusUtil.IDREPO_DRAFT_EXCEPTION.getCode()); + registrationStatusDto.setLatestTransactionStatusCode( + registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.IDREPO_DRAFT_EXCEPTION)); + description.setMessage(PlatformErrorMessages.IDREPO_DRAFT_EXCEPTION.getMessage()); + description.setCode(PlatformErrorMessages.IDREPO_DRAFT_EXCEPTION.getCode()); + object.setInternalError(Boolean.TRUE); + object.setRid(registrationStatusDto.getRegistrationId()); + } catch (IdrepoDraftReprocessableException e) { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + registrationId, + RegistrationStatusCode.PROCESSING.toString() + e.getMessage() + ExceptionUtils.getStackTrace(e)); + registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.name()); + registrationStatusDto.setStatusComment(trimExceptionMessage + .trimExceptionMessage( + StatusUtil.IDREPO_DRAFT_REPROCESSABLE_EXCEPTION.getMessage() + e.getMessage())); + registrationStatusDto.setSubStatusCode(StatusUtil.IDREPO_DRAFT_REPROCESSABLE_EXCEPTION.getCode()); + registrationStatusDto.setLatestTransactionStatusCode( + registrationStatusMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.IDREPO_DRAFT_REPROCESSABLE_EXCEPTION)); + description.setMessage(PlatformErrorMessages.IDREPO_DRAFT_EXCEPTION.getMessage()); + description.setCode(PlatformErrorMessages.IDREPO_DRAFT_EXCEPTION.getCode()); + object.setInternalError(Boolean.TRUE); + object.setRid(registrationStatusDto.getRegistrationId()); + } catch (Exception ex) { + registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.name()); + registrationStatusDto.setStatusComment( + trimExceptionMessage.trimExceptionMessage(StatusUtil.UNKNOWN_EXCEPTION_OCCURED.getMessage())); + registrationStatusDto.setSubStatusCode(StatusUtil.UNKNOWN_EXCEPTION_OCCURED.getCode()); + registrationStatusDto.setLatestTransactionStatusCode( + registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.PACKET_UIN_GENERATION_REPROCESS)); + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + registrationId, + RegistrationStatusCode.PROCESSING.toString() + ex.getMessage() + ExceptionUtils.getStackTrace(ex)); + object.setInternalError(Boolean.TRUE); + description.setMessage(PlatformErrorMessages.RPR_BDD_UNKNOWN_EXCEPTION.getMessage()); + description.setCode(PlatformErrorMessages.RPR_BDD_UNKNOWN_EXCEPTION.getCode()); + } finally { + if (description.getStatusComment() != null) + registrationStatusDto.setStatusComment(description.getStatusComment()); + if (description.getStatusCode() != null) + registrationStatusDto.setStatusCode(description.getStatusCode()); + if (description.getSubStatusCode() != null) + registrationStatusDto.setSubStatusCode(description.getSubStatusCode()); + if (description.getTransactionStatusCode() != null) + registrationStatusDto.setLatestTransactionStatusCode(description.getTransactionStatusCode()); + + if (object.getInternalError()) { + updateErrorFlags(registrationStatusDto, object); + } + String moduleId = isTransactionSuccessful + ? PlatformSuccessMessages.RPR_UIN_GENERATOR_STAGE_SUCCESS.getCode() + : description.getCode(); + String moduleName = ModuleName.UIN_GENERATOR.toString(); + registrationStatusService.updateRegistrationStatus(registrationStatusDto, moduleId, moduleName); + String eventId = isTransactionSuccessful ? EventId.RPR_402.toString() : EventId.RPR_405.toString(); + String eventName = eventId.equalsIgnoreCase(EventId.RPR_402.toString()) ? EventName.UPDATE.toString() + : EventName.EXCEPTION.toString(); + String eventType = eventId.equalsIgnoreCase(EventId.RPR_402.toString()) ? EventType.BUSINESS.toString() + : EventType.SYSTEM.toString(); + + auditLogRequestBuilder.createAuditRequestBuilder(description.getMessage(), eventId, eventName, eventType, + moduleId, moduleName, registrationId); + + } + + return object; + } + + private void loadDemographicIdentity(Map fieldMap, JSONObject demographicIdentity) throws IOException, JSONException { + for (Map.Entry e : fieldMap.entrySet()) { + if (e.getValue() != null) { + String value = e.getValue().toString(); + if (value != null) { + Object json = new JSONTokener(value).nextValue(); + if (json instanceof org.json.JSONObject) { + HashMap hashMap = objectMapper.readValue(value, HashMap.class); + demographicIdentity.putIfAbsent(e.getKey(), hashMap); + } + else if (json instanceof JSONArray) { + List jsonList = new ArrayList<>(); + JSONArray jsonArray = new JSONArray(value); + for (int i = 0; i < jsonArray.length(); i++) { + Object obj = jsonArray.get(i); + HashMap hashMap = objectMapper.readValue(obj.toString(), HashMap.class); + jsonList.add(hashMap); + } + demographicIdentity.putIfAbsent(e.getKey(), jsonList); + } else + demographicIdentity.putIfAbsent(e.getKey(), value); + } else + demographicIdentity.putIfAbsent(e.getKey(), value); + } + } + } + + /** + * Send id repo with uin. + * + * @param id + * the reg id + * @param uin + * the uin + * @throws ApisResourceAccessException + * @throws IOException + * @throws JsonMappingException + * @throws JsonParseException + * @throws VidCreationException + * @throws io.mosip.kernel.core.exception.IOException + * @throws Exception + */ + private IdResponseDTO sendIdRepoWithUin(String id, String process, JSONObject demographicIdentity, String uin) + throws Exception { + + List documentInfo = getAllDocumentsByRegId(id, process, demographicIdentity); + RequestDto requestDto = new RequestDto(); + requestDto.setIdentity(demographicIdentity); + requestDto.setDocuments(documentInfo); + requestDto.setRegistrationId(id); + requestDto.setStatus(RegistrationType.ACTIVATED.toString()); + requestDto.setBiometricReferenceId(uin); + + IdResponseDTO result = null; + IdRequestDto idRequestDTO = new IdRequestDto(); + idRequestDTO.setId(idRepoUpdate); + idRequestDTO.setRequest(requestDto); + idRequestDTO.setRequesttime(DateUtils.getUTCCurrentDateTimeString()); + idRequestDTO.setVersion(UINConstants.idRepoApiVersion); + idRequestDTO.setMetadata(null); + + try { + + result = idrepoDraftService.idrepoUpdateDraft(id, null, idRequestDTO); + + } catch (ApisResourceAccessException e) { + regProcLogger.error("Execption occured updating draft for id " + id, e); + if (e.getCause() instanceof HttpClientErrorException) { + HttpClientErrorException httpClientException = (HttpClientErrorException) e.getCause(); + throw new ApisResourceAccessException(httpClientException.getResponseBodyAsString(), + httpClientException); + } else if (e.getCause() instanceof HttpServerErrorException) { + HttpServerErrorException httpServerException = (HttpServerErrorException) e.getCause(); + throw new ApisResourceAccessException(httpServerException.getResponseBodyAsString(), + httpServerException); + } else { + throw e; + } + + } + return result; + + } + + /** + * Gets the all documents by reg id. + * + * @param regId + * the reg id + * @return the all documents by reg id + * @throws IOException + * @throws io.mosip.kernel.core.exception.IOException + * @throws ApisResourceAccessException + * @throws JsonMappingException + * @throws JsonParseException + */ + private List getAllDocumentsByRegId(String regId, String process, JSONObject demographicIdentity) throws Exception { + List applicantDocuments = new ArrayList<>(); + + JSONObject idJSON = demographicIdentity; + JSONObject docJson = utility.getRegistrationProcessorMappingJson(MappingJsonConstants.DOCUMENT); + JSONObject identityJson = utility.getRegistrationProcessorMappingJson(MappingJsonConstants.IDENTITY); + + String applicantBiometricLabel = JsonUtil.getJSONValue(JsonUtil.getJSONObject(identityJson, MappingJsonConstants.INDIVIDUAL_BIOMETRICS), MappingJsonConstants.VALUE); + + HashMap applicantBiometric = (HashMap) idJSON.get(applicantBiometricLabel); + + + for (Object doc : docJson.values()) { + Map docMap = (LinkedHashMap) doc; + String docValue = docMap.values().iterator().next().toString(); + HashMap docInIdentityJson = (HashMap) idJSON.get(docValue); + if (docInIdentityJson != null) + applicantDocuments + .add(getIdDocumnet(regId, docValue, process)); + } + + if (applicantBiometric != null) { + applicantDocuments.add(getBiometrics(regId, applicantBiometricLabel, process, applicantBiometricLabel)); + } + return applicantDocuments; + } + + private Documents getIdDocumnet(String registrationId, String dockey, String process) + throws IOException, ApisResourceAccessException, PacketManagerException, io.mosip.kernel.core.util.exception.JsonProcessingException { + Documents documentsInfoDto = new Documents(); + + Document document = + packetManagerService.getDocument(registrationId, dockey, process, ProviderStageName.UIN_GENERATOR); + if (document != null) { + documentsInfoDto.setValue(CryptoUtil.encodeToURLSafeBase64(document.getDocument())); + documentsInfoDto.setCategory(document.getValue()); + return documentsInfoDto; + } + return null; + } + + private Documents getBiometrics(String registrationId, String person, String process, String idDocLabel) throws Exception { + BiometricRecord biometricRecord = packetManagerService.getBiometrics(registrationId, person, process, ProviderStageName.UIN_GENERATOR); + byte[] xml = cbeffutil.createXML(biometricRecord.getSegments()); + Documents documentsInfoDto = new Documents(); + documentsInfoDto.setValue(CryptoUtil.encodeToURLSafeBase64(xml)); + documentsInfoDto.setCategory(utility.getMappingJsonValue(idDocLabel, MappingJsonConstants.IDENTITY)); + return documentsInfoDto; + + } + + /** + * Update id repo wit uin. + * + * @param regId the reg id + * @param uin the uin + * @param object the object + * @param description + * @return the id response DTO + * @throws ApisResourceAccessException the apis resource access + * exception + * @throws IOException Signals that an I/O exception + * has occurred. + * @throws RegistrationProcessorCheckedException + * @throws io.mosip.kernel.core.exception.IOException + */ + private boolean uinUpdate(String regId, String process, String uin, MessageDTO object, JSONObject demographicIdentity, LogDescription description) + throws Exception { + IdResponseDTO result; + boolean isTransactionSuccessful = Boolean.FALSE; + List documentInfo = getAllDocumentsByRegId(regId, process, demographicIdentity); + result = idRepoRequestBuilder(regId, uin, RegistrationType.ACTIVATED.toString().toUpperCase(), documentInfo, + demographicIdentity); + if (null!=result && isIdResponseNotNull(result)) { + + if (IDREPO_STATUS.equalsIgnoreCase(result.getResponse().getStatus())) { + isTransactionSuccessful = true; + description.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); + description.setStatusComment(StatusUtil.UIN_DATA_UPDATION_SUCCESS.getMessage()); + description.setSubStatusCode(StatusUtil.UIN_DATA_UPDATION_SUCCESS.getCode()); + description.setMessage( + StatusUtil.UIN_DATA_UPDATION_SUCCESS.getMessage() + " for registration Id: " + regId); + description.setTransactionStatusCode(RegistrationTransactionStatusCode.PROCESSED.toString()); + object.setIsValid(Boolean.TRUE); + } + } else { + String statusComment = result != null && result.getErrors() != null ? result.getErrors().get(0).getMessage() + : UINConstants.NULL_IDREPO_RESPONSE; + String message = result != null && result.getErrors() != null + ? result.getErrors().get(0).getMessage() + : UINConstants.NULL_IDREPO_RESPONSE; + description.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); + description.setStatusComment(trimExceptionMessage + .trimExceptionMessage(StatusUtil.UIN_DATA_UPDATION_FAILED.getMessage() + statusComment)); + description.setSubStatusCode(StatusUtil.UIN_DATA_UPDATION_FAILED.getCode()); + description + .setMessage(UINConstants.UIN_FAILURE + regId + "::" + message ); + description.setTransactionStatusCode(RegistrationTransactionStatusCode.PROCESSING.toString()); + object.setIsValid(Boolean.FALSE); + } + return isTransactionSuccessful; + } + + /** + * Id repo request builder. + * + * @param status the status + * @param id the reg id + * @param demographicIdentity the JSONObject + * @param documentInfo the document info + * @throws ApisResourceAccessException the apis resource access exception + * @throws IOException + * @throws IdrepoDraftReprocessableException + */ + private IdResponseDTO idRepoRequestBuilder(String id, String uin, String status, List documentInfo, + JSONObject demographicIdentity) + throws ApisResourceAccessException, IdrepoDraftException, IOException, IdrepoDraftReprocessableException { + IdResponseDTO idResponseDto; + RequestDto requestDto = new RequestDto(); + + if (documentInfo != null) + requestDto.setDocuments(documentInfo); + + requestDto.setRegistrationId(id); + requestDto.setStatus(status); + requestDto.setIdentity(demographicIdentity); + + IdRequestDto idRequestDTO = new IdRequestDto(); + idRequestDTO.setId(idRepoUpdate); + idRequestDTO.setMetadata(null); + idRequestDTO.setRequest(requestDto); + idRequestDTO.setRequesttime(DateUtils.getUTCCurrentDateTimeString()); + idRequestDTO.setVersion(UINConstants.idRepoApiVersion); + + try { + idResponseDto = idrepoDraftService.idrepoUpdateDraft(id, uin, idRequestDTO); + } catch (ApisResourceAccessException e) { + regProcLogger.error("Execption occured updating draft for id " + id, e); + if (e.getCause() instanceof HttpClientErrorException) { + regProcLogger.error("Exception occured updating draft for id " + id, e); + HttpClientErrorException httpClientException = (HttpClientErrorException) e.getCause(); + throw new ApisResourceAccessException(httpClientException.getResponseBodyAsString(), + httpClientException); + } else if (e.getCause() instanceof HttpServerErrorException) { + HttpServerErrorException httpServerException = (HttpServerErrorException) e.getCause(); + throw new ApisResourceAccessException(httpServerException.getResponseBodyAsString(), + httpServerException); + } else { + throw e; + } + + } + return idResponseDto; + } + + /** + * Re activate uin. + * + * @param id the reg id + * @param uin the uin + * @param object the object + * @param description + * @return the id response DTO + * @throws ApisResourceAccessException the apis resource access exception + * @throws IOException + * @throws IdrepoDraftReprocessableException + */ + private boolean reActivateUin(IdResponseDTO idResponseDTO, String id, String uin, MessageDTO object, + JSONObject demographicIdentity, LogDescription description) + throws ApisResourceAccessException, IOException, IdrepoDraftException, IdrepoDraftReprocessableException { + IdResponseDTO result = getIdRepoDataByUIN(uin, id, description); + List pathsegments = new ArrayList<>(); + RequestDto requestDto = new RequestDto(); + boolean isTransactionSuccessful = Boolean.FALSE; + + if (isIdResponseNotNull(result)) { + + if ((RegistrationType.ACTIVATED.toString()).equalsIgnoreCase(result.getResponse().getStatus())) { + + description.setStatusCode(RegistrationStatusCode.FAILED.toString()); + description.setStatusComment(StatusUtil.UIN_ALREADY_ACTIVATED.getMessage()); + description.setSubStatusCode(StatusUtil.UIN_ALREADY_ACTIVATED.getCode()); + description.setMessage(PlatformErrorMessages.UIN_ALREADY_ACTIVATED.getMessage()); + description.setCode(PlatformErrorMessages.UIN_ALREADY_ACTIVATED.getCode()); + description.setTransactionStatusCode(RegistrationTransactionStatusCode.FAILED.toString()); + object.setIsValid(Boolean.FALSE); + return isTransactionSuccessful; + + } else { + + requestDto.setRegistrationId(id); + requestDto.setStatus(RegistrationType.ACTIVATED.toString()); + requestDto.setBiometricReferenceId(uin); + requestDto.setIdentity(demographicIdentity); + + IdRequestDto idRequestDTO = new IdRequestDto(); + idRequestDTO.setId(idRepoUpdate); + idRequestDTO.setRequest(requestDto); + idRequestDTO.setMetadata(null); + idRequestDTO.setRequesttime(DateUtils.getUTCCurrentDateTimeString()); + idRequestDTO.setVersion(UINConstants.idRepoApiVersion); + + result = idrepoDraftService.idrepoUpdateDraft(id, uin, idRequestDTO); + + if (isIdResponseNotNull(result)) { + + if ((RegistrationType.ACTIVATED.toString()).equalsIgnoreCase(result.getResponse().getStatus())) { + isTransactionSuccessful = true; + description.setStatusCode(RegistrationStatusCode.PROCESSED.toString()); + description.setStatusComment(StatusUtil.UIN_ACTIVATED_SUCCESS.getMessage()); + description.setSubStatusCode(StatusUtil.UIN_ACTIVATED_SUCCESS.getCode()); + description.setMessage(StatusUtil.UIN_ACTIVATED_SUCCESS.getMessage() + id); + description.setMessage(PlatformSuccessMessages.RPR_UIN_ACTIVATED_SUCCESS.getMessage()); + description.setCode(PlatformSuccessMessages.RPR_UIN_ACTIVATED_SUCCESS.getCode()); + description.setTransactionStatusCode(RegistrationTransactionStatusCode.PROCESSED.toString()); + object.setIsValid(Boolean.TRUE); + } else { + description.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); + description.setStatusComment(StatusUtil.UIN_ACTIVATED_FAILED.getMessage()); + description.setSubStatusCode(StatusUtil.UIN_ACTIVATED_FAILED.getCode()); + description.setMessage(StatusUtil.UIN_ACTIVATED_FAILED.getMessage() + id); + description.setMessage(PlatformErrorMessages.UIN_ACTIVATED_FAILED.getMessage()); + description.setCode(PlatformErrorMessages.UIN_ACTIVATED_FAILED.getCode()); + description.setTransactionStatusCode(RegistrationTransactionStatusCode.REPROCESS.toString()); + object.setIsValid(Boolean.FALSE); + } + } else { + String statusComment = result != null && result.getErrors() != null + ? result.getErrors().get(0).getMessage() + : UINConstants.NULL_IDREPO_RESPONSE; + description.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); + description.setStatusComment(trimExceptionMessage + .trimExceptionMessage(StatusUtil.UIN_REACTIVATION_FAILED.getMessage() + statusComment)); + description.setSubStatusCode(StatusUtil.UIN_REACTIVATION_FAILED.getCode()); + description.setMessage( + UINConstants.UIN_FAILURE + id + "::" + (result != null && result.getErrors() != null + ? result.getErrors().get(0).getMessage() + : UINConstants.NULL_IDREPO_RESPONSE)); + description.setMessage(PlatformErrorMessages.UIN_REACTIVATION_FAILED.getMessage()); + description.setCode(PlatformErrorMessages.UIN_REACTIVATION_FAILED.getCode()); + description.setTransactionStatusCode(RegistrationTransactionStatusCode.REPROCESS.toString()); + object.setIsValid(Boolean.FALSE); + } + + } + + }else { + String statusComment = result != null && result.getErrors() != null + ? result.getErrors().get(0).getMessage() + : UINConstants.NULL_IDREPO_RESPONSE; + description.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); + description.setStatusComment(trimExceptionMessage + .trimExceptionMessage(StatusUtil.UIN_REACTIVATION_FAILED.getMessage() + statusComment)); + description.setSubStatusCode(StatusUtil.UIN_REACTIVATION_FAILED.getCode()); + description.setMessage( + UINConstants.UIN_FAILURE + id + "::" + (result != null && result.getErrors() != null + ? result.getErrors().get(0).getMessage() + : UINConstants.NULL_IDREPO_RESPONSE)); + description.setMessage(PlatformErrorMessages.UIN_REACTIVATION_FAILED.getMessage()); + description.setCode(PlatformErrorMessages.UIN_REACTIVATION_FAILED.getCode()); + description.setTransactionStatusCode(RegistrationTransactionStatusCode.REPROCESS.toString()); + object.setIsValid(Boolean.FALSE); + } + + return isTransactionSuccessful; + } + + private boolean isIdResponseNotNull(IdResponseDTO result) { + return result != null && result.getResponse() != null; + } + + private boolean isUinAlreadyPresent(IdResponseDTO result, String rid) { + if (result != null && result.getErrors() != null && result.getErrors().size() > 0 + && result.getErrors().get(0).getErrorCode().equalsIgnoreCase(RECORD_ALREADY_EXISTS_ERROR)) { + ErrorDTO errorDTO = result.getErrors().get(0); + regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString() + rid, + "Record is already present in IDREPO. Error message received : " + errorDTO.getMessage(), + "The stage will ignore this error and try to generate vid for the existing UIN now. " + + "This is to make sure if the packet processing fails while generating VID then re-processor can process the packet again"); + return true; + } + return false; + } + + /** + * Deactivate uin. + * + * @param id the reg id + * @param uin the uin + * @param object the object + * @param description + * @return the id response DTO + * @throws ApisResourceAccessException + * @throws IOException + * @throws IdrepoDraftReprocessableException + */ + private IdResponseDTO deactivateUin(String id, String uin, MessageDTO object, JSONObject demographicIdentity, + LogDescription description) + throws ApisResourceAccessException, IOException, IdrepoDraftException, IdrepoDraftReprocessableException { + IdResponseDTO idResponseDto; + RequestDto requestDto = new RequestDto(); + String statusComment = ""; + + idResponseDto = getIdRepoDataByUIN(uin, id, description); + + if (idResponseDto.getResponse() != null + && idResponseDto.getResponse().getStatus().equalsIgnoreCase(RegistrationType.DEACTIVATED.toString())) { + description.setStatusCode(RegistrationStatusCode.FAILED.toString()); + description.setStatusComment(StatusUtil.UIN_ALREADY_DEACTIVATED.getMessage()); + description.setSubStatusCode(StatusUtil.UIN_ALREADY_DEACTIVATED.getCode()); + description.setMessage(StatusUtil.UIN_ALREADY_DEACTIVATED.getMessage() + id); + description.setMessage(PlatformErrorMessages.UIN_ALREADY_DEACTIVATED.getMessage()); + description.setCode(PlatformErrorMessages.UIN_ALREADY_DEACTIVATED.getCode()); + description.setTransactionStatusCode(RegistrationTransactionStatusCode.FAILED.toString()); + object.setIsValid(Boolean.FALSE); + return idResponseDto; + + } else { + requestDto.setRegistrationId(id); + requestDto.setStatus(RegistrationType.DEACTIVATED.toString()); + requestDto.setIdentity(demographicIdentity); + requestDto.setBiometricReferenceId(uin); + + IdRequestDto idRequestDTO = new IdRequestDto(); + idRequestDTO.setId(idRepoUpdate); + idRequestDTO.setMetadata(null); + idRequestDTO.setRequest(requestDto); + idRequestDTO.setRequesttime(DateUtils.getUTCCurrentDateTimeString()); + idRequestDTO.setVersion(UINConstants.idRepoApiVersion); + + idResponseDto = idrepoDraftService.idrepoUpdateDraft(id, uin, idRequestDTO); + + if (isIdResponseNotNull(idResponseDto)) { + if (idResponseDto.getResponse().getStatus().equalsIgnoreCase(RegistrationType.DEACTIVATED.toString())) { + description.setStatusCode(RegistrationStatusCode.PROCESSED.toString()); + description.setStatusComment(StatusUtil.UIN_DEACTIVATION_SUCCESS.getMessage()); + description.setSubStatusCode(StatusUtil.UIN_DEACTIVATION_SUCCESS.getCode()); + description.setMessage(StatusUtil.UIN_DEACTIVATION_SUCCESS.getMessage() + id); + description.setMessage(PlatformSuccessMessages.RPR_UIN_DEACTIVATION_SUCCESS.getMessage()); + description.setCode(PlatformSuccessMessages.RPR_UIN_DEACTIVATION_SUCCESS.getCode()); + description.setTransactionStatusCode(RegistrationTransactionStatusCode.PROCESSED.toString()); + object.setIsValid(Boolean.TRUE); + statusComment = idResponseDto.getResponse().getStatus().toString(); + + } + } else { + + statusComment = idResponseDto != null && idResponseDto.getErrors() != null + ? idResponseDto.getErrors().get(0).getMessage() + : UINConstants.NULL_IDREPO_RESPONSE; + description.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); + description.setStatusComment(trimExceptionMessage + .trimExceptionMessage(StatusUtil.UIN_DEACTIVATION_FAILED.getMessage() + statusComment)); + description.setSubStatusCode(StatusUtil.UIN_DEACTIVATION_FAILED.getCode()); + description.setMessage(PlatformErrorMessages.UIN_DEACTIVATION_FAILED.getMessage()); + description.setCode(PlatformErrorMessages.UIN_DEACTIVATION_FAILED.getCode()); + description.setTransactionStatusCode(RegistrationTransactionStatusCode.REPROCESS.toString()); + object.setIsValid(Boolean.FALSE); + } + + } + regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString() + id, "Updated Response from IdRepo API", + "is : " + statusComment); + + return idResponseDto; + } + + /** + * Gets the id repo data by UIN. + * + * @param uin + * the uin + * @param description + * @return the id repo data by UIN + * @throws ApisResourceAccessException + * the apis resource access exception + * @throws IOException + */ + private IdResponseDTO getIdRepoDataByUIN(String uin, String regId, LogDescription description) + throws ApisResourceAccessException { + IdResponseDTO response; + + List pathsegments = new ArrayList<>(); + pathsegments.add(uin); + try { + + response = (IdResponseDTO) registrationProcessorRestClientService.getApi(ApiName.IDREPOGETIDBYUIN, + pathsegments, "", "", IdResponseDTO.class); + + } catch (ApisResourceAccessException e) { + if (e.getCause() instanceof HttpClientErrorException) { + HttpClientErrorException httpClientException = (HttpClientErrorException) e.getCause(); + description.setMessage(PlatformErrorMessages.UIN_GENERATION_FAILED.getMessage()); + description.setCode(PlatformErrorMessages.UIN_GENERATION_FAILED.getCode()); + throw new ApisResourceAccessException(httpClientException.getResponseBodyAsString(), + httpClientException); + } else if (e.getCause() instanceof HttpServerErrorException) { + HttpServerErrorException httpServerException = (HttpServerErrorException) e.getCause(); + description.setMessage(PlatformErrorMessages.UIN_GENERATION_FAILED.getMessage()); + description.setCode(PlatformErrorMessages.UIN_GENERATION_FAILED.getCode()); + + throw new ApisResourceAccessException(httpServerException.getResponseBodyAsString(), + httpServerException); + } else { + description.setMessage(PlatformErrorMessages.UIN_GENERATION_FAILED.getMessage()); + description.setCode(PlatformErrorMessages.UIN_GENERATION_FAILED.getCode()); + throw e; + } + } + return response; + } + + /** + * Deploy verticle. + */ + public void deployVerticle() { + + mosipEventBus = this.getEventBus(this, clusterManagerUrl, workerPoolSize); + this.consumeAndSend(mosipEventBus, MessageBusAddress.UIN_GENERATION_BUS_IN, + MessageBusAddress.UIN_GENERATION_BUS_OUT, messageExpiryTimeLimit); + } + + @Override + public void start() { + router.setRoute(this.postUrl(getVertx(), MessageBusAddress.UIN_GENERATION_BUS_IN, + MessageBusAddress.UIN_GENERATION_BUS_OUT)); + this.createServer(router.getRouter(), getPort()); + + } + + @Override + protected String getPropertyPrefix() { + return STAGE_PROPERTY_PREFIX; + } + + /** + * Link reg id wrt uin. + * + * @param lostPacketRegId the lost packet reg id + * @param matchedRegId the matched reg id + * @param object the object + * @param description + * @return the id response DTO + * @throws ApisResourceAccessException the apis resource access exception + * @throws IOException Signals that an I/O exception has + * occurred. + * @throws IdrepoDraftReprocessableException + */ + @SuppressWarnings("unchecked") + private IdResponseDTO lostAndUpdateUin(String lostPacketRegId, String matchedRegId, String process, MessageDTO object, + LogDescription description) throws ApisResourceAccessException, IOException, + io.mosip.kernel.core.util.exception.JsonProcessingException, PacketManagerException, IdrepoDraftException, + IdrepoDraftReprocessableException { + + IdResponseDTO idResponse = null; + String uin = idRepoService.getUinByRid(matchedRegId, utility.getGetRegProcessorDemographicIdentity()); + + + RequestDto requestDto = new RequestDto(); + String statusComment = ""; + + if (uin != null) { + + JSONObject regProcessorIdentityJson = utility.getRegistrationProcessorMappingJson(MappingJsonConstants.IDENTITY); + String idschemaversion = JsonUtil.getJSONValue(JsonUtil.getJSONObject(regProcessorIdentityJson, MappingJsonConstants.IDSCHEMA_VERSION), MappingJsonConstants.VALUE); + + JSONObject identityObject = new JSONObject(); + identityObject.put(UINConstants.UIN, uin); + String schemaVersion = packetManagerService.getFieldByMappingJsonKey(lostPacketRegId, MappingJsonConstants.IDSCHEMA_VERSION, process, ProviderStageName.UIN_GENERATOR); + identityObject.put(idschemaversion, convertIdschemaToDouble ? Double.valueOf(schemaVersion) : schemaVersion); + regProcLogger.info("Fields to be updated "+updateInfo); + if (null != updateInfo && !updateInfo.isEmpty()) { + String[] upd = updateInfo.split(","); + for (String infoField : upd) { + String fldValue = packetManagerService.getField(lostPacketRegId, infoField, process, + ProviderStageName.UIN_GENERATOR); + if (null != fldValue) + identityObject.put(infoField, fldValue); + } + } + requestDto.setRegistrationId(lostPacketRegId); + requestDto.setIdentity(identityObject); + + IdRequestDto idRequestDTO = new IdRequestDto(); + idRequestDTO.setId(idRepoUpdate); + idRequestDTO.setRequest(requestDto); + idRequestDTO.setMetadata(null); + idRequestDTO.setRequesttime(DateUtils.getUTCCurrentDateTimeString()); + idRequestDTO.setVersion(UINConstants.idRepoApiVersion); + + idResponse = idrepoDraftService.idrepoUpdateDraft(lostPacketRegId, uin, idRequestDTO); + + if (isIdResponseNotNull(idResponse)) { + description.setStatusCode(RegistrationStatusCode.PROCESSED.toString()); + description.setStatusComment(StatusUtil.LINK_RID_FOR_LOST_PACKET_SUCCESS.getMessage()); + description.setSubStatusCode(StatusUtil.LINK_RID_FOR_LOST_PACKET_SUCCESS.getCode()); + description.setMessage(UinStatusMessage.PACKET_LOST_UIN_UPDATION_SUCCESS_MSG + lostPacketRegId); + description.setTransactionStatusCode(RegistrationTransactionStatusCode.PROCESSED.toString()); + object.setIsValid(Boolean.TRUE); + + regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString() + lostPacketRegId, + " UIN LINKED WITH " + matchedRegId, "is : " + description); + } else { + + statusComment = idResponse != null && idResponse.getErrors() != null + && idResponse.getErrors().get(0) != null ? idResponse.getErrors().get(0).getMessage() + : UinStatusMessage.PACKET_LOST_UIN_UPDATION_FAILURE_MSG + " " + + UINConstants.NULL_IDREPO_RESPONSE + "for lostPacketRegId " + lostPacketRegId; + description.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); + description.setStatusComment(StatusUtil.LINK_RID_FOR_LOST_PACKET_SUCCESS.getMessage() + statusComment); + description.setSubStatusCode(StatusUtil.LINK_RID_FOR_LOST_PACKET_SUCCESS.getCode()); + description.setTransactionStatusCode(registrationStatusMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.PACKET_UIN_GENERATION_ID_REPO_ERROR)); + if (idResponse != null + && idResponse.getErrors() != null) + description.setMessage(idResponse.getErrors().get(0).getMessage()); + else + description.setMessage(UINConstants.NULL_IDREPO_RESPONSE); + object.setIsValid(Boolean.FALSE); + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString() + lostPacketRegId, + " UIN NOT LINKED WITH " + matchedRegId, "is : " + statusComment); + } + + } else { + statusComment = UinStatusMessage.PACKET_LOST_UIN_UPDATION_FAILURE_MSG + " " + + UINConstants.NULL_IDREPO_RESPONSE + " UIN not available for matchedRegId " + matchedRegId; + description.setStatusComment(StatusUtil.LINK_RID_FOR_LOST_PACKET_FAILED.getMessage()); + description.setSubStatusCode(StatusUtil.LINK_RID_FOR_LOST_PACKET_FAILED.getCode()); + description.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); + description.setTransactionStatusCode(registrationStatusMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.PACKET_UIN_GENERATION_REPROCESS)); + description.setMessage(UinStatusMessage.PACKET_LOST_UIN_UPDATION_FAILURE_MSG + " " + + UINConstants.NULL_IDREPO_RESPONSE + " UIN not available for matchedRegId " + matchedRegId); + + object.setIsValid(Boolean.FALSE); + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString() + lostPacketRegId, + " UIN NOT LINKED WITH " + matchedRegId, "is : " + statusComment); + } + + return idResponse; + } + + private void updateErrorFlags(InternalRegistrationStatusDto registrationStatusDto, MessageDTO object) { + object.setInternalError(true); + if (registrationStatusDto.getLatestTransactionStatusCode() + .equalsIgnoreCase(RegistrationTransactionStatusCode.REPROCESS.toString())) { + object.setIsValid(true); + } else { + object.setIsValid(false); + } + } +} diff --git a/registration-processor/core-processor/registration-processor-uin-generator-stage/src/test/java/io/mosip/registration/processor/stages/uigenerator/UinGeneratorStageTest.java b/registration-processor/core-processor/registration-processor-uin-generator-stage/src/test/java/io/mosip/registration/processor/stages/uigenerator/UinGeneratorStageTest.java index 73af66984c1..43a261bf0d4 100644 --- a/registration-processor/core-processor/registration-processor-uin-generator-stage/src/test/java/io/mosip/registration/processor/stages/uigenerator/UinGeneratorStageTest.java +++ b/registration-processor/core-processor/registration-processor-uin-generator-stage/src/test/java/io/mosip/registration/processor/stages/uigenerator/UinGeneratorStageTest.java @@ -85,6 +85,7 @@ import io.mosip.registration.processor.packet.manager.dto.IdResponseDTO; import io.mosip.registration.processor.packet.manager.dto.ResponseDTO; import io.mosip.registration.processor.packet.manager.exception.IdrepoDraftException; +import io.mosip.registration.processor.packet.manager.exception.IdrepoDraftReprocessableException; import io.mosip.registration.processor.packet.manager.idreposervice.IdRepoService; import io.mosip.registration.processor.packet.manager.idreposervice.IdrepoDraftService; import io.mosip.registration.processor.packet.storage.dto.ApplicantInfoDto; @@ -969,7 +970,8 @@ public void testApiResourceExceptionInUpdateIdRepoTest() throws Exception { } @Test - public void deactivateTestSuccess() throws ApisResourceAccessException, IOException, JSONException, JsonProcessingException, PacketManagerException, IdrepoDraftException { + public void deactivateTestSuccess() throws ApisResourceAccessException, IOException, JSONException, + JsonProcessingException, PacketManagerException, IdrepoDraftException, IdrepoDraftReprocessableException { Map fieldMap = new HashMap<>(); fieldMap.put("UIN", "123456"); @@ -1056,7 +1058,8 @@ public void checkIsUinDeactivatedSuccess() throws ApisResourceAccessException, I assertFalse(result.getInternalError()); } @Test - public void deactivateTestWithDeactivate() throws ApisResourceAccessException, IOException, JSONException, JsonProcessingException, PacketManagerException, IdrepoDraftException { + public void deactivateTestWithDeactivate() throws ApisResourceAccessException, IOException, JSONException, + JsonProcessingException, PacketManagerException, IdrepoDraftException, IdrepoDraftReprocessableException { Map fieldMap = new HashMap<>(); fieldMap.put("UIN", "123456"); fieldMap.put("name", "mono"); @@ -1105,7 +1108,9 @@ public void deactivateTestWithDeactivate() throws ApisResourceAccessException, I } @Test - public void deactivateTestWithNullResponseDTO() throws ApisResourceAccessException, PacketManagerException, IOException, JsonProcessingException, JSONException, IdrepoDraftException { + public void deactivateTestWithNullResponseDTO() + throws ApisResourceAccessException, PacketManagerException, IOException, JsonProcessingException, + JSONException, IdrepoDraftException, IdrepoDraftReprocessableException { Map fieldMap = new HashMap<>(); fieldMap.put("UIN", "123456"); fieldMap.put("name", "mono"); @@ -1152,7 +1157,9 @@ public void deactivateTestWithNullResponseDTO() throws ApisResourceAccessExcepti } @Test - public void deactivateTestForExistingUinTestSuccess() throws ApisResourceAccessException, PacketManagerException, IOException, JsonProcessingException, JSONException, IdrepoDraftException { + public void deactivateTestForExistingUinTestSuccess() + throws ApisResourceAccessException, PacketManagerException, IOException, JsonProcessingException, + JSONException, IdrepoDraftException, IdrepoDraftReprocessableException { MessageDTO messageDTO = new MessageDTO(); messageDTO.setRid("10031100110005020190313110030"); messageDTO.setReg_type(RegistrationType.valueOf("DEACTIVATED").name()); @@ -1202,7 +1209,8 @@ public void deactivateTestForExistingUinTestSuccess() throws ApisResourceAccessE } @Test - public void deactivateTestFailure() throws ApisResourceAccessException, PacketManagerException, IOException, JsonProcessingException, JSONException, IdrepoDraftException { + public void deactivateTestFailure() throws ApisResourceAccessException, PacketManagerException, IOException, + JsonProcessingException, JSONException, IdrepoDraftException, IdrepoDraftReprocessableException { Map fieldMap = new HashMap<>(); fieldMap.put("UIN", "123456"); @@ -1262,7 +1270,8 @@ public void deactivateTestFailure() throws ApisResourceAccessException, PacketMa } @Test - public void apisResourceAccessExceptionTest() throws ApisResourceAccessException, IOException, IdrepoDraftException { + public void apisResourceAccessExceptionTest() + throws ApisResourceAccessException, IOException, IdrepoDraftException, IdrepoDraftReprocessableException { ApisResourceAccessException apisResourceAccessException = Mockito.mock(ApisResourceAccessException.class); HttpServerErrorException httpServerErrorException = new HttpServerErrorException( @@ -1379,7 +1388,8 @@ public void testUinGenerationHttpServerErrorException() throws Exception { @Test - public void clientErrorExceptionTest() throws ApisResourceAccessException, IOException, IdrepoDraftException { + public void clientErrorExceptionTest() + throws ApisResourceAccessException, IOException, IdrepoDraftException, IdrepoDraftReprocessableException { ApisResourceAccessException apisResourceAccessException = Mockito.mock(ApisResourceAccessException.class); HttpClientErrorException httpErrorErrorException = new HttpClientErrorException( @@ -1423,7 +1433,8 @@ public void testDeployVerticle() { @Test @Ignore - public void testApiResourceException() throws ApisResourceAccessException, IOException, IdrepoDraftException { + public void testApiResourceException() + throws ApisResourceAccessException, IOException, IdrepoDraftException, IdrepoDraftReprocessableException { MessageDTO messageDTO = new MessageDTO(); messageDTO.setRid("10031100110005020190313110030"); messageDTO.setReg_type(RegistrationType.valueOf("DEACTIVATED").name()); @@ -1451,7 +1462,8 @@ public void testApiResourceException() throws ApisResourceAccessException, IOExc } @Test - public void testApisResourceAccessExceptionPostApi() throws ApisResourceAccessException, IOException, IdrepoDraftException { + public void testApisResourceAccessExceptionPostApi() + throws ApisResourceAccessException, IOException, IdrepoDraftException, IdrepoDraftReprocessableException { ApisResourceAccessException exc = new ApisResourceAccessException(); MessageDTO messageDTO = new MessageDTO(); messageDTO.setRid("27847657360002520181210094052"); @@ -1585,7 +1597,8 @@ public void testLinkSuccessForLostUinAndUpdateContactInfo() throws Exception { } @Test - public void updateTestSuccess() throws ApisResourceAccessException, IOException, JsonProcessingException, PacketManagerException, JSONException, IdrepoDraftException { + public void updateTestSuccess() throws ApisResourceAccessException, IOException, JsonProcessingException, + PacketManagerException, JSONException, IdrepoDraftException, IdrepoDraftReprocessableException { Map fieldMap = new HashMap<>(); fieldMap.put("UIN", "123456"); fieldMap.put("name", "mono"); @@ -1980,7 +1993,8 @@ public void testUinReActivationWithoutIDResponseDTO() throws Exception { @Test public void deactivateTestWithNullResponseDTOBeforeDeactivate() throws ApisResourceAccessException, PacketManagerException, - IOException, JsonProcessingException, JSONException, IdrepoDraftException { + IOException, JsonProcessingException, JSONException, IdrepoDraftException, + IdrepoDraftReprocessableException { Map fieldMap = new HashMap<>(); fieldMap.put("UIN", "123456"); fieldMap.put("name", "mono"); @@ -2029,7 +2043,8 @@ public void deactivateTestWithNullResponseDTOBeforeDeactivate() throws ApisResou @Test public void deactivateTesApiResourceClientException() throws ApisResourceAccessException, PacketManagerException, - IOException, JsonProcessingException, JSONException, IdrepoDraftException { + IOException, JsonProcessingException, JSONException, IdrepoDraftException, + IdrepoDraftReprocessableException { Map fieldMap = new HashMap<>(); fieldMap.put("UIN", "123456"); fieldMap.put("name", "mono"); @@ -2079,7 +2094,8 @@ public void deactivateTesApiResourceClientException() throws ApisResourceAccessE @Test public void deactivateTesApiResourceServerException() throws ApisResourceAccessException, PacketManagerException, - IOException, JsonProcessingException, JSONException, IdrepoDraftException { + IOException, JsonProcessingException, JSONException, IdrepoDraftException, + IdrepoDraftReprocessableException { Map fieldMap = new HashMap<>(); fieldMap.put("UIN", "123456"); fieldMap.put("name", "mono"); @@ -2127,7 +2143,8 @@ public void deactivateTesApiResourceServerException() throws ApisResourceAccessE @Test public void deactivateTesApiResourceException() throws ApisResourceAccessException, PacketManagerException, - IOException, JsonProcessingException, JSONException, IdrepoDraftException { + IOException, JsonProcessingException, JSONException, IdrepoDraftException, + IdrepoDraftReprocessableException { Map fieldMap = new HashMap<>(); fieldMap.put("UIN", "123456"); fieldMap.put("name", "mono"); @@ -2175,7 +2192,8 @@ public void deactivateTesApiResourceException() throws ApisResourceAccessExcepti @Test public void deactivateTestAlreadyDeactivated() throws ApisResourceAccessException, PacketManagerException, - IOException, JsonProcessingException, JSONException, IdrepoDraftException { + IOException, JsonProcessingException, JSONException, IdrepoDraftException, + IdrepoDraftReprocessableException { Map fieldMap = new HashMap<>(); fieldMap.put("UIN", "123456"); fieldMap.put("name", "mono"); @@ -2224,7 +2242,8 @@ public void deactivateTestAlreadyDeactivated() throws ApisResourceAccessExceptio } @Test - public void testUinAlreadyDeactivated() throws ApisResourceAccessException, PacketManagerException, IOException, JsonProcessingException, JSONException, IdrepoDraftException { + public void testUinAlreadyDeactivated() throws ApisResourceAccessException, PacketManagerException, IOException, + JsonProcessingException, JSONException, IdrepoDraftException, IdrepoDraftReprocessableException { Map fieldsMap = new HashMap<>(); fieldsMap.put("UIN", "123456"); fieldsMap.put("name", "mono"); diff --git a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/code/RegistrationExceptionTypeCode.java b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/code/RegistrationExceptionTypeCode.java index eea08d9c6d0..b1f839ff817 100644 --- a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/code/RegistrationExceptionTypeCode.java +++ b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/code/RegistrationExceptionTypeCode.java @@ -301,6 +301,9 @@ public enum RegistrationExceptionTypeCode { NO_RECORDS_ASSIGNED, MANUAL_VERIFICATION_FAILED, - INTRODUCER_BIOMETRIC_ALL_EXCEPTION_IN_PACKET; + INTRODUCER_BIOMETRIC_ALL_EXCEPTION_IN_PACKET, + + + IDREPO_DRAFT_REPROCESSABLE_EXCEPTION; } \ No newline at end of file diff --git a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/status/util/StatusUtil.java b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/status/util/StatusUtil.java index 8b860e167c3..39090eb52b4 100644 --- a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/status/util/StatusUtil.java +++ b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/status/util/StatusUtil.java @@ -251,18 +251,33 @@ public enum StatusUtil { IDREPO_DRAFT_EXCEPTION(StatusConstants.UIN_GENERATOR_MODULE_FAILED + "008", "Exception occured updating idrepo draft."), + IDREPO_DRAFT_REPROCESSABLE_EXCEPTION(StatusConstants.UIN_GENERATOR_MODULE_FAILED + "009", + "Exception occured updating idrepo draft,Which can be reprocess"), + // Biometric extraction stage BIOMETRIC_EXTRACTION_SUCCESS(StatusConstants.BIOMETRIC_EXTRACTION_MODULE_SUCCESS + "001", "biometric extaction was successful"), BIOMETRIC_EXTRACTION_DRAFT_REQUEST_UNAVAILABLE(StatusConstants.BIOMETRIC_EXTRACTION_MODULE_FAILED + "001", "Draft request is unavaialble in id-repo draft repository."), + BIOMETRIC_EXTRACTION_IDREPO_DRAFT_EXCEPTION(StatusConstants.BIOMETRIC_EXTRACTION_MODULE_FAILED + "002", + "Exception occured updating idrepo draft."), + + BIOMETRIC_EXTRACTION_IDREPO_DRAFT_REPROCESSABLE_EXCEPTION( + StatusConstants.BIOMETRIC_EXTRACTION_MODULE_FAILED + "003", + "Exception occured updating idrepo draft,Which can be reprocess"), FINALIZATION_SUCCESS(StatusConstants.FINALIZATION_MODULE_SUCCESS + "001", "idrepo draft was published successfuly"), FINALIZATION_FAILURE(StatusConstants.FINALIZATION_MODULE_FAILED + "001", "Draft request failed to publish."), - FINALIZATION_DRAFT_REQUEST_UNAVAILABLE(StatusConstants.FINALIZATION_MODULE_FAILED + "001", + FINALIZATION_DRAFT_REQUEST_UNAVAILABLE(StatusConstants.FINALIZATION_MODULE_FAILED + "002", "Draft request is unavaialble in id-repo draft repository."), + FINALIZATION_IDREPO_DRAFT_EXCEPTION(StatusConstants.FINALIZATION_MODULE_FAILED + "003", + "Exception occured updating idrepo draft."), + + FINALIZATION_IDREPO_DRAFT_REPROCESSABLE_EXCEPTION(StatusConstants.FINALIZATION_MODULE_FAILED + "004", + "Exception occured updating idrepo draft,Which can be reprocess"), + // Request handler service // 1)Resident UIN update RESIDENT_UPDATE_SUCCES(StatusConstants.REQUEST_HANDLER_MODULE_SUCCESS + "001", diff --git a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/util/RegistrationExceptionMapperUtil.java b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/util/RegistrationExceptionMapperUtil.java index 88d926adb88..853370d43a1 100644 --- a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/util/RegistrationExceptionMapperUtil.java +++ b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/util/RegistrationExceptionMapperUtil.java @@ -195,6 +195,8 @@ private static Map registrationProcessorRestClientService; - - public boolean idrepoHasDraft(String id) throws ApisResourceAccessException, IdrepoDraftException { - regProcLogger.debug("idrepoHasDraft entry " + id); - - Integer result = registrationProcessorRestClientService.headApi - (ApiName.IDREPOHASDRAFT, Lists.newArrayList(id), null, null); - - if (result == null || (result.intValue() != IDREPO_DRAFT_FOUND && result.intValue() != IDREPO_DRAFT_NOT_FOUND)) { - regProcLogger.error("idrepoHasDraft failed to get result for id " + id + " result received is " + result); - throw new IdrepoDraftException(PlatformErrorMessages.DRAFT_CHECK_FAILED.getCode(), PlatformErrorMessages.DRAFT_CHECK_FAILED.getMessage()); - } - - boolean hasDraft = result != null && result.intValue() == IDREPO_DRAFT_FOUND; - regProcLogger.info("idrepoHasDraft result for id " + id + " is " + hasDraft); - return hasDraft; - } - - public ResponseDTO idrepoGetDraft(String id) throws ApisResourceAccessException { - regProcLogger.debug("idrepoGetDraft entry " + id); - IdResponseDTO idResponseDTO = (IdResponseDTO) registrationProcessorRestClientService.getApi( - ApiName.IDREPOGETDRAFT, Lists.newArrayList(id), Lists.emptyList(), null, IdResponseDTO.class); - - regProcLogger.debug("idrepoGetDraft exit " + id); - return idResponseDTO.getResponse(); - } - - public boolean idrepoCreateDraft(String id, String uin) throws ApisResourceAccessException { - regProcLogger.debug("idrepoCreateDraft entry " + id); - String queryParam = uin != null ? UIN : null; - String queryParamValue = uin != null ? uin : null; - - ResponseWrapper response = (ResponseWrapper) registrationProcessorRestClientService.postApi( - ApiName.IDREPOCREATEDRAFT, Lists.newArrayList(id), queryParam, queryParamValue, null, ResponseWrapper.class); - - return (response.getErrors() == null || response.getErrors().isEmpty()); - } - - public IdResponseDTO idrepoUpdateDraft(String id, String uin, IdRequestDto idRequestDto) throws ApisResourceAccessException, IdrepoDraftException, IOException { - regProcLogger.debug("idrepoUpdateDraft entry " + id); - if (!idrepoHasDraft(id)) { - regProcLogger.info("Existing draft not found for id " + id + ". Creating new draft."); - idrepoCreateDraft(id, uin); - } else { - regProcLogger.info("Existing draft found for id " + id + ". Updating uin in demographic identity."); - ResponseDTO responseDTO = idrepoGetDraft(id); - RequestDto requestDto = new RequestDto(); - requestDto.setAnonymousProfile(responseDTO.getAnonymousProfile()); - requestDto.setBiometricReferenceId(responseDTO.getBiometricReferenceId()); - JSONObject existingIdentity = mapper.readValue(mapper.writeValueAsString(responseDTO.getIdentity()), JSONObject.class); - JSONObject newIdentity = mapper.readValue(mapper.writeValueAsString(idRequestDto.getRequest().getIdentity()), JSONObject.class); - newIdentity.put(UIN, existingIdentity.get(UIN)); - idRequestDto.getRequest().setIdentity(newIdentity); - requestDto.setRegistrationId(responseDTO.getRegistrationId()); - requestDto.setStatus(responseDTO.getStatus()); - requestDto.setUin(responseDTO.getUin()); - idRequestDto.setRequest(requestDto); - - } - - IdResponseDTO response = (IdResponseDTO) registrationProcessorRestClientService.patchApi( - ApiName.IDREPOUPDATEDRAFT, Lists.newArrayList(id), null, null, idRequestDto, IdResponseDTO.class); - if (response.getErrors() != null && !response.getErrors().isEmpty()) { - regProcLogger.error("Error occured while updating draft for id : " + id, response.getErrors().iterator().next().toString()); - throw new IdrepoDraftException(response.getErrors().iterator().next().getErrorCode(), - response.getErrors().iterator().next().getMessage()); - } - - regProcLogger.debug("idrepoUpdateDraft exit " + id); - return response; - } - - public IdResponseDTO idrepoPublishDraft(String id) throws ApisResourceAccessException, IdrepoDraftException { - regProcLogger.debug("idrepoPublishDraft entry " + id); - List pathsegments=new ArrayList(); - pathsegments.add(id); - IdResponseDTO response = (IdResponseDTO) registrationProcessorRestClientService. - getApi(ApiName.IDREPOPUBLISHDRAFT, pathsegments, "", "", IdResponseDTO.class); - if (response.getErrors() != null && !response.getErrors().isEmpty()) { - regProcLogger.error("Error occured while updating draft for id : " + id, response.getErrors().iterator().next().toString()); - throw new IdrepoDraftException(response.getErrors().iterator().next().getErrorCode(), - response.getErrors().iterator().next().getMessage()); - } - - regProcLogger.debug("idrepoPublishDraft exit " + id); - return response; - } -} +package io.mosip.registration.processor.packet.manager.idreposervice; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import org.assertj.core.util.Lists; +import org.json.simple.JSONObject; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import com.fasterxml.jackson.databind.ObjectMapper; + +import io.mosip.kernel.core.logger.spi.Logger; +import io.mosip.registration.processor.core.code.ApiName; +import io.mosip.registration.processor.core.common.rest.dto.ErrorDTO; +import io.mosip.registration.processor.core.exception.ApisResourceAccessException; +import io.mosip.registration.processor.core.exception.util.PlatformErrorMessages; +import io.mosip.registration.processor.core.http.ResponseWrapper; +import io.mosip.registration.processor.core.logger.RegProcessorLogger; +import io.mosip.registration.processor.core.spi.restclient.RegistrationProcessorRestClientService; +import io.mosip.registration.processor.packet.manager.dto.IdRequestDto; +import io.mosip.registration.processor.packet.manager.dto.IdResponseDTO; +import io.mosip.registration.processor.packet.manager.dto.RequestDto; +import io.mosip.registration.processor.packet.manager.dto.ResponseDTO; +import io.mosip.registration.processor.packet.manager.exception.IdrepoDraftException; +import io.mosip.registration.processor.packet.manager.exception.IdrepoDraftReprocessableException; + +@Service +public class IdrepoDraftService { + + private static final String UIN = "UIN"; + private static final Integer IDREPO_DRAFT_FOUND = 200; + private static final Integer IDREPO_DRAFT_NOT_FOUND = 204; + private static Logger regProcLogger = RegProcessorLogger.getLogger(IdrepoDraftService.class); + private static final String ID_REPO_KEY_MANAGER_ERROR = "IDR-IDS-003"; + + @Autowired + private ObjectMapper mapper; + + /** The registration processor rest client service. */ + @Autowired + private RegistrationProcessorRestClientService registrationProcessorRestClientService; + + public boolean idrepoHasDraft(String id) throws ApisResourceAccessException, IdrepoDraftException { + regProcLogger.debug("idrepoHasDraft entry " + id); + + Integer result = registrationProcessorRestClientService.headApi + (ApiName.IDREPOHASDRAFT, Lists.newArrayList(id), null, null); + + if (result == null || (result.intValue() != IDREPO_DRAFT_FOUND && result.intValue() != IDREPO_DRAFT_NOT_FOUND)) { + regProcLogger.error("idrepoHasDraft failed to get result for id " + id + " result received is " + result); + throw new IdrepoDraftException(PlatformErrorMessages.DRAFT_CHECK_FAILED.getCode(), PlatformErrorMessages.DRAFT_CHECK_FAILED.getMessage()); + } + + boolean hasDraft = result != null && result.intValue() == IDREPO_DRAFT_FOUND; + regProcLogger.info("idrepoHasDraft result for id " + id + " is " + hasDraft); + return hasDraft; + } + + public ResponseDTO idrepoGetDraft(String id) throws ApisResourceAccessException { + regProcLogger.debug("idrepoGetDraft entry " + id); + IdResponseDTO idResponseDTO = (IdResponseDTO) registrationProcessorRestClientService.getApi( + ApiName.IDREPOGETDRAFT, Lists.newArrayList(id), Lists.emptyList(), null, IdResponseDTO.class); + + regProcLogger.debug("idrepoGetDraft exit " + id); + return idResponseDTO.getResponse(); + } + + public boolean idrepoCreateDraft(String id, String uin) throws ApisResourceAccessException { + regProcLogger.debug("idrepoCreateDraft entry " + id); + String queryParam = uin != null ? UIN : null; + String queryParamValue = uin != null ? uin : null; + + ResponseWrapper response = (ResponseWrapper) registrationProcessorRestClientService.postApi( + ApiName.IDREPOCREATEDRAFT, Lists.newArrayList(id), queryParam, queryParamValue, null, ResponseWrapper.class); + + return (response.getErrors() == null || response.getErrors().isEmpty()); + } + + public IdResponseDTO idrepoUpdateDraft(String id, String uin, IdRequestDto idRequestDto) + throws ApisResourceAccessException, IdrepoDraftException, IOException, IdrepoDraftReprocessableException { + regProcLogger.debug("idrepoUpdateDraft entry " + id); + if (!idrepoHasDraft(id)) { + regProcLogger.info("Existing draft not found for id " + id + ". Creating new draft."); + idrepoCreateDraft(id, uin); + } else { + regProcLogger.info("Existing draft found for id " + id + ". Updating uin in demographic identity."); + ResponseDTO responseDTO = idrepoGetDraft(id); + RequestDto requestDto = new RequestDto(); + requestDto.setAnonymousProfile(responseDTO.getAnonymousProfile()); + requestDto.setBiometricReferenceId(responseDTO.getBiometricReferenceId()); + JSONObject existingIdentity = mapper.readValue(mapper.writeValueAsString(responseDTO.getIdentity()), JSONObject.class); + JSONObject newIdentity = mapper.readValue(mapper.writeValueAsString(idRequestDto.getRequest().getIdentity()), JSONObject.class); + newIdentity.put(UIN, existingIdentity.get(UIN)); + idRequestDto.getRequest().setIdentity(newIdentity); + requestDto.setRegistrationId(responseDTO.getRegistrationId()); + requestDto.setStatus(responseDTO.getStatus()); + requestDto.setUin(responseDTO.getUin()); + idRequestDto.setRequest(requestDto); + + } + + IdResponseDTO response = (IdResponseDTO) registrationProcessorRestClientService.patchApi( + ApiName.IDREPOUPDATEDRAFT, Lists.newArrayList(id), null, null, idRequestDto, IdResponseDTO.class); + if (response.getErrors() != null && !response.getErrors().isEmpty()) { + ErrorDTO error = response.getErrors().get(0); + regProcLogger.error("Error occured while updating draft for id : " + id, error.toString()); + if (response.getErrors().get(0).getErrorCode().equalsIgnoreCase(ID_REPO_KEY_MANAGER_ERROR)) { + throw new IdrepoDraftReprocessableException(error.getErrorCode(), error.getMessage()); + } else { + throw new IdrepoDraftException(error.getErrorCode(), error.getMessage()); + } + } + + regProcLogger.debug("idrepoUpdateDraft exit " + id); + return response; + } + + public IdResponseDTO idrepoPublishDraft(String id) + throws ApisResourceAccessException, IdrepoDraftException, IdrepoDraftReprocessableException { + regProcLogger.debug("idrepoPublishDraft entry " + id); + List pathsegments=new ArrayList(); + pathsegments.add(id); + IdResponseDTO response = (IdResponseDTO) registrationProcessorRestClientService. + getApi(ApiName.IDREPOPUBLISHDRAFT, pathsegments, "", "", IdResponseDTO.class); + if (response.getErrors() != null && !response.getErrors().isEmpty()) { + ErrorDTO error = response.getErrors().get(0); + regProcLogger.error("Error occured while updating draft for id : " + id, error.toString()); + if (response.getErrors().get(0).getErrorCode().equalsIgnoreCase(ID_REPO_KEY_MANAGER_ERROR)) { + throw new IdrepoDraftReprocessableException(error.getErrorCode(), error.getMessage()); + } else { + throw new IdrepoDraftException(error.getErrorCode(), error.getMessage()); + } + + } + + regProcLogger.debug("idrepoPublishDraft exit " + id); + return response; + } +} diff --git a/registration-processor/registration-processor-packet-manager/src/test/java/io/mosip/registration/processor/packet/manager/service/impl/test/IdrepoDraftServiceTest.java b/registration-processor/registration-processor-packet-manager/src/test/java/io/mosip/registration/processor/packet/manager/service/impl/test/IdrepoDraftServiceTest.java index f3f5f082658..1925eebd183 100644 --- a/registration-processor/registration-processor-packet-manager/src/test/java/io/mosip/registration/processor/packet/manager/service/impl/test/IdrepoDraftServiceTest.java +++ b/registration-processor/registration-processor-packet-manager/src/test/java/io/mosip/registration/processor/packet/manager/service/impl/test/IdrepoDraftServiceTest.java @@ -1,203 +1,207 @@ -package io.mosip.registration.processor.packet.manager.service.impl.test; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.when; - -import java.io.IOException; - -import org.apache.commons.io.IOUtils; -import org.assertj.core.util.Lists; -import org.json.simple.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; - -import com.fasterxml.jackson.databind.ObjectMapper; - -import io.mosip.kernel.core.util.HMACUtils2; -import io.mosip.registration.processor.core.code.ApiName; -import io.mosip.registration.processor.core.common.rest.dto.ErrorDTO; -import io.mosip.registration.processor.core.exception.ApisResourceAccessException; -import io.mosip.registration.processor.core.http.ResponseWrapper; -import io.mosip.registration.processor.core.spi.restclient.RegistrationProcessorRestClientService; -import io.mosip.registration.processor.packet.manager.dto.IdRequestDto; -import io.mosip.registration.processor.packet.manager.dto.IdResponseDTO; -import io.mosip.registration.processor.packet.manager.dto.RequestDto; -import io.mosip.registration.processor.packet.manager.dto.ResponseDTO; -import io.mosip.registration.processor.packet.manager.exception.IdrepoDraftException; -import io.mosip.registration.processor.packet.manager.idreposervice.IdrepoDraftService; - -@RunWith(PowerMockRunner.class) -@PrepareForTest({ IOUtils.class, HMACUtils2.class }) -@PowerMockIgnore({"com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "javax.management.*", "javax.net.ssl.*" }) -public class IdrepoDraftServiceTest { - - @InjectMocks - private IdrepoDraftService idrepoDraftService = new IdrepoDraftService(); - - @Mock - private RegistrationProcessorRestClientService registrationProcessorRestClientService; - - @Mock - private ObjectMapper mapper; - - private IdResponseDTO idResponseDTO; - - private String ID = "12345689"; - - @Before - public void setup() throws IOException { - ResponseDTO responseDTO = new ResponseDTO(); - responseDTO.setStatus("ACTIVATED"); - responseDTO.setRegistrationId(ID); - - JSONObject jsonObject = new JSONObject(); - jsonObject.put("UIN", "1234"); - responseDTO.setIdentity(jsonObject); - - idResponseDTO = new IdResponseDTO(); - idResponseDTO.setErrors(null); - idResponseDTO.setId("id.uin.update"); - idResponseDTO.setResponse(responseDTO); - - when(mapper.writeValueAsString(any())).thenReturn("string"); - when(mapper.readValue("string", JSONObject.class)).thenReturn(jsonObject); - - } - - @Test - public void idrepoDraftPresentTest() throws ApisResourceAccessException, IdrepoDraftException { - - when(registrationProcessorRestClientService.headApi - (ApiName.IDREPOHASDRAFT, Lists.newArrayList(ID), null, null)).thenReturn(200); - - boolean result = idrepoDraftService.idrepoHasDraft(ID); - - assertTrue(result); - } - - @Test - public void idrepoDraftNotPresentTest() throws ApisResourceAccessException, IdrepoDraftException { - - when(registrationProcessorRestClientService.headApi - (ApiName.IDREPOHASDRAFT, Lists.newArrayList(ID), null, null)).thenReturn(204); - - boolean result = idrepoDraftService.idrepoHasDraft(ID); - - assertFalse(result); - } - - @Test(expected = IdrepoDraftException.class) - public void idrepoDraftCheckExceptionTest() throws ApisResourceAccessException, IdrepoDraftException { - - when(registrationProcessorRestClientService.headApi - (ApiName.IDREPOHASDRAFT, Lists.newArrayList(ID), null, null)).thenReturn(500); - - idrepoDraftService.idrepoHasDraft(ID); - - } - - @Test - public void idrepoGetDraftSuccessTest() throws ApisResourceAccessException, IdrepoDraftException { - - when(registrationProcessorRestClientService.getApi( - ApiName.IDREPOGETDRAFT, Lists.newArrayList(ID), Lists.emptyList(), null, IdResponseDTO.class)).thenReturn(idResponseDTO); - - ResponseDTO result = idrepoDraftService.idrepoGetDraft(ID); - - assertTrue(result.getRegistrationId().equals(ID)); - } - - @Test - public void idrepoPublishDraftSuccessTest() throws ApisResourceAccessException, IdrepoDraftException { - - when(registrationProcessorRestClientService.getApi( - ApiName.IDREPOPUBLISHDRAFT, Lists.newArrayList(ID), "", "", IdResponseDTO.class)).thenReturn(idResponseDTO); - - IdResponseDTO result = idrepoDraftService.idrepoPublishDraft(ID); - - assertTrue(result.getResponse().getRegistrationId().equals(ID)); - } - - @Test(expected = IdrepoDraftException.class) - public void idrepoPublishDraftExceptionTest() throws ApisResourceAccessException, IdrepoDraftException { - RequestDto requestDto = new RequestDto(); - requestDto.setIdentity(idResponseDTO.getResponse().getIdentity()); - IdRequestDto idRequestDto = new IdRequestDto(); - idRequestDto.setRequest(requestDto); - - ErrorDTO errorDTO = new ErrorDTO(); - errorDTO.setMessage("ERROR"); - errorDTO.setErrorCode("ERROR"); - IdResponseDTO idResponseDTO1 = new IdResponseDTO(); - idResponseDTO1.setErrors(Lists.newArrayList(errorDTO)); - when(registrationProcessorRestClientService.getApi( - ApiName.IDREPOPUBLISHDRAFT, Lists.newArrayList(ID), "", "", IdResponseDTO.class)).thenReturn(idResponseDTO1); - - idrepoDraftService.idrepoPublishDraft(ID); - } - - @Test - public void idrepoCreateDraftSuccessTest() throws ApisResourceAccessException, IdrepoDraftException { - ResponseWrapper responseWrapper = new ResponseWrapper(); - - when(registrationProcessorRestClientService.postApi( - ApiName.IDREPOCREATEDRAFT, Lists.newArrayList(ID), null, null, null, ResponseWrapper.class)).thenReturn(responseWrapper); - - boolean result = idrepoDraftService.idrepoCreateDraft(ID, null); - - assertTrue(result); - } - - @Test - public void idrepoUpdateDraftSuccessTest() throws ApisResourceAccessException, IdrepoDraftException, IOException { - RequestDto requestDto = new RequestDto(); - requestDto.setIdentity(idResponseDTO.getResponse().getIdentity()); - IdRequestDto idRequestDto = new IdRequestDto(); - idRequestDto.setRequest(requestDto); - - when(registrationProcessorRestClientService.headApi - (ApiName.IDREPOHASDRAFT, Lists.newArrayList(ID), null, null)).thenReturn(200); - when(registrationProcessorRestClientService.getApi( - ApiName.IDREPOGETDRAFT, Lists.newArrayList(ID), Lists.emptyList(), null, IdResponseDTO.class)).thenReturn(idResponseDTO); - when(registrationProcessorRestClientService.patchApi( - any(), any(), any(), any(), any(), any())).thenReturn(idResponseDTO); - - IdResponseDTO result = idrepoDraftService.idrepoUpdateDraft(ID, null, idRequestDto); - - assertTrue(result.getResponse().getRegistrationId().equals(ID)); - } - - @Test(expected = IdrepoDraftException.class) - public void idrepoUpdateDraftExceptionTest() throws ApisResourceAccessException, IdrepoDraftException, IOException { - RequestDto requestDto = new RequestDto(); - requestDto.setIdentity(idResponseDTO.getResponse().getIdentity()); - IdRequestDto idRequestDto = new IdRequestDto(); - idRequestDto.setRequest(requestDto); - - ErrorDTO errorDTO = new ErrorDTO(); - errorDTO.setMessage("ERROR"); - errorDTO.setErrorCode("ERROR"); - IdResponseDTO idResponseDTO1 = new IdResponseDTO(); - idResponseDTO1.setErrors(Lists.newArrayList(errorDTO)); - - when(registrationProcessorRestClientService.headApi - (ApiName.IDREPOHASDRAFT, Lists.newArrayList(ID), null, null)).thenReturn(200); - when(registrationProcessorRestClientService.getApi( - ApiName.IDREPOGETDRAFT, Lists.newArrayList(ID), Lists.emptyList(), null, IdResponseDTO.class)).thenReturn(idResponseDTO); - when(registrationProcessorRestClientService.patchApi( - any(), any(), any(), any(), any(), any())).thenReturn(idResponseDTO1); - - idrepoDraftService.idrepoUpdateDraft(ID, null, idRequestDto); - - } - - -} +package io.mosip.registration.processor.packet.manager.service.impl.test; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.when; + +import java.io.IOException; + +import org.apache.commons.io.IOUtils; +import org.assertj.core.util.Lists; +import org.json.simple.JSONObject; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import com.fasterxml.jackson.databind.ObjectMapper; + +import io.mosip.kernel.core.util.HMACUtils2; +import io.mosip.registration.processor.core.code.ApiName; +import io.mosip.registration.processor.core.common.rest.dto.ErrorDTO; +import io.mosip.registration.processor.core.exception.ApisResourceAccessException; +import io.mosip.registration.processor.core.http.ResponseWrapper; +import io.mosip.registration.processor.core.spi.restclient.RegistrationProcessorRestClientService; +import io.mosip.registration.processor.packet.manager.dto.IdRequestDto; +import io.mosip.registration.processor.packet.manager.dto.IdResponseDTO; +import io.mosip.registration.processor.packet.manager.dto.RequestDto; +import io.mosip.registration.processor.packet.manager.dto.ResponseDTO; +import io.mosip.registration.processor.packet.manager.exception.IdrepoDraftException; +import io.mosip.registration.processor.packet.manager.exception.IdrepoDraftReprocessableException; +import io.mosip.registration.processor.packet.manager.idreposervice.IdrepoDraftService; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({ IOUtils.class, HMACUtils2.class }) +@PowerMockIgnore({"com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "javax.management.*", "javax.net.ssl.*" }) +public class IdrepoDraftServiceTest { + + @InjectMocks + private IdrepoDraftService idrepoDraftService = new IdrepoDraftService(); + + @Mock + private RegistrationProcessorRestClientService registrationProcessorRestClientService; + + @Mock + private ObjectMapper mapper; + + private IdResponseDTO idResponseDTO; + + private String ID = "12345689"; + + @Before + public void setup() throws IOException { + ResponseDTO responseDTO = new ResponseDTO(); + responseDTO.setStatus("ACTIVATED"); + responseDTO.setRegistrationId(ID); + + JSONObject jsonObject = new JSONObject(); + jsonObject.put("UIN", "1234"); + responseDTO.setIdentity(jsonObject); + + idResponseDTO = new IdResponseDTO(); + idResponseDTO.setErrors(null); + idResponseDTO.setId("id.uin.update"); + idResponseDTO.setResponse(responseDTO); + + when(mapper.writeValueAsString(any())).thenReturn("string"); + when(mapper.readValue("string", JSONObject.class)).thenReturn(jsonObject); + + } + + @Test + public void idrepoDraftPresentTest() throws ApisResourceAccessException, IdrepoDraftException { + + when(registrationProcessorRestClientService.headApi + (ApiName.IDREPOHASDRAFT, Lists.newArrayList(ID), null, null)).thenReturn(200); + + boolean result = idrepoDraftService.idrepoHasDraft(ID); + + assertTrue(result); + } + + @Test + public void idrepoDraftNotPresentTest() throws ApisResourceAccessException, IdrepoDraftException { + + when(registrationProcessorRestClientService.headApi + (ApiName.IDREPOHASDRAFT, Lists.newArrayList(ID), null, null)).thenReturn(204); + + boolean result = idrepoDraftService.idrepoHasDraft(ID); + + assertFalse(result); + } + + @Test(expected = IdrepoDraftException.class) + public void idrepoDraftCheckExceptionTest() throws ApisResourceAccessException, IdrepoDraftException { + + when(registrationProcessorRestClientService.headApi + (ApiName.IDREPOHASDRAFT, Lists.newArrayList(ID), null, null)).thenReturn(500); + + idrepoDraftService.idrepoHasDraft(ID); + + } + + @Test + public void idrepoGetDraftSuccessTest() throws ApisResourceAccessException, IdrepoDraftException { + + when(registrationProcessorRestClientService.getApi( + ApiName.IDREPOGETDRAFT, Lists.newArrayList(ID), Lists.emptyList(), null, IdResponseDTO.class)).thenReturn(idResponseDTO); + + ResponseDTO result = idrepoDraftService.idrepoGetDraft(ID); + + assertTrue(result.getRegistrationId().equals(ID)); + } + + @Test + public void idrepoPublishDraftSuccessTest() throws ApisResourceAccessException, IdrepoDraftException, IdrepoDraftReprocessableException { + + when(registrationProcessorRestClientService.getApi( + ApiName.IDREPOPUBLISHDRAFT, Lists.newArrayList(ID), "", "", IdResponseDTO.class)).thenReturn(idResponseDTO); + + IdResponseDTO result = idrepoDraftService.idrepoPublishDraft(ID); + + assertTrue(result.getResponse().getRegistrationId().equals(ID)); + } + + @Test(expected = IdrepoDraftException.class) + public void idrepoPublishDraftExceptionTest() + throws ApisResourceAccessException, IdrepoDraftException, IdrepoDraftReprocessableException { + RequestDto requestDto = new RequestDto(); + requestDto.setIdentity(idResponseDTO.getResponse().getIdentity()); + IdRequestDto idRequestDto = new IdRequestDto(); + idRequestDto.setRequest(requestDto); + + ErrorDTO errorDTO = new ErrorDTO(); + errorDTO.setMessage("ERROR"); + errorDTO.setErrorCode("ERROR"); + IdResponseDTO idResponseDTO1 = new IdResponseDTO(); + idResponseDTO1.setErrors(Lists.newArrayList(errorDTO)); + when(registrationProcessorRestClientService.getApi( + ApiName.IDREPOPUBLISHDRAFT, Lists.newArrayList(ID), "", "", IdResponseDTO.class)).thenReturn(idResponseDTO1); + + idrepoDraftService.idrepoPublishDraft(ID); + } + + @Test + public void idrepoCreateDraftSuccessTest() throws ApisResourceAccessException, IdrepoDraftException { + ResponseWrapper responseWrapper = new ResponseWrapper(); + + when(registrationProcessorRestClientService.postApi( + ApiName.IDREPOCREATEDRAFT, Lists.newArrayList(ID), null, null, null, ResponseWrapper.class)).thenReturn(responseWrapper); + + boolean result = idrepoDraftService.idrepoCreateDraft(ID, null); + + assertTrue(result); + } + + @Test + public void idrepoUpdateDraftSuccessTest() + throws ApisResourceAccessException, IdrepoDraftException, IOException, IdrepoDraftReprocessableException { + RequestDto requestDto = new RequestDto(); + requestDto.setIdentity(idResponseDTO.getResponse().getIdentity()); + IdRequestDto idRequestDto = new IdRequestDto(); + idRequestDto.setRequest(requestDto); + + when(registrationProcessorRestClientService.headApi + (ApiName.IDREPOHASDRAFT, Lists.newArrayList(ID), null, null)).thenReturn(200); + when(registrationProcessorRestClientService.getApi( + ApiName.IDREPOGETDRAFT, Lists.newArrayList(ID), Lists.emptyList(), null, IdResponseDTO.class)).thenReturn(idResponseDTO); + when(registrationProcessorRestClientService.patchApi( + any(), any(), any(), any(), any(), any())).thenReturn(idResponseDTO); + + IdResponseDTO result = idrepoDraftService.idrepoUpdateDraft(ID, null, idRequestDto); + + assertTrue(result.getResponse().getRegistrationId().equals(ID)); + } + + @Test(expected = IdrepoDraftException.class) + public void idrepoUpdateDraftExceptionTest() + throws ApisResourceAccessException, IdrepoDraftException, IOException, IdrepoDraftReprocessableException { + RequestDto requestDto = new RequestDto(); + requestDto.setIdentity(idResponseDTO.getResponse().getIdentity()); + IdRequestDto idRequestDto = new IdRequestDto(); + idRequestDto.setRequest(requestDto); + + ErrorDTO errorDTO = new ErrorDTO(); + errorDTO.setMessage("ERROR"); + errorDTO.setErrorCode("ERROR"); + IdResponseDTO idResponseDTO1 = new IdResponseDTO(); + idResponseDTO1.setErrors(Lists.newArrayList(errorDTO)); + + when(registrationProcessorRestClientService.headApi + (ApiName.IDREPOHASDRAFT, Lists.newArrayList(ID), null, null)).thenReturn(200); + when(registrationProcessorRestClientService.getApi( + ApiName.IDREPOGETDRAFT, Lists.newArrayList(ID), Lists.emptyList(), null, IdResponseDTO.class)).thenReturn(idResponseDTO); + when(registrationProcessorRestClientService.patchApi( + any(), any(), any(), any(), any(), any())).thenReturn(idResponseDTO1); + + idrepoDraftService.idrepoUpdateDraft(ID, null, idRequestDto); + + } + + +} From ab30bb02332e55d4ef7f660fe71ac93544aa9e47 Mon Sep 17 00:00:00 2001 From: Sowmya Ujjappa Banakar Date: Mon, 6 Nov 2023 14:13:50 +0530 Subject: [PATCH 13/38] MOSIP-29780 fixed test cases Signed-off-by: Sowmya Ujjappa Banakar --- .../test/BiometricExtractionStageTest.java | 25 +++++++++++++++++++ .../stage/tests/FinalizationStageTest.java | 18 +++++++++++++ .../uigenerator/UinGeneratorStageTest.java | 20 ++++++++++++++- .../impl/test/IdrepoDraftServiceTest.java | 24 ++++++++++++++++++ 4 files changed, 86 insertions(+), 1 deletion(-) diff --git a/registration-processor/core-processor/registration-processor-biometric-extraction-stage/src/test/java/io/mosip/registration/processor/stages/biometric/extraction/stages/test/BiometricExtractionStageTest.java b/registration-processor/core-processor/registration-processor-biometric-extraction-stage/src/test/java/io/mosip/registration/processor/stages/biometric/extraction/stages/test/BiometricExtractionStageTest.java index 2e582565e47..a443b07f2f5 100644 --- a/registration-processor/core-processor/registration-processor-biometric-extraction-stage/src/test/java/io/mosip/registration/processor/stages/biometric/extraction/stages/test/BiometricExtractionStageTest.java +++ b/registration-processor/core-processor/registration-processor-biometric-extraction-stage/src/test/java/io/mosip/registration/processor/stages/biometric/extraction/stages/test/BiometricExtractionStageTest.java @@ -10,6 +10,7 @@ import java.util.List; import org.apache.commons.io.IOUtils; +import org.assertj.core.util.Lists; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -35,6 +36,8 @@ import io.mosip.registration.processor.core.code.EventId; import io.mosip.registration.processor.core.code.EventName; import io.mosip.registration.processor.core.code.EventType; +import io.mosip.registration.processor.core.code.RegistrationExceptionTypeCode; +import io.mosip.registration.processor.core.common.rest.dto.ErrorDTO; import io.mosip.registration.processor.core.constant.RegistrationType; import io.mosip.registration.processor.core.exception.ApisResourceAccessException; import io.mosip.registration.processor.core.http.ResponseWrapper; @@ -331,4 +334,26 @@ public void testBiometricExtractionDraftException() throws Exception { public void testDeployVerticle() { biometricExtractionStage.deployVerticle(); } + + @Test + public void testIdrepoDraftReprocessableException() throws Exception { + MessageDTO messageDTO = new MessageDTO(); + messageDTO.setRid("27847657360002520181210094052"); + messageDTO.setReg_type(RegistrationType.NEW.name()); + messageDTO.setWorkflowInstanceId("123er"); + messageDTO.setIteration(1); + when(registrationStatusMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.IDREPO_DRAFT_REPROCESSABLE_EXCEPTION)) + .thenReturn("REPROCESS"); + ErrorDTO errorDTO = new ErrorDTO(); + errorDTO.setMessage("Failed to either encrypt/decrypt message using Kernel Crypto Manager"); + errorDTO.setErrorCode("IDR-IDS-003"); + IdResponseDTO idResponseDTO1 = new IdResponseDTO(); + idResponseDTO1.setErrors(Lists.newArrayList(errorDTO)); + when(registrationProcessorRestClientService.putApi(any(), any(), anyString(), anyString(), any(), any(), any())) + .thenReturn(idResponseDTO1); + MessageDTO result = biometricExtractionStage.process(messageDTO); + assertTrue(result.getInternalError()); + assertTrue(result.getIsValid()); + } } diff --git a/registration-processor/core-processor/registration-processor-finalization-stage/src/test/java/io/mosip/registration/processor/stages/finalization/stage/tests/FinalizationStageTest.java b/registration-processor/core-processor/registration-processor-finalization-stage/src/test/java/io/mosip/registration/processor/stages/finalization/stage/tests/FinalizationStageTest.java index 5def776c4cd..f559b8ed629 100644 --- a/registration-processor/core-processor/registration-processor-finalization-stage/src/test/java/io/mosip/registration/processor/stages/finalization/stage/tests/FinalizationStageTest.java +++ b/registration-processor/core-processor/registration-processor-finalization-stage/src/test/java/io/mosip/registration/processor/stages/finalization/stage/tests/FinalizationStageTest.java @@ -29,6 +29,7 @@ import io.mosip.registration.processor.core.code.EventId; import io.mosip.registration.processor.core.code.EventName; import io.mosip.registration.processor.core.code.EventType; +import io.mosip.registration.processor.core.code.RegistrationExceptionTypeCode; import io.mosip.registration.processor.core.constant.RegistrationType; import io.mosip.registration.processor.core.exception.ApisResourceAccessException; import io.mosip.registration.processor.core.http.ResponseWrapper; @@ -37,6 +38,7 @@ import io.mosip.registration.processor.packet.manager.dto.IdResponseDTO; import io.mosip.registration.processor.packet.manager.dto.ResponseDTO; import io.mosip.registration.processor.packet.manager.exception.IdrepoDraftException; +import io.mosip.registration.processor.packet.manager.exception.IdrepoDraftReprocessableException; import io.mosip.registration.processor.packet.manager.idreposervice.IdrepoDraftService; import io.mosip.registration.processor.rest.client.audit.builder.AuditLogRequestBuilder; import io.mosip.registration.processor.rest.client.audit.dto.AuditResponseDto; @@ -247,4 +249,20 @@ public void testBiometricExtractionUnknownException() throws Exception { public void testDeployVerticle() { finalizationStage.deployVerticle(); } + + @Test + public void testIdrepoDraftReprocessableException() throws Exception { + MessageDTO messageDTO = new MessageDTO(); + messageDTO.setRid("27847657360002520181210094052"); + messageDTO.setReg_type(RegistrationType.NEW.name()); + messageDTO.setWorkflowInstanceId("123er"); + messageDTO.setIteration(1); + when(registrationStatusMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.IDREPO_DRAFT_REPROCESSABLE_EXCEPTION)) + .thenReturn("REPROCESS"); + when(idrepoDraftService.idrepoPublishDraft(anyString())).thenThrow(IdrepoDraftReprocessableException.class); + MessageDTO result = finalizationStage.process(messageDTO); + assertTrue(result.getInternalError()); + assertTrue(result.getIsValid()); + } } diff --git a/registration-processor/core-processor/registration-processor-uin-generator-stage/src/test/java/io/mosip/registration/processor/stages/uigenerator/UinGeneratorStageTest.java b/registration-processor/core-processor/registration-processor-uin-generator-stage/src/test/java/io/mosip/registration/processor/stages/uigenerator/UinGeneratorStageTest.java index 43a261bf0d4..f3328aafd64 100644 --- a/registration-processor/core-processor/registration-processor-uin-generator-stage/src/test/java/io/mosip/registration/processor/stages/uigenerator/UinGeneratorStageTest.java +++ b/registration-processor/core-processor/registration-processor-uin-generator-stage/src/test/java/io/mosip/registration/processor/stages/uigenerator/UinGeneratorStageTest.java @@ -2413,5 +2413,23 @@ public void testUinUpdationIOExceptionFaliure() throws Exception { assertTrue(result.getInternalError()); assertTrue(result.getIsValid()); } - + + @Test + public void testUinGenerationIDRepoDraftReprocessableException() throws Exception { + MessageDTO messageDTO = new MessageDTO(); + messageDTO.setRid("27847657360002520181210094052"); + messageDTO.setReg_type(RegistrationType.NEW.name()); + + when(registrationStatusMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.IDREPO_DRAFT_REPROCESSABLE_EXCEPTION)) + .thenReturn("REPROCESS"); + when(idrepoDraftService.idrepoUpdateDraft(anyString(), any(), any())) + .thenThrow(IdrepoDraftReprocessableException.class); + when(utility.getRegistrationProcessorMappingJson(MappingJsonConstants.IDENTITY)).thenReturn(identityObj); + when(utility.getRegistrationProcessorMappingJson(MappingJsonConstants.DOCUMENT)).thenReturn(documentObj); + + MessageDTO result = uinGeneratorStage.process(messageDTO); + assertTrue(result.getInternalError()); + assertTrue(result.getIsValid()); + } } \ No newline at end of file diff --git a/registration-processor/registration-processor-packet-manager/src/test/java/io/mosip/registration/processor/packet/manager/service/impl/test/IdrepoDraftServiceTest.java b/registration-processor/registration-processor-packet-manager/src/test/java/io/mosip/registration/processor/packet/manager/service/impl/test/IdrepoDraftServiceTest.java index 1925eebd183..580e2b3c17d 100644 --- a/registration-processor/registration-processor-packet-manager/src/test/java/io/mosip/registration/processor/packet/manager/service/impl/test/IdrepoDraftServiceTest.java +++ b/registration-processor/registration-processor-packet-manager/src/test/java/io/mosip/registration/processor/packet/manager/service/impl/test/IdrepoDraftServiceTest.java @@ -203,5 +203,29 @@ public void idrepoUpdateDraftExceptionTest() } + @Test(expected = IdrepoDraftReprocessableException.class) + public void idrepoDraftReprocessableExceptionTest() + throws ApisResourceAccessException, IdrepoDraftException, IOException, IdrepoDraftReprocessableException { + RequestDto requestDto = new RequestDto(); + requestDto.setIdentity(idResponseDTO.getResponse().getIdentity()); + IdRequestDto idRequestDto = new IdRequestDto(); + idRequestDto.setRequest(requestDto); + + ErrorDTO errorDTO = new ErrorDTO(); + errorDTO.setMessage("Failed to either encrypt/decrypt message using Kernel Crypto Manager"); + errorDTO.setErrorCode("IDR-IDS-003"); + IdResponseDTO idResponseDTO1 = new IdResponseDTO(); + idResponseDTO1.setErrors(Lists.newArrayList(errorDTO)); + + when(registrationProcessorRestClientService.headApi(ApiName.IDREPOHASDRAFT, Lists.newArrayList(ID), null, null)) + .thenReturn(200); + when(registrationProcessorRestClientService.getApi(ApiName.IDREPOGETDRAFT, Lists.newArrayList(ID), + Lists.emptyList(), null, IdResponseDTO.class)).thenReturn(idResponseDTO); + when(registrationProcessorRestClientService.patchApi(any(), any(), any(), any(), any(), any())) + .thenReturn(idResponseDTO1); + + idrepoDraftService.idrepoUpdateDraft(ID, null, idRequestDto); + + } } From d9826467adcbe01cf5210c2f4d775cff954cd7a6 Mon Sep 17 00:00:00 2001 From: Khuddus shariff Date: Mon, 30 Oct 2023 20:15:02 +0530 Subject: [PATCH 14/38] [ MOSIP-27859 ] Adding pkt_cr_dtimes and setting the packet date and time from metadata of the packet Signed-off-by: khuddus shariff --- .../packet/validator/PacketValidateProcessor.java | 10 +++++++++- .../validator/PacketValidateProcessorTest.java | 6 ++++++ .../status/dto/InternalRegistrationStatusDto.java | 11 +++++++++++ .../status/entity/RegistrationStatusEntity.java | 12 ++++++++++++ .../service/impl/RegistrationStatusServiceImpl.java | 2 ++ 5 files changed, 40 insertions(+), 1 deletion(-) diff --git a/registration-processor/pre-processor/registration-processor-packet-validator-stage/src/main/java/io/mosip/registration/processor/stages/packet/validator/PacketValidateProcessor.java b/registration-processor/pre-processor/registration-processor-packet-validator-stage/src/main/java/io/mosip/registration/processor/stages/packet/validator/PacketValidateProcessor.java index 02421e7b7e5..11e70924e56 100644 --- a/registration-processor/pre-processor/registration-processor-packet-validator-stage/src/main/java/io/mosip/registration/processor/stages/packet/validator/PacketValidateProcessor.java +++ b/registration-processor/pre-processor/registration-processor-packet-validator-stage/src/main/java/io/mosip/registration/processor/stages/packet/validator/PacketValidateProcessor.java @@ -4,6 +4,8 @@ import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; import java.util.Arrays; import java.util.Date; import java.util.Map; @@ -168,6 +170,9 @@ public class PacketValidateProcessor { @Autowired private NotificationUtility notificationUtility; + @Value("${mosip.registration.processor.datetime.pattern}") + private String dateformat; + public MessageDTO process(MessageDTO object, String stageName) { TrimExceptionMessage trimMessage = new TrimExceptionMessage(); LogDescription description = new LogDescription(); @@ -188,7 +193,10 @@ public MessageDTO process(MessageDTO object, String stageName) { registrationStatusDto = registrationStatusService.getRegistrationStatus( registrationId, object.getReg_type(), object.getIteration(), object.getWorkflowInstanceId()); - + Map metaInfo = packetManagerService.getMetaInfo( + registrationId, registrationStatusDto.getRegistrationType(), ProviderStageName.PACKET_VALIDATOR); + DateTimeFormatter formatter = DateTimeFormatter.ofPattern(dateformat); + registrationStatusDto.setPacketCreateDateTime(LocalDateTime.parse(metaInfo.get(JsonConstant.CREATIONDATE),formatter)); registrationStatusDto .setLatestTransactionTypeCode(RegistrationTransactionTypeCode.VALIDATE_PACKET.toString()); registrationStatusDto.setRegistrationStageName(stageName); diff --git a/registration-processor/pre-processor/registration-processor-packet-validator-stage/src/test/java/io/mosip/registration/processor/stages/packet/validator/PacketValidateProcessorTest.java b/registration-processor/pre-processor/registration-processor-packet-validator-stage/src/test/java/io/mosip/registration/processor/stages/packet/validator/PacketValidateProcessorTest.java index 4b52a8820a2..b4f858b8762 100644 --- a/registration-processor/pre-processor/registration-processor-packet-validator-stage/src/test/java/io/mosip/registration/processor/stages/packet/validator/PacketValidateProcessorTest.java +++ b/registration-processor/pre-processor/registration-processor-packet-validator-stage/src/test/java/io/mosip/registration/processor/stages/packet/validator/PacketValidateProcessorTest.java @@ -64,6 +64,7 @@ import java.io.IOException; import java.io.InputStream; import java.security.MessageDigest; +import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; @@ -127,6 +128,9 @@ public class PacketValidateProcessorTest { @Mock private NotificationUtility notificationUtility; + + @Mock + DateTimeFormatter dateTimeFormatter; private MessageDTO messageDTO; private String stageName; @@ -136,6 +140,7 @@ public class PacketValidateProcessorTest { @Before public void setup() throws Exception { ReflectionTestUtils.setField(packetValidateProcessor, "notificationTypes", "SMS|EMAIL"); + ReflectionTestUtils.setField(packetValidateProcessor, "dateformat", "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); messageDTO=new MessageDTO(); messageDTO.setRid("123456789"); messageDTO.setInternalError(false); @@ -245,6 +250,7 @@ public void setup() throws Exception { Map metamap = new HashMap<>(); org.json.JSONArray jsonArray = new org.json.JSONArray(); org.json.JSONObject jsonObject1 = new org.json.JSONObject(); + metamap.put("creationDate","2023-10-17T03:01:09.893Z"); jsonObject1.put("preRegistrationId", "12345"); jsonArray.put(0, jsonObject1); metamap.put(JsonConstant.METADATA, jsonArray.toString()); diff --git a/registration-processor/registration-processor-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/dto/InternalRegistrationStatusDto.java b/registration-processor/registration-processor-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/dto/InternalRegistrationStatusDto.java index e045890f79c..5779b35f83f 100644 --- a/registration-processor/registration-processor-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/dto/InternalRegistrationStatusDto.java +++ b/registration-processor/registration-processor-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/dto/InternalRegistrationStatusDto.java @@ -48,6 +48,17 @@ public class InternalRegistrationStatusDto implements Serializable { /** The update date time. */ private LocalDateTime updateDateTime; + /** Packet Created Date and Time**/ + private LocalDateTime packetCreateDateTime; + + public LocalDateTime getPacketCreateDateTime() { + return packetCreateDateTime; + } + + public void setPacketCreateDateTime(LocalDateTime packetCreateDateTime) { + this.packetCreateDateTime = packetCreateDateTime; + } + /** The is deleted. */ private Boolean isDeleted; diff --git a/registration-processor/registration-processor-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/entity/RegistrationStatusEntity.java b/registration-processor/registration-processor-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/entity/RegistrationStatusEntity.java index c44c9eb35f4..0f40de4eaa2 100644 --- a/registration-processor/registration-processor-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/entity/RegistrationStatusEntity.java +++ b/registration-processor/registration-processor-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/entity/RegistrationStatusEntity.java @@ -67,6 +67,18 @@ public class RegistrationStatusEntity extends BaseRegistrationEntity Date: Mon, 6 Nov 2023 17:38:45 +0530 Subject: [PATCH 15/38] [Mosip-27859] [ MOSIP-29896 ] Adding pkt_cr_dtimes and setting the packet date and time from metadata of the packet Signed-off-by: khuddus shariff --- .../validator/PacketValidateProcessor.java | 36 ++++++++-- .../PacketValidateProcessorTest.java | 65 +++++++++++-------- .../exception/util/PlatformErrorMessages.java | 10 +++ 3 files changed, 78 insertions(+), 33 deletions(-) diff --git a/registration-processor/pre-processor/registration-processor-packet-validator-stage/src/main/java/io/mosip/registration/processor/stages/packet/validator/PacketValidateProcessor.java b/registration-processor/pre-processor/registration-processor-packet-validator-stage/src/main/java/io/mosip/registration/processor/stages/packet/validator/PacketValidateProcessor.java index 11e70924e56..ff7708859a8 100644 --- a/registration-processor/pre-processor/registration-processor-packet-validator-stage/src/main/java/io/mosip/registration/processor/stages/packet/validator/PacketValidateProcessor.java +++ b/registration-processor/pre-processor/registration-processor-packet-validator-stage/src/main/java/io/mosip/registration/processor/stages/packet/validator/PacketValidateProcessor.java @@ -6,12 +6,14 @@ import java.nio.charset.StandardCharsets; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; import java.util.Arrays; import java.util.Date; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; +import io.mosip.kernel.core.util.DateUtils; import io.mosip.registration.processor.packet.storage.utils.Utilities; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.exception.ExceptionUtils; @@ -177,7 +179,6 @@ public MessageDTO process(MessageDTO object, String stageName) { TrimExceptionMessage trimMessage = new TrimExceptionMessage(); LogDescription description = new LogDescription(); PacketValidationDto packetValidationDto = new PacketValidationDto(); - InternalRegistrationStatusDto registrationStatusDto = new InternalRegistrationStatusDto(); try { registrationStatusDto @@ -190,13 +191,9 @@ public MessageDTO process(MessageDTO object, String stageName) { "", "PacketValidateProcessor::process()::entry"); registrationId = object.getRid(); packetValidationDto.setTransactionSuccessful(false); - registrationStatusDto = registrationStatusService.getRegistrationStatus( registrationId, object.getReg_type(), object.getIteration(), object.getWorkflowInstanceId()); - Map metaInfo = packetManagerService.getMetaInfo( - registrationId, registrationStatusDto.getRegistrationType(), ProviderStageName.PACKET_VALIDATOR); - DateTimeFormatter formatter = DateTimeFormatter.ofPattern(dateformat); - registrationStatusDto.setPacketCreateDateTime(LocalDateTime.parse(metaInfo.get(JsonConstant.CREATIONDATE),formatter)); + setPacketCreatedDateTime(registrationStatusDto); registrationStatusDto .setLatestTransactionTypeCode(RegistrationTransactionTypeCode.VALIDATE_PACKET.toString()); registrationStatusDto.setRegistrationStageName(stageName); @@ -455,6 +452,33 @@ public MessageDTO process(MessageDTO object, String stageName) { } + + private void setPacketCreatedDateTime(InternalRegistrationStatusDto registrationStatusDto) throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { + try { + Map metaInfo = packetManagerService.getMetaInfo( + registrationStatusDto.getRefId(), registrationStatusDto.getRegistrationType(), ProviderStageName.PACKET_VALIDATOR); + DateTimeFormatter formatter = DateTimeFormatter.ofPattern(dateformat); + String packetCreatedDateTime = metaInfo.get(JsonConstant.CREATIONDATE); + if (packetCreatedDateTime != null && !packetCreatedDateTime.isEmpty()) { + LocalDateTime dateTime = DateUtils.parseToLocalDateTime(packetCreatedDateTime); + registrationStatusDto.setPacketCreateDateTime(dateTime); + } else { + regProcLogger.warn(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + " -- " + registrationStatusDto.getRefId(), + PlatformErrorMessages.RPR_PVM_PACKET_CREATED_DATE_TIME_EMPTY_OR_NULL.getMessage()); + } + } catch (DateTimeParseException e) { + regProcLogger.warn(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + " -- " + registrationStatusDto.getRefId(), + PlatformErrorMessages.RPR_PVM_PACKET_CREATED_DATE_TIME_PARSE_EXCEPTION.getMessage() + e.getMessage()); + }catch (IllegalArgumentException ex) + { + regProcLogger.warn(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + " -- " + registrationStatusDto.getRefId(), + PlatformErrorMessages.RPR_PVM_INVALID_ARGUMENT_EXCEPTION.getMessage() + ex.getMessage()); + } + } + private boolean isValidSupervisorStatus(MessageDTO messageDTO) { SyncRegistrationEntity regEntity = syncRegistrationService.findByWorkflowInstanceId(messageDTO.getWorkflowInstanceId()); if (regEntity.getSupervisorStatus().equalsIgnoreCase(APPROVED)) { diff --git a/registration-processor/pre-processor/registration-processor-packet-validator-stage/src/test/java/io/mosip/registration/processor/stages/packet/validator/PacketValidateProcessorTest.java b/registration-processor/pre-processor/registration-processor-packet-validator-stage/src/test/java/io/mosip/registration/processor/stages/packet/validator/PacketValidateProcessorTest.java index b4f858b8762..db224f2da8d 100644 --- a/registration-processor/pre-processor/registration-processor-packet-validator-stage/src/test/java/io/mosip/registration/processor/stages/packet/validator/PacketValidateProcessorTest.java +++ b/registration-processor/pre-processor/registration-processor-packet-validator-stage/src/test/java/io/mosip/registration/processor/stages/packet/validator/PacketValidateProcessorTest.java @@ -42,13 +42,11 @@ import io.mosip.registration.processor.status.service.SyncRegistrationService; import org.apache.commons.io.IOUtils; import org.json.JSONException; +import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Matchers; -import org.mockito.Mock; -import org.mockito.Mockito; +import org.mockito.*; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; @@ -64,6 +62,7 @@ import java.io.IOException; import java.io.InputStream; import java.security.MessageDigest; +import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.Arrays; @@ -71,11 +70,11 @@ import java.util.List; import java.util.Map; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; + import static org.mockito.ArgumentMatchers.any; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.anyBoolean; +import static org.junit.Assert.*; /** @@ -250,42 +249,54 @@ public void setup() throws Exception { Map metamap = new HashMap<>(); org.json.JSONArray jsonArray = new org.json.JSONArray(); org.json.JSONObject jsonObject1 = new org.json.JSONObject(); + metamap.put(JsonConstant.CREATIONDATE,"2023-10-17T03:01:09.893"); metamap.put("creationDate","2023-10-17T03:01:09.893Z"); jsonObject1.put("preRegistrationId", "12345"); jsonArray.put(0, jsonObject1); metamap.put(JsonConstant.METADATA, jsonArray.toString()); - Mockito.when(packetManagerService.getMetaInfo(anyString(), any(), any())).thenReturn(metamap); - + Mockito.when(packetManagerService.getMetaInfo(any(), any(), any())).thenReturn(metamap); Mockito.when(objectMapper.readValue(anyString(), any(Class.class))).thenReturn(new FieldValue("preRegistrationId", "12345")); - - } - + @Test - public void PacketValidationSuccessTest() { + public void PacketValidationSuccessTest() throws PacketManagerException, ApisResourceAccessException, IOException, JsonProcessingException { + Map metainfo1 = new HashMap<>(); + metainfo1.put(JsonConstant.CREATIONDATE,"2023-10-17T03:01:09.893"); MessageDTO object = packetValidateProcessor.process(messageDTO, stageName); - assertTrue(object.getIsValid()); - assertFalse(object.getInternalError()); + ArgumentCaptor argument = ArgumentCaptor + .forClass(InternalRegistrationStatusDto.class); + Mockito.verify(registrationStatusService,Mockito.atLeastOnce()).updateRegistrationStatus(argument.capture(), Mockito.any(), + Mockito.any()); + Assert.assertEquals(LocalDateTime.parse(metainfo1.get(JsonConstant.CREATIONDATE)), argument.getAllValues().get(0).getPacketCreateDateTime()); + Assert.assertTrue(object.getIsValid()); + Assert.assertFalse(object.getInternalError()); } - + @Test - public void PacketValidationFailureTest() throws PacketValidatorException, ApisResourceAccessException, JsonProcessingException, RegistrationProcessorCheckedException, IOException, PacketManagerException { - registrationStatusDto.setRetryCount(1); - Mockito.when(packetValidator.validate(any(), any(),any())).thenReturn(false); + public void PacketValidationSuccessTestwithPacketCreatedDateTimeNull() throws PacketManagerException, ApisResourceAccessException, IOException, JsonProcessingException { + Map metainfo = new HashMap<>(); + metainfo.put(JsonConstant.CREATIONDATE,null); + Mockito.when(packetManagerService.getMetaInfo(any(), any(), any())).thenReturn(metainfo); MessageDTO object = packetValidateProcessor.process(messageDTO, stageName); - assertFalse(object.getIsValid()); + ArgumentCaptor argument = ArgumentCaptor + .forClass(InternalRegistrationStatusDto.class); + Mockito.verify(registrationStatusService,Mockito.atLeastOnce()).updateRegistrationStatus(argument.capture(), Mockito.any(), + Mockito.any()); + assertEquals(metainfo.get(JsonConstant.CREATIONDATE), argument.getAllValues().get(0).getPacketCreateDateTime()); + assertTrue(object.getIsValid()); assertFalse(object.getInternalError()); } - + @Test - public void invalidSupervisorStatusTest() throws PacketValidatorException { - registrationStatusDto.setRetryCount(1); - regEntity=new SyncRegistrationEntity(); - regEntity.setSupervisorStatus("REJECTED"); - Mockito.when(syncRegistrationService.findByWorkflowInstanceId(any())).thenReturn(regEntity); + public void PacketValidationSuccessTestwithPacketCreatedDateTimeInvalidFormat() throws PacketManagerException, ApisResourceAccessException, IOException, JsonProcessingException { + Map metainfo = new HashMap<>(); + metainfo.put(JsonConstant.CREATIONDATE,"2023-10-1703:01:09.893"); + Mockito.when(packetManagerService.getMetaInfo(any(), any(), any())).thenReturn(metainfo); MessageDTO object = packetValidateProcessor.process(messageDTO, stageName); - assertFalse(object.getIsValid()); - assertFalse(object.getInternalError()); + ArgumentCaptor argument = ArgumentCaptor + .forClass(InternalRegistrationStatusDto.class); + Mockito.verify(registrationStatusService,Mockito.atLeastOnce()).updateRegistrationStatus(argument.capture(),any(),any()); + assertEquals(null, argument.getAllValues().get(0).getPacketCreateDateTime()); } @Test 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 1dadfa1741f..7acdd09892d 100644 --- a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/exception/util/PlatformErrorMessages.java +++ b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/exception/util/PlatformErrorMessages.java @@ -411,6 +411,16 @@ public enum PlatformErrorMessages { RPR_PVM_PACKET_REJECTED(PlatformConstants.RPR_PACKET_VALIDATOR_MODULE + "011", "Rejected by Supervisor"), + RPR_PVM_PACKET_CREATED_DATE_TIME_EMPTY_OR_NULL(PlatformConstants.RPR_PACKET_VALIDATOR_MODULE + "017", + "Packet Created Date time is Null or Empty"), + + RPR_PVM_PACKET_CREATED_DATE_TIME_PARSE_EXCEPTION(PlatformConstants.RPR_PACKET_VALIDATOR_MODULE + "018", + "Packet Created Date time is not in correct format"), + + RPR_PVM_INVALID_ARGUMENT_EXCEPTION(PlatformConstants.RPR_PACKET_VALIDATOR_MODULE + "019", + "Invalid Argument"), + + /** The packet classification failed. */ PACKET_CLASSIFICATION_FAILED(PlatformConstants.RPR_PACKET_CLASSIFIER_MODULE + "000", "Packet Classification failed"), From 6602518467fc7e150baa857ba002d7cedeca12d9 Mon Sep 17 00:00:00 2001 From: khuddus shariff Date: Mon, 6 Nov 2023 21:13:55 +0530 Subject: [PATCH 16/38] [Mosip-27859] [ MOSIP-29896 ] Adding pkt_cr_dtimes and setting the packet date and time from metadata of the packet Signed-off-by: khuddus shariff --- .../PacketValidateProcessorTest.java | 22 +++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/registration-processor/pre-processor/registration-processor-packet-validator-stage/src/test/java/io/mosip/registration/processor/stages/packet/validator/PacketValidateProcessorTest.java b/registration-processor/pre-processor/registration-processor-packet-validator-stage/src/test/java/io/mosip/registration/processor/stages/packet/validator/PacketValidateProcessorTest.java index db224f2da8d..264e8799ab6 100644 --- a/registration-processor/pre-processor/registration-processor-packet-validator-stage/src/test/java/io/mosip/registration/processor/stages/packet/validator/PacketValidateProcessorTest.java +++ b/registration-processor/pre-processor/registration-processor-packet-validator-stage/src/test/java/io/mosip/registration/processor/stages/packet/validator/PacketValidateProcessorTest.java @@ -298,7 +298,15 @@ public void PacketValidationSuccessTestwithPacketCreatedDateTimeInvalidFormat() Mockito.verify(registrationStatusService,Mockito.atLeastOnce()).updateRegistrationStatus(argument.capture(),any(),any()); assertEquals(null, argument.getAllValues().get(0).getPacketCreateDateTime()); } - + + @Test + public void PacketValidationFailureTest() throws PacketValidatorException, ApisResourceAccessException, JsonProcessingException, RegistrationProcessorCheckedException, IOException, PacketManagerException { + registrationStatusDto.setRetryCount(1); + Mockito.when(packetValidator.validate(any(), any(),any())).thenReturn(false); + MessageDTO object = packetValidateProcessor.process(messageDTO, stageName); + assertFalse(object.getIsValid()); + assertFalse(object.getInternalError()); + } @Test public void PacketValidationPacketManagerFailedTest() throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { @@ -310,7 +318,17 @@ public void PacketValidationPacketManagerFailedTest() assertTrue(object.getIsValid()); assertTrue(object.getInternalError()); } - + + @Test + public void invalidSupervisorStatusTest() throws PacketValidatorException { + registrationStatusDto.setRetryCount(1); + regEntity=new SyncRegistrationEntity(); + regEntity.setSupervisorStatus("REJECTED"); + Mockito.when(syncRegistrationService.findByWorkflowInstanceId(any())).thenReturn(regEntity); + MessageDTO object = packetValidateProcessor.process(messageDTO, stageName); + assertFalse(object.getIsValid()); + assertFalse(object.getInternalError()); + } @Test public void PacketValidationParsingFailedTest() throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { From b1310a0d867ac0d6a5b9e80e69287cc61ca96c61 Mon Sep 17 00:00:00 2001 From: Sowmya Ujjappa Banakar <43202851+sowmya695@users.noreply.github.com> Date: Fri, 10 Nov 2023 09:44:43 +0530 Subject: [PATCH 17/38] MOSIP-28185 registration confirmation notification corrected (#1789) * MOSIP-28185 registration confirmation notification corrected Signed-off-by: Sowmya Ujjappa Banakar * MOSIP-28185 code fix for packet validator Signed-off-by: Sowmya Ujjappa Banakar --------- Signed-off-by: Sowmya Ujjappa Banakar Signed-off-by: Sowmya Ujjappa Banakar Co-authored-by: Sowmya Ujjappa Banakar Co-authored-by: Sowmya Ujjappa Banakar --- .../processor/stages/utils/NotificationUtility.java | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/registration-processor/pre-processor/registration-processor-packet-validator-stage/src/main/java/io/mosip/registration/processor/stages/utils/NotificationUtility.java b/registration-processor/pre-processor/registration-processor-packet-validator-stage/src/main/java/io/mosip/registration/processor/stages/utils/NotificationUtility.java index e3c63542a05..92881b9ea38 100644 --- a/registration-processor/pre-processor/registration-processor-packet-validator-stage/src/main/java/io/mosip/registration/processor/stages/utils/NotificationUtility.java +++ b/registration-processor/pre-processor/registration-processor-packet-validator-stage/src/main/java/io/mosip/registration/processor/stages/utils/NotificationUtility.java @@ -155,13 +155,18 @@ public void sendNotification(RegistrationAdditionalInfoDTO registrationAdditiona String nameField = JsonUtil.getJSONValue( JsonUtil.getJSONObject(regProcessorIdentityJson, MappingJsonConstants.NAME), MappingJsonConstants.VALUE); + String[] nameArray = nameField.toString().split(","); for(String preferredLanguage:preferredLanguages) { if (registrationAdditionalInfoDTO.getName() != null) { - attributes.put(nameField , registrationAdditionalInfoDTO.getName()); + attributes.put(nameArray[0] + "_" + preferredLanguage, registrationAdditionalInfoDTO.getName()); } else { - attributes.put(nameField, ""); + attributes.put(nameArray[0] + "_" + preferredLanguage, ""); + } + if (nameArray.length > 1) { + for (int i = 1; i < nameArray.length; i++) { + attributes.put(nameArray[i] + "_" + preferredLanguage, ""); + } } - if (isProcessingSuccess) { type = setNotificationTemplateType(registrationStatusDto, type); } else if (!isValidSupervisorStatus) { From e5cb736a0049733b773e01fac8e32cd4569b65db Mon Sep 17 00:00:00 2001 From: Rakshithb1 <79500257+Rakshithb1@users.noreply.github.com> Date: Wed, 15 Nov 2023 10:58:04 +0530 Subject: [PATCH 18/38] [MOSIP-29918] added db-test.yml (#1792) Signed-off-by: Rakshithb1 --- .github/workflows/db-test.yml | 39 +++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 .github/workflows/db-test.yml diff --git a/.github/workflows/db-test.yml b/.github/workflows/db-test.yml new file mode 100644 index 00000000000..35a2e6a3585 --- /dev/null +++ b/.github/workflows/db-test.yml @@ -0,0 +1,39 @@ +name: PostgreSQL Test + +on: + release: + types: [published] + pull_request: + types: [opened, reopened, synchronize] + paths: + - 'db_scripts/**' + workflow_dispatch: + inputs: + message: + description: 'Message for manually triggering' + required: false + default: 'Triggered for Updates' + type: string + push: + branches: + - '!release-branch' + - release* + - master + - 1.* + - develop* + - MOSIP* + paths: + - 'db_scripts/**' + +jobs: + build-db-test: + strategy: + matrix: + include: + - DB_LOCATION: 'db_scripts/mosip_regprc' + DB_NAME: 'mosip_regprc' + fail-fast: false + name: ${{ matrix.DB_NAME }} + uses: mosip/kattu/.github/workflows/db-test.yml@master + with: + DB_LOCATION: ${{ matrix.DB_LOCATION}} From 32638c58bbdf0a84c23109087b71aee2cf60f063 Mon Sep 17 00:00:00 2001 From: Sowmya Ujjappa Banakar <43202851+sowmya695@users.noreply.github.com> Date: Mon, 11 Sep 2023 12:52:22 +0530 Subject: [PATCH 19/38] MOSIP-28559 trying one approach (#1772) Co-authored-by: Sowmya Ujjappa Banakar Signed-off-by: Monobikash Das --- .../notification/stage/SecurezoneNotificationStage.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/registration-processor/pre-processor/registration-processor-securezone-notification-stage/src/main/java/io/mosip/registration/processor/securezone/notification/stage/SecurezoneNotificationStage.java b/registration-processor/pre-processor/registration-processor-securezone-notification-stage/src/main/java/io/mosip/registration/processor/securezone/notification/stage/SecurezoneNotificationStage.java index 7059daa8f37..0164a57152f 100644 --- a/registration-processor/pre-processor/registration-processor-securezone-notification-stage/src/main/java/io/mosip/registration/processor/securezone/notification/stage/SecurezoneNotificationStage.java +++ b/registration-processor/pre-processor/registration-processor-securezone-notification-stage/src/main/java/io/mosip/registration/processor/securezone/notification/stage/SecurezoneNotificationStage.java @@ -132,7 +132,7 @@ protected String getPropertyPrefix() { @Override public void start() { - router.setRoute(this.postUrl(vertx, MessageBusAddress.SECUREZONE_NOTIFICATION_IN, + router.setRoute(this.postUrl(getVertx(), MessageBusAddress.SECUREZONE_NOTIFICATION_IN, MessageBusAddress.SECUREZONE_NOTIFICATION_OUT)); this.routes(router); this.createServer(router.getRouter(), getPort()); From 6a567c4af2d0d56983d070586f0512438d05304d Mon Sep 17 00:00:00 2001 From: Monobikash Das Date: Tue, 12 Sep 2023 18:25:15 +0530 Subject: [PATCH 20/38] MOSIP-28121 : opencrvs stage funationalities moved to common stage Signed-off-by: Monobikash Das --- .../processor/print/stage/PrintingStage.java | 50 ++++++++++++++++++- .../print/stage/test/PrintingStageTest.java | 5 ++ 2 files changed, 53 insertions(+), 2 deletions(-) diff --git a/registration-processor/post-processor/registration-processor-printing-stage/src/main/java/io/mosip/registration/processor/print/stage/PrintingStage.java b/registration-processor/post-processor/registration-processor-printing-stage/src/main/java/io/mosip/registration/processor/print/stage/PrintingStage.java index 1cdb7be32aa..cbd5e9a7899 100644 --- a/registration-processor/post-processor/registration-processor-printing-stage/src/main/java/io/mosip/registration/processor/print/stage/PrintingStage.java +++ b/registration-processor/post-processor/registration-processor-printing-stage/src/main/java/io/mosip/registration/processor/print/stage/PrintingStage.java @@ -9,6 +9,7 @@ import io.mosip.registration.processor.core.common.rest.dto.ErrorDTO; import io.mosip.registration.processor.core.constant.IdType; import io.mosip.registration.processor.core.constant.LoggerFileConstant; +import io.mosip.registration.processor.core.constant.ProviderStageName; import io.mosip.registration.processor.core.constant.VidType; import io.mosip.registration.processor.core.exception.ApisResourceAccessException; import io.mosip.registration.processor.core.exception.util.PlatformErrorMessages; @@ -33,6 +34,8 @@ import io.mosip.registration.processor.status.dto.RegistrationStatusDto; import io.mosip.registration.processor.status.service.RegistrationStatusService; import org.apache.commons.lang3.exception.ExceptionUtils; +import org.json.JSONArray; +import org.json.JSONException; import org.json.simple.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; @@ -149,6 +152,9 @@ public class PrintingStage extends MosipVerticleAPIManager { @Value("#{T(java.util.Arrays).asList('${mosip.registration.processor.default.issuers:}')}") private List defaultIssuers; + @Value("${mosip.registration.processor.opencrvs.credential.additionalparams}") + private String opencrvsAdditionalParam; + private static String COMMA = ","; private static String HASH_DELIMITER = "#"; @@ -236,7 +242,7 @@ public MessageDTO process(MessageDTO object) { } for (String key : credentialIssuerSet) { String[] parts = key.split(HASH_DELIMITER, 3); - CredentialRequestDto credentialRequestDto = getCredentialRequestDto(regId, parts[0], parts[1], parts[2]); + CredentialRequestDto credentialRequestDto = getCredentialRequestDto(regId, registrationStatusDto.getRegistrationType(), parts[0], parts[1], parts[2]); LocalDateTime localdatetime = LocalDateTime.parse( DateUtils.getUTCCurrentDateTimeString(env.getProperty(DATETIME_PATTERN)), format); requestWrapper.setRequesttime(localdatetime); @@ -362,7 +368,7 @@ public MessageDTO process(MessageDTO object) { return object; } - private CredentialRequestDto getCredentialRequestDto(String regId,String issuerId,String credentialType,String templateTypeCode) { + private CredentialRequestDto getCredentialRequestDto(String regId, String process, String issuerId,String credentialType,String templateTypeCode) { CredentialRequestDto credentialRequestDto = new CredentialRequestDto(); Map additionalAttributes=new HashMap<>(); @@ -376,11 +382,51 @@ private CredentialRequestDto getCredentialRequestDto(String regId,String issuerI credentialRequestDto.setEncryptionKey(generatePin()); additionalAttributes.put("templateTypeCode",templateTypeCode); additionalAttributes.put("registrationId", regId); + getOpencrvsFields(regId, process, issuerId, credentialType, additionalAttributes); credentialRequestDto.setAdditionalData(additionalAttributes); return credentialRequestDto; } + private void getOpencrvsFields(String regId, String process, String issuerId, + String credentialType, Map additionalAttributes) { + try { + JSONArray jArray=new JSONArray(opencrvsAdditionalParam); + for(int i=0;i metaInfo = utilities.getPacketManagerService().getMetaInfo(regId, process, ProviderStageName.PRINTING); + JSONArray metadata = new JSONArray(metaInfo.get("metaData")); + for(int i=0;i Date: Wed, 13 Sep 2023 17:07:52 +0530 Subject: [PATCH 21/38] MOSIP-28121 : renamed print stage to event handler stage Signed-off-by: Monobikash Das --- registration-processor/pom.xml | 12 +- registration-processor/post-processor/pom.xml | 2 +- .../Dockerfile-not-used | 110 +-- .../README.md | 4 +- .../pom.xml | 2 +- .../EventHandlerStageApplication.java} | 8 +- .../eventhandler}/config/PrintConfigBean.java | 4 +- .../stage/EventHandlerStage.java} | 14 +- .../exception/VidNotAvailableException.java | 54 +- .../util/CredentialPartnerUtil.java | 4 +- .../src/main/resources/bootstrap.properties | 64 +- .../src/main/resources/logback.xml | 0 .../print/stage/test/PrintingStageTest.java | 906 +++++++++--------- .../core/constant/ProviderStageName.java | 2 +- .../pom.xml | 2 +- 15 files changed, 594 insertions(+), 594 deletions(-) rename registration-processor/post-processor/{registration-processor-printing-stage => registration-processor-event-handler-stage}/Dockerfile-not-used (97%) rename registration-processor/post-processor/{registration-processor-printing-stage => registration-processor-event-handler-stage}/README.md (59%) rename registration-processor/post-processor/{registration-processor-printing-stage => registration-processor-event-handler-stage}/pom.xml (98%) rename registration-processor/post-processor/{registration-processor-printing-stage/src/main/java/io/mosip/registration/processor/print/PrintStageApplication.java => registration-processor-event-handler-stage/src/main/java/io/mosip/registration/processor/eventhandler/EventHandlerStageApplication.java} (72%) rename registration-processor/post-processor/{registration-processor-printing-stage/src/main/java/io/mosip/registration/processor/print => registration-processor-event-handler-stage/src/main/java/io/mosip/registration/processor/eventhandler}/config/PrintConfigBean.java (65%) rename registration-processor/post-processor/{registration-processor-printing-stage/src/main/java/io/mosip/registration/processor/print/stage/PrintingStage.java => registration-processor-event-handler-stage/src/main/java/io/mosip/registration/processor/eventhandler/stage/EventHandlerStage.java} (98%) rename registration-processor/post-processor/{registration-processor-printing-stage/src/main/java/io/mosip/registration/processor/print => registration-processor-event-handler-stage/src/main/java/io/mosip/registration/processor/eventhandler}/stage/exception/VidNotAvailableException.java (85%) rename registration-processor/post-processor/{registration-processor-printing-stage/src/main/java/io/mosip/registration/processor/print => registration-processor-event-handler-stage/src/main/java/io/mosip/registration/processor/eventhandler}/util/CredentialPartnerUtil.java (98%) rename registration-processor/post-processor/{registration-processor-printing-stage => registration-processor-event-handler-stage}/src/main/resources/bootstrap.properties (98%) rename registration-processor/post-processor/{registration-processor-printing-stage => registration-processor-event-handler-stage}/src/main/resources/logback.xml (100%) rename registration-processor/post-processor/{registration-processor-printing-stage => registration-processor-event-handler-stage}/src/test/java/io/mosip/registrationprocessor/print/stage/test/PrintingStageTest.java (96%) diff --git a/registration-processor/pom.xml b/registration-processor/pom.xml index a3be3369d60..33fddc4b218 100644 --- a/registration-processor/pom.xml +++ b/registration-processor/pom.xml @@ -230,9 +230,9 @@ **/registration/processor/core/queue/impl/*.java, **/registration/processor/core/tracing/*.java, **/registration/processor/message/sender/config/MsgNotificationBeanCofig.java, - **/registration/processor/print/exception/QueueConnectionNotFound.java, + **/registration/processor/eventhandler/exception/QueueConnectionNotFound.java, **/registration/processor/stages/demodedupe/StatusMessage.java, - **/registration/processor/print/service/utility/UINCardConstant.java, + **/registration/processor/eventhandler/service/utility/UINCardConstant.java, **/registration/processor/stages/demodedupe/BiometricValidation.java, **/registration/processor/camel/bridge/MosipBridgeFactory.java, **/registration/processor/manual/verification/stage/ManualVerificationStage.java, @@ -246,16 +246,16 @@ **/registration/processor/packet/storage/dao/PacketInfoDao.java, **/registration/processor/packet/uploader/constants/*.java, **/registration/processor/packet/manager/constant/*.java, - **/registration/processor/print/exception/PrintGlobalExceptionHandler.java, + **/registration/processor/eventhandler/exception/PrintGlobalExceptionHandler.java, **/registration/processor/packet/receiver/constants/*.java, - **/registration/processor/print/service/exception/*.java, - **/registration/processor/print/exception/*.java, + **/registration/processor/eventhandler/service/exception/*.java, + **/registration/processor/eventhandler/exception/*.java, **/registration/processor/packet/uploader/constants/*.java, **/registration/processor/packet/uploader/decryptor/*.java, **/registration/processor/core/abstractverticle/MosipRouter.java, **/registration/processor/packet/uploader/decryptor/*.java, - **/registration/processor/print/service/impl/PrintPostServiceImpl.java, + **/registration/processor/eventhandler/service/impl/PrintPostServiceImpl.java, **/registration/processor/message/sender/constants/*.java, **/registration/processor/core/abstractverticle/BaseHealthCheckModel.java, diff --git a/registration-processor/post-processor/pom.xml b/registration-processor/post-processor/pom.xml index 181c9a8be25..79009ecc58f 100644 --- a/registration-processor/post-processor/pom.xml +++ b/registration-processor/post-processor/pom.xml @@ -16,7 +16,7 @@ registration-processor-message-sender-stage - registration-processor-printing-stage + registration-processor-event-handler-stage registration-processor-registration-transaction-service diff --git a/registration-processor/post-processor/registration-processor-printing-stage/Dockerfile-not-used b/registration-processor/post-processor/registration-processor-event-handler-stage/Dockerfile-not-used similarity index 97% rename from registration-processor/post-processor/registration-processor-printing-stage/Dockerfile-not-used rename to registration-processor/post-processor/registration-processor-event-handler-stage/Dockerfile-not-used index 2c43739a850..772f2dfdf07 100644 --- a/registration-processor/post-processor/registration-processor-printing-stage/Dockerfile-not-used +++ b/registration-processor/post-processor/registration-processor-event-handler-stage/Dockerfile-not-used @@ -1,55 +1,55 @@ -FROM openjdk:11 - -#Uncomment below and Comment above line(i.e. FROM openjdk:8) for OS specific (e.g. Alpine OS ) docker base image -#FROM openjdk:8-jdk-alpine - -# can be passed during Docker build as build time environment for github branch to pickup configuration from. -ARG spring_config_label - -# can be passed during Docker build as build time environment for spring profiles active -ARG active_profile - -# can be passed during Docker build as build time environment for config server URL -ARG spring_config_url - -# can be passed during Docker build as build time environment for glowroot -ARG is_glowroot - -# can be passed during Docker build as build time environment for artifactory URL -ARG artifactory_url - -# environment variable to pass active profile such as DEV, QA etc at docker runtime -ENV active_profile_env=${active_profile} - -# environment variable to pass github branch to pickup configuration from, at docker runtime -ENV spring_config_label_env=${spring_config_label} - -# environment variable to pass github branch to pickup configuration from, at docker runtime -ENV spring_config_label_env=${spring_config_label} - -# environment variable to pass glowroot, at docker runtime -ENV is_glowroot_env=${is_glowroot} - -# environment variable to pass artifactory url, at docker runtime -ENV artifactory_url_env=${artifactory_url} - -# change volume to whichever storage directory you want to use for this container. -VOLUME /home/logs - -COPY ./target/registration-processor-printing-stage-*.jar registration-processor-printing-stage.jar - -CMD if [ "$is_glowroot_env" = "present" ]; then \ - wget "${artifactory_url_env}"/artifactory/libs-release-local/io/mosip/testing/glowroot.zip ; \ - apt-get update && apt-get install -y unzip ; \ - unzip glowroot.zip ; \ - rm -rf glowroot.zip ; \ - - sed -i 's//registration-processor-printing-stage/g' glowroot/glowroot.properties ; \ - java -Dspring.cloud.config.label="${spring_config_label_env}" -Dspring.profiles.active="${active_profile_env}" -Dspring.cloud.config.uri="${spring_config_url_env}" -jar -javaagent:glowroot/glowroot.jar registration-processor-printing-stage.jar ; \ - else \ - java -Dspring.cloud.config.label="${spring_config_label_env}" -Dspring.profiles.active="${active_profile_env}" -Dspring.cloud.config.uri="${spring_config_url_env}" -jar registration-processor-printing-stage.jar ; \ - fi - - -#CMD ["java","-Dspring.cloud.config.label=${spring_config_label_env}","-Dspring.profiles.active=${active_profile_env}","-Dspring.cloud.config.uri=${spring_config_url_env}","-jar","registration-processor-printing-stage.jar"] - +FROM openjdk:11 + +#Uncomment below and Comment above line(i.e. FROM openjdk:8) for OS specific (e.g. Alpine OS ) docker base image +#FROM openjdk:8-jdk-alpine + +# can be passed during Docker build as build time environment for github branch to pickup configuration from. +ARG spring_config_label + +# can be passed during Docker build as build time environment for spring profiles active +ARG active_profile + +# can be passed during Docker build as build time environment for config server URL +ARG spring_config_url + +# can be passed during Docker build as build time environment for glowroot +ARG is_glowroot + +# can be passed during Docker build as build time environment for artifactory URL +ARG artifactory_url + +# environment variable to pass active profile such as DEV, QA etc at docker runtime +ENV active_profile_env=${active_profile} + +# environment variable to pass github branch to pickup configuration from, at docker runtime +ENV spring_config_label_env=${spring_config_label} + +# environment variable to pass github branch to pickup configuration from, at docker runtime +ENV spring_config_label_env=${spring_config_label} + +# environment variable to pass glowroot, at docker runtime +ENV is_glowroot_env=${is_glowroot} + +# environment variable to pass artifactory url, at docker runtime +ENV artifactory_url_env=${artifactory_url} + +# change volume to whichever storage directory you want to use for this container. +VOLUME /home/logs + +COPY ./target/registration-processor-printing-stage-*.jar registration-processor-printing-stage.jar + +CMD if [ "$is_glowroot_env" = "present" ]; then \ + wget "${artifactory_url_env}"/artifactory/libs-release-local/io/mosip/testing/glowroot.zip ; \ + apt-get update && apt-get install -y unzip ; \ + unzip glowroot.zip ; \ + rm -rf glowroot.zip ; \ + + sed -i 's//registration-processor-printing-stage/g' glowroot/glowroot.properties ; \ + java -Dspring.cloud.config.label="${spring_config_label_env}" -Dspring.profiles.active="${active_profile_env}" -Dspring.cloud.config.uri="${spring_config_url_env}" -jar -javaagent:glowroot/glowroot.jar registration-processor-printing-stage.jar ; \ + else \ + java -Dspring.cloud.config.label="${spring_config_label_env}" -Dspring.profiles.active="${active_profile_env}" -Dspring.cloud.config.uri="${spring_config_url_env}" -jar registration-processor-printing-stage.jar ; \ + fi + + +#CMD ["java","-Dspring.cloud.config.label=${spring_config_label_env}","-Dspring.profiles.active=${active_profile_env}","-Dspring.cloud.config.uri=${spring_config_url_env}","-jar","registration-processor-printing-stage.jar"] + diff --git a/registration-processor/post-processor/registration-processor-printing-stage/README.md b/registration-processor/post-processor/registration-processor-event-handler-stage/README.md similarity index 59% rename from registration-processor/post-processor/registration-processor-printing-stage/README.md rename to registration-processor/post-processor/registration-processor-event-handler-stage/README.md index 71b6369e3b6..972ed13d764 100644 --- a/registration-processor/post-processor/registration-processor-printing-stage/README.md +++ b/registration-processor/post-processor/registration-processor-event-handler-stage/README.md @@ -1,7 +1,7 @@ -# Priting Stage +# Event handler Stage ## About -Creates Credential Request for printing systems. +Creates Credential Request for internal/external systems. ## Default context, path, port Refert to [bootstrap properties](src/main/resources/bootstrap.properties) diff --git a/registration-processor/post-processor/registration-processor-printing-stage/pom.xml b/registration-processor/post-processor/registration-processor-event-handler-stage/pom.xml similarity index 98% rename from registration-processor/post-processor/registration-processor-printing-stage/pom.xml rename to registration-processor/post-processor/registration-processor-event-handler-stage/pom.xml index c8a190d5350..225a1f84a19 100644 --- a/registration-processor/post-processor/registration-processor-printing-stage/pom.xml +++ b/registration-processor/post-processor/registration-processor-event-handler-stage/pom.xml @@ -8,7 +8,7 @@ post-processor 1.2.1-SNAPSHOT - registration-processor-printing-stage + registration-processor-event-handler-stage 1.2.1-SNAPSHOT UTF-8 diff --git a/registration-processor/post-processor/registration-processor-printing-stage/src/main/java/io/mosip/registration/processor/print/PrintStageApplication.java b/registration-processor/post-processor/registration-processor-event-handler-stage/src/main/java/io/mosip/registration/processor/eventhandler/EventHandlerStageApplication.java similarity index 72% rename from registration-processor/post-processor/registration-processor-printing-stage/src/main/java/io/mosip/registration/processor/print/PrintStageApplication.java rename to registration-processor/post-processor/registration-processor-event-handler-stage/src/main/java/io/mosip/registration/processor/eventhandler/EventHandlerStageApplication.java index 742d6a00973..fc0eda3ced1 100644 --- a/registration-processor/post-processor/registration-processor-printing-stage/src/main/java/io/mosip/registration/processor/print/PrintStageApplication.java +++ b/registration-processor/post-processor/registration-processor-event-handler-stage/src/main/java/io/mosip/registration/processor/eventhandler/EventHandlerStageApplication.java @@ -1,14 +1,14 @@ -package io.mosip.registration.processor.print; +package io.mosip.registration.processor.eventhandler; import org.springframework.context.annotation.AnnotationConfigApplicationContext; -import io.mosip.registration.processor.print.stage.PrintingStage; +import io.mosip.registration.processor.eventhandler.stage.EventHandlerStage; /** * @author M1048399 * */ -public class PrintStageApplication { +public class EventHandlerStageApplication { public static void main(String[] args) { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); @@ -19,7 +19,7 @@ public static void main(String[] args) { "io.mosip.registration.processor.packet.storage.config"); ctx.refresh(); - PrintingStage printStage = ctx.getBean(PrintingStage.class); + EventHandlerStage printStage = ctx.getBean(EventHandlerStage.class); printStage.deployVerticle(); } diff --git a/registration-processor/post-processor/registration-processor-printing-stage/src/main/java/io/mosip/registration/processor/print/config/PrintConfigBean.java b/registration-processor/post-processor/registration-processor-event-handler-stage/src/main/java/io/mosip/registration/processor/eventhandler/config/PrintConfigBean.java similarity index 65% rename from registration-processor/post-processor/registration-processor-printing-stage/src/main/java/io/mosip/registration/processor/print/config/PrintConfigBean.java rename to registration-processor/post-processor/registration-processor-event-handler-stage/src/main/java/io/mosip/registration/processor/eventhandler/config/PrintConfigBean.java index e00d94694b0..4666ce45128 100644 --- a/registration-processor/post-processor/registration-processor-printing-stage/src/main/java/io/mosip/registration/processor/print/config/PrintConfigBean.java +++ b/registration-processor/post-processor/registration-processor-event-handler-stage/src/main/java/io/mosip/registration/processor/eventhandler/config/PrintConfigBean.java @@ -1,6 +1,6 @@ -package io.mosip.registration.processor.print.config; +package io.mosip.registration.processor.eventhandler.config; -import io.mosip.registration.processor.print.util.CredentialPartnerUtil; +import io.mosip.registration.processor.eventhandler.util.CredentialPartnerUtil; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; diff --git a/registration-processor/post-processor/registration-processor-printing-stage/src/main/java/io/mosip/registration/processor/print/stage/PrintingStage.java b/registration-processor/post-processor/registration-processor-event-handler-stage/src/main/java/io/mosip/registration/processor/eventhandler/stage/EventHandlerStage.java similarity index 98% rename from registration-processor/post-processor/registration-processor-printing-stage/src/main/java/io/mosip/registration/processor/print/stage/PrintingStage.java rename to registration-processor/post-processor/registration-processor-event-handler-stage/src/main/java/io/mosip/registration/processor/eventhandler/stage/EventHandlerStage.java index cbd5e9a7899..2329d5df7ab 100644 --- a/registration-processor/post-processor/registration-processor-printing-stage/src/main/java/io/mosip/registration/processor/print/stage/PrintingStage.java +++ b/registration-processor/post-processor/registration-processor-event-handler-stage/src/main/java/io/mosip/registration/processor/eventhandler/stage/EventHandlerStage.java @@ -1,4 +1,4 @@ -package io.mosip.registration.processor.print.stage; +package io.mosip.registration.processor.eventhandler.stage; import com.fasterxml.jackson.databind.ObjectMapper; import io.mosip.kernel.core.exception.ServiceError; @@ -27,8 +27,8 @@ import io.mosip.registration.processor.core.status.util.TrimExceptionMessage; import io.mosip.registration.processor.core.util.JsonUtil; import io.mosip.registration.processor.packet.storage.utils.Utilities; -import io.mosip.registration.processor.print.stage.exception.VidNotAvailableException; -import io.mosip.registration.processor.print.util.CredentialPartnerUtil; +import io.mosip.registration.processor.eventhandler.stage.exception.VidNotAvailableException; +import io.mosip.registration.processor.eventhandler.util.CredentialPartnerUtil; import io.mosip.registration.processor.rest.client.audit.builder.AuditLogRequestBuilder; import io.mosip.registration.processor.status.dto.InternalRegistrationStatusDto; import io.mosip.registration.processor.status.dto.RegistrationStatusDto; @@ -70,7 +70,7 @@ @ComponentScan(basePackages = { "${mosip.auth.adapter.impl.basepackage}", "io.mosip.registration.processor.core.config", "io.mosip.registration.processor.stages.config", - "io.mosip.registration.processor.print.config", + "io.mosip.registration.processor.eventhandler.config", "io.mosip.registrationprocessor.stages.config", "io.mosip.registration.processor.status.config", "io.mosip.registration.processor.rest.client.config", @@ -78,7 +78,7 @@ "io.mosip.registration.processor.packet.manager.config", "io.mosip.kernel.idobjectvalidator.config", "io.mosip.registration.processor.core.kernel.beans" }) -public class PrintingStage extends MosipVerticleAPIManager { +public class EventHandlerStage extends MosipVerticleAPIManager { private static final String STAGE_PROPERTY_PREFIX = "mosip.regproc.printing."; private Random sr = null; @@ -90,7 +90,7 @@ public class PrintingStage extends MosipVerticleAPIManager { /** The reg proc logger. */ - private static Logger regProcLogger = RegProcessorLogger.getLogger(PrintingStage.class); + private static Logger regProcLogger = RegProcessorLogger.getLogger(EventHandlerStage.class); /** The cluster manager url. */ @Value("${vertx.cluster.configuration}") @@ -411,7 +411,7 @@ private void getOpencrvsFields(String regId, String process, String issuerId, private String getCrvsField(String regId, String process, String additionalAttr){ try { - Map metaInfo = utilities.getPacketManagerService().getMetaInfo(regId, process, ProviderStageName.PRINTING); + Map metaInfo = utilities.getPacketManagerService().getMetaInfo(regId, process, ProviderStageName.EVENT_HANDLER); JSONArray metadata = new JSONArray(metaInfo.get("metaData")); for(int i=0;i getCredentialPartners(String regId, String registrationType, } Map identityFieldValueMap = utilities.getPacketManagerService().getFields(regId, - requiredIdObjectFieldNames, registrationType, ProviderStageName.PRINTING); + requiredIdObjectFieldNames, registrationType, ProviderStageName.EVENT_HANDLER); Map context = new HashMap<>(); for (Map.Entry identityAttribute: identityFieldValueMap.entrySet()) { diff --git a/registration-processor/post-processor/registration-processor-printing-stage/src/main/resources/bootstrap.properties b/registration-processor/post-processor/registration-processor-event-handler-stage/src/main/resources/bootstrap.properties similarity index 98% rename from registration-processor/post-processor/registration-processor-printing-stage/src/main/resources/bootstrap.properties rename to registration-processor/post-processor/registration-processor-event-handler-stage/src/main/resources/bootstrap.properties index 7f48739d8f8..080d4db8b6d 100644 --- a/registration-processor/post-processor/registration-processor-printing-stage/src/main/resources/bootstrap.properties +++ b/registration-processor/post-processor/registration-processor-event-handler-stage/src/main/resources/bootstrap.properties @@ -1,33 +1,33 @@ -spring.cloud.config.uri=localhost -spring.cloud.config.label=master -spring.application.name=application,registration-processor -spring.profiles.active=dev -spring.cloud.config.name=application,registration-processor -registration.processor.identityjson=RegistrationProcessorIdentity.json -registration.processor.demographic.identity=identity -packet.info.storage.service=registration-processor-packet-info-storage-service -config.server.file.storage.uri=${spring.cloud.config.uri}/${packet.info.storage.service}/${spring.profiles.active}/${spring.cloud.config.label}/ -management.endpoints.web.exposure.include=refresh -registration.processor.zone=secure -vertx.cluster.configuration=${spring.cloud.config.uri}/*/${spring.profiles.active}/${spring.cloud.config.label}/hazelcast_${registration.processor.zone}.xml -#management.security.enabled=false -server.port=8099 -server.servlet.path=/registrationprocessor/v1/print-stage - -#disabling health check so that client doesnt try to load properties from sprint config server every -# 5 minutes (should not be done in production) -health.config.enabled=false -eventbus.port=5722 -#Kafka event bus configruations -mosip.regproc.eventbus.kafka.commit.type=${mosip.regproc.printing.eventbus.kafka.commit.type} -mosip.regproc.eventbus.kafka.max.poll.records=${mosip.regproc.printing.eventbus.kafka.max.poll.records} -mosip.regproc.eventbus.kafka.poll.frequency=${mosip.regproc.printing.eventbus.kafka.poll.frequency} -mosip.regproc.eventbus.kafka.group.id=${mosip.regproc.printing.eventbus.kafka.group.id} -mosip.registration.processor.digitalcard.credentialtype=PDFCard -mosip.registration.processor.print.credentialtype=euin -mosip.registration.processor.digitalcard.template=RPR_UIN_CARD_TEMPLATE -mosip.registration.processor.print.template=RPR_UIN_CARD_TEMPLATE -# this property is used to define issuers eg partnerid:credentialType:templateTypeCode -mosip.registration.processor.default.internal.issuers=mpartner-default-digitalcard#PDFCard#RPR_UIN_CARD_TEMPLATE - +spring.cloud.config.uri=localhost +spring.cloud.config.label=master +spring.application.name=application,registration-processor +spring.profiles.active=dev +spring.cloud.config.name=application,registration-processor +registration.processor.identityjson=RegistrationProcessorIdentity.json +registration.processor.demographic.identity=identity +packet.info.storage.service=registration-processor-packet-info-storage-service +config.server.file.storage.uri=${spring.cloud.config.uri}/${packet.info.storage.service}/${spring.profiles.active}/${spring.cloud.config.label}/ +management.endpoints.web.exposure.include=refresh +registration.processor.zone=secure +vertx.cluster.configuration=${spring.cloud.config.uri}/*/${spring.profiles.active}/${spring.cloud.config.label}/hazelcast_${registration.processor.zone}.xml +#management.security.enabled=false +server.port=8099 +server.servlet.path=/registrationprocessor/v1/print-stage + +#disabling health check so that client doesnt try to load properties from sprint config server every +# 5 minutes (should not be done in production) +health.config.enabled=false +eventbus.port=5722 +#Kafka event bus configruations +mosip.regproc.eventbus.kafka.commit.type=${mosip.regproc.printing.eventbus.kafka.commit.type} +mosip.regproc.eventbus.kafka.max.poll.records=${mosip.regproc.printing.eventbus.kafka.max.poll.records} +mosip.regproc.eventbus.kafka.poll.frequency=${mosip.regproc.printing.eventbus.kafka.poll.frequency} +mosip.regproc.eventbus.kafka.group.id=${mosip.regproc.printing.eventbus.kafka.group.id} +mosip.registration.processor.digitalcard.credentialtype=PDFCard +mosip.registration.processor.print.credentialtype=euin +mosip.registration.processor.digitalcard.template=RPR_UIN_CARD_TEMPLATE +mosip.registration.processor.print.template=RPR_UIN_CARD_TEMPLATE +# this property is used to define issuers eg partnerid:credentialType:templateTypeCode +mosip.registration.processor.default.internal.issuers=mpartner-default-digitalcard#PDFCard#RPR_UIN_CARD_TEMPLATE + mosip.registration.processor.default.issuers=mpartner-default-print#euin#RPR_UIN_CARD_TEMPLATE \ No newline at end of file diff --git a/registration-processor/post-processor/registration-processor-printing-stage/src/main/resources/logback.xml b/registration-processor/post-processor/registration-processor-event-handler-stage/src/main/resources/logback.xml similarity index 100% rename from registration-processor/post-processor/registration-processor-printing-stage/src/main/resources/logback.xml rename to registration-processor/post-processor/registration-processor-event-handler-stage/src/main/resources/logback.xml diff --git a/registration-processor/post-processor/registration-processor-printing-stage/src/test/java/io/mosip/registrationprocessor/print/stage/test/PrintingStageTest.java b/registration-processor/post-processor/registration-processor-event-handler-stage/src/test/java/io/mosip/registrationprocessor/print/stage/test/PrintingStageTest.java similarity index 96% rename from registration-processor/post-processor/registration-processor-printing-stage/src/test/java/io/mosip/registrationprocessor/print/stage/test/PrintingStageTest.java rename to registration-processor/post-processor/registration-processor-event-handler-stage/src/test/java/io/mosip/registrationprocessor/print/stage/test/PrintingStageTest.java index fae7a3bd405..7d8c67487e2 100644 --- a/registration-processor/post-processor/registration-processor-printing-stage/src/test/java/io/mosip/registrationprocessor/print/stage/test/PrintingStageTest.java +++ b/registration-processor/post-processor/registration-processor-event-handler-stage/src/test/java/io/mosip/registrationprocessor/print/stage/test/PrintingStageTest.java @@ -1,454 +1,454 @@ -package io.mosip.registrationprocessor.print.stage.test; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.when; - -import java.io.IOException; -import java.lang.reflect.Field; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.json.simple.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; -import org.springframework.context.annotation.PropertySource; -import org.springframework.core.env.Environment; -import org.springframework.http.MediaType; -import org.springframework.test.util.ReflectionTestUtils; - -import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.databind.JsonMappingException; -import com.fasterxml.jackson.databind.ObjectMapper; - -import io.mosip.kernel.core.exception.ServiceError; -import io.mosip.registration.processor.core.abstractverticle.EventDTO; -import io.mosip.registration.processor.core.abstractverticle.HealthCheckDTO; -import io.mosip.registration.processor.core.abstractverticle.MessageBusAddress; -import io.mosip.registration.processor.core.abstractverticle.MessageDTO; -import io.mosip.registration.processor.core.abstractverticle.MosipEventBus; -import io.mosip.registration.processor.core.abstractverticle.MosipRouter; -import io.mosip.registration.processor.core.code.ApiName; -import io.mosip.registration.processor.core.common.rest.dto.ErrorDTO; -import io.mosip.registration.processor.core.constant.EventId; -import io.mosip.registration.processor.core.constant.EventName; -import io.mosip.registration.processor.core.constant.EventType; -import io.mosip.registration.processor.core.constant.RegistrationType; -import io.mosip.registration.processor.core.constant.VidType; -import io.mosip.registration.processor.core.exception.ApisResourceAccessException; -import io.mosip.registration.processor.core.http.ResponseWrapper; -import io.mosip.registration.processor.core.idrepo.dto.CredentialResponseDto; -import io.mosip.registration.processor.core.idrepo.dto.VidInfoDTO; -import io.mosip.registration.processor.core.idrepo.dto.VidsInfosDTO; -import io.mosip.registration.processor.core.packet.dto.Identity; -import io.mosip.registration.processor.core.spi.eventbus.EventHandler; -import io.mosip.registration.processor.core.spi.restclient.RegistrationProcessorRestClientService; -import io.mosip.registration.processor.core.util.PropertiesUtil; -import io.mosip.registration.processor.packet.storage.utils.Utilities; -import io.mosip.registration.processor.print.stage.PrintingStage; -import io.mosip.registration.processor.rest.client.audit.builder.AuditLogRequestBuilder; -import io.mosip.registration.processor.rest.client.audit.dto.AuditResponseDto; -import io.mosip.registration.processor.status.dto.InternalRegistrationStatusDto; -import io.mosip.registration.processor.status.dto.RegistrationStatusDto; -import io.mosip.registration.processor.status.service.RegistrationStatusService; -import io.vertx.core.AsyncResult; -import io.vertx.core.Handler; -import io.vertx.core.Vertx; -import io.vertx.ext.web.Router; -import io.vertx.ext.web.RoutingContext; - -@SuppressWarnings("deprecation") -@RunWith(PowerMockRunner.class) -@PrepareForTest({}) -@PowerMockIgnore({ "com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*","javax.management.*", "javax.net.*" }) -@PropertySource("classpath:bootstrap.properties") -public class PrintingStageTest { - - @Mock - private AuditLogRequestBuilder auditLogRequestBuilder; - - @Mock - MosipRouter router; - - @Mock - protected PropertiesUtil propertiesUtil; - - @Mock - private ObjectMapper objectMapper; - - private InternalRegistrationStatusDto registrationStatusDto = new InternalRegistrationStatusDto(); - - @Mock - private RegistrationStatusService registrationStatusService; - /** The rest template. */ - @Mock - private RegistrationProcessorRestClientService restClientService; - - - - /** The identity. */ - Identity identity = new Identity(); - - @Mock - private Environment env; - - private String response; - - @Mock - private Utilities utitilites; - - @InjectMocks - private PrintingStage stage = new PrintingStage() { - @Override - public MosipEventBus getEventBus(Object verticleName, String url, int instanceNumber) { - vertx = Vertx.vertx(); - - return new MosipEventBus() { - - @Override - public Vertx getEventbus() { - return vertx; - } - - @Override - public void consume(MessageBusAddress fromAddress, - EventHandler>> eventHandler) { - - } - - @Override - public void consumeAndSend(MessageBusAddress fromAddress, MessageBusAddress toAddress, - EventHandler>> eventHandler) { - - } - - @Override - public void send(MessageBusAddress toAddress, MessageDTO message) { - - } - - @Override - public void consumerHealthCheck(Handler eventHandler, String address) { - // TODO Auto-generated method stub - - } - - @Override - public void senderHealthCheck(Handler eventHandler, String address) { - // TODO Auto-generated method stub - - } - - - }; - } - - @Override - public void consume(MosipEventBus mosipEventBus, MessageBusAddress fromAddress, - long messageExpiryTimeLimit) { - } - - - @Override - public void send(MosipEventBus mosipEventBus, MessageBusAddress toAddress, MessageDTO message) { - } - - @Override - public void createServer(Router router, int port) { - - } - - @Override - public Router postUrl(Vertx vertx, MessageBusAddress consumeAddress, MessageBusAddress sendAddress) { - return null; - } - - @Override - public void setResponseWithDigitalSignature(RoutingContext ctx, Object object, String contentType) { - - } - }; - - @Before - public void setup() throws Exception { - when(env.getProperty("mosip.registration.processor.datetime.pattern")) - .thenReturn("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); - when(env.getProperty("mosip.regproc.printing.server.port")).thenReturn("8099"); - when(env.getProperty("mosip.registration.processor.issuer")) - .thenReturn("mpartner-default-digitalcard:PDFCard:RPR_UIN_CARD_TEMPLATE;mpartner-default-print:euin:RPR_UIN_CARD_TEMPLATE"); - ReflectionTestUtils.setField(stage, "workerPoolSize", 10); - ReflectionTestUtils.setField(stage, "messageExpiryTimeLimit", Long.valueOf(0)); - ReflectionTestUtils.setField(stage, "clusterManagerUrl", "/dummyPath"); - ReflectionTestUtils.setField(stage, "busOutHaltAddresses", Arrays.asList()); - ReflectionTestUtils.setField(stage, "pdfDelimiter", "-PDF"); - ReflectionTestUtils.setField(stage, "defaultInternalIssuers", Arrays.asList("mpartner-default-digitalcard#PDFCard#RPR_UIN_CARD_TEMPLATE")); - ReflectionTestUtils.setField(stage, "defaultIssuers", Arrays.asList("mpartner-default-print#euin#RPR_UIN_CARD_TEMPLATE")); - ReflectionTestUtils.setField(stage, "opencrvsAdditionalParam", "[{'process':'OPENCRVS_NEW','credentialType':'opencrvs','issuer':'opencrvs-partner','fields':['opencrvsBRN']}]"); - - System.setProperty("server.port", "8099"); - - //ReflectionTestUtils.setField(stage, "port", "8080"); - ReflectionTestUtils.setField(stage, "encrypt", false); - registrationStatusDto.setRegistrationId("45451454520011220230523070548"); - registrationStatusDto.setRegistrationType("NEW"); - registrationStatusDto.setWorkflowInstanceId("33e1fb7f-8202-41dc-82a1-49e821364eb2"); - Mockito.when(registrationStatusService.getRegistrationStatus(any(String.class), any(), any(), any())).thenReturn(registrationStatusDto); - Mockito.when(propertiesUtil.getIntegerProperty(any(), any())).thenReturn(8080); - - - - //Mockito.doNothing().when(registrationStatusDto).setStatusCode(any()); - //Mockito.doNothing().when(registrationStatusDto).setStatusComment(any()); - Mockito.doNothing().when(registrationStatusService).updateRegistrationStatus(any(), any(), any()); - //Mockito.doNothing().when(registrationStatusDto).setLatestTransactionTypeCode(any()); - //Mockito.doNothing().when(registrationStatusDto).setRegistrationStageName(any()); - //Mockito.doNothing().when(registrationStatusDto).setLatestTransactionStatusCode(any()); - Mockito.when(router.post(any())).thenReturn(null); - Mockito.when(router.get(any())).thenReturn(null); - - - Field auditLog = AuditLogRequestBuilder.class.getDeclaredField("registrationProcessorRestService"); - auditLog.setAccessible(true); - @SuppressWarnings("unchecked") - RegistrationProcessorRestClientService mockObj = Mockito - .mock(RegistrationProcessorRestClientService.class); - auditLog.set(auditLogRequestBuilder, mockObj); - AuditResponseDto auditResponseDto = new AuditResponseDto(); - ResponseWrapper responseWrapper = new ResponseWrapper<>(); - responseWrapper.setResponse(auditResponseDto); - Mockito.doReturn(responseWrapper).when(auditLogRequestBuilder).createAuditRequestBuilder( - "test case description", EventId.RPR_401.toString(), EventName.ADD.toString(), - EventType.BUSINESS.toString(), "1234testcase", ApiName.AUDIT); - Mockito.when(objectMapper.writeValueAsString(any())).thenReturn(response); - VidsInfosDTO vidsInfosDTO = new VidsInfosDTO(); - List vidList = new ArrayList<>(); - VidInfoDTO vidInfoDTO = new VidInfoDTO(); - vidInfoDTO.setVid("4796042638691271"); - vidInfoDTO.setVidType(VidType.PERPETUAL.name()); - vidList.add(vidInfoDTO); - vidsInfosDTO.setResponse(vidList); - Mockito.when(restClientService.getApi(any(), any(), anyString(), any(), any())).thenReturn(vidsInfosDTO); - Map map1 = new HashMap<>(); - map1.put("UIN", "4238135072"); - JSONObject jsonObject = new JSONObject(map1); - Mockito.when(utitilites.retrieveUIN(any())).thenReturn(jsonObject); - - - - } - - @Test - public void testAll() throws Exception { - testDeployVerticle(); - testStart(); - testPrintStageSuccess(); - testPrintStageFailure(); - } - - public void testStart() { - stage.start(); - } - - public void testDeployVerticle() throws Exception { - - - stage.deployVerticle(); - } - - - - - @Test - public void testPrintStageSuccess() - throws ApisResourceAccessException, JsonParseException, JsonMappingException, IOException { - MessageDTO dto = new MessageDTO(); - dto.setRid("1234567890987654321"); - - dto.setReg_type(RegistrationType.NEW.name()); - - ResponseWrapper responseWrapper = new ResponseWrapper<>(); - CredentialResponseDto credentialResponseDto = new CredentialResponseDto(); - credentialResponseDto.setRequestId("879664323421"); - Mockito.when(objectMapper.readValue(response, CredentialResponseDto.class)) - .thenReturn(credentialResponseDto); - responseWrapper.setResponse(credentialResponseDto); - Mockito.when(restClientService.postApi(any(), any(), any(), any(), any(), any(MediaType.class))) - .thenReturn(responseWrapper); - Mockito.when(restClientService.postApi((ApiName) any(), any(MediaType.class),any(),any(), any(), any(), any())) - .thenReturn(responseWrapper); - MessageDTO result = stage.process(dto); - assertTrue(result.getIsValid()); - assertFalse(result.getInternalError()); - } - - - @Test - public void testPrintStageFailure() throws ApisResourceAccessException { - - MessageDTO dto = new MessageDTO(); - dto.setRid("1234567890987654321"); - - dto.setReg_type(RegistrationType.NEW.name()); - - ResponseWrapper responseWrapper = new ResponseWrapper<>(); - ErrorDTO error = new ErrorDTO(); - error.setErrorCode("IDR-CRG-004"); - error.setMessage("unknown exception"); - List errors = new ArrayList<>(); - errors.add(error); - responseWrapper.setErrors(errors); - - Mockito.when(restClientService.postApi(any(), any(), any(), any(), any(), any(MediaType.class))) - .thenReturn(responseWrapper); - - MessageDTO result = stage.process(dto); - assertFalse(result.getIsValid()); - assertFalse(result.getInternalError()); - } - - - @Test - public void testException() - throws JsonParseException, JsonMappingException, IOException, ApisResourceAccessException { - MessageDTO dto = new MessageDTO(); - dto.setRid("1234567890987654321"); - - dto.setReg_type(RegistrationType.NEW.name()); - - ResponseWrapper responseWrapper = new ResponseWrapper<>(); - CredentialResponseDto credentialResponseDto = new CredentialResponseDto(); - credentialResponseDto.setRequestId("879664323421"); - Mockito.when(objectMapper.readValue(response, CredentialResponseDto.class)).thenReturn(credentialResponseDto); - responseWrapper.setResponse(credentialResponseDto); - Mockito.when(restClientService.postApi(any(), any(), any(), any(), any(), any(MediaType.class))) - .thenReturn(null); - MessageDTO result = stage.process(dto); - assertTrue(result.getInternalError()); - assertTrue(result.getIsValid()); - } - - @Test - public void testApisResourceAccessException() - throws JsonParseException, JsonMappingException, IOException, ApisResourceAccessException { - MessageDTO dto = new MessageDTO(); - dto.setRid("1234567890987654321"); - - dto.setReg_type(RegistrationType.NEW.name()); - - ResponseWrapper responseWrapper = new ResponseWrapper<>(); - CredentialResponseDto credentialResponseDto = new CredentialResponseDto(); - credentialResponseDto.setRequestId("879664323421"); - Mockito.when(objectMapper.readValue(response, CredentialResponseDto.class)).thenReturn(credentialResponseDto); - responseWrapper.setResponse(credentialResponseDto); - Mockito.when(restClientService.postApi(any(), any(), any(), any(), any(), any(MediaType.class))) - .thenThrow(new ApisResourceAccessException()); - MessageDTO result = stage.process(dto); - assertTrue(result.getInternalError()); - assertTrue(result.getIsValid()); - } - - @Test - public void testUINNotavailable() - throws JsonParseException, JsonMappingException, IOException, ApisResourceAccessException { - MessageDTO dto = new MessageDTO(); - dto.setRid("1234567890987654321"); - - dto.setReg_type(RegistrationType.NEW.name()); - - ResponseWrapper responseWrapper = new ResponseWrapper<>(); - CredentialResponseDto credentialResponseDto = new CredentialResponseDto(); - credentialResponseDto.setRequestId("879664323421"); - Mockito.when(objectMapper.readValue(response, CredentialResponseDto.class)).thenReturn(credentialResponseDto); - responseWrapper.setResponse(credentialResponseDto); - Mockito.when(restClientService.postApi(any(), any(), any(), any(), any(), any(MediaType.class))) - .thenThrow(new ApisResourceAccessException()); - Map map1 = new HashMap<>(); - - JSONObject jsonObject = new JSONObject(map1); - Mockito.when(utitilites.retrieveUIN(any())).thenReturn(jsonObject); - MessageDTO result = stage.process(dto); - - assertFalse(result.getIsValid()); - assertFalse(result.getInternalError()); - } - - @Test - public void testVidNotAvailableException() - throws JsonParseException, JsonMappingException, IOException, ApisResourceAccessException { - MessageDTO dto = new MessageDTO(); - dto.setRid("1234567890987654321"); - - dto.setReg_type(RegistrationType.NEW.name()); - - ResponseWrapper responseWrapper = new ResponseWrapper<>(); - CredentialResponseDto credentialResponseDto = new CredentialResponseDto(); - credentialResponseDto.setRequestId("879664323421"); - Mockito.when(objectMapper.readValue(response, CredentialResponseDto.class)).thenReturn(credentialResponseDto); - responseWrapper.setResponse(credentialResponseDto); - Mockito.when(restClientService.postApi(any(), any(), any(), any(), any(), any(MediaType.class))) - .thenThrow(new ApisResourceAccessException()); - VidsInfosDTO vidsInfosDTO = new VidsInfosDTO(); - List vidList = new ArrayList<>(); - VidInfoDTO vidInfoDTO = new VidInfoDTO(); - vidInfoDTO.setVid("4796042638691271"); - vidInfoDTO.setVidType(VidType.TEMPORARY.name()); - vidList.add(vidInfoDTO); - vidsInfosDTO.setResponse(vidList); - Mockito.when(restClientService.getApi(any(), any(), anyString(), any(), any())).thenReturn(vidsInfosDTO); - MessageDTO result = stage.process(dto); - - assertTrue(result.getInternalError()); - assertTrue(result.getIsValid()); - } - - @Test - public void testVidNotAvailableGETAPIResponseNullException() - throws ApisResourceAccessException, JsonParseException, JsonMappingException, IOException { - MessageDTO dto = new MessageDTO(); - dto.setRid("1234567890987654321"); - - dto.setReg_type(RegistrationType.NEW.name()); - - VidsInfosDTO vidsInfosDTO = new VidsInfosDTO(); - vidsInfosDTO.setResponse(null); - Mockito.when(restClientService.getApi(any(), any(), anyString(), any(), any())).thenReturn(vidsInfosDTO); - - MessageDTO result = stage.process(dto); - assertTrue(result.getIsValid()); - assertTrue(result.getInternalError()); - } - - @Test - public void testVidNotAvailableGETAPIException() - throws ApisResourceAccessException, JsonParseException, JsonMappingException, IOException { - MessageDTO dto = new MessageDTO(); - dto.setRid("1234567890987654321"); - - dto.setReg_type(RegistrationType.NEW.name()); - - VidsInfosDTO vidsInfosDTO = new VidsInfosDTO(); - vidsInfosDTO.setResponse(null); - ServiceError error = new ServiceError(); - error.setErrorCode("ERR-001"); - error.setMessage("exception occured"); - vidsInfosDTO.setErrors(Arrays.asList(error)); - Mockito.when(restClientService.getApi(any(), any(), anyString(), any(), any())).thenReturn(vidsInfosDTO); - - MessageDTO result = stage.process(dto); - assertTrue(result.getIsValid()); - assertTrue(result.getInternalError()); - } - +package io.mosip.registrationprocessor.print.stage.test; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.when; + +import java.io.IOException; +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.json.simple.JSONObject; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.springframework.context.annotation.PropertySource; +import org.springframework.core.env.Environment; +import org.springframework.http.MediaType; +import org.springframework.test.util.ReflectionTestUtils; + +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +import io.mosip.kernel.core.exception.ServiceError; +import io.mosip.registration.processor.core.abstractverticle.EventDTO; +import io.mosip.registration.processor.core.abstractverticle.HealthCheckDTO; +import io.mosip.registration.processor.core.abstractverticle.MessageBusAddress; +import io.mosip.registration.processor.core.abstractverticle.MessageDTO; +import io.mosip.registration.processor.core.abstractverticle.MosipEventBus; +import io.mosip.registration.processor.core.abstractverticle.MosipRouter; +import io.mosip.registration.processor.core.code.ApiName; +import io.mosip.registration.processor.core.common.rest.dto.ErrorDTO; +import io.mosip.registration.processor.core.constant.EventId; +import io.mosip.registration.processor.core.constant.EventName; +import io.mosip.registration.processor.core.constant.EventType; +import io.mosip.registration.processor.core.constant.RegistrationType; +import io.mosip.registration.processor.core.constant.VidType; +import io.mosip.registration.processor.core.exception.ApisResourceAccessException; +import io.mosip.registration.processor.core.http.ResponseWrapper; +import io.mosip.registration.processor.core.idrepo.dto.CredentialResponseDto; +import io.mosip.registration.processor.core.idrepo.dto.VidInfoDTO; +import io.mosip.registration.processor.core.idrepo.dto.VidsInfosDTO; +import io.mosip.registration.processor.core.packet.dto.Identity; +import io.mosip.registration.processor.core.spi.eventbus.EventHandler; +import io.mosip.registration.processor.core.spi.restclient.RegistrationProcessorRestClientService; +import io.mosip.registration.processor.core.util.PropertiesUtil; +import io.mosip.registration.processor.packet.storage.utils.Utilities; +import io.mosip.registration.processor.eventhandler.stage.EventHandlerStage; +import io.mosip.registration.processor.rest.client.audit.builder.AuditLogRequestBuilder; +import io.mosip.registration.processor.rest.client.audit.dto.AuditResponseDto; +import io.mosip.registration.processor.status.dto.InternalRegistrationStatusDto; +import io.mosip.registration.processor.status.dto.RegistrationStatusDto; +import io.mosip.registration.processor.status.service.RegistrationStatusService; +import io.vertx.core.AsyncResult; +import io.vertx.core.Handler; +import io.vertx.core.Vertx; +import io.vertx.ext.web.Router; +import io.vertx.ext.web.RoutingContext; + +@SuppressWarnings("deprecation") +@RunWith(PowerMockRunner.class) +@PrepareForTest({}) +@PowerMockIgnore({ "com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*","javax.management.*", "javax.net.*" }) +@PropertySource("classpath:bootstrap.properties") +public class PrintingStageTest { + + @Mock + private AuditLogRequestBuilder auditLogRequestBuilder; + + @Mock + MosipRouter router; + + @Mock + protected PropertiesUtil propertiesUtil; + + @Mock + private ObjectMapper objectMapper; + + private InternalRegistrationStatusDto registrationStatusDto = new InternalRegistrationStatusDto(); + + @Mock + private RegistrationStatusService registrationStatusService; + /** The rest template. */ + @Mock + private RegistrationProcessorRestClientService restClientService; + + + + /** The identity. */ + Identity identity = new Identity(); + + @Mock + private Environment env; + + private String response; + + @Mock + private Utilities utitilites; + + @InjectMocks + private EventHandlerStage stage = new EventHandlerStage() { + @Override + public MosipEventBus getEventBus(Object verticleName, String url, int instanceNumber) { + vertx = Vertx.vertx(); + + return new MosipEventBus() { + + @Override + public Vertx getEventbus() { + return vertx; + } + + @Override + public void consume(MessageBusAddress fromAddress, + EventHandler>> eventHandler) { + + } + + @Override + public void consumeAndSend(MessageBusAddress fromAddress, MessageBusAddress toAddress, + EventHandler>> eventHandler) { + + } + + @Override + public void send(MessageBusAddress toAddress, MessageDTO message) { + + } + + @Override + public void consumerHealthCheck(Handler eventHandler, String address) { + // TODO Auto-generated method stub + + } + + @Override + public void senderHealthCheck(Handler eventHandler, String address) { + // TODO Auto-generated method stub + + } + + + }; + } + + @Override + public void consume(MosipEventBus mosipEventBus, MessageBusAddress fromAddress, + long messageExpiryTimeLimit) { + } + + + @Override + public void send(MosipEventBus mosipEventBus, MessageBusAddress toAddress, MessageDTO message) { + } + + @Override + public void createServer(Router router, int port) { + + } + + @Override + public Router postUrl(Vertx vertx, MessageBusAddress consumeAddress, MessageBusAddress sendAddress) { + return null; + } + + @Override + public void setResponseWithDigitalSignature(RoutingContext ctx, Object object, String contentType) { + + } + }; + + @Before + public void setup() throws Exception { + when(env.getProperty("mosip.registration.processor.datetime.pattern")) + .thenReturn("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); + when(env.getProperty("mosip.regproc.printing.server.port")).thenReturn("8099"); + when(env.getProperty("mosip.registration.processor.issuer")) + .thenReturn("mpartner-default-digitalcard:PDFCard:RPR_UIN_CARD_TEMPLATE;mpartner-default-print:euin:RPR_UIN_CARD_TEMPLATE"); + ReflectionTestUtils.setField(stage, "workerPoolSize", 10); + ReflectionTestUtils.setField(stage, "messageExpiryTimeLimit", Long.valueOf(0)); + ReflectionTestUtils.setField(stage, "clusterManagerUrl", "/dummyPath"); + ReflectionTestUtils.setField(stage, "busOutHaltAddresses", Arrays.asList()); + ReflectionTestUtils.setField(stage, "pdfDelimiter", "-PDF"); + ReflectionTestUtils.setField(stage, "defaultInternalIssuers", Arrays.asList("mpartner-default-digitalcard#PDFCard#RPR_UIN_CARD_TEMPLATE")); + ReflectionTestUtils.setField(stage, "defaultIssuers", Arrays.asList("mpartner-default-print#euin#RPR_UIN_CARD_TEMPLATE")); + ReflectionTestUtils.setField(stage, "opencrvsAdditionalParam", "[{'process':'OPENCRVS_NEW','credentialType':'opencrvs','issuer':'opencrvs-partner','fields':['opencrvsBRN']}]"); + + System.setProperty("server.port", "8099"); + + //ReflectionTestUtils.setField(stage, "port", "8080"); + ReflectionTestUtils.setField(stage, "encrypt", false); + registrationStatusDto.setRegistrationId("45451454520011220230523070548"); + registrationStatusDto.setRegistrationType("NEW"); + registrationStatusDto.setWorkflowInstanceId("33e1fb7f-8202-41dc-82a1-49e821364eb2"); + Mockito.when(registrationStatusService.getRegistrationStatus(any(String.class), any(), any(), any())).thenReturn(registrationStatusDto); + Mockito.when(propertiesUtil.getIntegerProperty(any(), any())).thenReturn(8080); + + + + //Mockito.doNothing().when(registrationStatusDto).setStatusCode(any()); + //Mockito.doNothing().when(registrationStatusDto).setStatusComment(any()); + Mockito.doNothing().when(registrationStatusService).updateRegistrationStatus(any(), any(), any()); + //Mockito.doNothing().when(registrationStatusDto).setLatestTransactionTypeCode(any()); + //Mockito.doNothing().when(registrationStatusDto).setRegistrationStageName(any()); + //Mockito.doNothing().when(registrationStatusDto).setLatestTransactionStatusCode(any()); + Mockito.when(router.post(any())).thenReturn(null); + Mockito.when(router.get(any())).thenReturn(null); + + + Field auditLog = AuditLogRequestBuilder.class.getDeclaredField("registrationProcessorRestService"); + auditLog.setAccessible(true); + @SuppressWarnings("unchecked") + RegistrationProcessorRestClientService mockObj = Mockito + .mock(RegistrationProcessorRestClientService.class); + auditLog.set(auditLogRequestBuilder, mockObj); + AuditResponseDto auditResponseDto = new AuditResponseDto(); + ResponseWrapper responseWrapper = new ResponseWrapper<>(); + responseWrapper.setResponse(auditResponseDto); + Mockito.doReturn(responseWrapper).when(auditLogRequestBuilder).createAuditRequestBuilder( + "test case description", EventId.RPR_401.toString(), EventName.ADD.toString(), + EventType.BUSINESS.toString(), "1234testcase", ApiName.AUDIT); + Mockito.when(objectMapper.writeValueAsString(any())).thenReturn(response); + VidsInfosDTO vidsInfosDTO = new VidsInfosDTO(); + List vidList = new ArrayList<>(); + VidInfoDTO vidInfoDTO = new VidInfoDTO(); + vidInfoDTO.setVid("4796042638691271"); + vidInfoDTO.setVidType(VidType.PERPETUAL.name()); + vidList.add(vidInfoDTO); + vidsInfosDTO.setResponse(vidList); + Mockito.when(restClientService.getApi(any(), any(), anyString(), any(), any())).thenReturn(vidsInfosDTO); + Map map1 = new HashMap<>(); + map1.put("UIN", "4238135072"); + JSONObject jsonObject = new JSONObject(map1); + Mockito.when(utitilites.retrieveUIN(any())).thenReturn(jsonObject); + + + + } + + @Test + public void testAll() throws Exception { + testDeployVerticle(); + testStart(); + testPrintStageSuccess(); + testPrintStageFailure(); + } + + public void testStart() { + stage.start(); + } + + public void testDeployVerticle() throws Exception { + + + stage.deployVerticle(); + } + + + + + @Test + public void testPrintStageSuccess() + throws ApisResourceAccessException, JsonParseException, JsonMappingException, IOException { + MessageDTO dto = new MessageDTO(); + dto.setRid("1234567890987654321"); + + dto.setReg_type(RegistrationType.NEW.name()); + + ResponseWrapper responseWrapper = new ResponseWrapper<>(); + CredentialResponseDto credentialResponseDto = new CredentialResponseDto(); + credentialResponseDto.setRequestId("879664323421"); + Mockito.when(objectMapper.readValue(response, CredentialResponseDto.class)) + .thenReturn(credentialResponseDto); + responseWrapper.setResponse(credentialResponseDto); + Mockito.when(restClientService.postApi(any(), any(), any(), any(), any(), any(MediaType.class))) + .thenReturn(responseWrapper); + Mockito.when(restClientService.postApi((ApiName) any(), any(MediaType.class),any(),any(), any(), any(), any())) + .thenReturn(responseWrapper); + MessageDTO result = stage.process(dto); + assertTrue(result.getIsValid()); + assertFalse(result.getInternalError()); + } + + + @Test + public void testPrintStageFailure() throws ApisResourceAccessException { + + MessageDTO dto = new MessageDTO(); + dto.setRid("1234567890987654321"); + + dto.setReg_type(RegistrationType.NEW.name()); + + ResponseWrapper responseWrapper = new ResponseWrapper<>(); + ErrorDTO error = new ErrorDTO(); + error.setErrorCode("IDR-CRG-004"); + error.setMessage("unknown exception"); + List errors = new ArrayList<>(); + errors.add(error); + responseWrapper.setErrors(errors); + + Mockito.when(restClientService.postApi(any(), any(), any(), any(), any(), any(MediaType.class))) + .thenReturn(responseWrapper); + + MessageDTO result = stage.process(dto); + assertFalse(result.getIsValid()); + assertFalse(result.getInternalError()); + } + + + @Test + public void testException() + throws JsonParseException, JsonMappingException, IOException, ApisResourceAccessException { + MessageDTO dto = new MessageDTO(); + dto.setRid("1234567890987654321"); + + dto.setReg_type(RegistrationType.NEW.name()); + + ResponseWrapper responseWrapper = new ResponseWrapper<>(); + CredentialResponseDto credentialResponseDto = new CredentialResponseDto(); + credentialResponseDto.setRequestId("879664323421"); + Mockito.when(objectMapper.readValue(response, CredentialResponseDto.class)).thenReturn(credentialResponseDto); + responseWrapper.setResponse(credentialResponseDto); + Mockito.when(restClientService.postApi(any(), any(), any(), any(), any(), any(MediaType.class))) + .thenReturn(null); + MessageDTO result = stage.process(dto); + assertTrue(result.getInternalError()); + assertTrue(result.getIsValid()); + } + + @Test + public void testApisResourceAccessException() + throws JsonParseException, JsonMappingException, IOException, ApisResourceAccessException { + MessageDTO dto = new MessageDTO(); + dto.setRid("1234567890987654321"); + + dto.setReg_type(RegistrationType.NEW.name()); + + ResponseWrapper responseWrapper = new ResponseWrapper<>(); + CredentialResponseDto credentialResponseDto = new CredentialResponseDto(); + credentialResponseDto.setRequestId("879664323421"); + Mockito.when(objectMapper.readValue(response, CredentialResponseDto.class)).thenReturn(credentialResponseDto); + responseWrapper.setResponse(credentialResponseDto); + Mockito.when(restClientService.postApi(any(), any(), any(), any(), any(), any(MediaType.class))) + .thenThrow(new ApisResourceAccessException()); + MessageDTO result = stage.process(dto); + assertTrue(result.getInternalError()); + assertTrue(result.getIsValid()); + } + + @Test + public void testUINNotavailable() + throws JsonParseException, JsonMappingException, IOException, ApisResourceAccessException { + MessageDTO dto = new MessageDTO(); + dto.setRid("1234567890987654321"); + + dto.setReg_type(RegistrationType.NEW.name()); + + ResponseWrapper responseWrapper = new ResponseWrapper<>(); + CredentialResponseDto credentialResponseDto = new CredentialResponseDto(); + credentialResponseDto.setRequestId("879664323421"); + Mockito.when(objectMapper.readValue(response, CredentialResponseDto.class)).thenReturn(credentialResponseDto); + responseWrapper.setResponse(credentialResponseDto); + Mockito.when(restClientService.postApi(any(), any(), any(), any(), any(), any(MediaType.class))) + .thenThrow(new ApisResourceAccessException()); + Map map1 = new HashMap<>(); + + JSONObject jsonObject = new JSONObject(map1); + Mockito.when(utitilites.retrieveUIN(any())).thenReturn(jsonObject); + MessageDTO result = stage.process(dto); + + assertFalse(result.getIsValid()); + assertFalse(result.getInternalError()); + } + + @Test + public void testVidNotAvailableException() + throws JsonParseException, JsonMappingException, IOException, ApisResourceAccessException { + MessageDTO dto = new MessageDTO(); + dto.setRid("1234567890987654321"); + + dto.setReg_type(RegistrationType.NEW.name()); + + ResponseWrapper responseWrapper = new ResponseWrapper<>(); + CredentialResponseDto credentialResponseDto = new CredentialResponseDto(); + credentialResponseDto.setRequestId("879664323421"); + Mockito.when(objectMapper.readValue(response, CredentialResponseDto.class)).thenReturn(credentialResponseDto); + responseWrapper.setResponse(credentialResponseDto); + Mockito.when(restClientService.postApi(any(), any(), any(), any(), any(), any(MediaType.class))) + .thenThrow(new ApisResourceAccessException()); + VidsInfosDTO vidsInfosDTO = new VidsInfosDTO(); + List vidList = new ArrayList<>(); + VidInfoDTO vidInfoDTO = new VidInfoDTO(); + vidInfoDTO.setVid("4796042638691271"); + vidInfoDTO.setVidType(VidType.TEMPORARY.name()); + vidList.add(vidInfoDTO); + vidsInfosDTO.setResponse(vidList); + Mockito.when(restClientService.getApi(any(), any(), anyString(), any(), any())).thenReturn(vidsInfosDTO); + MessageDTO result = stage.process(dto); + + assertTrue(result.getInternalError()); + assertTrue(result.getIsValid()); + } + + @Test + public void testVidNotAvailableGETAPIResponseNullException() + throws ApisResourceAccessException, JsonParseException, JsonMappingException, IOException { + MessageDTO dto = new MessageDTO(); + dto.setRid("1234567890987654321"); + + dto.setReg_type(RegistrationType.NEW.name()); + + VidsInfosDTO vidsInfosDTO = new VidsInfosDTO(); + vidsInfosDTO.setResponse(null); + Mockito.when(restClientService.getApi(any(), any(), anyString(), any(), any())).thenReturn(vidsInfosDTO); + + MessageDTO result = stage.process(dto); + assertTrue(result.getIsValid()); + assertTrue(result.getInternalError()); + } + + @Test + public void testVidNotAvailableGETAPIException() + throws ApisResourceAccessException, JsonParseException, JsonMappingException, IOException { + MessageDTO dto = new MessageDTO(); + dto.setRid("1234567890987654321"); + + dto.setReg_type(RegistrationType.NEW.name()); + + VidsInfosDTO vidsInfosDTO = new VidsInfosDTO(); + vidsInfosDTO.setResponse(null); + ServiceError error = new ServiceError(); + error.setErrorCode("ERR-001"); + error.setMessage("exception occured"); + vidsInfosDTO.setErrors(Arrays.asList(error)); + Mockito.when(restClientService.getApi(any(), any(), anyString(), any(), any())).thenReturn(vidsInfosDTO); + + MessageDTO result = stage.process(dto); + assertTrue(result.getIsValid()); + assertTrue(result.getInternalError()); + } + } \ No newline at end of file diff --git a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/constant/ProviderStageName.java b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/constant/ProviderStageName.java index 8013d3918dc..c3f1a09cd54 100644 --- a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/constant/ProviderStageName.java +++ b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/constant/ProviderStageName.java @@ -20,7 +20,7 @@ public enum ProviderStageName { UIN_GENERATOR("uingenerator"), WORKFLOW_MANAGER("workflowmanager"), MESSAGE_SENDER("messagesender"), - PRINTING("printing"); + EVENT_HANDLER("eventhandler"); private String value; diff --git a/registration-processor/stage-groups/registration-processor-stage-group-7/pom.xml b/registration-processor/stage-groups/registration-processor-stage-group-7/pom.xml index a8e4b47658c..1bb5a7d1dd5 100644 --- a/registration-processor/stage-groups/registration-processor-stage-group-7/pom.xml +++ b/registration-processor/stage-groups/registration-processor-stage-group-7/pom.xml @@ -42,7 +42,7 @@ io.mosip.registrationprocessor - registration-processor-printing-stage + registration-processor-event-handler-stage 1.2.1-SNAPSHOT From 9f07448e611ade0ce44fa1c242798cec91d58525 Mon Sep 17 00:00:00 2001 From: Monobikash Das Date: Fri, 22 Sep 2023 14:47:21 +0530 Subject: [PATCH 22/38] MOSIP-28121 : Fixed review comments Signed-off-by: Monobikash Das --- registration-processor/post-processor/pom.xml | 2 +- .../Dockerfile-not-used | 10 ++-- .../README.md | 0 .../pom.xml | 2 +- .../CredentialRequestorStageApplication.java} | 8 +-- .../config/CredentialRequestorConfigBean.java | 15 +++++ .../stage/CredentialRequestorStage.java} | 58 +++++++++++-------- .../exception/VidNotAvailableException.java | 2 +- .../util/CredentialPartnerUtil.java | 2 +- .../src/main/resources/bootstrap.properties | 10 ++-- .../src/main/resources/logback.xml | 0 .../test/CredentialRequestorStageTest.java} | 12 ++-- .../eventhandler/config/PrintConfigBean.java | 15 ----- .../core/constant/ProviderStageName.java | 2 +- .../exception/util/PlatformErrorMessages.java | 2 + .../pom.xml | 2 +- 16 files changed, 77 insertions(+), 65 deletions(-) rename registration-processor/post-processor/{registration-processor-event-handler-stage => registration-processor-credential-requestor-stage}/Dockerfile-not-used (85%) rename registration-processor/post-processor/{registration-processor-event-handler-stage => registration-processor-credential-requestor-stage}/README.md (100%) rename registration-processor/post-processor/{registration-processor-event-handler-stage => registration-processor-credential-requestor-stage}/pom.xml (97%) rename registration-processor/post-processor/{registration-processor-event-handler-stage/src/main/java/io/mosip/registration/processor/eventhandler/EventHandlerStageApplication.java => registration-processor-credential-requestor-stage/src/main/java/io/mosip/registration/processor/credentialrequestor/CredentialRequestorStageApplication.java} (68%) create mode 100644 registration-processor/post-processor/registration-processor-credential-requestor-stage/src/main/java/io/mosip/registration/processor/credentialrequestor/config/CredentialRequestorConfigBean.java rename registration-processor/post-processor/{registration-processor-event-handler-stage/src/main/java/io/mosip/registration/processor/eventhandler/stage/EventHandlerStage.java => registration-processor-credential-requestor-stage/src/main/java/io/mosip/registration/processor/credentialrequestor/stage/CredentialRequestorStage.java} (89%) rename registration-processor/post-processor/{registration-processor-event-handler-stage/src/main/java/io/mosip/registration/processor/eventhandler => registration-processor-credential-requestor-stage/src/main/java/io/mosip/registration/processor/credentialrequestor}/stage/exception/VidNotAvailableException.java (87%) rename registration-processor/post-processor/{registration-processor-event-handler-stage/src/main/java/io/mosip/registration/processor/eventhandler => registration-processor-credential-requestor-stage/src/main/java/io/mosip/registration/processor/credentialrequestor}/util/CredentialPartnerUtil.java (99%) rename registration-processor/post-processor/{registration-processor-event-handler-stage => registration-processor-credential-requestor-stage}/src/main/resources/bootstrap.properties (76%) rename registration-processor/post-processor/{registration-processor-event-handler-stage => registration-processor-credential-requestor-stage}/src/main/resources/logback.xml (100%) rename registration-processor/post-processor/{registration-processor-event-handler-stage/src/test/java/io/mosip/registrationprocessor/print/stage/test/PrintingStageTest.java => registration-processor-credential-requestor-stage/src/test/java/io/mosip/registrationprocessor/credentialrequestor/test/CredentialRequestorStageTest.java} (96%) delete mode 100644 registration-processor/post-processor/registration-processor-event-handler-stage/src/main/java/io/mosip/registration/processor/eventhandler/config/PrintConfigBean.java diff --git a/registration-processor/post-processor/pom.xml b/registration-processor/post-processor/pom.xml index 79009ecc58f..3aba489bf87 100644 --- a/registration-processor/post-processor/pom.xml +++ b/registration-processor/post-processor/pom.xml @@ -16,7 +16,7 @@ registration-processor-message-sender-stage - registration-processor-event-handler-stage + registration-processor-credential-requestor-stage registration-processor-registration-transaction-service diff --git a/registration-processor/post-processor/registration-processor-event-handler-stage/Dockerfile-not-used b/registration-processor/post-processor/registration-processor-credential-requestor-stage/Dockerfile-not-used similarity index 85% rename from registration-processor/post-processor/registration-processor-event-handler-stage/Dockerfile-not-used rename to registration-processor/post-processor/registration-processor-credential-requestor-stage/Dockerfile-not-used index 772f2dfdf07..2767feb48d7 100644 --- a/registration-processor/post-processor/registration-processor-event-handler-stage/Dockerfile-not-used +++ b/registration-processor/post-processor/registration-processor-credential-requestor-stage/Dockerfile-not-used @@ -36,7 +36,7 @@ ENV artifactory_url_env=${artifactory_url} # change volume to whichever storage directory you want to use for this container. VOLUME /home/logs -COPY ./target/registration-processor-printing-stage-*.jar registration-processor-printing-stage.jar +COPY ./target/registration-processor-credential-requestor-stage-*.jar registration-processor-credential-requestor-stage.jar CMD if [ "$is_glowroot_env" = "present" ]; then \ wget "${artifactory_url_env}"/artifactory/libs-release-local/io/mosip/testing/glowroot.zip ; \ @@ -44,12 +44,12 @@ CMD if [ "$is_glowroot_env" = "present" ]; then \ unzip glowroot.zip ; \ rm -rf glowroot.zip ; \ - sed -i 's//registration-processor-printing-stage/g' glowroot/glowroot.properties ; \ - java -Dspring.cloud.config.label="${spring_config_label_env}" -Dspring.profiles.active="${active_profile_env}" -Dspring.cloud.config.uri="${spring_config_url_env}" -jar -javaagent:glowroot/glowroot.jar registration-processor-printing-stage.jar ; \ + sed -i 's//registration-processor-credential-requestor-stage/g' glowroot/glowroot.properties ; \ + java -Dspring.cloud.config.label="${spring_config_label_env}" -Dspring.profiles.active="${active_profile_env}" -Dspring.cloud.config.uri="${spring_config_url_env}" -jar -javaagent:glowroot/glowroot.jar registration-processor-credential-requestor-stage.jar ; \ else \ - java -Dspring.cloud.config.label="${spring_config_label_env}" -Dspring.profiles.active="${active_profile_env}" -Dspring.cloud.config.uri="${spring_config_url_env}" -jar registration-processor-printing-stage.jar ; \ + java -Dspring.cloud.config.label="${spring_config_label_env}" -Dspring.profiles.active="${active_profile_env}" -Dspring.cloud.config.uri="${spring_config_url_env}" -jar registration-processor-credential-requestor-stage.jar ; \ fi -#CMD ["java","-Dspring.cloud.config.label=${spring_config_label_env}","-Dspring.profiles.active=${active_profile_env}","-Dspring.cloud.config.uri=${spring_config_url_env}","-jar","registration-processor-printing-stage.jar"] +#CMD ["java","-Dspring.cloud.config.label=${spring_config_label_env}","-Dspring.profiles.active=${active_profile_env}","-Dspring.cloud.config.uri=${spring_config_url_env}","-jar","registration-processor-credential-requestor-stage.jar"] diff --git a/registration-processor/post-processor/registration-processor-event-handler-stage/README.md b/registration-processor/post-processor/registration-processor-credential-requestor-stage/README.md similarity index 100% rename from registration-processor/post-processor/registration-processor-event-handler-stage/README.md rename to registration-processor/post-processor/registration-processor-credential-requestor-stage/README.md diff --git a/registration-processor/post-processor/registration-processor-event-handler-stage/pom.xml b/registration-processor/post-processor/registration-processor-credential-requestor-stage/pom.xml similarity index 97% rename from registration-processor/post-processor/registration-processor-event-handler-stage/pom.xml rename to registration-processor/post-processor/registration-processor-credential-requestor-stage/pom.xml index 225a1f84a19..8df5b0653f1 100644 --- a/registration-processor/post-processor/registration-processor-event-handler-stage/pom.xml +++ b/registration-processor/post-processor/registration-processor-credential-requestor-stage/pom.xml @@ -8,7 +8,7 @@ post-processor 1.2.1-SNAPSHOT - registration-processor-event-handler-stage + registration-processor-credential-requestor-stage 1.2.1-SNAPSHOT UTF-8 diff --git a/registration-processor/post-processor/registration-processor-event-handler-stage/src/main/java/io/mosip/registration/processor/eventhandler/EventHandlerStageApplication.java b/registration-processor/post-processor/registration-processor-credential-requestor-stage/src/main/java/io/mosip/registration/processor/credentialrequestor/CredentialRequestorStageApplication.java similarity index 68% rename from registration-processor/post-processor/registration-processor-event-handler-stage/src/main/java/io/mosip/registration/processor/eventhandler/EventHandlerStageApplication.java rename to registration-processor/post-processor/registration-processor-credential-requestor-stage/src/main/java/io/mosip/registration/processor/credentialrequestor/CredentialRequestorStageApplication.java index fc0eda3ced1..25c6ce2c4be 100644 --- a/registration-processor/post-processor/registration-processor-event-handler-stage/src/main/java/io/mosip/registration/processor/eventhandler/EventHandlerStageApplication.java +++ b/registration-processor/post-processor/registration-processor-credential-requestor-stage/src/main/java/io/mosip/registration/processor/credentialrequestor/CredentialRequestorStageApplication.java @@ -1,14 +1,14 @@ -package io.mosip.registration.processor.eventhandler; +package io.mosip.registration.processor.credentialrequestor; import org.springframework.context.annotation.AnnotationConfigApplicationContext; -import io.mosip.registration.processor.eventhandler.stage.EventHandlerStage; +import io.mosip.registration.processor.credentialrequestor.stage.CredentialRequestorStage; /** * @author M1048399 * */ -public class EventHandlerStageApplication { +public class CredentialRequestorStageApplication { public static void main(String[] args) { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); @@ -19,7 +19,7 @@ public static void main(String[] args) { "io.mosip.registration.processor.packet.storage.config"); ctx.refresh(); - EventHandlerStage printStage = ctx.getBean(EventHandlerStage.class); + CredentialRequestorStage printStage = ctx.getBean(CredentialRequestorStage.class); printStage.deployVerticle(); } diff --git a/registration-processor/post-processor/registration-processor-credential-requestor-stage/src/main/java/io/mosip/registration/processor/credentialrequestor/config/CredentialRequestorConfigBean.java b/registration-processor/post-processor/registration-processor-credential-requestor-stage/src/main/java/io/mosip/registration/processor/credentialrequestor/config/CredentialRequestorConfigBean.java new file mode 100644 index 00000000000..344cb73d687 --- /dev/null +++ b/registration-processor/post-processor/registration-processor-credential-requestor-stage/src/main/java/io/mosip/registration/processor/credentialrequestor/config/CredentialRequestorConfigBean.java @@ -0,0 +1,15 @@ +package io.mosip.registration.processor.credentialrequestor.config; + +import io.mosip.registration.processor.credentialrequestor.util.CredentialPartnerUtil; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class CredentialRequestorConfigBean { + + @Bean + CredentialPartnerUtil credentialPartnerUtil() { + return new CredentialPartnerUtil(); + } + +} \ No newline at end of file diff --git a/registration-processor/post-processor/registration-processor-event-handler-stage/src/main/java/io/mosip/registration/processor/eventhandler/stage/EventHandlerStage.java b/registration-processor/post-processor/registration-processor-credential-requestor-stage/src/main/java/io/mosip/registration/processor/credentialrequestor/stage/CredentialRequestorStage.java similarity index 89% rename from registration-processor/post-processor/registration-processor-event-handler-stage/src/main/java/io/mosip/registration/processor/eventhandler/stage/EventHandlerStage.java rename to registration-processor/post-processor/registration-processor-credential-requestor-stage/src/main/java/io/mosip/registration/processor/credentialrequestor/stage/CredentialRequestorStage.java index 2329d5df7ab..31d97fce51f 100644 --- a/registration-processor/post-processor/registration-processor-event-handler-stage/src/main/java/io/mosip/registration/processor/eventhandler/stage/EventHandlerStage.java +++ b/registration-processor/post-processor/registration-processor-credential-requestor-stage/src/main/java/io/mosip/registration/processor/credentialrequestor/stage/CredentialRequestorStage.java @@ -1,4 +1,4 @@ -package io.mosip.registration.processor.eventhandler.stage; +package io.mosip.registration.processor.credentialrequestor.stage; import com.fasterxml.jackson.databind.ObjectMapper; import io.mosip.kernel.core.exception.ServiceError; @@ -26,13 +26,16 @@ import io.mosip.registration.processor.core.status.util.StatusUtil; import io.mosip.registration.processor.core.status.util.TrimExceptionMessage; import io.mosip.registration.processor.core.util.JsonUtil; +import io.mosip.registration.processor.packet.storage.exception.ParsingException; import io.mosip.registration.processor.packet.storage.utils.Utilities; -import io.mosip.registration.processor.eventhandler.stage.exception.VidNotAvailableException; -import io.mosip.registration.processor.eventhandler.util.CredentialPartnerUtil; +import io.mosip.registration.processor.credentialrequestor.stage.exception.VidNotAvailableException; +import io.mosip.registration.processor.credentialrequestor.util.CredentialPartnerUtil; import io.mosip.registration.processor.rest.client.audit.builder.AuditLogRequestBuilder; +import io.mosip.registration.processor.status.code.RegistrationStatusCode; import io.mosip.registration.processor.status.dto.InternalRegistrationStatusDto; import io.mosip.registration.processor.status.dto.RegistrationStatusDto; import io.mosip.registration.processor.status.service.RegistrationStatusService; +import org.apache.commons.lang.StringUtils; import org.apache.commons.lang3.exception.ExceptionUtils; import org.json.JSONArray; import org.json.JSONException; @@ -70,7 +73,7 @@ @ComponentScan(basePackages = { "${mosip.auth.adapter.impl.basepackage}", "io.mosip.registration.processor.core.config", "io.mosip.registration.processor.stages.config", - "io.mosip.registration.processor.eventhandler.config", + "io.mosip.registration.processor.credentialrequestor.config", "io.mosip.registrationprocessor.stages.config", "io.mosip.registration.processor.status.config", "io.mosip.registration.processor.rest.client.config", @@ -78,9 +81,9 @@ "io.mosip.registration.processor.packet.manager.config", "io.mosip.kernel.idobjectvalidator.config", "io.mosip.registration.processor.core.kernel.beans" }) -public class EventHandlerStage extends MosipVerticleAPIManager { +public class CredentialRequestorStage extends MosipVerticleAPIManager { - private static final String STAGE_PROPERTY_PREFIX = "mosip.regproc.printing."; + private static final String STAGE_PROPERTY_PREFIX = "mosip.regproc.credentialrequestor."; private Random sr = null; private static final int max = 999999; private static final int min = 100000; @@ -90,7 +93,7 @@ public class EventHandlerStage extends MosipVerticleAPIManager { /** The reg proc logger. */ - private static Logger regProcLogger = RegProcessorLogger.getLogger(EventHandlerStage.class); + private static Logger regProcLogger = RegProcessorLogger.getLogger(CredentialRequestorStage.class); /** The cluster manager url. */ @Value("${vertx.cluster.configuration}") @@ -113,7 +116,7 @@ public class EventHandlerStage extends MosipVerticleAPIManager { private Integer workerPoolSize; /** After this time intervel, message should be considered as expired (In seconds). */ - @Value("${mosip.regproc.printing.message.expiry-time-limit}") + @Value("${mosip.regproc.credentialrequestor.message.expiry-time-limit}") private Long messageExpiryTimeLimit; @Value("${mosip.registration.processor.encrypt:false}") @@ -152,8 +155,8 @@ public class EventHandlerStage extends MosipVerticleAPIManager { @Value("#{T(java.util.Arrays).asList('${mosip.registration.processor.default.issuers:}')}") private List defaultIssuers; - @Value("${mosip.registration.processor.opencrvs.credential.additionalparams}") - private String opencrvsAdditionalParam; + @Value("${mosip.registration.processor.additional.credential.request:}") + private String additionalConfiguredCredentials; private static String COMMA = ","; private static String HASH_DELIMITER = "#"; @@ -382,48 +385,55 @@ private CredentialRequestDto getCredentialRequestDto(String regId, String proces credentialRequestDto.setEncryptionKey(generatePin()); additionalAttributes.put("templateTypeCode",templateTypeCode); additionalAttributes.put("registrationId", regId); - getOpencrvsFields(regId, process, issuerId, credentialType, additionalAttributes); + getAdditionalCredentialFields(regId, process, issuerId, credentialType, additionalAttributes); credentialRequestDto.setAdditionalData(additionalAttributes); return credentialRequestDto; } - private void getOpencrvsFields(String regId, String process, String issuerId, - String credentialType, Map additionalAttributes) { + private void getAdditionalCredentialFields(String regId, String process, String issuerId, + String credentialType, Map additionalAttributes) { + if (StringUtils.isEmpty(additionalConfiguredCredentials)) + return; try { - JSONArray jArray=new JSONArray(opencrvsAdditionalParam); + JSONArray jArray=new JSONArray(additionalConfiguredCredentials); for(int i=0;i metaInfo = utilities.getPacketManagerService().getMetaInfo(regId, process, ProviderStageName.EVENT_HANDLER); + Map metaInfo = utilities.getPacketManagerService().getMetaInfo(regId, process, ProviderStageName.CREDENTIAL_REQUESTOR); JSONArray metadata = new JSONArray(metaInfo.get("metaData")); for(int i=0;i io.mosip.registrationprocessor - registration-processor-event-handler-stage + registration-processor-credential-requestor-stage 1.2.1-SNAPSHOT From 6d3063f40213f01117425414fb7eac8089f619ba Mon Sep 17 00:00:00 2001 From: Monobikash Das Date: Fri, 22 Sep 2023 14:55:16 +0530 Subject: [PATCH 23/38] MOSIP-28121 : Fixed review comments Signed-off-by: Monobikash Das --- registration-processor/pom.xml | 9 ++------- .../README.md | 2 +- 2 files changed, 3 insertions(+), 8 deletions(-) diff --git a/registration-processor/pom.xml b/registration-processor/pom.xml index 33fddc4b218..d6c32faf9bd 100644 --- a/registration-processor/pom.xml +++ b/registration-processor/pom.xml @@ -230,9 +230,8 @@ **/registration/processor/core/queue/impl/*.java, **/registration/processor/core/tracing/*.java, **/registration/processor/message/sender/config/MsgNotificationBeanCofig.java, - **/registration/processor/eventhandler/exception/QueueConnectionNotFound.java, + **/registration/processor/abis/exception/QueueConnectionNotFound.java, **/registration/processor/stages/demodedupe/StatusMessage.java, - **/registration/processor/eventhandler/service/utility/UINCardConstant.java, **/registration/processor/stages/demodedupe/BiometricValidation.java, **/registration/processor/camel/bridge/MosipBridgeFactory.java, **/registration/processor/manual/verification/stage/ManualVerificationStage.java, @@ -246,17 +245,13 @@ **/registration/processor/packet/storage/dao/PacketInfoDao.java, **/registration/processor/packet/uploader/constants/*.java, **/registration/processor/packet/manager/constant/*.java, - **/registration/processor/eventhandler/exception/PrintGlobalExceptionHandler.java, **/registration/processor/packet/receiver/constants/*.java, - **/registration/processor/eventhandler/service/exception/*.java, - **/registration/processor/eventhandler/exception/*.java, + **/registration/processor/credentialrequestor/stage/exception/*.java, **/registration/processor/packet/uploader/constants/*.java, **/registration/processor/packet/uploader/decryptor/*.java, **/registration/processor/core/abstractverticle/MosipRouter.java, **/registration/processor/packet/uploader/decryptor/*.java, - **/registration/processor/eventhandler/service/impl/PrintPostServiceImpl.java, - **/registration/processor/message/sender/constants/*.java, **/registration/processor/core/abstractverticle/BaseHealthCheckModel.java, **/registration/processor/core/**/TokenValidator.java, diff --git a/registration-processor/post-processor/registration-processor-credential-requestor-stage/README.md b/registration-processor/post-processor/registration-processor-credential-requestor-stage/README.md index 972ed13d764..320dffd6672 100644 --- a/registration-processor/post-processor/registration-processor-credential-requestor-stage/README.md +++ b/registration-processor/post-processor/registration-processor-credential-requestor-stage/README.md @@ -1,4 +1,4 @@ -# Event handler Stage +# Credential Requestor Stage ## About Creates Credential Request for internal/external systems. From 2eb013b40c16b3834247bef5ffbbbe45915bc12c Mon Sep 17 00:00:00 2001 From: Monobikash Das Date: Wed, 8 Nov 2023 12:23:42 +0530 Subject: [PATCH 24/38] MOSIP-28121 : added partner profile feature Signed-off-by: Monobikash Das --- .../dto/CredentialPartner.java | 16 ++ .../dto/CredentialPartnersList.java | 10 + .../stage/CredentialRequestorStage.java | 185 +++++++----------- .../util/CredentialPartnerUtil.java | 146 +++++++++----- .../test/CredentialRequestorStageTest.java | 37 +++- .../exception/util/PlatformErrorMessages.java | 2 +- 6 files changed, 216 insertions(+), 180 deletions(-) create mode 100644 registration-processor/post-processor/registration-processor-credential-requestor-stage/src/main/java/io/mosip/registration/processor/credentialrequestor/dto/CredentialPartner.java create mode 100644 registration-processor/post-processor/registration-processor-credential-requestor-stage/src/main/java/io/mosip/registration/processor/credentialrequestor/dto/CredentialPartnersList.java diff --git a/registration-processor/post-processor/registration-processor-credential-requestor-stage/src/main/java/io/mosip/registration/processor/credentialrequestor/dto/CredentialPartner.java b/registration-processor/post-processor/registration-processor-credential-requestor-stage/src/main/java/io/mosip/registration/processor/credentialrequestor/dto/CredentialPartner.java new file mode 100644 index 00000000000..4cd399b0e5b --- /dev/null +++ b/registration-processor/post-processor/registration-processor-credential-requestor-stage/src/main/java/io/mosip/registration/processor/credentialrequestor/dto/CredentialPartner.java @@ -0,0 +1,16 @@ +package io.mosip.registration.processor.credentialrequestor.dto; + +import lombok.Data; + +import java.util.List; + +@Data +public class CredentialPartner { + private String id; + private String partnerId; + private String credentialType; + private String template; + private String appIdBasedCredentialIdSuffix; + private List process; + private List metaInfoFields; +} diff --git a/registration-processor/post-processor/registration-processor-credential-requestor-stage/src/main/java/io/mosip/registration/processor/credentialrequestor/dto/CredentialPartnersList.java b/registration-processor/post-processor/registration-processor-credential-requestor-stage/src/main/java/io/mosip/registration/processor/credentialrequestor/dto/CredentialPartnersList.java new file mode 100644 index 00000000000..72afbab0056 --- /dev/null +++ b/registration-processor/post-processor/registration-processor-credential-requestor-stage/src/main/java/io/mosip/registration/processor/credentialrequestor/dto/CredentialPartnersList.java @@ -0,0 +1,10 @@ +package io.mosip.registration.processor.credentialrequestor.dto; + +import lombok.Data; + +import java.util.List; + +@Data +public class CredentialPartnersList { + private List partners; +} diff --git a/registration-processor/post-processor/registration-processor-credential-requestor-stage/src/main/java/io/mosip/registration/processor/credentialrequestor/stage/CredentialRequestorStage.java b/registration-processor/post-processor/registration-processor-credential-requestor-stage/src/main/java/io/mosip/registration/processor/credentialrequestor/stage/CredentialRequestorStage.java index 31d97fce51f..74b1d6c6ddd 100644 --- a/registration-processor/post-processor/registration-processor-credential-requestor-stage/src/main/java/io/mosip/registration/processor/credentialrequestor/stage/CredentialRequestorStage.java +++ b/registration-processor/post-processor/registration-processor-credential-requestor-stage/src/main/java/io/mosip/registration/processor/credentialrequestor/stage/CredentialRequestorStage.java @@ -1,16 +1,17 @@ package io.mosip.registration.processor.credentialrequestor.stage; import com.fasterxml.jackson.databind.ObjectMapper; +import io.mosip.kernel.core.exception.BaseUncheckedException; import io.mosip.kernel.core.exception.ServiceError; import io.mosip.kernel.core.logger.spi.Logger; import io.mosip.kernel.core.util.DateUtils; import io.mosip.registration.processor.core.abstractverticle.*; import io.mosip.registration.processor.core.code.*; +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.common.rest.dto.ErrorDTO; -import io.mosip.registration.processor.core.constant.IdType; -import io.mosip.registration.processor.core.constant.LoggerFileConstant; -import io.mosip.registration.processor.core.constant.ProviderStageName; -import io.mosip.registration.processor.core.constant.VidType; +import io.mosip.registration.processor.core.constant.*; import io.mosip.registration.processor.core.exception.ApisResourceAccessException; import io.mosip.registration.processor.core.exception.util.PlatformErrorMessages; import io.mosip.registration.processor.core.exception.util.PlatformSuccessMessages; @@ -26,15 +27,17 @@ import io.mosip.registration.processor.core.status.util.StatusUtil; import io.mosip.registration.processor.core.status.util.TrimExceptionMessage; import io.mosip.registration.processor.core.util.JsonUtil; -import io.mosip.registration.processor.packet.storage.exception.ParsingException; -import io.mosip.registration.processor.packet.storage.utils.Utilities; +import io.mosip.registration.processor.credentialrequestor.dto.CredentialPartner; import io.mosip.registration.processor.credentialrequestor.stage.exception.VidNotAvailableException; import io.mosip.registration.processor.credentialrequestor.util.CredentialPartnerUtil; +import io.mosip.registration.processor.packet.storage.exception.ParsingException; +import io.mosip.registration.processor.packet.storage.utils.Utilities; import io.mosip.registration.processor.rest.client.audit.builder.AuditLogRequestBuilder; import io.mosip.registration.processor.status.code.RegistrationStatusCode; import io.mosip.registration.processor.status.dto.InternalRegistrationStatusDto; import io.mosip.registration.processor.status.dto.RegistrationStatusDto; import io.mosip.registration.processor.status.service.RegistrationStatusService; +import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang3.exception.ExceptionUtils; import org.json.JSONArray; @@ -51,13 +54,13 @@ import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; -import java.io.File; import java.io.IOException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.*; +import java.util.stream.Collectors; /** * The Class PrintStage. @@ -88,10 +91,6 @@ public class CredentialRequestorStage extends MosipVerticleAPIManager { private static final int max = 999999; private static final int min = 100000; - /** The Constant FILE_SEPARATOR. */ - public static final String FILE_SEPARATOR = File.separator; - - /** The reg proc logger. */ private static Logger regProcLogger = RegProcessorLogger.getLogger(CredentialRequestorStage.class); @@ -122,15 +121,10 @@ public class CredentialRequestorStage extends MosipVerticleAPIManager { @Value("${mosip.registration.processor.encrypt:false}") private boolean encrypt; - @Value("#{${mosip.registration.processor.print.issuer.config-map:{}}}") - private Map credentialPartnerMap; - /** Mosip router for APIs */ @Autowired MosipRouter router; - boolean isConnection = false; - private static final String SEPERATOR = "::"; @Autowired @@ -146,17 +140,8 @@ public class CredentialRequestorStage extends MosipVerticleAPIManager { private static final String ISSUERS = "mosip.registration.processor.issuer"; - @Value("${mosip.registration.processor.rid.delimiter:-PDF}") - private String pdfDelimiter; - - @Value("#{T(java.util.Arrays).asList('${mosip.registration.processor.default.internal.issuers:}')}") - private List defaultInternalIssuers; - - @Value("#{T(java.util.Arrays).asList('${mosip.registration.processor.default.issuers:}')}") - private List defaultIssuers; - - @Value("${mosip.registration.processor.additional.credential.request:}") - private String additionalConfiguredCredentials; + @Value("#{T(java.util.Arrays).asList('${mosip.registration.processor.credential.default.partner-ids:}')}") + private List defaultPartners; private static String COMMA = ","; private static String HASH_DELIMITER = "#"; @@ -198,6 +183,7 @@ public MessageDTO process(MessageDTO object) { boolean isTransactionSuccessful = false; String uin = null; + String refIds = null; String regId = object.getRid(); regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), regId, "PrintStage::process()::entry"); @@ -232,56 +218,59 @@ public MessageDTO process(MessageDTO object) { .setLatestTransactionTypeCode(RegistrationTransactionTypeCode.PRINT_SERVICE.toString()); } else { - String vid = getVid(uin); requestWrapper.setId(env.getProperty("mosip.registration.processor.credential.request.service.id")); DateTimeFormatter format = DateTimeFormatter.ofPattern(env.getProperty(DATETIME_PATTERN)); requestWrapper.setVersion("1.0"); - Set credentialIssuerSet = new HashSet<>(); - credentialIssuerSet.addAll(defaultInternalIssuers); - credentialIssuerSet.addAll(defaultIssuers); - if (credentialPartnerMap != null && !credentialPartnerMap.isEmpty()) { - credentialIssuerSet.addAll(credentialPartnerUtil.getCredentialPartners( - regId, registrationStatusDto.getRegistrationType(), jsonObject)); - } - for (String key : credentialIssuerSet) { - String[] parts = key.split(HASH_DELIMITER, 3); - CredentialRequestDto credentialRequestDto = getCredentialRequestDto(regId, registrationStatusDto.getRegistrationType(), parts[0], parts[1], parts[2]); + List allIssuerList = credentialPartnerUtil.getAllCredentialPartners().getPartners(); + // filtering with default partner ids and process + List filteredPartners = allIssuerList.stream() + .filter(issuer -> defaultPartners.contains(issuer.getId())) + .filter(issuer -> (issuer.getProcess() == null) || (issuer.getProcess().contains(object.getReg_type()))) + .collect(Collectors.toList()); + filteredPartners.addAll(credentialPartnerUtil.getCredentialPartners( + regId, registrationStatusDto.getRegistrationType(), jsonObject)); + for (CredentialPartner key : filteredPartners) { + CredentialRequestDto credentialRequestDto = getCredentialRequestDto(regId, registrationStatusDto.getRegistrationType(), key); LocalDateTime localdatetime = LocalDateTime.parse( DateUtils.getUTCCurrentDateTimeString(env.getProperty(DATETIME_PATTERN)), format); requestWrapper.setRequesttime(localdatetime); requestWrapper.setRequest(credentialRequestDto); - if (defaultInternalIssuers.contains(key)) { + // issuers with appIdBasedCredentialIdSuffix is calling v1 api and for others stage is calling v2 api for credential + if (StringUtils.isNotEmpty(key.getAppIdBasedCredentialIdSuffix())) { List pathsegments = new ArrayList<>(); - pathsegments.add(regId + pdfDelimiter); // #PDF suffix is added to identify the requested credential via rid + pathsegments.add(regId + key.getAppIdBasedCredentialIdSuffix()); // #PDF suffix is added to identify the requested credential via rid responseWrapper = (ResponseWrapper) restClientService.postApi(ApiName.CREDENTIALREQUESTV2, MediaType.APPLICATION_JSON, pathsegments, null, null, requestWrapper, ResponseWrapper.class); - } else { // for default issuer stage is calling v1 api and for others stage is calling v2 api for credential + } else { responseWrapper = (ResponseWrapper) restClientService.postApi(ApiName.CREDENTIALREQUEST, null, null, requestWrapper, ResponseWrapper.class, MediaType.APPLICATION_JSON); } - } - - if (responseWrapper.getErrors() != null && !responseWrapper.getErrors().isEmpty()) { - ErrorDTO error = responseWrapper.getErrors().get(0); - object.setIsValid(Boolean.FALSE); - isTransactionSuccessful = false; - description.setMessage(PlatformErrorMessages.RPR_PRT_PRINT_REQUEST_FAILED.getMessage()); - description.setCode(PlatformErrorMessages.RPR_PRT_PRINT_REQUEST_FAILED.getCode()); - - registrationStatusDto.setStatusComment( - StatusUtil.PRINT_REQUEST_FAILED.getMessage() + SEPERATOR + error.getMessage()); - registrationStatusDto.setSubStatusCode(StatusUtil.PRINT_REQUEST_FAILED.getCode()); - registrationStatusDto + if (responseWrapper.getErrors() != null && !responseWrapper.getErrors().isEmpty()) { + ErrorDTO error = responseWrapper.getErrors().get(0); + object.setIsValid(Boolean.FALSE); + isTransactionSuccessful = false; + registrationStatusDto.setRefId(refIds); + description.setMessage(PlatformErrorMessages.RPR_PRT_PRINT_REQUEST_FAILED.getMessage()); + description.setCode(PlatformErrorMessages.RPR_PRT_PRINT_REQUEST_FAILED.getCode()); + + registrationStatusDto.setStatusComment( + StatusUtil.PRINT_REQUEST_FAILED.getMessage() + SEPERATOR + error.getMessage()); + registrationStatusDto.setSubStatusCode(StatusUtil.PRINT_REQUEST_FAILED.getCode()); + registrationStatusDto .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.REPROCESS.toString()); - registrationStatusDto - .setLatestTransactionTypeCode(RegistrationTransactionTypeCode.PRINT_SERVICE.toString()); - } else { - credentialResponseDto = mapper.readValue(mapper.writeValueAsString(responseWrapper.getResponse()), - CredentialResponseDto.class); - - registrationStatusDto.setRefId(credentialResponseDto.getRequestId()); + registrationStatusDto + .setLatestTransactionTypeCode(RegistrationTransactionTypeCode.PRINT_SERVICE.toString()); + break; + } else { + credentialResponseDto = mapper.readValue(mapper.writeValueAsString(responseWrapper.getResponse()), + CredentialResponseDto.class); + refIds = credentialResponseDto.getRequestId(); + isTransactionSuccessful = true; + } + } + if (isTransactionSuccessful) { + registrationStatusDto.setRefId(refIds); object.setIsValid(Boolean.TRUE); - isTransactionSuccessful = true; description.setMessage(PlatformSuccessMessages.RPR_PRINT_STAGE_REQUEST_SUCCESS.getMessage()); description.setCode(PlatformSuccessMessages.RPR_PRINT_STAGE_REQUEST_SUCCESS.getCode()); registrationStatusDto.setStatusComment( @@ -320,18 +309,6 @@ public MessageDTO process(MessageDTO object) { description.setMessage(PlatformErrorMessages.RPR_PRT_PRINT_REQUEST_FAILED.getMessage()); description.setCode(PlatformErrorMessages.RPR_PRT_PRINT_REQUEST_FAILED.getCode()); object.setInternalError(Boolean.TRUE); - } catch (VidNotAvailableException e) { - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - regId, PlatformErrorMessages.RPR_PRT_PRINT_REQUEST_FAILED.name() + e.getMessage() - + ExceptionUtils.getStackTrace(e)); - registrationStatusDto - .setLatestTransactionStatusCode(RegistrationTransactionStatusCode.REPROCESS.toString()); - registrationStatusDto.setStatusComment( - trimeExpMessage.trimExceptionMessage(StatusUtil.VID_NOT_AVAILABLE.getMessage())); - registrationStatusDto.setSubStatusCode(StatusUtil.VID_NOT_AVAILABLE.getCode()); - description.setMessage(PlatformErrorMessages.RPR_PRT_PRINT_REQUEST_FAILED.getMessage()); - description.setCode(PlatformErrorMessages.RPR_PRT_PRINT_REQUEST_FAILED.getCode()); - object.setInternalError(Boolean.TRUE); } catch (Exception e) { regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), regId, PlatformErrorMessages.RPR_PRT_PRINT_REQUEST_FAILED.name() + e.getMessage() @@ -371,72 +348,48 @@ public MessageDTO process(MessageDTO object) { return object; } - private CredentialRequestDto getCredentialRequestDto(String regId, String process, String issuerId,String credentialType,String templateTypeCode) { + private CredentialRequestDto getCredentialRequestDto(String regId, String process, CredentialPartner key) { CredentialRequestDto credentialRequestDto = new CredentialRequestDto(); Map additionalAttributes=new HashMap<>(); - credentialRequestDto.setCredentialType(credentialType); + credentialRequestDto.setCredentialType(key.getCredentialType()); credentialRequestDto.setEncrypt(encrypt); credentialRequestDto.setId(regId); - credentialRequestDto.setIssuer(issuerId); + credentialRequestDto.setIssuer(key.getPartnerId()); credentialRequestDto.setEncryptionKey(generatePin()); - additionalAttributes.put("templateTypeCode",templateTypeCode); + additionalAttributes.put("templateTypeCode", key.getTemplate()); additionalAttributes.put("registrationId", regId); - getAdditionalCredentialFields(regId, process, issuerId, credentialType, additionalAttributes); + if (CollectionUtils.isNotEmpty(key.getMetaInfoFields())) + getAdditionalCredentialFields(regId, process, key.getMetaInfoFields(), additionalAttributes); credentialRequestDto.setAdditionalData(additionalAttributes); return credentialRequestDto; } - private void getAdditionalCredentialFields(String regId, String process, String issuerId, - String credentialType, Map additionalAttributes) { - if (StringUtils.isEmpty(additionalConfiguredCredentials)) - return; + private void getAdditionalCredentialFields(String regId, String process, + List metaInfoFields, + Map additionalAttributes) { try { - JSONArray jArray=new JSONArray(additionalConfiguredCredentials); - for(int i=0;i metaInfo = utilities.getPacketManagerService().getMetaInfo(regId, process, ProviderStageName.CREDENTIAL_REQUESTOR); + JSONArray metadata = new JSONArray(metaInfo.get(JsonConstant.METADATA)); + for(int i=0; i metaInfo = utilities.getPacketManagerService().getMetaInfo(regId, process, ProviderStageName.CREDENTIAL_REQUESTOR); - JSONArray metadata = new JSONArray(metaInfo.get("metaData")); - for(int i=0;i mandatoryLanguages; - @Value("${mosip.registration.processor.print.issuer.noMatch}") + @Value("${mosip.registration.processor.credential.conditional.no-match-partner-ids}") private String noMatchIssuer; - @Value("#{${mosip.registration.processor.print.issuer.config-map:{}}}") + @Value("#{${mosip.registration.processor.credential.conditional.partner-id-map:{}}}") private Map credentialPartnerExpression; + @Value("${config.server.file.storage.uri}") + private String configServerFileStorageURL; + /** * This map will hold the actual field names after resolving, using mapping JSON as keys and * configured field names as values @@ -65,7 +82,7 @@ public class CredentialPartnerUtil { */ private List requiredIdObjectFieldNames; - public List getCredentialPartners(String regId, String registrationType, JSONObject identity) throws PacketManagerException, JSONException, ApisResourceAccessException, IOException, JsonProcessingException { + public List getCredentialPartners(String regId, String registrationType, JSONObject identity) throws PacketManagerException, JSONException, ApisResourceAccessException, IOException, JsonProcessingException { regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), regId, "CredentialPartnerUtil::getCredentialPartners()::entry"); @@ -75,35 +92,50 @@ public List getCredentialPartners(String regId, String registrationType, regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), regId, PlatformErrorMessages.RPR_PRT_ISSUER_NOT_FOUND_IN_PROPERTY.name()); - return filteredPartners; + return Lists.emptyList(); } + String schemaVersion = utilities.getPacketManagerService().getFieldByMappingJsonKey(regId, + MappingJsonConstants.IDSCHEMA_VERSION, registrationType, ProviderStageName.CREDENTIAL_REQUESTOR); + Map identityFieldValueMap = utilities.getPacketManagerService().getFields(regId, - requiredIdObjectFieldNames, registrationType, ProviderStageName.EVENT_HANDLER); + idSchemaUtil.getDefaultFields(Double.valueOf(schemaVersion)), registrationType, ProviderStageName.CREDENTIAL_REQUESTOR); Map context = new HashMap<>(); for (Map.Entry identityAttribute: identityFieldValueMap.entrySet()) { JSONObject attributeObject = new JSONObject(identityFieldValueMap); try { - JSONParser parser = new JSONParser(); - Object obj = parser.parse((String)attributeObject.get(identityAttribute.getKey())); - if (obj instanceof org.json.simple.JSONArray) { - org.json.simple.JSONArray attributeArray = (org.json.simple.JSONArray) obj; - for (int i = 0; i < attributeArray.size(); i++) { - JSONObject jsonObject = (JSONObject) attributeArray.get(i); - if (mandatoryLanguages.get(0).equalsIgnoreCase((String) jsonObject.get(LANGUAGE))) { - context.put(identityAttribute.getKey(), jsonObject.get(VALUE_LABEL)); + if (identityAttribute.getKey() != null && identityAttribute.getValue() != null) { + Object obj = attributeObject.get(identityAttribute.getKey()); + if (obj instanceof org.json.simple.JSONArray) { + org.json.simple.JSONArray attributeArray = (org.json.simple.JSONArray) obj; + for (int i = 0; i < attributeArray.size(); i++) { + JSONObject jsonObject = (JSONObject) attributeArray.get(i); + if (mandatoryLanguages.get(0).equalsIgnoreCase((String) jsonObject.get(LANGUAGE))) { + context.put(identityAttribute.getKey(), jsonObject.get(VALUE_LABEL)); + } + } + } else { + if (obj != null) { + context.put(identityAttribute.getKey(), obj.toString()); } } - } else { - if (obj != null) { - context.put(identityAttribute.getKey(), obj.toString()); - } - } - } catch (org.json.simple.parser.ParseException e) { + } else + context.put(identityAttribute.getKey(), identityAttribute.getValue()); + } catch (Exception e) { regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), "", ExceptionUtils.getStackTrace(e)); - throw new ParsingException(PlatformErrorMessages.RPR_BDD_JSON_PARSING_EXCEPTION.getCode(), e); + throw new ParsingException(PlatformErrorMessages.RPR_PRT_DATA_VALIDATION_FAILED.getCode(), e); + } + } + + // adding additional metadata so that it can be used for MVEL expression + Map metaInfo = utilities.getPacketManagerService().getMetaInfo(regId, registrationType, ProviderStageName.CREDENTIAL_REQUESTOR); + if (MapUtils.isNotEmpty(metaInfo)) { + String metadata = metaInfo.get(JsonConstant.METADATA); + if (!StringUtils.isEmpty(metadata)) { + JSONArray jsonArray = new JSONArray(metadata); + addToMap(jsonArray, context); } } @@ -122,36 +154,42 @@ public List getCredentialPartners(String regId, String registrationType, regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), regId, "CredentialPartnerUtil::FilteredPartners::" + filteredPartners.toString()); - return filteredPartners; + List finalList = new ArrayList<>(); + if (!filteredPartners.isEmpty()) { + filteredPartners.forEach( + p -> { + Optional partner = credentialPartners.getPartners() + .stream().filter(pr -> pr.getId().equalsIgnoreCase(p)).findAny(); + if (partner.isPresent()) + finalList.add(partner.get()); + }); + } + return finalList; + } + + private void addToMap(JSONArray jsonArray, Map allMap) throws JSONException, IOException { + for (int i =0; i < jsonArray.length(); i++) { + org.json.JSONObject jsonObject = (org.json.JSONObject) jsonArray.get(i); + FieldValue fieldValue = objectMapper.readValue(jsonObject.toString(), FieldValue.class); + allMap.put(fieldValue.getLabel(), fieldValue.getValue()); + } } @PostConstruct - private void getIdObjectFieldNames() throws BaseCheckedException { - regProcLogger.info( "CredentialPartnerUtil::getIdObjectFieldNames()::PostConstruct"); + public void loadPartnerDetails() throws RegistrationProcessorCheckedException { try { - org.json.simple.JSONObject identityMappingJson = - utilities.getRegistrationProcessorMappingJson(MappingJsonConstants.IDENTITY); - requiredIDObjectFieldNamesMap = new HashMap<>(); - for(Map.Entry expressionEntry : credentialPartnerExpression.entrySet()) { - ParserContext parserContext = ParserContext.create(); - MVEL.analysisCompile(expressionEntry.getValue(), parserContext); - Map expressionVariablesMap = parserContext.getInputs(); - for(Map.Entry variableEntry: expressionVariablesMap.entrySet()) { - String actualFieldName = JsonUtil.getJSONValue( - JsonUtil.getJSONObject(identityMappingJson, variableEntry.getKey()), - VALUE_LABEL); - if(actualFieldName == null) - throw new BaseCheckedException( - PlatformErrorMessages.RPR_PCM_FIELD_NAME_NOT_AVAILABLE_IN_MAPPING_JSON.getCode(), - PlatformErrorMessages.RPR_PCM_FIELD_NAME_NOT_AVAILABLE_IN_MAPPING_JSON.getMessage()); - requiredIDObjectFieldNamesMap.put(actualFieldName, variableEntry.getKey()); - } - } - requiredIdObjectFieldNames = requiredIDObjectFieldNamesMap.keySet().stream().collect(Collectors.toList()); - } catch (IOException e) { - throw new BaseCheckedException( - PlatformErrorMessages.RPR_PCM_ACCESSING_IDOBJECT_MAPPING_FILE_FAILED.getCode(), - PlatformErrorMessages.RPR_PCM_ACCESSING_IDOBJECT_MAPPING_FILE_FAILED.getMessage(), e); + String partners = Utilities.getJson(configServerFileStorageURL, partnerProfileFileName); + credentialPartners = JsonUtil.readValueWithUnknownProperties(partners, CredentialPartnersList.class); + } catch (Exception e) { + regProcLogger.error("Error loading credential Partners", e); + throw new RegistrationProcessorCheckedException(PlatformErrorMessages.RPR_SYS_IO_EXCEPTION.getCode(), + PlatformErrorMessages.RPR_SYS_IO_EXCEPTION.getMessage(), e); } } + + public CredentialPartnersList getAllCredentialPartners() throws RegistrationProcessorCheckedException { + if (credentialPartners == null) + loadPartnerDetails(); + return credentialPartners; + } } diff --git a/registration-processor/post-processor/registration-processor-credential-requestor-stage/src/test/java/io/mosip/registrationprocessor/credentialrequestor/test/CredentialRequestorStageTest.java b/registration-processor/post-processor/registration-processor-credential-requestor-stage/src/test/java/io/mosip/registrationprocessor/credentialrequestor/test/CredentialRequestorStageTest.java index 44222ed7955..c20ece9327b 100644 --- a/registration-processor/post-processor/registration-processor-credential-requestor-stage/src/test/java/io/mosip/registrationprocessor/credentialrequestor/test/CredentialRequestorStageTest.java +++ b/registration-processor/post-processor/registration-processor-credential-requestor-stage/src/test/java/io/mosip/registrationprocessor/credentialrequestor/test/CredentialRequestorStageTest.java @@ -14,6 +14,10 @@ import java.util.List; import java.util.Map; +import io.mosip.registration.processor.credentialrequestor.dto.CredentialPartner; +import io.mosip.registration.processor.credentialrequestor.dto.CredentialPartnersList; +import io.mosip.registration.processor.credentialrequestor.util.CredentialPartnerUtil; +import org.assertj.core.util.Lists; import org.json.simple.JSONObject; import org.junit.Before; import org.junit.Test; @@ -85,6 +89,9 @@ public class CredentialRequestorStageTest { @Mock protected PropertiesUtil propertiesUtil; + @Mock + private CredentialPartnerUtil credentialPartnerUtil; + @Mock private ObjectMapper objectMapper; @@ -192,10 +199,7 @@ public void setup() throws Exception { ReflectionTestUtils.setField(stage, "messageExpiryTimeLimit", Long.valueOf(0)); ReflectionTestUtils.setField(stage, "clusterManagerUrl", "/dummyPath"); ReflectionTestUtils.setField(stage, "busOutHaltAddresses", Arrays.asList()); - ReflectionTestUtils.setField(stage, "pdfDelimiter", "-PDF"); - ReflectionTestUtils.setField(stage, "defaultInternalIssuers", Arrays.asList("mpartner-default-digitalcard#PDFCard#RPR_UIN_CARD_TEMPLATE")); - ReflectionTestUtils.setField(stage, "defaultIssuers", Arrays.asList("mpartner-default-print#euin#RPR_UIN_CARD_TEMPLATE")); - ReflectionTestUtils.setField(stage, "additionalConfiguredCredentials", "[{'process':'OPENCRVS_NEW','credentialType':'opencrvs','issuer':'opencrvs-partner','fields':['opencrvsBRN']}]"); + ReflectionTestUtils.setField(stage, "defaultPartners", Arrays.asList("digitalcardPartner", "opencrvsPartner")); System.setProperty("server.port", "8099"); @@ -245,6 +249,23 @@ public void setup() throws Exception { JSONObject jsonObject = new JSONObject(map1); Mockito.when(utitilites.retrieveUIN(any())).thenReturn(jsonObject); + CredentialPartner partner1 = new CredentialPartner(); + partner1.setId("digitalcardPartner"); + partner1.setPartnerId("mpartner-default-digitalcard"); + partner1.setCredentialType("PDFCard"); + partner1.setTemplate("RPR_UIN_CARD_TEMPLATE"); + partner1.setAppIdBasedCredentialIdSuffix(".pdf"); + + CredentialPartner partner2 = new CredentialPartner(); + partner2.setId("opencrvsPartner"); + partner2.setPartnerId("opencrvs-partner"); + partner2.setCredentialType("opencrvs"); + partner2.setTemplate("RPR_UIN_CARD_TEMPLATE"); + + CredentialPartnersList partnersList = new CredentialPartnersList(); + partnersList.setPartners(Lists.newArrayList(partner1, partner2)); + when(credentialPartnerUtil.getAllCredentialPartners()).thenReturn(partnersList); + } @@ -254,7 +275,6 @@ public void testAll() throws Exception { testDeployVerticle(); testStart(); testPrintStageSuccess(); - testPrintStageFailure(); } public void testStart() { @@ -302,7 +322,7 @@ public void testPrintStageFailure() throws ApisResourceAccessException { dto.setReg_type(RegistrationType.NEW.name()); - ResponseWrapper responseWrapper = new ResponseWrapper<>(); + ResponseWrapper responseWrapper = new ResponseWrapper<>(); ErrorDTO error = new ErrorDTO(); error.setErrorCode("IDR-CRG-004"); error.setMessage("unknown exception"); @@ -310,12 +330,11 @@ public void testPrintStageFailure() throws ApisResourceAccessException { errors.add(error); responseWrapper.setErrors(errors); - Mockito.when(restClientService.postApi(any(), any(), any(), any(), any(), any(MediaType.class))) + Mockito.when(restClientService.postApi(any(ApiName.class), any(), any(), any(), any(), any(MediaType.class))) .thenReturn(responseWrapper); MessageDTO result = stage.process(dto); - assertFalse(result.getIsValid()); - assertFalse(result.getInternalError()); + assertTrue(result.getInternalError()); } 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 dea62cfceb0..42697266ac1 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 @@ -1136,7 +1136,7 @@ public enum PlatformErrorMessages { /** The rpr prt print issuer not found in property. */ RPR_PRT_ISSUER_NOT_FOUND_IN_PROPERTY(PlatformConstants.RPR_PRINTING_MODULE + "028", "Print issuer property is not found"), - RPR_PRT_PARSING_ADDITIONAL_CRED_CONFIG(PlatformConstants.RPR_PRINTING_MODULE + "029", "issue with property mosip.registration.processor.additional.credential.request"), + RPR_PRT_PARSING_ADDITIONAL_CRED_CONFIG(PlatformConstants.RPR_PRINTING_MODULE + "029", "issue with metaInfoFields in credential partner profiles."), /** The rpr rgs registration connector not accessible. */ RPR_RGS_REGISTRATION_CONNECTOR_NOT_ACCESSIBLE("", "Registration connector stage is not accessible "), From 3b120a637da12d08de407264f99bf2941d6da044 Mon Sep 17 00:00:00 2001 From: Monobikash Das Date: Thu, 16 Nov 2023 13:58:40 +0530 Subject: [PATCH 25/38] MOSIP-28121 : added partner profile feature Signed-off-by: Monobikash Das --- .../util/CredentialPartnerUtil.java | 38 +++++++++++++++++-- 1 file changed, 34 insertions(+), 4 deletions(-) diff --git a/registration-processor/post-processor/registration-processor-credential-requestor-stage/src/main/java/io/mosip/registration/processor/credentialrequestor/util/CredentialPartnerUtil.java b/registration-processor/post-processor/registration-processor-credential-requestor-stage/src/main/java/io/mosip/registration/processor/credentialrequestor/util/CredentialPartnerUtil.java index 0be2cb49890..b357a6076e0 100644 --- a/registration-processor/post-processor/registration-processor-credential-requestor-stage/src/main/java/io/mosip/registration/processor/credentialrequestor/util/CredentialPartnerUtil.java +++ b/registration-processor/post-processor/registration-processor-credential-requestor-stage/src/main/java/io/mosip/registration/processor/credentialrequestor/util/CredentialPartnerUtil.java @@ -1,6 +1,7 @@ package io.mosip.registration.processor.credentialrequestor.util; import com.fasterxml.jackson.databind.ObjectMapper; +import io.mosip.kernel.core.exception.BaseCheckedException; import io.mosip.kernel.core.exception.ExceptionUtils; import io.mosip.kernel.core.logger.spi.Logger; import io.mosip.kernel.core.util.exception.JsonProcessingException; @@ -26,6 +27,7 @@ import org.json.JSONException; import org.json.simple.JSONObject; import org.mvel2.MVEL; +import org.mvel2.ParserContext; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.env.Environment; @@ -35,6 +37,7 @@ import javax.annotation.PostConstruct; import java.io.IOException; import java.util.*; +import java.util.stream.Collectors; @Component public class CredentialPartnerUtil { @@ -82,6 +85,36 @@ public class CredentialPartnerUtil { */ private List requiredIdObjectFieldNames; + @PostConstruct + private void getIdObjectFieldNames() throws BaseCheckedException { + regProcLogger.info( "CredentialPartnerUtil::getIdObjectFieldNames()::PostConstruct"); + try { + org.json.simple.JSONObject identityMappingJson = + utilities.getRegistrationProcessorMappingJson(MappingJsonConstants.IDENTITY); + requiredIDObjectFieldNamesMap = new HashMap<>(); + for(Map.Entry expressionEntry : credentialPartnerExpression.entrySet()) { + ParserContext parserContext = ParserContext.create(); + MVEL.analysisCompile(expressionEntry.getValue(), parserContext); + Map expressionVariablesMap = parserContext.getInputs(); + for(Map.Entry variableEntry: expressionVariablesMap.entrySet()) { + String actualFieldName = JsonUtil.getJSONValue( + JsonUtil.getJSONObject(identityMappingJson, variableEntry.getKey()), + VALUE_LABEL); + if(actualFieldName == null) + throw new BaseCheckedException( + PlatformErrorMessages.RPR_PCM_FIELD_NAME_NOT_AVAILABLE_IN_MAPPING_JSON.getCode(), + PlatformErrorMessages.RPR_PCM_FIELD_NAME_NOT_AVAILABLE_IN_MAPPING_JSON.getMessage()); + requiredIDObjectFieldNamesMap.put(actualFieldName, variableEntry.getKey()); + } + } + requiredIdObjectFieldNames = requiredIDObjectFieldNamesMap.keySet().stream().collect(Collectors.toList()); + } catch (IOException e) { + throw new BaseCheckedException( + PlatformErrorMessages.RPR_PCM_ACCESSING_IDOBJECT_MAPPING_FILE_FAILED.getCode(), + PlatformErrorMessages.RPR_PCM_ACCESSING_IDOBJECT_MAPPING_FILE_FAILED.getMessage(), e); + } + } + public List getCredentialPartners(String regId, String registrationType, JSONObject identity) throws PacketManagerException, JSONException, ApisResourceAccessException, IOException, JsonProcessingException { regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), @@ -95,11 +128,8 @@ public List getCredentialPartners(String regId, String regist return Lists.emptyList(); } - String schemaVersion = utilities.getPacketManagerService().getFieldByMappingJsonKey(regId, - MappingJsonConstants.IDSCHEMA_VERSION, registrationType, ProviderStageName.CREDENTIAL_REQUESTOR); - Map identityFieldValueMap = utilities.getPacketManagerService().getFields(regId, - idSchemaUtil.getDefaultFields(Double.valueOf(schemaVersion)), registrationType, ProviderStageName.CREDENTIAL_REQUESTOR); + requiredIdObjectFieldNames, registrationType, ProviderStageName.CREDENTIAL_REQUESTOR); Map context = new HashMap<>(); for (Map.Entry identityAttribute: identityFieldValueMap.entrySet()) { From 925cecd09a038451c90953402a63a32b7390434e Mon Sep 17 00:00:00 2001 From: khuddus shariff Date: Tue, 28 Nov 2023 16:03:37 +0530 Subject: [PATCH 26/38] [ MOSIP-29896 ] Adding pkt_cr_dtimes and setting the packet date and time from metadata of the packet (#1795) Signed-off-by: khuddus shariff --- .../stages/packet/validator/PacketValidateProcessor.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/registration-processor/pre-processor/registration-processor-packet-validator-stage/src/main/java/io/mosip/registration/processor/stages/packet/validator/PacketValidateProcessor.java b/registration-processor/pre-processor/registration-processor-packet-validator-stage/src/main/java/io/mosip/registration/processor/stages/packet/validator/PacketValidateProcessor.java index ff7708859a8..a728c2d415d 100644 --- a/registration-processor/pre-processor/registration-processor-packet-validator-stage/src/main/java/io/mosip/registration/processor/stages/packet/validator/PacketValidateProcessor.java +++ b/registration-processor/pre-processor/registration-processor-packet-validator-stage/src/main/java/io/mosip/registration/processor/stages/packet/validator/PacketValidateProcessor.java @@ -456,7 +456,7 @@ public MessageDTO process(MessageDTO object, String stageName) { private void setPacketCreatedDateTime(InternalRegistrationStatusDto registrationStatusDto) throws ApisResourceAccessException, PacketManagerException, JsonProcessingException, IOException { try { Map metaInfo = packetManagerService.getMetaInfo( - registrationStatusDto.getRefId(), registrationStatusDto.getRegistrationType(), ProviderStageName.PACKET_VALIDATOR); + registrationStatusDto.getRegistrationId(), registrationStatusDto.getRegistrationType(), ProviderStageName.PACKET_VALIDATOR); DateTimeFormatter formatter = DateTimeFormatter.ofPattern(dateformat); String packetCreatedDateTime = metaInfo.get(JsonConstant.CREATIONDATE); if (packetCreatedDateTime != null && !packetCreatedDateTime.isEmpty()) { From ebffc927b627941c4de17b3df1caf27bac621892 Mon Sep 17 00:00:00 2001 From: khuddus shariff Date: Thu, 14 Dec 2023 13:42:50 +0530 Subject: [PATCH 27/38] [Mosip-30417] Regproc -Landing zone config property naming convention to be change Signed-off-by: khuddus shariff --- .../receiver/service/impl/PacketReceiverServiceImpl.java | 4 ++-- .../uploader/service/impl/PacketUploaderServiceImpl.java | 4 ++-- .../io/mosip/registration/processor/util/LandingZone.java | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/registration-processor/init/registration-processor-packet-receiver-stage/src/main/java/io/mosip/registration/processor/packet/receiver/service/impl/PacketReceiverServiceImpl.java b/registration-processor/init/registration-processor-packet-receiver-stage/src/main/java/io/mosip/registration/processor/packet/receiver/service/impl/PacketReceiverServiceImpl.java index f07963d01c1..9668819abf3 100644 --- a/registration-processor/init/registration-processor-packet-receiver-stage/src/main/java/io/mosip/registration/processor/packet/receiver/service/impl/PacketReceiverServiceImpl.java +++ b/registration-processor/init/registration-processor-packet-receiver-stage/src/main/java/io/mosip/registration/processor/packet/receiver/service/impl/PacketReceiverServiceImpl.java @@ -117,10 +117,10 @@ public class PacketReceiverServiceImpl implements PacketReceiverService Date: Wed, 20 Dec 2023 23:46:31 +0530 Subject: [PATCH 28/38] [DSD-3932] removed release-changes.yml, tag.yml and updated push-trigger.yml file (#1809) Signed-off-by: techno-467 --- .github/workflows/push-trigger.yml | 4 +-- .github/workflows/release-changes.yml | 29 ---------------------- .github/workflows/tag.yml | 35 --------------------------- 3 files changed, 2 insertions(+), 66 deletions(-) delete mode 100644 .github/workflows/release-changes.yml delete mode 100644 .github/workflows/tag.yml diff --git a/.github/workflows/push-trigger.yml b/.github/workflows/push-trigger.yml index ab05c642dcc..fd0f12aa220 100644 --- a/.github/workflows/push-trigger.yml +++ b/.github/workflows/push-trigger.yml @@ -4,7 +4,7 @@ on: release: types: [published] pull_request: - types: [opened] + types: [opened, reopened, synchronize] workflow_dispatch: inputs: @@ -35,7 +35,7 @@ jobs: SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK }} publish_to_nexus: - if: "${{ !contains(github.ref, 'master') && github.event_name != 'pull_request' }}" + if: "${{ !contains(github.ref, 'master') && github.event_name != 'pull_request' && github.event_name != 'release' && github.event_name != 'prerelease' && github.event_name != 'publish' }}" needs: build-maven-registration uses: mosip/kattu/.github/workflows/maven-publish-to-nexus.yml@master with: diff --git a/.github/workflows/release-changes.yml b/.github/workflows/release-changes.yml deleted file mode 100644 index 783d4896a2a..00000000000 --- a/.github/workflows/release-changes.yml +++ /dev/null @@ -1,29 +0,0 @@ -name: Release/pre-release Preparation. - -on: - workflow_dispatch: - inputs: - MESSAGE: - description: 'Triggered for release or pe-release' - required: false - default: 'Release Preparation' - RELEASE_TAG: - description: 'tag to update' - required: true - SNAPSHOT_TAG: - description: 'tag to be replaced' - required: true - BASE: - description: 'base branch for PR' - required: true -jobs: - maven-release-preparation: - uses: mosip/kattu/.github/workflows/release-changes.yml@master - with: - MESSAGE: ${{ inputs.MESSAGE }} - RELEASE_TAG: ${{ inputs.RELEASE_TAG }} - SNAPSHOT_TAG: ${{ inputs.SNAPSHOT_TAG }} - BASE: ${{ inputs.BASE }} - secrets: - SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK }} - ACTION_PAT: ${{ secrets.ACTION_PAT }} \ No newline at end of file diff --git a/.github/workflows/tag.yml b/.github/workflows/tag.yml deleted file mode 100644 index 9a5b079ffdf..00000000000 --- a/.github/workflows/tag.yml +++ /dev/null @@ -1,35 +0,0 @@ -name: Tagging of repos - -on: - workflow_dispatch: - inputs: - TAG: - description: 'Tag to be published' - required: true - type: string - BODY: - description: 'Release body message' - required: true - default: 'Changes in this Release' - type: string - PRE_RELEASE: - description: 'Pre-release? True/False' - required: true - default: False - type: string - DRAFT: - description: 'Draft? True/False' - required: false - default: False - type: string - -jobs: - tag-branch: - uses: mosip/kattu/.github/workflows/tag.yml@master - with: - TAG: ${{ inputs.TAG }} - BODY: ${{ inputs.BODY }} - PRE_RELEASE: ${{ inputs.PRE_RELEASE }} - DRAFT: ${{ inputs.DRAFT }} - secrets: - SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK }} \ No newline at end of file From 776ba74875e94f053ba77b24b50375b03d95c8d3 Mon Sep 17 00:00:00 2001 From: Sowmya Ujjappa Banakar <43202851+sowmya695@users.noreply.github.com> Date: Tue, 26 Dec 2023 12:01:47 +0530 Subject: [PATCH 29/38] MOSIP-29935 Code changes (#1800) * MOSIP-29935 Code changes Signed-off-by: Sowmya Ujjappa Banakar * MOSIP-29935 intial changes after new approach Signed-off-by: Sowmya Ujjappa Banakar * MOSIP-29935 code fix Signed-off-by: Sowmya Ujjappa Banakar * MOSIP-29935 code fix Signed-off-by: Sowmya Ujjappa Banakar * MOSIp-29935 code fix after testing Signed-off-by: Sowmya Ujjappa Banakar --------- Signed-off-by: Sowmya Ujjappa Banakar Co-authored-by: Sowmya Ujjappa Banakar --- .../util/PlatformSuccessMessages.java | 431 +++++----- .../core/status/util/StatusUtil.java | 2 + .../verticle/ReprocessorVerticle.java | 772 ++++++++++-------- .../verticle/ReprocessorVerticleTest.java | 34 + 4 files changed, 678 insertions(+), 561 deletions(-) diff --git a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/exception/util/PlatformSuccessMessages.java b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/exception/util/PlatformSuccessMessages.java index c18347781b7..51956273957 100644 --- a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/exception/util/PlatformSuccessMessages.java +++ b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/exception/util/PlatformSuccessMessages.java @@ -1,214 +1,217 @@ -package io.mosip.registration.processor.core.exception.util; - -/** - * - * @author M1048399 Horteppa - * - */ -public enum PlatformSuccessMessages { - - // Packet Receiver Success messages. - - /** The rpr pkr packet receiver. */ - PACKET_RECEIVER_VALIDATION_SUCCESS(PlatformConstants.RPR_PACKET_RECEIVER_MODULE + "001", - "Packet receiver validation success"), - - /** The rpr pkr packet receiver. */ - RPR_PKR_PACKET_RECEIVER(PlatformConstants.RPR_PACKET_RECEIVER_MODULE + "000", - "Packet received and uploaded to landing zone"), - - // securezone notification success messages - /** The rpr sez notification. */ - RPR_SEZ_SECUREZONE_NOTIFICATION(PlatformConstants.RPR_SECUREZONE_NOTIFICATION_MODULE + "000", "Securezone Notification Success"), - - RPR_PUM_PACKET_UPLOADER(PlatformConstants.RPR_PACKET_UPLOADER_MODULE + "000", "Packet uploaded to file system"), - - RPR_PUM_PACKET_ARCHIVED(PlatformConstants.RPR_PACKET_UPLOADER_MODULE + "001", "Packet successfully archived"), - - RPR_PUM_PACKET_UPLOADER_ALREADY_UPLOADED(PlatformConstants.RPR_PACKET_UPLOADER_MODULE + "002", "Packet already present in object store"), - - // Packet Validator Success messages - /** The rpr pkr packet validate. */ - RPR_PKR_PACKET_VALIDATE(PlatformConstants.RPR_PACKET_VALIDATOR_MODULE + "000", "Packet Validation Success"), - /** The reverse data sync success. */ - REVERSE_DATA_SYNC_SUCCESS(PlatformConstants.RPR_PACKET_VALIDATOR_MODULE + "017", "Reverse Data Sync Success"), - // Packet Classifier Success messages - /** The rpr pkr packet classifier. */ - RPR_PKR_PACKET_CLASSIFIER(PlatformConstants.RPR_PACKET_CLASSIFIER_MODULE + "000", "Packet Classifier Success"), - - RPR_PKR_ADDITIONAL_INFO_DELETED(PlatformConstants.RPR_PACKET_VALIDATOR_MODULE + "000", "Deleted additionalInfo from RegistrationList"), - - RPR_PKR_OPERATOR_VALIDATE(PlatformConstants.RPR_OVM_VALIDATOR_MODULE + "000", "OPERATOR Validation Success"), - - RPR_PKR_SUPERVISOR_VALIDATE(PlatformConstants.RPR_SVM_VALIDATOR_MODULE + "000", "SUPERVISOR Validation Success"), - - RPR_PKR_INTRODUCER_VALIDATE(PlatformConstants.RPR_IVM_VALIDATOR_MODULE + "000", "INTRODUCER Validation Success"), - - // CMD validator Success messages - RPR_PKR_CMD_VALIDATE(PlatformConstants.RPR_CMD_VALIDATOR_MODULE + "000", "CMD Validation Success"), - - // DEMO-De-dupe Success Messages - /** The rpr pkr demode-dupe validate. */ - RPR_PKR_DEMO_DE_DUP(PlatformConstants.RPR_DEMO_DEDUPE_MODULE + "000", "Demo-de-dupe Success"), - - RPR_PKR_DEMO_DE_DUP_POTENTIAL_DUPLICATION_FOUND(PlatformConstants.RPR_DEMO_DEDUPE_MODULE + "001", - "Potential duplicate packet found for registration id : "), - - RPR_PKR_DEMO_DE_DUP_SKIP(PlatformConstants.RPR_DEMO_DEDUPE_MODULE + "002", "Demographic Deduplication Skipped"), - - // Biometric Authentication Success Messages - RPR_PKR_BIOMETRIC_AUTHENTICATION(PlatformConstants.RPR_BIOMETRIC_AUTHENTICATION_MODULE + "000", - "Biometric Authentication Success"), - - - - // Bio-De-dupe Success messages - /** The Constant PACKET_BIODEDUPE_SUCCESS. */ - RPR_BIO_DEDUPE_SUCCESS(PlatformConstants.RPR_BIO_DEDUPE_STAGE_MODULE + "000", "Packet biodedupe successful"), - - /** The Constant PACKET_BIOMETRIC_POTENTIAL_MATCH. */ - RPR_BIO_METRIC_POTENTIAL_MATCH(PlatformConstants.RPR_BIO_DEDUPE_STAGE_MODULE + "000", - "Potential match found while processing bio dedupe"), - - RPR_BIO_LOST_PACKET_UNIQUE_MATCH_FOUND(PlatformConstants.RPR_BIO_DEDUPE_STAGE_MODULE + "001", - "Unique Match was Found for the Biometrics Received"), - - RPR_RE_PROCESS_SUCCESS(PlatformConstants.RPR_REPROCESSOR_VERTICLE + "000", "Reprocessor Success"), - - RPR_RE_PROCESS_FAILED(PlatformConstants.RPR_REPROCESSOR_VERTICLE + "002", "Reprocessor FAILED"), - - RPR_SENT_TO_REPROCESS_SUCCESS(PlatformConstants.RPR_REPROCESSOR_VERTICLE + "001", "sent to reprocess Success"), - - RPR_WORKFLOW_INTERNAL_ACTION_SUCCESS(PlatformConstants.RPR_WORKFLOW_INTERNAL_ACTION + "000", - "Workflow internal action completed successfully"), - - RPR_WORKFLOW_ACTION_SERVICE_SUCCESS(PlatformConstants.RPR_WORKFLOW_ACTION_SERVICE + "000", - "Processed the workflow action - %s"), - - RPR_WORKFLOW_ACTION_API_SUCCESS(PlatformConstants.RPR_WORKFLOW_ACTION_API + "000", - "Process the workflow action success"), - RPR_WORKFLOW_SEARCH_API_SUCCESS(PlatformConstants.RPR_WORKFLOW_SEARCH_API + "000", - "Process the workflow search success"), - RPR_WORKFLOW_ACTION_JOB_SUCCESS(PlatformConstants.RPR_WORKFLOW_ACTION_JOB + "000", "Workflow action job success"), - - RPR_EXTERNAL_STAGE_SUCCESS(PlatformConstants.RPR_EXTERNAL_STAGE + "000", "External stage Success"), - - RPR_UIN_GENERATOR_STAGE_SUCCESS(PlatformConstants.RPR_UIN_GENERATOR_STAGE + "000", "UIN Generator Success"), - - RPR_BIOMETRIC_EXTRACTION_SUCCESS(PlatformConstants.RPR_BIOMETRIC_EXTRACTION_STAGE + "000", - "biometric extraction success"), - - RPR_FINALIZATION_SUCCESS(PlatformConstants.RPR_FINALIZATION_STAGE + "000", - "Finalization success"), - - RPR_UIN_DATA_UPDATION_SUCCESS(PlatformConstants.RPR_UIN_GENERATOR_STAGE + "001", "UIN Generator Success"), - - RPR_UIN_ACTIVATED_SUCCESS(PlatformConstants.RPR_UIN_GENERATOR_STAGE + "002", "UIN Generator Success"), - - RPR_UIN_DEACTIVATION_SUCCESS(PlatformConstants.RPR_UIN_GENERATOR_STAGE + "003", "UIN Generator Success"), - - RPR_LINK_RID_FOR_LOST_PACKET_SUCCESS(PlatformConstants.RPR_UIN_GENERATOR_STAGE + "004", "UIN Generator Success"), - - RPR_QUALITY_CHECK_SUCCESS(PlatformConstants.RPR_QUALITY_CHECKER_MODULE + "000", "Quality check Success"), - - RPR_PRINT_STAGE_REQUEST_SUCCESS(PlatformConstants.RPR_PRINTING_MODULE + "000", - "Print request submitted"), - - RPR_PRINT_STAGE_SUCCESS(PlatformConstants.RPR_PRINTING_MODULE + "001", "Print and Post Completed"), - - RPR_MESSAGE_SENDER_STAGE_SUCCESS(PlatformConstants.RPR_MESSAGE_SENDER_TEMPLATE + "001", - "Message Sender Stage success"), - - RPR_ABIS_HANDLER_STAGE_SUCCESS(PlatformConstants.RPR_ABIS_HANDLER + "000", "ABIS hanlder stage success"), - - RPR_ABIS_MIDDLEWARE_STAGE_SUCCESS(PlatformConstants.RPR_ABIS_MIDDLEWARE + "000", - "Abis insertRequests sucessfully sent to Queue"), - - RPR_MANUAL_VERIFICATION_APPROVED(PlatformConstants.RPR_MANUAL_ADJUDICATION_MODULE + "000", - "Manual verification approved"), - - RPR_MANUAL_VERIFICATION_RESEND(PlatformConstants.RPR_MANUAL_ADJUDICATION_MODULE + "002", - "Manual verification resend"), - - RPR_MANUAL_VERIFICATION_SENT(PlatformConstants.RPR_MANUAL_ADJUDICATION_MODULE + "001", - "Manual verification Sent to queue"), - - RPR_VERIFICATION_SENT(PlatformConstants.RPR_VERIFICATION_MODULE + "000", - "Sent for Verification"), - - RPR_VERIFICATION_SUCCESS(PlatformConstants.RPR_VERIFICATION_MODULE + "001", - "Verification successful"), - - RPR_DECRYPTION_SUCCESS(PlatformConstants.RPR_PACKET_DECRYPTION_MODULE + "000", "Decryption success"), - - RPR_ENCRYPTION_SUCCESS(PlatformConstants.RPR_PACKET_DECRYPTION_MODULE + "000", "Encryption success"), - - RPR_PRINT_SERVICE_SUCCESS(PlatformConstants.RPR_PRINTING_MODULE + "002", "Pdf generated and sent to print stage"), - - RPR_SYNC_REGISTRATION_SERVICE_SUCCESS(PlatformConstants.RPR_REGISTRATION_STATUS_MODULE + "000", "SYNC successfull"), - - RPR_REQUEST_HANDLER_LOST_PACKET_SUCCESS(PlatformConstants.RPR_PACKET_REQUEST_HANDLER_MODULE + "000", - "Lost packet id value fetched successfully"), - - PACKET_MARK_AS_PAUSED(PlatformConstants.RPR_CAMEL_BRIDGE_MODULE + "000", - "Packet paused because of pause settings match"), - PACKET_COMPLETE_AS_PROCESSED(PlatformConstants.RPR_CAMEL_BRIDGE_MODULE + "001", - "Packet processing completed with processed status"), - PACKET_COMPLETE_AS_REJECTED(PlatformConstants.RPR_CAMEL_BRIDGE_MODULE + "002", - "Packet processing completed with reject status"), - PACKET_COMPLETE_AS_FAILED(PlatformConstants.RPR_CAMEL_BRIDGE_MODULE + "003", - "Packet processing completed with failed status"), - PACKET_MARK_AS_REPROCESS(PlatformConstants.RPR_CAMEL_BRIDGE_MODULE + "004", "Packet marked for reprocessing"), - PACKET_PROCESSING_COMPLETED(PlatformConstants.RPR_CAMEL_BRIDGE_MODULE + "009", - "Packet processing completed with action code : "), - - PAUSE_AND_REQUEST_ADDITIONAL_INFO(PlatformConstants.RPR_CAMEL_BRIDGE_MODULE + "005", - "packet paused and request additional info"), - - PACKET_RESTART_PARENT_FLOW(PlatformConstants.RPR_CAMEL_BRIDGE_MODULE + "006", - "Packet parent flow restart initiated"), - - PACKET_COMPLETE_AS_REJECTED_WITHOUT_PARENT_FLOW(PlatformConstants.RPR_CAMEL_BRIDGE_MODULE + "007", - "Packet processing completed with reject status without Parent flow"), - - PACKET_ANONYMOUS_PROFILE(PlatformConstants.RPR_CAMEL_BRIDGE_MODULE + "008", - "Packet anonymous profile flow initiated"); - - /** The success message. */ - private final String successMessage; - - /** The success code. */ - private final String successCode; - - /** - * Instantiates a new platform success messages. - * - * @param errorCode - * the error code - * @param errorMsg - * the error msg - */ - private PlatformSuccessMessages(String errorCode, String errorMsg) { - this.successCode = errorCode; - this.successMessage = errorMsg; - } - - /** - * Gets the message. - * - * @return the message - */ - public String getMessage() { - return this.successMessage; - } - - /** - * Gets the code. - * - * @return the code - */ - public String getCode() { - return this.successCode; - } - -} +package io.mosip.registration.processor.core.exception.util; + +/** + * + * @author M1048399 Horteppa + * + */ +public enum PlatformSuccessMessages { + + // Packet Receiver Success messages. + + /** The rpr pkr packet receiver. */ + PACKET_RECEIVER_VALIDATION_SUCCESS(PlatformConstants.RPR_PACKET_RECEIVER_MODULE + "001", + "Packet receiver validation success"), + + /** The rpr pkr packet receiver. */ + RPR_PKR_PACKET_RECEIVER(PlatformConstants.RPR_PACKET_RECEIVER_MODULE + "000", + "Packet received and uploaded to landing zone"), + + // securezone notification success messages + /** The rpr sez notification. */ + RPR_SEZ_SECUREZONE_NOTIFICATION(PlatformConstants.RPR_SECUREZONE_NOTIFICATION_MODULE + "000", "Securezone Notification Success"), + + RPR_PUM_PACKET_UPLOADER(PlatformConstants.RPR_PACKET_UPLOADER_MODULE + "000", "Packet uploaded to file system"), + + RPR_PUM_PACKET_ARCHIVED(PlatformConstants.RPR_PACKET_UPLOADER_MODULE + "001", "Packet successfully archived"), + + RPR_PUM_PACKET_UPLOADER_ALREADY_UPLOADED(PlatformConstants.RPR_PACKET_UPLOADER_MODULE + "002", "Packet already present in object store"), + + // Packet Validator Success messages + /** The rpr pkr packet validate. */ + RPR_PKR_PACKET_VALIDATE(PlatformConstants.RPR_PACKET_VALIDATOR_MODULE + "000", "Packet Validation Success"), + /** The reverse data sync success. */ + REVERSE_DATA_SYNC_SUCCESS(PlatformConstants.RPR_PACKET_VALIDATOR_MODULE + "017", "Reverse Data Sync Success"), + // Packet Classifier Success messages + /** The rpr pkr packet classifier. */ + RPR_PKR_PACKET_CLASSIFIER(PlatformConstants.RPR_PACKET_CLASSIFIER_MODULE + "000", "Packet Classifier Success"), + + RPR_PKR_ADDITIONAL_INFO_DELETED(PlatformConstants.RPR_PACKET_VALIDATOR_MODULE + "000", "Deleted additionalInfo from RegistrationList"), + + RPR_PKR_OPERATOR_VALIDATE(PlatformConstants.RPR_OVM_VALIDATOR_MODULE + "000", "OPERATOR Validation Success"), + + RPR_PKR_SUPERVISOR_VALIDATE(PlatformConstants.RPR_SVM_VALIDATOR_MODULE + "000", "SUPERVISOR Validation Success"), + + RPR_PKR_INTRODUCER_VALIDATE(PlatformConstants.RPR_IVM_VALIDATOR_MODULE + "000", "INTRODUCER Validation Success"), + + // CMD validator Success messages + RPR_PKR_CMD_VALIDATE(PlatformConstants.RPR_CMD_VALIDATOR_MODULE + "000", "CMD Validation Success"), + + // DEMO-De-dupe Success Messages + /** The rpr pkr demode-dupe validate. */ + RPR_PKR_DEMO_DE_DUP(PlatformConstants.RPR_DEMO_DEDUPE_MODULE + "000", "Demo-de-dupe Success"), + + RPR_PKR_DEMO_DE_DUP_POTENTIAL_DUPLICATION_FOUND(PlatformConstants.RPR_DEMO_DEDUPE_MODULE + "001", + "Potential duplicate packet found for registration id : "), + + RPR_PKR_DEMO_DE_DUP_SKIP(PlatformConstants.RPR_DEMO_DEDUPE_MODULE + "002", "Demographic Deduplication Skipped"), + + // Biometric Authentication Success Messages + RPR_PKR_BIOMETRIC_AUTHENTICATION(PlatformConstants.RPR_BIOMETRIC_AUTHENTICATION_MODULE + "000", + "Biometric Authentication Success"), + + + + // Bio-De-dupe Success messages + /** The Constant PACKET_BIODEDUPE_SUCCESS. */ + RPR_BIO_DEDUPE_SUCCESS(PlatformConstants.RPR_BIO_DEDUPE_STAGE_MODULE + "000", "Packet biodedupe successful"), + + /** The Constant PACKET_BIOMETRIC_POTENTIAL_MATCH. */ + RPR_BIO_METRIC_POTENTIAL_MATCH(PlatformConstants.RPR_BIO_DEDUPE_STAGE_MODULE + "000", + "Potential match found while processing bio dedupe"), + + RPR_BIO_LOST_PACKET_UNIQUE_MATCH_FOUND(PlatformConstants.RPR_BIO_DEDUPE_STAGE_MODULE + "001", + "Unique Match was Found for the Biometrics Received"), + + RPR_RE_PROCESS_SUCCESS(PlatformConstants.RPR_REPROCESSOR_VERTICLE + "000", "Reprocessor Success"), + + RPR_RE_PROCESS_FAILED(PlatformConstants.RPR_REPROCESSOR_VERTICLE + "002", "Reprocessor FAILED"), + + RPR_SENT_TO_REPROCESS_SUCCESS(PlatformConstants.RPR_REPROCESSOR_VERTICLE + "001", "sent to reprocess Success"), + + RPR_SENT_TO_REPROCESS_RESTART_FROM_STAGE_SUCCESS(PlatformConstants.RPR_REPROCESSOR_VERTICLE + "002", + "sent to reprocess restart from stage Success"), + + RPR_WORKFLOW_INTERNAL_ACTION_SUCCESS(PlatformConstants.RPR_WORKFLOW_INTERNAL_ACTION + "000", + "Workflow internal action completed successfully"), + + RPR_WORKFLOW_ACTION_SERVICE_SUCCESS(PlatformConstants.RPR_WORKFLOW_ACTION_SERVICE + "000", + "Processed the workflow action - %s"), + + RPR_WORKFLOW_ACTION_API_SUCCESS(PlatformConstants.RPR_WORKFLOW_ACTION_API + "000", + "Process the workflow action success"), + RPR_WORKFLOW_SEARCH_API_SUCCESS(PlatformConstants.RPR_WORKFLOW_SEARCH_API + "000", + "Process the workflow search success"), + RPR_WORKFLOW_ACTION_JOB_SUCCESS(PlatformConstants.RPR_WORKFLOW_ACTION_JOB + "000", "Workflow action job success"), + + RPR_EXTERNAL_STAGE_SUCCESS(PlatformConstants.RPR_EXTERNAL_STAGE + "000", "External stage Success"), + + RPR_UIN_GENERATOR_STAGE_SUCCESS(PlatformConstants.RPR_UIN_GENERATOR_STAGE + "000", "UIN Generator Success"), + + RPR_BIOMETRIC_EXTRACTION_SUCCESS(PlatformConstants.RPR_BIOMETRIC_EXTRACTION_STAGE + "000", + "biometric extraction success"), + + RPR_FINALIZATION_SUCCESS(PlatformConstants.RPR_FINALIZATION_STAGE + "000", + "Finalization success"), + + RPR_UIN_DATA_UPDATION_SUCCESS(PlatformConstants.RPR_UIN_GENERATOR_STAGE + "001", "UIN Generator Success"), + + RPR_UIN_ACTIVATED_SUCCESS(PlatformConstants.RPR_UIN_GENERATOR_STAGE + "002", "UIN Generator Success"), + + RPR_UIN_DEACTIVATION_SUCCESS(PlatformConstants.RPR_UIN_GENERATOR_STAGE + "003", "UIN Generator Success"), + + RPR_LINK_RID_FOR_LOST_PACKET_SUCCESS(PlatformConstants.RPR_UIN_GENERATOR_STAGE + "004", "UIN Generator Success"), + + RPR_QUALITY_CHECK_SUCCESS(PlatformConstants.RPR_QUALITY_CHECKER_MODULE + "000", "Quality check Success"), + + RPR_PRINT_STAGE_REQUEST_SUCCESS(PlatformConstants.RPR_PRINTING_MODULE + "000", + "Print request submitted"), + + RPR_PRINT_STAGE_SUCCESS(PlatformConstants.RPR_PRINTING_MODULE + "001", "Print and Post Completed"), + + RPR_MESSAGE_SENDER_STAGE_SUCCESS(PlatformConstants.RPR_MESSAGE_SENDER_TEMPLATE + "001", + "Message Sender Stage success"), + + RPR_ABIS_HANDLER_STAGE_SUCCESS(PlatformConstants.RPR_ABIS_HANDLER + "000", "ABIS hanlder stage success"), + + RPR_ABIS_MIDDLEWARE_STAGE_SUCCESS(PlatformConstants.RPR_ABIS_MIDDLEWARE + "000", + "Abis insertRequests sucessfully sent to Queue"), + + RPR_MANUAL_VERIFICATION_APPROVED(PlatformConstants.RPR_MANUAL_ADJUDICATION_MODULE + "000", + "Manual verification approved"), + + RPR_MANUAL_VERIFICATION_RESEND(PlatformConstants.RPR_MANUAL_ADJUDICATION_MODULE + "002", + "Manual verification resend"), + + RPR_MANUAL_VERIFICATION_SENT(PlatformConstants.RPR_MANUAL_ADJUDICATION_MODULE + "001", + "Manual verification Sent to queue"), + + RPR_VERIFICATION_SENT(PlatformConstants.RPR_VERIFICATION_MODULE + "000", + "Sent for Verification"), + + RPR_VERIFICATION_SUCCESS(PlatformConstants.RPR_VERIFICATION_MODULE + "001", + "Verification successful"), + + RPR_DECRYPTION_SUCCESS(PlatformConstants.RPR_PACKET_DECRYPTION_MODULE + "000", "Decryption success"), + + RPR_ENCRYPTION_SUCCESS(PlatformConstants.RPR_PACKET_DECRYPTION_MODULE + "000", "Encryption success"), + + RPR_PRINT_SERVICE_SUCCESS(PlatformConstants.RPR_PRINTING_MODULE + "002", "Pdf generated and sent to print stage"), + + RPR_SYNC_REGISTRATION_SERVICE_SUCCESS(PlatformConstants.RPR_REGISTRATION_STATUS_MODULE + "000", "SYNC successfull"), + + RPR_REQUEST_HANDLER_LOST_PACKET_SUCCESS(PlatformConstants.RPR_PACKET_REQUEST_HANDLER_MODULE + "000", + "Lost packet id value fetched successfully"), + + PACKET_MARK_AS_PAUSED(PlatformConstants.RPR_CAMEL_BRIDGE_MODULE + "000", + "Packet paused because of pause settings match"), + PACKET_COMPLETE_AS_PROCESSED(PlatformConstants.RPR_CAMEL_BRIDGE_MODULE + "001", + "Packet processing completed with processed status"), + PACKET_COMPLETE_AS_REJECTED(PlatformConstants.RPR_CAMEL_BRIDGE_MODULE + "002", + "Packet processing completed with reject status"), + PACKET_COMPLETE_AS_FAILED(PlatformConstants.RPR_CAMEL_BRIDGE_MODULE + "003", + "Packet processing completed with failed status"), + PACKET_MARK_AS_REPROCESS(PlatformConstants.RPR_CAMEL_BRIDGE_MODULE + "004", "Packet marked for reprocessing"), + PACKET_PROCESSING_COMPLETED(PlatformConstants.RPR_CAMEL_BRIDGE_MODULE + "009", + "Packet processing completed with action code : "), + + PAUSE_AND_REQUEST_ADDITIONAL_INFO(PlatformConstants.RPR_CAMEL_BRIDGE_MODULE + "005", + "packet paused and request additional info"), + + PACKET_RESTART_PARENT_FLOW(PlatformConstants.RPR_CAMEL_BRIDGE_MODULE + "006", + "Packet parent flow restart initiated"), + + PACKET_COMPLETE_AS_REJECTED_WITHOUT_PARENT_FLOW(PlatformConstants.RPR_CAMEL_BRIDGE_MODULE + "007", + "Packet processing completed with reject status without Parent flow"), + + PACKET_ANONYMOUS_PROFILE(PlatformConstants.RPR_CAMEL_BRIDGE_MODULE + "008", + "Packet anonymous profile flow initiated"); + + /** The success message. */ + private final String successMessage; + + /** The success code. */ + private final String successCode; + + /** + * Instantiates a new platform success messages. + * + * @param errorCode + * the error code + * @param errorMsg + * the error msg + */ + private PlatformSuccessMessages(String errorCode, String errorMsg) { + this.successCode = errorCode; + this.successMessage = errorMsg; + } + + /** + * Gets the message. + * + * @return the message + */ + public String getMessage() { + return this.successMessage; + } + + /** + * Gets the code. + * + * @return the code + */ + public String getCode() { + return this.successCode; + } + +} diff --git a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/status/util/StatusUtil.java b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/status/util/StatusUtil.java index 8b860e167c3..7d3910b450f 100644 --- a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/status/util/StatusUtil.java +++ b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/status/util/StatusUtil.java @@ -314,6 +314,8 @@ public enum StatusUtil { RE_PROCESS_FAILED(StatusConstants.RE_PROCESS_MODULE_FAILED + "001", "Reprocess count has exceeded the configured attempts"), RE_PROCESS_COMPLETED(StatusConstants.RE_PROCESS_MODULE_SUCCESS + "001", "Reprocess Completed"), + RE_PROCESS_RESTART_FROM_STAGE(StatusConstants.RE_PROCESS_MODULE_SUCCESS + "002", + "Reprocess restart from stage Completed"), // Message sender stage NOTIFICATION_SUCESSFUL(StatusConstants.MESSAGE_SENDER_NOTIF_SUCCESS_CODE + "001", "Notification Sent Successfully"), diff --git a/registration-processor/workflow-engine/registration-processor-reprocessor/src/main/java/io/mosip/registration/processor/reprocessor/verticle/ReprocessorVerticle.java b/registration-processor/workflow-engine/registration-processor-reprocessor/src/main/java/io/mosip/registration/processor/reprocessor/verticle/ReprocessorVerticle.java index 8233e09837d..bebd730a69a 100644 --- a/registration-processor/workflow-engine/registration-processor-reprocessor/src/main/java/io/mosip/registration/processor/reprocessor/verticle/ReprocessorVerticle.java +++ b/registration-processor/workflow-engine/registration-processor-reprocessor/src/main/java/io/mosip/registration/processor/reprocessor/verticle/ReprocessorVerticle.java @@ -1,347 +1,425 @@ -package io.mosip.registration.processor.reprocessor.verticle; - -import java.util.ArrayList; -import java.util.List; - -import io.mosip.registration.processor.reprocessor.constants.ReprocessorConstants; -import org.apache.commons.lang3.exception.ExceptionUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.core.env.Environment; -import org.springframework.stereotype.Component; -import org.springframework.util.CollectionUtils; - -import io.mosip.kernel.core.logger.spi.Logger; -import io.mosip.registration.processor.core.abstractverticle.MessageBusAddress; -import io.mosip.registration.processor.core.abstractverticle.MessageDTO; -import io.mosip.registration.processor.core.abstractverticle.MosipEventBus; -import io.mosip.registration.processor.core.abstractverticle.MosipRouter; -import io.mosip.registration.processor.core.abstractverticle.MosipVerticleAPIManager; -import io.mosip.registration.processor.core.code.EventId; -import io.mosip.registration.processor.core.code.EventName; -import io.mosip.registration.processor.core.code.EventType; -import io.mosip.registration.processor.core.code.ModuleName; -import io.mosip.registration.processor.core.code.RegistrationTransactionStatusCode; -import io.mosip.registration.processor.core.code.RegistrationTransactionTypeCode; -import io.mosip.registration.processor.core.constant.LoggerFileConstant; -import io.mosip.registration.processor.core.exception.util.PlatformErrorMessages; -import io.mosip.registration.processor.core.exception.util.PlatformSuccessMessages; -import io.mosip.registration.processor.core.logger.LogDescription; -import io.mosip.registration.processor.core.logger.RegProcessorLogger; -import io.mosip.registration.processor.core.status.util.StatusUtil; -import io.mosip.registration.processor.core.util.MessageBusUtil; -import io.mosip.registration.processor.rest.client.audit.builder.AuditLogRequestBuilder; -import io.mosip.registration.processor.status.code.RegistrationStatusCode; -import io.mosip.registration.processor.status.dto.InternalRegistrationStatusDto; -import io.mosip.registration.processor.status.dto.RegistrationStatusDto; -import io.mosip.registration.processor.status.exception.TablenotAccessibleException; -import io.mosip.registration.processor.status.service.RegistrationStatusService; -import io.vertx.core.AsyncResult; -import io.vertx.core.Vertx; -import io.vertx.core.eventbus.EventBus; -import io.vertx.core.json.JsonObject; - -/** - * The Reprocessor Verticle to deploy the scheduler and implement re-processing - * logic - * - * @author Alok Ranjan - * @author Sowmya - * @author Pranav Kumar - * - * @since 0.10.0 - * - */ -@Component -public class ReprocessorVerticle extends MosipVerticleAPIManager { - - private static final String VERTICLE_PROPERTY_PREFIX = "mosip.regproc.reprocessor."; - - private static Logger regProcLogger = RegProcessorLogger.getLogger(ReprocessorVerticle.class); - - /** The cluster manager url. */ - @Value("${vertx.cluster.configuration}") - private String clusterManagerUrl; - - /** The environment. */ - @Autowired - Environment environment; - - /** The mosip event bus. */ - MosipEventBus mosipEventBus = null; - - /** The fetch size. */ - @Value("${registration.processor.reprocess.fetchsize}") - private Integer fetchSize; - - /** The elapse time. */ - @Value("${registration.processor.reprocess.elapse.time}") - private long elapseTime; - - /** The reprocess count. */ - @Value("${registration.processor.reprocess.attempt.count}") - private Integer reprocessCount; - - /** Comman seperated stage names that should be excluded while reprocessing. */ - @Value("#{T(java.util.Arrays).asList('${mosip.registration.processor.reprocessor.exclude-stage-names:PacketReceiverStage}')}") - private List reprocessExcludeStageNames; - - /** The is transaction successful. */ - boolean isTransactionSuccessful; - - /** The registration status service. */ - @Autowired - RegistrationStatusService registrationStatusService; - - /** The core audit request builder. */ - @Autowired - AuditLogRequestBuilder auditLogRequestBuilder; - - /** Mosip router for APIs */ - @Autowired - MosipRouter router; - - /** The port. */ - @Value("${server.port}") - private String port; - - /** - * Deploy verticle. - */ - public void deployVerticle() { - mosipEventBus = this.getEventBus(this, clusterManagerUrl); - deployScheduler(getVertx()); - - } - - /** - * This method deploys the chime scheduler - * - * @param vertx - * the vertx - */ - private void deployScheduler(Vertx vertx) { - vertx.deployVerticle(ReprocessorConstants.CEYLON_SCHEDULER, this::schedulerResult); - } - - public void schedulerResult(AsyncResult res) { - if (res.succeeded()) { - regProcLogger.info("ReprocessorVerticle::schedular()::deployed"); - cronScheduling(vertx); - } else { - regProcLogger.error("ReprocessorVerticle::schedular()::deployment failure " + res.cause().getMessage()); - } - } - - /** - * This method does the cron scheduling by fetchin cron expression from config - * server - * - * @param vertx - * the vertx - */ - private void cronScheduling(Vertx vertx) { - - EventBus eventBus = vertx.eventBus(); - // listen the timer events - eventBus.consumer((ReprocessorConstants.TIMER_EVENT), message -> { - - process(new MessageDTO()); - }); - - // description of timers - JsonObject timer = (new JsonObject()) - .put(ReprocessorConstants.TYPE, environment.getProperty(ReprocessorConstants.TYPE_VALUE)) - .put(ReprocessorConstants.SECONDS, environment.getProperty(ReprocessorConstants.SECONDS_VALUE)) - .put(ReprocessorConstants.MINUTES, environment.getProperty(ReprocessorConstants.MINUTES_VALUE)) - .put(ReprocessorConstants.HOURS, environment.getProperty(ReprocessorConstants.HOURS_VALUE)) - .put(ReprocessorConstants.DAY_OF_MONTH, - environment.getProperty(ReprocessorConstants.DAY_OF_MONTH_VALUE)) - .put(ReprocessorConstants.MONTHS, environment.getProperty(ReprocessorConstants.MONTHS_VALUE)) - .put(ReprocessorConstants.DAYS_OF_WEEK, - environment.getProperty(ReprocessorConstants.DAYS_OF_WEEK_VALUE)); - - // create scheduler - eventBus.send(ReprocessorConstants.CHIME, - (new JsonObject()).put(ReprocessorConstants.OPERATION, ReprocessorConstants.OPERATION_VALUE) - .put(ReprocessorConstants.NAME, ReprocessorConstants.NAME_VALUE) - .put(ReprocessorConstants.DESCRIPTION, timer), - ar -> { - if (ar.succeeded()) { - regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), - LoggerFileConstant.REGISTRATIONID.toString(), "", - "ReprocessorVerticle::schedular()::started"); - } else { - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), - LoggerFileConstant.REGISTRATIONID.toString(), "", - "ReprocessorVerticle::schedular()::failed " + ar.cause()); - vertx.close(); - } - }); - - } - - /** - * Send message. - * - * @param message - * the message - * @param toAddress - * the to address - */ - public void sendMessage(MessageDTO message, MessageBusAddress toAddress) { - this.send(this.mosipEventBus, toAddress, message); - } - - @Override - public void start() { - router.setRoute(this.postUrl(getVertx(), null, null)); - this.createServer(router.getRouter(), Integer.parseInt(port)); - } - - /* - * (non-Javadoc) - * - * @see - * io.mosip.registration.processor.core.spi.eventbus.EventBusManager#process( - * java.lang.Object) - */ - @Override - public MessageDTO process(MessageDTO object) { - List reprocessorDtoList = null; - LogDescription description = new LogDescription(); - List statusList = new ArrayList<>(); - statusList.add(RegistrationTransactionStatusCode.SUCCESS.toString()); - statusList.add(RegistrationTransactionStatusCode.REPROCESS.toString()); - statusList.add(RegistrationTransactionStatusCode.IN_PROGRESS.toString()); - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), "", - "ReprocessorVerticle::process()::entry"); - StringBuffer ridSb=new StringBuffer(); - try { - reprocessorDtoList = registrationStatusService.getResumablePackets(fetchSize); - if (!CollectionUtils.isEmpty(reprocessorDtoList)) { - if (reprocessorDtoList.size() < fetchSize) { - List reprocessorPacketList = registrationStatusService.getUnProcessedPackets(fetchSize - reprocessorDtoList.size(), elapseTime, - reprocessCount, statusList, reprocessExcludeStageNames); - if (!CollectionUtils.isEmpty(reprocessorPacketList)) { - reprocessorDtoList.addAll(reprocessorPacketList); - } - } - } else { - reprocessorDtoList = registrationStatusService.getUnProcessedPackets(fetchSize, elapseTime, - reprocessCount, statusList, reprocessExcludeStageNames); - } - - - if (!CollectionUtils.isEmpty(reprocessorDtoList)) { - reprocessorDtoList.forEach(dto -> { - String registrationId = dto.getRegistrationId(); - ridSb.append(registrationId); - ridSb.append(","); - MessageDTO messageDTO = new MessageDTO(); - messageDTO.setRid(registrationId); - messageDTO.setReg_type(dto.getRegistrationType()); - messageDTO.setSource(dto.getSource()); - messageDTO.setIteration(dto.getIteration()); - messageDTO.setWorkflowInstanceId(dto.getWorkflowInstanceId()); - if (reprocessCount.equals(dto.getReProcessRetryCount())) { - dto.setLatestTransactionStatusCode( - RegistrationTransactionStatusCode.REPROCESS_FAILED.toString()); - dto.setLatestTransactionTypeCode( - RegistrationTransactionTypeCode.PACKET_REPROCESS.toString()); - dto.setStatusComment(StatusUtil.RE_PROCESS_FAILED.getMessage()); - dto.setStatusCode(RegistrationStatusCode.REPROCESS_FAILED.toString()); - dto.setSubStatusCode(StatusUtil.RE_PROCESS_FAILED.getCode()); - messageDTO.setIsValid(false); - description.setMessage(PlatformSuccessMessages.RPR_RE_PROCESS_FAILED.getMessage()); - description.setCode(PlatformSuccessMessages.RPR_RE_PROCESS_FAILED.getCode()); - - } else { - messageDTO.setIsValid(true); - isTransactionSuccessful = true; - String stageName = MessageBusUtil.getMessageBusAdress(dto.getRegistrationStageName()); - if (RegistrationTransactionStatusCode.SUCCESS.name() - .equalsIgnoreCase(dto.getLatestTransactionStatusCode())) { - stageName = stageName.concat(ReprocessorConstants.BUS_OUT); - } else { - stageName = stageName.concat(ReprocessorConstants.BUS_IN); - } - MessageBusAddress address = new MessageBusAddress(stageName); - sendMessage(messageDTO, address); - dto.setUpdatedBy(ReprocessorConstants.USER); - Integer reprocessRetryCount = dto.getReProcessRetryCount() != null - ? dto.getReProcessRetryCount() + 1 - : 1; - dto.setReProcessRetryCount(reprocessRetryCount); - dto.setLatestTransactionStatusCode(RegistrationTransactionStatusCode.REPROCESS.toString()); - dto.setLatestTransactionTypeCode( - RegistrationTransactionTypeCode.PACKET_REPROCESS.toString()); - dto.setStatusComment(StatusUtil.RE_PROCESS_COMPLETED.getMessage()); - dto.setSubStatusCode(StatusUtil.RE_PROCESS_COMPLETED.getCode()); - description.setMessage(PlatformSuccessMessages.RPR_SENT_TO_REPROCESS_SUCCESS.getMessage()); - description.setCode(PlatformSuccessMessages.RPR_SENT_TO_REPROCESS_SUCCESS.getCode()); - } - regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), - LoggerFileConstant.REGISTRATIONID.toString(), registrationId, description.getMessage()); - - /** Module-Id can be Both Success/Error code */ - String moduleId = PlatformSuccessMessages.RPR_SENT_TO_REPROCESS_SUCCESS.getCode(); - String moduleName = ModuleName.RE_PROCESSOR.toString(); - registrationStatusService.updateRegistrationStatusForWorkflowEngine(dto, moduleId, moduleName); - String eventId = EventId.RPR_402.toString(); - String eventName = EventName.UPDATE.toString(); - String eventType = EventType.BUSINESS.toString(); - - if (!isTransactionSuccessful) - auditLogRequestBuilder.createAuditRequestBuilder(description.getMessage(), eventId, eventName, - eventType, moduleId, moduleName, registrationId); - }); - - } - } catch (TablenotAccessibleException e) { - isTransactionSuccessful = false; - object.setInternalError(Boolean.TRUE); - description.setMessage(PlatformErrorMessages.RPR_RGS_REGISTRATION_TABLE_NOT_ACCESSIBLE.getMessage()); - description.setCode(PlatformErrorMessages.RPR_RGS_REGISTRATION_TABLE_NOT_ACCESSIBLE.getCode()); - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), - description.getCode() + " -- ", - PlatformErrorMessages.RPR_RGS_REGISTRATION_TABLE_NOT_ACCESSIBLE.getMessage(), e.toString()); - - }catch (Exception ex) { - isTransactionSuccessful = false; - description.setMessage(PlatformErrorMessages.REPROCESSOR_VERTICLE_FAILED.getMessage()); - description.setCode(PlatformErrorMessages.REPROCESSOR_VERTICLE_FAILED.getCode()); - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - description.getCode() + " -- ", - PlatformErrorMessages.REPROCESSOR_VERTICLE_FAILED.getMessage() + ex.getMessage() - + ExceptionUtils.getStackTrace(ex)); - object.setInternalError(Boolean.TRUE); - - } finally { - regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - null, description.getMessage()); - if (isTransactionSuccessful) - description.setMessage(PlatformSuccessMessages.RPR_RE_PROCESS_SUCCESS.getMessage()); - - String eventId = isTransactionSuccessful ? EventId.RPR_402.toString() : EventId.RPR_405.toString(); - String eventName = isTransactionSuccessful ? EventName.UPDATE.toString() : EventName.EXCEPTION.toString(); - String eventType = isTransactionSuccessful ? EventType.BUSINESS.toString() : EventType.SYSTEM.toString(); - - /** Module-Id can be Both Success/Error code */ - String moduleId = isTransactionSuccessful ? PlatformSuccessMessages.RPR_RE_PROCESS_SUCCESS.getCode() - : description.getCode(); - String moduleName = ModuleName.RE_PROCESSOR.toString(); - auditLogRequestBuilder.createAuditRequestBuilder(description.getMessage(), eventId, eventName, eventType, - moduleId, moduleName, (ridSb.toString().length()>1?ridSb.substring(0,ridSb.length()-1):"")); - } - - return object; - } - - - - @Override - protected String getPropertyPrefix() { - return VERTICLE_PROPERTY_PREFIX; - } -} +package io.mosip.registration.processor.reprocessor.verticle; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.apache.commons.lang3.exception.ExceptionUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Component; +import org.springframework.util.CollectionUtils; + +import io.mosip.kernel.core.logger.spi.Logger; +import io.mosip.registration.processor.core.abstractverticle.MessageBusAddress; +import io.mosip.registration.processor.core.abstractverticle.MessageDTO; +import io.mosip.registration.processor.core.abstractverticle.MosipEventBus; +import io.mosip.registration.processor.core.abstractverticle.MosipRouter; +import io.mosip.registration.processor.core.abstractverticle.MosipVerticleAPIManager; +import io.mosip.registration.processor.core.code.EventId; +import io.mosip.registration.processor.core.code.EventName; +import io.mosip.registration.processor.core.code.EventType; +import io.mosip.registration.processor.core.code.ModuleName; +import io.mosip.registration.processor.core.code.RegistrationTransactionStatusCode; +import io.mosip.registration.processor.core.code.RegistrationTransactionTypeCode; +import io.mosip.registration.processor.core.constant.LoggerFileConstant; +import io.mosip.registration.processor.core.exception.util.PlatformErrorMessages; +import io.mosip.registration.processor.core.exception.util.PlatformSuccessMessages; +import io.mosip.registration.processor.core.logger.LogDescription; +import io.mosip.registration.processor.core.logger.RegProcessorLogger; +import io.mosip.registration.processor.core.status.util.StatusUtil; +import io.mosip.registration.processor.core.util.MessageBusUtil; +import io.mosip.registration.processor.reprocessor.constants.ReprocessorConstants; +import io.mosip.registration.processor.rest.client.audit.builder.AuditLogRequestBuilder; +import io.mosip.registration.processor.status.code.RegistrationStatusCode; +import io.mosip.registration.processor.status.dto.InternalRegistrationStatusDto; +import io.mosip.registration.processor.status.dto.RegistrationStatusDto; +import io.mosip.registration.processor.status.exception.TablenotAccessibleException; +import io.mosip.registration.processor.status.service.RegistrationStatusService; +import io.vertx.core.AsyncResult; +import io.vertx.core.Vertx; +import io.vertx.core.eventbus.EventBus; +import io.vertx.core.json.JsonObject; + +/** + * The Reprocessor Verticle to deploy the scheduler and implement re-processing + * logic + * + * @author Alok Ranjan + * @author Sowmya + * @author Pranav Kumar + * + * @since 0.10.0 + * + */ +@Component +public class ReprocessorVerticle extends MosipVerticleAPIManager { + + private static final String VERTICLE_PROPERTY_PREFIX = "mosip.regproc.reprocessor."; + + private static Logger regProcLogger = RegProcessorLogger.getLogger(ReprocessorVerticle.class); + + /** The cluster manager url. */ + @Value("${vertx.cluster.configuration}") + private String clusterManagerUrl; + + /** The environment. */ + @Autowired + Environment environment; + + /** The mosip event bus. */ + MosipEventBus mosipEventBus = null; + + /** The fetch size. */ + @Value("${registration.processor.reprocess.fetchsize}") + private Integer fetchSize; + + /** The elapse time. */ + @Value("${registration.processor.reprocess.elapse.time}") + private long elapseTime; + + /** The reprocess count. */ + @Value("${registration.processor.reprocess.attempt.count}") + private Integer reprocessCount; + + /** Comman seperated stage names that should be excluded while reprocessing. */ + @Value("#{T(java.util.Arrays).asList('${mosip.registration.processor.reprocessor.exclude-stage-names:PacketReceiverStage}')}") + private List reprocessExcludeStageNames; + + @Value("${registration.processor.reprocess.restart-from-stage}") + private String reprocessRestartFromStage; + + @Value("#{'${registration.processor.reprocess.restart-trigger-filter}'.split(',')}") + private List reprocessRestartTriggerFilter; + + /** The is transaction successful. */ + boolean isTransactionSuccessful; + + /** The registration status service. */ + @Autowired + RegistrationStatusService registrationStatusService; + + /** The core audit request builder. */ + @Autowired + AuditLogRequestBuilder auditLogRequestBuilder; + + /** Mosip router for APIs */ + @Autowired + MosipRouter router; + + /** The port. */ + @Value("${server.port}") + private String port; + + /** + * Deploy verticle. + */ + public void deployVerticle() { + mosipEventBus = this.getEventBus(this, clusterManagerUrl); + deployScheduler(getVertx()); + + } + + /** + * This method deploys the chime scheduler + * + * @param vertx + * the vertx + */ + private void deployScheduler(Vertx vertx) { + vertx.deployVerticle(ReprocessorConstants.CEYLON_SCHEDULER, this::schedulerResult); + } + + public void schedulerResult(AsyncResult res) { + if (res.succeeded()) { + regProcLogger.info("ReprocessorVerticle::schedular()::deployed"); + cronScheduling(vertx); + } else { + regProcLogger.error("ReprocessorVerticle::schedular()::deployment failure " + res.cause().getMessage()); + } + } + + /** + * This method does the cron scheduling by fetchin cron expression from config + * server + * + * @param vertx + * the vertx + */ + private void cronScheduling(Vertx vertx) { + + EventBus eventBus = vertx.eventBus(); + // listen the timer events + eventBus.consumer((ReprocessorConstants.TIMER_EVENT), message -> { + + process(new MessageDTO()); + }); + + // description of timers + JsonObject timer = (new JsonObject()) + .put(ReprocessorConstants.TYPE, environment.getProperty(ReprocessorConstants.TYPE_VALUE)) + .put(ReprocessorConstants.SECONDS, environment.getProperty(ReprocessorConstants.SECONDS_VALUE)) + .put(ReprocessorConstants.MINUTES, environment.getProperty(ReprocessorConstants.MINUTES_VALUE)) + .put(ReprocessorConstants.HOURS, environment.getProperty(ReprocessorConstants.HOURS_VALUE)) + .put(ReprocessorConstants.DAY_OF_MONTH, + environment.getProperty(ReprocessorConstants.DAY_OF_MONTH_VALUE)) + .put(ReprocessorConstants.MONTHS, environment.getProperty(ReprocessorConstants.MONTHS_VALUE)) + .put(ReprocessorConstants.DAYS_OF_WEEK, + environment.getProperty(ReprocessorConstants.DAYS_OF_WEEK_VALUE)); + + // create scheduler + eventBus.send(ReprocessorConstants.CHIME, + (new JsonObject()).put(ReprocessorConstants.OPERATION, ReprocessorConstants.OPERATION_VALUE) + .put(ReprocessorConstants.NAME, ReprocessorConstants.NAME_VALUE) + .put(ReprocessorConstants.DESCRIPTION, timer), + ar -> { + if (ar.succeeded()) { + regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString(), "", + "ReprocessorVerticle::schedular()::started"); + } else { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString(), "", + "ReprocessorVerticle::schedular()::failed " + ar.cause()); + vertx.close(); + } + }); + + } + + /** + * Send message. + * + * @param message + * the message + * @param toAddress + * the to address + */ + public void sendMessage(MessageDTO message, MessageBusAddress toAddress) { + this.send(this.mosipEventBus, toAddress, message); + } + + @Override + public void start() { + router.setRoute(this.postUrl(getVertx(), null, null)); + this.createServer(router.getRouter(), Integer.parseInt(port)); + } + + /* + * (non-Javadoc) + * + * @see + * io.mosip.registration.processor.core.spi.eventbus.EventBusManager#process( + * java.lang.Object) + */ + @Override + public MessageDTO process(MessageDTO object) { + List reprocessorDtoList = null; + LogDescription description = new LogDescription(); + List statusList = new ArrayList<>(); + statusList.add(RegistrationTransactionStatusCode.SUCCESS.toString()); + statusList.add(RegistrationTransactionStatusCode.REPROCESS.toString()); + statusList.add(RegistrationTransactionStatusCode.IN_PROGRESS.toString()); + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), "", + "ReprocessorVerticle::process()::entry"); + StringBuffer ridSb=new StringBuffer(); + try { + Map> reprocessRestartTriggerMap = intializeReprocessRestartTriggerMapping(); + reprocessorDtoList = registrationStatusService.getResumablePackets(fetchSize); + if (!CollectionUtils.isEmpty(reprocessorDtoList)) { + if (reprocessorDtoList.size() < fetchSize) { + List reprocessorPacketList = registrationStatusService.getUnProcessedPackets(fetchSize - reprocessorDtoList.size(), elapseTime, + reprocessCount, statusList, reprocessExcludeStageNames); + if (!CollectionUtils.isEmpty(reprocessorPacketList)) { + reprocessorDtoList.addAll(reprocessorPacketList); + } + } + } else { + reprocessorDtoList = registrationStatusService.getUnProcessedPackets(fetchSize, elapseTime, + reprocessCount, statusList, reprocessExcludeStageNames); + } + + + if (!CollectionUtils.isEmpty(reprocessorDtoList)) { + reprocessorDtoList.forEach(dto -> { + String registrationId = dto.getRegistrationId(); + ridSb.append(registrationId); + ridSb.append(","); + MessageDTO messageDTO = new MessageDTO(); + messageDTO.setRid(registrationId); + messageDTO.setReg_type(dto.getRegistrationType()); + messageDTO.setSource(dto.getSource()); + messageDTO.setIteration(dto.getIteration()); + messageDTO.setWorkflowInstanceId(dto.getWorkflowInstanceId()); + if (reprocessCount.equals(dto.getReProcessRetryCount())) { + dto.setLatestTransactionStatusCode( + RegistrationTransactionStatusCode.REPROCESS_FAILED.toString()); + dto.setLatestTransactionTypeCode( + RegistrationTransactionTypeCode.PACKET_REPROCESS.toString()); + dto.setStatusComment(StatusUtil.RE_PROCESS_FAILED.getMessage()); + dto.setStatusCode(RegistrationStatusCode.REPROCESS_FAILED.toString()); + dto.setSubStatusCode(StatusUtil.RE_PROCESS_FAILED.getCode()); + messageDTO.setIsValid(false); + description.setMessage(PlatformSuccessMessages.RPR_RE_PROCESS_FAILED.getMessage()); + description.setCode(PlatformSuccessMessages.RPR_RE_PROCESS_FAILED.getCode()); + + } else { + messageDTO.setIsValid(true); + isTransactionSuccessful = true; + String stageName; + if (isRestartFromStageRequired(dto, reprocessRestartTriggerMap)) { + stageName = MessageBusUtil.getMessageBusAdress(reprocessRestartFromStage); + stageName = stageName.concat(ReprocessorConstants.BUS_IN); + sendAndSetStatus(dto, messageDTO, stageName); + dto.setStatusComment(StatusUtil.RE_PROCESS_RESTART_FROM_STAGE.getMessage()); + dto.setSubStatusCode(StatusUtil.RE_PROCESS_RESTART_FROM_STAGE.getCode()); + description + .setMessage( + PlatformSuccessMessages.RPR_SENT_TO_REPROCESS_RESTART_FROM_STAGE_SUCCESS + .getMessage()); + description.setCode( + PlatformSuccessMessages.RPR_SENT_TO_REPROCESS_RESTART_FROM_STAGE_SUCCESS + .getCode()); + + } else { + stageName = MessageBusUtil.getMessageBusAdress(dto.getRegistrationStageName()); + if (RegistrationTransactionStatusCode.SUCCESS.name() + .equalsIgnoreCase(dto.getLatestTransactionStatusCode())) { + stageName = stageName.concat(ReprocessorConstants.BUS_OUT); + } else { + stageName = stageName.concat(ReprocessorConstants.BUS_IN); + } + sendAndSetStatus(dto, messageDTO, stageName); + dto.setStatusComment(StatusUtil.RE_PROCESS_COMPLETED.getMessage()); + dto.setSubStatusCode(StatusUtil.RE_PROCESS_COMPLETED.getCode()); + description.setMessage(PlatformSuccessMessages.RPR_SENT_TO_REPROCESS_SUCCESS.getMessage()); + description.setCode(PlatformSuccessMessages.RPR_SENT_TO_REPROCESS_SUCCESS.getCode()); + } + } + regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString(), registrationId, description.getMessage()); + + /** Module-Id can be Both Success/Error code */ + String moduleId = PlatformSuccessMessages.RPR_SENT_TO_REPROCESS_SUCCESS.getCode(); + String moduleName = ModuleName.RE_PROCESSOR.toString(); + registrationStatusService.updateRegistrationStatusForWorkflowEngine(dto, moduleId, moduleName); + String eventId = EventId.RPR_402.toString(); + String eventName = EventName.UPDATE.toString(); + String eventType = EventType.BUSINESS.toString(); + + if (!isTransactionSuccessful) + auditLogRequestBuilder.createAuditRequestBuilder(description.getMessage(), eventId, eventName, + eventType, moduleId, moduleName, registrationId); + }); + + } + } catch (TablenotAccessibleException e) { + isTransactionSuccessful = false; + object.setInternalError(Boolean.TRUE); + description.setMessage(PlatformErrorMessages.RPR_RGS_REGISTRATION_TABLE_NOT_ACCESSIBLE.getMessage()); + description.setCode(PlatformErrorMessages.RPR_RGS_REGISTRATION_TABLE_NOT_ACCESSIBLE.getCode()); + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), + description.getCode() + " -- ", + PlatformErrorMessages.RPR_RGS_REGISTRATION_TABLE_NOT_ACCESSIBLE.getMessage(), e.toString()); + + }catch (Exception ex) { + isTransactionSuccessful = false; + description.setMessage(PlatformErrorMessages.REPROCESSOR_VERTICLE_FAILED.getMessage()); + description.setCode(PlatformErrorMessages.REPROCESSOR_VERTICLE_FAILED.getCode()); + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + description.getCode() + " -- ", + PlatformErrorMessages.REPROCESSOR_VERTICLE_FAILED.getMessage() + ex.getMessage() + + ExceptionUtils.getStackTrace(ex)); + object.setInternalError(Boolean.TRUE); + + } finally { + regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + null, description.getMessage()); + if (isTransactionSuccessful) + description.setMessage(PlatformSuccessMessages.RPR_RE_PROCESS_SUCCESS.getMessage()); + + String eventId = isTransactionSuccessful ? EventId.RPR_402.toString() : EventId.RPR_405.toString(); + String eventName = isTransactionSuccessful ? EventName.UPDATE.toString() : EventName.EXCEPTION.toString(); + String eventType = isTransactionSuccessful ? EventType.BUSINESS.toString() : EventType.SYSTEM.toString(); + + /** Module-Id can be Both Success/Error code */ + String moduleId = isTransactionSuccessful ? PlatformSuccessMessages.RPR_RE_PROCESS_SUCCESS.getCode() + : description.getCode(); + String moduleName = ModuleName.RE_PROCESSOR.toString(); + auditLogRequestBuilder.createAuditRequestBuilder(description.getMessage(), eventId, eventName, eventType, + moduleId, moduleName, (ridSb.toString().length()>1?ridSb.substring(0,ridSb.length()-1):"")); + } + + return object; + } + + private Map> intializeReprocessRestartTriggerMapping() { + Map> reprocessRestartTriggerMap = new HashMap>(); + for (String filter : reprocessRestartTriggerFilter) { + String[] stageAndStatus = filter.split(":"); + String stageName = stageAndStatus[0]; + String latestTransactionStatusCode = stageAndStatus[1]; + Set latestTransactionStatusCodeSet; + if (reprocessRestartTriggerMap.containsKey(stageName)) { + latestTransactionStatusCodeSet = reprocessRestartTriggerMap.get(stageName); + if (latestTransactionStatusCodeSet.size() != 3) { + setReprocessRestartTriggerMap(reprocessRestartTriggerMap, stageName, latestTransactionStatusCode, + latestTransactionStatusCodeSet); + } + } else { + latestTransactionStatusCodeSet = new HashSet(); + setReprocessRestartTriggerMap(reprocessRestartTriggerMap, stageName, latestTransactionStatusCode, + latestTransactionStatusCodeSet); + } + } + return reprocessRestartTriggerMap; + + + } + + private void setReprocessRestartTriggerMap(Map> reprocessRestartTriggerMap, String stageName, + String latestTransactionStatusCode, Set latestTransactionStatusCodeSet) { + if (latestTransactionStatusCode.equalsIgnoreCase("*")) { + latestTransactionStatusCodeSet.add(RegistrationTransactionStatusCode.SUCCESS.toString()); + latestTransactionStatusCodeSet.add(RegistrationTransactionStatusCode.IN_PROGRESS.toString()); + latestTransactionStatusCodeSet.add(RegistrationTransactionStatusCode.REPROCESS.toString()); + } else { + latestTransactionStatusCodeSet.add(latestTransactionStatusCode.toUpperCase()); + } + reprocessRestartTriggerMap.put(stageName, latestTransactionStatusCodeSet); + } + + private boolean isRestartFromStageRequired(InternalRegistrationStatusDto dto, + Map> reprocessRestartTriggerMap) { + boolean isRestartFromStageRequired = false; + String stageName = dto.getRegistrationStageName(); + if (reprocessRestartTriggerMap.containsKey(stageName)) { + Set latestTransactionStatusCodes = reprocessRestartTriggerMap.get(stageName); + if (latestTransactionStatusCodes.contains(dto.getLatestTransactionStatusCode())) { + isRestartFromStageRequired = true; + } + } + return isRestartFromStageRequired; + } + + private void sendAndSetStatus(InternalRegistrationStatusDto dto, MessageDTO messageDTO, String stageName) { + MessageBusAddress address = new MessageBusAddress(stageName); + sendMessage(messageDTO, address); + dto.setUpdatedBy(ReprocessorConstants.USER); + Integer reprocessRetryCount = dto.getReProcessRetryCount() != null ? dto.getReProcessRetryCount() + 1 : 1; + dto.setReProcessRetryCount(reprocessRetryCount); + dto.setLatestTransactionStatusCode(RegistrationTransactionStatusCode.REPROCESS.toString()); + dto.setLatestTransactionTypeCode(RegistrationTransactionTypeCode.PACKET_REPROCESS.toString()); + } + + + + @Override + protected String getPropertyPrefix() { + return VERTICLE_PROPERTY_PREFIX; + } +} diff --git a/registration-processor/workflow-engine/registration-processor-reprocessor/src/test/java/io/mosip/registration/processor/reprocessor/verticle/ReprocessorVerticleTest.java b/registration-processor/workflow-engine/registration-processor-reprocessor/src/test/java/io/mosip/registration/processor/reprocessor/verticle/ReprocessorVerticleTest.java index cb182bf77db..b028d511454 100644 --- a/registration-processor/workflow-engine/registration-processor-reprocessor/src/test/java/io/mosip/registration/processor/reprocessor/verticle/ReprocessorVerticleTest.java +++ b/registration-processor/workflow-engine/registration-processor-reprocessor/src/test/java/io/mosip/registration/processor/reprocessor/verticle/ReprocessorVerticleTest.java @@ -38,6 +38,7 @@ import io.mosip.registration.processor.core.spi.restclient.RegistrationProcessorRestClientService; import io.mosip.registration.processor.rest.client.audit.builder.AuditLogRequestBuilder; import io.mosip.registration.processor.rest.client.audit.dto.AuditResponseDto; +import io.mosip.registration.processor.status.code.RegistrationStatusCode; import io.mosip.registration.processor.status.code.RegistrationType; import io.mosip.registration.processor.status.dto.InternalRegistrationStatusDto; import io.mosip.registration.processor.status.dto.RegistrationStatusDto; @@ -120,6 +121,16 @@ public void setup() throws Exception { ReflectionTestUtils.setField(reprocessorVerticle, "elapseTime", 21600); ReflectionTestUtils.setField(reprocessorVerticle, "reprocessCount", 3); ReflectionTestUtils.setField(reprocessorVerticle, "reprocessExcludeStageNames", new ArrayList<>()); + List reprocessRestartTriggerFilterList = new ArrayList<>(); + reprocessRestartTriggerFilterList.add("DemodedupStage:Success"); + reprocessRestartTriggerFilterList.add("BioDedupeStage:*"); + reprocessRestartTriggerFilterList.add("UinGeneratorStage:reprocess"); + reprocessRestartTriggerFilterList.add("BioDedupeStage:reprocess"); + + ReflectionTestUtils.setField(reprocessorVerticle, "reprocessRestartTriggerFilter", + reprocessRestartTriggerFilterList); + ReflectionTestUtils.setField(reprocessorVerticle, "reprocessRestartFromStage", + "SecurezoneNotificationStage"); Field auditLog = AuditLogRequestBuilder.class.getDeclaredField("registrationProcessorRestService"); auditLog.setAccessible(true); @SuppressWarnings("unchecked") @@ -259,4 +270,27 @@ public void testProcessValidWithResumablePackets() throws TablenotAccessibleExce reprocessorVerticle.process(dto); } + + @Test + public void testProcessWithRestartFromStage() throws TablenotAccessibleException, + PacketManagerException, + ApisResourceAccessException, WorkflowActionException { + + List dtolist = new ArrayList<>(); + InternalRegistrationStatusDto registrationStatusDto = new InternalRegistrationStatusDto(); + + registrationStatusDto.setRegistrationId("2018701130000410092018110735"); + registrationStatusDto.setRegistrationType(RegistrationType.NEW.toString()); + registrationStatusDto.setRegistrationStageName("BioDedupeStage"); + registrationStatusDto.setReProcessRetryCount(0); + registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); + registrationStatusDto.setLatestTransactionStatusCode(RegistrationTransactionStatusCode.REPROCESS.toString()); + dtolist.add(registrationStatusDto); + Mockito.when( + registrationStatusService.getUnProcessedPackets(anyInt(), anyLong(), anyInt(), anyList(), anyList())) + .thenReturn(dtolist); + reprocessorVerticle.process(dto); + + } + } From 8fdeb4995c892a60c4ff268b2077d58c458047ee Mon Sep 17 00:00:00 2001 From: Rakshith B <79500257+Rakshithb1@users.noreply.github.com> Date: Tue, 2 Jan 2024 17:47:31 +0530 Subject: [PATCH 30/38] [MOSIP-29961] removed paths from db-test.yml (#1816) Signed-off-by: Rakshith B <79500257+Rakshithb1@users.noreply.github.com> --- .github/workflows/db-test.yml | 2 -- 1 file changed, 2 deletions(-) diff --git a/.github/workflows/db-test.yml b/.github/workflows/db-test.yml index 35a2e6a3585..6d650a592e3 100644 --- a/.github/workflows/db-test.yml +++ b/.github/workflows/db-test.yml @@ -5,8 +5,6 @@ on: types: [published] pull_request: types: [opened, reopened, synchronize] - paths: - - 'db_scripts/**' workflow_dispatch: inputs: message: From 059a7d9538b1df9c8918998c05a4886942fbb572 Mon Sep 17 00:00:00 2001 From: Monobikash Das Date: Tue, 2 Jan 2024 18:43:58 +0530 Subject: [PATCH 31/38] MOSIP-28121 : calling idrepo instead of packetmanager in credential requestor Signed-off-by: Monobikash Das --- .../stage/CredentialRequestorStage.java | 4 +--- .../util/CredentialPartnerUtil.java | 11 ++++------- .../test/CredentialRequestorStageTest.java | 4 ++-- .../processor/packet/storage/utils/Utilities.java | 2 +- .../service/impl/MessageNotificationServiceImpl.java | 2 +- .../service/MessageNotificationServiceImplTest.java | 2 +- 6 files changed, 10 insertions(+), 15 deletions(-) diff --git a/registration-processor/post-processor/registration-processor-credential-requestor-stage/src/main/java/io/mosip/registration/processor/credentialrequestor/stage/CredentialRequestorStage.java b/registration-processor/post-processor/registration-processor-credential-requestor-stage/src/main/java/io/mosip/registration/processor/credentialrequestor/stage/CredentialRequestorStage.java index 74b1d6c6ddd..2932fe84bff 100644 --- a/registration-processor/post-processor/registration-processor-credential-requestor-stage/src/main/java/io/mosip/registration/processor/credentialrequestor/stage/CredentialRequestorStage.java +++ b/registration-processor/post-processor/registration-processor-credential-requestor-stage/src/main/java/io/mosip/registration/processor/credentialrequestor/stage/CredentialRequestorStage.java @@ -30,7 +30,6 @@ import io.mosip.registration.processor.credentialrequestor.dto.CredentialPartner; import io.mosip.registration.processor.credentialrequestor.stage.exception.VidNotAvailableException; import io.mosip.registration.processor.credentialrequestor.util.CredentialPartnerUtil; -import io.mosip.registration.processor.packet.storage.exception.ParsingException; import io.mosip.registration.processor.packet.storage.utils.Utilities; import io.mosip.registration.processor.rest.client.audit.builder.AuditLogRequestBuilder; import io.mosip.registration.processor.status.code.RegistrationStatusCode; @@ -41,7 +40,6 @@ import org.apache.commons.lang.StringUtils; import org.apache.commons.lang3.exception.ExceptionUtils; import org.json.JSONArray; -import org.json.JSONException; import org.json.simple.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; @@ -198,7 +196,7 @@ public MessageDTO process(MessageDTO object) { registrationStatusDto .setLatestTransactionTypeCode(RegistrationTransactionTypeCode.PRINT_SERVICE.toString()); registrationStatusDto.setRegistrationStageName(getStageName()); - JSONObject jsonObject = utilities.retrieveUIN(regId); + JSONObject jsonObject = utilities.idrepoRetrieveIdentityByRid(regId); uin = JsonUtil.getJSONValue(jsonObject, IdType.UIN.toString()); if (uin == null) { regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), diff --git a/registration-processor/post-processor/registration-processor-credential-requestor-stage/src/main/java/io/mosip/registration/processor/credentialrequestor/util/CredentialPartnerUtil.java b/registration-processor/post-processor/registration-processor-credential-requestor-stage/src/main/java/io/mosip/registration/processor/credentialrequestor/util/CredentialPartnerUtil.java index b357a6076e0..4495ae6e7ed 100644 --- a/registration-processor/post-processor/registration-processor-credential-requestor-stage/src/main/java/io/mosip/registration/processor/credentialrequestor/util/CredentialPartnerUtil.java +++ b/registration-processor/post-processor/registration-processor-credential-requestor-stage/src/main/java/io/mosip/registration/processor/credentialrequestor/util/CredentialPartnerUtil.java @@ -5,10 +5,7 @@ import io.mosip.kernel.core.exception.ExceptionUtils; import io.mosip.kernel.core.logger.spi.Logger; import io.mosip.kernel.core.util.exception.JsonProcessingException; -import io.mosip.registration.processor.core.constant.JsonConstant; -import io.mosip.registration.processor.core.constant.LoggerFileConstant; -import io.mosip.registration.processor.core.constant.MappingJsonConstants; -import io.mosip.registration.processor.core.constant.ProviderStageName; +import io.mosip.registration.processor.core.constant.*; import io.mosip.registration.processor.core.exception.ApisResourceAccessException; import io.mosip.registration.processor.core.exception.PacketManagerException; import io.mosip.registration.processor.core.exception.RegistrationProcessorCheckedException; @@ -128,11 +125,11 @@ public List getCredentialPartners(String regId, String regist return Lists.emptyList(); } - Map identityFieldValueMap = utilities.getPacketManagerService().getFields(regId, - requiredIdObjectFieldNames, registrationType, ProviderStageName.CREDENTIAL_REQUESTOR); + Map identityFieldValueMap = new HashMap<>(); + requiredIdObjectFieldNames.forEach(field -> identityFieldValueMap.put(field, JsonUtil.getJSONValue(identity, field))); Map context = new HashMap<>(); - for (Map.Entry identityAttribute: identityFieldValueMap.entrySet()) { + for (Map.Entry identityAttribute: identityFieldValueMap.entrySet()) { JSONObject attributeObject = new JSONObject(identityFieldValueMap); try { if (identityAttribute.getKey() != null && identityAttribute.getValue() != null) { diff --git a/registration-processor/post-processor/registration-processor-credential-requestor-stage/src/test/java/io/mosip/registrationprocessor/credentialrequestor/test/CredentialRequestorStageTest.java b/registration-processor/post-processor/registration-processor-credential-requestor-stage/src/test/java/io/mosip/registrationprocessor/credentialrequestor/test/CredentialRequestorStageTest.java index c20ece9327b..6c2f1189ff5 100644 --- a/registration-processor/post-processor/registration-processor-credential-requestor-stage/src/test/java/io/mosip/registrationprocessor/credentialrequestor/test/CredentialRequestorStageTest.java +++ b/registration-processor/post-processor/registration-processor-credential-requestor-stage/src/test/java/io/mosip/registrationprocessor/credentialrequestor/test/CredentialRequestorStageTest.java @@ -247,7 +247,7 @@ public void setup() throws Exception { Map map1 = new HashMap<>(); map1.put("UIN", "4238135072"); JSONObject jsonObject = new JSONObject(map1); - Mockito.when(utitilites.retrieveUIN(any())).thenReturn(jsonObject); + Mockito.when(utitilites.idrepoRetrieveIdentityByRid(any())).thenReturn(jsonObject); CredentialPartner partner1 = new CredentialPartner(); partner1.setId("digitalcardPartner"); @@ -396,7 +396,7 @@ public void testUINNotavailable() Map map1 = new HashMap<>(); JSONObject jsonObject = new JSONObject(map1); - Mockito.when(utitilites.retrieveUIN(any())).thenReturn(jsonObject); + Mockito.when(utitilites.idrepoRetrieveIdentityByRid(any())).thenReturn(jsonObject); MessageDTO result = stage.process(dto); assertFalse(result.getIsValid()); diff --git a/registration-processor/registration-processor-info-storage-service/src/main/java/io/mosip/registration/processor/packet/storage/utils/Utilities.java b/registration-processor/registration-processor-info-storage-service/src/main/java/io/mosip/registration/processor/packet/storage/utils/Utilities.java index 8619900d1e2..a0818625144 100644 --- a/registration-processor/registration-processor-info-storage-service/src/main/java/io/mosip/registration/processor/packet/storage/utils/Utilities.java +++ b/registration-processor/registration-processor-info-storage-service/src/main/java/io/mosip/registration/processor/packet/storage/utils/Utilities.java @@ -656,7 +656,7 @@ public String getLatestTransactionId(String registrationId, String process, int * @throws IOException Signals that an I/O exception has * occurred. */ - public JSONObject retrieveUIN(String regId) throws ApisResourceAccessException, IdRepoAppException, IOException { + public JSONObject idrepoRetrieveIdentityByRid(String regId) throws ApisResourceAccessException, IdRepoAppException, IOException { regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), regId, "Utilities::retrieveUIN()::entry"); diff --git a/registration-processor/registration-processor-message-sender-impl/src/main/java/io/mosip/registration/processor/message/sender/service/impl/MessageNotificationServiceImpl.java b/registration-processor/registration-processor-message-sender-impl/src/main/java/io/mosip/registration/processor/message/sender/service/impl/MessageNotificationServiceImpl.java index bd728d00455..e0c25f6c7c4 100644 --- a/registration-processor/registration-processor-message-sender-impl/src/main/java/io/mosip/registration/processor/message/sender/service/impl/MessageNotificationServiceImpl.java +++ b/registration-processor/registration-processor-message-sender-impl/src/main/java/io/mosip/registration/processor/message/sender/service/impl/MessageNotificationServiceImpl.java @@ -449,7 +449,7 @@ private Map setAttributes(String id, String process, String lang String uin = ""; if (idType.toString().equalsIgnoreCase(UIN)) { - JSONObject jsonObject = utility.retrieveUIN(id); + JSONObject jsonObject = utility.idrepoRetrieveIdentityByRid(id); uin = JsonUtil.getJSONValue(jsonObject, UIN); attributes.put("RID", id); attributes.put("UIN", uin); diff --git a/registration-processor/registration-processor-message-sender-impl/src/test/java/io/mosip/registration/processor/message/sender/test/service/MessageNotificationServiceImplTest.java b/registration-processor/registration-processor-message-sender-impl/src/test/java/io/mosip/registration/processor/message/sender/test/service/MessageNotificationServiceImplTest.java index 4f242aa7e98..ea6d1b11d1e 100644 --- a/registration-processor/registration-processor-message-sender-impl/src/test/java/io/mosip/registration/processor/message/sender/test/service/MessageNotificationServiceImplTest.java +++ b/registration-processor/registration-processor-message-sender-impl/src/test/java/io/mosip/registration/processor/message/sender/test/service/MessageNotificationServiceImplTest.java @@ -202,7 +202,7 @@ public void setup() throws Exception { map1.put("UIN", "423072"); JSONObject jsonObject1 = new JSONObject(map1); - Mockito.when(utility.retrieveUIN(any())).thenReturn(jsonObject1); + Mockito.when(utility.idrepoRetrieveIdentityByRid(any())).thenReturn(jsonObject1); Mockito.when(utility.getGetRegProcessorDemographicIdentity()).thenReturn("identity"); InputStream in = IOUtils.toInputStream("Hi Alok, Your UIN is generated", "UTF-8"); From 593c50cd6b1bdeb12dfd322727bf9912616dc9e9 Mon Sep 17 00:00:00 2001 From: khuddus shariff Date: Wed, 3 Jan 2024 16:59:37 +0530 Subject: [PATCH 32/38] [Mosip-28440] changes to compare the biometric records only with the records which are not processed Signed-off-by: khuddus shariff --- .../packet/storage/dao/PacketInfoDao.java | 7 +- .../packet/storage/utils/ABISHandlerUtil.java | 29 ++- .../storage/utils/ABISHandlerUtilTest.java | 246 +++++++++--------- .../repositary/RegistrationRepositary.java | 6 +- 4 files changed, 148 insertions(+), 140 deletions(-) diff --git a/registration-processor/registration-processor-info-storage-service/src/main/java/io/mosip/registration/processor/packet/storage/dao/PacketInfoDao.java b/registration-processor/registration-processor-info-storage-service/src/main/java/io/mosip/registration/processor/packet/storage/dao/PacketInfoDao.java index af857405162..f19ef8b3379 100644 --- a/registration-processor/registration-processor-info-storage-service/src/main/java/io/mosip/registration/processor/packet/storage/dao/PacketInfoDao.java +++ b/registration-processor/registration-processor-info-storage-service/src/main/java/io/mosip/registration/processor/packet/storage/dao/PacketInfoDao.java @@ -5,6 +5,7 @@ import java.util.List; import java.util.Map; +import io.mosip.registration.processor.status.entity.RegistrationStatusEntity; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @@ -592,12 +593,10 @@ public List getProcessedOrProcessingRegIds(List matchedRegIds, L * the matched reg ids * @param statusCode1 * the status code - * @param statusCode2 - * the status code * @return the processed or processing reg ids */ - public List getWithoutStatusCodes(List matchedRegIds, String statusCode1, String statusCode2) { - return registrationRepositary.getWithoutStatusCodes(matchedRegIds, "REJECTED", "PROCESSED"); + public List getWithoutStatusCode(List matchedRegIds, String statusCode) { + return registrationRepositary.getWithoutStatusCode(matchedRegIds, statusCode); } /** diff --git a/registration-processor/registration-processor-info-storage-service/src/main/java/io/mosip/registration/processor/packet/storage/utils/ABISHandlerUtil.java b/registration-processor/registration-processor-info-storage-service/src/main/java/io/mosip/registration/processor/packet/storage/utils/ABISHandlerUtil.java index d6ad7833d50..898f48a3c36 100644 --- a/registration-processor/registration-processor-info-storage-service/src/main/java/io/mosip/registration/processor/packet/storage/utils/ABISHandlerUtil.java +++ b/registration-processor/registration-processor-info-storage-service/src/main/java/io/mosip/registration/processor/packet/storage/utils/ABISHandlerUtil.java @@ -13,6 +13,8 @@ import io.mosip.registration.processor.core.code.AbisStatusCode; import io.mosip.registration.processor.core.constant.ProviderStageName; import io.mosip.registration.processor.core.exception.PacketManagerException; +import io.mosip.registration.processor.status.code.RegistrationStatusCode; +import io.mosip.registration.processor.status.entity.RegistrationStatusEntity; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.util.CollectionUtils; @@ -99,15 +101,26 @@ public Set getUniqueRegIds(String registrationId, String registrationTyp if (!CollectionUtils.isEmpty(machedRefIds)) { List matchedRegIds = packetInfoDao.getAbisRefRegIdsByMatchedRefIds(machedRefIds); if (!CollectionUtils.isEmpty(matchedRegIds)) { - List processingRegIds = packetInfoDao.getWithoutStatusCodes(matchedRegIds, - RegistrationTransactionStatusCode.REJECTED.toString(), RegistrationTransactionStatusCode.PROCESSED.toString()); - List statusList=new ArrayList<>(); - statusList.add(RegistrationTransactionStatusCode.PROCESSED.toString()); - statusList.add(RegistrationTransactionStatusCode.PROCESSING.toString()); - List processedRegIds = packetInfoDao.getProcessedOrProcessingRegIds(matchedRegIds, - statusList); - uniqueRIDs = getUniqueRegIds(processedRegIds, registrationId, registrationType, stageName); + List matchedRegistrationStatusEntities = packetInfoDao + .getWithoutStatusCode(matchedRegIds, + RegistrationStatusCode.REJECTED.toString()); + List processingRegistrationStatusEntities = matchedRegistrationStatusEntities + .stream() + .filter(e -> RegistrationStatusCode.PROCESSING.toString().equals(e.getStatusCode())) + .collect(Collectors.toList()); + List processingRegIds = processingRegistrationStatusEntities.stream() + .map(RegistrationStatusEntity::getRegId) + .collect(Collectors.toList()); + List matchedProcessedRegIds = matchedRegistrationStatusEntities.stream() + .map(RegistrationStatusEntity::getRegId).collect(Collectors.toList()); uniqueRIDs.addAll(processingRegIds); + Set processedRegIds = getUniqueRegIds(matchedProcessedRegIds, registrationId, + registrationType, + stageName); + for(String rid:processedRegIds) { + if(!uniqueRIDs.contains(rid)) + uniqueRIDs.add(rid); + } } } } diff --git a/registration-processor/registration-processor-info-storage-service/src/test/java/io/mosip/registration/processor/packet/storage/utils/ABISHandlerUtilTest.java b/registration-processor/registration-processor-info-storage-service/src/test/java/io/mosip/registration/processor/packet/storage/utils/ABISHandlerUtilTest.java index dce4b2c684c..3ed2d2edcbc 100644 --- a/registration-processor/registration-processor-info-storage-service/src/test/java/io/mosip/registration/processor/packet/storage/utils/ABISHandlerUtilTest.java +++ b/registration-processor/registration-processor-info-storage-service/src/test/java/io/mosip/registration/processor/packet/storage/utils/ABISHandlerUtilTest.java @@ -15,6 +15,8 @@ import io.mosip.registration.processor.packet.storage.dao.PacketInfoDao; import io.mosip.registration.processor.packet.storage.dto.ApplicantInfoDto; import io.mosip.registration.processor.packet.storage.mapper.PacketInfoMapper; +import io.mosip.registration.processor.status.code.RegistrationStatusCode; +import io.mosip.registration.processor.status.entity.RegistrationStatusEntity; import org.assertj.core.util.Lists; import org.junit.Before; import org.junit.Test; @@ -45,129 +47,125 @@ @PowerMockIgnore({ "javax.management.*", "javax.net.ssl.*","com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "javax.management.*" }) public class ABISHandlerUtilTest { - private static final String registrationId = "10002100820001420210108085956"; - private static final String registrationType = "NEW"; - private static final String latestTransactionId = "123-456-789"; - List matchedRids = new ArrayList<>(); - - - @InjectMocks - private ABISHandlerUtil abisHandlerUtil; - - @Mock - private Utilities utilities; - - @Mock - private PacketInfoManager packetInfoManager; - - @Mock - private PacketInfoDao packetInfoDao; - - @Mock - private IdRepoService idRepoService; - - List lst=new ArrayList<>(); - - @Before - public void setup() throws Exception { - MockitoAnnotations.initMocks(this); - when(utilities.getLatestTransactionId(any(),any(),anyInt(), any())).thenReturn(latestTransactionId); - - List regBioRefIds = new ArrayList<>(); - regBioRefIds.add("cf1c941a-142c-44f1-9543-4606b4a7884e"); - - when(packetInfoDao.getAbisRefIdByWorkflowInstanceId(any())).thenReturn(regBioRefIds); - when(utilities.getGetRegProcessorDemographicIdentity()).thenReturn(new String()); - - List inprogressMatchedIds = new ArrayList<>(); - inprogressMatchedIds.add("10002100820001420210108085100"); - inprogressMatchedIds.add("10002100820001420210108085101"); - inprogressMatchedIds.add("10002100820001420210108085102"); - - List processedMatchedIds = new ArrayList<>(); - processedMatchedIds.add("10002100820001420210108085103"); - processedMatchedIds.add("10002100820001420210108085104"); - - matchedRids.addAll(inprogressMatchedIds); - matchedRids.addAll(processedMatchedIds); - - List abisResponseDtoList = new ArrayList<>(); - matchedRids.forEach(matchedRid -> { - AbisResponseDto abisResponseDto = new AbisResponseDto(); - abisResponseDto.setId(matchedRid); - abisResponseDtoList.add(abisResponseDto); - }); - - - lst.add(RegistrationTransactionStatusCode.PROCESSED.toString());lst.add(RegistrationTransactionStatusCode.PROCESSING.toString()); - - - when(packetInfoManager.getAbisResponseRecords(regBioRefIds.get(0), - latestTransactionId, AbisConstant.IDENTIFY)).thenReturn(abisResponseDtoList); - - List abisResponseDetDtoList = new ArrayList<>(); - - matchedRids.forEach(matchedRid -> { - AbisResponseDetDto abisResponseDto = new AbisResponseDetDto(); - abisResponseDto.setMatchedBioRefId(matchedRid); - abisResponseDetDtoList.add(abisResponseDto); - }); - for (AbisResponseDetDto dto : abisResponseDetDtoList) { - AbisResponseDetDto responseDetDto = new AbisResponseDetDto(); - responseDetDto.setMatchedBioRefId(dto.getMatchedBioRefId()); - when(packetInfoManager.getAbisResponseDetails(dto.getMatchedBioRefId())).thenReturn(Lists.newArrayList(responseDetDto)); - } - - when(packetInfoDao.getAbisRefRegIdsByMatchedRefIds(matchedRids)).thenReturn(matchedRids); - - when(packetInfoDao.getWithoutStatusCodes(matchedRids, RegistrationTransactionStatusCode.REJECTED.toString(), - RegistrationTransactionStatusCode.PROCESSED.toString())).thenReturn(inprogressMatchedIds); - when(packetInfoDao.getProcessedOrProcessingRegIds(matchedRids, - lst)).thenReturn(processedMatchedIds); - - when(idRepoService.getUinByRid(processedMatchedIds.get(0), new String())).thenReturn("123456789"); - when(idRepoService.getUinByRid(processedMatchedIds.get(1), new String())).thenReturn("987654321"); - - } - - @Test - public void testProcesssedWithUniqueUin() throws ApisResourceAccessException, JsonProcessingException, PacketManagerException, IOException, io.mosip.kernel.core.exception.IOException { - - Set uniqueRids = abisHandlerUtil.getUniqueRegIds(registrationId, registrationType, 1, "", ProviderStageName.BIO_DEDUPE); - - assertEquals(matchedRids.size(), uniqueRids.size()); - } - - @Test - public void testProcesssedWithSameUin() throws ApisResourceAccessException, JsonProcessingException, PacketManagerException, IOException, io.mosip.kernel.core.exception.IOException { - - when(idRepoService.getUinByRid(anyString(), anyString())).thenReturn("987654321"); - - Set uniqueRids = abisHandlerUtil.getUniqueRegIds(registrationId, registrationType,1, "", ProviderStageName.BIO_DEDUPE); - // expected to pick only 1 rid from processedMatchedIds list. Total should be 3(inprogress) + 1(processed) - assertEquals(4, uniqueRids.size()); - } - - @Test - public void testDonotReturnRejected() throws ApisResourceAccessException, JsonProcessingException, PacketManagerException, IOException, io.mosip.kernel.core.exception.IOException { - - when(packetInfoDao.getWithoutStatusCodes(matchedRids, RegistrationTransactionStatusCode.REJECTED.toString(), - RegistrationTransactionStatusCode.PROCESSED.toString())).thenReturn(Lists.newArrayList()); - - Set uniqueRids = abisHandlerUtil.getUniqueRegIds(registrationId, registrationType,1, "", ProviderStageName.BIO_DEDUPE); - // expected to pick only rocessedMatchedIds list i.e 2 records. - assertEquals(2, uniqueRids.size()); - } - - @Test - public void testReturnAllInprogress() throws ApisResourceAccessException, JsonProcessingException, PacketManagerException, IOException, io.mosip.kernel.core.exception.IOException { - - when(packetInfoDao.getProcessedOrProcessingRegIds(matchedRids, - lst)).thenReturn(Lists.newArrayList()); - - Set uniqueRids = abisHandlerUtil.getUniqueRegIds(registrationId, registrationType,1, "", ProviderStageName.BIO_DEDUPE); - // expected not to pick rocessedMatchedIds list i.e 3 records. - assertEquals(3, uniqueRids.size()); - } + private static final String registrationId = "10002100820001420210108085956"; + private static final String registrationType = "NEW"; + private static final String latestTransactionId = "123-456-789"; + List matchedRids = new ArrayList<>(); + + + @InjectMocks + private ABISHandlerUtil abisHandlerUtil; + + @Mock + private Utilities utilities; + + @Mock + private PacketInfoManager packetInfoManager; + + @Mock + private PacketInfoDao packetInfoDao; + + @Mock + private IdRepoService idRepoService; + + List lst=new ArrayList<>(); + + @Before + public void setup() throws Exception { + MockitoAnnotations.initMocks(this); + when(utilities.getLatestTransactionId(any(),any(),anyInt(), any())).thenReturn(latestTransactionId); + + List regBioRefIds = new ArrayList<>(); + regBioRefIds.add("cf1c941a-142c-44f1-9543-4606b4a7884e"); + + when(packetInfoDao.getAbisRefIdByWorkflowInstanceId(any())).thenReturn(regBioRefIds); + when(utilities.getGetRegProcessorDemographicIdentity()).thenReturn(new String()); + + List registrationStatusEntityList = new ArrayList<>(); + + RegistrationStatusEntity registrationEntity1 = new RegistrationStatusEntity(); + registrationEntity1.setRegId("10002100820001420210108085103"); + registrationEntity1.setStatusCode(RegistrationStatusCode.PROCESSED.toString()); + registrationStatusEntityList.add(registrationEntity1); + RegistrationStatusEntity registrationEntity2 = new RegistrationStatusEntity(); + registrationEntity2.setRegId("10002100820001420210108085100"); + registrationEntity2.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); + registrationStatusEntityList.add(registrationEntity2); + RegistrationStatusEntity registrationEntity3 = new RegistrationStatusEntity(); + registrationEntity3.setRegId("10002100820001420210108085102"); + registrationEntity3.setStatusCode(RegistrationStatusCode.PROCESSED.toString()); + registrationStatusEntityList.add(registrationEntity3); + matchedRids.add("10002100820001420210108085100"); + matchedRids.add("10002100820001420210108085103"); + matchedRids.add("10002100820001420210108085101");// REJECTED + matchedRids.add("10002100820001420210108085102"); + + List abisResponseDtoList = new ArrayList<>(); + matchedRids.forEach(matchedRid -> { + AbisResponseDto abisResponseDto = new AbisResponseDto(); + abisResponseDto.setId(matchedRid); + abisResponseDtoList.add(abisResponseDto); + }); + + lst.add(RegistrationTransactionStatusCode.PROCESSED.toString());lst.add(RegistrationTransactionStatusCode.PROCESSING.toString()); + + when(packetInfoManager.getAbisResponseRecords(regBioRefIds.get(0), + latestTransactionId, AbisConstant.IDENTIFY)).thenReturn(abisResponseDtoList); + + List abisResponseDetDtoList = new ArrayList<>(); + matchedRids.forEach(matchedRid -> { + AbisResponseDetDto abisResponseDto = new AbisResponseDetDto(); + abisResponseDto.setMatchedBioRefId(matchedRid); + abisResponseDetDtoList.add(abisResponseDto); + }); + for (AbisResponseDetDto dto : abisResponseDetDtoList) { + AbisResponseDetDto responseDetDto = new AbisResponseDetDto(); + responseDetDto.setMatchedBioRefId(dto.getMatchedBioRefId()); + when(packetInfoManager.getAbisResponseDetails(dto.getMatchedBioRefId())).thenReturn(Lists.newArrayList(responseDetDto)); + } + when(packetInfoDao.getAbisRefRegIdsByMatchedRefIds(matchedRids)).thenReturn(matchedRids); + when(packetInfoDao.getWithoutStatusCode(matchedRids, RegistrationStatusCode.REJECTED.toString())) + .thenReturn(registrationStatusEntityList); + when(idRepoService.getUinByRid("10002100820001420210108085103", new String())).thenReturn("123456789"); + when(idRepoService.getUinByRid("10002100820001420210108085102", new String())).thenReturn("987654321"); + } + + @Test + public void testProcesssedWithUniqueUin() throws ApisResourceAccessException, JsonProcessingException, PacketManagerException, IOException, io.mosip.kernel.core.exception.IOException { + + Set uniqueRids = abisHandlerUtil.getUniqueRegIds(registrationId, registrationType, 1, "", ProviderStageName.BIO_DEDUPE); +// expected to pick 2 rids from processedMatchedIds list because different uin. + // Total should be 1(inprogress) + 2(processed) + assertEquals(3, uniqueRids.size()); + } + + @Test + public void testProcesssedWithSameUin() throws ApisResourceAccessException, JsonProcessingException, PacketManagerException, IOException, io.mosip.kernel.core.exception.IOException { + + when(idRepoService.getUinByRid(anyString(), anyString())).thenReturn("987654321"); + + Set uniqueRids = abisHandlerUtil.getUniqueRegIds(registrationId, registrationType,1, "", ProviderStageName.BIO_DEDUPE); + // expected to pick only 1 rid from processedMatchedIds list because same uin. Total should be 1(inprogress) + 1(processed) + assertEquals(2, uniqueRids.size()); + } + + @Test + public void testDonotReturnRejected() throws ApisResourceAccessException, JsonProcessingException, PacketManagerException, IOException, io.mosip.kernel.core.exception.IOException { + +// List uniqueRids = abisHandlerUtil.getUniqueRegIds(registrationId, registrationType, ProviderStageName.BIO_DEDUPE); + Set uniqueRids= abisHandlerUtil.getUniqueRegIds(registrationId,registrationType,1,"",ProviderStageName.BIO_DEDUPE); + // expected to pick only processingandprocessed list i.e 3 records. + assertEquals(3, uniqueRids.size()); + } + + @Test + public void testReturnAllInprogress() throws ApisResourceAccessException, JsonProcessingException, PacketManagerException, IOException, io.mosip.kernel.core.exception.IOException { + + when(idRepoService.getUinByRid(anyString(), anyString())).thenReturn(null); + + Set uniqueRids = abisHandlerUtil.getUniqueRegIds(registrationId, registrationType,1, "", ProviderStageName.BIO_DEDUPE); + // expected not to pick processedMatchedIds list i.e 1 records.. + assertEquals(1, uniqueRids.size()); + } } diff --git a/registration-processor/registration-processor-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/repositary/RegistrationRepositary.java b/registration-processor/registration-processor-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/repositary/RegistrationRepositary.java index 73cacb1a5d7..fc9a51848e0 100644 --- a/registration-processor/registration-processor-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/repositary/RegistrationRepositary.java +++ b/registration-processor/registration-processor-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/repositary/RegistrationRepositary.java @@ -31,10 +31,8 @@ public interface RegistrationRepositary ext public List getProcessedOrProcessingRegIds(@Param("regIds") List regIds, @Param("statusCode") List statusCode); - @Query("SELECT registration.regId FROM RegistrationStatusEntity registration WHERE registration.regId in :regIds AND registration.statusCode !=:statusCode1 AND registration.statusCode !=:statusCode2") - public List getWithoutStatusCodes(@Param("regIds") List regIds, - @Param("statusCode1") String statusCode1, @Param("statusCode2") String statusCode2); - + @Query("SELECT registration FROM RegistrationStatusEntity registration WHERE registration.id in :regIds and registration.statusCode !=:statusCode") + public List getWithoutStatusCode(@Param("regIds") List regIds, @Param("statusCode") String statusCode); @Query("SELECT registration FROM RegistrationStatusEntity registration WHERE registration.regId = :regId AND registration.isDeleted =false AND registration.isActive=true") public List findByRegId(@Param("regId") String regId); From dc57c8b442b212f2598ff0855c0aa1ef867c9283 Mon Sep 17 00:00:00 2001 From: Sowmya Ujjappa Banakar <43202851+sowmya695@users.noreply.github.com> Date: Wed, 10 Jan 2024 11:20:05 +0530 Subject: [PATCH 33/38] MOSIP-31016 code changes (#1824) Signed-off-by: Sowmya Ujjappa Banakar Co-authored-by: Sowmya Ujjappa Banakar --- pom.xml | 162 --------------------------------- registration-processor/pom.xml | 7 -- 2 files changed, 169 deletions(-) delete mode 100644 pom.xml diff --git a/pom.xml b/pom.xml deleted file mode 100644 index 4f5637a884d..00000000000 --- a/pom.xml +++ /dev/null @@ -1,162 +0,0 @@ - - - - 4.0.0 - io.mosip - registration - 1.2.1-SNAPSHOT - pom - - MOSIP Registration Parent POM - Mosip Registration Project - https://github.com/mosip/registration - - - MPL 2.0 - https://www.mozilla.org/en-US/MPL/2.0/ - - - - scm:git:git://github.com/mosip/registration.git - scm:git:ssh://github.com:mosip/registration.git - https://github.com/mosip/registration - HEAD - - - - Mosip - mosip.emailnotifier@gmail.com - io.mosip - https://github.com/mosip/registration - - - - - - ossrh - Central Repository - https://oss.sonatype.org/content/repositories/snapshots - default - - true - - - - central - Maven Central - default - https://repo1.maven.org/maven2 - - false - - - - - - - - ossrh - https://oss.sonatype.org/content/repositories/snapshots - - - ossrh - https://oss.sonatype.org/service/local/staging/deploy/maven2/ - - - - - - org.sonatype.plugins - nexus-staging-maven-plugin - 1.6.7 - true - - ossrh - https://oss.sonatype.org/ - false - - - - - org.apache.maven.plugins - maven-source-plugin - 2.2.1 - - - attach-sources - - jar-no-fork - - - - - - org.apache.maven.plugins - maven-javadoc-plugin - 3.2.0 - - - attach-javadocs - - jar - - - - - none - - - - - org.apache.maven.plugins - maven-gpg-plugin - 1.5 - - - sign-artifacts - verify - - sign - - - - --pinentry-mode - loopback - - - - - - - pl.project13.maven - git-commit-id-plugin - 3.0.1 - - - get-the-git-infos - - revision - - validate - - - - true - ${project.build.outputDirectory}/git.properties - - ^git.build.(time|version)$ - ^git.commit.id.(abbrev|full)$ - - full - ${project.basedir}/.git - - - - - - - - - registration-processor - - \ No newline at end of file diff --git a/registration-processor/pom.xml b/registration-processor/pom.xml index 09509bc0ab9..95341868fc1 100644 --- a/registration-processor/pom.xml +++ b/registration-processor/pom.xml @@ -1,13 +1,6 @@ 4.0.0 - - - io.mosip - registration - 1.2.1-SNAPSHOT - - MPL 2.0 From df1a4e38b89424a55a982a6a7273fce5395f7823 Mon Sep 17 00:00:00 2001 From: khuddus shariff Date: Wed, 17 Jan 2024 12:15:45 +0530 Subject: [PATCH 34/38] [Mosip-30241] triming the demographic data based on the property Signed-off-by: khuddus shariff --- .../storage/mapper/PacketInfoMapper.java | 15 +++++++---- .../service/impl/PacketInfoManagerImpl.java | 7 +++-- .../storage/PacketInfoManagerImplTest.java | 27 ++++++++++++++----- 3 files changed, 36 insertions(+), 13 deletions(-) diff --git a/registration-processor/registration-processor-info-storage-service/src/main/java/io/mosip/registration/processor/packet/storage/mapper/PacketInfoMapper.java b/registration-processor/registration-processor-info-storage-service/src/main/java/io/mosip/registration/processor/packet/storage/mapper/PacketInfoMapper.java index ec4dead9cb5..2118643dd1f 100644 --- a/registration-processor/registration-processor-info-storage-service/src/main/java/io/mosip/registration/processor/packet/storage/mapper/PacketInfoMapper.java +++ b/registration-processor/registration-processor-info-storage-service/src/main/java/io/mosip/registration/processor/packet/storage/mapper/PacketInfoMapper.java @@ -71,12 +71,17 @@ private PacketInfoMapper() { * the language * @return the json values */ - private static String getJsonValues(JsonValue[] jsonNode, String language) { + private static String getJsonValues(JsonValue[] jsonNode, String language,Boolean istrim) { String value = null; if (jsonNode != null) { for (int i = 0; i < jsonNode.length; i++) { if (jsonNode[i].getLanguage().equals(language)) { - value = jsonNode[i].getValue(); + if(istrim) + { + value = jsonNode[i].getValue().trim(); + }else { + value = jsonNode[i].getValue(); + } } } } @@ -114,7 +119,7 @@ private static String[] getLanguages(JsonValue[] jsonNode, StringBuilder languag * @return the list */ public static List converDemographicDedupeDtoToEntity( - IndividualDemographicDedupe demoDto, String regId,String process, int iteration, String workflowInstanceId) throws NoSuchAlgorithmException { + IndividualDemographicDedupe demoDto, String regId,String process, int iteration, String workflowInstanceId,Boolean istrim) throws NoSuchAlgorithmException { regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), regId, "PacketInfoMapper::converDemographicDedupeDtoToEntity()::entry"); IndividualDemographicDedupeEntity entity; @@ -144,7 +149,7 @@ public static List converDemographicDedupeDto if (demoDto.getName()!=null &&!demoDto.getName().isEmpty()) { for (JsonValue[] jsonValue : demoDto.getName()) { - applicantFullName.append(getJsonValues(jsonValue, languageArray[i])); + applicantFullName.append(getJsonValues(jsonValue, languageArray[i],istrim)); } entity.setName(!applicantFullName.toString().isEmpty() ? getHMACHashCode(applicantFullName.toString().trim().toUpperCase()) @@ -163,7 +168,7 @@ public static List converDemographicDedupeDto throw new DateParseException(PlatformErrorMessages.RPR_SYS_PARSING_DATE_EXCEPTION.getMessage(), e); } } - entity.setGender(getHMACHashCode(getJsonValues(demoDto.getGender(), languageArray[i]))); + entity.setGender(getHMACHashCode(getJsonValues(demoDto.getGender(), languageArray[i],istrim))); entity.setPhone(getHMACHashCode(demoDto.getPhone())); entity.setEmail(getHMACHashCode(demoDto.getEmail())); demogrphicDedupeEntities.add(entity); diff --git a/registration-processor/registration-processor-info-storage-service/src/main/java/io/mosip/registration/processor/packet/storage/service/impl/PacketInfoManagerImpl.java b/registration-processor/registration-processor-info-storage-service/src/main/java/io/mosip/registration/processor/packet/storage/service/impl/PacketInfoManagerImpl.java index 4ea28232ac8..0d434dec81c 100644 --- a/registration-processor/registration-processor-info-storage-service/src/main/java/io/mosip/registration/processor/packet/storage/service/impl/PacketInfoManagerImpl.java +++ b/registration-processor/registration-processor-info-storage-service/src/main/java/io/mosip/registration/processor/packet/storage/service/impl/PacketInfoManagerImpl.java @@ -141,6 +141,9 @@ public class PacketInfoManagerImpl implements PacketInfoManager applicantDemographicEntities = PacketInfoMapper - .converDemographicDedupeDtoToEntity(demographicData, regId,process,iteration, workflowInstanceId); + .converDemographicDedupeDtoToEntity(demographicData, regId,process,iteration, workflowInstanceId,trimWhitespace); for (IndividualDemographicDedupeEntity applicantDemographicEntity : applicantDemographicEntities) { demographicDedupeRepository.save(applicantDemographicEntity); @@ -339,7 +342,7 @@ public void saveIndividualDemographicDedupeUpdatePacket(IndividualDemographicDed try { List applicantDemographicEntities = PacketInfoMapper - .converDemographicDedupeDtoToEntity(demographicData, registrationId,process,iteration, workflowInstanceId); + .converDemographicDedupeDtoToEntity(demographicData, registrationId,process,iteration, workflowInstanceId,trimWhitespace); for (IndividualDemographicDedupeEntity applicantDemographicEntity : applicantDemographicEntities) { demographicDedupeRepository.save(applicantDemographicEntity); diff --git a/registration-processor/registration-processor-info-storage-service/src/test/java/io/mosip/registration/processor/packet/storage/PacketInfoManagerImplTest.java b/registration-processor/registration-processor-info-storage-service/src/test/java/io/mosip/registration/processor/packet/storage/PacketInfoManagerImplTest.java index d6c53205c4a..13d184b70ee 100644 --- a/registration-processor/registration-processor-info-storage-service/src/test/java/io/mosip/registration/processor/packet/storage/PacketInfoManagerImplTest.java +++ b/registration-processor/registration-processor-info-storage-service/src/test/java/io/mosip/registration/processor/packet/storage/PacketInfoManagerImplTest.java @@ -27,10 +27,7 @@ import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; +import org.mockito.*; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; @@ -93,6 +90,7 @@ import io.mosip.registration.processor.packet.storage.utils.PriorityBasedPacketManagerService; import io.mosip.registration.processor.packet.storage.utils.Utilities; import io.mosip.registration.processor.rest.client.audit.builder.AuditLogRequestBuilder; +import org.springframework.test.util.ReflectionTestUtils; /** * The Class PacketInfoManagerImplTest. @@ -1057,7 +1055,7 @@ public void testsaveIndividualDemographicDedupe() throws NoSuchAlgorithmExceptio entity.setDob("2019-03-02T06:29:41.011Z"); applicantDemographicEntities.add(entity); PowerMockito.mockStatic(PacketInfoMapper.class); - Mockito.when(PacketInfoMapper.converDemographicDedupeDtoToEntity(Mockito.any(), Mockito.any(),Mockito.any(),Mockito.anyInt(), any())) + Mockito.when(PacketInfoMapper.converDemographicDedupeDtoToEntity(Mockito.any(), Mockito.any(),Mockito.any(),Mockito.anyInt(), any(),any())) .thenReturn(applicantDemographicEntities); Mockito.when(demographicDedupeRepository.save(any())).thenReturn(entity); packetInfoManagerImpl.saveIndividualDemographicDedupeUpdatePacket(demographicData, @@ -1075,7 +1073,7 @@ public void testsaveIndividualDemographicDedupeException() throws NoSuchAlgorith entity.setDob("2019-03-02T06:29:41.011Z"); applicantDemographicEntities.add(entity); PowerMockito.mockStatic(PacketInfoMapper.class); - Mockito.when(PacketInfoMapper.converDemographicDedupeDtoToEntity(Mockito.any(), Mockito.any(),Mockito.any(),Mockito.anyInt(), any())) + Mockito.when(PacketInfoMapper.converDemographicDedupeDtoToEntity(Mockito.any(), Mockito.any(),Mockito.any(),Mockito.anyInt(), any(),any())) .thenReturn(applicantDemographicEntities); Mockito.when(demographicDedupeRepository.save(any())).thenThrow(exp); packetInfoManagerImpl.saveIndividualDemographicDedupeUpdatePacket(demographicData, @@ -1153,4 +1151,21 @@ public void dataAccessLayerExceptionTest() { } + @Test + public void testsaveIndividualDemographicDedupeWithTrim() throws NoSuchAlgorithmException { + ReflectionTestUtils.setField(packetInfoManagerImpl,"trimWhitespace",true); + IndividualDemographicDedupe demographicData = new IndividualDemographicDedupe(); + demographicData.setDateOfBirth("2019-03-02T06:29:41.011Z"); + List applicantDemographicEntities = new ArrayList<>(); + IndividualDemographicDedupeEntity entity = new IndividualDemographicDedupeEntity(); + entity.setDob("2019-03-02T06:29:41.011Z"); + applicantDemographicEntities.add(entity); + PowerMockito.mockStatic(PacketInfoMapper.class); + Mockito.when(PacketInfoMapper.converDemographicDedupeDtoToEntity(Mockito.any(), Mockito.any(),Mockito.any(),Mockito.anyInt(), any(),any())) + .thenReturn(applicantDemographicEntities); + Mockito.when(demographicDedupeRepository.save(any())).thenReturn(entity); + ArgumentCaptor arg2 = ArgumentCaptor.forClass(Integer.class); + packetInfoManagerImpl.saveIndividualDemographicDedupeUpdatePacket(demographicData, + "1001", "","NEW", "",1, ""); + } } From 13ff6d9c1c89e3e42e295b2c507bb9a4e8665792 Mon Sep 17 00:00:00 2001 From: khuddus shariff Date: Wed, 17 Jan 2024 12:29:35 +0530 Subject: [PATCH 35/38] [Mosip-30241] triming the demographic data based on the property Signed-off-by: khuddus shariff --- .../processor/packet/storage/mapper/PacketInfoMapper.java | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/registration-processor/registration-processor-info-storage-service/src/main/java/io/mosip/registration/processor/packet/storage/mapper/PacketInfoMapper.java b/registration-processor/registration-processor-info-storage-service/src/main/java/io/mosip/registration/processor/packet/storage/mapper/PacketInfoMapper.java index 2118643dd1f..3f8313742fa 100644 --- a/registration-processor/registration-processor-info-storage-service/src/main/java/io/mosip/registration/processor/packet/storage/mapper/PacketInfoMapper.java +++ b/registration-processor/registration-processor-info-storage-service/src/main/java/io/mosip/registration/processor/packet/storage/mapper/PacketInfoMapper.java @@ -118,6 +118,11 @@ private static String[] getLanguages(JsonValue[] jsonNode, StringBuilder languag * @param iteration * @return the list */ + public static List converDemographicDedupeDtoToEntity( + IndividualDemographicDedupe demoDto, String regId,String process, int iteration, String workflowInstanceId) throws NoSuchAlgorithmException { + + return converDemographicDedupeDtoToEntity(demoDto,regId,process,iteration,workflowInstanceId,false); + } public static List converDemographicDedupeDtoToEntity( IndividualDemographicDedupe demoDto, String regId,String process, int iteration, String workflowInstanceId,Boolean istrim) throws NoSuchAlgorithmException { regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), regId, From 794e3e810f5dcd054ceeaa7993e7ba30c23e826a Mon Sep 17 00:00:00 2001 From: Sowmya Ujjappa Banakar Date: Tue, 23 Jan 2024 12:01:00 +0530 Subject: [PATCH 36/38] registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/status/util/StatusUtil.java Signed-off-by: Sowmya Ujjappa Banakar --- .../registration/processor/core/status/util/StatusUtil.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) 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 faf73cfe26c..768420770d7 100644 --- a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/status/util/StatusUtil.java +++ b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/status/util/StatusUtil.java @@ -252,7 +252,7 @@ public enum StatusUtil { "Exception occured updating idrepo draft."), IDREPO_DRAFT_REPROCESSABLE_EXCEPTION(StatusConstants.UIN_GENERATOR_MODULE_FAILED + "009", - "Exception occured updating idrepo draft,Which can be reprocess"), + "Exception occured updating idrepo draft, which can be reprocessed"), // Biometric extraction stage BIOMETRIC_EXTRACTION_SUCCESS(StatusConstants.BIOMETRIC_EXTRACTION_MODULE_SUCCESS + "001", @@ -264,7 +264,7 @@ public enum StatusUtil { BIOMETRIC_EXTRACTION_IDREPO_DRAFT_REPROCESSABLE_EXCEPTION( StatusConstants.BIOMETRIC_EXTRACTION_MODULE_FAILED + "003", - "Exception occured updating idrepo draft,Which can be reprocess"), + "Exception occured updating idrepo draft, which can be reprocessed"), FINALIZATION_SUCCESS(StatusConstants.FINALIZATION_MODULE_SUCCESS + "001", "idrepo draft was published successfuly"), @@ -276,7 +276,7 @@ public enum StatusUtil { "Exception occured updating idrepo draft."), FINALIZATION_IDREPO_DRAFT_REPROCESSABLE_EXCEPTION(StatusConstants.FINALIZATION_MODULE_FAILED + "004", - "Exception occured updating idrepo draft,Which can be reprocess"), + "Exception occured updating idrepo draft, which can be reprocessed"), // Request handler service // 1)Resident UIN update From 88e7912d3023c9fb0fda1b18ea1d858fdeae61aa Mon Sep 17 00:00:00 2001 From: khuddus shariff Date: Wed, 24 Jan 2024 10:41:20 +0530 Subject: [PATCH 37/38] [Mosip-30241]adding trim functionality based on property (#1837) Signed-off-by: khuddus shariff --- .../uingenerator/stage/UinGeneratorStage.java | 7 ++- .../uigenerator/UinGeneratorStageTest.java | 59 ++++++++++++++++--- 2 files changed, 57 insertions(+), 9 deletions(-) diff --git a/registration-processor/core-processor/registration-processor-uin-generator-stage/src/main/java/io/mosip/registration/processor/stages/uingenerator/stage/UinGeneratorStage.java b/registration-processor/core-processor/registration-processor-uin-generator-stage/src/main/java/io/mosip/registration/processor/stages/uingenerator/stage/UinGeneratorStage.java index 5d5e8ac4421..63c05ac64ac 100644 --- a/registration-processor/core-processor/registration-processor-uin-generator-stage/src/main/java/io/mosip/registration/processor/stages/uingenerator/stage/UinGeneratorStage.java +++ b/registration-processor/core-processor/registration-processor-uin-generator-stage/src/main/java/io/mosip/registration/processor/stages/uingenerator/stage/UinGeneratorStage.java @@ -152,6 +152,9 @@ public class UinGeneratorStage extends MosipVerticleAPIManager { @Value("${uingenerator.lost.packet.allowed.update.fields:null}") private String updateInfo; + @Value("${mosip.regproc.uin.generator.trim-whitespaces.simpleType-value:false}") + private boolean trimWhitespaces; + /** The core audit request builder. */ @Autowired private AuditLogRequestBuilder auditLogRequestBuilder; @@ -323,7 +326,6 @@ public MessageDTO process(MessageDTO object) { description); } } - } regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), registrationId, description.getMessage()); @@ -477,6 +479,9 @@ else if (json instanceof JSONArray) { for (int i = 0; i < jsonArray.length(); i++) { Object obj = jsonArray.get(i); HashMap hashMap = objectMapper.readValue(obj.toString(), HashMap.class); + if(trimWhitespaces && hashMap.get("value") instanceof String) { + hashMap.put("value",((String)hashMap.get("value")).trim()); + } jsonList.add(hashMap); } demographicIdentity.putIfAbsent(e.getKey(), jsonList); diff --git a/registration-processor/core-processor/registration-processor-uin-generator-stage/src/test/java/io/mosip/registration/processor/stages/uigenerator/UinGeneratorStageTest.java b/registration-processor/core-processor/registration-processor-uin-generator-stage/src/test/java/io/mosip/registration/processor/stages/uigenerator/UinGeneratorStageTest.java index f3328aafd64..a94473058a9 100644 --- a/registration-processor/core-processor/registration-processor-uin-generator-stage/src/test/java/io/mosip/registration/processor/stages/uigenerator/UinGeneratorStageTest.java +++ b/registration-processor/core-processor/registration-processor-uin-generator-stage/src/test/java/io/mosip/registration/processor/stages/uigenerator/UinGeneratorStageTest.java @@ -1,12 +1,11 @@ package io.mosip.registration.processor.stages.uigenerator; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.Assert.*; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyDouble; import static org.mockito.ArgumentMatchers.anyList; import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.when; +import static org.mockito.Mockito.*; import java.io.ByteArrayInputStream; import java.io.File; @@ -15,6 +14,8 @@ import java.io.InputStream; import java.lang.reflect.Field; import java.nio.charset.StandardCharsets; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; @@ -22,6 +23,10 @@ import java.util.List; import java.util.Map; +import com.fasterxml.jackson.databind.JsonNode; +import io.mosip.kernel.core.util.DateUtils; +import io.mosip.registration.processor.packet.manager.dto.IdRequestDto; +import io.mosip.registration.processor.stages.uingenerator.dto.VidResponseDto; import org.apache.commons.io.IOUtils; import org.assertj.core.util.Lists; import org.json.JSONException; @@ -30,11 +35,7 @@ import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; -import org.mockito.Spy; +import org.mockito.*; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; @@ -2432,4 +2433,46 @@ public void testUinGenerationIDRepoDraftReprocessableException() throws Exceptio assertTrue(result.getInternalError()); assertTrue(result.getIsValid()); } + + @Test + public void testUinGenerationSuccessWithEmptyName() throws Exception { + ReflectionTestUtils.setField(uinGeneratorStage,"trimWhitespaces",true); + Map fieldMap = new HashMap<>(); + fieldMap.put("firstName","[ {\n" + + " \"language\" : \"eng\",\n" + + " \"value\" : \" \"\n" + + "} ]"); + fieldMap.put("email", "mono@mono.com"); + fieldMap.put("phone", "23456"); + fieldMap.put("dob", "11/11/2011"); + when(packetManagerService.getFields(any(),any(),any(),any())).thenReturn(fieldMap); + ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(IdRequestDto.class); + + MessageDTO messageDTO = new MessageDTO(); + messageDTO.setRid("27847657360002520181210094052"); + messageDTO.setReg_type(RegistrationType.NEW.name()); + + IdResponseDTO idResponseDTO = new IdResponseDTO(); + ResponseDTO responseDTO = new ResponseDTO(); + responseDTO.setStatus("ACTIVATED"); + idResponseDTO.setErrors(null); + idResponseDTO.setId("mosip.id.update"); + idResponseDTO.setResponse(responseDTO); + idResponseDTO.setResponsetime("2019-01-17T06:29:01.940Z"); + idResponseDTO.setVersion("1.0"); + + when(idrepoDraftService.idrepoUpdateDraft(anyString(), any(), any())).thenReturn(idResponseDTO); + when(utility.getRegistrationProcessorMappingJson(MappingJsonConstants.IDENTITY)).thenReturn(identityObj); + when(utility.getRegistrationProcessorMappingJson(MappingJsonConstants.DOCUMENT)).thenReturn(documentObj); + + MessageDTO result = uinGeneratorStage.process(messageDTO); + verify(idrepoDraftService).idrepoUpdateDraft(any(), any(), argumentCaptor.capture()); + ObjectMapper objectMapper = new ObjectMapper(); + String jsonobject=objectMapper.writeValueAsString(argumentCaptor.getAllValues().get(0).getRequest().getIdentity()); + JsonNode jsonNode=objectMapper.readTree(jsonobject); + + assertEquals("",jsonNode.get("firstName").asText()); + assertFalse(result.getInternalError()); + assertTrue(result.getIsValid()); + } } \ No newline at end of file From f41f0993f2f263d925ad78e07f40ea01c1820475 Mon Sep 17 00:00:00 2001 From: Monobikash Das <43202165+MonobikashDas@users.noreply.github.com> Date: Thu, 1 Feb 2024 14:46:18 +0530 Subject: [PATCH 38/38] Added credential requestor documentation (#1842) Signed-off-by: Monobikash Das --- README.md | 2 +- .../README.md | 110 +++++++++++++++++- 2 files changed, 109 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index b8d6b37cc06..d423976b56c 100644 --- a/README.md +++ b/README.md @@ -42,7 +42,7 @@ Staged architecture: * UIN generator * Biometric extraction * Finalization - * Printing + * [Credential requestor](registration-processor/post-processor/registration-processor-credential-requestor-stage) The control and data flow in the stages is controlled by [Workflow engine](registration-processor/workflow-engine/) diff --git a/registration-processor/post-processor/registration-processor-credential-requestor-stage/README.md b/registration-processor/post-processor/registration-processor-credential-requestor-stage/README.md index 320dffd6672..7d5775d9b36 100644 --- a/registration-processor/post-processor/registration-processor-credential-requestor-stage/README.md +++ b/registration-processor/post-processor/registration-processor-credential-requestor-stage/README.md @@ -1,7 +1,113 @@ -# Credential Requestor Stage +# Credential Requestor Stage(previously called print stage) ## About -Creates Credential Request for internal/external systems. +- This stage is renamed from print-stage to credential-requestor-stage. +- Creates Credential Request for internal/external systems. ## Default context, path, port Refert to [bootstrap properties](src/main/resources/bootstrap.properties) + + +## History of Print Stage in MOSIP +In the initial version of MOSIP (0.9.0), the "print stage" was primarily designed to facilitate the submission of printing requests. Its core functionality revolved around initiating a request for the physical printing of credentials. However, as the system evolved and incorporated additional features, the scope of the print stage expanded beyond its original purpose. + +In the evolved version, particularly after the integration of new features, the print stage underwent significant enhancements. Contrary to its initial purpose, the print stage no longer serves the singular function of printing credentials. Instead, it has transformed into a multifaceted component with a broader set of responsibilities. + +In the current system, the print stage's role extends beyond traditional printing activities. Its primary function now revolves around initiating a request for credential generation once a Unique Identification Number (UIN) is generated. This request is not aimed at physical printing but serves as a mechanism to gather additional information for specific partners. These partners may require supplementary data beyond what is initially generated with the UIN. + +Therefore, in the evolved approach, the print stage has transitioned from being a straightforward printing request to a more versatile component that manages the initiation of credential requests tailored to partner-specific information needs. This adaptation reflects the system's responsiveness to changing requirements and the dynamic nature of credentialing processes. This reason led us to rename the “Print Stage” to the “Credential Requestor Stage” as this name serves the purpose of the work executed by this stage. + +## Introduction +The Credential Requestor Stage in MOSIP, formerly known as the Print Stage, is a crucial component used to request credentials for configurable partners after the Unique Identification Number (UIN) is generated. This stage enables countries to share information with multiple partners, each with specific needs after UIN generation. Partners, such as Print Partners and Digital Card Partners, may require demographic or biometric information to perform operations. + +## What is the credential requestor stage? +The Credential Requestor Stage plays a crucial role in the MOSIP system, serving as a mechanism to solicit credentials from configurable partners post-UIN generation. In this context, partners, previously registered with MOSIP, require demographic and biometric data to execute their respective operations. For instance, a Print Partner necessitates specific demographic details for the purpose of printing cards. Similarly, digital card partners seek demographic information to generate digital cards. Additionally, DPGs might seek confirmation of successful UIN generation to integrate this information into their systems. The Credential Requestor Stage facilitates various use cases where the country aims to share pertinent information with multiple partners subsequent to UIN generation. + +## What are the latest changes done in the credential requestor stage? +### Partner Profile Configuration +MOSIP has introduced a new partner profile for the Credential Requestor Stage. The partner profiles are maintained in the [registration-processor-credential-partners.json](https://github.com/mosip/mosip-config/blob/develop1-v3/registration-processor-credential-partners.json) + +### Sample Partner Profile: + +```json +{ +"partners": [ +{ +"id": "digitalcardPartner", +"partnerId": "mpartner-default-digitalcard", +"credentialType": "PDFCard", +"template": "RPR_UIN_CARD_TEMPLATE", +"appIdBasedCredentialIdSuffix": ".pdf", +"process": null, +"metaInfoFields": null +}, +{ +"id": "printPartner", +"partnerId": "mpartner-default-print", +"credentialType": "euin", +"template": "RPR_UIN_CARD_TEMPLATE", +"appIdBasedCredentialIdSuffix": null, +"process": null, +"metaInfoFields": null +}, +{ +"id": "opencrvsPartner", +"partnerId": "opencrvs-partner", +"type": "opencrvs", +"template": "RPR_UIN_CARD_TEMPLATE", +"process": ["OPENCRVS_NEW"], +"metaInfoFields": ["opencrvsBRN"] +} +] +} + +``` +### Explanation of Fields: + +id: Logical unique identifier. + +partnerId: Partner identifier configured in MOSIP. + +credentialType: Type of credential configured in MOSIP. + +template: Template used for generating the credential. + +appIdBasedCredentialIdSuffix: Applicable for special conditions where the credential ID is the application ID itself, with an optional suffix (e.g., .pdf). This is applicable for digital card credentials as of now. + +process: If applicable for a particular process. If applicable for all processes, it can be left as null. + +metaInfoFields: Meta information fields to be sent as additional information while generating the credential. + +### Configuration Changes +Once the partner profile is configured, the System Integrator (SI) needs to make changes to the following configurations: + +mosip.registration.processor.credential.partner-profiles: Specify the file name for the partner profiles. By default its → registration-processor-credential-partners.json. If a country wants to change the file name only then this configuration need to be updated otherwise use default configuration. + +mosip.registration.processor.credential.default.partner-ids: Specify default partner IDs for which credentials will be created automatically. + +mosip.registration.processor.credential.conditional.partner-id-map: Define conditions for conditional partners. Credentials for these partners will be requested only if the conditions are met. Use MVEL expressions for conditions. + +mosip.registration.processor.credential.conditional.no-match-partner-ids: Specify a partner ID to be used when no conditions are met for conditional partners. + +### Conditional Partner Requests +The stage will create credentials for default partner IDs by default. + +For conditional partners, credentials will be requested only if they match a particular MVEL expression. + +MVEL expressions can be written on any identity field as well as meta info field. + +If there is no condition match for conditional partners, SI can configure a no-match partner, which will be used when no conditional partner match is found. + +### Configuration File Locations +Credential Requestor Stage Configuration: + +File: [registration-processor-default.properties](https://github.com/mosip/mosip-config/blob/develop1-v3/registration-processor-default.properties#L479) + +Partner Profile Configuration: + +File: [registration-processor-credential-partners.json](https://github.com/mosip/mosip-config/blob/develop1-v3/registration-processor-credential-partners.json) + +## Conclusion +The Credential Requestor Stage configuration is an essential part of MOSIP's functionality, enabling seamless communication with partners and ensuring the secure exchange of information post-UIN generation. + +Note: Ensure that configured IDs are logically unique and consistent across future configurations. \ No newline at end of file