diff --git a/registration-processor/core-processor/registration-processor-biometric-extraction-stage/src/main/java/io/mosip/registration/processor/stages/biometric/extraction/stage/BiometricExtractionStage.java b/registration-processor/core-processor/registration-processor-biometric-extraction-stage/src/main/java/io/mosip/registration/processor/stages/biometric/extraction/stage/BiometricExtractionStage.java index bd355ca1600..893abfcee5a 100644 --- a/registration-processor/core-processor/registration-processor-biometric-extraction-stage/src/main/java/io/mosip/registration/processor/stages/biometric/extraction/stage/BiometricExtractionStage.java +++ b/registration-processor/core-processor/registration-processor-biometric-extraction-stage/src/main/java/io/mosip/registration/processor/stages/biometric/extraction/stage/BiometricExtractionStage.java @@ -4,8 +4,6 @@ import java.util.ArrayList; import java.util.List; -import javax.ws.rs.core.MediaType; - import org.apache.commons.lang3.exception.ExceptionUtils; import org.json.JSONArray; import org.json.JSONException; @@ -52,6 +50,7 @@ import io.mosip.registration.processor.core.util.RegistrationExceptionMapperUtil; import io.mosip.registration.processor.packet.manager.dto.IdResponseDTO; import io.mosip.registration.processor.packet.manager.exception.IdrepoDraftException; +import io.mosip.registration.processor.packet.manager.exception.IdrepoDraftReprocessableException; import io.mosip.registration.processor.packet.manager.idreposervice.IdrepoDraftService; import io.mosip.registration.processor.rest.client.audit.builder.AuditLogRequestBuilder; import io.mosip.registration.processor.status.code.RegistrationStatusCode; @@ -76,6 +75,7 @@ public class BiometricExtractionStage extends MosipVerticleAPIManager{ /** stage properties prefix */ private static final String STAGE_PROPERTY_PREFIX = "mosip.regproc.biometric.extraction."; private static final String USER = "MOSIP_SYSTEM"; + private static final String ID_REPO_KEY_MANAGER_ERROR = "IDR-IDS-003"; /** The mosip event bus. */ MosipEventBus mosipEventBus = null; @@ -267,14 +267,31 @@ public MessageDTO process(MessageDTO object) { RegistrationStatusCode.FAILED.toString() + e.getMessage() + ExceptionUtils.getStackTrace(e)); registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.name()); registrationStatusDto.setStatusComment( - trimExceptionMessage.trimExceptionMessage(StatusUtil.IDREPO_DRAFT_EXCEPTION.getMessage() + e.getMessage())); - registrationStatusDto.setSubStatusCode(StatusUtil.IDREPO_DRAFT_EXCEPTION.getCode()); + trimExceptionMessage.trimExceptionMessage( + StatusUtil.BIOMETRIC_EXTRACTION_IDREPO_DRAFT_EXCEPTION.getMessage() + e.getMessage())); + registrationStatusDto.setSubStatusCode(StatusUtil.BIOMETRIC_EXTRACTION_IDREPO_DRAFT_EXCEPTION.getCode()); registrationStatusDto.setLatestTransactionStatusCode( registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.IDREPO_DRAFT_EXCEPTION)); description.setMessage(PlatformErrorMessages.IDREPO_DRAFT_EXCEPTION.getMessage()); description.setCode(PlatformErrorMessages.IDREPO_DRAFT_EXCEPTION.getCode()); object.setInternalError(Boolean.TRUE); object.setRid(registrationStatusDto.getRegistrationId()); + } catch (IdrepoDraftReprocessableException e) { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + registrationId, + RegistrationStatusCode.PROCESSING.toString() + e.getMessage() + ExceptionUtils.getStackTrace(e)); + registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.name()); + registrationStatusDto.setStatusComment(trimExceptionMessage.trimExceptionMessage( + StatusUtil.BIOMETRIC_EXTRACTION_IDREPO_DRAFT_REPROCESSABLE_EXCEPTION.getMessage() + + e.getMessage())); + registrationStatusDto + .setSubStatusCode(StatusUtil.BIOMETRIC_EXTRACTION_IDREPO_DRAFT_REPROCESSABLE_EXCEPTION.getCode()); + registrationStatusDto.setLatestTransactionStatusCode(registrationStatusMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.IDREPO_DRAFT_REPROCESSABLE_EXCEPTION)); + description.setMessage(PlatformErrorMessages.IDREPO_DRAFT_EXCEPTION.getMessage()); + description.setCode(PlatformErrorMessages.IDREPO_DRAFT_EXCEPTION.getCode()); + object.setInternalError(Boolean.TRUE); + object.setRid(registrationStatusDto.getRegistrationId()); }catch (Exception ex) { registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.name()); registrationStatusDto.setStatusComment( @@ -323,13 +340,17 @@ public MessageDTO process(MessageDTO object) { /** * add biometric extractions to id repo + * * @param dto * @param registrationId * @throws ApisResourceAccessException - * @throws RegistrationProcessorCheckedException + * @throws IdrepoDraftReprocessableException + * @throws IdrepoDraftException + * */ private IdResponseDTO addBiometricExtractiontoIdRepository(ExtractorDto dto, - String registrationId) throws ApisResourceAccessException, RegistrationProcessorCheckedException { + String registrationId) + throws ApisResourceAccessException, IdrepoDraftReprocessableException, IdrepoDraftException { String extractionFormat = ""; if(dto.getBiometric().equals("iris")) { extractionFormat="irisExtractionFormat"; @@ -340,10 +361,15 @@ private IdResponseDTO addBiometricExtractiontoIdRepository(ExtractorDto dto, } List segments=List.of(registrationId); IdResponseDTO response= (IdResponseDTO) registrationProcessorRestClientService.putApi(ApiName.IDREPOEXTRACTBIOMETRICS, segments, extractionFormat, dto.getAttributeName(), null, IdResponseDTO.class, null); + if (response.getErrors() != null && !response.getErrors().isEmpty()) { - regProcLogger.error("Error occured while updating draft for id : " + registrationId, response.getErrors().iterator().next().toString()); - throw new RegistrationProcessorCheckedException(response.getErrors().iterator().next().getErrorCode(), - response.getErrors().iterator().next().getMessage()); + ErrorDTO error = response.getErrors().get(0); + regProcLogger.error("Error occured while updating draft for id : " + registrationId, error.toString()); + if (response.getErrors().get(0).getErrorCode().equalsIgnoreCase(ID_REPO_KEY_MANAGER_ERROR)) { + throw new IdrepoDraftReprocessableException(error.getErrorCode(), error.getMessage()); + } else { + throw new IdrepoDraftException(error.getErrorCode(), error.getMessage()); + } } return response; } diff --git a/registration-processor/core-processor/registration-processor-biometric-extraction-stage/src/test/java/io/mosip/registration/processor/stages/biometric/extraction/stages/test/BiometricExtractionStageTest.java b/registration-processor/core-processor/registration-processor-biometric-extraction-stage/src/test/java/io/mosip/registration/processor/stages/biometric/extraction/stages/test/BiometricExtractionStageTest.java index c0d91296e82..a39a44be7b5 100644 --- a/registration-processor/core-processor/registration-processor-biometric-extraction-stage/src/test/java/io/mosip/registration/processor/stages/biometric/extraction/stages/test/BiometricExtractionStageTest.java +++ b/registration-processor/core-processor/registration-processor-biometric-extraction-stage/src/test/java/io/mosip/registration/processor/stages/biometric/extraction/stages/test/BiometricExtractionStageTest.java @@ -10,6 +10,7 @@ import java.util.List; import org.apache.commons.io.IOUtils; +import org.assertj.core.util.Lists; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -35,6 +36,8 @@ import io.mosip.registration.processor.core.code.EventId; import io.mosip.registration.processor.core.code.EventName; import io.mosip.registration.processor.core.code.EventType; +import io.mosip.registration.processor.core.code.RegistrationExceptionTypeCode; +import io.mosip.registration.processor.core.common.rest.dto.ErrorDTO; import io.mosip.registration.processor.core.constant.RegistrationType; import io.mosip.registration.processor.core.exception.ApisResourceAccessException; import io.mosip.registration.processor.core.http.ResponseWrapper; @@ -329,4 +332,26 @@ public void testBiometricExtractionDraftException() throws Exception { public void testDeployVerticle() { biometricExtractionStage.deployVerticle(); } + + @Test + public void testIdrepoDraftReprocessableException() throws Exception { + MessageDTO messageDTO = new MessageDTO(); + messageDTO.setRid("27847657360002520181210094052"); + messageDTO.setReg_type(RegistrationType.NEW.name()); + messageDTO.setWorkflowInstanceId("123er"); + messageDTO.setIteration(1); + when(registrationStatusMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.IDREPO_DRAFT_REPROCESSABLE_EXCEPTION)) + .thenReturn("REPROCESS"); + ErrorDTO errorDTO = new ErrorDTO(); + errorDTO.setMessage("Failed to either encrypt/decrypt message using Kernel Crypto Manager"); + errorDTO.setErrorCode("IDR-IDS-003"); + IdResponseDTO idResponseDTO1 = new IdResponseDTO(); + idResponseDTO1.setErrors(Lists.newArrayList(errorDTO)); + when(registrationProcessorRestClientService.putApi(any(), any(), anyString(), anyString(), any(), any(), any())) + .thenReturn(idResponseDTO1); + MessageDTO result = biometricExtractionStage.process(messageDTO); + assertTrue(result.getInternalError()); + assertTrue(result.getIsValid()); + } } diff --git a/registration-processor/core-processor/registration-processor-finalization-stage/src/main/java/io/mosip/registration/processor/stages/finalization/stage/FinalizationStage.java b/registration-processor/core-processor/registration-processor-finalization-stage/src/main/java/io/mosip/registration/processor/stages/finalization/stage/FinalizationStage.java index 38c81750354..c4236fde362 100644 --- a/registration-processor/core-processor/registration-processor-finalization-stage/src/main/java/io/mosip/registration/processor/stages/finalization/stage/FinalizationStage.java +++ b/registration-processor/core-processor/registration-processor-finalization-stage/src/main/java/io/mosip/registration/processor/stages/finalization/stage/FinalizationStage.java @@ -32,6 +32,7 @@ import io.mosip.registration.processor.core.util.RegistrationExceptionMapperUtil; import io.mosip.registration.processor.packet.manager.dto.IdResponseDTO; import io.mosip.registration.processor.packet.manager.exception.IdrepoDraftException; +import io.mosip.registration.processor.packet.manager.exception.IdrepoDraftReprocessableException; import io.mosip.registration.processor.packet.manager.idreposervice.IdrepoDraftService; import io.mosip.registration.processor.rest.client.audit.builder.AuditLogRequestBuilder; import io.mosip.registration.processor.status.code.RegistrationStatusCode; @@ -199,14 +200,32 @@ public MessageDTO process(MessageDTO object) { RegistrationStatusCode.FAILED.toString() + e.getMessage() + ExceptionUtils.getStackTrace(e)); registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.name()); registrationStatusDto.setStatusComment( - trimExceptionMessage.trimExceptionMessage(StatusUtil.IDREPO_DRAFT_EXCEPTION.getMessage() + e.getMessage())); - registrationStatusDto.setSubStatusCode(StatusUtil.IDREPO_DRAFT_EXCEPTION.getCode()); + trimExceptionMessage.trimExceptionMessage( + StatusUtil.FINALIZATION_IDREPO_DRAFT_EXCEPTION.getMessage() + e.getMessage())); + registrationStatusDto.setSubStatusCode(StatusUtil.FINALIZATION_IDREPO_DRAFT_EXCEPTION.getCode()); registrationStatusDto.setLatestTransactionStatusCode( registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.IDREPO_DRAFT_EXCEPTION)); description.setMessage(PlatformErrorMessages.IDREPO_DRAFT_EXCEPTION.getMessage()); description.setCode(PlatformErrorMessages.IDREPO_DRAFT_EXCEPTION.getCode()); object.setInternalError(Boolean.TRUE); object.setRid(registrationStatusDto.getRegistrationId()); + } catch (IdrepoDraftReprocessableException e) { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + registrationId, + RegistrationStatusCode.PROCESSING.toString() + e.getMessage() + ExceptionUtils.getStackTrace(e)); + registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.name()); + registrationStatusDto.setStatusComment(trimExceptionMessage + .trimExceptionMessage( + StatusUtil.FINALIZATION_IDREPO_DRAFT_REPROCESSABLE_EXCEPTION.getMessage() + + e.getMessage())); + registrationStatusDto + .setSubStatusCode(StatusUtil.FINALIZATION_IDREPO_DRAFT_REPROCESSABLE_EXCEPTION.getCode()); + registrationStatusDto.setLatestTransactionStatusCode(registrationStatusMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.IDREPO_DRAFT_REPROCESSABLE_EXCEPTION)); + description.setMessage(PlatformErrorMessages.IDREPO_DRAFT_EXCEPTION.getMessage()); + description.setCode(PlatformErrorMessages.IDREPO_DRAFT_EXCEPTION.getCode()); + object.setInternalError(Boolean.TRUE); + object.setRid(registrationStatusDto.getRegistrationId()); }catch (Exception ex) { registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.name()); registrationStatusDto.setStatusComment( diff --git a/registration-processor/core-processor/registration-processor-finalization-stage/src/test/java/io/mosip/registration/processor/stages/finalization/stage/tests/FinalizationStageTest.java b/registration-processor/core-processor/registration-processor-finalization-stage/src/test/java/io/mosip/registration/processor/stages/finalization/stage/tests/FinalizationStageTest.java index 5def776c4cd..f559b8ed629 100644 --- a/registration-processor/core-processor/registration-processor-finalization-stage/src/test/java/io/mosip/registration/processor/stages/finalization/stage/tests/FinalizationStageTest.java +++ b/registration-processor/core-processor/registration-processor-finalization-stage/src/test/java/io/mosip/registration/processor/stages/finalization/stage/tests/FinalizationStageTest.java @@ -29,6 +29,7 @@ import io.mosip.registration.processor.core.code.EventId; import io.mosip.registration.processor.core.code.EventName; import io.mosip.registration.processor.core.code.EventType; +import io.mosip.registration.processor.core.code.RegistrationExceptionTypeCode; import io.mosip.registration.processor.core.constant.RegistrationType; import io.mosip.registration.processor.core.exception.ApisResourceAccessException; import io.mosip.registration.processor.core.http.ResponseWrapper; @@ -37,6 +38,7 @@ import io.mosip.registration.processor.packet.manager.dto.IdResponseDTO; import io.mosip.registration.processor.packet.manager.dto.ResponseDTO; import io.mosip.registration.processor.packet.manager.exception.IdrepoDraftException; +import io.mosip.registration.processor.packet.manager.exception.IdrepoDraftReprocessableException; import io.mosip.registration.processor.packet.manager.idreposervice.IdrepoDraftService; import io.mosip.registration.processor.rest.client.audit.builder.AuditLogRequestBuilder; import io.mosip.registration.processor.rest.client.audit.dto.AuditResponseDto; @@ -247,4 +249,20 @@ public void testBiometricExtractionUnknownException() throws Exception { public void testDeployVerticle() { finalizationStage.deployVerticle(); } + + @Test + public void testIdrepoDraftReprocessableException() throws Exception { + MessageDTO messageDTO = new MessageDTO(); + messageDTO.setRid("27847657360002520181210094052"); + messageDTO.setReg_type(RegistrationType.NEW.name()); + messageDTO.setWorkflowInstanceId("123er"); + messageDTO.setIteration(1); + when(registrationStatusMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.IDREPO_DRAFT_REPROCESSABLE_EXCEPTION)) + .thenReturn("REPROCESS"); + when(idrepoDraftService.idrepoPublishDraft(anyString())).thenThrow(IdrepoDraftReprocessableException.class); + MessageDTO result = finalizationStage.process(messageDTO); + assertTrue(result.getInternalError()); + assertTrue(result.getIsValid()); + } } diff --git a/registration-processor/core-processor/registration-processor-uin-generator-stage/src/main/java/io/mosip/registration/processor/stages/uingenerator/stage/UinGeneratorStage.java b/registration-processor/core-processor/registration-processor-uin-generator-stage/src/main/java/io/mosip/registration/processor/stages/uingenerator/stage/UinGeneratorStage.java index e0fa2df1f34..5d5e8ac4421 100644 --- a/registration-processor/core-processor/registration-processor-uin-generator-stage/src/main/java/io/mosip/registration/processor/stages/uingenerator/stage/UinGeneratorStage.java +++ b/registration-processor/core-processor/registration-processor-uin-generator-stage/src/main/java/io/mosip/registration/processor/stages/uingenerator/stage/UinGeneratorStage.java @@ -1,1113 +1,1116 @@ -package io.mosip.registration.processor.stages.uingenerator.stage; - -import java.io.IOException; -import java.time.LocalDateTime; -import java.time.format.DateTimeFormatter; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -import io.mosip.registration.processor.packet.manager.exception.IdrepoDraftException; -import io.mosip.registration.processor.packet.manager.idreposervice.IdrepoDraftService; -import org.apache.commons.lang3.exception.ExceptionUtils; -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONTokener; -import org.json.simple.JSONObject; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.cloud.context.config.annotation.RefreshScope; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.core.env.Environment; -import org.springframework.stereotype.Service; -import org.springframework.web.client.HttpClientErrorException; -import org.springframework.web.client.HttpServerErrorException; - -import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.databind.JsonMappingException; -import com.fasterxml.jackson.databind.ObjectMapper; - -import io.mosip.kernel.biometrics.entities.BiometricRecord; -import io.mosip.kernel.biometrics.spi.CbeffUtil; -import io.mosip.kernel.core.http.RequestWrapper; -import io.mosip.kernel.core.logger.spi.Logger; -import io.mosip.kernel.core.util.CryptoUtil; -import io.mosip.kernel.core.util.DateUtils; -import io.mosip.kernel.core.util.StringUtils; -import io.mosip.registration.processor.core.abstractverticle.MessageBusAddress; -import io.mosip.registration.processor.core.abstractverticle.MessageDTO; -import io.mosip.registration.processor.core.abstractverticle.MosipEventBus; -import io.mosip.registration.processor.core.abstractverticle.MosipRouter; -import io.mosip.registration.processor.core.abstractverticle.MosipVerticleAPIManager; -import io.mosip.registration.processor.core.code.ApiName; -import io.mosip.registration.processor.core.code.ModuleName; -import io.mosip.registration.processor.core.code.RegistrationExceptionTypeCode; -import io.mosip.registration.processor.core.code.RegistrationTransactionStatusCode; -import io.mosip.registration.processor.core.code.RegistrationTransactionTypeCode; -import io.mosip.registration.processor.core.common.rest.dto.ErrorDTO; -import io.mosip.registration.processor.core.constant.EventId; -import io.mosip.registration.processor.core.constant.EventName; -import io.mosip.registration.processor.core.constant.EventType; -import io.mosip.registration.processor.core.constant.LoggerFileConstant; -import io.mosip.registration.processor.core.constant.MappingJsonConstants; -import io.mosip.registration.processor.core.constant.ProviderStageName; -import io.mosip.registration.processor.core.exception.ApisResourceAccessException; -import io.mosip.registration.processor.core.exception.PacketManagerException; -import io.mosip.registration.processor.core.exception.RegistrationProcessorCheckedException; -import io.mosip.registration.processor.core.exception.util.PlatformErrorMessages; -import io.mosip.registration.processor.core.exception.util.PlatformSuccessMessages; -import io.mosip.registration.processor.core.http.ResponseWrapper; -import io.mosip.registration.processor.core.idrepo.dto.Documents; -import io.mosip.registration.processor.core.logger.LogDescription; -import io.mosip.registration.processor.core.logger.RegProcessorLogger; -import io.mosip.registration.processor.core.spi.restclient.RegistrationProcessorRestClientService; -import io.mosip.registration.processor.core.status.util.StatusUtil; -import io.mosip.registration.processor.core.status.util.TrimExceptionMessage; -import io.mosip.registration.processor.core.util.JsonUtil; -import io.mosip.registration.processor.core.util.RegistrationExceptionMapperUtil; -import io.mosip.registration.processor.packet.manager.idreposervice.IdRepoService; -import io.mosip.registration.processor.packet.storage.dto.Document; -import io.mosip.registration.processor.packet.storage.entity.RegLostUinDetEntity; -import io.mosip.registration.processor.packet.storage.repository.BasePacketRepository; -import io.mosip.registration.processor.packet.storage.utils.ABISHandlerUtil; -import io.mosip.registration.processor.packet.storage.utils.IdSchemaUtil; -import io.mosip.registration.processor.packet.storage.utils.PriorityBasedPacketManagerService; -import io.mosip.registration.processor.packet.storage.utils.Utilities; -import io.mosip.registration.processor.rest.client.audit.builder.AuditLogRequestBuilder; -import io.mosip.registration.processor.stages.uingenerator.constants.UINConstants; -import io.mosip.registration.processor.stages.uingenerator.dto.UinGenResponseDto; -import io.mosip.registration.processor.stages.uingenerator.dto.VidRequestDto; -import io.mosip.registration.processor.stages.uingenerator.dto.VidResponseDto; -import io.mosip.registration.processor.stages.uingenerator.exception.VidCreationException; -import io.mosip.registration.processor.packet.manager.dto.IdRequestDto; -import io.mosip.registration.processor.packet.manager.dto.IdResponseDTO; -import io.mosip.registration.processor.packet.manager.dto.RequestDto; -import io.mosip.registration.processor.stages.uingenerator.util.UinStatusMessage; -import io.mosip.registration.processor.status.code.RegistrationStatusCode; -import io.mosip.registration.processor.status.code.RegistrationType; -import io.mosip.registration.processor.status.dto.InternalRegistrationStatusDto; -import io.mosip.registration.processor.status.dto.RegistrationStatusDto; -import io.mosip.registration.processor.status.service.RegistrationStatusService; - -/** - * The Class UinGeneratorStage. - * - * @author Ranjitha Siddegowda - * @author Rishabh Keshari - */ -@RefreshScope -@Service -@Configuration -@ComponentScan(basePackages = { "${mosip.auth.adapter.impl.basepackage}", - "io.mosip.registration.processor.core.config", - "io.mosip.registration.processor.stages.uingenerator.config", - "io.mosip.registration.processor.status.config", "io.mosip.registration.processor.rest.client.config", - "io.mosip.registration.processor.packet.storage.config", - "io.mosip.registration.processor.stages.config", - "io.mosip.kernel.packetmanager.config", - "io.mosip.registration.processor.packet.manager.config", - "io.mosip.registration.processor.core.kernel.beans"}) -public class UinGeneratorStage extends MosipVerticleAPIManager { - - /** The reg proc logger. */ - private static Logger regProcLogger = RegProcessorLogger.getLogger(UinGeneratorStage.class); - private static final String RECORD_ALREADY_EXISTS_ERROR = "IDR-IDC-012"; - private static final String STAGE_PROPERTY_PREFIX = "mosip.regproc.uin.generator."; - private static final String UIN = "UIN"; - private static final String IDREPO_STATUS = "DRAFTED"; - - @Autowired - private Environment env; - - @Autowired - private IdRepoService idRepoService; - - /** The mosip event bus. */ - MosipEventBus mosipEventBus = null; - - @Value("${registration.processor.id.repo.vidType}") - private String vidType; - - @Value("${mosip.commons.packet.manager.schema.validator.convertIdSchemaToDouble:true}") - private boolean convertIdschemaToDouble; - - /** The cluster manager url. */ - @Value("${vertx.cluster.configuration}") - private String clusterManagerUrl; - - /** The id repo create. */ - @Value("${registration.processor.id.repo.create}") - private String idRepoCreate; - - /** The id repo update. */ - @Value("${registration.processor.id.repo.update}") - private String idRepoUpdate; - - /** worker pool size. */ - @Value("${worker.pool.size}") - private Integer workerPoolSize; - - /** After this time intervel, message should be considered as expired (In seconds). */ - @Value("${mosip.regproc.uin.generator.message.expiry-time-limit}") - private Long messageExpiryTimeLimit; - - @Value("${uingenerator.lost.packet.allowed.update.fields:null}") - private String updateInfo; - - /** The core audit request builder. */ - @Autowired - private AuditLogRequestBuilder auditLogRequestBuilder; - - /** Mosip router for APIs */ - @Autowired - private MosipRouter router; - - @Autowired - private ObjectMapper mapper; - - @Autowired - private IdrepoDraftService idrepoDraftService; - - /** The registration processor rest client service. */ - @Autowired - private RegistrationProcessorRestClientService registrationProcessorRestClientService; - - /** The demographic dedupe repository. */ - @Autowired - private BasePacketRepository regLostUinDetEntity; - - /** The registration status service. */ - @Autowired - private RegistrationStatusService registrationStatusService; - - /** The utility. */ - @Autowired - private Utilities utility; - - @Autowired - private CbeffUtil cbeffutil; - - @Autowired - private RegistrationExceptionMapperUtil registrationStatusMapperUtil; - - @Autowired - private ABISHandlerUtil aBISHandlerUtil; - - @Autowired - private PriorityBasedPacketManagerService packetManagerService; - - @Autowired - private IdSchemaUtil idSchemaUtil; - - @Autowired - private ObjectMapper objectMapper; - - private TrimExceptionMessage trimExceptionMessage = new TrimExceptionMessage(); - - /* - * (non-Javadoc) - * - * @see - * io.mosip.registration.processor.core.spi.eventbus.EventBusManager#process( - * java.lang.Object) - */ - @SuppressWarnings("unchecked") - @Override - public MessageDTO process(MessageDTO object) { - boolean isTransactionSuccessful = Boolean.FALSE; - object.setMessageBusAddress(MessageBusAddress.UIN_GENERATION_BUS_IN); - object.setInternalError(Boolean.FALSE); - object.setIsValid(Boolean.TRUE); - LogDescription description = new LogDescription(); - String registrationId = object.getRid(); - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - registrationId, "UinGeneratorStage::process()::entry"); - UinGenResponseDto uinResponseDto = null; - - InternalRegistrationStatusDto registrationStatusDto = registrationStatusService.getRegistrationStatus( - registrationId, object.getReg_type(), object.getIteration(), object.getWorkflowInstanceId()); - try { - registrationStatusDto - .setLatestTransactionTypeCode(RegistrationTransactionTypeCode.UIN_GENERATOR.toString()); - registrationStatusDto.setRegistrationStageName(getStageName()); - - if ((RegistrationType.LOST.toString()).equalsIgnoreCase(object.getReg_type())) { - String lostPacketRegId = object.getRid(); - String matchedRegId = regLostUinDetEntity.getLostUinMatchedRegIdByWorkflowId(object.getWorkflowInstanceId()); - - if (matchedRegId != null) { - regProcLogger.info("Match for lostPacketRegId"+lostPacketRegId +"is "+matchedRegId); - lostAndUpdateUin(lostPacketRegId, matchedRegId, registrationStatusDto.getRegistrationType(), object, description); - } - - } else { - - IdResponseDTO idResponseDTO = new IdResponseDTO(); - String schemaVersion = packetManagerService.getFieldByMappingJsonKey(registrationId, MappingJsonConstants.IDSCHEMA_VERSION, registrationStatusDto.getRegistrationType(), ProviderStageName.UIN_GENERATOR); - - Map fieldMap = packetManagerService.getFields(registrationId, - idSchemaUtil.getDefaultFields(Double.valueOf(schemaVersion)), registrationStatusDto.getRegistrationType(), ProviderStageName.UIN_GENERATOR); - String uinField = fieldMap.get(utility.getMappingJsonValue(MappingJsonConstants.UIN, MappingJsonConstants.IDENTITY)); - - JSONObject demographicIdentity = new JSONObject(); - demographicIdentity.put(MappingJsonConstants.IDSCHEMA_VERSION, convertIdschemaToDouble ? Double.valueOf(schemaVersion) : schemaVersion); - - loadDemographicIdentity(fieldMap, demographicIdentity); - - if (StringUtils.isEmpty(uinField) || uinField.equalsIgnoreCase("null") ) { - - idResponseDTO = sendIdRepoWithUin(registrationId, registrationStatusDto.getRegistrationType(), demographicIdentity, - uinField); - - boolean isUinAlreadyPresent = isUinAlreadyPresent(idResponseDTO, registrationId); - - if (isIdResponseNotNull(idResponseDTO) || isUinAlreadyPresent) { - registrationStatusDto.setStatusComment(StatusUtil.UIN_GENERATED_SUCCESS.getMessage()); - registrationStatusDto.setSubStatusCode(StatusUtil.UIN_GENERATED_SUCCESS.getCode()); - isTransactionSuccessful = true; - registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); - description.setMessage(PlatformSuccessMessages.RPR_UIN_GENERATOR_STAGE_SUCCESS.getMessage()); - description.setCode(PlatformSuccessMessages.RPR_UIN_GENERATOR_STAGE_SUCCESS.getCode()); - description.setTransactionStatusCode(RegistrationTransactionStatusCode.SUCCESS.toString()); - - } else { - List errors = idResponseDTO != null ? idResponseDTO.getErrors() : null; - String statusComment = errors != null ? errors.get(0).getMessage() - : UINConstants.NULL_IDREPO_RESPONSE; - int unknownErrorCount=0; - for(ErrorDTO dto:errors) { - if(dto.getErrorCode().equalsIgnoreCase("IDR-IDC-004")||dto.getErrorCode().equalsIgnoreCase("IDR-IDC-001")) { - unknownErrorCount++; - } - } - if(unknownErrorCount>0) { - registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); - registrationStatusDto.setLatestTransactionStatusCode(registrationStatusMapperUtil - .getStatusCode(RegistrationExceptionTypeCode.PACKET_UIN_GENERATION_REPROCESS)); - description.setTransactionStatusCode(registrationStatusMapperUtil - .getStatusCode(RegistrationExceptionTypeCode.PACKET_UIN_GENERATION_REPROCESS)); - } - else { - registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.toString()); - registrationStatusDto.setLatestTransactionStatusCode(registrationStatusMapperUtil - .getStatusCode(RegistrationExceptionTypeCode.PACKET_UIN_GENERATION_FAILED)); - description.setTransactionStatusCode(registrationStatusMapperUtil - .getStatusCode(RegistrationExceptionTypeCode.PACKET_UIN_GENERATION_FAILED)); - } - registrationStatusDto.setStatusComment(trimExceptionMessage - .trimExceptionMessage(StatusUtil.UIN_GENERATION_FAILED.getMessage() + statusComment)); - object.setInternalError(Boolean.TRUE); - isTransactionSuccessful = false; - description.setMessage(PlatformErrorMessages.RPR_UGS_UIN_UPDATE_FAILURE.getMessage()); - description.setCode(PlatformErrorMessages.RPR_UGS_UIN_UPDATE_FAILURE.getCode()); - description.setSubStatusCode(StatusUtil.UIN_GENERATION_FAILED.getCode()); - String idres = idResponseDTO != null ? idResponseDTO.toString() - : UINConstants.NULL_IDREPO_RESPONSE; - - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), - LoggerFileConstant.REGISTRATIONID.toString(), registrationId, - statusComment + " : " + idres); - object.setIsValid(Boolean.FALSE); - } - - } else { - if ((RegistrationType.ACTIVATED.toString()).equalsIgnoreCase(object.getReg_type())) { - isTransactionSuccessful = reActivateUin(idResponseDTO, registrationId, uinField, object, - demographicIdentity, description); - } else if ((RegistrationType.DEACTIVATED.toString()) - .equalsIgnoreCase(object.getReg_type())) { - idResponseDTO = deactivateUin(registrationId, uinField, object, demographicIdentity, - description); - } else if (RegistrationType.UPDATE.toString().equalsIgnoreCase(object.getReg_type()) - || (RegistrationType.RES_UPDATE.toString() - .equalsIgnoreCase(object.getReg_type()))) { - isTransactionSuccessful = uinUpdate(registrationId, registrationStatusDto.getRegistrationType(), uinField, object, demographicIdentity, - description); - } - } - - } - regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - registrationId, description.getMessage()); - registrationStatusDto.setUpdatedBy(UINConstants.USER); - - } catch (io.mosip.kernel.core.util.exception.JsonProcessingException e) { - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - registrationId, - RegistrationStatusCode.FAILED.toString() + e.getMessage() + ExceptionUtils.getStackTrace(e)); - registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.toString()); - registrationStatusDto.setStatusComment( - trimExceptionMessage.trimExceptionMessage(StatusUtil.JSON_PARSING_EXCEPTION.getMessage() + e.getMessage())); - registrationStatusDto.setSubStatusCode(StatusUtil.JSON_PARSING_EXCEPTION.getCode()); - registrationStatusDto.setLatestTransactionStatusCode( - registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.JSON_PROCESSING_EXCEPTION)); - isTransactionSuccessful = false; - description.setMessage(PlatformErrorMessages.RPR_SYS_JSON_PARSING_EXCEPTION.getMessage()); - description.setCode(PlatformErrorMessages.RPR_SYS_JSON_PARSING_EXCEPTION.getCode()); - object.setInternalError(Boolean.TRUE); - object.setRid(registrationStatusDto.getRegistrationId()); - } catch (PacketManagerException e) { - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - registrationId, - RegistrationStatusCode.PROCESSING.toString() + e.getMessage() + ExceptionUtils.getStackTrace(e)); - registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.name()); - registrationStatusDto.setStatusComment( - trimExceptionMessage.trimExceptionMessage(StatusUtil.PACKET_MANAGER_EXCEPTION.getMessage() + e.getMessage())); - registrationStatusDto.setSubStatusCode(StatusUtil.PACKET_MANAGER_EXCEPTION.getCode()); - registrationStatusDto.setLatestTransactionStatusCode( - registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.PACKET_MANAGER_EXCEPTION)); - description.setMessage(PlatformErrorMessages.PACKET_MANAGER_EXCEPTION.getMessage()); - description.setCode(PlatformErrorMessages.PACKET_MANAGER_EXCEPTION.getCode()); - object.setInternalError(Boolean.TRUE); - object.setRid(registrationStatusDto.getRegistrationId()); - } catch (ApisResourceAccessException ex) { - registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.name()); - registrationStatusDto.setStatusComment(trimExceptionMessage - .trimExceptionMessage(StatusUtil.API_RESOUCE_ACCESS_FAILED.getMessage() + ex.getMessage())); - registrationStatusDto.setSubStatusCode(StatusUtil.API_RESOUCE_ACCESS_FAILED.getCode()); - registrationStatusDto.setLatestTransactionStatusCode(registrationStatusMapperUtil - .getStatusCode(RegistrationExceptionTypeCode.APIS_RESOURCE_ACCESS_EXCEPTION)); - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - registrationId, - RegistrationStatusCode.PROCESSING.toString() + ex.getMessage() + ExceptionUtils.getStackTrace(ex)); - object.setInternalError(Boolean.TRUE); - description.setMessage(trimExceptionMessage - .trimExceptionMessage(StatusUtil.API_RESOUCE_ACCESS_FAILED.getMessage() + ex.getMessage())); - description.setCode(PlatformErrorMessages.RPR_UGS_API_RESOURCE_EXCEPTION.getCode()); - - } catch (IOException e) { - registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.name()); - registrationStatusDto.setStatusComment( - trimExceptionMessage.trimExceptionMessage(StatusUtil.IO_EXCEPTION.getMessage() + e.getMessage())); - registrationStatusDto.setSubStatusCode(StatusUtil.IO_EXCEPTION.getCode()); - registrationStatusDto.setLatestTransactionStatusCode( - registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.PACKET_UIN_GENERATION_REPROCESS)); - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - registrationId, - PlatformErrorMessages.RPR_SYS_IO_EXCEPTION.getMessage() + ExceptionUtils.getStackTrace(e)); - object.setInternalError(Boolean.TRUE); - description.setMessage(PlatformErrorMessages.RPR_SYS_IO_EXCEPTION.getMessage()); - description.setCode(PlatformErrorMessages.RPR_SYS_IO_EXCEPTION.getCode()); - } catch (IdrepoDraftException e) { - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - registrationId, - RegistrationStatusCode.PROCESSING.toString() + e.getMessage() + ExceptionUtils.getStackTrace(e)); - registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.name()); - registrationStatusDto.setStatusComment( - trimExceptionMessage.trimExceptionMessage(StatusUtil.IDREPO_DRAFT_EXCEPTION.getMessage() + e.getMessage())); - registrationStatusDto.setSubStatusCode(StatusUtil.IDREPO_DRAFT_EXCEPTION.getCode()); - registrationStatusDto.setLatestTransactionStatusCode( - registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.IDREPO_DRAFT_EXCEPTION)); - description.setMessage(PlatformErrorMessages.IDREPO_DRAFT_EXCEPTION.getMessage()); - description.setCode(PlatformErrorMessages.IDREPO_DRAFT_EXCEPTION.getCode()); - object.setInternalError(Boolean.TRUE); - object.setRid(registrationStatusDto.getRegistrationId()); - } catch (Exception ex) { - registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.name()); - registrationStatusDto.setStatusComment( - trimExceptionMessage.trimExceptionMessage(StatusUtil.UNKNOWN_EXCEPTION_OCCURED.getMessage())); - registrationStatusDto.setSubStatusCode(StatusUtil.UNKNOWN_EXCEPTION_OCCURED.getCode()); - registrationStatusDto.setLatestTransactionStatusCode( - registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.PACKET_UIN_GENERATION_REPROCESS)); - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - registrationId, - RegistrationStatusCode.PROCESSING.toString() + ex.getMessage() + ExceptionUtils.getStackTrace(ex)); - object.setInternalError(Boolean.TRUE); - description.setMessage(PlatformErrorMessages.RPR_BDD_UNKNOWN_EXCEPTION.getMessage()); - description.setCode(PlatformErrorMessages.RPR_BDD_UNKNOWN_EXCEPTION.getCode()); - } finally { - if (description.getStatusComment() != null) - registrationStatusDto.setStatusComment(description.getStatusComment()); - if (description.getStatusCode() != null) - registrationStatusDto.setStatusCode(description.getStatusCode()); - if (description.getSubStatusCode() != null) - registrationStatusDto.setSubStatusCode(description.getSubStatusCode()); - if (description.getTransactionStatusCode() != null) - registrationStatusDto.setLatestTransactionStatusCode(description.getTransactionStatusCode()); - - if (object.getInternalError()) { - updateErrorFlags(registrationStatusDto, object); - } - String moduleId = isTransactionSuccessful - ? PlatformSuccessMessages.RPR_UIN_GENERATOR_STAGE_SUCCESS.getCode() - : description.getCode(); - String moduleName = ModuleName.UIN_GENERATOR.toString(); - registrationStatusService.updateRegistrationStatus(registrationStatusDto, moduleId, moduleName); - String eventId = isTransactionSuccessful ? EventId.RPR_402.toString() : EventId.RPR_405.toString(); - String eventName = eventId.equalsIgnoreCase(EventId.RPR_402.toString()) ? EventName.UPDATE.toString() - : EventName.EXCEPTION.toString(); - String eventType = eventId.equalsIgnoreCase(EventId.RPR_402.toString()) ? EventType.BUSINESS.toString() - : EventType.SYSTEM.toString(); - - auditLogRequestBuilder.createAuditRequestBuilder(description.getMessage(), eventId, eventName, eventType, - moduleId, moduleName, registrationId); - - } - - return object; - } - - private void loadDemographicIdentity(Map fieldMap, JSONObject demographicIdentity) throws IOException, JSONException { - for (Map.Entry e : fieldMap.entrySet()) { - if (e.getValue() != null) { - String value = e.getValue().toString(); - if (value != null) { - Object json = new JSONTokener(value).nextValue(); - if (json instanceof org.json.JSONObject) { - HashMap hashMap = objectMapper.readValue(value, HashMap.class); - demographicIdentity.putIfAbsent(e.getKey(), hashMap); - } - else if (json instanceof JSONArray) { - List jsonList = new ArrayList<>(); - JSONArray jsonArray = new JSONArray(value); - for (int i = 0; i < jsonArray.length(); i++) { - Object obj = jsonArray.get(i); - HashMap hashMap = objectMapper.readValue(obj.toString(), HashMap.class); - jsonList.add(hashMap); - } - demographicIdentity.putIfAbsent(e.getKey(), jsonList); - } else - demographicIdentity.putIfAbsent(e.getKey(), value); - } else - demographicIdentity.putIfAbsent(e.getKey(), value); - } - } - } - - /** - * Send id repo with uin. - * - * @param id - * the reg id - * @param uin - * the uin - * @throws ApisResourceAccessException - * @throws IOException - * @throws JsonMappingException - * @throws JsonParseException - * @throws VidCreationException - * @throws io.mosip.kernel.core.exception.IOException - * @throws Exception - */ - private IdResponseDTO sendIdRepoWithUin(String id, String process, JSONObject demographicIdentity, String uin) - throws Exception { - - List documentInfo = getAllDocumentsByRegId(id, process, demographicIdentity); - RequestDto requestDto = new RequestDto(); - requestDto.setIdentity(demographicIdentity); - requestDto.setDocuments(documentInfo); - requestDto.setRegistrationId(id); - requestDto.setStatus(RegistrationType.ACTIVATED.toString()); - requestDto.setBiometricReferenceId(uin); - - IdResponseDTO result = null; - IdRequestDto idRequestDTO = new IdRequestDto(); - idRequestDTO.setId(idRepoUpdate); - idRequestDTO.setRequest(requestDto); - idRequestDTO.setRequesttime(DateUtils.getUTCCurrentDateTimeString()); - idRequestDTO.setVersion(UINConstants.idRepoApiVersion); - idRequestDTO.setMetadata(null); - - try { - - result = idrepoDraftService.idrepoUpdateDraft(id, null, idRequestDTO); - - } catch (ApisResourceAccessException e) { - regProcLogger.error("Execption occured updating draft for id " + id, e); - if (e.getCause() instanceof HttpClientErrorException) { - HttpClientErrorException httpClientException = (HttpClientErrorException) e.getCause(); - throw new ApisResourceAccessException(httpClientException.getResponseBodyAsString(), - httpClientException); - } else if (e.getCause() instanceof HttpServerErrorException) { - HttpServerErrorException httpServerException = (HttpServerErrorException) e.getCause(); - throw new ApisResourceAccessException(httpServerException.getResponseBodyAsString(), - httpServerException); - } else { - throw e; - } - - } - return result; - - } - - /** - * Gets the all documents by reg id. - * - * @param regId - * the reg id - * @return the all documents by reg id - * @throws IOException - * @throws io.mosip.kernel.core.exception.IOException - * @throws ApisResourceAccessException - * @throws JsonMappingException - * @throws JsonParseException - */ - private List getAllDocumentsByRegId(String regId, String process, JSONObject demographicIdentity) throws Exception { - List applicantDocuments = new ArrayList<>(); - - JSONObject idJSON = demographicIdentity; - JSONObject docJson = utility.getRegistrationProcessorMappingJson(MappingJsonConstants.DOCUMENT); - JSONObject identityJson = utility.getRegistrationProcessorMappingJson(MappingJsonConstants.IDENTITY); - - String applicantBiometricLabel = JsonUtil.getJSONValue(JsonUtil.getJSONObject(identityJson, MappingJsonConstants.INDIVIDUAL_BIOMETRICS), MappingJsonConstants.VALUE); - - HashMap applicantBiometric = (HashMap) idJSON.get(applicantBiometricLabel); - - - for (Object doc : docJson.values()) { - Map docMap = (LinkedHashMap) doc; - String docValue = docMap.values().iterator().next().toString(); - HashMap docInIdentityJson = (HashMap) idJSON.get(docValue); - if (docInIdentityJson != null) - applicantDocuments - .add(getIdDocumnet(regId, docValue, process)); - } - - if (applicantBiometric != null) { - applicantDocuments.add(getBiometrics(regId, applicantBiometricLabel, process, applicantBiometricLabel)); - } - return applicantDocuments; - } - - private Documents getIdDocumnet(String registrationId, String dockey, String process) - throws IOException, ApisResourceAccessException, PacketManagerException, io.mosip.kernel.core.util.exception.JsonProcessingException { - Documents documentsInfoDto = new Documents(); - - Document document = - packetManagerService.getDocument(registrationId, dockey, process, ProviderStageName.UIN_GENERATOR); - if (document != null) { - documentsInfoDto.setValue(CryptoUtil.encodeToURLSafeBase64(document.getDocument())); - documentsInfoDto.setCategory(document.getValue()); - return documentsInfoDto; - } - return null; - } - - private Documents getBiometrics(String registrationId, String person, String process, String idDocLabel) throws Exception { - BiometricRecord biometricRecord = packetManagerService.getBiometrics(registrationId, person, process, ProviderStageName.UIN_GENERATOR); - byte[] xml = cbeffutil.createXML(biometricRecord.getSegments()); - Documents documentsInfoDto = new Documents(); - documentsInfoDto.setValue(CryptoUtil.encodeToURLSafeBase64(xml)); - documentsInfoDto.setCategory(utility.getMappingJsonValue(idDocLabel, MappingJsonConstants.IDENTITY)); - return documentsInfoDto; - - } - - /** - * Update id repo wit uin. - * - * @param regId the reg id - * @param uin the uin - * @param object the object - * @param description - * @return the id response DTO - * @throws ApisResourceAccessException the apis resource access - * exception - * @throws IOException Signals that an I/O exception - * has occurred. - * @throws RegistrationProcessorCheckedException - * @throws io.mosip.kernel.core.exception.IOException - */ - private boolean uinUpdate(String regId, String process, String uin, MessageDTO object, JSONObject demographicIdentity, LogDescription description) - throws Exception { - IdResponseDTO result; - boolean isTransactionSuccessful = Boolean.FALSE; - List documentInfo = getAllDocumentsByRegId(regId, process, demographicIdentity); - result = idRepoRequestBuilder(regId, uin, RegistrationType.ACTIVATED.toString().toUpperCase(), documentInfo, - demographicIdentity); - if (null!=result && isIdResponseNotNull(result)) { - - if (IDREPO_STATUS.equalsIgnoreCase(result.getResponse().getStatus())) { - isTransactionSuccessful = true; - description.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); - description.setStatusComment(StatusUtil.UIN_DATA_UPDATION_SUCCESS.getMessage()); - description.setSubStatusCode(StatusUtil.UIN_DATA_UPDATION_SUCCESS.getCode()); - description.setMessage( - StatusUtil.UIN_DATA_UPDATION_SUCCESS.getMessage() + " for registration Id: " + regId); - description.setTransactionStatusCode(RegistrationTransactionStatusCode.PROCESSED.toString()); - object.setIsValid(Boolean.TRUE); - } - } else { - String statusComment = result != null && result.getErrors() != null ? result.getErrors().get(0).getMessage() - : UINConstants.NULL_IDREPO_RESPONSE; - String message = result != null && result.getErrors() != null - ? result.getErrors().get(0).getMessage() - : UINConstants.NULL_IDREPO_RESPONSE; - description.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); - description.setStatusComment(trimExceptionMessage - .trimExceptionMessage(StatusUtil.UIN_DATA_UPDATION_FAILED.getMessage() + statusComment)); - description.setSubStatusCode(StatusUtil.UIN_DATA_UPDATION_FAILED.getCode()); - description - .setMessage(UINConstants.UIN_FAILURE + regId + "::" + message ); - description.setTransactionStatusCode(RegistrationTransactionStatusCode.PROCESSING.toString()); - object.setIsValid(Boolean.FALSE); - } - return isTransactionSuccessful; - } - - /** - * Id repo request builder. - * - * @param status - * the status - * @param id - * the reg id - * @param demographicIdentity - * the JSONObject - * @param documentInfo - * the document info - * @throws ApisResourceAccessException - * the apis resource access exception - * @throws IOException - */ - private IdResponseDTO idRepoRequestBuilder(String id, String uin, String status, List documentInfo, - JSONObject demographicIdentity) throws ApisResourceAccessException, IdrepoDraftException, IOException { - IdResponseDTO idResponseDto; - RequestDto requestDto = new RequestDto(); - - if (documentInfo != null) - requestDto.setDocuments(documentInfo); - - requestDto.setRegistrationId(id); - requestDto.setStatus(status); - requestDto.setIdentity(demographicIdentity); - - IdRequestDto idRequestDTO = new IdRequestDto(); - idRequestDTO.setId(idRepoUpdate); - idRequestDTO.setMetadata(null); - idRequestDTO.setRequest(requestDto); - idRequestDTO.setRequesttime(DateUtils.getUTCCurrentDateTimeString()); - idRequestDTO.setVersion(UINConstants.idRepoApiVersion); - - try { - idResponseDto = idrepoDraftService.idrepoUpdateDraft(id, uin, idRequestDTO); - } catch (ApisResourceAccessException e) { - regProcLogger.error("Execption occured updating draft for id " + id, e); - if (e.getCause() instanceof HttpClientErrorException) { - regProcLogger.error("Exception occured updating draft for id " + id, e); - HttpClientErrorException httpClientException = (HttpClientErrorException) e.getCause(); - throw new ApisResourceAccessException(httpClientException.getResponseBodyAsString(), - httpClientException); - } else if (e.getCause() instanceof HttpServerErrorException) { - HttpServerErrorException httpServerException = (HttpServerErrorException) e.getCause(); - throw new ApisResourceAccessException(httpServerException.getResponseBodyAsString(), - httpServerException); - } else { - throw e; - } - - } - return idResponseDto; - } - - /** - * Re activate uin. - * - * @param id - * the reg id - * @param uin - * the uin - * @param object - * the object - * @param description - * @return the id response DTO - * @throws ApisResourceAccessException - * the apis resource access exception - * @throws IOException - */ - private boolean reActivateUin(IdResponseDTO idResponseDTO, String id, String uin, MessageDTO object, - JSONObject demographicIdentity, LogDescription description) - throws ApisResourceAccessException, IOException, IdrepoDraftException { - IdResponseDTO result = getIdRepoDataByUIN(uin, id, description); - List pathsegments = new ArrayList<>(); - RequestDto requestDto = new RequestDto(); - boolean isTransactionSuccessful = Boolean.FALSE; - - if (isIdResponseNotNull(result)) { - - if ((RegistrationType.ACTIVATED.toString()).equalsIgnoreCase(result.getResponse().getStatus())) { - - description.setStatusCode(RegistrationStatusCode.FAILED.toString()); - description.setStatusComment(StatusUtil.UIN_ALREADY_ACTIVATED.getMessage()); - description.setSubStatusCode(StatusUtil.UIN_ALREADY_ACTIVATED.getCode()); - description.setMessage(PlatformErrorMessages.UIN_ALREADY_ACTIVATED.getMessage()); - description.setCode(PlatformErrorMessages.UIN_ALREADY_ACTIVATED.getCode()); - description.setTransactionStatusCode(RegistrationTransactionStatusCode.FAILED.toString()); - object.setIsValid(Boolean.FALSE); - return isTransactionSuccessful; - - } else { - - requestDto.setRegistrationId(id); - requestDto.setStatus(RegistrationType.ACTIVATED.toString()); - requestDto.setBiometricReferenceId(uin); - requestDto.setIdentity(demographicIdentity); - - IdRequestDto idRequestDTO = new IdRequestDto(); - idRequestDTO.setId(idRepoUpdate); - idRequestDTO.setRequest(requestDto); - idRequestDTO.setMetadata(null); - idRequestDTO.setRequesttime(DateUtils.getUTCCurrentDateTimeString()); - idRequestDTO.setVersion(UINConstants.idRepoApiVersion); - - result = idrepoDraftService.idrepoUpdateDraft(id, uin, idRequestDTO); - - if (isIdResponseNotNull(result)) { - - if ((RegistrationType.ACTIVATED.toString()).equalsIgnoreCase(result.getResponse().getStatus())) { - isTransactionSuccessful = true; - description.setStatusCode(RegistrationStatusCode.PROCESSED.toString()); - description.setStatusComment(StatusUtil.UIN_ACTIVATED_SUCCESS.getMessage()); - description.setSubStatusCode(StatusUtil.UIN_ACTIVATED_SUCCESS.getCode()); - description.setMessage(StatusUtil.UIN_ACTIVATED_SUCCESS.getMessage() + id); - description.setMessage(PlatformSuccessMessages.RPR_UIN_ACTIVATED_SUCCESS.getMessage()); - description.setCode(PlatformSuccessMessages.RPR_UIN_ACTIVATED_SUCCESS.getCode()); - description.setTransactionStatusCode(RegistrationTransactionStatusCode.PROCESSED.toString()); - object.setIsValid(Boolean.TRUE); - } else { - description.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); - description.setStatusComment(StatusUtil.UIN_ACTIVATED_FAILED.getMessage()); - description.setSubStatusCode(StatusUtil.UIN_ACTIVATED_FAILED.getCode()); - description.setMessage(StatusUtil.UIN_ACTIVATED_FAILED.getMessage() + id); - description.setMessage(PlatformErrorMessages.UIN_ACTIVATED_FAILED.getMessage()); - description.setCode(PlatformErrorMessages.UIN_ACTIVATED_FAILED.getCode()); - description.setTransactionStatusCode(RegistrationTransactionStatusCode.REPROCESS.toString()); - object.setIsValid(Boolean.FALSE); - } - } else { - String statusComment = result != null && result.getErrors() != null - ? result.getErrors().get(0).getMessage() - : UINConstants.NULL_IDREPO_RESPONSE; - description.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); - description.setStatusComment(trimExceptionMessage - .trimExceptionMessage(StatusUtil.UIN_REACTIVATION_FAILED.getMessage() + statusComment)); - description.setSubStatusCode(StatusUtil.UIN_REACTIVATION_FAILED.getCode()); - description.setMessage( - UINConstants.UIN_FAILURE + id + "::" + (result != null && result.getErrors() != null - ? result.getErrors().get(0).getMessage() - : UINConstants.NULL_IDREPO_RESPONSE)); - description.setMessage(PlatformErrorMessages.UIN_REACTIVATION_FAILED.getMessage()); - description.setCode(PlatformErrorMessages.UIN_REACTIVATION_FAILED.getCode()); - description.setTransactionStatusCode(RegistrationTransactionStatusCode.REPROCESS.toString()); - object.setIsValid(Boolean.FALSE); - } - - } - - }else { - String statusComment = result != null && result.getErrors() != null - ? result.getErrors().get(0).getMessage() - : UINConstants.NULL_IDREPO_RESPONSE; - description.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); - description.setStatusComment(trimExceptionMessage - .trimExceptionMessage(StatusUtil.UIN_REACTIVATION_FAILED.getMessage() + statusComment)); - description.setSubStatusCode(StatusUtil.UIN_REACTIVATION_FAILED.getCode()); - description.setMessage( - UINConstants.UIN_FAILURE + id + "::" + (result != null && result.getErrors() != null - ? result.getErrors().get(0).getMessage() - : UINConstants.NULL_IDREPO_RESPONSE)); - description.setMessage(PlatformErrorMessages.UIN_REACTIVATION_FAILED.getMessage()); - description.setCode(PlatformErrorMessages.UIN_REACTIVATION_FAILED.getCode()); - description.setTransactionStatusCode(RegistrationTransactionStatusCode.REPROCESS.toString()); - object.setIsValid(Boolean.FALSE); - } - - return isTransactionSuccessful; - } - - private boolean isIdResponseNotNull(IdResponseDTO result) { - return result != null && result.getResponse() != null; - } - - private boolean isUinAlreadyPresent(IdResponseDTO result, String rid) { - if (result != null && result.getErrors() != null && result.getErrors().size() > 0 - && result.getErrors().get(0).getErrorCode().equalsIgnoreCase(RECORD_ALREADY_EXISTS_ERROR)) { - ErrorDTO errorDTO = result.getErrors().get(0); - regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), - LoggerFileConstant.REGISTRATIONID.toString() + rid, - "Record is already present in IDREPO. Error message received : " + errorDTO.getMessage(), - "The stage will ignore this error and try to generate vid for the existing UIN now. " + - "This is to make sure if the packet processing fails while generating VID then re-processor can process the packet again"); - return true; - } - return false; - } - - /** - * Deactivate uin. - * - * @param id - * the reg id - * @param uin - * the uin - * @param object - * the object - * @param description - * @return the id response DTO - * @throws ApisResourceAccessException - * @throws IOException - */ - private IdResponseDTO deactivateUin(String id, String uin, MessageDTO object, JSONObject demographicIdentity, - LogDescription description) throws ApisResourceAccessException, IOException, IdrepoDraftException { - IdResponseDTO idResponseDto; - RequestDto requestDto = new RequestDto(); - String statusComment = ""; - - idResponseDto = getIdRepoDataByUIN(uin, id, description); - - if (idResponseDto.getResponse() != null - && idResponseDto.getResponse().getStatus().equalsIgnoreCase(RegistrationType.DEACTIVATED.toString())) { - description.setStatusCode(RegistrationStatusCode.FAILED.toString()); - description.setStatusComment(StatusUtil.UIN_ALREADY_DEACTIVATED.getMessage()); - description.setSubStatusCode(StatusUtil.UIN_ALREADY_DEACTIVATED.getCode()); - description.setMessage(StatusUtil.UIN_ALREADY_DEACTIVATED.getMessage() + id); - description.setMessage(PlatformErrorMessages.UIN_ALREADY_DEACTIVATED.getMessage()); - description.setCode(PlatformErrorMessages.UIN_ALREADY_DEACTIVATED.getCode()); - description.setTransactionStatusCode(RegistrationTransactionStatusCode.FAILED.toString()); - object.setIsValid(Boolean.FALSE); - return idResponseDto; - - } else { - requestDto.setRegistrationId(id); - requestDto.setStatus(RegistrationType.DEACTIVATED.toString()); - requestDto.setIdentity(demographicIdentity); - requestDto.setBiometricReferenceId(uin); - - IdRequestDto idRequestDTO = new IdRequestDto(); - idRequestDTO.setId(idRepoUpdate); - idRequestDTO.setMetadata(null); - idRequestDTO.setRequest(requestDto); - idRequestDTO.setRequesttime(DateUtils.getUTCCurrentDateTimeString()); - idRequestDTO.setVersion(UINConstants.idRepoApiVersion); - - idResponseDto = idrepoDraftService.idrepoUpdateDraft(id, uin, idRequestDTO); - - if (isIdResponseNotNull(idResponseDto)) { - if (idResponseDto.getResponse().getStatus().equalsIgnoreCase(RegistrationType.DEACTIVATED.toString())) { - description.setStatusCode(RegistrationStatusCode.PROCESSED.toString()); - description.setStatusComment(StatusUtil.UIN_DEACTIVATION_SUCCESS.getMessage()); - description.setSubStatusCode(StatusUtil.UIN_DEACTIVATION_SUCCESS.getCode()); - description.setMessage(StatusUtil.UIN_DEACTIVATION_SUCCESS.getMessage() + id); - description.setMessage(PlatformSuccessMessages.RPR_UIN_DEACTIVATION_SUCCESS.getMessage()); - description.setCode(PlatformSuccessMessages.RPR_UIN_DEACTIVATION_SUCCESS.getCode()); - description.setTransactionStatusCode(RegistrationTransactionStatusCode.PROCESSED.toString()); - object.setIsValid(Boolean.TRUE); - statusComment = idResponseDto.getResponse().getStatus().toString(); - - } - } else { - - statusComment = idResponseDto != null && idResponseDto.getErrors() != null - ? idResponseDto.getErrors().get(0).getMessage() - : UINConstants.NULL_IDREPO_RESPONSE; - description.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); - description.setStatusComment(trimExceptionMessage - .trimExceptionMessage(StatusUtil.UIN_DEACTIVATION_FAILED.getMessage() + statusComment)); - description.setSubStatusCode(StatusUtil.UIN_DEACTIVATION_FAILED.getCode()); - description.setMessage(PlatformErrorMessages.UIN_DEACTIVATION_FAILED.getMessage()); - description.setCode(PlatformErrorMessages.UIN_DEACTIVATION_FAILED.getCode()); - description.setTransactionStatusCode(RegistrationTransactionStatusCode.REPROCESS.toString()); - object.setIsValid(Boolean.FALSE); - } - - } - regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), - LoggerFileConstant.REGISTRATIONID.toString() + id, "Updated Response from IdRepo API", - "is : " + statusComment); - - return idResponseDto; - } - - /** - * Gets the id repo data by UIN. - * - * @param uin - * the uin - * @param description - * @return the id repo data by UIN - * @throws ApisResourceAccessException - * the apis resource access exception - * @throws IOException - */ - private IdResponseDTO getIdRepoDataByUIN(String uin, String regId, LogDescription description) - throws ApisResourceAccessException { - IdResponseDTO response; - - List pathsegments = new ArrayList<>(); - pathsegments.add(uin); - try { - - response = (IdResponseDTO) registrationProcessorRestClientService.getApi(ApiName.IDREPOGETIDBYUIN, - pathsegments, "", "", IdResponseDTO.class); - - } catch (ApisResourceAccessException e) { - if (e.getCause() instanceof HttpClientErrorException) { - HttpClientErrorException httpClientException = (HttpClientErrorException) e.getCause(); - description.setMessage(PlatformErrorMessages.UIN_GENERATION_FAILED.getMessage()); - description.setCode(PlatformErrorMessages.UIN_GENERATION_FAILED.getCode()); - throw new ApisResourceAccessException(httpClientException.getResponseBodyAsString(), - httpClientException); - } else if (e.getCause() instanceof HttpServerErrorException) { - HttpServerErrorException httpServerException = (HttpServerErrorException) e.getCause(); - description.setMessage(PlatformErrorMessages.UIN_GENERATION_FAILED.getMessage()); - description.setCode(PlatformErrorMessages.UIN_GENERATION_FAILED.getCode()); - - throw new ApisResourceAccessException(httpServerException.getResponseBodyAsString(), - httpServerException); - } else { - description.setMessage(PlatformErrorMessages.UIN_GENERATION_FAILED.getMessage()); - description.setCode(PlatformErrorMessages.UIN_GENERATION_FAILED.getCode()); - throw e; - } - } - return response; - } - - /** - * Deploy verticle. - */ - public void deployVerticle() { - - mosipEventBus = this.getEventBus(this, clusterManagerUrl, workerPoolSize); - this.consumeAndSend(mosipEventBus, MessageBusAddress.UIN_GENERATION_BUS_IN, - MessageBusAddress.UIN_GENERATION_BUS_OUT, messageExpiryTimeLimit); - } - - @Override - public void start() { - router.setRoute(this.postUrl(getVertx(), MessageBusAddress.UIN_GENERATION_BUS_IN, - MessageBusAddress.UIN_GENERATION_BUS_OUT)); - this.createServer(router.getRouter(), getPort()); - - } - - @Override - protected String getPropertyPrefix() { - return STAGE_PROPERTY_PREFIX; - } - - /** - * Link reg id wrt uin. - * - * @param lostPacketRegId - * the lost packet reg id - * @param matchedRegId - * the matched reg id - * @param object - * the object - * @param description - * @return the id response DTO - * @throws ApisResourceAccessException - * the apis resource access exception - * @throws IOException - * Signals that an I/O exception has occurred. - */ - @SuppressWarnings("unchecked") - private IdResponseDTO lostAndUpdateUin(String lostPacketRegId, String matchedRegId, String process, MessageDTO object, - LogDescription description) throws ApisResourceAccessException, IOException, io.mosip.kernel.core.util.exception.JsonProcessingException, PacketManagerException, IdrepoDraftException { - - IdResponseDTO idResponse = null; - String uin = idRepoService.getUinByRid(matchedRegId, utility.getGetRegProcessorDemographicIdentity()); - - - RequestDto requestDto = new RequestDto(); - String statusComment = ""; - - if (uin != null) { - - JSONObject regProcessorIdentityJson = utility.getRegistrationProcessorMappingJson(MappingJsonConstants.IDENTITY); - String idschemaversion = JsonUtil.getJSONValue(JsonUtil.getJSONObject(regProcessorIdentityJson, MappingJsonConstants.IDSCHEMA_VERSION), MappingJsonConstants.VALUE); - - JSONObject identityObject = new JSONObject(); - identityObject.put(UINConstants.UIN, uin); - String schemaVersion = packetManagerService.getFieldByMappingJsonKey(lostPacketRegId, MappingJsonConstants.IDSCHEMA_VERSION, process, ProviderStageName.UIN_GENERATOR); - identityObject.put(idschemaversion, convertIdschemaToDouble ? Double.valueOf(schemaVersion) : schemaVersion); - regProcLogger.info("Fields to be updated "+updateInfo); - if (null != updateInfo && !updateInfo.isEmpty()) { - String[] upd = updateInfo.split(","); - for (String infoField : upd) { - String fldValue = packetManagerService.getField(lostPacketRegId, infoField, process, - ProviderStageName.UIN_GENERATOR); - if (null != fldValue) - identityObject.put(infoField, fldValue); - } - } - requestDto.setRegistrationId(lostPacketRegId); - requestDto.setIdentity(identityObject); - - IdRequestDto idRequestDTO = new IdRequestDto(); - idRequestDTO.setId(idRepoUpdate); - idRequestDTO.setRequest(requestDto); - idRequestDTO.setMetadata(null); - idRequestDTO.setRequesttime(DateUtils.getUTCCurrentDateTimeString()); - idRequestDTO.setVersion(UINConstants.idRepoApiVersion); - - idResponse = idrepoDraftService.idrepoUpdateDraft(lostPacketRegId, uin, idRequestDTO); - - if (isIdResponseNotNull(idResponse)) { - description.setStatusCode(RegistrationStatusCode.PROCESSED.toString()); - description.setStatusComment(StatusUtil.LINK_RID_FOR_LOST_PACKET_SUCCESS.getMessage()); - description.setSubStatusCode(StatusUtil.LINK_RID_FOR_LOST_PACKET_SUCCESS.getCode()); - description.setMessage(UinStatusMessage.PACKET_LOST_UIN_UPDATION_SUCCESS_MSG + lostPacketRegId); - description.setTransactionStatusCode(RegistrationTransactionStatusCode.PROCESSED.toString()); - object.setIsValid(Boolean.TRUE); - - regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), - LoggerFileConstant.REGISTRATIONID.toString() + lostPacketRegId, - " UIN LINKED WITH " + matchedRegId, "is : " + description); - } else { - - statusComment = idResponse != null && idResponse.getErrors() != null - && idResponse.getErrors().get(0) != null ? idResponse.getErrors().get(0).getMessage() - : UinStatusMessage.PACKET_LOST_UIN_UPDATION_FAILURE_MSG + " " - + UINConstants.NULL_IDREPO_RESPONSE + "for lostPacketRegId " + lostPacketRegId; - description.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); - description.setStatusComment(StatusUtil.LINK_RID_FOR_LOST_PACKET_SUCCESS.getMessage() + statusComment); - description.setSubStatusCode(StatusUtil.LINK_RID_FOR_LOST_PACKET_SUCCESS.getCode()); - description.setTransactionStatusCode(registrationStatusMapperUtil - .getStatusCode(RegistrationExceptionTypeCode.PACKET_UIN_GENERATION_ID_REPO_ERROR)); - if (idResponse != null - && idResponse.getErrors() != null) - description.setMessage(idResponse.getErrors().get(0).getMessage()); - else - description.setMessage(UINConstants.NULL_IDREPO_RESPONSE); - object.setIsValid(Boolean.FALSE); - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), - LoggerFileConstant.REGISTRATIONID.toString() + lostPacketRegId, - " UIN NOT LINKED WITH " + matchedRegId, "is : " + statusComment); - } - - } else { - statusComment = UinStatusMessage.PACKET_LOST_UIN_UPDATION_FAILURE_MSG + " " - + UINConstants.NULL_IDREPO_RESPONSE + " UIN not available for matchedRegId " + matchedRegId; - description.setStatusComment(StatusUtil.LINK_RID_FOR_LOST_PACKET_FAILED.getMessage()); - description.setSubStatusCode(StatusUtil.LINK_RID_FOR_LOST_PACKET_FAILED.getCode()); - description.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); - description.setTransactionStatusCode(registrationStatusMapperUtil - .getStatusCode(RegistrationExceptionTypeCode.PACKET_UIN_GENERATION_REPROCESS)); - description.setMessage(UinStatusMessage.PACKET_LOST_UIN_UPDATION_FAILURE_MSG + " " - + UINConstants.NULL_IDREPO_RESPONSE + " UIN not available for matchedRegId " + matchedRegId); - - object.setIsValid(Boolean.FALSE); - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), - LoggerFileConstant.REGISTRATIONID.toString() + lostPacketRegId, - " UIN NOT LINKED WITH " + matchedRegId, "is : " + statusComment); - } - - return idResponse; - } - - private void updateErrorFlags(InternalRegistrationStatusDto registrationStatusDto, MessageDTO object) { - object.setInternalError(true); - if (registrationStatusDto.getLatestTransactionStatusCode() - .equalsIgnoreCase(RegistrationTransactionStatusCode.REPROCESS.toString())) { - object.setIsValid(true); - } else { - object.setIsValid(false); - } - } -} +package io.mosip.registration.processor.stages.uingenerator.stage; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import org.apache.commons.lang3.exception.ExceptionUtils; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONTokener; +import org.json.simple.JSONObject; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.cloud.context.config.annotation.RefreshScope; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Service; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.web.client.HttpServerErrorException; + +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +import io.mosip.kernel.biometrics.entities.BiometricRecord; +import io.mosip.kernel.biometrics.spi.CbeffUtil; +import io.mosip.kernel.core.logger.spi.Logger; +import io.mosip.kernel.core.util.CryptoUtil; +import io.mosip.kernel.core.util.DateUtils; +import io.mosip.kernel.core.util.StringUtils; +import io.mosip.registration.processor.core.abstractverticle.MessageBusAddress; +import io.mosip.registration.processor.core.abstractverticle.MessageDTO; +import io.mosip.registration.processor.core.abstractverticle.MosipEventBus; +import io.mosip.registration.processor.core.abstractverticle.MosipRouter; +import io.mosip.registration.processor.core.abstractverticle.MosipVerticleAPIManager; +import io.mosip.registration.processor.core.code.ApiName; +import io.mosip.registration.processor.core.code.ModuleName; +import io.mosip.registration.processor.core.code.RegistrationExceptionTypeCode; +import io.mosip.registration.processor.core.code.RegistrationTransactionStatusCode; +import io.mosip.registration.processor.core.code.RegistrationTransactionTypeCode; +import io.mosip.registration.processor.core.common.rest.dto.ErrorDTO; +import io.mosip.registration.processor.core.constant.EventId; +import io.mosip.registration.processor.core.constant.EventName; +import io.mosip.registration.processor.core.constant.EventType; +import io.mosip.registration.processor.core.constant.LoggerFileConstant; +import io.mosip.registration.processor.core.constant.MappingJsonConstants; +import io.mosip.registration.processor.core.constant.ProviderStageName; +import io.mosip.registration.processor.core.exception.ApisResourceAccessException; +import io.mosip.registration.processor.core.exception.PacketManagerException; +import io.mosip.registration.processor.core.exception.RegistrationProcessorCheckedException; +import io.mosip.registration.processor.core.exception.util.PlatformErrorMessages; +import io.mosip.registration.processor.core.exception.util.PlatformSuccessMessages; +import io.mosip.registration.processor.core.idrepo.dto.Documents; +import io.mosip.registration.processor.core.logger.LogDescription; +import io.mosip.registration.processor.core.logger.RegProcessorLogger; +import io.mosip.registration.processor.core.spi.restclient.RegistrationProcessorRestClientService; +import io.mosip.registration.processor.core.status.util.StatusUtil; +import io.mosip.registration.processor.core.status.util.TrimExceptionMessage; +import io.mosip.registration.processor.core.util.JsonUtil; +import io.mosip.registration.processor.core.util.RegistrationExceptionMapperUtil; +import io.mosip.registration.processor.packet.manager.dto.IdRequestDto; +import io.mosip.registration.processor.packet.manager.dto.IdResponseDTO; +import io.mosip.registration.processor.packet.manager.dto.RequestDto; +import io.mosip.registration.processor.packet.manager.exception.IdrepoDraftException; +import io.mosip.registration.processor.packet.manager.exception.IdrepoDraftReprocessableException; +import io.mosip.registration.processor.packet.manager.idreposervice.IdRepoService; +import io.mosip.registration.processor.packet.manager.idreposervice.IdrepoDraftService; +import io.mosip.registration.processor.packet.storage.dto.Document; +import io.mosip.registration.processor.packet.storage.entity.RegLostUinDetEntity; +import io.mosip.registration.processor.packet.storage.repository.BasePacketRepository; +import io.mosip.registration.processor.packet.storage.utils.ABISHandlerUtil; +import io.mosip.registration.processor.packet.storage.utils.IdSchemaUtil; +import io.mosip.registration.processor.packet.storage.utils.PriorityBasedPacketManagerService; +import io.mosip.registration.processor.packet.storage.utils.Utilities; +import io.mosip.registration.processor.rest.client.audit.builder.AuditLogRequestBuilder; +import io.mosip.registration.processor.stages.uingenerator.constants.UINConstants; +import io.mosip.registration.processor.stages.uingenerator.dto.UinGenResponseDto; +import io.mosip.registration.processor.stages.uingenerator.exception.VidCreationException; +import io.mosip.registration.processor.stages.uingenerator.util.UinStatusMessage; +import io.mosip.registration.processor.status.code.RegistrationStatusCode; +import io.mosip.registration.processor.status.code.RegistrationType; +import io.mosip.registration.processor.status.dto.InternalRegistrationStatusDto; +import io.mosip.registration.processor.status.dto.RegistrationStatusDto; +import io.mosip.registration.processor.status.service.RegistrationStatusService; + +/** + * The Class UinGeneratorStage. + * + * @author Ranjitha Siddegowda + * @author Rishabh Keshari + */ +@RefreshScope +@Service +@Configuration +@ComponentScan(basePackages = { "${mosip.auth.adapter.impl.basepackage}", + "io.mosip.registration.processor.core.config", + "io.mosip.registration.processor.stages.uingenerator.config", + "io.mosip.registration.processor.status.config", "io.mosip.registration.processor.rest.client.config", + "io.mosip.registration.processor.packet.storage.config", + "io.mosip.registration.processor.stages.config", + "io.mosip.kernel.packetmanager.config", + "io.mosip.registration.processor.packet.manager.config", + "io.mosip.registration.processor.core.kernel.beans"}) +public class UinGeneratorStage extends MosipVerticleAPIManager { + + /** The reg proc logger. */ + private static Logger regProcLogger = RegProcessorLogger.getLogger(UinGeneratorStage.class); + private static final String RECORD_ALREADY_EXISTS_ERROR = "IDR-IDC-012"; + private static final String STAGE_PROPERTY_PREFIX = "mosip.regproc.uin.generator."; + private static final String UIN = "UIN"; + private static final String IDREPO_STATUS = "DRAFTED"; + + @Autowired + private Environment env; + + @Autowired + private IdRepoService idRepoService; + + /** The mosip event bus. */ + MosipEventBus mosipEventBus = null; + + @Value("${registration.processor.id.repo.vidType}") + private String vidType; + + @Value("${mosip.commons.packet.manager.schema.validator.convertIdSchemaToDouble:true}") + private boolean convertIdschemaToDouble; + + /** The cluster manager url. */ + @Value("${vertx.cluster.configuration}") + private String clusterManagerUrl; + + /** The id repo create. */ + @Value("${registration.processor.id.repo.create}") + private String idRepoCreate; + + /** The id repo update. */ + @Value("${registration.processor.id.repo.update}") + private String idRepoUpdate; + + /** worker pool size. */ + @Value("${worker.pool.size}") + private Integer workerPoolSize; + + /** After this time intervel, message should be considered as expired (In seconds). */ + @Value("${mosip.regproc.uin.generator.message.expiry-time-limit}") + private Long messageExpiryTimeLimit; + + @Value("${uingenerator.lost.packet.allowed.update.fields:null}") + private String updateInfo; + + /** The core audit request builder. */ + @Autowired + private AuditLogRequestBuilder auditLogRequestBuilder; + + /** Mosip router for APIs */ + @Autowired + private MosipRouter router; + + @Autowired + private ObjectMapper mapper; + + @Autowired + private IdrepoDraftService idrepoDraftService; + + /** The registration processor rest client service. */ + @Autowired + private RegistrationProcessorRestClientService registrationProcessorRestClientService; + + /** The demographic dedupe repository. */ + @Autowired + private BasePacketRepository regLostUinDetEntity; + + /** The registration status service. */ + @Autowired + private RegistrationStatusService registrationStatusService; + + /** The utility. */ + @Autowired + private Utilities utility; + + @Autowired + private CbeffUtil cbeffutil; + + @Autowired + private RegistrationExceptionMapperUtil registrationStatusMapperUtil; + + @Autowired + private ABISHandlerUtil aBISHandlerUtil; + + @Autowired + private PriorityBasedPacketManagerService packetManagerService; + + @Autowired + private IdSchemaUtil idSchemaUtil; + + @Autowired + private ObjectMapper objectMapper; + + private TrimExceptionMessage trimExceptionMessage = new TrimExceptionMessage(); + + /* + * (non-Javadoc) + * + * @see + * io.mosip.registration.processor.core.spi.eventbus.EventBusManager#process( + * java.lang.Object) + */ + @SuppressWarnings("unchecked") + @Override + public MessageDTO process(MessageDTO object) { + boolean isTransactionSuccessful = Boolean.FALSE; + object.setMessageBusAddress(MessageBusAddress.UIN_GENERATION_BUS_IN); + object.setInternalError(Boolean.FALSE); + object.setIsValid(Boolean.TRUE); + LogDescription description = new LogDescription(); + String registrationId = object.getRid(); + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + registrationId, "UinGeneratorStage::process()::entry"); + UinGenResponseDto uinResponseDto = null; + + InternalRegistrationStatusDto registrationStatusDto = registrationStatusService.getRegistrationStatus( + registrationId, object.getReg_type(), object.getIteration(), object.getWorkflowInstanceId()); + try { + registrationStatusDto + .setLatestTransactionTypeCode(RegistrationTransactionTypeCode.UIN_GENERATOR.toString()); + registrationStatusDto.setRegistrationStageName(getStageName()); + + if ((RegistrationType.LOST.toString()).equalsIgnoreCase(object.getReg_type())) { + String lostPacketRegId = object.getRid(); + String matchedRegId = regLostUinDetEntity.getLostUinMatchedRegIdByWorkflowId(object.getWorkflowInstanceId()); + + if (matchedRegId != null) { + regProcLogger.info("Match for lostPacketRegId"+lostPacketRegId +"is "+matchedRegId); + lostAndUpdateUin(lostPacketRegId, matchedRegId, registrationStatusDto.getRegistrationType(), object, description); + } + + } else { + + IdResponseDTO idResponseDTO = new IdResponseDTO(); + String schemaVersion = packetManagerService.getFieldByMappingJsonKey(registrationId, MappingJsonConstants.IDSCHEMA_VERSION, registrationStatusDto.getRegistrationType(), ProviderStageName.UIN_GENERATOR); + + Map fieldMap = packetManagerService.getFields(registrationId, + idSchemaUtil.getDefaultFields(Double.valueOf(schemaVersion)), registrationStatusDto.getRegistrationType(), ProviderStageName.UIN_GENERATOR); + String uinField = fieldMap.get(utility.getMappingJsonValue(MappingJsonConstants.UIN, MappingJsonConstants.IDENTITY)); + + JSONObject demographicIdentity = new JSONObject(); + demographicIdentity.put(MappingJsonConstants.IDSCHEMA_VERSION, convertIdschemaToDouble ? Double.valueOf(schemaVersion) : schemaVersion); + + loadDemographicIdentity(fieldMap, demographicIdentity); + + if (StringUtils.isEmpty(uinField) || uinField.equalsIgnoreCase("null") ) { + + idResponseDTO = sendIdRepoWithUin(registrationId, registrationStatusDto.getRegistrationType(), demographicIdentity, + uinField); + + boolean isUinAlreadyPresent = isUinAlreadyPresent(idResponseDTO, registrationId); + + if (isIdResponseNotNull(idResponseDTO) || isUinAlreadyPresent) { + registrationStatusDto.setStatusComment(StatusUtil.UIN_GENERATED_SUCCESS.getMessage()); + registrationStatusDto.setSubStatusCode(StatusUtil.UIN_GENERATED_SUCCESS.getCode()); + isTransactionSuccessful = true; + registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); + description.setMessage(PlatformSuccessMessages.RPR_UIN_GENERATOR_STAGE_SUCCESS.getMessage()); + description.setCode(PlatformSuccessMessages.RPR_UIN_GENERATOR_STAGE_SUCCESS.getCode()); + description.setTransactionStatusCode(RegistrationTransactionStatusCode.SUCCESS.toString()); + + } else { + List errors = idResponseDTO != null ? idResponseDTO.getErrors() : null; + String statusComment = errors != null ? errors.get(0).getMessage() + : UINConstants.NULL_IDREPO_RESPONSE; + int unknownErrorCount=0; + for(ErrorDTO dto:errors) { + if(dto.getErrorCode().equalsIgnoreCase("IDR-IDC-004")||dto.getErrorCode().equalsIgnoreCase("IDR-IDC-001")) { + unknownErrorCount++; + } + } + if(unknownErrorCount>0) { + registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); + registrationStatusDto.setLatestTransactionStatusCode(registrationStatusMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.PACKET_UIN_GENERATION_REPROCESS)); + description.setTransactionStatusCode(registrationStatusMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.PACKET_UIN_GENERATION_REPROCESS)); + } + else { + registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.toString()); + registrationStatusDto.setLatestTransactionStatusCode(registrationStatusMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.PACKET_UIN_GENERATION_FAILED)); + description.setTransactionStatusCode(registrationStatusMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.PACKET_UIN_GENERATION_FAILED)); + } + registrationStatusDto.setStatusComment(trimExceptionMessage + .trimExceptionMessage(StatusUtil.UIN_GENERATION_FAILED.getMessage() + statusComment)); + object.setInternalError(Boolean.TRUE); + isTransactionSuccessful = false; + description.setMessage(PlatformErrorMessages.RPR_UGS_UIN_UPDATE_FAILURE.getMessage()); + description.setCode(PlatformErrorMessages.RPR_UGS_UIN_UPDATE_FAILURE.getCode()); + description.setSubStatusCode(StatusUtil.UIN_GENERATION_FAILED.getCode()); + String idres = idResponseDTO != null ? idResponseDTO.toString() + : UINConstants.NULL_IDREPO_RESPONSE; + + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString(), registrationId, + statusComment + " : " + idres); + object.setIsValid(Boolean.FALSE); + } + + } else { + if ((RegistrationType.ACTIVATED.toString()).equalsIgnoreCase(object.getReg_type())) { + isTransactionSuccessful = reActivateUin(idResponseDTO, registrationId, uinField, object, + demographicIdentity, description); + } else if ((RegistrationType.DEACTIVATED.toString()) + .equalsIgnoreCase(object.getReg_type())) { + idResponseDTO = deactivateUin(registrationId, uinField, object, demographicIdentity, + description); + } else if (RegistrationType.UPDATE.toString().equalsIgnoreCase(object.getReg_type()) + || (RegistrationType.RES_UPDATE.toString() + .equalsIgnoreCase(object.getReg_type()))) { + isTransactionSuccessful = uinUpdate(registrationId, registrationStatusDto.getRegistrationType(), uinField, object, demographicIdentity, + description); + } + } + + } + regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + registrationId, description.getMessage()); + registrationStatusDto.setUpdatedBy(UINConstants.USER); + + } catch (io.mosip.kernel.core.util.exception.JsonProcessingException e) { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + registrationId, + RegistrationStatusCode.FAILED.toString() + e.getMessage() + ExceptionUtils.getStackTrace(e)); + registrationStatusDto.setStatusCode(RegistrationStatusCode.FAILED.toString()); + registrationStatusDto.setStatusComment( + trimExceptionMessage.trimExceptionMessage(StatusUtil.JSON_PARSING_EXCEPTION.getMessage() + e.getMessage())); + registrationStatusDto.setSubStatusCode(StatusUtil.JSON_PARSING_EXCEPTION.getCode()); + registrationStatusDto.setLatestTransactionStatusCode( + registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.JSON_PROCESSING_EXCEPTION)); + isTransactionSuccessful = false; + description.setMessage(PlatformErrorMessages.RPR_SYS_JSON_PARSING_EXCEPTION.getMessage()); + description.setCode(PlatformErrorMessages.RPR_SYS_JSON_PARSING_EXCEPTION.getCode()); + object.setInternalError(Boolean.TRUE); + object.setRid(registrationStatusDto.getRegistrationId()); + } catch (PacketManagerException e) { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + registrationId, + RegistrationStatusCode.PROCESSING.toString() + e.getMessage() + ExceptionUtils.getStackTrace(e)); + registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.name()); + registrationStatusDto.setStatusComment( + trimExceptionMessage.trimExceptionMessage(StatusUtil.PACKET_MANAGER_EXCEPTION.getMessage() + e.getMessage())); + registrationStatusDto.setSubStatusCode(StatusUtil.PACKET_MANAGER_EXCEPTION.getCode()); + registrationStatusDto.setLatestTransactionStatusCode( + registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.PACKET_MANAGER_EXCEPTION)); + description.setMessage(PlatformErrorMessages.PACKET_MANAGER_EXCEPTION.getMessage()); + description.setCode(PlatformErrorMessages.PACKET_MANAGER_EXCEPTION.getCode()); + object.setInternalError(Boolean.TRUE); + object.setRid(registrationStatusDto.getRegistrationId()); + } catch (ApisResourceAccessException ex) { + registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.name()); + registrationStatusDto.setStatusComment(trimExceptionMessage + .trimExceptionMessage(StatusUtil.API_RESOUCE_ACCESS_FAILED.getMessage() + ex.getMessage())); + registrationStatusDto.setSubStatusCode(StatusUtil.API_RESOUCE_ACCESS_FAILED.getCode()); + registrationStatusDto.setLatestTransactionStatusCode(registrationStatusMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.APIS_RESOURCE_ACCESS_EXCEPTION)); + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + registrationId, + RegistrationStatusCode.PROCESSING.toString() + ex.getMessage() + ExceptionUtils.getStackTrace(ex)); + object.setInternalError(Boolean.TRUE); + description.setMessage(trimExceptionMessage + .trimExceptionMessage(StatusUtil.API_RESOUCE_ACCESS_FAILED.getMessage() + ex.getMessage())); + description.setCode(PlatformErrorMessages.RPR_UGS_API_RESOURCE_EXCEPTION.getCode()); + + } catch (IOException e) { + registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.name()); + registrationStatusDto.setStatusComment( + trimExceptionMessage.trimExceptionMessage(StatusUtil.IO_EXCEPTION.getMessage() + e.getMessage())); + registrationStatusDto.setSubStatusCode(StatusUtil.IO_EXCEPTION.getCode()); + registrationStatusDto.setLatestTransactionStatusCode( + registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.PACKET_UIN_GENERATION_REPROCESS)); + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + registrationId, + PlatformErrorMessages.RPR_SYS_IO_EXCEPTION.getMessage() + ExceptionUtils.getStackTrace(e)); + object.setInternalError(Boolean.TRUE); + description.setMessage(PlatformErrorMessages.RPR_SYS_IO_EXCEPTION.getMessage()); + description.setCode(PlatformErrorMessages.RPR_SYS_IO_EXCEPTION.getCode()); + } catch (IdrepoDraftException e) { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + registrationId, + RegistrationStatusCode.PROCESSING.toString() + e.getMessage() + ExceptionUtils.getStackTrace(e)); + registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.name()); + registrationStatusDto.setStatusComment( + trimExceptionMessage.trimExceptionMessage(StatusUtil.IDREPO_DRAFT_EXCEPTION.getMessage() + e.getMessage())); + registrationStatusDto.setSubStatusCode(StatusUtil.IDREPO_DRAFT_EXCEPTION.getCode()); + registrationStatusDto.setLatestTransactionStatusCode( + registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.IDREPO_DRAFT_EXCEPTION)); + description.setMessage(PlatformErrorMessages.IDREPO_DRAFT_EXCEPTION.getMessage()); + description.setCode(PlatformErrorMessages.IDREPO_DRAFT_EXCEPTION.getCode()); + object.setInternalError(Boolean.TRUE); + object.setRid(registrationStatusDto.getRegistrationId()); + } catch (IdrepoDraftReprocessableException e) { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + registrationId, + RegistrationStatusCode.PROCESSING.toString() + e.getMessage() + ExceptionUtils.getStackTrace(e)); + registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.name()); + registrationStatusDto.setStatusComment(trimExceptionMessage + .trimExceptionMessage( + StatusUtil.IDREPO_DRAFT_REPROCESSABLE_EXCEPTION.getMessage() + e.getMessage())); + registrationStatusDto.setSubStatusCode(StatusUtil.IDREPO_DRAFT_REPROCESSABLE_EXCEPTION.getCode()); + registrationStatusDto.setLatestTransactionStatusCode( + registrationStatusMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.IDREPO_DRAFT_REPROCESSABLE_EXCEPTION)); + description.setMessage(PlatformErrorMessages.IDREPO_DRAFT_EXCEPTION.getMessage()); + description.setCode(PlatformErrorMessages.IDREPO_DRAFT_EXCEPTION.getCode()); + object.setInternalError(Boolean.TRUE); + object.setRid(registrationStatusDto.getRegistrationId()); + } catch (Exception ex) { + registrationStatusDto.setStatusCode(RegistrationStatusCode.PROCESSING.name()); + registrationStatusDto.setStatusComment( + trimExceptionMessage.trimExceptionMessage(StatusUtil.UNKNOWN_EXCEPTION_OCCURED.getMessage())); + registrationStatusDto.setSubStatusCode(StatusUtil.UNKNOWN_EXCEPTION_OCCURED.getCode()); + registrationStatusDto.setLatestTransactionStatusCode( + registrationStatusMapperUtil.getStatusCode(RegistrationExceptionTypeCode.PACKET_UIN_GENERATION_REPROCESS)); + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + registrationId, + RegistrationStatusCode.PROCESSING.toString() + ex.getMessage() + ExceptionUtils.getStackTrace(ex)); + object.setInternalError(Boolean.TRUE); + description.setMessage(PlatformErrorMessages.RPR_BDD_UNKNOWN_EXCEPTION.getMessage()); + description.setCode(PlatformErrorMessages.RPR_BDD_UNKNOWN_EXCEPTION.getCode()); + } finally { + if (description.getStatusComment() != null) + registrationStatusDto.setStatusComment(description.getStatusComment()); + if (description.getStatusCode() != null) + registrationStatusDto.setStatusCode(description.getStatusCode()); + if (description.getSubStatusCode() != null) + registrationStatusDto.setSubStatusCode(description.getSubStatusCode()); + if (description.getTransactionStatusCode() != null) + registrationStatusDto.setLatestTransactionStatusCode(description.getTransactionStatusCode()); + + if (object.getInternalError()) { + updateErrorFlags(registrationStatusDto, object); + } + String moduleId = isTransactionSuccessful + ? PlatformSuccessMessages.RPR_UIN_GENERATOR_STAGE_SUCCESS.getCode() + : description.getCode(); + String moduleName = ModuleName.UIN_GENERATOR.toString(); + registrationStatusService.updateRegistrationStatus(registrationStatusDto, moduleId, moduleName); + String eventId = isTransactionSuccessful ? EventId.RPR_402.toString() : EventId.RPR_405.toString(); + String eventName = eventId.equalsIgnoreCase(EventId.RPR_402.toString()) ? EventName.UPDATE.toString() + : EventName.EXCEPTION.toString(); + String eventType = eventId.equalsIgnoreCase(EventId.RPR_402.toString()) ? EventType.BUSINESS.toString() + : EventType.SYSTEM.toString(); + + auditLogRequestBuilder.createAuditRequestBuilder(description.getMessage(), eventId, eventName, eventType, + moduleId, moduleName, registrationId); + + } + + return object; + } + + private void loadDemographicIdentity(Map fieldMap, JSONObject demographicIdentity) throws IOException, JSONException { + for (Map.Entry e : fieldMap.entrySet()) { + if (e.getValue() != null) { + String value = e.getValue().toString(); + if (value != null) { + Object json = new JSONTokener(value).nextValue(); + if (json instanceof org.json.JSONObject) { + HashMap hashMap = objectMapper.readValue(value, HashMap.class); + demographicIdentity.putIfAbsent(e.getKey(), hashMap); + } + else if (json instanceof JSONArray) { + List jsonList = new ArrayList<>(); + JSONArray jsonArray = new JSONArray(value); + for (int i = 0; i < jsonArray.length(); i++) { + Object obj = jsonArray.get(i); + HashMap hashMap = objectMapper.readValue(obj.toString(), HashMap.class); + jsonList.add(hashMap); + } + demographicIdentity.putIfAbsent(e.getKey(), jsonList); + } else + demographicIdentity.putIfAbsent(e.getKey(), value); + } else + demographicIdentity.putIfAbsent(e.getKey(), value); + } + } + } + + /** + * Send id repo with uin. + * + * @param id + * the reg id + * @param uin + * the uin + * @throws ApisResourceAccessException + * @throws IOException + * @throws JsonMappingException + * @throws JsonParseException + * @throws VidCreationException + * @throws io.mosip.kernel.core.exception.IOException + * @throws Exception + */ + private IdResponseDTO sendIdRepoWithUin(String id, String process, JSONObject demographicIdentity, String uin) + throws Exception { + + List documentInfo = getAllDocumentsByRegId(id, process, demographicIdentity); + RequestDto requestDto = new RequestDto(); + requestDto.setIdentity(demographicIdentity); + requestDto.setDocuments(documentInfo); + requestDto.setRegistrationId(id); + requestDto.setStatus(RegistrationType.ACTIVATED.toString()); + requestDto.setBiometricReferenceId(uin); + + IdResponseDTO result = null; + IdRequestDto idRequestDTO = new IdRequestDto(); + idRequestDTO.setId(idRepoUpdate); + idRequestDTO.setRequest(requestDto); + idRequestDTO.setRequesttime(DateUtils.getUTCCurrentDateTimeString()); + idRequestDTO.setVersion(UINConstants.idRepoApiVersion); + idRequestDTO.setMetadata(null); + + try { + + result = idrepoDraftService.idrepoUpdateDraft(id, null, idRequestDTO); + + } catch (ApisResourceAccessException e) { + regProcLogger.error("Execption occured updating draft for id " + id, e); + if (e.getCause() instanceof HttpClientErrorException) { + HttpClientErrorException httpClientException = (HttpClientErrorException) e.getCause(); + throw new ApisResourceAccessException(httpClientException.getResponseBodyAsString(), + httpClientException); + } else if (e.getCause() instanceof HttpServerErrorException) { + HttpServerErrorException httpServerException = (HttpServerErrorException) e.getCause(); + throw new ApisResourceAccessException(httpServerException.getResponseBodyAsString(), + httpServerException); + } else { + throw e; + } + + } + return result; + + } + + /** + * Gets the all documents by reg id. + * + * @param regId + * the reg id + * @return the all documents by reg id + * @throws IOException + * @throws io.mosip.kernel.core.exception.IOException + * @throws ApisResourceAccessException + * @throws JsonMappingException + * @throws JsonParseException + */ + private List getAllDocumentsByRegId(String regId, String process, JSONObject demographicIdentity) throws Exception { + List applicantDocuments = new ArrayList<>(); + + JSONObject idJSON = demographicIdentity; + JSONObject docJson = utility.getRegistrationProcessorMappingJson(MappingJsonConstants.DOCUMENT); + JSONObject identityJson = utility.getRegistrationProcessorMappingJson(MappingJsonConstants.IDENTITY); + + String applicantBiometricLabel = JsonUtil.getJSONValue(JsonUtil.getJSONObject(identityJson, MappingJsonConstants.INDIVIDUAL_BIOMETRICS), MappingJsonConstants.VALUE); + + HashMap applicantBiometric = (HashMap) idJSON.get(applicantBiometricLabel); + + + for (Object doc : docJson.values()) { + Map docMap = (LinkedHashMap) doc; + String docValue = docMap.values().iterator().next().toString(); + HashMap docInIdentityJson = (HashMap) idJSON.get(docValue); + if (docInIdentityJson != null) + applicantDocuments + .add(getIdDocumnet(regId, docValue, process)); + } + + if (applicantBiometric != null) { + applicantDocuments.add(getBiometrics(regId, applicantBiometricLabel, process, applicantBiometricLabel)); + } + return applicantDocuments; + } + + private Documents getIdDocumnet(String registrationId, String dockey, String process) + throws IOException, ApisResourceAccessException, PacketManagerException, io.mosip.kernel.core.util.exception.JsonProcessingException { + Documents documentsInfoDto = new Documents(); + + Document document = + packetManagerService.getDocument(registrationId, dockey, process, ProviderStageName.UIN_GENERATOR); + if (document != null) { + documentsInfoDto.setValue(CryptoUtil.encodeToURLSafeBase64(document.getDocument())); + documentsInfoDto.setCategory(document.getValue()); + return documentsInfoDto; + } + return null; + } + + private Documents getBiometrics(String registrationId, String person, String process, String idDocLabel) throws Exception { + BiometricRecord biometricRecord = packetManagerService.getBiometrics(registrationId, person, process, ProviderStageName.UIN_GENERATOR); + byte[] xml = cbeffutil.createXML(biometricRecord.getSegments()); + Documents documentsInfoDto = new Documents(); + documentsInfoDto.setValue(CryptoUtil.encodeToURLSafeBase64(xml)); + documentsInfoDto.setCategory(utility.getMappingJsonValue(idDocLabel, MappingJsonConstants.IDENTITY)); + return documentsInfoDto; + + } + + /** + * Update id repo wit uin. + * + * @param regId the reg id + * @param uin the uin + * @param object the object + * @param description + * @return the id response DTO + * @throws ApisResourceAccessException the apis resource access + * exception + * @throws IOException Signals that an I/O exception + * has occurred. + * @throws RegistrationProcessorCheckedException + * @throws io.mosip.kernel.core.exception.IOException + */ + private boolean uinUpdate(String regId, String process, String uin, MessageDTO object, JSONObject demographicIdentity, LogDescription description) + throws Exception { + IdResponseDTO result; + boolean isTransactionSuccessful = Boolean.FALSE; + List documentInfo = getAllDocumentsByRegId(regId, process, demographicIdentity); + result = idRepoRequestBuilder(regId, uin, RegistrationType.ACTIVATED.toString().toUpperCase(), documentInfo, + demographicIdentity); + if (null!=result && isIdResponseNotNull(result)) { + + if (IDREPO_STATUS.equalsIgnoreCase(result.getResponse().getStatus())) { + isTransactionSuccessful = true; + description.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); + description.setStatusComment(StatusUtil.UIN_DATA_UPDATION_SUCCESS.getMessage()); + description.setSubStatusCode(StatusUtil.UIN_DATA_UPDATION_SUCCESS.getCode()); + description.setMessage( + StatusUtil.UIN_DATA_UPDATION_SUCCESS.getMessage() + " for registration Id: " + regId); + description.setTransactionStatusCode(RegistrationTransactionStatusCode.PROCESSED.toString()); + object.setIsValid(Boolean.TRUE); + } + } else { + String statusComment = result != null && result.getErrors() != null ? result.getErrors().get(0).getMessage() + : UINConstants.NULL_IDREPO_RESPONSE; + String message = result != null && result.getErrors() != null + ? result.getErrors().get(0).getMessage() + : UINConstants.NULL_IDREPO_RESPONSE; + description.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); + description.setStatusComment(trimExceptionMessage + .trimExceptionMessage(StatusUtil.UIN_DATA_UPDATION_FAILED.getMessage() + statusComment)); + description.setSubStatusCode(StatusUtil.UIN_DATA_UPDATION_FAILED.getCode()); + description + .setMessage(UINConstants.UIN_FAILURE + regId + "::" + message ); + description.setTransactionStatusCode(RegistrationTransactionStatusCode.PROCESSING.toString()); + object.setIsValid(Boolean.FALSE); + } + return isTransactionSuccessful; + } + + /** + * Id repo request builder. + * + * @param status the status + * @param id the reg id + * @param demographicIdentity the JSONObject + * @param documentInfo the document info + * @throws ApisResourceAccessException the apis resource access exception + * @throws IOException + * @throws IdrepoDraftReprocessableException + */ + private IdResponseDTO idRepoRequestBuilder(String id, String uin, String status, List documentInfo, + JSONObject demographicIdentity) + throws ApisResourceAccessException, IdrepoDraftException, IOException, IdrepoDraftReprocessableException { + IdResponseDTO idResponseDto; + RequestDto requestDto = new RequestDto(); + + if (documentInfo != null) + requestDto.setDocuments(documentInfo); + + requestDto.setRegistrationId(id); + requestDto.setStatus(status); + requestDto.setIdentity(demographicIdentity); + + IdRequestDto idRequestDTO = new IdRequestDto(); + idRequestDTO.setId(idRepoUpdate); + idRequestDTO.setMetadata(null); + idRequestDTO.setRequest(requestDto); + idRequestDTO.setRequesttime(DateUtils.getUTCCurrentDateTimeString()); + idRequestDTO.setVersion(UINConstants.idRepoApiVersion); + + try { + idResponseDto = idrepoDraftService.idrepoUpdateDraft(id, uin, idRequestDTO); + } catch (ApisResourceAccessException e) { + regProcLogger.error("Execption occured updating draft for id " + id, e); + if (e.getCause() instanceof HttpClientErrorException) { + regProcLogger.error("Exception occured updating draft for id " + id, e); + HttpClientErrorException httpClientException = (HttpClientErrorException) e.getCause(); + throw new ApisResourceAccessException(httpClientException.getResponseBodyAsString(), + httpClientException); + } else if (e.getCause() instanceof HttpServerErrorException) { + HttpServerErrorException httpServerException = (HttpServerErrorException) e.getCause(); + throw new ApisResourceAccessException(httpServerException.getResponseBodyAsString(), + httpServerException); + } else { + throw e; + } + + } + return idResponseDto; + } + + /** + * Re activate uin. + * + * @param id the reg id + * @param uin the uin + * @param object the object + * @param description + * @return the id response DTO + * @throws ApisResourceAccessException the apis resource access exception + * @throws IOException + * @throws IdrepoDraftReprocessableException + */ + private boolean reActivateUin(IdResponseDTO idResponseDTO, String id, String uin, MessageDTO object, + JSONObject demographicIdentity, LogDescription description) + throws ApisResourceAccessException, IOException, IdrepoDraftException, IdrepoDraftReprocessableException { + IdResponseDTO result = getIdRepoDataByUIN(uin, id, description); + List pathsegments = new ArrayList<>(); + RequestDto requestDto = new RequestDto(); + boolean isTransactionSuccessful = Boolean.FALSE; + + if (isIdResponseNotNull(result)) { + + if ((RegistrationType.ACTIVATED.toString()).equalsIgnoreCase(result.getResponse().getStatus())) { + + description.setStatusCode(RegistrationStatusCode.FAILED.toString()); + description.setStatusComment(StatusUtil.UIN_ALREADY_ACTIVATED.getMessage()); + description.setSubStatusCode(StatusUtil.UIN_ALREADY_ACTIVATED.getCode()); + description.setMessage(PlatformErrorMessages.UIN_ALREADY_ACTIVATED.getMessage()); + description.setCode(PlatformErrorMessages.UIN_ALREADY_ACTIVATED.getCode()); + description.setTransactionStatusCode(RegistrationTransactionStatusCode.FAILED.toString()); + object.setIsValid(Boolean.FALSE); + return isTransactionSuccessful; + + } else { + + requestDto.setRegistrationId(id); + requestDto.setStatus(RegistrationType.ACTIVATED.toString()); + requestDto.setBiometricReferenceId(uin); + requestDto.setIdentity(demographicIdentity); + + IdRequestDto idRequestDTO = new IdRequestDto(); + idRequestDTO.setId(idRepoUpdate); + idRequestDTO.setRequest(requestDto); + idRequestDTO.setMetadata(null); + idRequestDTO.setRequesttime(DateUtils.getUTCCurrentDateTimeString()); + idRequestDTO.setVersion(UINConstants.idRepoApiVersion); + + result = idrepoDraftService.idrepoUpdateDraft(id, uin, idRequestDTO); + + if (isIdResponseNotNull(result)) { + + if ((RegistrationType.ACTIVATED.toString()).equalsIgnoreCase(result.getResponse().getStatus())) { + isTransactionSuccessful = true; + description.setStatusCode(RegistrationStatusCode.PROCESSED.toString()); + description.setStatusComment(StatusUtil.UIN_ACTIVATED_SUCCESS.getMessage()); + description.setSubStatusCode(StatusUtil.UIN_ACTIVATED_SUCCESS.getCode()); + description.setMessage(StatusUtil.UIN_ACTIVATED_SUCCESS.getMessage() + id); + description.setMessage(PlatformSuccessMessages.RPR_UIN_ACTIVATED_SUCCESS.getMessage()); + description.setCode(PlatformSuccessMessages.RPR_UIN_ACTIVATED_SUCCESS.getCode()); + description.setTransactionStatusCode(RegistrationTransactionStatusCode.PROCESSED.toString()); + object.setIsValid(Boolean.TRUE); + } else { + description.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); + description.setStatusComment(StatusUtil.UIN_ACTIVATED_FAILED.getMessage()); + description.setSubStatusCode(StatusUtil.UIN_ACTIVATED_FAILED.getCode()); + description.setMessage(StatusUtil.UIN_ACTIVATED_FAILED.getMessage() + id); + description.setMessage(PlatformErrorMessages.UIN_ACTIVATED_FAILED.getMessage()); + description.setCode(PlatformErrorMessages.UIN_ACTIVATED_FAILED.getCode()); + description.setTransactionStatusCode(RegistrationTransactionStatusCode.REPROCESS.toString()); + object.setIsValid(Boolean.FALSE); + } + } else { + String statusComment = result != null && result.getErrors() != null + ? result.getErrors().get(0).getMessage() + : UINConstants.NULL_IDREPO_RESPONSE; + description.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); + description.setStatusComment(trimExceptionMessage + .trimExceptionMessage(StatusUtil.UIN_REACTIVATION_FAILED.getMessage() + statusComment)); + description.setSubStatusCode(StatusUtil.UIN_REACTIVATION_FAILED.getCode()); + description.setMessage( + UINConstants.UIN_FAILURE + id + "::" + (result != null && result.getErrors() != null + ? result.getErrors().get(0).getMessage() + : UINConstants.NULL_IDREPO_RESPONSE)); + description.setMessage(PlatformErrorMessages.UIN_REACTIVATION_FAILED.getMessage()); + description.setCode(PlatformErrorMessages.UIN_REACTIVATION_FAILED.getCode()); + description.setTransactionStatusCode(RegistrationTransactionStatusCode.REPROCESS.toString()); + object.setIsValid(Boolean.FALSE); + } + + } + + }else { + String statusComment = result != null && result.getErrors() != null + ? result.getErrors().get(0).getMessage() + : UINConstants.NULL_IDREPO_RESPONSE; + description.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); + description.setStatusComment(trimExceptionMessage + .trimExceptionMessage(StatusUtil.UIN_REACTIVATION_FAILED.getMessage() + statusComment)); + description.setSubStatusCode(StatusUtil.UIN_REACTIVATION_FAILED.getCode()); + description.setMessage( + UINConstants.UIN_FAILURE + id + "::" + (result != null && result.getErrors() != null + ? result.getErrors().get(0).getMessage() + : UINConstants.NULL_IDREPO_RESPONSE)); + description.setMessage(PlatformErrorMessages.UIN_REACTIVATION_FAILED.getMessage()); + description.setCode(PlatformErrorMessages.UIN_REACTIVATION_FAILED.getCode()); + description.setTransactionStatusCode(RegistrationTransactionStatusCode.REPROCESS.toString()); + object.setIsValid(Boolean.FALSE); + } + + return isTransactionSuccessful; + } + + private boolean isIdResponseNotNull(IdResponseDTO result) { + return result != null && result.getResponse() != null; + } + + private boolean isUinAlreadyPresent(IdResponseDTO result, String rid) { + if (result != null && result.getErrors() != null && result.getErrors().size() > 0 + && result.getErrors().get(0).getErrorCode().equalsIgnoreCase(RECORD_ALREADY_EXISTS_ERROR)) { + ErrorDTO errorDTO = result.getErrors().get(0); + regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString() + rid, + "Record is already present in IDREPO. Error message received : " + errorDTO.getMessage(), + "The stage will ignore this error and try to generate vid for the existing UIN now. " + + "This is to make sure if the packet processing fails while generating VID then re-processor can process the packet again"); + return true; + } + return false; + } + + /** + * Deactivate uin. + * + * @param id the reg id + * @param uin the uin + * @param object the object + * @param description + * @return the id response DTO + * @throws ApisResourceAccessException + * @throws IOException + * @throws IdrepoDraftReprocessableException + */ + private IdResponseDTO deactivateUin(String id, String uin, MessageDTO object, JSONObject demographicIdentity, + LogDescription description) + throws ApisResourceAccessException, IOException, IdrepoDraftException, IdrepoDraftReprocessableException { + IdResponseDTO idResponseDto; + RequestDto requestDto = new RequestDto(); + String statusComment = ""; + + idResponseDto = getIdRepoDataByUIN(uin, id, description); + + if (idResponseDto.getResponse() != null + && idResponseDto.getResponse().getStatus().equalsIgnoreCase(RegistrationType.DEACTIVATED.toString())) { + description.setStatusCode(RegistrationStatusCode.FAILED.toString()); + description.setStatusComment(StatusUtil.UIN_ALREADY_DEACTIVATED.getMessage()); + description.setSubStatusCode(StatusUtil.UIN_ALREADY_DEACTIVATED.getCode()); + description.setMessage(StatusUtil.UIN_ALREADY_DEACTIVATED.getMessage() + id); + description.setMessage(PlatformErrorMessages.UIN_ALREADY_DEACTIVATED.getMessage()); + description.setCode(PlatformErrorMessages.UIN_ALREADY_DEACTIVATED.getCode()); + description.setTransactionStatusCode(RegistrationTransactionStatusCode.FAILED.toString()); + object.setIsValid(Boolean.FALSE); + return idResponseDto; + + } else { + requestDto.setRegistrationId(id); + requestDto.setStatus(RegistrationType.DEACTIVATED.toString()); + requestDto.setIdentity(demographicIdentity); + requestDto.setBiometricReferenceId(uin); + + IdRequestDto idRequestDTO = new IdRequestDto(); + idRequestDTO.setId(idRepoUpdate); + idRequestDTO.setMetadata(null); + idRequestDTO.setRequest(requestDto); + idRequestDTO.setRequesttime(DateUtils.getUTCCurrentDateTimeString()); + idRequestDTO.setVersion(UINConstants.idRepoApiVersion); + + idResponseDto = idrepoDraftService.idrepoUpdateDraft(id, uin, idRequestDTO); + + if (isIdResponseNotNull(idResponseDto)) { + if (idResponseDto.getResponse().getStatus().equalsIgnoreCase(RegistrationType.DEACTIVATED.toString())) { + description.setStatusCode(RegistrationStatusCode.PROCESSED.toString()); + description.setStatusComment(StatusUtil.UIN_DEACTIVATION_SUCCESS.getMessage()); + description.setSubStatusCode(StatusUtil.UIN_DEACTIVATION_SUCCESS.getCode()); + description.setMessage(StatusUtil.UIN_DEACTIVATION_SUCCESS.getMessage() + id); + description.setMessage(PlatformSuccessMessages.RPR_UIN_DEACTIVATION_SUCCESS.getMessage()); + description.setCode(PlatformSuccessMessages.RPR_UIN_DEACTIVATION_SUCCESS.getCode()); + description.setTransactionStatusCode(RegistrationTransactionStatusCode.PROCESSED.toString()); + object.setIsValid(Boolean.TRUE); + statusComment = idResponseDto.getResponse().getStatus().toString(); + + } + } else { + + statusComment = idResponseDto != null && idResponseDto.getErrors() != null + ? idResponseDto.getErrors().get(0).getMessage() + : UINConstants.NULL_IDREPO_RESPONSE; + description.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); + description.setStatusComment(trimExceptionMessage + .trimExceptionMessage(StatusUtil.UIN_DEACTIVATION_FAILED.getMessage() + statusComment)); + description.setSubStatusCode(StatusUtil.UIN_DEACTIVATION_FAILED.getCode()); + description.setMessage(PlatformErrorMessages.UIN_DEACTIVATION_FAILED.getMessage()); + description.setCode(PlatformErrorMessages.UIN_DEACTIVATION_FAILED.getCode()); + description.setTransactionStatusCode(RegistrationTransactionStatusCode.REPROCESS.toString()); + object.setIsValid(Boolean.FALSE); + } + + } + regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString() + id, "Updated Response from IdRepo API", + "is : " + statusComment); + + return idResponseDto; + } + + /** + * Gets the id repo data by UIN. + * + * @param uin + * the uin + * @param description + * @return the id repo data by UIN + * @throws ApisResourceAccessException + * the apis resource access exception + * @throws IOException + */ + private IdResponseDTO getIdRepoDataByUIN(String uin, String regId, LogDescription description) + throws ApisResourceAccessException { + IdResponseDTO response; + + List pathsegments = new ArrayList<>(); + pathsegments.add(uin); + try { + + response = (IdResponseDTO) registrationProcessorRestClientService.getApi(ApiName.IDREPOGETIDBYUIN, + pathsegments, "", "", IdResponseDTO.class); + + } catch (ApisResourceAccessException e) { + if (e.getCause() instanceof HttpClientErrorException) { + HttpClientErrorException httpClientException = (HttpClientErrorException) e.getCause(); + description.setMessage(PlatformErrorMessages.UIN_GENERATION_FAILED.getMessage()); + description.setCode(PlatformErrorMessages.UIN_GENERATION_FAILED.getCode()); + throw new ApisResourceAccessException(httpClientException.getResponseBodyAsString(), + httpClientException); + } else if (e.getCause() instanceof HttpServerErrorException) { + HttpServerErrorException httpServerException = (HttpServerErrorException) e.getCause(); + description.setMessage(PlatformErrorMessages.UIN_GENERATION_FAILED.getMessage()); + description.setCode(PlatformErrorMessages.UIN_GENERATION_FAILED.getCode()); + + throw new ApisResourceAccessException(httpServerException.getResponseBodyAsString(), + httpServerException); + } else { + description.setMessage(PlatformErrorMessages.UIN_GENERATION_FAILED.getMessage()); + description.setCode(PlatformErrorMessages.UIN_GENERATION_FAILED.getCode()); + throw e; + } + } + return response; + } + + /** + * Deploy verticle. + */ + public void deployVerticle() { + + mosipEventBus = this.getEventBus(this, clusterManagerUrl, workerPoolSize); + this.consumeAndSend(mosipEventBus, MessageBusAddress.UIN_GENERATION_BUS_IN, + MessageBusAddress.UIN_GENERATION_BUS_OUT, messageExpiryTimeLimit); + } + + @Override + public void start() { + router.setRoute(this.postUrl(getVertx(), MessageBusAddress.UIN_GENERATION_BUS_IN, + MessageBusAddress.UIN_GENERATION_BUS_OUT)); + this.createServer(router.getRouter(), getPort()); + + } + + @Override + protected String getPropertyPrefix() { + return STAGE_PROPERTY_PREFIX; + } + + /** + * Link reg id wrt uin. + * + * @param lostPacketRegId the lost packet reg id + * @param matchedRegId the matched reg id + * @param object the object + * @param description + * @return the id response DTO + * @throws ApisResourceAccessException the apis resource access exception + * @throws IOException Signals that an I/O exception has + * occurred. + * @throws IdrepoDraftReprocessableException + */ + @SuppressWarnings("unchecked") + private IdResponseDTO lostAndUpdateUin(String lostPacketRegId, String matchedRegId, String process, MessageDTO object, + LogDescription description) throws ApisResourceAccessException, IOException, + io.mosip.kernel.core.util.exception.JsonProcessingException, PacketManagerException, IdrepoDraftException, + IdrepoDraftReprocessableException { + + IdResponseDTO idResponse = null; + String uin = idRepoService.getUinByRid(matchedRegId, utility.getGetRegProcessorDemographicIdentity()); + + + RequestDto requestDto = new RequestDto(); + String statusComment = ""; + + if (uin != null) { + + JSONObject regProcessorIdentityJson = utility.getRegistrationProcessorMappingJson(MappingJsonConstants.IDENTITY); + String idschemaversion = JsonUtil.getJSONValue(JsonUtil.getJSONObject(regProcessorIdentityJson, MappingJsonConstants.IDSCHEMA_VERSION), MappingJsonConstants.VALUE); + + JSONObject identityObject = new JSONObject(); + identityObject.put(UINConstants.UIN, uin); + String schemaVersion = packetManagerService.getFieldByMappingJsonKey(lostPacketRegId, MappingJsonConstants.IDSCHEMA_VERSION, process, ProviderStageName.UIN_GENERATOR); + identityObject.put(idschemaversion, convertIdschemaToDouble ? Double.valueOf(schemaVersion) : schemaVersion); + regProcLogger.info("Fields to be updated "+updateInfo); + if (null != updateInfo && !updateInfo.isEmpty()) { + String[] upd = updateInfo.split(","); + for (String infoField : upd) { + String fldValue = packetManagerService.getField(lostPacketRegId, infoField, process, + ProviderStageName.UIN_GENERATOR); + if (null != fldValue) + identityObject.put(infoField, fldValue); + } + } + requestDto.setRegistrationId(lostPacketRegId); + requestDto.setIdentity(identityObject); + + IdRequestDto idRequestDTO = new IdRequestDto(); + idRequestDTO.setId(idRepoUpdate); + idRequestDTO.setRequest(requestDto); + idRequestDTO.setMetadata(null); + idRequestDTO.setRequesttime(DateUtils.getUTCCurrentDateTimeString()); + idRequestDTO.setVersion(UINConstants.idRepoApiVersion); + + idResponse = idrepoDraftService.idrepoUpdateDraft(lostPacketRegId, uin, idRequestDTO); + + if (isIdResponseNotNull(idResponse)) { + description.setStatusCode(RegistrationStatusCode.PROCESSED.toString()); + description.setStatusComment(StatusUtil.LINK_RID_FOR_LOST_PACKET_SUCCESS.getMessage()); + description.setSubStatusCode(StatusUtil.LINK_RID_FOR_LOST_PACKET_SUCCESS.getCode()); + description.setMessage(UinStatusMessage.PACKET_LOST_UIN_UPDATION_SUCCESS_MSG + lostPacketRegId); + description.setTransactionStatusCode(RegistrationTransactionStatusCode.PROCESSED.toString()); + object.setIsValid(Boolean.TRUE); + + regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString() + lostPacketRegId, + " UIN LINKED WITH " + matchedRegId, "is : " + description); + } else { + + statusComment = idResponse != null && idResponse.getErrors() != null + && idResponse.getErrors().get(0) != null ? idResponse.getErrors().get(0).getMessage() + : UinStatusMessage.PACKET_LOST_UIN_UPDATION_FAILURE_MSG + " " + + UINConstants.NULL_IDREPO_RESPONSE + "for lostPacketRegId " + lostPacketRegId; + description.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); + description.setStatusComment(StatusUtil.LINK_RID_FOR_LOST_PACKET_SUCCESS.getMessage() + statusComment); + description.setSubStatusCode(StatusUtil.LINK_RID_FOR_LOST_PACKET_SUCCESS.getCode()); + description.setTransactionStatusCode(registrationStatusMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.PACKET_UIN_GENERATION_ID_REPO_ERROR)); + if (idResponse != null + && idResponse.getErrors() != null) + description.setMessage(idResponse.getErrors().get(0).getMessage()); + else + description.setMessage(UINConstants.NULL_IDREPO_RESPONSE); + object.setIsValid(Boolean.FALSE); + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString() + lostPacketRegId, + " UIN NOT LINKED WITH " + matchedRegId, "is : " + statusComment); + } + + } else { + statusComment = UinStatusMessage.PACKET_LOST_UIN_UPDATION_FAILURE_MSG + " " + + UINConstants.NULL_IDREPO_RESPONSE + " UIN not available for matchedRegId " + matchedRegId; + description.setStatusComment(StatusUtil.LINK_RID_FOR_LOST_PACKET_FAILED.getMessage()); + description.setSubStatusCode(StatusUtil.LINK_RID_FOR_LOST_PACKET_FAILED.getCode()); + description.setStatusCode(RegistrationStatusCode.PROCESSING.toString()); + description.setTransactionStatusCode(registrationStatusMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.PACKET_UIN_GENERATION_REPROCESS)); + description.setMessage(UinStatusMessage.PACKET_LOST_UIN_UPDATION_FAILURE_MSG + " " + + UINConstants.NULL_IDREPO_RESPONSE + " UIN not available for matchedRegId " + matchedRegId); + + object.setIsValid(Boolean.FALSE); + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString() + lostPacketRegId, + " UIN NOT LINKED WITH " + matchedRegId, "is : " + statusComment); + } + + return idResponse; + } + + private void updateErrorFlags(InternalRegistrationStatusDto registrationStatusDto, MessageDTO object) { + object.setInternalError(true); + if (registrationStatusDto.getLatestTransactionStatusCode() + .equalsIgnoreCase(RegistrationTransactionStatusCode.REPROCESS.toString())) { + object.setIsValid(true); + } else { + object.setIsValid(false); + } + } +} diff --git a/registration-processor/core-processor/registration-processor-uin-generator-stage/src/test/java/io/mosip/registration/processor/stages/uigenerator/UinGeneratorStageTest.java b/registration-processor/core-processor/registration-processor-uin-generator-stage/src/test/java/io/mosip/registration/processor/stages/uigenerator/UinGeneratorStageTest.java index 933b45eeb93..b57952a8d2a 100644 --- a/registration-processor/core-processor/registration-processor-uin-generator-stage/src/test/java/io/mosip/registration/processor/stages/uigenerator/UinGeneratorStageTest.java +++ b/registration-processor/core-processor/registration-processor-uin-generator-stage/src/test/java/io/mosip/registration/processor/stages/uigenerator/UinGeneratorStageTest.java @@ -85,6 +85,7 @@ import io.mosip.registration.processor.packet.manager.dto.IdResponseDTO; import io.mosip.registration.processor.packet.manager.dto.ResponseDTO; import io.mosip.registration.processor.packet.manager.exception.IdrepoDraftException; +import io.mosip.registration.processor.packet.manager.exception.IdrepoDraftReprocessableException; import io.mosip.registration.processor.packet.manager.idreposervice.IdRepoService; import io.mosip.registration.processor.packet.manager.idreposervice.IdrepoDraftService; import io.mosip.registration.processor.packet.storage.dto.ApplicantInfoDto; @@ -969,7 +970,8 @@ public void testApiResourceExceptionInUpdateIdRepoTest() throws Exception { } @Test - public void deactivateTestSuccess() throws ApisResourceAccessException, IOException, JSONException, JsonProcessingException, PacketManagerException, IdrepoDraftException { + public void deactivateTestSuccess() throws ApisResourceAccessException, IOException, JSONException, + JsonProcessingException, PacketManagerException, IdrepoDraftException, IdrepoDraftReprocessableException { Map fieldMap = new HashMap<>(); fieldMap.put("UIN", "123456"); @@ -1056,7 +1058,8 @@ public void checkIsUinDeactivatedSuccess() throws ApisResourceAccessException, I assertFalse(result.getInternalError()); } @Test - public void deactivateTestWithDeactivate() throws ApisResourceAccessException, IOException, JSONException, JsonProcessingException, PacketManagerException, IdrepoDraftException { + public void deactivateTestWithDeactivate() throws ApisResourceAccessException, IOException, JSONException, + JsonProcessingException, PacketManagerException, IdrepoDraftException, IdrepoDraftReprocessableException { Map fieldMap = new HashMap<>(); fieldMap.put("UIN", "123456"); fieldMap.put("name", "mono"); @@ -1105,7 +1108,9 @@ public void deactivateTestWithDeactivate() throws ApisResourceAccessException, I } @Test - public void deactivateTestWithNullResponseDTO() throws ApisResourceAccessException, PacketManagerException, IOException, JsonProcessingException, JSONException, IdrepoDraftException { + public void deactivateTestWithNullResponseDTO() + throws ApisResourceAccessException, PacketManagerException, IOException, JsonProcessingException, + JSONException, IdrepoDraftException, IdrepoDraftReprocessableException { Map fieldMap = new HashMap<>(); fieldMap.put("UIN", "123456"); fieldMap.put("name", "mono"); @@ -1152,7 +1157,9 @@ public void deactivateTestWithNullResponseDTO() throws ApisResourceAccessExcepti } @Test - public void deactivateTestForExistingUinTestSuccess() throws ApisResourceAccessException, PacketManagerException, IOException, JsonProcessingException, JSONException, IdrepoDraftException { + public void deactivateTestForExistingUinTestSuccess() + throws ApisResourceAccessException, PacketManagerException, IOException, JsonProcessingException, + JSONException, IdrepoDraftException, IdrepoDraftReprocessableException { MessageDTO messageDTO = new MessageDTO(); messageDTO.setRid("10031100110005020190313110030"); messageDTO.setReg_type(RegistrationType.valueOf("DEACTIVATED").name()); @@ -1202,7 +1209,8 @@ public void deactivateTestForExistingUinTestSuccess() throws ApisResourceAccessE } @Test - public void deactivateTestFailure() throws ApisResourceAccessException, PacketManagerException, IOException, JsonProcessingException, JSONException, IdrepoDraftException { + public void deactivateTestFailure() throws ApisResourceAccessException, PacketManagerException, IOException, + JsonProcessingException, JSONException, IdrepoDraftException, IdrepoDraftReprocessableException { Map fieldMap = new HashMap<>(); fieldMap.put("UIN", "123456"); @@ -1262,7 +1270,8 @@ public void deactivateTestFailure() throws ApisResourceAccessException, PacketMa } @Test - public void apisResourceAccessExceptionTest() throws ApisResourceAccessException, IOException, IdrepoDraftException { + public void apisResourceAccessExceptionTest() + throws ApisResourceAccessException, IOException, IdrepoDraftException, IdrepoDraftReprocessableException { ApisResourceAccessException apisResourceAccessException = Mockito.mock(ApisResourceAccessException.class); HttpServerErrorException httpServerErrorException = new HttpServerErrorException( @@ -1379,7 +1388,8 @@ public void testUinGenerationHttpServerErrorException() throws Exception { @Test - public void clientErrorExceptionTest() throws ApisResourceAccessException, IOException, IdrepoDraftException { + public void clientErrorExceptionTest() + throws ApisResourceAccessException, IOException, IdrepoDraftException, IdrepoDraftReprocessableException { ApisResourceAccessException apisResourceAccessException = Mockito.mock(ApisResourceAccessException.class); HttpClientErrorException httpErrorErrorException = new HttpClientErrorException( @@ -1423,7 +1433,8 @@ public void testDeployVerticle() { @Test @Ignore - public void testApiResourceException() throws ApisResourceAccessException, IOException, IdrepoDraftException { + public void testApiResourceException() + throws ApisResourceAccessException, IOException, IdrepoDraftException, IdrepoDraftReprocessableException { MessageDTO messageDTO = new MessageDTO(); messageDTO.setRid("10031100110005020190313110030"); messageDTO.setReg_type(RegistrationType.valueOf("DEACTIVATED").name()); @@ -1451,7 +1462,8 @@ public void testApiResourceException() throws ApisResourceAccessException, IOExc } @Test - public void testApisResourceAccessExceptionPostApi() throws ApisResourceAccessException, IOException, IdrepoDraftException { + public void testApisResourceAccessExceptionPostApi() + throws ApisResourceAccessException, IOException, IdrepoDraftException, IdrepoDraftReprocessableException { ApisResourceAccessException exc = new ApisResourceAccessException(); MessageDTO messageDTO = new MessageDTO(); messageDTO.setRid("27847657360002520181210094052"); @@ -1585,7 +1597,8 @@ public void testLinkSuccessForLostUinAndUpdateContactInfo() throws Exception { } @Test - public void updateTestSuccess() throws ApisResourceAccessException, IOException, JsonProcessingException, PacketManagerException, JSONException, IdrepoDraftException { + public void updateTestSuccess() throws ApisResourceAccessException, IOException, JsonProcessingException, + PacketManagerException, JSONException, IdrepoDraftException, IdrepoDraftReprocessableException { Map fieldMap = new HashMap<>(); fieldMap.put("UIN", "123456"); fieldMap.put("name", "mono"); @@ -1980,7 +1993,8 @@ public void testUinReActivationWithoutIDResponseDTO() throws Exception { @Test public void deactivateTestWithNullResponseDTOBeforeDeactivate() throws ApisResourceAccessException, PacketManagerException, - IOException, JsonProcessingException, JSONException, IdrepoDraftException { + IOException, JsonProcessingException, JSONException, IdrepoDraftException, + IdrepoDraftReprocessableException { Map fieldMap = new HashMap<>(); fieldMap.put("UIN", "123456"); fieldMap.put("name", "mono"); @@ -2029,7 +2043,8 @@ public void deactivateTestWithNullResponseDTOBeforeDeactivate() throws ApisResou @Test public void deactivateTesApiResourceClientException() throws ApisResourceAccessException, PacketManagerException, - IOException, JsonProcessingException, JSONException, IdrepoDraftException { + IOException, JsonProcessingException, JSONException, IdrepoDraftException, + IdrepoDraftReprocessableException { Map fieldMap = new HashMap<>(); fieldMap.put("UIN", "123456"); fieldMap.put("name", "mono"); @@ -2079,7 +2094,8 @@ public void deactivateTesApiResourceClientException() throws ApisResourceAccessE @Test public void deactivateTesApiResourceServerException() throws ApisResourceAccessException, PacketManagerException, - IOException, JsonProcessingException, JSONException, IdrepoDraftException { + IOException, JsonProcessingException, JSONException, IdrepoDraftException, + IdrepoDraftReprocessableException { Map fieldMap = new HashMap<>(); fieldMap.put("UIN", "123456"); fieldMap.put("name", "mono"); @@ -2127,7 +2143,8 @@ public void deactivateTesApiResourceServerException() throws ApisResourceAccessE @Test public void deactivateTesApiResourceException() throws ApisResourceAccessException, PacketManagerException, - IOException, JsonProcessingException, JSONException, IdrepoDraftException { + IOException, JsonProcessingException, JSONException, IdrepoDraftException, + IdrepoDraftReprocessableException { Map fieldMap = new HashMap<>(); fieldMap.put("UIN", "123456"); fieldMap.put("name", "mono"); @@ -2175,7 +2192,8 @@ public void deactivateTesApiResourceException() throws ApisResourceAccessExcepti @Test public void deactivateTestAlreadyDeactivated() throws ApisResourceAccessException, PacketManagerException, - IOException, JsonProcessingException, JSONException, IdrepoDraftException { + IOException, JsonProcessingException, JSONException, IdrepoDraftException, + IdrepoDraftReprocessableException { Map fieldMap = new HashMap<>(); fieldMap.put("UIN", "123456"); fieldMap.put("name", "mono"); @@ -2224,7 +2242,8 @@ public void deactivateTestAlreadyDeactivated() throws ApisResourceAccessExceptio } @Test - public void testUinAlreadyDeactivated() throws ApisResourceAccessException, PacketManagerException, IOException, JsonProcessingException, JSONException, IdrepoDraftException { + public void testUinAlreadyDeactivated() throws ApisResourceAccessException, PacketManagerException, IOException, + JsonProcessingException, JSONException, IdrepoDraftException, IdrepoDraftReprocessableException { Map fieldsMap = new HashMap<>(); fieldsMap.put("UIN", "123456"); fieldsMap.put("name", "mono"); @@ -2394,5 +2413,23 @@ public void testUinUpdationIOExceptionFaliure() throws Exception { assertTrue(result.getInternalError()); assertTrue(result.getIsValid()); } - + + @Test + public void testUinGenerationIDRepoDraftReprocessableException() throws Exception { + MessageDTO messageDTO = new MessageDTO(); + messageDTO.setRid("27847657360002520181210094052"); + messageDTO.setReg_type(RegistrationType.NEW.name()); + + when(registrationStatusMapperUtil + .getStatusCode(RegistrationExceptionTypeCode.IDREPO_DRAFT_REPROCESSABLE_EXCEPTION)) + .thenReturn("REPROCESS"); + when(idrepoDraftService.idrepoUpdateDraft(anyString(), any(), any())) + .thenThrow(IdrepoDraftReprocessableException.class); + when(utility.getRegistrationProcessorMappingJson(MappingJsonConstants.IDENTITY)).thenReturn(identityObj); + when(utility.getRegistrationProcessorMappingJson(MappingJsonConstants.DOCUMENT)).thenReturn(documentObj); + + MessageDTO result = uinGeneratorStage.process(messageDTO); + assertTrue(result.getInternalError()); + assertTrue(result.getIsValid()); + } } \ No newline at end of file diff --git a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/code/RegistrationExceptionTypeCode.java b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/code/RegistrationExceptionTypeCode.java index eea08d9c6d0..b1f839ff817 100644 --- a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/code/RegistrationExceptionTypeCode.java +++ b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/code/RegistrationExceptionTypeCode.java @@ -301,6 +301,9 @@ public enum RegistrationExceptionTypeCode { NO_RECORDS_ASSIGNED, MANUAL_VERIFICATION_FAILED, - INTRODUCER_BIOMETRIC_ALL_EXCEPTION_IN_PACKET; + INTRODUCER_BIOMETRIC_ALL_EXCEPTION_IN_PACKET, + + + IDREPO_DRAFT_REPROCESSABLE_EXCEPTION; } \ No newline at end of file diff --git a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/status/util/StatusUtil.java b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/status/util/StatusUtil.java index 7d3910b450f..768420770d7 100644 --- a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/status/util/StatusUtil.java +++ b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/status/util/StatusUtil.java @@ -251,18 +251,33 @@ public enum StatusUtil { IDREPO_DRAFT_EXCEPTION(StatusConstants.UIN_GENERATOR_MODULE_FAILED + "008", "Exception occured updating idrepo draft."), + IDREPO_DRAFT_REPROCESSABLE_EXCEPTION(StatusConstants.UIN_GENERATOR_MODULE_FAILED + "009", + "Exception occured updating idrepo draft, which can be reprocessed"), + // Biometric extraction stage BIOMETRIC_EXTRACTION_SUCCESS(StatusConstants.BIOMETRIC_EXTRACTION_MODULE_SUCCESS + "001", "biometric extaction was successful"), BIOMETRIC_EXTRACTION_DRAFT_REQUEST_UNAVAILABLE(StatusConstants.BIOMETRIC_EXTRACTION_MODULE_FAILED + "001", "Draft request is unavaialble in id-repo draft repository."), + BIOMETRIC_EXTRACTION_IDREPO_DRAFT_EXCEPTION(StatusConstants.BIOMETRIC_EXTRACTION_MODULE_FAILED + "002", + "Exception occured updating idrepo draft."), + + BIOMETRIC_EXTRACTION_IDREPO_DRAFT_REPROCESSABLE_EXCEPTION( + StatusConstants.BIOMETRIC_EXTRACTION_MODULE_FAILED + "003", + "Exception occured updating idrepo draft, which can be reprocessed"), FINALIZATION_SUCCESS(StatusConstants.FINALIZATION_MODULE_SUCCESS + "001", "idrepo draft was published successfuly"), FINALIZATION_FAILURE(StatusConstants.FINALIZATION_MODULE_FAILED + "001", "Draft request failed to publish."), - FINALIZATION_DRAFT_REQUEST_UNAVAILABLE(StatusConstants.FINALIZATION_MODULE_FAILED + "001", + FINALIZATION_DRAFT_REQUEST_UNAVAILABLE(StatusConstants.FINALIZATION_MODULE_FAILED + "002", "Draft request is unavaialble in id-repo draft repository."), + FINALIZATION_IDREPO_DRAFT_EXCEPTION(StatusConstants.FINALIZATION_MODULE_FAILED + "003", + "Exception occured updating idrepo draft."), + + FINALIZATION_IDREPO_DRAFT_REPROCESSABLE_EXCEPTION(StatusConstants.FINALIZATION_MODULE_FAILED + "004", + "Exception occured updating idrepo draft, which can be reprocessed"), + // Request handler service // 1)Resident UIN update RESIDENT_UPDATE_SUCCES(StatusConstants.REQUEST_HANDLER_MODULE_SUCCESS + "001", diff --git a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/util/RegistrationExceptionMapperUtil.java b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/util/RegistrationExceptionMapperUtil.java index 88d926adb88..853370d43a1 100644 --- a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/util/RegistrationExceptionMapperUtil.java +++ b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/util/RegistrationExceptionMapperUtil.java @@ -195,6 +195,8 @@ private static Map registrationProcessorRestClientService; - - public boolean idrepoHasDraft(String id) throws ApisResourceAccessException, IdrepoDraftException { - regProcLogger.debug("idrepoHasDraft entry " + id); - - Integer result = registrationProcessorRestClientService.headApi - (ApiName.IDREPOHASDRAFT, Lists.newArrayList(id), null, null); - - if (result == null || (result.intValue() != IDREPO_DRAFT_FOUND && result.intValue() != IDREPO_DRAFT_NOT_FOUND)) { - regProcLogger.error("idrepoHasDraft failed to get result for id " + id + " result received is " + result); - throw new IdrepoDraftException(PlatformErrorMessages.DRAFT_CHECK_FAILED.getCode(), PlatformErrorMessages.DRAFT_CHECK_FAILED.getMessage()); - } - - boolean hasDraft = result != null && result.intValue() == IDREPO_DRAFT_FOUND; - regProcLogger.info("idrepoHasDraft result for id " + id + " is " + hasDraft); - return hasDraft; - } - - public ResponseDTO idrepoGetDraft(String id) throws ApisResourceAccessException { - regProcLogger.debug("idrepoGetDraft entry " + id); - IdResponseDTO idResponseDTO = (IdResponseDTO) registrationProcessorRestClientService.getApi( - ApiName.IDREPOGETDRAFT, Lists.newArrayList(id), Lists.emptyList(), null, IdResponseDTO.class); - - regProcLogger.debug("idrepoGetDraft exit " + id); - return idResponseDTO.getResponse(); - } - - public boolean idrepoCreateDraft(String id, String uin) throws ApisResourceAccessException { - regProcLogger.debug("idrepoCreateDraft entry " + id); - String queryParam = uin != null ? UIN : null; - String queryParamValue = uin != null ? uin : null; - - ResponseWrapper response = (ResponseWrapper) registrationProcessorRestClientService.postApi( - ApiName.IDREPOCREATEDRAFT, Lists.newArrayList(id), queryParam, queryParamValue, null, ResponseWrapper.class); - - return (response.getErrors() == null || response.getErrors().isEmpty()); - } - - public IdResponseDTO idrepoUpdateDraft(String id, String uin, IdRequestDto idRequestDto) throws ApisResourceAccessException, IdrepoDraftException, IOException { - regProcLogger.debug("idrepoUpdateDraft entry " + id); - if (!idrepoHasDraft(id)) { - regProcLogger.info("Existing draft not found for id " + id + ". Creating new draft."); - idrepoCreateDraft(id, uin); - } else { - regProcLogger.info("Existing draft found for id " + id + ". Updating uin in demographic identity."); - ResponseDTO responseDTO = idrepoGetDraft(id); - RequestDto requestDto = new RequestDto(); - requestDto.setAnonymousProfile(responseDTO.getAnonymousProfile()); - requestDto.setBiometricReferenceId(responseDTO.getBiometricReferenceId()); - JSONObject existingIdentity = mapper.readValue(mapper.writeValueAsString(responseDTO.getIdentity()), JSONObject.class); - JSONObject newIdentity = mapper.readValue(mapper.writeValueAsString(idRequestDto.getRequest().getIdentity()), JSONObject.class); - newIdentity.put(UIN, existingIdentity.get(UIN)); - idRequestDto.getRequest().setIdentity(newIdentity); - requestDto.setRegistrationId(responseDTO.getRegistrationId()); - requestDto.setStatus(responseDTO.getStatus()); - requestDto.setUin(responseDTO.getUin()); - idRequestDto.setRequest(requestDto); - - } - - IdResponseDTO response = (IdResponseDTO) registrationProcessorRestClientService.patchApi( - ApiName.IDREPOUPDATEDRAFT, Lists.newArrayList(id), null, null, idRequestDto, IdResponseDTO.class); - if (response.getErrors() != null && !response.getErrors().isEmpty()) { - regProcLogger.error("Error occured while updating draft for id : " + id, response.getErrors().iterator().next().toString()); - throw new IdrepoDraftException(response.getErrors().iterator().next().getErrorCode(), - response.getErrors().iterator().next().getMessage()); - } - - regProcLogger.debug("idrepoUpdateDraft exit " + id); - return response; - } - - public IdResponseDTO idrepoPublishDraft(String id) throws ApisResourceAccessException, IdrepoDraftException { - regProcLogger.debug("idrepoPublishDraft entry " + id); - List pathsegments=new ArrayList(); - pathsegments.add(id); - IdResponseDTO response = (IdResponseDTO) registrationProcessorRestClientService. - getApi(ApiName.IDREPOPUBLISHDRAFT, pathsegments, "", "", IdResponseDTO.class); - if (response.getErrors() != null && !response.getErrors().isEmpty()) { - regProcLogger.error("Error occured while updating draft for id : " + id, response.getErrors().iterator().next().toString()); - throw new IdrepoDraftException(response.getErrors().iterator().next().getErrorCode(), - response.getErrors().iterator().next().getMessage()); - } - - regProcLogger.debug("idrepoPublishDraft exit " + id); - return response; - } -} +package io.mosip.registration.processor.packet.manager.idreposervice; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import org.assertj.core.util.Lists; +import org.json.simple.JSONObject; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import com.fasterxml.jackson.databind.ObjectMapper; + +import io.mosip.kernel.core.logger.spi.Logger; +import io.mosip.registration.processor.core.code.ApiName; +import io.mosip.registration.processor.core.common.rest.dto.ErrorDTO; +import io.mosip.registration.processor.core.exception.ApisResourceAccessException; +import io.mosip.registration.processor.core.exception.util.PlatformErrorMessages; +import io.mosip.registration.processor.core.http.ResponseWrapper; +import io.mosip.registration.processor.core.logger.RegProcessorLogger; +import io.mosip.registration.processor.core.spi.restclient.RegistrationProcessorRestClientService; +import io.mosip.registration.processor.packet.manager.dto.IdRequestDto; +import io.mosip.registration.processor.packet.manager.dto.IdResponseDTO; +import io.mosip.registration.processor.packet.manager.dto.RequestDto; +import io.mosip.registration.processor.packet.manager.dto.ResponseDTO; +import io.mosip.registration.processor.packet.manager.exception.IdrepoDraftException; +import io.mosip.registration.processor.packet.manager.exception.IdrepoDraftReprocessableException; + +@Service +public class IdrepoDraftService { + + private static final String UIN = "UIN"; + private static final Integer IDREPO_DRAFT_FOUND = 200; + private static final Integer IDREPO_DRAFT_NOT_FOUND = 204; + private static Logger regProcLogger = RegProcessorLogger.getLogger(IdrepoDraftService.class); + private static final String ID_REPO_KEY_MANAGER_ERROR = "IDR-IDS-003"; + + @Autowired + private ObjectMapper mapper; + + /** The registration processor rest client service. */ + @Autowired + private RegistrationProcessorRestClientService registrationProcessorRestClientService; + + public boolean idrepoHasDraft(String id) throws ApisResourceAccessException, IdrepoDraftException { + regProcLogger.debug("idrepoHasDraft entry " + id); + + Integer result = registrationProcessorRestClientService.headApi + (ApiName.IDREPOHASDRAFT, Lists.newArrayList(id), null, null); + + if (result == null || (result.intValue() != IDREPO_DRAFT_FOUND && result.intValue() != IDREPO_DRAFT_NOT_FOUND)) { + regProcLogger.error("idrepoHasDraft failed to get result for id " + id + " result received is " + result); + throw new IdrepoDraftException(PlatformErrorMessages.DRAFT_CHECK_FAILED.getCode(), PlatformErrorMessages.DRAFT_CHECK_FAILED.getMessage()); + } + + boolean hasDraft = result != null && result.intValue() == IDREPO_DRAFT_FOUND; + regProcLogger.info("idrepoHasDraft result for id " + id + " is " + hasDraft); + return hasDraft; + } + + public ResponseDTO idrepoGetDraft(String id) throws ApisResourceAccessException { + regProcLogger.debug("idrepoGetDraft entry " + id); + IdResponseDTO idResponseDTO = (IdResponseDTO) registrationProcessorRestClientService.getApi( + ApiName.IDREPOGETDRAFT, Lists.newArrayList(id), Lists.emptyList(), null, IdResponseDTO.class); + + regProcLogger.debug("idrepoGetDraft exit " + id); + return idResponseDTO.getResponse(); + } + + public boolean idrepoCreateDraft(String id, String uin) throws ApisResourceAccessException { + regProcLogger.debug("idrepoCreateDraft entry " + id); + String queryParam = uin != null ? UIN : null; + String queryParamValue = uin != null ? uin : null; + + ResponseWrapper response = (ResponseWrapper) registrationProcessorRestClientService.postApi( + ApiName.IDREPOCREATEDRAFT, Lists.newArrayList(id), queryParam, queryParamValue, null, ResponseWrapper.class); + + return (response.getErrors() == null || response.getErrors().isEmpty()); + } + + public IdResponseDTO idrepoUpdateDraft(String id, String uin, IdRequestDto idRequestDto) + throws ApisResourceAccessException, IdrepoDraftException, IOException, IdrepoDraftReprocessableException { + regProcLogger.debug("idrepoUpdateDraft entry " + id); + if (!idrepoHasDraft(id)) { + regProcLogger.info("Existing draft not found for id " + id + ". Creating new draft."); + idrepoCreateDraft(id, uin); + } else { + regProcLogger.info("Existing draft found for id " + id + ". Updating uin in demographic identity."); + ResponseDTO responseDTO = idrepoGetDraft(id); + RequestDto requestDto = new RequestDto(); + requestDto.setAnonymousProfile(responseDTO.getAnonymousProfile()); + requestDto.setBiometricReferenceId(responseDTO.getBiometricReferenceId()); + JSONObject existingIdentity = mapper.readValue(mapper.writeValueAsString(responseDTO.getIdentity()), JSONObject.class); + JSONObject newIdentity = mapper.readValue(mapper.writeValueAsString(idRequestDto.getRequest().getIdentity()), JSONObject.class); + newIdentity.put(UIN, existingIdentity.get(UIN)); + idRequestDto.getRequest().setIdentity(newIdentity); + requestDto.setRegistrationId(responseDTO.getRegistrationId()); + requestDto.setStatus(responseDTO.getStatus()); + requestDto.setUin(responseDTO.getUin()); + idRequestDto.setRequest(requestDto); + + } + + IdResponseDTO response = (IdResponseDTO) registrationProcessorRestClientService.patchApi( + ApiName.IDREPOUPDATEDRAFT, Lists.newArrayList(id), null, null, idRequestDto, IdResponseDTO.class); + if (response.getErrors() != null && !response.getErrors().isEmpty()) { + ErrorDTO error = response.getErrors().get(0); + regProcLogger.error("Error occured while updating draft for id : " + id, error.toString()); + if (response.getErrors().get(0).getErrorCode().equalsIgnoreCase(ID_REPO_KEY_MANAGER_ERROR)) { + throw new IdrepoDraftReprocessableException(error.getErrorCode(), error.getMessage()); + } else { + throw new IdrepoDraftException(error.getErrorCode(), error.getMessage()); + } + } + + regProcLogger.debug("idrepoUpdateDraft exit " + id); + return response; + } + + public IdResponseDTO idrepoPublishDraft(String id) + throws ApisResourceAccessException, IdrepoDraftException, IdrepoDraftReprocessableException { + regProcLogger.debug("idrepoPublishDraft entry " + id); + List pathsegments=new ArrayList(); + pathsegments.add(id); + IdResponseDTO response = (IdResponseDTO) registrationProcessorRestClientService. + getApi(ApiName.IDREPOPUBLISHDRAFT, pathsegments, "", "", IdResponseDTO.class); + if (response.getErrors() != null && !response.getErrors().isEmpty()) { + ErrorDTO error = response.getErrors().get(0); + regProcLogger.error("Error occured while updating draft for id : " + id, error.toString()); + if (response.getErrors().get(0).getErrorCode().equalsIgnoreCase(ID_REPO_KEY_MANAGER_ERROR)) { + throw new IdrepoDraftReprocessableException(error.getErrorCode(), error.getMessage()); + } else { + throw new IdrepoDraftException(error.getErrorCode(), error.getMessage()); + } + + } + + regProcLogger.debug("idrepoPublishDraft exit " + id); + return response; + } +} diff --git a/registration-processor/registration-processor-packet-manager/src/test/java/io/mosip/registration/processor/packet/manager/service/impl/test/IdrepoDraftServiceTest.java b/registration-processor/registration-processor-packet-manager/src/test/java/io/mosip/registration/processor/packet/manager/service/impl/test/IdrepoDraftServiceTest.java index f3f5f082658..580e2b3c17d 100644 --- a/registration-processor/registration-processor-packet-manager/src/test/java/io/mosip/registration/processor/packet/manager/service/impl/test/IdrepoDraftServiceTest.java +++ b/registration-processor/registration-processor-packet-manager/src/test/java/io/mosip/registration/processor/packet/manager/service/impl/test/IdrepoDraftServiceTest.java @@ -1,203 +1,231 @@ -package io.mosip.registration.processor.packet.manager.service.impl.test; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.when; - -import java.io.IOException; - -import org.apache.commons.io.IOUtils; -import org.assertj.core.util.Lists; -import org.json.simple.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; - -import com.fasterxml.jackson.databind.ObjectMapper; - -import io.mosip.kernel.core.util.HMACUtils2; -import io.mosip.registration.processor.core.code.ApiName; -import io.mosip.registration.processor.core.common.rest.dto.ErrorDTO; -import io.mosip.registration.processor.core.exception.ApisResourceAccessException; -import io.mosip.registration.processor.core.http.ResponseWrapper; -import io.mosip.registration.processor.core.spi.restclient.RegistrationProcessorRestClientService; -import io.mosip.registration.processor.packet.manager.dto.IdRequestDto; -import io.mosip.registration.processor.packet.manager.dto.IdResponseDTO; -import io.mosip.registration.processor.packet.manager.dto.RequestDto; -import io.mosip.registration.processor.packet.manager.dto.ResponseDTO; -import io.mosip.registration.processor.packet.manager.exception.IdrepoDraftException; -import io.mosip.registration.processor.packet.manager.idreposervice.IdrepoDraftService; - -@RunWith(PowerMockRunner.class) -@PrepareForTest({ IOUtils.class, HMACUtils2.class }) -@PowerMockIgnore({"com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "javax.management.*", "javax.net.ssl.*" }) -public class IdrepoDraftServiceTest { - - @InjectMocks - private IdrepoDraftService idrepoDraftService = new IdrepoDraftService(); - - @Mock - private RegistrationProcessorRestClientService registrationProcessorRestClientService; - - @Mock - private ObjectMapper mapper; - - private IdResponseDTO idResponseDTO; - - private String ID = "12345689"; - - @Before - public void setup() throws IOException { - ResponseDTO responseDTO = new ResponseDTO(); - responseDTO.setStatus("ACTIVATED"); - responseDTO.setRegistrationId(ID); - - JSONObject jsonObject = new JSONObject(); - jsonObject.put("UIN", "1234"); - responseDTO.setIdentity(jsonObject); - - idResponseDTO = new IdResponseDTO(); - idResponseDTO.setErrors(null); - idResponseDTO.setId("id.uin.update"); - idResponseDTO.setResponse(responseDTO); - - when(mapper.writeValueAsString(any())).thenReturn("string"); - when(mapper.readValue("string", JSONObject.class)).thenReturn(jsonObject); - - } - - @Test - public void idrepoDraftPresentTest() throws ApisResourceAccessException, IdrepoDraftException { - - when(registrationProcessorRestClientService.headApi - (ApiName.IDREPOHASDRAFT, Lists.newArrayList(ID), null, null)).thenReturn(200); - - boolean result = idrepoDraftService.idrepoHasDraft(ID); - - assertTrue(result); - } - - @Test - public void idrepoDraftNotPresentTest() throws ApisResourceAccessException, IdrepoDraftException { - - when(registrationProcessorRestClientService.headApi - (ApiName.IDREPOHASDRAFT, Lists.newArrayList(ID), null, null)).thenReturn(204); - - boolean result = idrepoDraftService.idrepoHasDraft(ID); - - assertFalse(result); - } - - @Test(expected = IdrepoDraftException.class) - public void idrepoDraftCheckExceptionTest() throws ApisResourceAccessException, IdrepoDraftException { - - when(registrationProcessorRestClientService.headApi - (ApiName.IDREPOHASDRAFT, Lists.newArrayList(ID), null, null)).thenReturn(500); - - idrepoDraftService.idrepoHasDraft(ID); - - } - - @Test - public void idrepoGetDraftSuccessTest() throws ApisResourceAccessException, IdrepoDraftException { - - when(registrationProcessorRestClientService.getApi( - ApiName.IDREPOGETDRAFT, Lists.newArrayList(ID), Lists.emptyList(), null, IdResponseDTO.class)).thenReturn(idResponseDTO); - - ResponseDTO result = idrepoDraftService.idrepoGetDraft(ID); - - assertTrue(result.getRegistrationId().equals(ID)); - } - - @Test - public void idrepoPublishDraftSuccessTest() throws ApisResourceAccessException, IdrepoDraftException { - - when(registrationProcessorRestClientService.getApi( - ApiName.IDREPOPUBLISHDRAFT, Lists.newArrayList(ID), "", "", IdResponseDTO.class)).thenReturn(idResponseDTO); - - IdResponseDTO result = idrepoDraftService.idrepoPublishDraft(ID); - - assertTrue(result.getResponse().getRegistrationId().equals(ID)); - } - - @Test(expected = IdrepoDraftException.class) - public void idrepoPublishDraftExceptionTest() throws ApisResourceAccessException, IdrepoDraftException { - RequestDto requestDto = new RequestDto(); - requestDto.setIdentity(idResponseDTO.getResponse().getIdentity()); - IdRequestDto idRequestDto = new IdRequestDto(); - idRequestDto.setRequest(requestDto); - - ErrorDTO errorDTO = new ErrorDTO(); - errorDTO.setMessage("ERROR"); - errorDTO.setErrorCode("ERROR"); - IdResponseDTO idResponseDTO1 = new IdResponseDTO(); - idResponseDTO1.setErrors(Lists.newArrayList(errorDTO)); - when(registrationProcessorRestClientService.getApi( - ApiName.IDREPOPUBLISHDRAFT, Lists.newArrayList(ID), "", "", IdResponseDTO.class)).thenReturn(idResponseDTO1); - - idrepoDraftService.idrepoPublishDraft(ID); - } - - @Test - public void idrepoCreateDraftSuccessTest() throws ApisResourceAccessException, IdrepoDraftException { - ResponseWrapper responseWrapper = new ResponseWrapper(); - - when(registrationProcessorRestClientService.postApi( - ApiName.IDREPOCREATEDRAFT, Lists.newArrayList(ID), null, null, null, ResponseWrapper.class)).thenReturn(responseWrapper); - - boolean result = idrepoDraftService.idrepoCreateDraft(ID, null); - - assertTrue(result); - } - - @Test - public void idrepoUpdateDraftSuccessTest() throws ApisResourceAccessException, IdrepoDraftException, IOException { - RequestDto requestDto = new RequestDto(); - requestDto.setIdentity(idResponseDTO.getResponse().getIdentity()); - IdRequestDto idRequestDto = new IdRequestDto(); - idRequestDto.setRequest(requestDto); - - when(registrationProcessorRestClientService.headApi - (ApiName.IDREPOHASDRAFT, Lists.newArrayList(ID), null, null)).thenReturn(200); - when(registrationProcessorRestClientService.getApi( - ApiName.IDREPOGETDRAFT, Lists.newArrayList(ID), Lists.emptyList(), null, IdResponseDTO.class)).thenReturn(idResponseDTO); - when(registrationProcessorRestClientService.patchApi( - any(), any(), any(), any(), any(), any())).thenReturn(idResponseDTO); - - IdResponseDTO result = idrepoDraftService.idrepoUpdateDraft(ID, null, idRequestDto); - - assertTrue(result.getResponse().getRegistrationId().equals(ID)); - } - - @Test(expected = IdrepoDraftException.class) - public void idrepoUpdateDraftExceptionTest() throws ApisResourceAccessException, IdrepoDraftException, IOException { - RequestDto requestDto = new RequestDto(); - requestDto.setIdentity(idResponseDTO.getResponse().getIdentity()); - IdRequestDto idRequestDto = new IdRequestDto(); - idRequestDto.setRequest(requestDto); - - ErrorDTO errorDTO = new ErrorDTO(); - errorDTO.setMessage("ERROR"); - errorDTO.setErrorCode("ERROR"); - IdResponseDTO idResponseDTO1 = new IdResponseDTO(); - idResponseDTO1.setErrors(Lists.newArrayList(errorDTO)); - - when(registrationProcessorRestClientService.headApi - (ApiName.IDREPOHASDRAFT, Lists.newArrayList(ID), null, null)).thenReturn(200); - when(registrationProcessorRestClientService.getApi( - ApiName.IDREPOGETDRAFT, Lists.newArrayList(ID), Lists.emptyList(), null, IdResponseDTO.class)).thenReturn(idResponseDTO); - when(registrationProcessorRestClientService.patchApi( - any(), any(), any(), any(), any(), any())).thenReturn(idResponseDTO1); - - idrepoDraftService.idrepoUpdateDraft(ID, null, idRequestDto); - - } - - -} +package io.mosip.registration.processor.packet.manager.service.impl.test; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.when; + +import java.io.IOException; + +import org.apache.commons.io.IOUtils; +import org.assertj.core.util.Lists; +import org.json.simple.JSONObject; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import com.fasterxml.jackson.databind.ObjectMapper; + +import io.mosip.kernel.core.util.HMACUtils2; +import io.mosip.registration.processor.core.code.ApiName; +import io.mosip.registration.processor.core.common.rest.dto.ErrorDTO; +import io.mosip.registration.processor.core.exception.ApisResourceAccessException; +import io.mosip.registration.processor.core.http.ResponseWrapper; +import io.mosip.registration.processor.core.spi.restclient.RegistrationProcessorRestClientService; +import io.mosip.registration.processor.packet.manager.dto.IdRequestDto; +import io.mosip.registration.processor.packet.manager.dto.IdResponseDTO; +import io.mosip.registration.processor.packet.manager.dto.RequestDto; +import io.mosip.registration.processor.packet.manager.dto.ResponseDTO; +import io.mosip.registration.processor.packet.manager.exception.IdrepoDraftException; +import io.mosip.registration.processor.packet.manager.exception.IdrepoDraftReprocessableException; +import io.mosip.registration.processor.packet.manager.idreposervice.IdrepoDraftService; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({ IOUtils.class, HMACUtils2.class }) +@PowerMockIgnore({"com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "javax.management.*", "javax.net.ssl.*" }) +public class IdrepoDraftServiceTest { + + @InjectMocks + private IdrepoDraftService idrepoDraftService = new IdrepoDraftService(); + + @Mock + private RegistrationProcessorRestClientService registrationProcessorRestClientService; + + @Mock + private ObjectMapper mapper; + + private IdResponseDTO idResponseDTO; + + private String ID = "12345689"; + + @Before + public void setup() throws IOException { + ResponseDTO responseDTO = new ResponseDTO(); + responseDTO.setStatus("ACTIVATED"); + responseDTO.setRegistrationId(ID); + + JSONObject jsonObject = new JSONObject(); + jsonObject.put("UIN", "1234"); + responseDTO.setIdentity(jsonObject); + + idResponseDTO = new IdResponseDTO(); + idResponseDTO.setErrors(null); + idResponseDTO.setId("id.uin.update"); + idResponseDTO.setResponse(responseDTO); + + when(mapper.writeValueAsString(any())).thenReturn("string"); + when(mapper.readValue("string", JSONObject.class)).thenReturn(jsonObject); + + } + + @Test + public void idrepoDraftPresentTest() throws ApisResourceAccessException, IdrepoDraftException { + + when(registrationProcessorRestClientService.headApi + (ApiName.IDREPOHASDRAFT, Lists.newArrayList(ID), null, null)).thenReturn(200); + + boolean result = idrepoDraftService.idrepoHasDraft(ID); + + assertTrue(result); + } + + @Test + public void idrepoDraftNotPresentTest() throws ApisResourceAccessException, IdrepoDraftException { + + when(registrationProcessorRestClientService.headApi + (ApiName.IDREPOHASDRAFT, Lists.newArrayList(ID), null, null)).thenReturn(204); + + boolean result = idrepoDraftService.idrepoHasDraft(ID); + + assertFalse(result); + } + + @Test(expected = IdrepoDraftException.class) + public void idrepoDraftCheckExceptionTest() throws ApisResourceAccessException, IdrepoDraftException { + + when(registrationProcessorRestClientService.headApi + (ApiName.IDREPOHASDRAFT, Lists.newArrayList(ID), null, null)).thenReturn(500); + + idrepoDraftService.idrepoHasDraft(ID); + + } + + @Test + public void idrepoGetDraftSuccessTest() throws ApisResourceAccessException, IdrepoDraftException { + + when(registrationProcessorRestClientService.getApi( + ApiName.IDREPOGETDRAFT, Lists.newArrayList(ID), Lists.emptyList(), null, IdResponseDTO.class)).thenReturn(idResponseDTO); + + ResponseDTO result = idrepoDraftService.idrepoGetDraft(ID); + + assertTrue(result.getRegistrationId().equals(ID)); + } + + @Test + public void idrepoPublishDraftSuccessTest() throws ApisResourceAccessException, IdrepoDraftException, IdrepoDraftReprocessableException { + + when(registrationProcessorRestClientService.getApi( + ApiName.IDREPOPUBLISHDRAFT, Lists.newArrayList(ID), "", "", IdResponseDTO.class)).thenReturn(idResponseDTO); + + IdResponseDTO result = idrepoDraftService.idrepoPublishDraft(ID); + + assertTrue(result.getResponse().getRegistrationId().equals(ID)); + } + + @Test(expected = IdrepoDraftException.class) + public void idrepoPublishDraftExceptionTest() + throws ApisResourceAccessException, IdrepoDraftException, IdrepoDraftReprocessableException { + RequestDto requestDto = new RequestDto(); + requestDto.setIdentity(idResponseDTO.getResponse().getIdentity()); + IdRequestDto idRequestDto = new IdRequestDto(); + idRequestDto.setRequest(requestDto); + + ErrorDTO errorDTO = new ErrorDTO(); + errorDTO.setMessage("ERROR"); + errorDTO.setErrorCode("ERROR"); + IdResponseDTO idResponseDTO1 = new IdResponseDTO(); + idResponseDTO1.setErrors(Lists.newArrayList(errorDTO)); + when(registrationProcessorRestClientService.getApi( + ApiName.IDREPOPUBLISHDRAFT, Lists.newArrayList(ID), "", "", IdResponseDTO.class)).thenReturn(idResponseDTO1); + + idrepoDraftService.idrepoPublishDraft(ID); + } + + @Test + public void idrepoCreateDraftSuccessTest() throws ApisResourceAccessException, IdrepoDraftException { + ResponseWrapper responseWrapper = new ResponseWrapper(); + + when(registrationProcessorRestClientService.postApi( + ApiName.IDREPOCREATEDRAFT, Lists.newArrayList(ID), null, null, null, ResponseWrapper.class)).thenReturn(responseWrapper); + + boolean result = idrepoDraftService.idrepoCreateDraft(ID, null); + + assertTrue(result); + } + + @Test + public void idrepoUpdateDraftSuccessTest() + throws ApisResourceAccessException, IdrepoDraftException, IOException, IdrepoDraftReprocessableException { + RequestDto requestDto = new RequestDto(); + requestDto.setIdentity(idResponseDTO.getResponse().getIdentity()); + IdRequestDto idRequestDto = new IdRequestDto(); + idRequestDto.setRequest(requestDto); + + when(registrationProcessorRestClientService.headApi + (ApiName.IDREPOHASDRAFT, Lists.newArrayList(ID), null, null)).thenReturn(200); + when(registrationProcessorRestClientService.getApi( + ApiName.IDREPOGETDRAFT, Lists.newArrayList(ID), Lists.emptyList(), null, IdResponseDTO.class)).thenReturn(idResponseDTO); + when(registrationProcessorRestClientService.patchApi( + any(), any(), any(), any(), any(), any())).thenReturn(idResponseDTO); + + IdResponseDTO result = idrepoDraftService.idrepoUpdateDraft(ID, null, idRequestDto); + + assertTrue(result.getResponse().getRegistrationId().equals(ID)); + } + + @Test(expected = IdrepoDraftException.class) + public void idrepoUpdateDraftExceptionTest() + throws ApisResourceAccessException, IdrepoDraftException, IOException, IdrepoDraftReprocessableException { + RequestDto requestDto = new RequestDto(); + requestDto.setIdentity(idResponseDTO.getResponse().getIdentity()); + IdRequestDto idRequestDto = new IdRequestDto(); + idRequestDto.setRequest(requestDto); + + ErrorDTO errorDTO = new ErrorDTO(); + errorDTO.setMessage("ERROR"); + errorDTO.setErrorCode("ERROR"); + IdResponseDTO idResponseDTO1 = new IdResponseDTO(); + idResponseDTO1.setErrors(Lists.newArrayList(errorDTO)); + + when(registrationProcessorRestClientService.headApi + (ApiName.IDREPOHASDRAFT, Lists.newArrayList(ID), null, null)).thenReturn(200); + when(registrationProcessorRestClientService.getApi( + ApiName.IDREPOGETDRAFT, Lists.newArrayList(ID), Lists.emptyList(), null, IdResponseDTO.class)).thenReturn(idResponseDTO); + when(registrationProcessorRestClientService.patchApi( + any(), any(), any(), any(), any(), any())).thenReturn(idResponseDTO1); + + idrepoDraftService.idrepoUpdateDraft(ID, null, idRequestDto); + + } + + @Test(expected = IdrepoDraftReprocessableException.class) + public void idrepoDraftReprocessableExceptionTest() + throws ApisResourceAccessException, IdrepoDraftException, IOException, IdrepoDraftReprocessableException { + RequestDto requestDto = new RequestDto(); + requestDto.setIdentity(idResponseDTO.getResponse().getIdentity()); + IdRequestDto idRequestDto = new IdRequestDto(); + idRequestDto.setRequest(requestDto); + + ErrorDTO errorDTO = new ErrorDTO(); + errorDTO.setMessage("Failed to either encrypt/decrypt message using Kernel Crypto Manager"); + errorDTO.setErrorCode("IDR-IDS-003"); + IdResponseDTO idResponseDTO1 = new IdResponseDTO(); + idResponseDTO1.setErrors(Lists.newArrayList(errorDTO)); + + when(registrationProcessorRestClientService.headApi(ApiName.IDREPOHASDRAFT, Lists.newArrayList(ID), null, null)) + .thenReturn(200); + when(registrationProcessorRestClientService.getApi(ApiName.IDREPOGETDRAFT, Lists.newArrayList(ID), + Lists.emptyList(), null, IdResponseDTO.class)).thenReturn(idResponseDTO); + when(registrationProcessorRestClientService.patchApi(any(), any(), any(), any(), any(), any())) + .thenReturn(idResponseDTO1); + + idrepoDraftService.idrepoUpdateDraft(ID, null, idRequestDto); + + } + +}