From 908af2c926919239f3c46aed6d348d335d358e42 Mon Sep 17 00:00:00 2001 From: Sowmya Ujjappa Banakar Date: Wed, 26 Jun 2024 15:01:09 +0530 Subject: [PATCH 1/4] MOSIP-32461 sonar duplicate code fix Signed-off-by: Sowmya Ujjappa Banakar --- .../service/impl/PacketInfoManagerImpl.java | 2002 ++++++++-------- .../impl/RegistrationStatusServiceImpl.java | 21 +- .../impl/SyncRegistrationServiceImpl.java | 2036 ++++++++--------- 3 files changed, 2010 insertions(+), 2049 deletions(-) diff --git a/registration-processor/registration-processor-info-storage-service/src/main/java/io/mosip/registration/processor/packet/storage/service/impl/PacketInfoManagerImpl.java b/registration-processor/registration-processor-info-storage-service/src/main/java/io/mosip/registration/processor/packet/storage/service/impl/PacketInfoManagerImpl.java index 0d434dec81c..0a1d73244aa 100644 --- a/registration-processor/registration-processor-info-storage-service/src/main/java/io/mosip/registration/processor/packet/storage/service/impl/PacketInfoManagerImpl.java +++ b/registration-processor/registration-processor-info-storage-service/src/main/java/io/mosip/registration/processor/packet/storage/service/impl/PacketInfoManagerImpl.java @@ -1,1015 +1,987 @@ -package io.mosip.registration.processor.packet.storage.service.impl; - -import java.io.IOException; -import java.security.NoSuchAlgorithmException; -import java.sql.Timestamp; -import java.time.LocalDateTime; -import java.time.ZoneId; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.UUID; - -import org.apache.commons.lang3.exception.ExceptionUtils; -import org.json.simple.JSONArray; -import org.json.simple.JSONObject; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.cloud.context.config.annotation.RefreshScope; -import org.springframework.stereotype.Service; - -import com.fasterxml.jackson.databind.ObjectMapper; - -import io.mosip.kernel.core.dataaccess.exception.DataAccessLayerException; -import io.mosip.kernel.core.logger.spi.Logger; -import io.mosip.registration.processor.core.abstractverticle.MessageDTO; -import io.mosip.registration.processor.core.code.ApiName; -import io.mosip.registration.processor.core.code.AuditLogConstant; -import io.mosip.registration.processor.core.code.DedupeSourceName; -import io.mosip.registration.processor.core.code.EventId; -import io.mosip.registration.processor.core.code.EventName; -import io.mosip.registration.processor.core.code.EventType; -import io.mosip.registration.processor.core.constant.LoggerFileConstant; -import io.mosip.registration.processor.core.constant.MappingJsonConstants; -import io.mosip.registration.processor.core.constant.PacketFiles; -import io.mosip.registration.processor.core.constant.ProviderStageName; -import io.mosip.registration.processor.core.exception.util.PlatformErrorMessages; -import io.mosip.registration.processor.core.logger.LogDescription; -import io.mosip.registration.processor.core.logger.RegProcessorLogger; -import io.mosip.registration.processor.core.packet.dto.Identity; -import io.mosip.registration.processor.core.packet.dto.abis.AbisApplicationDto; -import io.mosip.registration.processor.core.packet.dto.abis.AbisRequestDto; -import io.mosip.registration.processor.core.packet.dto.abis.AbisResponseDetDto; -import io.mosip.registration.processor.core.packet.dto.abis.AbisResponseDto; -import io.mosip.registration.processor.core.packet.dto.abis.RegBioRefDto; -import io.mosip.registration.processor.core.packet.dto.abis.RegDemoDedupeListDto; -import io.mosip.registration.processor.core.packet.dto.demographicinfo.DemographicInfoDto; -import io.mosip.registration.processor.core.packet.dto.demographicinfo.IndividualDemographicDedupe; -import io.mosip.registration.processor.core.packet.dto.demographicinfo.JsonValue; -import io.mosip.registration.processor.core.spi.packetmanager.PacketInfoManager; -import io.mosip.registration.processor.core.util.JsonUtil; -import io.mosip.registration.processor.packet.storage.dao.PacketInfoDao; -import io.mosip.registration.processor.packet.storage.dto.ApplicantInfoDto; -import io.mosip.registration.processor.packet.storage.entity.AbisApplicationEntity; -import io.mosip.registration.processor.packet.storage.entity.AbisRequestEntity; -import io.mosip.registration.processor.packet.storage.entity.IndividualDemographicDedupeEntity; -import io.mosip.registration.processor.packet.storage.entity.ManualVerificationEntity; -import io.mosip.registration.processor.packet.storage.entity.ManualVerificationPKEntity; -import io.mosip.registration.processor.packet.storage.entity.RegBioRefEntity; -import io.mosip.registration.processor.packet.storage.entity.RegDemoDedupeListEntity; -import io.mosip.registration.processor.packet.storage.entity.RegLostUinDetEntity; -import io.mosip.registration.processor.packet.storage.entity.RegLostUinDetPKEntity; -import io.mosip.registration.processor.packet.storage.exception.MappingJsonException; -import io.mosip.registration.processor.packet.storage.exception.ParsingException; -import io.mosip.registration.processor.packet.storage.exception.TablenotAccessibleException; -import io.mosip.registration.processor.packet.storage.exception.UnableToInsertData; -import io.mosip.registration.processor.packet.storage.mapper.PacketInfoMapper; -import io.mosip.registration.processor.packet.storage.repository.BasePacketRepository; -import io.mosip.registration.processor.packet.storage.utils.PriorityBasedPacketManagerService; -import io.mosip.registration.processor.packet.storage.utils.Utilities; -import io.mosip.registration.processor.rest.client.audit.builder.AuditLogRequestBuilder; - -/** - * The Class PacketInfoManagerImpl. - * - * @author Horteppa M1048399 - * @author Girish Yarru - * - */ - -@RefreshScope -@Service -public class PacketInfoManagerImpl implements PacketInfoManager { - - /** The Constant FILE_SEPARATOR. */ - public static final String FILE_SEPARATOR = "\\"; - - /** The Constant LOG_FORMATTER. */ - public static final String LOG_FORMATTER = "{} - {}"; - - /** The Constant DEMOGRAPHIC_APPLICANT. */ - public static final String DEMOGRAPHIC_APPLICANT = PacketFiles.DEMOGRAPHIC.name() + FILE_SEPARATOR - + PacketFiles.APPLICANT.name() + FILE_SEPARATOR; - - /** The reg bio ref repository. */ - @Autowired - private BasePacketRepository regBioRefRepository; - - /** The reg abis request repository. */ - @Autowired - private BasePacketRepository regAbisRequestRepository; - - /** The reg abis application repository. */ - @Autowired - private BasePacketRepository regAbisApplicationRepository; - - /** The reg demo dedupe list repository. */ - @Autowired - private BasePacketRepository regDemoDedupeListRepository; - - /** The demographic dedupe repository. */ - @Autowired - private BasePacketRepository demographicDedupeRepository; - - /** The manual verfication repository. */ - @Autowired - private BasePacketRepository manualVerficationRepository; - - @Autowired - private BasePacketRepository regLostUinDetRepository; - - /** The core audit request builder. */ - @Autowired - AuditLogRequestBuilder auditLogRequestBuilder; - - /** The packet info dao. */ - @Autowired - private PacketInfoDao packetInfoDao; - - /** The utility. */ - @Autowired - private Utilities utility; - - @Autowired - private ObjectMapper objectMapper; - - @Autowired - private PriorityBasedPacketManagerService packetManagerService; - - @Value("${registration.processor.demodedupe.manual.adjudication.status}") - private String manualVerificationStatus; - - @Value("${mosip.regproc.demo.dedupe.trim-whitespaces.simpleType-value:false}") - private boolean trimWhitespace; - - /** The Constant MATCHED_REFERENCE_TYPE. */ - private static final String MATCHED_REFERENCE_TYPE = "rid"; - - /** The reg proc logger. */ - private static Logger regProcLogger = RegProcessorLogger.getLogger(PacketInfoManagerImpl.class); - - /* - * (non-Javadoc) - * - * @see - * io.mosip.registration.processor.core.spi.packetmanager.PacketInfoManager# - * getPacketsforQCUser(java.lang.String) - */ - @Override - public List getPacketsforQCUser(String qcUserId) { - - boolean isTransactionSuccessful = false; - LogDescription description = new LogDescription(); - List applicantInfoDtoList = null; - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), qcUserId, - "PacketInfoManagerImpl::getPacketsforQCUser()::entry"); - try { - applicantInfoDtoList = packetInfoDao.getPacketsforQCUser(qcUserId); - isTransactionSuccessful = true; - description.setMessage("QcUser packet Info fetch Success"); - return applicantInfoDtoList; - } catch (DataAccessLayerException e) { - - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - "", e.getMessage() + ExceptionUtils.getStackTrace(e)); - - description - .setMessage("DataAccessLayerException while fetching QcUser packet Info" + "::" + e.getMessage()); - - throw new TablenotAccessibleException( - PlatformErrorMessages.RPR_PIS_REGISTRATION_TABLE_NOT_ACCESSIBLE.getMessage(), e); - } finally { - - 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, - AuditLogConstant.NO_ID.toString(), ApiName.AUDIT); - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - qcUserId, "PacketInfoManagerImpl::getPacketsforQCUser()::exit"); - } - - } - - /** - * Gets the identity keys and fetch values from JSON. - * - * @param registrationId the demographic json string @return the identity - * keys and fetch values from JSON @throws - * PacketDecryptionFailureException @throws ApiNotAccessibleException @throws - */ - @Override - public IndividualDemographicDedupe getIdentityKeysAndFetchValuesFromJSON(String registrationId, String process, ProviderStageName stageName) { - IndividualDemographicDedupe demographicData = new IndividualDemographicDedupe(); - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", - "PacketInfoManagerImpl::getIdentityKeysAndFetchValuesFromJSON()::entry"); - try { - List fields = new ArrayList<>(); - - JSONObject regProcessorIdentityJson = utility.getRegistrationProcessorMappingJson(MappingJsonConstants.IDENTITY); - String nameKey = JsonUtil.getJSONValue( - JsonUtil.getJSONObject(regProcessorIdentityJson, MappingJsonConstants.NAME), - MappingJsonConstants.VALUE); - String dob = JsonUtil.getJSONValue( - JsonUtil.getJSONObject(regProcessorIdentityJson, MappingJsonConstants.DOB), - MappingJsonConstants.VALUE); - String gender = JsonUtil.getJSONValue( - JsonUtil.getJSONObject(regProcessorIdentityJson, MappingJsonConstants.GENDER), - MappingJsonConstants.VALUE); - String phone = JsonUtil.getJSONValue( - JsonUtil.getJSONObject(regProcessorIdentityJson, MappingJsonConstants.PHONE), - MappingJsonConstants.VALUE); - String email = JsonUtil.getJSONValue( - JsonUtil.getJSONObject(regProcessorIdentityJson, MappingJsonConstants.EMAIL), - MappingJsonConstants.VALUE); - - fields.addAll(Arrays.asList(nameKey.split(","))); - fields.add(dob); - fields.add(gender); - fields.add(email); - fields.add(phone); - - Map fieldMap = packetManagerService.getFields(registrationId, fields, process, stageName); - - - String[] names = ((String) JsonUtil.getJSONValue(JsonUtil.getJSONObject(regProcessorIdentityJson, MappingJsonConstants.NAME), - "value")).split(","); - List jsonValueList = new ArrayList<>(); - for (String name : names) { - if (fieldMap.get(name) != null) { - JSONObject jsonObject = new JSONObject(); - jsonObject.put(name, objectMapper.readValue(fieldMap.get(name), Object.class)); - JsonValue[] nameArray = JsonUtil.getJsonValues(jsonObject, name); - if (nameArray != null) - jsonValueList.add(nameArray); - } - } - demographicData.setName(jsonValueList.isEmpty() ? null : jsonValueList); - demographicData.setDateOfBirth(fieldMap.get(dob)); - if (fieldMap.get(gender) != null) { - JSONObject jsonObject = new JSONObject(); - jsonObject.put(gender, objectMapper.readValue(fieldMap.get(gender), Object.class)); - demographicData.setGender(JsonUtil.getJsonValues(jsonObject, gender)); - } - demographicData.setPhone(fieldMap.get(phone)); - demographicData.setEmail(fieldMap.get(email)); - - } catch (IOException e) { - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - "", e.getMessage() + ExceptionUtils.getStackTrace(e)); - - throw new MappingJsonException(PlatformErrorMessages.RPR_SYS_IDENTITY_JSON_MAPPING_EXCEPTION.getMessage(), - e); - - } - catch (Exception e) { - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - "", e.getMessage() + ExceptionUtils.getStackTrace(e)); - - throw new ParsingException(PlatformErrorMessages.RPR_SYS_JSON_PARSING_EXCEPTION.getMessage(), e); - } - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", - "PacketInfoManagerImpl::getIdentityKeysAndFetchValuesFromJSON()::exit"); - return demographicData; - - } - - - - /** - * Save individual demographic dedupe. - * - * @param regId the regId - * @param description - */ - private void saveIndividualDemographicDedupe(String regId, String process, LogDescription description, - String moduleId, String moduleName, Integer iteration, String workflowInstanceId) throws Exception { - - boolean isTransactionSuccessful = false; - - IndividualDemographicDedupe demographicData = getIdentityKeysAndFetchValuesFromJSON(regId, process, ProviderStageName.DEMO_DEDUPE); - - try { - List applicantDemographicEntities = PacketInfoMapper - .converDemographicDedupeDtoToEntity(demographicData, regId,process,iteration, workflowInstanceId,trimWhitespace); - for (IndividualDemographicDedupeEntity applicantDemographicEntity : applicantDemographicEntities) { - demographicDedupeRepository.save(applicantDemographicEntity); - - } - isTransactionSuccessful = true; - description.setMessage("Individual Demographic Dedupe data saved "); - - } catch (DataAccessLayerException e) { - description.setMessage("DataAccessLayerException while saving Individual Demographic Dedupe data " + "::" - + e.getMessage()); - - throw new UnableToInsertData(PlatformErrorMessages.RPR_PIS_UNABLE_TO_INSERT_DATA.getMessage() + regId, e); - } finally { - - String eventId = isTransactionSuccessful ? EventId.RPR_407.toString() : EventId.RPR_405.toString(); - String eventName = eventId.equalsIgnoreCase(EventId.RPR_407.toString()) ? EventName.ADD.toString() - : EventName.EXCEPTION.toString(); - String eventType = eventId.equalsIgnoreCase(EventId.RPR_407.toString()) ? EventType.BUSINESS.toString() - : EventType.SYSTEM.toString(); - auditLogRequestBuilder.createAuditRequestBuilder(description.getMessage(), eventId, eventName, eventType, - moduleId, moduleName, regId); - - } - - } - - /* - * (non-Javadoc) - * - * @see - * io.mosip.registration.processor.core.spi.packetmanager.PacketInfoManager# - * saveIndividualDemographicDedupeUpdatePacket(io.mosip.registration.processor. - * core.packet.dto.demographicinfo.IndividualDemographicDedupe, - * java.lang.String) - */ - @Override - public void saveIndividualDemographicDedupeUpdatePacket(IndividualDemographicDedupe demographicData, - String registrationId, String moduleId,String process, String moduleName,Integer iteration, String workflowInstanceId) { - boolean isTransactionSuccessful = false; - LogDescription description = new LogDescription(); - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", - "PacketInfoManagerImpl::saveIndividualDemographicDedupeUpdatePacket()::entry"); - - try { - List applicantDemographicEntities = PacketInfoMapper - .converDemographicDedupeDtoToEntity(demographicData, registrationId,process,iteration, workflowInstanceId,trimWhitespace); - for (IndividualDemographicDedupeEntity applicantDemographicEntity : applicantDemographicEntities) { - demographicDedupeRepository.save(applicantDemographicEntity); - - } - isTransactionSuccessful = true; - description.setMessage("Individual Demographic Dedupe data saved "); - - } catch (DataAccessLayerException | NoSuchAlgorithmException e) { - description.setMessage("DataAccessLayerException while saving Individual Demographic Dedupe data " + "::" - + e.getMessage()); - - throw new UnableToInsertData( - PlatformErrorMessages.RPR_PIS_UNABLE_TO_INSERT_DATA.getMessage() + registrationId, e); - } finally { - - String eventId = isTransactionSuccessful ? EventId.RPR_407.toString() : EventId.RPR_405.toString(); - String eventName = eventId.equalsIgnoreCase(EventId.RPR_407.toString()) ? EventName.ADD.toString() - : EventName.EXCEPTION.toString(); - String eventType = eventId.equalsIgnoreCase(EventId.RPR_407.toString()) ? EventType.BUSINESS.toString() - : EventType.SYSTEM.toString(); - auditLogRequestBuilder.createAuditRequestBuilder(description.getMessage(), eventId, eventName, eventType, - moduleId, moduleName, registrationId); - - } - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", - "PacketInfoManagerImpl::saveIndividualDemographicDedupeUpdatePacket()::exit"); - - } - - /* - * (non-Javadoc) - * - * @see - * io.mosip.registration.processor.core.spi.packetmanager.PacketInfoManager# - * saveDemographicInfoJson(java.io.InputStream, java.util.List) - */ - @Override - public void saveDemographicInfoJson(String registrationId, String process, String moduleId, - String moduleName,Integer iteration, String workflowInstanceId) throws Exception { - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", - "PacketInfoManagerImpl::saveDemographicInfoJson()::entry"); - LogDescription description = new LogDescription(); - - boolean isTransactionSuccessful = false; - - - try { - - saveIndividualDemographicDedupe(registrationId, process, description, moduleId, moduleName, iteration, workflowInstanceId); - - isTransactionSuccessful = true; - description.setMessage("Demographic Json saved"); - - } catch (DataAccessLayerException e) { - - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - "", e.getMessage() + ExceptionUtils.getStackTrace(e)); - - description.setMessage("DataAccessLayerException while saving Demographic Json" + "::" + e.getMessage()); - - throw new UnableToInsertData( - PlatformErrorMessages.RPR_PIS_UNABLE_TO_INSERT_DATA.getMessage() + registrationId, e); - } finally { - - String eventId = isTransactionSuccessful ? EventId.RPR_407.toString() : EventId.RPR_405.toString(); - String eventName = eventId.equalsIgnoreCase(EventId.RPR_407.toString()) ? EventName.ADD.toString() - : EventName.EXCEPTION.toString(); - String eventType = eventId.equalsIgnoreCase(EventId.RPR_407.toString()) ? EventType.BUSINESS.toString() - : EventType.SYSTEM.toString(); - auditLogRequestBuilder.createAuditRequestBuilder(description.getMessage(), eventId, eventName, eventType, - moduleId, moduleName, registrationId); - - } - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", - "PacketInfoManagerImpl::saveDemographicInfoJson()::exit"); - - } - - /* - * (non-Javadoc) - * - * @see - * io.mosip.registration.processor.core.spi.packetmanager.PacketInfoManager# - * findDemoById(java.lang.String) - */ - @Override - public List findDemoById(String regId) { - return packetInfoDao.findDemoById(regId); - } - - /* - * (non-Javadoc) - * - * @see - * io.mosip.registration.processor.core.spi.packetmanager.PacketInfoManager# - * saveManualAdjudicationData(java.util.Set, java.lang.String) - */ - @Override - public void saveManualAdjudicationData(Set uniqueMatchedRefIds, MessageDTO messageDTO, - DedupeSourceName sourceName, String moduleId, String moduleName, String transactionId, String requestId) { - boolean isTransactionSuccessful = false; - LogDescription description = new LogDescription(); - String registrationId = messageDTO.getRid(); - - try { - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), - registrationId, "PacketInfoManagerImpl::saveManualAdjudicationData()::entry"); - for (String matchedRefId : uniqueMatchedRefIds) { - ManualVerificationEntity manualVerificationEntity = new ManualVerificationEntity(); - ManualVerificationPKEntity manualVerificationPKEntity = new ManualVerificationPKEntity(); - manualVerificationPKEntity.setMatchedRefId(matchedRefId); - manualVerificationPKEntity.setMatchedRefType(MATCHED_REFERENCE_TYPE); - manualVerificationPKEntity.setWorkflowInstanceId(messageDTO.getWorkflowInstanceId()); - - manualVerificationEntity.setRegId(registrationId); - manualVerificationEntity.setId(manualVerificationPKEntity); - manualVerificationEntity.setLangCode("eng"); - manualVerificationEntity.setRequestId(UUID.randomUUID().toString()); - //manualVerificationEntity.setMatchedScore(null); - manualVerificationEntity.setReponseText(null); - manualVerificationEntity.setRequestId(requestId); - manualVerificationEntity.setTransactionId(transactionId); - manualVerificationEntity.setMvUsrId(null); - manualVerificationEntity.setReasonCode("Potential Match"); - if (sourceName.equals(DedupeSourceName.DEMO)) { - manualVerificationEntity.setStatusCode(manualVerificationStatus); - - } else { - manualVerificationEntity.setStatusCode("PENDING"); - - } - manualVerificationEntity.setStatusComment("Assigned to manual Adjudication"); - manualVerificationEntity.setIsActive(true); - manualVerificationEntity.setIsDeleted(false); - manualVerificationEntity.setCrBy("SYSTEM"); - manualVerificationEntity.setCrDtimes(Timestamp.valueOf(LocalDateTime.now(ZoneId.of("UTC")))); - manualVerificationEntity.setUpdDtimes(Timestamp.valueOf(LocalDateTime.now(ZoneId.of("UTC")))); - manualVerificationEntity.setTrnTypCode(sourceName.toString()); - manualVerficationRepository.save(manualVerificationEntity); - isTransactionSuccessful = true; - description.setMessage("Manual Adjudication data saved successfully"); - } - - } catch (DataAccessLayerException e) { - description.setMessage("DataAccessLayerException while saving Manual Adjudication data for rid" - + registrationId + "::" + e.getMessage()); - - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - "", e.getMessage() + ExceptionUtils.getStackTrace(e)); - - throw new UnableToInsertData( - PlatformErrorMessages.RPR_PIS_UNABLE_TO_INSERT_DATA.getMessage() + registrationId, e); - } finally { - - String eventId = isTransactionSuccessful ? EventId.RPR_407.toString() : EventId.RPR_405.toString(); - String eventName = eventId.equalsIgnoreCase(EventId.RPR_407.toString()) ? EventName.ADD.toString() - : EventName.EXCEPTION.toString(); - String eventType = eventId.equalsIgnoreCase(EventId.RPR_407.toString()) ? EventType.BUSINESS.toString() - : EventType.SYSTEM.toString(); - - auditLogRequestBuilder.createAuditRequestBuilder(description.getMessage(), eventId, eventName, eventType, - moduleId, moduleName, registrationId); - - } - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), - registrationId, "PacketInfoManagerImpl::saveManualAdjudicationData()::exit"); - } - - /* - * (non-Javadoc) - * - * @see - * io.mosip.registration.processor.core.spi.packetmanager.PacketInfoManager# - * getReferenceIdByRid(java.lang.String) - */ - @Override - public List getReferenceIdByWorkflowInstanceId(String workflowInstanceId) { - return regBioRefRepository.getRefIdByWorkflowInstanceId(workflowInstanceId); - } - - /* - * (non-Javadoc) - * - * @see - * io.mosip.registration.processor.core.spi.packetmanager.PacketInfoManager# - * getRidByReferenceId(java.lang.String) - */ - @Override - public List getRidByReferenceId(String refId) { - return regBioRefRepository.getRidByReferenceId(refId); - } - - /* - * (non-Javadoc) - * - * @see - * io.mosip.registration.processor.core.spi.packetmanager.PacketInfoManager# - * saveAbisRef(io.mosip.registration.processor.core.packet.dto.RegAbisRefDto) - */ - @Override - public void saveAbisRef(RegBioRefDto regBioRefDto, String moduleId, String moduleName) { - boolean isTransactionSuccessful = false; - LogDescription description = new LogDescription(); - String regId = regBioRefDto.getRegId(); - try { - if (regBioRefDto != null) { - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), - regId, "PacketInfoManagerImpl::saveAbisRef()::entry"); - - RegBioRefEntity regBioRefEntity = PacketInfoMapper.convertBioRefDtoToEntity(regBioRefDto); - regBioRefRepository.save(regBioRefEntity); - isTransactionSuccessful = true; - description.setMessage("ABIS data saved successfully"); - } - } catch (DataAccessLayerException e) { - description.setMessage("DataAccessLayerException while saving the ABIS data" + "::" + e.getMessage()); - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - "", e.getMessage() + ExceptionUtils.getStackTrace(e)); - throw new UnableToInsertData(PlatformErrorMessages.RPR_PIS_UNABLE_TO_INSERT_DATA.getMessage() + regId, e); - } finally { - - String eventId = isTransactionSuccessful ? EventId.RPR_407.toString() : EventId.RPR_405.toString(); - String eventName = eventId.equalsIgnoreCase(EventId.RPR_407.toString()) ? EventName.ADD.toString() - : EventName.EXCEPTION.toString(); - String eventType = eventId.equalsIgnoreCase(EventId.RPR_407.toString()) ? EventType.BUSINESS.toString() - : EventType.SYSTEM.toString(); - - auditLogRequestBuilder.createAuditRequestBuilder(description.getMessage(), eventId, eventName, eventType, - moduleId, moduleName, AuditLogConstant.NO_ID.toString()); - - } - - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), regId, - "PacketInfoManagerImpl::saveAbisRef()::exit"); - - } - - /* - * (non-Javadoc) - * - * @see - * io.mosip.registration.processor.core.spi.packetmanager.PacketInfoManager# - * getInsertOrIdentifyRequest(java.lang.String, java.lang.String) - */ - @Override - public List getInsertOrIdentifyRequest(String bioRefId, String refRegtrnId) { - List abisRequestList = packetInfoDao.getInsertOrIdentifyRequest(bioRefId, refRegtrnId); - return PacketInfoMapper.convertAbisRequestEntityListToDto(abisRequestList); - } - - @Override - public List getReferenceIdByBatchId(String batchId) { - return packetInfoDao.getReferenceIdByBatchId(batchId); - } - - /* - * (non-Javadoc) - * - * @see - * io.mosip.registration.processor.core.spi.packetmanager.PacketInfoManager# - * getAbisTransactionIdByRequestId(java.lang.String) - */ - @Override - public List getAbisTransactionIdByRequestId(String requestId) { - return packetInfoDao.getAbisTransactionIdByRequestId(requestId); - } - - @Override - public List getIdentifyReqListByTransactionId(String transactionId, String requestType) { - List abisRequestList = packetInfoDao.getIdentifyReqListByTransactionId(transactionId, - requestType); - return PacketInfoMapper.convertAbisRequestEntityListToDto(abisRequestList); - } - - /* - * (non-Javadoc) - * - * @see - * io.mosip.registration.processor.core.spi.packetmanager.PacketInfoManager# - * getBatchStatusbyBatchId(java.lang.String) - */ - @Override - public List getBatchStatusbyBatchId(String batchId) { - return packetInfoDao.getBatchStatusbyBatchId(batchId); - - } - - /* - * (non-Javadoc) - * - * @see - * io.mosip.registration.processor.core.spi.packetmanager.PacketInfoManager# - * getAbisRequestByRequestId(java.lang.String) - */ - @Override - public AbisRequestDto getAbisRequestByRequestId(String abisRequestId) { - List abisRequestList = packetInfoDao.getAbisRequestByRequestId(abisRequestId); - List abisRequestDtoList = PacketInfoMapper.convertAbisRequestEntityListToDto(abisRequestList); - if (!abisRequestDtoList.isEmpty()) { - return PacketInfoMapper.convertAbisRequestEntityListToDto(abisRequestList).get(0); - } else { - return null; - - } - } - - /* - * (non-Javadoc) - * - * @see - * io.mosip.registration.processor.core.spi.packetmanager.PacketInfoManager# - * getBatchIdByRequestId(java.lang.String) - */ - @Override - public String getBatchIdByRequestId(String abisRequestId) { - return packetInfoDao.getBatchIdByRequestId(abisRequestId); - } - - /* - * (non-Javadoc) - * - * @see - * io.mosip.registration.processor.core.spi.packetmanager.PacketInfoManager# - * getInsertOrIdentifyRequest(java.lang.String, java.lang.String, - * java.lang.String) - */ - @Override - public List getInsertOrIdentifyRequest(String bioRefId, String refRegtrnId, String requestType) { - List abisRequestEntities = packetInfoDao.getInsertOrIdentifyRequest(bioRefId, refRegtrnId, - requestType); - return PacketInfoMapper.convertAbisRequestEntityListToDto(abisRequestEntities); - } - - /* - * (non-Javadoc) - * - * @see - * io.mosip.registration.processor.core.spi.packetmanager.PacketInfoManager# - * getIdentifyByTransactionId(java.lang.String, java.lang.String) - */ - @Override - public Boolean getIdentifyByTransactionId(String transactionId, String identify) { - List abisRequestList = packetInfoDao.getIdentifyByTransactionId(transactionId, identify); - return abisRequestList.isEmpty() ? Boolean.FALSE : Boolean.TRUE; - } - - /* - * (non-Javadoc) - * - * @see - * io.mosip.registration.processor.core.spi.packetmanager.PacketInfoManager# - * getBioRefIdByRegId(java.lang.String) - */ - @Override - public List getBioRefIdByRegId(String regId) { - List regBioRefEntityList = packetInfoDao.getBioRefIdByRegId(regId); - return PacketInfoMapper.convertRegBioRefEntityListToDto(regBioRefEntityList); - } - - /* - * (non-Javadoc) - * - * @see - * io.mosip.registration.processor.core.spi.packetmanager.PacketInfoManager# - * getAllAbisDetails() - */ - @Override - public List getAllAbisDetails() { - List abisApplicationEntityList = regAbisApplicationRepository - .findAll(AbisApplicationEntity.class); - return PacketInfoMapper.convertAbisApplicationEntityListToDto(abisApplicationEntityList); - } - - /* - * (non-Javadoc) - * - * @see - * io.mosip.registration.processor.core.spi.packetmanager.PacketInfoManager# - * saveBioRef(io.mosip.registration.processor.core.packet.dto.abis.RegBioRefDto) - */ - @Override - public void saveBioRef(RegBioRefDto regBioRefDto, String moduleId, String moduleName) { - boolean isTransactionSuccessful = false; - LogDescription description = new LogDescription(); - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", - "PacketInfoManagerImpl::saveBioRef()::entry"); - - try { - RegBioRefEntity regBioRefEntity = PacketInfoMapper.convertBioRefDtoToEntity(regBioRefDto); - regBioRefRepository.save(regBioRefEntity); - isTransactionSuccessful = true; - description.setMessage("Bio ref data saved successfully"); - } catch (DataAccessLayerException e) { - description.setMessage("DataAccessLayerException while saving ABIS data" + "::" + e.getMessage()); - - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - "", e.getMessage() + ExceptionUtils.getStackTrace(e)); - throw new UnableToInsertData( - PlatformErrorMessages.RPR_PIS_UNABLE_TO_INSERT_DATA.getMessage() + regBioRefDto.getRegId(), e); - } finally { - - String eventId = isTransactionSuccessful ? EventId.RPR_407.toString() : EventId.RPR_405.toString(); - String eventName = eventId.equalsIgnoreCase(EventId.RPR_407.toString()) ? EventName.ADD.toString() - : EventName.EXCEPTION.toString(); - String eventType = eventId.equalsIgnoreCase(EventId.RPR_407.toString()) ? EventType.BUSINESS.toString() - : EventType.SYSTEM.toString(); - - auditLogRequestBuilder.createAuditRequestBuilder(description.getMessage(), eventId, eventName, eventType, - moduleId, moduleName, AuditLogConstant.NO_ID.toString()); - - } - - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", - "PacketInfoManagerImpl::saveBioRef()::exit"); - - } - - /* - * (non-Javadoc) - * - * @see - * io.mosip.registration.processor.core.spi.packetmanager.PacketInfoManager# - * saveAbisRequest(io.mosip.registration.processor.core.packet.dto.abis. - * AbisRequestDto) - */ - @Override - public void saveAbisRequest(AbisRequestDto abisRequestDto, String moduleId, String moduleName) { - boolean isTransactionSuccessful = false; - LogDescription description = new LogDescription(); - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", - "PacketInfoManagerImpl::saveAbisRequest()::entry"); - - try { - AbisRequestEntity abisRequestEntity = PacketInfoMapper.convertAbisRequestDtoToEntity(abisRequestDto); - regAbisRequestRepository.save(abisRequestEntity); - isTransactionSuccessful = true; - description.setMessage("ABIS Request data saved successfully"); - } catch (DataAccessLayerException e) { - description.setMessage("DataAccessLayerException while saving ABIS data" + "::" + e.getMessage()); - - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - "", e.getMessage() + ExceptionUtils.getStackTrace(e)); - throw new UnableToInsertData( - PlatformErrorMessages.RPR_PIS_UNABLE_TO_INSERT_DATA.getMessage() + abisRequestDto.getId(), e); - } finally { - - String eventId = isTransactionSuccessful ? EventId.RPR_407.toString() : EventId.RPR_405.toString(); - String eventName = eventId.equalsIgnoreCase(EventId.RPR_407.toString()) ? EventName.ADD.toString() - : EventName.EXCEPTION.toString(); - String eventType = eventId.equalsIgnoreCase(EventId.RPR_407.toString()) ? EventType.BUSINESS.toString() - : EventType.SYSTEM.toString(); - - auditLogRequestBuilder.createAuditRequestBuilder(description.getMessage(), eventId, eventName, eventType, - moduleId, moduleName, AuditLogConstant.NO_ID.toString()); - - } - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", - "PacketInfoManagerImpl::saveAbisRequest()::exit"); - - } - - /* - * (non-Javadoc) - * - * @see - * io.mosip.registration.processor.core.spi.packetmanager.PacketInfoManager# - * getDemoListByTransactionId(java.lang.String) - */ - @Override - public List getDemoListByTransactionId(String transactionId) { - List regDemoDedupeListEntityList = packetInfoDao - .getDemoListByTransactionId(transactionId); - return PacketInfoMapper.convertDemoDedupeEntityListToDto(regDemoDedupeListEntityList); - } - - /* - * (non-Javadoc) - * - * @see - * io.mosip.registration.processor.core.spi.packetmanager.PacketInfoManager# - * saveDemoDedupePotentialData(io.mosip.registration.processor.core.packet.dto. - * abis.RegDemoDedupeListDto) - */ - @Override - public void saveDemoDedupePotentialData(RegDemoDedupeListDto regDemoDedupeListDto, String moduleId, - String moduleName) { - boolean isTransactionSuccessful = false; - LogDescription description = new LogDescription(); - - String regId = ""; - try { - - if (regDemoDedupeListDto != null) { - regId = regDemoDedupeListDto.getRegId(); - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), - regId, "PacketInfoManagerImpl::saveDemoDedupePotentialData()::entry"); - - RegDemoDedupeListEntity regDemoDedupeListEntity = PacketInfoMapper - .convertDemoDedupeEntityToDto(regDemoDedupeListDto); - regDemoDedupeListRepository.save(regDemoDedupeListEntity); - isTransactionSuccessful = true; - description.setMessage("Demo dedupe potential match data saved successfully"); - - } - } catch (DataAccessLayerException e) { - description.setMessage( - "DataAccessLayerException while saving Demo dedupe potential match data" + "::" + e.getMessage()); - - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - "", e.getMessage() + ExceptionUtils.getStackTrace(e)); - throw new UnableToInsertData(PlatformErrorMessages.RPR_PIS_UNABLE_TO_INSERT_DATA.getMessage() + regId, e); - } finally { - - String eventId = isTransactionSuccessful ? EventId.RPR_407.toString() : EventId.RPR_405.toString(); - String eventName = eventId.equalsIgnoreCase(EventId.RPR_407.toString()) ? EventName.ADD.toString() - : EventName.EXCEPTION.toString(); - String eventType = eventId.equalsIgnoreCase(EventId.RPR_407.toString()) ? EventType.BUSINESS.toString() - : EventType.SYSTEM.toString(); - - auditLogRequestBuilder.createAuditRequestBuilder(description.getMessage(), eventId, eventName, eventType, - moduleId, moduleName, AuditLogConstant.NO_ID.toString()); - - } - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), regId, - "PacketInfoManagerImpl::saveDemoDedupePotentialData()::exit"); - } - - /* - * (non-Javadoc) - * - * @see - * io.mosip.registration.processor.core.spi.packetmanager.PacketInfoManager# - * getAbisResponseRecords(java.lang.String, java.lang.String) - */ - @Override - public List getAbisResponseRecords(String latestTransactionId, String requestType) { - return packetInfoDao.getAbisResponseRecords(latestTransactionId, requestType); - } - - /* - * (non-Javadoc) - * - * @see - * io.mosip.registration.processor.core.spi.packetmanager.PacketInfoManager# - * getAbisResponseRecords(java.lang.String, java.lang.String, java.lang.String) - */ - @Override - public List getAbisResponseRecords(String abisRefId, String latestTransactionId, - String requestType) { - return packetInfoDao.getAbisResponseRecords(abisRefId, latestTransactionId, requestType); - } - - /* - * (non-Javadoc) - * - * @see - * io.mosip.registration.processor.core.spi.packetmanager.PacketInfoManager# - * getAbisResponseDetRecords(io.mosip.registration.processor.core.packet.dto. - * abis.AbisResponseDto) - */ - @Override - public List getAbisResponseDetRecords(AbisResponseDto abisResponseDto) { - return packetInfoDao.getAbisResponseDetailedRecords(abisResponseDto); - } - - /* - * (non-Javadoc) - * - * @see - * io.mosip.registration.processor.core.spi.packetmanager.PacketInfoManager# - * getAbisResponseIDs(java.lang.String) - */ - @Override - public List getAbisResponseIDs(String abisRequestId) { - return PacketInfoMapper.convertAbisResponseEntityListToDto(packetInfoDao.getAbisResponseIDs(abisRequestId)); - } - - /* - * (non-Javadoc) - * - * @see - * io.mosip.registration.processor.core.spi.packetmanager.PacketInfoManager# - * getAbisResponseDetails(java.lang.String) - */ - @Override - public List getAbisResponseDetails(String abisResponseId) { - return PacketInfoMapper - .convertAbisResponseDetEntityListToDto(packetInfoDao.getAbisResponseDetails(abisResponseId)); - } - - /* - * (non-Javadoc) - * - * @see - * io.mosip.registration.processor.core.spi.packetmanager.PacketInfoManager# - * getAbisRequestsByBioRefId(java.lang.String) - */ - @Override - public List getAbisRequestsByBioRefId(String bioRefId) { - List abisRequestEntityList = packetInfoDao.getAbisRequestsByBioRefId(bioRefId); - return PacketInfoMapper.convertAbisRequestEntityListToDto(abisRequestEntityList); - } - - @Override - public List getAbisProcessedRequestsAppCodeByBioRefId(String bioRefId, String requestType, - String processed) { - return packetInfoDao.getAbisProcessedRequestsAppCodeByBioRefId(bioRefId, requestType, processed); - } - - @Override - public List getAbisResponseDetRecordsList(List abisResponseDto) { - return packetInfoDao.getAbisResponseDetRecordsList(abisResponseDto); - } - - @Override - public void saveRegLostUinDet(String regId, String workflowInstanceId, String latestRegId, String moduleId, String moduleName) { - boolean isTransactionSuccessful = false; - LogDescription description = new LogDescription(); - - try { - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), regId, - "PacketInfoManagerImpl::saveRegLostUinDetData()::entry"); - RegLostUinDetEntity regLostUinDetEntity = new RegLostUinDetEntity(); - RegLostUinDetPKEntity regLostUinDetPKEntity = new RegLostUinDetPKEntity(); - regLostUinDetPKEntity.setWorkflowInstanceId(workflowInstanceId); - - regLostUinDetEntity.setRegId(regId); - regLostUinDetEntity.setId(regLostUinDetPKEntity); - regLostUinDetEntity.setLatestRegId(latestRegId); - regLostUinDetEntity.setCrBy("SYSTEM"); - regLostUinDetEntity.setCrDtimes(LocalDateTime.now(ZoneId.of("UTC"))); - regLostUinDetEntity.setUpdDtimes(LocalDateTime.now(ZoneId.of("UTC"))); - regLostUinDetEntity.setIsDeleted(false); - - regLostUinDetRepository.save(regLostUinDetEntity); - isTransactionSuccessful = true; - description.setMessage("Lost Uin detail data saved successfully"); - } catch (DataAccessLayerException e) { - description.setMessage("DataAccessLayerException while saving Lost Uin detail data for rid" + regId + "::" - + e.getMessage()); - - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - "", e.getMessage() + ExceptionUtils.getStackTrace(e)); - - throw new UnableToInsertData(PlatformErrorMessages.RPR_PIS_UNABLE_TO_INSERT_DATA.getMessage() + regId, e); - } finally { - - String eventId = isTransactionSuccessful ? EventId.RPR_407.toString() : EventId.RPR_405.toString(); - String eventName = eventId.equalsIgnoreCase(EventId.RPR_407.toString()) ? EventName.ADD.toString() - : EventName.EXCEPTION.toString(); - String eventType = eventId.equalsIgnoreCase(EventId.RPR_407.toString()) ? EventType.BUSINESS.toString() - : EventType.SYSTEM.toString(); - - auditLogRequestBuilder.createAuditRequestBuilder(description.getMessage(), eventId, eventName, eventType, - moduleId, moduleName, AuditLogConstant.NO_ID.toString()); - - } - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), regId, - "PacketInfoManagerImpl::saveRegLostUinDetData()::exit"); - - } - - @Override - public List getRegBioRefDataByBioRefIds(List bioRefId) { - List regBioRefList = packetInfoDao.getRegBioRefDataByBioRefIds(bioRefId); - return PacketInfoMapper.convertRegBioRefEntityListToDto(regBioRefList); - } - - -} +package io.mosip.registration.processor.packet.storage.service.impl; + +import java.io.IOException; +import java.security.NoSuchAlgorithmException; +import java.sql.Timestamp; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; + +import org.apache.commons.lang3.exception.ExceptionUtils; +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.cloud.context.config.annotation.RefreshScope; +import org.springframework.stereotype.Service; + +import com.fasterxml.jackson.databind.ObjectMapper; + +import io.mosip.kernel.core.dataaccess.exception.DataAccessLayerException; +import io.mosip.kernel.core.logger.spi.Logger; +import io.mosip.registration.processor.core.abstractverticle.MessageDTO; +import io.mosip.registration.processor.core.code.ApiName; +import io.mosip.registration.processor.core.code.AuditLogConstant; +import io.mosip.registration.processor.core.code.DedupeSourceName; +import io.mosip.registration.processor.core.code.EventId; +import io.mosip.registration.processor.core.code.EventName; +import io.mosip.registration.processor.core.code.EventType; +import io.mosip.registration.processor.core.constant.LoggerFileConstant; +import io.mosip.registration.processor.core.constant.MappingJsonConstants; +import io.mosip.registration.processor.core.constant.PacketFiles; +import io.mosip.registration.processor.core.constant.ProviderStageName; +import io.mosip.registration.processor.core.exception.util.PlatformErrorMessages; +import io.mosip.registration.processor.core.logger.LogDescription; +import io.mosip.registration.processor.core.logger.RegProcessorLogger; +import io.mosip.registration.processor.core.packet.dto.Identity; +import io.mosip.registration.processor.core.packet.dto.abis.AbisApplicationDto; +import io.mosip.registration.processor.core.packet.dto.abis.AbisRequestDto; +import io.mosip.registration.processor.core.packet.dto.abis.AbisResponseDetDto; +import io.mosip.registration.processor.core.packet.dto.abis.AbisResponseDto; +import io.mosip.registration.processor.core.packet.dto.abis.RegBioRefDto; +import io.mosip.registration.processor.core.packet.dto.abis.RegDemoDedupeListDto; +import io.mosip.registration.processor.core.packet.dto.demographicinfo.DemographicInfoDto; +import io.mosip.registration.processor.core.packet.dto.demographicinfo.IndividualDemographicDedupe; +import io.mosip.registration.processor.core.packet.dto.demographicinfo.JsonValue; +import io.mosip.registration.processor.core.spi.packetmanager.PacketInfoManager; +import io.mosip.registration.processor.core.util.JsonUtil; +import io.mosip.registration.processor.packet.storage.dao.PacketInfoDao; +import io.mosip.registration.processor.packet.storage.dto.ApplicantInfoDto; +import io.mosip.registration.processor.packet.storage.entity.AbisApplicationEntity; +import io.mosip.registration.processor.packet.storage.entity.AbisRequestEntity; +import io.mosip.registration.processor.packet.storage.entity.IndividualDemographicDedupeEntity; +import io.mosip.registration.processor.packet.storage.entity.ManualVerificationEntity; +import io.mosip.registration.processor.packet.storage.entity.ManualVerificationPKEntity; +import io.mosip.registration.processor.packet.storage.entity.RegBioRefEntity; +import io.mosip.registration.processor.packet.storage.entity.RegDemoDedupeListEntity; +import io.mosip.registration.processor.packet.storage.entity.RegLostUinDetEntity; +import io.mosip.registration.processor.packet.storage.entity.RegLostUinDetPKEntity; +import io.mosip.registration.processor.packet.storage.exception.MappingJsonException; +import io.mosip.registration.processor.packet.storage.exception.ParsingException; +import io.mosip.registration.processor.packet.storage.exception.TablenotAccessibleException; +import io.mosip.registration.processor.packet.storage.exception.UnableToInsertData; +import io.mosip.registration.processor.packet.storage.mapper.PacketInfoMapper; +import io.mosip.registration.processor.packet.storage.repository.BasePacketRepository; +import io.mosip.registration.processor.packet.storage.utils.PriorityBasedPacketManagerService; +import io.mosip.registration.processor.packet.storage.utils.Utilities; +import io.mosip.registration.processor.rest.client.audit.builder.AuditLogRequestBuilder; + +/** + * The Class PacketInfoManagerImpl. + * + * @author Horteppa M1048399 + * @author Girish Yarru + * + */ + +@RefreshScope +@Service +public class PacketInfoManagerImpl implements PacketInfoManager { + + /** The Constant FILE_SEPARATOR. */ + public static final String FILE_SEPARATOR = "\\"; + + /** The Constant LOG_FORMATTER. */ + public static final String LOG_FORMATTER = "{} - {}"; + + /** The Constant DEMOGRAPHIC_APPLICANT. */ + public static final String DEMOGRAPHIC_APPLICANT = PacketFiles.DEMOGRAPHIC.name() + FILE_SEPARATOR + + PacketFiles.APPLICANT.name() + FILE_SEPARATOR; + + /** The reg bio ref repository. */ + @Autowired + private BasePacketRepository regBioRefRepository; + + /** The reg abis request repository. */ + @Autowired + private BasePacketRepository regAbisRequestRepository; + + /** The reg abis application repository. */ + @Autowired + private BasePacketRepository regAbisApplicationRepository; + + /** The reg demo dedupe list repository. */ + @Autowired + private BasePacketRepository regDemoDedupeListRepository; + + /** The demographic dedupe repository. */ + @Autowired + private BasePacketRepository demographicDedupeRepository; + + /** The manual verfication repository. */ + @Autowired + private BasePacketRepository manualVerficationRepository; + + @Autowired + private BasePacketRepository regLostUinDetRepository; + + /** The core audit request builder. */ + @Autowired + AuditLogRequestBuilder auditLogRequestBuilder; + + /** The packet info dao. */ + @Autowired + private PacketInfoDao packetInfoDao; + + /** The utility. */ + @Autowired + private Utilities utility; + + @Autowired + private ObjectMapper objectMapper; + + @Autowired + private PriorityBasedPacketManagerService packetManagerService; + + @Value("${registration.processor.demodedupe.manual.adjudication.status}") + private String manualVerificationStatus; + + @Value("${mosip.regproc.demo.dedupe.trim-whitespaces.simpleType-value:false}") + private boolean trimWhitespace; + + /** The Constant MATCHED_REFERENCE_TYPE. */ + private static final String MATCHED_REFERENCE_TYPE = "rid"; + + /** The reg proc logger. */ + private static Logger regProcLogger = RegProcessorLogger.getLogger(PacketInfoManagerImpl.class); + + /* + * (non-Javadoc) + * + * @see + * io.mosip.registration.processor.core.spi.packetmanager.PacketInfoManager# + * getPacketsforQCUser(java.lang.String) + */ + @Override + public List getPacketsforQCUser(String qcUserId) { + + boolean isTransactionSuccessful = false; + LogDescription description = new LogDescription(); + List applicantInfoDtoList = null; + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), qcUserId, + "PacketInfoManagerImpl::getPacketsforQCUser()::entry"); + try { + applicantInfoDtoList = packetInfoDao.getPacketsforQCUser(qcUserId); + isTransactionSuccessful = true; + description.setMessage("QcUser packet Info fetch Success"); + return applicantInfoDtoList; + } catch (DataAccessLayerException e) { + + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + "", e.getMessage() + ExceptionUtils.getStackTrace(e)); + + description + .setMessage("DataAccessLayerException while fetching QcUser packet Info" + "::" + e.getMessage()); + + throw new TablenotAccessibleException( + PlatformErrorMessages.RPR_PIS_REGISTRATION_TABLE_NOT_ACCESSIBLE.getMessage(), e); + } finally { + + 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, + AuditLogConstant.NO_ID.toString(), ApiName.AUDIT); + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + qcUserId, "PacketInfoManagerImpl::getPacketsforQCUser()::exit"); + } + + } + + /** + * Gets the identity keys and fetch values from JSON. + * + * @param registrationId the demographic json string @return the identity + * keys and fetch values from JSON @throws + * PacketDecryptionFailureException @throws ApiNotAccessibleException @throws + */ + @Override + public IndividualDemographicDedupe getIdentityKeysAndFetchValuesFromJSON(String registrationId, String process, ProviderStageName stageName) { + IndividualDemographicDedupe demographicData = new IndividualDemographicDedupe(); + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", + "PacketInfoManagerImpl::getIdentityKeysAndFetchValuesFromJSON()::entry"); + try { + List fields = new ArrayList<>(); + + JSONObject regProcessorIdentityJson = utility.getRegistrationProcessorMappingJson(MappingJsonConstants.IDENTITY); + String nameKey = JsonUtil.getJSONValue( + JsonUtil.getJSONObject(regProcessorIdentityJson, MappingJsonConstants.NAME), + MappingJsonConstants.VALUE); + String dob = JsonUtil.getJSONValue( + JsonUtil.getJSONObject(regProcessorIdentityJson, MappingJsonConstants.DOB), + MappingJsonConstants.VALUE); + String gender = JsonUtil.getJSONValue( + JsonUtil.getJSONObject(regProcessorIdentityJson, MappingJsonConstants.GENDER), + MappingJsonConstants.VALUE); + String phone = JsonUtil.getJSONValue( + JsonUtil.getJSONObject(regProcessorIdentityJson, MappingJsonConstants.PHONE), + MappingJsonConstants.VALUE); + String email = JsonUtil.getJSONValue( + JsonUtil.getJSONObject(regProcessorIdentityJson, MappingJsonConstants.EMAIL), + MappingJsonConstants.VALUE); + + fields.addAll(Arrays.asList(nameKey.split(","))); + fields.add(dob); + fields.add(gender); + fields.add(email); + fields.add(phone); + + Map fieldMap = packetManagerService.getFields(registrationId, fields, process, stageName); + + + String[] names = ((String) JsonUtil.getJSONValue(JsonUtil.getJSONObject(regProcessorIdentityJson, MappingJsonConstants.NAME), + "value")).split(","); + List jsonValueList = new ArrayList<>(); + for (String name : names) { + if (fieldMap.get(name) != null) { + JSONObject jsonObject = new JSONObject(); + jsonObject.put(name, objectMapper.readValue(fieldMap.get(name), Object.class)); + JsonValue[] nameArray = JsonUtil.getJsonValues(jsonObject, name); + if (nameArray != null) + jsonValueList.add(nameArray); + } + } + demographicData.setName(jsonValueList.isEmpty() ? null : jsonValueList); + demographicData.setDateOfBirth(fieldMap.get(dob)); + if (fieldMap.get(gender) != null) { + JSONObject jsonObject = new JSONObject(); + jsonObject.put(gender, objectMapper.readValue(fieldMap.get(gender), Object.class)); + demographicData.setGender(JsonUtil.getJsonValues(jsonObject, gender)); + } + demographicData.setPhone(fieldMap.get(phone)); + demographicData.setEmail(fieldMap.get(email)); + + } catch (IOException e) { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + "", e.getMessage() + ExceptionUtils.getStackTrace(e)); + + throw new MappingJsonException(PlatformErrorMessages.RPR_SYS_IDENTITY_JSON_MAPPING_EXCEPTION.getMessage(), + e); + + } + catch (Exception e) { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + "", e.getMessage() + ExceptionUtils.getStackTrace(e)); + + throw new ParsingException(PlatformErrorMessages.RPR_SYS_JSON_PARSING_EXCEPTION.getMessage(), e); + } + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", + "PacketInfoManagerImpl::getIdentityKeysAndFetchValuesFromJSON()::exit"); + return demographicData; + + } + + + + /** + * Save individual demographic dedupe. + * + * @param regId the regId + * @param description + */ + private void saveIndividualDemographicDedupe(String regId, String process, LogDescription description, + String moduleId, String moduleName, Integer iteration, String workflowInstanceId) throws Exception { + + boolean isTransactionSuccessful = false; + + IndividualDemographicDedupe demographicData = getIdentityKeysAndFetchValuesFromJSON(regId, process, ProviderStageName.DEMO_DEDUPE); + + try { + List applicantDemographicEntities = PacketInfoMapper + .converDemographicDedupeDtoToEntity(demographicData, regId,process,iteration, workflowInstanceId,trimWhitespace); + for (IndividualDemographicDedupeEntity applicantDemographicEntity : applicantDemographicEntities) { + demographicDedupeRepository.save(applicantDemographicEntity); + + } + isTransactionSuccessful = true; + description.setMessage("Individual Demographic Dedupe data saved "); + + } catch (DataAccessLayerException e) { + description.setMessage("DataAccessLayerException while saving Individual Demographic Dedupe data " + "::" + + e.getMessage()); + + throw new UnableToInsertData(PlatformErrorMessages.RPR_PIS_UNABLE_TO_INSERT_DATA.getMessage() + regId, e); + } finally { + + String eventId = isTransactionSuccessful ? EventId.RPR_407.toString() : EventId.RPR_405.toString(); + String eventName = eventId.equalsIgnoreCase(EventId.RPR_407.toString()) ? EventName.ADD.toString() + : EventName.EXCEPTION.toString(); + String eventType = eventId.equalsIgnoreCase(EventId.RPR_407.toString()) ? EventType.BUSINESS.toString() + : EventType.SYSTEM.toString(); + auditLogRequestBuilder.createAuditRequestBuilder(description.getMessage(), eventId, eventName, eventType, + moduleId, moduleName, regId); + + } + + } + + /* + * (non-Javadoc) + * + * @see + * io.mosip.registration.processor.core.spi.packetmanager.PacketInfoManager# + * saveIndividualDemographicDedupeUpdatePacket(io.mosip.registration.processor. + * core.packet.dto.demographicinfo.IndividualDemographicDedupe, + * java.lang.String) + */ + @Override + public void saveIndividualDemographicDedupeUpdatePacket(IndividualDemographicDedupe demographicData, + String registrationId, String moduleId,String process, String moduleName,Integer iteration, String workflowInstanceId) { + boolean isTransactionSuccessful = false; + LogDescription description = new LogDescription(); + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", + "PacketInfoManagerImpl::saveIndividualDemographicDedupeUpdatePacket()::entry"); + + try { + List applicantDemographicEntities = PacketInfoMapper + .converDemographicDedupeDtoToEntity(demographicData, registrationId,process,iteration, workflowInstanceId,trimWhitespace); + for (IndividualDemographicDedupeEntity applicantDemographicEntity : applicantDemographicEntities) { + demographicDedupeRepository.save(applicantDemographicEntity); + + } + isTransactionSuccessful = true; + description.setMessage("Individual Demographic Dedupe data saved "); + + } catch (DataAccessLayerException | NoSuchAlgorithmException e) { + description.setMessage("DataAccessLayerException while saving Individual Demographic Dedupe data " + "::" + + e.getMessage()); + + throw new UnableToInsertData( + PlatformErrorMessages.RPR_PIS_UNABLE_TO_INSERT_DATA.getMessage() + registrationId, e); + } finally { + + String eventId = isTransactionSuccessful ? EventId.RPR_407.toString() : EventId.RPR_405.toString(); + String eventName = eventId.equalsIgnoreCase(EventId.RPR_407.toString()) ? EventName.ADD.toString() + : EventName.EXCEPTION.toString(); + String eventType = eventId.equalsIgnoreCase(EventId.RPR_407.toString()) ? EventType.BUSINESS.toString() + : EventType.SYSTEM.toString(); + auditLogRequestBuilder.createAuditRequestBuilder(description.getMessage(), eventId, eventName, eventType, + moduleId, moduleName, registrationId); + + } + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", + "PacketInfoManagerImpl::saveIndividualDemographicDedupeUpdatePacket()::exit"); + + } + + /* + * (non-Javadoc) + * + * @see + * io.mosip.registration.processor.core.spi.packetmanager.PacketInfoManager# + * saveDemographicInfoJson(java.io.InputStream, java.util.List) + */ + @Override + public void saveDemographicInfoJson(String registrationId, String process, String moduleId, + String moduleName,Integer iteration, String workflowInstanceId) throws Exception { + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", + "PacketInfoManagerImpl::saveDemographicInfoJson()::entry"); + LogDescription description = new LogDescription(); + + boolean isTransactionSuccessful = false; + + + try { + + saveIndividualDemographicDedupe(registrationId, process, description, moduleId, moduleName, iteration, workflowInstanceId); + + isTransactionSuccessful = true; + description.setMessage("Demographic Json saved"); + + } catch (DataAccessLayerException e) { + + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + "", e.getMessage() + ExceptionUtils.getStackTrace(e)); + + description.setMessage("DataAccessLayerException while saving Demographic Json" + "::" + e.getMessage()); + + throw new UnableToInsertData( + PlatformErrorMessages.RPR_PIS_UNABLE_TO_INSERT_DATA.getMessage() + registrationId, e); + } finally { + + String eventId = isTransactionSuccessful ? EventId.RPR_407.toString() : EventId.RPR_405.toString(); + String eventName = eventId.equalsIgnoreCase(EventId.RPR_407.toString()) ? EventName.ADD.toString() + : EventName.EXCEPTION.toString(); + String eventType = eventId.equalsIgnoreCase(EventId.RPR_407.toString()) ? EventType.BUSINESS.toString() + : EventType.SYSTEM.toString(); + auditLogRequestBuilder.createAuditRequestBuilder(description.getMessage(), eventId, eventName, eventType, + moduleId, moduleName, registrationId); + + } + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", + "PacketInfoManagerImpl::saveDemographicInfoJson()::exit"); + + } + + /* + * (non-Javadoc) + * + * @see + * io.mosip.registration.processor.core.spi.packetmanager.PacketInfoManager# + * findDemoById(java.lang.String) + */ + @Override + public List findDemoById(String regId) { + return packetInfoDao.findDemoById(regId); + } + + /* + * (non-Javadoc) + * + * @see + * io.mosip.registration.processor.core.spi.packetmanager.PacketInfoManager# + * saveManualAdjudicationData(java.util.Set, java.lang.String) + */ + @Override + public void saveManualAdjudicationData(Set uniqueMatchedRefIds, MessageDTO messageDTO, + DedupeSourceName sourceName, String moduleId, String moduleName, String transactionId, String requestId) { + boolean isTransactionSuccessful = false; + LogDescription description = new LogDescription(); + String registrationId = messageDTO.getRid(); + + try { + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), + registrationId, "PacketInfoManagerImpl::saveManualAdjudicationData()::entry"); + for (String matchedRefId : uniqueMatchedRefIds) { + ManualVerificationEntity manualVerificationEntity = new ManualVerificationEntity(); + ManualVerificationPKEntity manualVerificationPKEntity = new ManualVerificationPKEntity(); + manualVerificationPKEntity.setMatchedRefId(matchedRefId); + manualVerificationPKEntity.setMatchedRefType(MATCHED_REFERENCE_TYPE); + manualVerificationPKEntity.setWorkflowInstanceId(messageDTO.getWorkflowInstanceId()); + + manualVerificationEntity.setRegId(registrationId); + manualVerificationEntity.setId(manualVerificationPKEntity); + manualVerificationEntity.setLangCode("eng"); + manualVerificationEntity.setRequestId(UUID.randomUUID().toString()); + //manualVerificationEntity.setMatchedScore(null); + manualVerificationEntity.setReponseText(null); + manualVerificationEntity.setRequestId(requestId); + manualVerificationEntity.setTransactionId(transactionId); + manualVerificationEntity.setMvUsrId(null); + manualVerificationEntity.setReasonCode("Potential Match"); + if (sourceName.equals(DedupeSourceName.DEMO)) { + manualVerificationEntity.setStatusCode(manualVerificationStatus); + + } else { + manualVerificationEntity.setStatusCode("PENDING"); + + } + manualVerificationEntity.setStatusComment("Assigned to manual Adjudication"); + manualVerificationEntity.setIsActive(true); + manualVerificationEntity.setIsDeleted(false); + manualVerificationEntity.setCrBy("SYSTEM"); + manualVerificationEntity.setCrDtimes(Timestamp.valueOf(LocalDateTime.now(ZoneId.of("UTC")))); + manualVerificationEntity.setUpdDtimes(Timestamp.valueOf(LocalDateTime.now(ZoneId.of("UTC")))); + manualVerificationEntity.setTrnTypCode(sourceName.toString()); + manualVerficationRepository.save(manualVerificationEntity); + isTransactionSuccessful = true; + description.setMessage("Manual Adjudication data saved successfully"); + } + + } catch (DataAccessLayerException e) { + description.setMessage("DataAccessLayerException while saving Manual Adjudication data for rid" + + registrationId + "::" + e.getMessage()); + + unAbleToInsertData(registrationId, e); + } finally { + + String eventId = isTransactionSuccessful ? EventId.RPR_407.toString() : EventId.RPR_405.toString(); + String eventName = eventId.equalsIgnoreCase(EventId.RPR_407.toString()) ? EventName.ADD.toString() + : EventName.EXCEPTION.toString(); + String eventType = eventId.equalsIgnoreCase(EventId.RPR_407.toString()) ? EventType.BUSINESS.toString() + : EventType.SYSTEM.toString(); + + auditLogRequestBuilder.createAuditRequestBuilder(description.getMessage(), eventId, eventName, eventType, + moduleId, moduleName, registrationId); + + } + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), + registrationId, "PacketInfoManagerImpl::saveManualAdjudicationData()::exit"); + } + + /* + * (non-Javadoc) + * + * @see + * io.mosip.registration.processor.core.spi.packetmanager.PacketInfoManager# + * getReferenceIdByRid(java.lang.String) + */ + @Override + public List getReferenceIdByWorkflowInstanceId(String workflowInstanceId) { + return regBioRefRepository.getRefIdByWorkflowInstanceId(workflowInstanceId); + } + + /* + * (non-Javadoc) + * + * @see + * io.mosip.registration.processor.core.spi.packetmanager.PacketInfoManager# + * getRidByReferenceId(java.lang.String) + */ + @Override + public List getRidByReferenceId(String refId) { + return regBioRefRepository.getRidByReferenceId(refId); + } + + /* + * (non-Javadoc) + * + * @see + * io.mosip.registration.processor.core.spi.packetmanager.PacketInfoManager# + * saveAbisRef(io.mosip.registration.processor.core.packet.dto.RegAbisRefDto) + */ + @Override + public void saveAbisRef(RegBioRefDto regBioRefDto, String moduleId, String moduleName) { + boolean isTransactionSuccessful = false; + LogDescription description = new LogDescription(); + String regId = regBioRefDto.getRegId(); + try { + if (regBioRefDto != null) { + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), + regId, "PacketInfoManagerImpl::saveAbisRef()::entry"); + + RegBioRefEntity regBioRefEntity = PacketInfoMapper.convertBioRefDtoToEntity(regBioRefDto); + regBioRefRepository.save(regBioRefEntity); + isTransactionSuccessful = true; + description.setMessage("ABIS data saved successfully"); + } + } catch (DataAccessLayerException e) { + description.setMessage("DataAccessLayerException while saving the ABIS data" + "::" + e.getMessage()); + unAbleToInsertData(regId, e); + } finally { + + createAudit(moduleId, moduleName, isTransactionSuccessful, description); + + } + + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), regId, + "PacketInfoManagerImpl::saveAbisRef()::exit"); + + } + + private void unAbleToInsertData(String regId, DataAccessLayerException e) { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + "", e.getMessage() + ExceptionUtils.getStackTrace(e)); + throw new UnableToInsertData(PlatformErrorMessages.RPR_PIS_UNABLE_TO_INSERT_DATA.getMessage() + regId, e); + } + + /* + * (non-Javadoc) + * + * @see + * io.mosip.registration.processor.core.spi.packetmanager.PacketInfoManager# + * getInsertOrIdentifyRequest(java.lang.String, java.lang.String) + */ + @Override + public List getInsertOrIdentifyRequest(String bioRefId, String refRegtrnId) { + List abisRequestList = packetInfoDao.getInsertOrIdentifyRequest(bioRefId, refRegtrnId); + return PacketInfoMapper.convertAbisRequestEntityListToDto(abisRequestList); + } + + @Override + public List getReferenceIdByBatchId(String batchId) { + return packetInfoDao.getReferenceIdByBatchId(batchId); + } + + /* + * (non-Javadoc) + * + * @see + * io.mosip.registration.processor.core.spi.packetmanager.PacketInfoManager# + * getAbisTransactionIdByRequestId(java.lang.String) + */ + @Override + public List getAbisTransactionIdByRequestId(String requestId) { + return packetInfoDao.getAbisTransactionIdByRequestId(requestId); + } + + @Override + public List getIdentifyReqListByTransactionId(String transactionId, String requestType) { + List abisRequestList = packetInfoDao.getIdentifyReqListByTransactionId(transactionId, + requestType); + return PacketInfoMapper.convertAbisRequestEntityListToDto(abisRequestList); + } + + /* + * (non-Javadoc) + * + * @see + * io.mosip.registration.processor.core.spi.packetmanager.PacketInfoManager# + * getBatchStatusbyBatchId(java.lang.String) + */ + @Override + public List getBatchStatusbyBatchId(String batchId) { + return packetInfoDao.getBatchStatusbyBatchId(batchId); + + } + + /* + * (non-Javadoc) + * + * @see + * io.mosip.registration.processor.core.spi.packetmanager.PacketInfoManager# + * getAbisRequestByRequestId(java.lang.String) + */ + @Override + public AbisRequestDto getAbisRequestByRequestId(String abisRequestId) { + List abisRequestList = packetInfoDao.getAbisRequestByRequestId(abisRequestId); + List abisRequestDtoList = PacketInfoMapper.convertAbisRequestEntityListToDto(abisRequestList); + if (!abisRequestDtoList.isEmpty()) { + return PacketInfoMapper.convertAbisRequestEntityListToDto(abisRequestList).get(0); + } else { + return null; + + } + } + + /* + * (non-Javadoc) + * + * @see + * io.mosip.registration.processor.core.spi.packetmanager.PacketInfoManager# + * getBatchIdByRequestId(java.lang.String) + */ + @Override + public String getBatchIdByRequestId(String abisRequestId) { + return packetInfoDao.getBatchIdByRequestId(abisRequestId); + } + + /* + * (non-Javadoc) + * + * @see + * io.mosip.registration.processor.core.spi.packetmanager.PacketInfoManager# + * getInsertOrIdentifyRequest(java.lang.String, java.lang.String, + * java.lang.String) + */ + @Override + public List getInsertOrIdentifyRequest(String bioRefId, String refRegtrnId, String requestType) { + List abisRequestEntities = packetInfoDao.getInsertOrIdentifyRequest(bioRefId, refRegtrnId, + requestType); + return PacketInfoMapper.convertAbisRequestEntityListToDto(abisRequestEntities); + } + + /* + * (non-Javadoc) + * + * @see + * io.mosip.registration.processor.core.spi.packetmanager.PacketInfoManager# + * getIdentifyByTransactionId(java.lang.String, java.lang.String) + */ + @Override + public Boolean getIdentifyByTransactionId(String transactionId, String identify) { + List abisRequestList = packetInfoDao.getIdentifyByTransactionId(transactionId, identify); + return abisRequestList.isEmpty() ? Boolean.FALSE : Boolean.TRUE; + } + + /* + * (non-Javadoc) + * + * @see + * io.mosip.registration.processor.core.spi.packetmanager.PacketInfoManager# + * getBioRefIdByRegId(java.lang.String) + */ + @Override + public List getBioRefIdByRegId(String regId) { + List regBioRefEntityList = packetInfoDao.getBioRefIdByRegId(regId); + return PacketInfoMapper.convertRegBioRefEntityListToDto(regBioRefEntityList); + } + + /* + * (non-Javadoc) + * + * @see + * io.mosip.registration.processor.core.spi.packetmanager.PacketInfoManager# + * getAllAbisDetails() + */ + @Override + public List getAllAbisDetails() { + List abisApplicationEntityList = regAbisApplicationRepository + .findAll(AbisApplicationEntity.class); + return PacketInfoMapper.convertAbisApplicationEntityListToDto(abisApplicationEntityList); + } + + /* + * (non-Javadoc) + * + * @see + * io.mosip.registration.processor.core.spi.packetmanager.PacketInfoManager# + * saveBioRef(io.mosip.registration.processor.core.packet.dto.abis.RegBioRefDto) + */ + @Override + public void saveBioRef(RegBioRefDto regBioRefDto, String moduleId, String moduleName) { + boolean isTransactionSuccessful = false; + LogDescription description = new LogDescription(); + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", + "PacketInfoManagerImpl::saveBioRef()::entry"); + + try { + RegBioRefEntity regBioRefEntity = PacketInfoMapper.convertBioRefDtoToEntity(regBioRefDto); + regBioRefRepository.save(regBioRefEntity); + isTransactionSuccessful = true; + description.setMessage("Bio ref data saved successfully"); + } catch (DataAccessLayerException e) { + description.setMessage("DataAccessLayerException while saving ABIS data" + "::" + e.getMessage()); + + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + "", e.getMessage() + ExceptionUtils.getStackTrace(e)); + throw new UnableToInsertData( + PlatformErrorMessages.RPR_PIS_UNABLE_TO_INSERT_DATA.getMessage() + regBioRefDto.getRegId(), e); + } finally { + + createAudit(moduleId, moduleName, isTransactionSuccessful, description); + + } + + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", + "PacketInfoManagerImpl::saveBioRef()::exit"); + + } + + /* + * (non-Javadoc) + * + * @see + * io.mosip.registration.processor.core.spi.packetmanager.PacketInfoManager# + * saveAbisRequest(io.mosip.registration.processor.core.packet.dto.abis. + * AbisRequestDto) + */ + @Override + public void saveAbisRequest(AbisRequestDto abisRequestDto, String moduleId, String moduleName) { + boolean isTransactionSuccessful = false; + LogDescription description = new LogDescription(); + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", + "PacketInfoManagerImpl::saveAbisRequest()::entry"); + + try { + AbisRequestEntity abisRequestEntity = PacketInfoMapper.convertAbisRequestDtoToEntity(abisRequestDto); + regAbisRequestRepository.save(abisRequestEntity); + isTransactionSuccessful = true; + description.setMessage("ABIS Request data saved successfully"); + } catch (DataAccessLayerException e) { + description.setMessage("DataAccessLayerException while saving ABIS data" + "::" + e.getMessage()); + + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + "", e.getMessage() + ExceptionUtils.getStackTrace(e)); + throw new UnableToInsertData( + PlatformErrorMessages.RPR_PIS_UNABLE_TO_INSERT_DATA.getMessage() + abisRequestDto.getId(), e); + } finally { + + createAudit(moduleId, moduleName, isTransactionSuccessful, description); + + } + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", + "PacketInfoManagerImpl::saveAbisRequest()::exit"); + + } + + /* + * (non-Javadoc) + * + * @see + * io.mosip.registration.processor.core.spi.packetmanager.PacketInfoManager# + * getDemoListByTransactionId(java.lang.String) + */ + @Override + public List getDemoListByTransactionId(String transactionId) { + List regDemoDedupeListEntityList = packetInfoDao + .getDemoListByTransactionId(transactionId); + return PacketInfoMapper.convertDemoDedupeEntityListToDto(regDemoDedupeListEntityList); + } + + /* + * (non-Javadoc) + * + * @see + * io.mosip.registration.processor.core.spi.packetmanager.PacketInfoManager# + * saveDemoDedupePotentialData(io.mosip.registration.processor.core.packet.dto. + * abis.RegDemoDedupeListDto) + */ + @Override + public void saveDemoDedupePotentialData(RegDemoDedupeListDto regDemoDedupeListDto, String moduleId, + String moduleName) { + boolean isTransactionSuccessful = false; + LogDescription description = new LogDescription(); + + String regId = ""; + try { + + if (regDemoDedupeListDto != null) { + regId = regDemoDedupeListDto.getRegId(); + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), + regId, "PacketInfoManagerImpl::saveDemoDedupePotentialData()::entry"); + + RegDemoDedupeListEntity regDemoDedupeListEntity = PacketInfoMapper + .convertDemoDedupeEntityToDto(regDemoDedupeListDto); + regDemoDedupeListRepository.save(regDemoDedupeListEntity); + isTransactionSuccessful = true; + description.setMessage("Demo dedupe potential match data saved successfully"); + + } + } catch (DataAccessLayerException e) { + description.setMessage( + "DataAccessLayerException while saving Demo dedupe potential match data" + "::" + e.getMessage()); + + unAbleToInsertData(regId, e); + } finally { + + createAudit(moduleId, moduleName, isTransactionSuccessful, description); + + } + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), regId, + "PacketInfoManagerImpl::saveDemoDedupePotentialData()::exit"); + } + + private void createAudit(String moduleId, String moduleName, boolean isTransactionSuccessful, + LogDescription description) { + String eventId = isTransactionSuccessful ? EventId.RPR_407.toString() : EventId.RPR_405.toString(); + String eventName = eventId.equalsIgnoreCase(EventId.RPR_407.toString()) ? EventName.ADD.toString() + : EventName.EXCEPTION.toString(); + String eventType = eventId.equalsIgnoreCase(EventId.RPR_407.toString()) ? EventType.BUSINESS.toString() + : EventType.SYSTEM.toString(); + + auditLogRequestBuilder.createAuditRequestBuilder(description.getMessage(), eventId, eventName, eventType, + moduleId, moduleName, AuditLogConstant.NO_ID.toString()); + } + + /* + * (non-Javadoc) + * + * @see + * io.mosip.registration.processor.core.spi.packetmanager.PacketInfoManager# + * getAbisResponseRecords(java.lang.String, java.lang.String) + */ + @Override + public List getAbisResponseRecords(String latestTransactionId, String requestType) { + return packetInfoDao.getAbisResponseRecords(latestTransactionId, requestType); + } + + /* + * (non-Javadoc) + * + * @see + * io.mosip.registration.processor.core.spi.packetmanager.PacketInfoManager# + * getAbisResponseRecords(java.lang.String, java.lang.String, java.lang.String) + */ + @Override + public List getAbisResponseRecords(String abisRefId, String latestTransactionId, + String requestType) { + return packetInfoDao.getAbisResponseRecords(abisRefId, latestTransactionId, requestType); + } + + /* + * (non-Javadoc) + * + * @see + * io.mosip.registration.processor.core.spi.packetmanager.PacketInfoManager# + * getAbisResponseDetRecords(io.mosip.registration.processor.core.packet.dto. + * abis.AbisResponseDto) + */ + @Override + public List getAbisResponseDetRecords(AbisResponseDto abisResponseDto) { + return packetInfoDao.getAbisResponseDetailedRecords(abisResponseDto); + } + + /* + * (non-Javadoc) + * + * @see + * io.mosip.registration.processor.core.spi.packetmanager.PacketInfoManager# + * getAbisResponseIDs(java.lang.String) + */ + @Override + public List getAbisResponseIDs(String abisRequestId) { + return PacketInfoMapper.convertAbisResponseEntityListToDto(packetInfoDao.getAbisResponseIDs(abisRequestId)); + } + + /* + * (non-Javadoc) + * + * @see + * io.mosip.registration.processor.core.spi.packetmanager.PacketInfoManager# + * getAbisResponseDetails(java.lang.String) + */ + @Override + public List getAbisResponseDetails(String abisResponseId) { + return PacketInfoMapper + .convertAbisResponseDetEntityListToDto(packetInfoDao.getAbisResponseDetails(abisResponseId)); + } + + /* + * (non-Javadoc) + * + * @see + * io.mosip.registration.processor.core.spi.packetmanager.PacketInfoManager# + * getAbisRequestsByBioRefId(java.lang.String) + */ + @Override + public List getAbisRequestsByBioRefId(String bioRefId) { + List abisRequestEntityList = packetInfoDao.getAbisRequestsByBioRefId(bioRefId); + return PacketInfoMapper.convertAbisRequestEntityListToDto(abisRequestEntityList); + } + + @Override + public List getAbisProcessedRequestsAppCodeByBioRefId(String bioRefId, String requestType, + String processed) { + return packetInfoDao.getAbisProcessedRequestsAppCodeByBioRefId(bioRefId, requestType, processed); + } + + @Override + public List getAbisResponseDetRecordsList(List abisResponseDto) { + return packetInfoDao.getAbisResponseDetRecordsList(abisResponseDto); + } + + @Override + public void saveRegLostUinDet(String regId, String workflowInstanceId, String latestRegId, String moduleId, String moduleName) { + boolean isTransactionSuccessful = false; + LogDescription description = new LogDescription(); + + try { + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), regId, + "PacketInfoManagerImpl::saveRegLostUinDetData()::entry"); + RegLostUinDetEntity regLostUinDetEntity = new RegLostUinDetEntity(); + RegLostUinDetPKEntity regLostUinDetPKEntity = new RegLostUinDetPKEntity(); + regLostUinDetPKEntity.setWorkflowInstanceId(workflowInstanceId); + + regLostUinDetEntity.setRegId(regId); + regLostUinDetEntity.setId(regLostUinDetPKEntity); + regLostUinDetEntity.setLatestRegId(latestRegId); + regLostUinDetEntity.setCrBy("SYSTEM"); + regLostUinDetEntity.setCrDtimes(LocalDateTime.now(ZoneId.of("UTC"))); + regLostUinDetEntity.setUpdDtimes(LocalDateTime.now(ZoneId.of("UTC"))); + regLostUinDetEntity.setIsDeleted(false); + + regLostUinDetRepository.save(regLostUinDetEntity); + isTransactionSuccessful = true; + description.setMessage("Lost Uin detail data saved successfully"); + } catch (DataAccessLayerException e) { + description.setMessage("DataAccessLayerException while saving Lost Uin detail data for rid" + regId + "::" + + e.getMessage()); + + unAbleToInsertData(regId, e); + } finally { + + createAudit(moduleId, moduleName, isTransactionSuccessful, description); + + } + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), regId, + "PacketInfoManagerImpl::saveRegLostUinDetData()::exit"); + + } + + @Override + public List getRegBioRefDataByBioRefIds(List bioRefId) { + List regBioRefList = packetInfoDao.getRegBioRefDataByBioRefIds(bioRefId); + return PacketInfoMapper.convertRegBioRefEntityListToDto(regBioRefList); + } + + +} diff --git a/registration-processor/registration-processor-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/service/impl/RegistrationStatusServiceImpl.java b/registration-processor/registration-processor-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/service/impl/RegistrationStatusServiceImpl.java index 76647932140..a47e57314fc 100644 --- a/registration-processor/registration-processor-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/service/impl/RegistrationStatusServiceImpl.java +++ b/registration-processor/registration-processor-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/service/impl/RegistrationStatusServiceImpl.java @@ -949,14 +949,7 @@ public void updateRegistrationStatusForWorkflow(InternalRegistrationStatusDto re PlatformErrorMessages.RPR_RGS_REGISTRATION_TABLE_NOT_ACCESSIBLE.getMessage(), e); } finally { - String eventId = isTransactionSuccessful ? EventId.RPR_407.toString() : EventId.RPR_405.toString(); - String eventName = eventId.equalsIgnoreCase(EventId.RPR_407.toString()) ? EventName.UPDATE.toString() - : EventName.EXCEPTION.toString(); - String eventType = eventId.equalsIgnoreCase(EventId.RPR_407.toString()) ? EventType.BUSINESS.toString() - : EventType.SYSTEM.toString(); - - auditLogRequestBuilder.createAuditRequestBuilder(description.getMessage(), eventId, eventName, eventType, - moduleId, moduleName, registrationStatusDto.getRegistrationId()); + createAudit(registrationStatusDto, moduleId, moduleName, isTransactionSuccessful, description); } regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), @@ -964,5 +957,17 @@ public void updateRegistrationStatusForWorkflow(InternalRegistrationStatusDto re "RegistrationStatusServiceImpl::updateRegistrationStatusForWorkFlow()::exit"); } + + private void createAudit(InternalRegistrationStatusDto registrationStatusDto, String moduleId, String moduleName, + boolean isTransactionSuccessful, LogDescription description) { + String eventId = isTransactionSuccessful ? EventId.RPR_407.toString() : EventId.RPR_405.toString(); + String eventName = eventId.equalsIgnoreCase(EventId.RPR_407.toString()) ? EventName.UPDATE.toString() + : EventName.EXCEPTION.toString(); + String eventType = eventId.equalsIgnoreCase(EventId.RPR_407.toString()) ? EventType.BUSINESS.toString() + : EventType.SYSTEM.toString(); + + auditLogRequestBuilder.createAuditRequestBuilder(description.getMessage(), eventId, eventName, eventType, + moduleId, moduleName, registrationStatusDto.getRegistrationId()); + } } diff --git a/registration-processor/registration-processor-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/service/impl/SyncRegistrationServiceImpl.java b/registration-processor/registration-processor-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/service/impl/SyncRegistrationServiceImpl.java index c487a9efcae..5b359f6db50 100644 --- a/registration-processor/registration-processor-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/service/impl/SyncRegistrationServiceImpl.java +++ b/registration-processor/registration-processor-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/service/impl/SyncRegistrationServiceImpl.java @@ -1,1026 +1,1010 @@ -/** - * - */ -package io.mosip.registration.processor.status.service.impl; - -import java.net.URI; -import java.security.NoSuchAlgorithmException; -import java.sql.Timestamp; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.time.ZoneId; -import java.time.format.DateTimeFormatter; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - -import io.mosip.kernel.core.util.DateUtils; -import org.json.JSONException; -import org.json.JSONObject; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.core.env.Environment; -import org.springframework.stereotype.Component; - -import com.fasterxml.jackson.databind.ObjectMapper; - -import io.mosip.kernel.core.dataaccess.exception.DataAccessLayerException; -import io.mosip.kernel.core.exception.ExceptionUtils; -import io.mosip.kernel.core.exception.IOException; -import io.mosip.kernel.core.idvalidator.exception.InvalidIDException; -import io.mosip.kernel.core.idvalidator.spi.RidValidator; -import io.mosip.kernel.core.logger.spi.Logger; -import io.mosip.kernel.core.util.CryptoUtil; -import io.mosip.kernel.core.util.HMACUtils2; -import io.mosip.kernel.core.util.JsonUtils; -import io.mosip.kernel.core.util.StringUtils; -import io.mosip.kernel.core.util.exception.JsonMappingException; -import io.mosip.kernel.core.util.exception.JsonParseException; -import io.mosip.kernel.core.util.exception.JsonProcessingException; -import io.mosip.kernel.idvalidator.rid.constant.RidExceptionProperty; -import io.mosip.registration.processor.core.anonymous.dto.AnonymousProfileDTO; -import io.mosip.registration.processor.core.code.EventId; -import io.mosip.registration.processor.core.code.EventName; -import io.mosip.registration.processor.core.code.EventType; -import io.mosip.registration.processor.core.code.ModuleName; -import io.mosip.registration.processor.core.constant.AuditLogConstant; -import io.mosip.registration.processor.core.constant.LoggerFileConstant; -import io.mosip.registration.processor.core.constant.MappingJsonConstants; -import io.mosip.registration.processor.core.constant.ResponseStatusCode; -import io.mosip.registration.processor.core.exception.ApisResourceAccessException; -import io.mosip.registration.processor.core.exception.util.PlatformErrorMessages; -import io.mosip.registration.processor.core.exception.util.PlatformSuccessMessages; -import io.mosip.registration.processor.core.logger.LogDescription; -import io.mosip.registration.processor.core.logger.RegProcessorLogger; -import io.mosip.registration.processor.core.util.JsonUtil; -import io.mosip.registration.processor.rest.client.audit.builder.AuditLogRequestBuilder; -import io.mosip.registration.processor.rest.client.utils.RestApiClient; -import io.mosip.registration.processor.status.code.RegistrationExternalStatusCode; -import io.mosip.registration.processor.status.code.SupervisorStatus; -import io.mosip.registration.processor.status.dao.SyncRegistrationDao; -import io.mosip.registration.processor.status.decryptor.Decryptor; -import io.mosip.registration.processor.status.dto.FilterInfo; -import io.mosip.registration.processor.status.dto.LostRidDto; -import io.mosip.registration.processor.status.dto.RegistrationAdditionalInfoDTO; -import io.mosip.registration.processor.status.dto.RegistrationStatusDto; -import io.mosip.registration.processor.status.dto.RegistrationStatusSubRequestDto; -import io.mosip.registration.processor.status.dto.RegistrationSyncRequestDTO; -import io.mosip.registration.processor.status.dto.SearchInfo; -import io.mosip.registration.processor.status.dto.SyncRegistrationDto; -import io.mosip.registration.processor.status.dto.SyncResponseDto; -import io.mosip.registration.processor.status.dto.SyncResponseFailDto; -import io.mosip.registration.processor.status.dto.SyncResponseFailureDto; -import io.mosip.registration.processor.status.dto.SyncResponseFailureV2Dto; -import io.mosip.registration.processor.status.dto.SyncResponseSuccessDto; -import io.mosip.registration.processor.status.dto.SyncResponseSuccessV2Dto; -import io.mosip.registration.processor.status.encryptor.Encryptor; -import io.mosip.registration.processor.status.entity.SyncRegistrationEntity; -import io.mosip.registration.processor.status.exception.EncryptionFailureException; -import io.mosip.registration.processor.status.exception.LostRidValidationException; -import io.mosip.registration.processor.status.exception.PacketDecryptionFailureException; -import io.mosip.registration.processor.status.exception.RegStatusAppException; -import io.mosip.registration.processor.status.exception.TablenotAccessibleException; -import io.mosip.registration.processor.status.service.AnonymousProfileService; -import io.mosip.registration.processor.status.service.SyncRegistrationService; -import io.mosip.registration.processor.status.utilities.RegistrationUtility; - -/** - * The Class SyncRegistrationServiceImpl. - * - * @author M1048399 - * @author M1048219 - * @author M1047487 - */ -@Component -public class SyncRegistrationServiceImpl implements SyncRegistrationService { - - /** The Constant CREATED_BY. */ - private static final String CREATED_BY = "MOSIP"; - - /** The event id. */ - private String eventId = ""; - - /** The event name. */ - private String eventName = ""; - - @Value("${mosip.registration.processor.postalcode.req.url}") - private String locationCodeReqUrl; - - @Value("${mosip.registration.processor.lostrid.iteration.max.count:10000}") - private int iteration; - - @Value("${registration.processor.lostrid.max.registrationid:5}") - private int maxSearchResult; - - /** The event type. */ - private String eventType = ""; - - /** The sync registration dao. */ - @Autowired - private SyncRegistrationDao syncRegistrationDao; - /** The sync AnonymousProfileService . */ - @Autowired - private AnonymousProfileService anonymousProfileService; - - /** The core audit request builder. */ - @Autowired - private AuditLogRequestBuilder auditLogRequestBuilder; - - /** The rid validator. */ - @Autowired - private RidValidator ridValidator; - - @Autowired - ObjectMapper objectMapper; - - @Autowired - private RegistrationUtility registrationUtility; - - /** The lancode length. */ - private int LANCODE_LENGTH = 3; - - /** The reg proc logger. */ - private static Logger regProcLogger = RegProcessorLogger.getLogger(SyncRegistrationServiceImpl.class); - - /** The decryptor. */ - @Autowired - private Decryptor decryptor; - - /** The encryptor. */ - @Autowired - private Encryptor encryptor; - - @Value("#{'${registration.processor.main-processes}'.split(',')}") - private List mainProcesses; - - @Value("#{'${registration.processor.sub-processes}'.split(',')}") - private List subProcesses; - - /** The config server file storage URL. */ - @Value("${config.server.file.storage.uri}") - private String configServerFileStorageURL; - - /** The get reg processor identity json. */ - @Value("${registration.processor.identityjson}") - private String getRegProcessorIdentityJson; - - @Autowired - RestApiClient restApiClient; - /** - * Instantiates a new sync registration service impl. - */ - public SyncRegistrationServiceImpl() { - super(); - } - - /* - * (non-Javadoc) - * - * @see - * io.mosip.registration.processor.status.service.SyncRegistrationService#sync( - * java.util.List) - */ - public List sync(List resgistrationDtos, String referenceId, - String timeStamp) { - List syncResponseList = new ArrayList<>(); - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", - "SyncRegistrationServiceImpl::sync()::entry"); - LogDescription description = new LogDescription(); - boolean isTransactionSuccessful = false; - try { - for (SyncRegistrationDto registrationDto : resgistrationDtos) { - syncResponseList = validateSync(registrationDto, syncResponseList, referenceId, timeStamp); - } - isTransactionSuccessful = true; - description.setMessage("Registartion Id's are successfully synched in Sync Registration table"); - - regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - "", ""); - } catch (DataAccessLayerException e) { - description.setMessage(PlatformErrorMessages.RPR_RGS_DATA_ACCESS_EXCEPTION.getMessage()); - description.setCode(PlatformErrorMessages.RPR_RGS_DATA_ACCESS_EXCEPTION.getCode()); - description.setMessage("DataAccessLayerException while syncing Registartion Id's" + "::" + e.getMessage()); - - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - "", e.getMessage() + ExceptionUtils.getStackTrace(e)); - throw new TablenotAccessibleException( - PlatformErrorMessages.RPR_RGS_REGISTRATION_TABLE_NOT_ACCESSIBLE.getMessage(), e); - } finally { - if (isTransactionSuccessful) { - eventName = eventId.equalsIgnoreCase(EventId.RPR_402.toString()) ? EventName.UPDATE.toString() - : EventName.ADD.toString(); - eventType = EventType.BUSINESS.toString(); - } else { - description.setMessage(PlatformErrorMessages.RPR_RGS_REGISTRATION_SYNC_SERVICE_FAILED.getMessage()); - description.setCode(PlatformErrorMessages.RPR_RGS_REGISTRATION_SYNC_SERVICE_FAILED.getCode()); - eventId = EventId.RPR_405.toString(); - eventName = EventName.EXCEPTION.toString(); - eventType = EventType.SYSTEM.toString(); - } - /** Module-Id can be Both Success/Error code */ - String moduleId = isTransactionSuccessful - ? PlatformSuccessMessages.RPR_SYNC_REGISTRATION_SERVICE_SUCCESS.getCode() - : description.getCode(); - String moduleName = ModuleName.SYNC_REGISTRATION_SERVICE.toString(); - auditLogRequestBuilder.createAuditRequestBuilder(description.getMessage(), eventId, eventName, eventType, - moduleId, moduleName, AuditLogConstant.MULTIPLE_ID.toString()); - - } - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", - "SyncRegistrationServiceImpl::sync()::exit"); - return syncResponseList; - - } - - public List syncV2(List resgistrationDtos, String referenceId, - String timeStamp) { - List syncResponseList = new ArrayList<>(); - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", - "SyncRegistrationServiceImpl::sync()::entry"); - LogDescription description = new LogDescription(); - boolean isTransactionSuccessful = false; - try { - for (SyncRegistrationDto registrationDto : resgistrationDtos) { - if(registrationDto.getPacketId()!=null && !registrationDto.getPacketId().isBlank()){ - syncResponseList = validateSyncV2(registrationDto, syncResponseList, referenceId, timeStamp); - } - else { - SyncResponseFailDto syncResponseFailureDto = new SyncResponseFailDto(); - syncResponseFailureDto.setStatus(ResponseStatusCode.FAILURE.toString()); - syncResponseFailureDto.setMessage("Missing Request Value - packetId"); - syncResponseFailureDto.setErrorCode(PlatformErrorMessages.RPR_RGS_MISSING_INPUT_PARAMETER.getCode()); - syncResponseList.add(syncResponseFailureDto); - } - } - isTransactionSuccessful = true; - description.setMessage("Registartion Id's are successfully synched in Sync Registration table"); - - regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - "", ""); - } catch (DataAccessLayerException e) { - description.setMessage(PlatformErrorMessages.RPR_RGS_DATA_ACCESS_EXCEPTION.getMessage()); - description.setCode(PlatformErrorMessages.RPR_RGS_DATA_ACCESS_EXCEPTION.getCode()); - description.setMessage("DataAccessLayerException while syncing Registartion Id's" + "::" + e.getMessage()); - - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - "", e.getMessage() + ExceptionUtils.getStackTrace(e)); - throw new TablenotAccessibleException( - PlatformErrorMessages.RPR_RGS_REGISTRATION_TABLE_NOT_ACCESSIBLE.getMessage(), e); - } finally { - if (isTransactionSuccessful) { - eventName = eventId.equalsIgnoreCase(EventId.RPR_402.toString()) ? EventName.UPDATE.toString() - : EventName.ADD.toString(); - eventType = EventType.BUSINESS.toString(); - } else { - description.setMessage(PlatformErrorMessages.RPR_RGS_REGISTRATION_SYNC_SERVICE_FAILED.getMessage()); - description.setCode(PlatformErrorMessages.RPR_RGS_REGISTRATION_SYNC_SERVICE_FAILED.getCode()); - eventId = EventId.RPR_405.toString(); - eventName = EventName.EXCEPTION.toString(); - eventType = EventType.SYSTEM.toString(); - } - /** Module-Id can be Both Success/Error code */ - String moduleId = isTransactionSuccessful - ? PlatformSuccessMessages.RPR_SYNC_REGISTRATION_SERVICE_SUCCESS.getCode() - : description.getCode(); - String moduleName = ModuleName.SYNC_REGISTRATION_SERVICE.toString(); - auditLogRequestBuilder.createAuditRequestBuilder(description.getMessage(), eventId, eventName, eventType, - moduleId, moduleName, AuditLogConstant.MULTIPLE_ID.toString()); - - } - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", - "SyncRegistrationServiceImpl::sync()::exit"); - return syncResponseList; - - } - - /** - * Validate RegiId with Kernel RidValiator. - * - * @param registrationDto - * the registration dto - * @param syncResponseList - * the sync response list - * @return the list - */ - private List validateSync(SyncRegistrationDto registrationDto, - List syncResponseList, String referenceId, - String timeStamp) { - if (validateLanguageCode(registrationDto, syncResponseList) - && validateRegistrationType(registrationDto, syncResponseList) - && validateHashValue(registrationDto, syncResponseList) - && validateSupervisorStatus(registrationDto, syncResponseList)) { - if (validateRegistrationID(registrationDto, syncResponseList)) { - SyncResponseFailureDto syncResponseFailureDto = new SyncResponseFailureDto(); - try { - if (ridValidator.validateId(registrationDto.getRegistrationId())) { - syncResponseList = syncRegistrationRecord(registrationDto, syncResponseList, referenceId, timeStamp); - } - } catch (InvalidIDException e) { - syncResponseFailureDto.setRegistrationId(registrationDto.getRegistrationId()); - - syncResponseFailureDto.setStatus(ResponseStatusCode.FAILURE.toString()); - if (e.getErrorCode().equals(RidExceptionProperty.INVALID_RID_LENGTH.getErrorCode())) { - syncResponseFailureDto - .setMessage(PlatformErrorMessages.RPR_RGS_INVALID_REGISTRATIONID_LENGTH.getMessage()); - syncResponseFailureDto - .setErrorCode(PlatformErrorMessages.RPR_RGS_INVALID_REGISTRATIONID_LENGTH.getCode()); - } else if (e.getErrorCode().equals(RidExceptionProperty.INVALID_RID.getErrorCode())) { - syncResponseFailureDto - .setMessage(PlatformErrorMessages.RPR_RGS_INVALID_REGISTRATIONID.getMessage()); - syncResponseFailureDto - .setErrorCode(PlatformErrorMessages.RPR_RGS_INVALID_REGISTRATIONID.getCode()); - } else if (e.getErrorCode().equals(RidExceptionProperty.INVALID_RID_TIMESTAMP.getErrorCode())) { - syncResponseFailureDto.setMessage( - PlatformErrorMessages.RPR_RGS_INVALID_REGISTRATIONID_TIMESTAMP.getMessage()); - syncResponseFailureDto - .setErrorCode(PlatformErrorMessages.RPR_RGS_INVALID_REGISTRATIONID_TIMESTAMP.getCode()); - } - syncResponseList.add(syncResponseFailureDto); - } - } - } - return syncResponseList; - } - - - private List validateSyncV2(SyncRegistrationDto registrationDto, - List syncResponseList, String referenceId, - String timeStamp) { - if (validateLanguageCode(registrationDto, syncResponseList) - && validateRegistrationType(registrationDto, syncResponseList) - && validateHashValue(registrationDto, syncResponseList) - && validateSupervisorStatus(registrationDto, syncResponseList)) { - if (validateRegistrationID(registrationDto, syncResponseList)) { - syncResponseList = syncRegistrationRecord(registrationDto, syncResponseList, referenceId, timeStamp); - } - } - List syncResponseV2List=new ArrayList<>(); - for(SyncResponseDto dto:syncResponseList) { - if(dto instanceof SyncResponseFailureDto) { - SyncResponseFailureV2Dto v2Dto=new SyncResponseFailureV2Dto(dto.getRegistrationId(),dto.getStatus(), - ((SyncResponseFailureDto) dto).getErrorCode(),((SyncResponseFailureDto) dto).getMessage(), - registrationDto.getPacketId()); - syncResponseV2List.add(v2Dto); - } - if(dto instanceof SyncResponseSuccessDto || dto instanceof SyncResponseDto) { - SyncResponseSuccessV2Dto v2Dto=new SyncResponseSuccessV2Dto(dto.getRegistrationId(),dto.getStatus(), - registrationDto.getPacketId()); - syncResponseV2List.add(v2Dto); - } - if(dto instanceof SyncResponseFailDto) { - SyncResponseFailureV2Dto v2Dto=new SyncResponseFailureV2Dto(dto.getRegistrationId(),dto.getStatus(), - ((SyncResponseFailDto) dto).getErrorCode(),((SyncResponseFailDto) dto).getMessage(), - registrationDto.getPacketId()); - syncResponseV2List.add(v2Dto); - } - } - - return syncResponseV2List; - } - - /** - * Validate supervisor status. - * - * @param registrationDto - * the registration dto - * @param syncResponseList - * the sync response list - * @return true, if successful - */ - private boolean validateSupervisorStatus(SyncRegistrationDto registrationDto, - List syncResponseList) { - String value = registrationDto.getSupervisorStatus(); - if (SupervisorStatus.APPROVED.toString().equals(value)) { - return true; - } else if (SupervisorStatus.REJECTED.toString().equals(value)) { - return true; - - } else { - SyncResponseFailureDto syncResponseFailureDto = new SyncResponseFailureDto(); - syncResponseFailureDto.setRegistrationId(registrationDto.getRegistrationId()); - - syncResponseFailureDto.setStatus(ResponseStatusCode.FAILURE.toString()); - syncResponseFailureDto.setMessage(PlatformErrorMessages.RPR_RGS_INVALID_SUPERVISOR_STATUS.getMessage()); - syncResponseFailureDto.setErrorCode(PlatformErrorMessages.RPR_RGS_INVALID_SUPERVISOR_STATUS.getCode()); - syncResponseList.add(syncResponseFailureDto); - return false; - } - - } - - /** - * Validate hash value. - * - * @param registrationDto - * the registration dto - * @param syncResponseList - * the sync response list - * @return true, if successful - */ - private boolean validateHashValue(SyncRegistrationDto registrationDto, List syncResponseList) { - - if (registrationDto.getPacketHashValue() == null) { - SyncResponseFailureDto syncResponseFailureDto = new SyncResponseFailureDto(); - syncResponseFailureDto.setRegistrationId(registrationDto.getRegistrationId()); - - syncResponseFailureDto.setStatus(ResponseStatusCode.FAILURE.toString()); - syncResponseFailureDto.setMessage(PlatformErrorMessages.RPR_RGS_INVALID_HASHVALUE.getMessage()); - syncResponseFailureDto.setErrorCode(PlatformErrorMessages.RPR_RGS_INVALID_HASHVALUE.getCode()); - syncResponseList.add(syncResponseFailureDto); - return false; - } else { - return true; - } - } - - /** - * Validate status code. - * - * @param registrationDto - * the registration dto - * @param syncResponseList - * the sync response list - * @return true, if successful - */ - private boolean validateRegistrationType(SyncRegistrationDto registrationDto, - List syncResponseList) { - List processes=new ArrayList<>(); - processes.addAll(mainProcesses); - processes.addAll(subProcesses); - String value = registrationDto.getRegistrationType(); - if(processes.contains(value)) { - return true; - }else { - SyncResponseFailureDto syncResponseFailureDto = new SyncResponseFailureDto(); - syncResponseFailureDto.setRegistrationId(registrationDto.getRegistrationId()); - - syncResponseFailureDto.setStatus(ResponseStatusCode.FAILURE.toString()); - syncResponseFailureDto.setMessage(PlatformErrorMessages.RPR_RGS_INVALID_SYNCTYPE.getMessage()); - syncResponseFailureDto.setErrorCode(PlatformErrorMessages.RPR_RGS_INVALID_SYNCTYPE.getCode()); - syncResponseList.add(syncResponseFailureDto); - return false; - } - } - - /** - * Validate language code. - * - * @param registrationDto - * the registration dto - * @param syncResponseList - * the sync response list - * @return true, if successful - */ - private boolean validateLanguageCode(SyncRegistrationDto registrationDto, List syncResponseList) { - if (registrationDto.getLangCode().length() == LANCODE_LENGTH) { - return true; - } else { - SyncResponseFailureDto syncResponseFailureDto = new SyncResponseFailureDto(); - syncResponseFailureDto.setRegistrationId(registrationDto.getRegistrationId()); - - syncResponseFailureDto.setStatus(ResponseStatusCode.FAILURE.toString()); - syncResponseFailureDto.setMessage(PlatformErrorMessages.RPR_RGS_INVALID_LANGUAGECODE.getMessage()); - syncResponseFailureDto.setErrorCode(PlatformErrorMessages.RPR_RGS_INVALID_LANGUAGECODE.getCode()); - syncResponseList.add(syncResponseFailureDto); - return false; - } - } - - /** - * Validate registration ID. - * - * @param registrationDto - * the registration dto - * @param syncResponseList - * the sync response list - * @return true, if successful - */ - private boolean validateRegistrationID(SyncRegistrationDto registrationDto, - List syncResponseList) { - if (registrationDto.getRegistrationId() != null) { - return true; - } else { - SyncResponseFailureDto syncResponseFailureDto = new SyncResponseFailureDto(); - syncResponseFailureDto.setRegistrationId(registrationDto.getRegistrationId()); - syncResponseFailureDto.setStatus(ResponseStatusCode.FAILURE.toString()); - syncResponseFailureDto.setErrorCode(PlatformErrorMessages.RPR_RGS_EMPTY_REGISTRATIONID.getCode()); - syncResponseFailureDto.setMessage(PlatformErrorMessages.RPR_RGS_EMPTY_REGISTRATIONID.getMessage()); - syncResponseList.add(syncResponseFailureDto); - return false; - } - } - - /** - * Validate reg id. - * - * @param registrationDto - * the registration dto - * @param syncResponseList - * the sync response list - * @return the list - */ - public List syncRegistrationRecord(SyncRegistrationDto registrationDto, - List syncResponseList, String referenceId, - String timeStamp) { - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), - registrationDto.getRegistrationId(), "SyncRegistrationServiceImpl::validateRegId()::entry"); - SyncResponseSuccessDto syncResponseDto = new SyncResponseSuccessDto(); - SyncRegistrationEntity existingSyncRegistration = findByPacketId(registrationDto.getPacketId()); - SyncRegistrationEntity syncRegistration; - if (existingSyncRegistration != null) { - // update sync registration record - syncRegistration = convertDtoToEntity(registrationDto, referenceId, timeStamp); - syncRegistration.setWorkflowInstanceId(existingSyncRegistration.getWorkflowInstanceId()); - syncRegistration.setCreateDateTime(existingSyncRegistration.getCreateDateTime()); - if(syncRegistration.getCreateDateTime()!=null) { - syncRegistration.setRegistrationDate(syncRegistration.getCreateDateTime().toLocalDate()); - } - syncRegistrationDao.update(syncRegistration); - syncResponseDto.setRegistrationId(registrationDto.getRegistrationId()); - - eventId = EventId.RPR_402.toString(); - } else { - // first time sync registration - - syncRegistration = convertDtoToEntity(registrationDto, referenceId, timeStamp); - syncRegistration.setCreateDateTime(LocalDateTime.now(ZoneId.of("UTC"))); - syncRegistration.setWorkflowInstanceId(RegistrationUtility.generateId()); - if(syncRegistration.getCreateDateTime()!=null) { - syncRegistration.setRegistrationDate(syncRegistration.getCreateDateTime().toLocalDate()); - } - syncRegistrationDao.save(syncRegistration); - syncResponseDto.setRegistrationId(registrationDto.getRegistrationId()); - - eventId = EventId.RPR_407.toString(); - } - syncResponseDto.setStatus(ResponseStatusCode.SUCCESS.toString()); - syncResponseList.add(syncResponseDto); - saveAnonymousProfile( registrationDto, referenceId, timeStamp); - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), - registrationDto.getRegistrationId(), "SyncRegistrationServiceImpl::validateRegId()::exit"); - return syncResponseList; - } - - private void saveAnonymousProfile(SyncRegistrationDto registrationDto, String referenceId, String timeStamp) { - AnonymousProfileDTO dto=new AnonymousProfileDTO(); - try{ - dto.setProcessName(registrationDto.getRegistrationType()); - dto.setStatus("REGISTERED"); - dto.setStartDateTime(timeStamp); - dto.setDate(LocalDate.now(ZoneId.of("UTC")).toString()); - dto.setProcessStage("SYNC"); - List channel=new ArrayList<>(); - String mappingJsonString = registrationUtility.getMappingJson(); - org.json.simple.JSONObject mappingJsonObject = objectMapper.readValue(mappingJsonString, org.json.simple.JSONObject.class); - org.json.simple.JSONObject regProcessorIdentityJson =JsonUtil.getJSONObject(mappingJsonObject, MappingJsonConstants.IDENTITY); - - channel.add( registrationDto.getEmail() != null ? JsonUtil.getJSONValue( - JsonUtil.getJSONObject(regProcessorIdentityJson, MappingJsonConstants.EMAIL), - MappingJsonConstants.VALUE) : null); - channel.add( registrationDto.getPhone() != null ? JsonUtil.getJSONValue( - JsonUtil.getJSONObject(regProcessorIdentityJson, MappingJsonConstants.PHONE), - MappingJsonConstants.VALUE) : null); - dto.setChannel(channel); - dto.setEnrollmentCenterId(referenceId.split("_")[0]); - anonymousProfileService.saveAnonymousProfile(registrationDto.getRegistrationId(), - "SYNC", JsonUtil.objectMapperObjectToJson(dto)); - } catch (java.io.IOException exception) { - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - "", exception.getMessage() + ExceptionUtils.getStackTrace(exception)); - } - } - - /* - * (non-Javadoc) - * - * @see io.mosip.registration.processor.status.service.SyncRegistrationService# - * isPresent(java.lang.String) - */ - @Override - public boolean isPresent(String registrationId) { - return findByRegistrationId(registrationId) != null; - } - - /** - * Find by registration id. - * - * @param registrationId - * the registration id - * @return the sync registration entity - */ - @Override - public List findByRegistrationId(String registrationId) { - return syncRegistrationDao.findById(registrationId); - } - - @Override - public SyncRegistrationEntity findByWorkflowInstanceId(String workflowInstanceId) { - return syncRegistrationDao.findByWorkflowInstanceId(workflowInstanceId); - } - - /** - * Find by registration id and additional info req id. - * @param registrationId - * the registration id - * @param additionalInfoRequestId - * the additional info req id - * @return the sync registration entity - */ - @Override - public SyncRegistrationEntity findByRegistrationIdAndAdditionalInfoReqId(String registrationId, String additionalInfoRequestId) { - return syncRegistrationDao.findByRegistrationIdIdAndAdditionalInfoReqId(registrationId,additionalInfoRequestId); - } - - @Override - public SyncRegistrationEntity findByPacketId(String packetId) { - return syncRegistrationDao.findByPacketId(packetId); - } - - @Override - public List findByAdditionalInfoReqId(String additionalInfoReqId) { - return syncRegistrationDao.findByAdditionalInfoReqId(additionalInfoReqId); - } - - /** - * Convert dto to entity. - * - * @param dto - * the dto - * @return the sync registration entity - */ - private SyncRegistrationEntity convertDtoToEntity(SyncRegistrationDto dto, String referenceId, - String timeStamp) { - SyncRegistrationEntity syncRegistrationEntity = new SyncRegistrationEntity(); - syncRegistrationEntity.setRegistrationId(dto.getRegistrationId().trim()); - syncRegistrationEntity.setIsDeleted(dto.getIsDeleted() != null ? dto.getIsDeleted() : Boolean.FALSE); - syncRegistrationEntity.setLangCode(dto.getLangCode()); - syncRegistrationEntity.setRegistrationType(dto.getRegistrationType()); - syncRegistrationEntity.setPacketHashValue(dto.getPacketHashValue()); - syncRegistrationEntity.setPacketSize(dto.getPacketSize()); - syncRegistrationEntity.setSupervisorStatus(dto.getSupervisorStatus()); - syncRegistrationEntity.setSupervisorComment(dto.getSupervisorComment()); - syncRegistrationEntity.setUpdateDateTime(LocalDateTime.now(ZoneId.of("UTC"))); - syncRegistrationEntity.setAdditionalInfoReqId(dto.getAdditionalInfoReqId()); - syncRegistrationEntity.setPacketId(dto.getPacketId() != null ? dto.getPacketId() : dto.getRegistrationId()); - syncRegistrationEntity.setReferenceId(referenceId); - try { - RegistrationAdditionalInfoDTO regAdditionalInfo = new RegistrationAdditionalInfoDTO(); - regAdditionalInfo.setName(dto.getName()); - regAdditionalInfo.setEmail(dto.getEmail()); - regAdditionalInfo.setPhone(dto.getPhone()); - - String additionalInfo = JsonUtils.javaObjectToJsonString(regAdditionalInfo); - byte[] encryptedInfo = encryptor.encrypt(additionalInfo, referenceId, timeStamp); - syncRegistrationEntity.setOptionalValues(encryptedInfo); - if (dto.getName() != null) { - syncRegistrationEntity.setName(dto.getName() != null ? - getHashCode(dto.getName().replaceAll("\\s", "").toLowerCase()) : null); - } - syncRegistrationEntity.setEmail(dto.getEmail() != null ? getHashCode(dto.getEmail()) : null); - syncRegistrationEntity.setCenterId(getHashCode(referenceId.split("_")[0])); - syncRegistrationEntity.setPhone(dto.getPhone() != null ? getHashCode(dto.getPhone()) : null); - syncRegistrationEntity - .setLocationCode(getHashCode(getLocationCode(referenceId.split("_")[0], dto.getLangCode()))); - } catch (JsonProcessingException | RegStatusAppException | EncryptionFailureException - | ApisResourceAccessException exception) { - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - "", exception.getMessage() + ExceptionUtils.getStackTrace(exception)); - } - - syncRegistrationEntity.setCreatedBy(CREATED_BY); - syncRegistrationEntity.setUpdatedBy(CREATED_BY); - if (syncRegistrationEntity.getIsDeleted() != null && syncRegistrationEntity.getIsDeleted()) { - syncRegistrationEntity.setDeletedDateTime(LocalDateTime.now(ZoneId.of("UTC"))); - } else { - syncRegistrationEntity.setDeletedDateTime(null); - } - - return syncRegistrationEntity; - } - - /* - * (non-Javadoc) - * - * @see io.mosip.registration.processor.status.service.SyncRegistrationService# - * decryptAndGetSyncRequest(java.lang.Object, java.lang.String, - * java.lang.String, java.util.List) - */ - @Override - public RegistrationSyncRequestDTO decryptAndGetSyncRequest(Object encryptedSyncMetaInfo, String referenceId, - String timeStamp, List syncResponseList) { - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", - "SyncRegistrationServiceImpl::decryptAndGetSyncRequest()::entry"); - - RegistrationSyncRequestDTO registrationSyncRequestDTO = null; - try { - String decryptedSyncMetaData = decryptor.decrypt(encryptedSyncMetaInfo, referenceId, timeStamp); - registrationSyncRequestDTO = (RegistrationSyncRequestDTO) JsonUtils - .jsonStringToJavaObject(RegistrationSyncRequestDTO.class, decryptedSyncMetaData); - - } catch (PacketDecryptionFailureException | ApisResourceAccessException e) { - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - "", e.getMessage() + ExceptionUtils.getStackTrace(e)); - SyncResponseFailDto syncResponseFailureDto = new SyncResponseFailDto(); - - syncResponseFailureDto.setStatus(ResponseStatusCode.FAILURE.toString()); - syncResponseFailureDto.setMessage(PlatformErrorMessages.RPR_RGS_DECRYPTION_FAILED.getMessage()); - syncResponseFailureDto.setErrorCode(PlatformErrorMessages.RPR_RGS_DECRYPTION_FAILED.getCode()); - syncResponseList.add(syncResponseFailureDto); - } catch (JsonParseException e) { - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - "", e.getMessage() + ExceptionUtils.getStackTrace(e)); - SyncResponseFailDto syncResponseFailureDto = new SyncResponseFailDto(); - - syncResponseFailureDto.setStatus(ResponseStatusCode.FAILURE.toString()); - syncResponseFailureDto.setMessage(PlatformErrorMessages.RPR_RGS_JSON_PARSING_EXCEPTION.getMessage()); - syncResponseFailureDto.setErrorCode(PlatformErrorMessages.RPR_RGS_JSON_PARSING_EXCEPTION.getCode()); - syncResponseList.add(syncResponseFailureDto); - - } catch (JsonMappingException e) { - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - "", e.getMessage() + ExceptionUtils.getStackTrace(e)); - SyncResponseFailDto syncResponseFailureDto = new SyncResponseFailDto(); - - syncResponseFailureDto.setStatus(ResponseStatusCode.FAILURE.toString()); - syncResponseFailureDto.setMessage(PlatformErrorMessages.RPR_RGS_JSON_MAPPING_EXCEPTION.getMessage()); - syncResponseFailureDto.setErrorCode(PlatformErrorMessages.RPR_RGS_JSON_MAPPING_EXCEPTION.getCode()); - syncResponseList.add(syncResponseFailureDto); - } catch (IOException e) { - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - "", e.getMessage() + ExceptionUtils.getStackTrace(e)); - SyncResponseFailDto syncResponseFailureDto = new SyncResponseFailDto(); - - syncResponseFailureDto.setStatus(ResponseStatusCode.FAILURE.toString()); - syncResponseFailureDto.setMessage(PlatformErrorMessages.RPR_SYS_IO_EXCEPTION.getMessage()); - syncResponseFailureDto.setErrorCode(PlatformErrorMessages.RPR_SYS_IO_EXCEPTION.getCode()); - syncResponseList.add(syncResponseFailureDto); - } - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", - "SyncRegistrationServiceImpl::decryptAndGetSyncRequest()::exit"); - - return registrationSyncRequestDTO; - } - - /* - * (non-Javadoc) - * - * @see io.mosip.registration.processor.status.service.SyncRegistrationService# - * getByIds(java.util.List) - */ - @Override - public List getByIds(List requestIds) { - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", - "SyncRegistrationServiceImpl::getByIds()::entry"); - - try { - List registrationIds = new ArrayList<>(); - - for (RegistrationStatusSubRequestDto registrationStatusSubRequestDto : requestIds) { - registrationIds.add(registrationStatusSubRequestDto.getRegistrationId()); - } - if (!registrationIds.isEmpty()) { - List syncRegistrationEntityList = syncRegistrationDao.getByIds(registrationIds); - - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", - "SyncRegistrationServiceImpl::getByIds()::exit"); - return convertEntityListToDtoListAndGetExternalStatus(syncRegistrationEntityList); - } - return null; - } catch (DataAccessLayerException e) { - - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - "", e.getMessage() + ExceptionUtils.getStackTrace(e)); - throw new TablenotAccessibleException( - PlatformErrorMessages.RPR_RGS_REGISTRATION_TABLE_NOT_ACCESSIBLE.getMessage(), e); - } - - } - - @Override - public List searchLostRid(SearchInfo searchInfo) { - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), "", - "SyncRegistrationServiceImpl::getByIds()::entry"); - try { - updateFiltersWithHashedValues(searchInfo); - List syncRegistrationEntities = syncRegistrationDao.getSearchResults( - searchInfo.getFilters(), - searchInfo.getSort()); - List lostRidDtos = entityToDtoMapper(syncRegistrationEntities); - validateRegistrationIds(lostRidDtos); - return lostRidDtos; - } catch (DataAccessLayerException | NoSuchAlgorithmException | RegStatusAppException e) { - - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - "", e.getMessage() + ExceptionUtils.getStackTrace(e)); - throw new TablenotAccessibleException( - PlatformErrorMessages.RPR_RGS_REGISTRATION_TABLE_NOT_ACCESSIBLE.getMessage(), e); - } - } - - @Override - public List getExternalStatusByIds(List requestIds) { - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", - "SyncRegistrationServiceImpl::getExternalStatusByIds()::entry"); - - try { - if (!requestIds.isEmpty()) { - List syncRegistrationEntityList = syncRegistrationDao.getByIds(requestIds); - - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", - "SyncRegistrationServiceImpl::getExternalStatusByIds()::exit"); - return convertEntityListToDtoListAndGetExternalStatus(syncRegistrationEntityList); - } - return null; - } catch (DataAccessLayerException e) { - - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - "", e.getMessage() + ExceptionUtils.getStackTrace(e)); - throw new TablenotAccessibleException( - PlatformErrorMessages.RPR_RGS_REGISTRATION_TABLE_NOT_ACCESSIBLE.getMessage(), e); - } - - } - - private List entityToDtoMapper(List syncRegistrationEntities) { - List lostRidDtos = new ArrayList(); - syncRegistrationEntities.forEach(syncEntity -> { - LostRidDto lostRidDto = new LostRidDto(); - lostRidDto.setRegistrationId(syncEntity.getRegistrationId()); - lostRidDto.setRegistartionDate(null!=syncEntity.getRegistrationDate()?syncEntity.getRegistrationDate().toString():null); - lostRidDto.setSyncDateTime(null!=syncEntity.getCreateDateTime()?syncEntity.getCreateDateTime().toString():null); - if(syncEntity.getOptionalValues()!=null) { - getAdditionalInfo(syncEntity.getReferenceId(), syncEntity.getOptionalValues(), lostRidDto.getAdditionalInfo()); - } - lostRidDtos.add(lostRidDto); - }); - return lostRidDtos.stream().distinct().collect(Collectors.toList()); - } - - private void getAdditionalInfo(String referenceId, byte[] optionalValues, Map additionalInfo) { - String name=null; - try { - String decryptedData=decryptor.decrypt(CryptoUtil.encodeBase64String(optionalValues),referenceId, DateUtils.formatToISOString(DateUtils.getUTCCurrentDateTime())); - JSONObject jsonObject=new JSONObject(decryptedData); - name=jsonObject.getString("name"); - additionalInfo.put("name",name); - - } catch (PacketDecryptionFailureException | ApisResourceAccessException |JSONException e) { - throw new TablenotAccessibleException( - PlatformErrorMessages.RPR_RGS_DECRYPTION_FAILED.getMessage(),e); } - } - - private void validateRegistrationIds(List lostRidDtos) throws RegStatusAppException { - LostRidValidationException exception = new LostRidValidationException(); - if (lostRidDtos.size() >= maxSearchResult) { - throw new RegStatusAppException(PlatformErrorMessages.RPR_RGS_INVALID_SEARCH, exception); - } - - } - - private void updateFiltersWithHashedValues(SearchInfo searchInfo) - throws NoSuchAlgorithmException, RegStatusAppException { - for (FilterInfo filterInfo : searchInfo.getFilters()) { - if (filterInfo.getColumnName().equals("email") || filterInfo.getColumnName().equals("phone") - || filterInfo.getColumnName().equals("centerId") - || filterInfo.getColumnName().equals("locationCode")) { - - filterInfo.setValue(getHashCode(filterInfo.getValue())); - } else if (filterInfo.getColumnName().equalsIgnoreCase("name")) { - filterInfo.setValue(getHashCode(filterInfo.getValue().replaceAll("\\s", "").toLowerCase())); - } - } - } - - /** - * Convert entity list to dto list and get external status. - * - * @param syncRegistrationEntityList - * the sync registration entity list - * @return the list - */ - private List convertEntityListToDtoListAndGetExternalStatus( - List syncRegistrationEntityList) { - List list = new ArrayList<>(); - if (syncRegistrationEntityList != null) { - for (SyncRegistrationEntity entity : syncRegistrationEntityList) { - list.add(convertEntityToDtoAndGetExternalStatus(entity)); - } - - } - return list; - } - - /** - * Convert entity to dto and get external status. - * - * @param entity - * the entity - * @return the registration status dto - */ - private RegistrationStatusDto convertEntityToDtoAndGetExternalStatus(SyncRegistrationEntity entity) { - RegistrationStatusDto registrationStatusDto = new RegistrationStatusDto(); - registrationStatusDto.setRegistrationId(entity.getRegistrationId()); - registrationStatusDto.setAdditionalInfoReqId(entity.getAdditionalInfoReqId()); - registrationStatusDto.setStatusCode(RegistrationExternalStatusCode.UPLOAD_PENDING.toString()); - return registrationStatusDto; - } - - private String getLocationCode(String centerId, String langCode) { - String requestUrl = locationCodeReqUrl + "/" + centerId + "/" + langCode; - URI requestUri = URI.create(requestUrl); - String locationCode = null; - try { - String response = restApiClient.getApi(requestUri, String.class); - JSONObject jsonObjects = new JSONObject(response); - locationCode = jsonObjects.getJSONObject("response") != null ? ((JSONObject) jsonObjects.getJSONObject("response").getJSONArray("registrationCenters").get(0)) - .getString("locationCode") : null; - } catch (Exception e) { - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - "", e.getMessage() + ExceptionUtils.getStackTrace(e)); - } - return locationCode; - } - - @Override - public boolean deleteAdditionalInfo(SyncRegistrationEntity syncEntity) { - return syncRegistrationDao.deleteAdditionalInfo(syncEntity); - } - - @Override - public List getByPacketIds(List packetIdList) { - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", - "SyncRegistrationServiceImpl::getByPacketIds()::entry"); - try { - if (!packetIdList.isEmpty()) { - List syncRegistrationEntityList = syncRegistrationDao - .getByPacketIds(packetIdList); - - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", - "SyncRegistrationServiceImpl::getByPacketIds()::exit"); - return syncRegistrationEntityList; - } - return null; - } catch (DataAccessLayerException e) { - - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - "", e.getMessage() + ExceptionUtils.getStackTrace(e)); - throw new TablenotAccessibleException( - PlatformErrorMessages.RPR_RGS_REGISTRATION_TABLE_NOT_ACCESSIBLE.getMessage(), e); - } - } - - private static byte[] getHMACHash(String value) throws java.security.NoSuchAlgorithmException { - if (value == null) - return null; - return HMACUtils2.generateHash(value.getBytes()); - } - - private static byte[] getHMACHashWithSalt(byte[] valueBytes, byte[] saltBytes) - throws java.security.NoSuchAlgorithmException { - if (valueBytes == null) - return null; - return HMACUtils2.digestAsPlainTextWithSalt(valueBytes, saltBytes).getBytes(); - } - - private String getHashCode(String value) throws RegStatusAppException { - String encodedHash = null; - if (value == null) { - return null; - } - try { - byte[] hashCode = getHMACHash(value); - byte[] nonce = Arrays.copyOfRange(hashCode, hashCode.length - 2, hashCode.length); - String result = convertBytesToHex(nonce); - Long hashValue = Long.parseLong(result, 16); - Long saltIndex = hashValue % 10000; - String salt = syncRegistrationDao.getSaltValue(saltIndex); - byte[] saltBytes=null; - try { - saltBytes= CryptoUtil.decodeURLSafeBase64(salt); - } catch (IllegalArgumentException exception) { - saltBytes = CryptoUtil.decodePlainBase64(salt); - } - byte[] hashBytes = value.getBytes(); - for (int i = 0; i <= iteration; i++) { - hashBytes = getHMACHashWithSalt(hashBytes, saltBytes); - } - encodedHash = CryptoUtil.encodeToURLSafeBase64(hashBytes); - } catch (NoSuchAlgorithmException e) { - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - "", e.getMessage() + ExceptionUtils.getStackTrace(e)); - throw new RegStatusAppException(PlatformErrorMessages.RPR_RGS_INVALID_SEARCH, e); - } - return encodedHash; - } - - private static String convertBytesToHex(byte[] bytes) { - StringBuilder result = new StringBuilder(); - for (byte temp : bytes) { - result.append(String.format("%02x", temp)); - } - return result.toString(); - } - -} +/** + * + */ +package io.mosip.registration.processor.status.service.impl; + +import java.net.URI; +import java.security.NoSuchAlgorithmException; +import java.sql.Timestamp; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import io.mosip.kernel.core.util.DateUtils; +import org.json.JSONException; +import org.json.JSONObject; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Component; + +import com.fasterxml.jackson.databind.ObjectMapper; + +import io.mosip.kernel.core.dataaccess.exception.DataAccessLayerException; +import io.mosip.kernel.core.exception.ExceptionUtils; +import io.mosip.kernel.core.exception.IOException; +import io.mosip.kernel.core.idvalidator.exception.InvalidIDException; +import io.mosip.kernel.core.idvalidator.spi.RidValidator; +import io.mosip.kernel.core.logger.spi.Logger; +import io.mosip.kernel.core.util.CryptoUtil; +import io.mosip.kernel.core.util.HMACUtils2; +import io.mosip.kernel.core.util.JsonUtils; +import io.mosip.kernel.core.util.StringUtils; +import io.mosip.kernel.core.util.exception.JsonMappingException; +import io.mosip.kernel.core.util.exception.JsonParseException; +import io.mosip.kernel.core.util.exception.JsonProcessingException; +import io.mosip.kernel.idvalidator.rid.constant.RidExceptionProperty; +import io.mosip.registration.processor.core.anonymous.dto.AnonymousProfileDTO; +import io.mosip.registration.processor.core.code.EventId; +import io.mosip.registration.processor.core.code.EventName; +import io.mosip.registration.processor.core.code.EventType; +import io.mosip.registration.processor.core.code.ModuleName; +import io.mosip.registration.processor.core.constant.AuditLogConstant; +import io.mosip.registration.processor.core.constant.LoggerFileConstant; +import io.mosip.registration.processor.core.constant.MappingJsonConstants; +import io.mosip.registration.processor.core.constant.ResponseStatusCode; +import io.mosip.registration.processor.core.exception.ApisResourceAccessException; +import io.mosip.registration.processor.core.exception.util.PlatformErrorMessages; +import io.mosip.registration.processor.core.exception.util.PlatformSuccessMessages; +import io.mosip.registration.processor.core.logger.LogDescription; +import io.mosip.registration.processor.core.logger.RegProcessorLogger; +import io.mosip.registration.processor.core.util.JsonUtil; +import io.mosip.registration.processor.rest.client.audit.builder.AuditLogRequestBuilder; +import io.mosip.registration.processor.rest.client.utils.RestApiClient; +import io.mosip.registration.processor.status.code.RegistrationExternalStatusCode; +import io.mosip.registration.processor.status.code.SupervisorStatus; +import io.mosip.registration.processor.status.dao.SyncRegistrationDao; +import io.mosip.registration.processor.status.decryptor.Decryptor; +import io.mosip.registration.processor.status.dto.FilterInfo; +import io.mosip.registration.processor.status.dto.LostRidDto; +import io.mosip.registration.processor.status.dto.RegistrationAdditionalInfoDTO; +import io.mosip.registration.processor.status.dto.RegistrationStatusDto; +import io.mosip.registration.processor.status.dto.RegistrationStatusSubRequestDto; +import io.mosip.registration.processor.status.dto.RegistrationSyncRequestDTO; +import io.mosip.registration.processor.status.dto.SearchInfo; +import io.mosip.registration.processor.status.dto.SyncRegistrationDto; +import io.mosip.registration.processor.status.dto.SyncResponseDto; +import io.mosip.registration.processor.status.dto.SyncResponseFailDto; +import io.mosip.registration.processor.status.dto.SyncResponseFailureDto; +import io.mosip.registration.processor.status.dto.SyncResponseFailureV2Dto; +import io.mosip.registration.processor.status.dto.SyncResponseSuccessDto; +import io.mosip.registration.processor.status.dto.SyncResponseSuccessV2Dto; +import io.mosip.registration.processor.status.encryptor.Encryptor; +import io.mosip.registration.processor.status.entity.SyncRegistrationEntity; +import io.mosip.registration.processor.status.exception.EncryptionFailureException; +import io.mosip.registration.processor.status.exception.LostRidValidationException; +import io.mosip.registration.processor.status.exception.PacketDecryptionFailureException; +import io.mosip.registration.processor.status.exception.RegStatusAppException; +import io.mosip.registration.processor.status.exception.TablenotAccessibleException; +import io.mosip.registration.processor.status.service.AnonymousProfileService; +import io.mosip.registration.processor.status.service.SyncRegistrationService; +import io.mosip.registration.processor.status.utilities.RegistrationUtility; + +/** + * The Class SyncRegistrationServiceImpl. + * + * @author M1048399 + * @author M1048219 + * @author M1047487 + */ +@Component +public class SyncRegistrationServiceImpl implements SyncRegistrationService { + + /** The Constant CREATED_BY. */ + private static final String CREATED_BY = "MOSIP"; + + /** The event id. */ + private String eventId = ""; + + /** The event name. */ + private String eventName = ""; + + @Value("${mosip.registration.processor.postalcode.req.url}") + private String locationCodeReqUrl; + + @Value("${mosip.registration.processor.lostrid.iteration.max.count:10000}") + private int iteration; + + @Value("${registration.processor.lostrid.max.registrationid:5}") + private int maxSearchResult; + + /** The event type. */ + private String eventType = ""; + + /** The sync registration dao. */ + @Autowired + private SyncRegistrationDao syncRegistrationDao; + /** The sync AnonymousProfileService . */ + @Autowired + private AnonymousProfileService anonymousProfileService; + + /** The core audit request builder. */ + @Autowired + private AuditLogRequestBuilder auditLogRequestBuilder; + + /** The rid validator. */ + @Autowired + private RidValidator ridValidator; + + @Autowired + ObjectMapper objectMapper; + + @Autowired + private RegistrationUtility registrationUtility; + + /** The lancode length. */ + private int LANCODE_LENGTH = 3; + + /** The reg proc logger. */ + private static Logger regProcLogger = RegProcessorLogger.getLogger(SyncRegistrationServiceImpl.class); + + /** The decryptor. */ + @Autowired + private Decryptor decryptor; + + /** The encryptor. */ + @Autowired + private Encryptor encryptor; + + @Value("#{'${registration.processor.main-processes}'.split(',')}") + private List mainProcesses; + + @Value("#{'${registration.processor.sub-processes}'.split(',')}") + private List subProcesses; + + /** The config server file storage URL. */ + @Value("${config.server.file.storage.uri}") + private String configServerFileStorageURL; + + /** The get reg processor identity json. */ + @Value("${registration.processor.identityjson}") + private String getRegProcessorIdentityJson; + + @Autowired + RestApiClient restApiClient; + /** + * Instantiates a new sync registration service impl. + */ + public SyncRegistrationServiceImpl() { + super(); + } + + /* + * (non-Javadoc) + * + * @see + * io.mosip.registration.processor.status.service.SyncRegistrationService#sync( + * java.util.List) + */ + public List sync(List resgistrationDtos, String referenceId, + String timeStamp) { + List syncResponseList = new ArrayList<>(); + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", + "SyncRegistrationServiceImpl::sync()::entry"); + LogDescription description = new LogDescription(); + boolean isTransactionSuccessful = false; + try { + for (SyncRegistrationDto registrationDto : resgistrationDtos) { + syncResponseList = validateSync(registrationDto, syncResponseList, referenceId, timeStamp); + } + isTransactionSuccessful = true; + description.setMessage("Registartion Id's are successfully synched in Sync Registration table"); + + regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + "", ""); + } catch (DataAccessLayerException e) { + handleTableNotAccessibleException(description, e); + } finally { + createAudit(description, isTransactionSuccessful); + + } + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", + "SyncRegistrationServiceImpl::sync()::exit"); + return syncResponseList; + + } + + public List syncV2(List resgistrationDtos, String referenceId, + String timeStamp) { + List syncResponseList = new ArrayList<>(); + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", + "SyncRegistrationServiceImpl::sync()::entry"); + LogDescription description = new LogDescription(); + boolean isTransactionSuccessful = false; + try { + for (SyncRegistrationDto registrationDto : resgistrationDtos) { + if(registrationDto.getPacketId()!=null && !registrationDto.getPacketId().isBlank()){ + syncResponseList = validateSyncV2(registrationDto, syncResponseList, referenceId, timeStamp); + } + else { + SyncResponseFailDto syncResponseFailureDto = new SyncResponseFailDto(); + syncResponseFailureDto.setStatus(ResponseStatusCode.FAILURE.toString()); + syncResponseFailureDto.setMessage("Missing Request Value - packetId"); + syncResponseFailureDto.setErrorCode(PlatformErrorMessages.RPR_RGS_MISSING_INPUT_PARAMETER.getCode()); + syncResponseList.add(syncResponseFailureDto); + } + } + isTransactionSuccessful = true; + description.setMessage("Registartion Id's are successfully synched in Sync Registration table"); + + regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + "", ""); + } catch (DataAccessLayerException e) { + handleTableNotAccessibleException(description, e); + } finally { + createAudit(description, isTransactionSuccessful); + + } + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", + "SyncRegistrationServiceImpl::sync()::exit"); + return syncResponseList; + + } + + private void handleTableNotAccessibleException(LogDescription description, DataAccessLayerException e) { + description.setMessage(PlatformErrorMessages.RPR_RGS_DATA_ACCESS_EXCEPTION.getMessage()); + description.setCode(PlatformErrorMessages.RPR_RGS_DATA_ACCESS_EXCEPTION.getCode()); + description.setMessage("DataAccessLayerException while syncing Registartion Id's" + "::" + e.getMessage()); + + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + "", e.getMessage() + ExceptionUtils.getStackTrace(e)); + throw new TablenotAccessibleException( + PlatformErrorMessages.RPR_RGS_REGISTRATION_TABLE_NOT_ACCESSIBLE.getMessage(), e); + } + + private void createAudit(LogDescription description, boolean isTransactionSuccessful) { + if (isTransactionSuccessful) { + eventName = eventId.equalsIgnoreCase(EventId.RPR_402.toString()) ? EventName.UPDATE.toString() + : EventName.ADD.toString(); + eventType = EventType.BUSINESS.toString(); + } else { + description.setMessage(PlatformErrorMessages.RPR_RGS_REGISTRATION_SYNC_SERVICE_FAILED.getMessage()); + description.setCode(PlatformErrorMessages.RPR_RGS_REGISTRATION_SYNC_SERVICE_FAILED.getCode()); + eventId = EventId.RPR_405.toString(); + eventName = EventName.EXCEPTION.toString(); + eventType = EventType.SYSTEM.toString(); + } + /** Module-Id can be Both Success/Error code */ + String moduleId = isTransactionSuccessful + ? PlatformSuccessMessages.RPR_SYNC_REGISTRATION_SERVICE_SUCCESS.getCode() + : description.getCode(); + String moduleName = ModuleName.SYNC_REGISTRATION_SERVICE.toString(); + auditLogRequestBuilder.createAuditRequestBuilder(description.getMessage(), eventId, eventName, eventType, + moduleId, moduleName, AuditLogConstant.MULTIPLE_ID.toString()); + } + + /** + * Validate RegiId with Kernel RidValiator. + * + * @param registrationDto + * the registration dto + * @param syncResponseList + * the sync response list + * @return the list + */ + private List validateSync(SyncRegistrationDto registrationDto, + List syncResponseList, String referenceId, + String timeStamp) { + if (validateLanguageCode(registrationDto, syncResponseList) + && validateRegistrationType(registrationDto, syncResponseList) + && validateHashValue(registrationDto, syncResponseList) + && validateSupervisorStatus(registrationDto, syncResponseList)) { + if (validateRegistrationID(registrationDto, syncResponseList)) { + SyncResponseFailureDto syncResponseFailureDto = new SyncResponseFailureDto(); + try { + if (ridValidator.validateId(registrationDto.getRegistrationId())) { + syncResponseList = syncRegistrationRecord(registrationDto, syncResponseList, referenceId, timeStamp); + } + } catch (InvalidIDException e) { + syncResponseFailureDto.setRegistrationId(registrationDto.getRegistrationId()); + + syncResponseFailureDto.setStatus(ResponseStatusCode.FAILURE.toString()); + if (e.getErrorCode().equals(RidExceptionProperty.INVALID_RID_LENGTH.getErrorCode())) { + syncResponseFailureDto + .setMessage(PlatformErrorMessages.RPR_RGS_INVALID_REGISTRATIONID_LENGTH.getMessage()); + syncResponseFailureDto + .setErrorCode(PlatformErrorMessages.RPR_RGS_INVALID_REGISTRATIONID_LENGTH.getCode()); + } else if (e.getErrorCode().equals(RidExceptionProperty.INVALID_RID.getErrorCode())) { + syncResponseFailureDto + .setMessage(PlatformErrorMessages.RPR_RGS_INVALID_REGISTRATIONID.getMessage()); + syncResponseFailureDto + .setErrorCode(PlatformErrorMessages.RPR_RGS_INVALID_REGISTRATIONID.getCode()); + } else if (e.getErrorCode().equals(RidExceptionProperty.INVALID_RID_TIMESTAMP.getErrorCode())) { + syncResponseFailureDto.setMessage( + PlatformErrorMessages.RPR_RGS_INVALID_REGISTRATIONID_TIMESTAMP.getMessage()); + syncResponseFailureDto + .setErrorCode(PlatformErrorMessages.RPR_RGS_INVALID_REGISTRATIONID_TIMESTAMP.getCode()); + } + syncResponseList.add(syncResponseFailureDto); + } + } + } + return syncResponseList; + } + + + private List validateSyncV2(SyncRegistrationDto registrationDto, + List syncResponseList, String referenceId, + String timeStamp) { + if (validateLanguageCode(registrationDto, syncResponseList) + && validateRegistrationType(registrationDto, syncResponseList) + && validateHashValue(registrationDto, syncResponseList) + && validateSupervisorStatus(registrationDto, syncResponseList)) { + if (validateRegistrationID(registrationDto, syncResponseList)) { + syncResponseList = syncRegistrationRecord(registrationDto, syncResponseList, referenceId, timeStamp); + } + } + List syncResponseV2List=new ArrayList<>(); + for(SyncResponseDto dto:syncResponseList) { + if(dto instanceof SyncResponseFailureDto) { + SyncResponseFailureV2Dto v2Dto=new SyncResponseFailureV2Dto(dto.getRegistrationId(),dto.getStatus(), + ((SyncResponseFailureDto) dto).getErrorCode(),((SyncResponseFailureDto) dto).getMessage(), + registrationDto.getPacketId()); + syncResponseV2List.add(v2Dto); + } + if(dto instanceof SyncResponseSuccessDto || dto instanceof SyncResponseDto) { + SyncResponseSuccessV2Dto v2Dto=new SyncResponseSuccessV2Dto(dto.getRegistrationId(),dto.getStatus(), + registrationDto.getPacketId()); + syncResponseV2List.add(v2Dto); + } + if(dto instanceof SyncResponseFailDto) { + SyncResponseFailureV2Dto v2Dto=new SyncResponseFailureV2Dto(dto.getRegistrationId(),dto.getStatus(), + ((SyncResponseFailDto) dto).getErrorCode(),((SyncResponseFailDto) dto).getMessage(), + registrationDto.getPacketId()); + syncResponseV2List.add(v2Dto); + } + } + + return syncResponseV2List; + } + + /** + * Validate supervisor status. + * + * @param registrationDto + * the registration dto + * @param syncResponseList + * the sync response list + * @return true, if successful + */ + private boolean validateSupervisorStatus(SyncRegistrationDto registrationDto, + List syncResponseList) { + String value = registrationDto.getSupervisorStatus(); + if (SupervisorStatus.APPROVED.toString().equals(value)) { + return true; + } else if (SupervisorStatus.REJECTED.toString().equals(value)) { + return true; + + } else { + SyncResponseFailureDto syncResponseFailureDto = new SyncResponseFailureDto(); + syncResponseFailureDto.setRegistrationId(registrationDto.getRegistrationId()); + + syncResponseFailureDto.setStatus(ResponseStatusCode.FAILURE.toString()); + syncResponseFailureDto.setMessage(PlatformErrorMessages.RPR_RGS_INVALID_SUPERVISOR_STATUS.getMessage()); + syncResponseFailureDto.setErrorCode(PlatformErrorMessages.RPR_RGS_INVALID_SUPERVISOR_STATUS.getCode()); + syncResponseList.add(syncResponseFailureDto); + return false; + } + + } + + /** + * Validate hash value. + * + * @param registrationDto + * the registration dto + * @param syncResponseList + * the sync response list + * @return true, if successful + */ + private boolean validateHashValue(SyncRegistrationDto registrationDto, List syncResponseList) { + + if (registrationDto.getPacketHashValue() == null) { + SyncResponseFailureDto syncResponseFailureDto = new SyncResponseFailureDto(); + syncResponseFailureDto.setRegistrationId(registrationDto.getRegistrationId()); + + syncResponseFailureDto.setStatus(ResponseStatusCode.FAILURE.toString()); + syncResponseFailureDto.setMessage(PlatformErrorMessages.RPR_RGS_INVALID_HASHVALUE.getMessage()); + syncResponseFailureDto.setErrorCode(PlatformErrorMessages.RPR_RGS_INVALID_HASHVALUE.getCode()); + syncResponseList.add(syncResponseFailureDto); + return false; + } else { + return true; + } + } + + /** + * Validate status code. + * + * @param registrationDto + * the registration dto + * @param syncResponseList + * the sync response list + * @return true, if successful + */ + private boolean validateRegistrationType(SyncRegistrationDto registrationDto, + List syncResponseList) { + List processes=new ArrayList<>(); + processes.addAll(mainProcesses); + processes.addAll(subProcesses); + String value = registrationDto.getRegistrationType(); + if(processes.contains(value)) { + return true; + }else { + SyncResponseFailureDto syncResponseFailureDto = new SyncResponseFailureDto(); + syncResponseFailureDto.setRegistrationId(registrationDto.getRegistrationId()); + + syncResponseFailureDto.setStatus(ResponseStatusCode.FAILURE.toString()); + syncResponseFailureDto.setMessage(PlatformErrorMessages.RPR_RGS_INVALID_SYNCTYPE.getMessage()); + syncResponseFailureDto.setErrorCode(PlatformErrorMessages.RPR_RGS_INVALID_SYNCTYPE.getCode()); + syncResponseList.add(syncResponseFailureDto); + return false; + } + } + + /** + * Validate language code. + * + * @param registrationDto + * the registration dto + * @param syncResponseList + * the sync response list + * @return true, if successful + */ + private boolean validateLanguageCode(SyncRegistrationDto registrationDto, List syncResponseList) { + if (registrationDto.getLangCode().length() == LANCODE_LENGTH) { + return true; + } else { + SyncResponseFailureDto syncResponseFailureDto = new SyncResponseFailureDto(); + syncResponseFailureDto.setRegistrationId(registrationDto.getRegistrationId()); + + syncResponseFailureDto.setStatus(ResponseStatusCode.FAILURE.toString()); + syncResponseFailureDto.setMessage(PlatformErrorMessages.RPR_RGS_INVALID_LANGUAGECODE.getMessage()); + syncResponseFailureDto.setErrorCode(PlatformErrorMessages.RPR_RGS_INVALID_LANGUAGECODE.getCode()); + syncResponseList.add(syncResponseFailureDto); + return false; + } + } + + /** + * Validate registration ID. + * + * @param registrationDto + * the registration dto + * @param syncResponseList + * the sync response list + * @return true, if successful + */ + private boolean validateRegistrationID(SyncRegistrationDto registrationDto, + List syncResponseList) { + if (registrationDto.getRegistrationId() != null) { + return true; + } else { + SyncResponseFailureDto syncResponseFailureDto = new SyncResponseFailureDto(); + syncResponseFailureDto.setRegistrationId(registrationDto.getRegistrationId()); + syncResponseFailureDto.setStatus(ResponseStatusCode.FAILURE.toString()); + syncResponseFailureDto.setErrorCode(PlatformErrorMessages.RPR_RGS_EMPTY_REGISTRATIONID.getCode()); + syncResponseFailureDto.setMessage(PlatformErrorMessages.RPR_RGS_EMPTY_REGISTRATIONID.getMessage()); + syncResponseList.add(syncResponseFailureDto); + return false; + } + } + + /** + * Validate reg id. + * + * @param registrationDto + * the registration dto + * @param syncResponseList + * the sync response list + * @return the list + */ + public List syncRegistrationRecord(SyncRegistrationDto registrationDto, + List syncResponseList, String referenceId, + String timeStamp) { + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), + registrationDto.getRegistrationId(), "SyncRegistrationServiceImpl::validateRegId()::entry"); + SyncResponseSuccessDto syncResponseDto = new SyncResponseSuccessDto(); + SyncRegistrationEntity existingSyncRegistration = findByPacketId(registrationDto.getPacketId()); + SyncRegistrationEntity syncRegistration; + if (existingSyncRegistration != null) { + // update sync registration record + syncRegistration = convertDtoToEntity(registrationDto, referenceId, timeStamp); + syncRegistration.setWorkflowInstanceId(existingSyncRegistration.getWorkflowInstanceId()); + syncRegistration.setCreateDateTime(existingSyncRegistration.getCreateDateTime()); + if(syncRegistration.getCreateDateTime()!=null) { + syncRegistration.setRegistrationDate(syncRegistration.getCreateDateTime().toLocalDate()); + } + syncRegistrationDao.update(syncRegistration); + syncResponseDto.setRegistrationId(registrationDto.getRegistrationId()); + + eventId = EventId.RPR_402.toString(); + } else { + // first time sync registration + + syncRegistration = convertDtoToEntity(registrationDto, referenceId, timeStamp); + syncRegistration.setCreateDateTime(LocalDateTime.now(ZoneId.of("UTC"))); + syncRegistration.setWorkflowInstanceId(RegistrationUtility.generateId()); + if(syncRegistration.getCreateDateTime()!=null) { + syncRegistration.setRegistrationDate(syncRegistration.getCreateDateTime().toLocalDate()); + } + syncRegistrationDao.save(syncRegistration); + syncResponseDto.setRegistrationId(registrationDto.getRegistrationId()); + + eventId = EventId.RPR_407.toString(); + } + syncResponseDto.setStatus(ResponseStatusCode.SUCCESS.toString()); + syncResponseList.add(syncResponseDto); + saveAnonymousProfile( registrationDto, referenceId, timeStamp); + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), + registrationDto.getRegistrationId(), "SyncRegistrationServiceImpl::validateRegId()::exit"); + return syncResponseList; + } + + private void saveAnonymousProfile(SyncRegistrationDto registrationDto, String referenceId, String timeStamp) { + AnonymousProfileDTO dto=new AnonymousProfileDTO(); + try{ + dto.setProcessName(registrationDto.getRegistrationType()); + dto.setStatus("REGISTERED"); + dto.setStartDateTime(timeStamp); + dto.setDate(LocalDate.now(ZoneId.of("UTC")).toString()); + dto.setProcessStage("SYNC"); + List channel=new ArrayList<>(); + String mappingJsonString = registrationUtility.getMappingJson(); + org.json.simple.JSONObject mappingJsonObject = objectMapper.readValue(mappingJsonString, org.json.simple.JSONObject.class); + org.json.simple.JSONObject regProcessorIdentityJson =JsonUtil.getJSONObject(mappingJsonObject, MappingJsonConstants.IDENTITY); + + channel.add( registrationDto.getEmail() != null ? JsonUtil.getJSONValue( + JsonUtil.getJSONObject(regProcessorIdentityJson, MappingJsonConstants.EMAIL), + MappingJsonConstants.VALUE) : null); + channel.add( registrationDto.getPhone() != null ? JsonUtil.getJSONValue( + JsonUtil.getJSONObject(regProcessorIdentityJson, MappingJsonConstants.PHONE), + MappingJsonConstants.VALUE) : null); + dto.setChannel(channel); + dto.setEnrollmentCenterId(referenceId.split("_")[0]); + anonymousProfileService.saveAnonymousProfile(registrationDto.getRegistrationId(), + "SYNC", JsonUtil.objectMapperObjectToJson(dto)); + } catch (java.io.IOException exception) { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + "", exception.getMessage() + ExceptionUtils.getStackTrace(exception)); + } + } + + /* + * (non-Javadoc) + * + * @see io.mosip.registration.processor.status.service.SyncRegistrationService# + * isPresent(java.lang.String) + */ + @Override + public boolean isPresent(String registrationId) { + return findByRegistrationId(registrationId) != null; + } + + /** + * Find by registration id. + * + * @param registrationId + * the registration id + * @return the sync registration entity + */ + @Override + public List findByRegistrationId(String registrationId) { + return syncRegistrationDao.findById(registrationId); + } + + @Override + public SyncRegistrationEntity findByWorkflowInstanceId(String workflowInstanceId) { + return syncRegistrationDao.findByWorkflowInstanceId(workflowInstanceId); + } + + /** + * Find by registration id and additional info req id. + * @param registrationId + * the registration id + * @param additionalInfoRequestId + * the additional info req id + * @return the sync registration entity + */ + @Override + public SyncRegistrationEntity findByRegistrationIdAndAdditionalInfoReqId(String registrationId, String additionalInfoRequestId) { + return syncRegistrationDao.findByRegistrationIdIdAndAdditionalInfoReqId(registrationId,additionalInfoRequestId); + } + + @Override + public SyncRegistrationEntity findByPacketId(String packetId) { + return syncRegistrationDao.findByPacketId(packetId); + } + + @Override + public List findByAdditionalInfoReqId(String additionalInfoReqId) { + return syncRegistrationDao.findByAdditionalInfoReqId(additionalInfoReqId); + } + + /** + * Convert dto to entity. + * + * @param dto + * the dto + * @return the sync registration entity + */ + private SyncRegistrationEntity convertDtoToEntity(SyncRegistrationDto dto, String referenceId, + String timeStamp) { + SyncRegistrationEntity syncRegistrationEntity = new SyncRegistrationEntity(); + syncRegistrationEntity.setRegistrationId(dto.getRegistrationId().trim()); + syncRegistrationEntity.setIsDeleted(dto.getIsDeleted() != null ? dto.getIsDeleted() : Boolean.FALSE); + syncRegistrationEntity.setLangCode(dto.getLangCode()); + syncRegistrationEntity.setRegistrationType(dto.getRegistrationType()); + syncRegistrationEntity.setPacketHashValue(dto.getPacketHashValue()); + syncRegistrationEntity.setPacketSize(dto.getPacketSize()); + syncRegistrationEntity.setSupervisorStatus(dto.getSupervisorStatus()); + syncRegistrationEntity.setSupervisorComment(dto.getSupervisorComment()); + syncRegistrationEntity.setUpdateDateTime(LocalDateTime.now(ZoneId.of("UTC"))); + syncRegistrationEntity.setAdditionalInfoReqId(dto.getAdditionalInfoReqId()); + syncRegistrationEntity.setPacketId(dto.getPacketId() != null ? dto.getPacketId() : dto.getRegistrationId()); + syncRegistrationEntity.setReferenceId(referenceId); + try { + RegistrationAdditionalInfoDTO regAdditionalInfo = new RegistrationAdditionalInfoDTO(); + regAdditionalInfo.setName(dto.getName()); + regAdditionalInfo.setEmail(dto.getEmail()); + regAdditionalInfo.setPhone(dto.getPhone()); + + String additionalInfo = JsonUtils.javaObjectToJsonString(regAdditionalInfo); + byte[] encryptedInfo = encryptor.encrypt(additionalInfo, referenceId, timeStamp); + syncRegistrationEntity.setOptionalValues(encryptedInfo); + if (dto.getName() != null) { + syncRegistrationEntity.setName(dto.getName() != null ? + getHashCode(dto.getName().replaceAll("\\s", "").toLowerCase()) : null); + } + syncRegistrationEntity.setEmail(dto.getEmail() != null ? getHashCode(dto.getEmail()) : null); + syncRegistrationEntity.setCenterId(getHashCode(referenceId.split("_")[0])); + syncRegistrationEntity.setPhone(dto.getPhone() != null ? getHashCode(dto.getPhone()) : null); + syncRegistrationEntity + .setLocationCode(getHashCode(getLocationCode(referenceId.split("_")[0], dto.getLangCode()))); + } catch (JsonProcessingException | RegStatusAppException | EncryptionFailureException + | ApisResourceAccessException exception) { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + "", exception.getMessage() + ExceptionUtils.getStackTrace(exception)); + } + + syncRegistrationEntity.setCreatedBy(CREATED_BY); + syncRegistrationEntity.setUpdatedBy(CREATED_BY); + if (syncRegistrationEntity.getIsDeleted() != null && syncRegistrationEntity.getIsDeleted()) { + syncRegistrationEntity.setDeletedDateTime(LocalDateTime.now(ZoneId.of("UTC"))); + } else { + syncRegistrationEntity.setDeletedDateTime(null); + } + + return syncRegistrationEntity; + } + + /* + * (non-Javadoc) + * + * @see io.mosip.registration.processor.status.service.SyncRegistrationService# + * decryptAndGetSyncRequest(java.lang.Object, java.lang.String, + * java.lang.String, java.util.List) + */ + @Override + public RegistrationSyncRequestDTO decryptAndGetSyncRequest(Object encryptedSyncMetaInfo, String referenceId, + String timeStamp, List syncResponseList) { + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", + "SyncRegistrationServiceImpl::decryptAndGetSyncRequest()::entry"); + + RegistrationSyncRequestDTO registrationSyncRequestDTO = null; + try { + String decryptedSyncMetaData = decryptor.decrypt(encryptedSyncMetaInfo, referenceId, timeStamp); + registrationSyncRequestDTO = (RegistrationSyncRequestDTO) JsonUtils + .jsonStringToJavaObject(RegistrationSyncRequestDTO.class, decryptedSyncMetaData); + + } catch (PacketDecryptionFailureException | ApisResourceAccessException e) { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + "", e.getMessage() + ExceptionUtils.getStackTrace(e)); + SyncResponseFailDto syncResponseFailureDto = new SyncResponseFailDto(); + + syncResponseFailureDto.setStatus(ResponseStatusCode.FAILURE.toString()); + syncResponseFailureDto.setMessage(PlatformErrorMessages.RPR_RGS_DECRYPTION_FAILED.getMessage()); + syncResponseFailureDto.setErrorCode(PlatformErrorMessages.RPR_RGS_DECRYPTION_FAILED.getCode()); + syncResponseList.add(syncResponseFailureDto); + } catch (JsonParseException e) { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + "", e.getMessage() + ExceptionUtils.getStackTrace(e)); + SyncResponseFailDto syncResponseFailureDto = new SyncResponseFailDto(); + + syncResponseFailureDto.setStatus(ResponseStatusCode.FAILURE.toString()); + syncResponseFailureDto.setMessage(PlatformErrorMessages.RPR_RGS_JSON_PARSING_EXCEPTION.getMessage()); + syncResponseFailureDto.setErrorCode(PlatformErrorMessages.RPR_RGS_JSON_PARSING_EXCEPTION.getCode()); + syncResponseList.add(syncResponseFailureDto); + + } catch (JsonMappingException e) { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + "", e.getMessage() + ExceptionUtils.getStackTrace(e)); + SyncResponseFailDto syncResponseFailureDto = new SyncResponseFailDto(); + + syncResponseFailureDto.setStatus(ResponseStatusCode.FAILURE.toString()); + syncResponseFailureDto.setMessage(PlatformErrorMessages.RPR_RGS_JSON_MAPPING_EXCEPTION.getMessage()); + syncResponseFailureDto.setErrorCode(PlatformErrorMessages.RPR_RGS_JSON_MAPPING_EXCEPTION.getCode()); + syncResponseList.add(syncResponseFailureDto); + } catch (IOException e) { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + "", e.getMessage() + ExceptionUtils.getStackTrace(e)); + SyncResponseFailDto syncResponseFailureDto = new SyncResponseFailDto(); + + syncResponseFailureDto.setStatus(ResponseStatusCode.FAILURE.toString()); + syncResponseFailureDto.setMessage(PlatformErrorMessages.RPR_SYS_IO_EXCEPTION.getMessage()); + syncResponseFailureDto.setErrorCode(PlatformErrorMessages.RPR_SYS_IO_EXCEPTION.getCode()); + syncResponseList.add(syncResponseFailureDto); + } + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", + "SyncRegistrationServiceImpl::decryptAndGetSyncRequest()::exit"); + + return registrationSyncRequestDTO; + } + + /* + * (non-Javadoc) + * + * @see io.mosip.registration.processor.status.service.SyncRegistrationService# + * getByIds(java.util.List) + */ + @Override + public List getByIds(List requestIds) { + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", + "SyncRegistrationServiceImpl::getByIds()::entry"); + + try { + List registrationIds = new ArrayList<>(); + + for (RegistrationStatusSubRequestDto registrationStatusSubRequestDto : requestIds) { + registrationIds.add(registrationStatusSubRequestDto.getRegistrationId()); + } + if (!registrationIds.isEmpty()) { + List syncRegistrationEntityList = syncRegistrationDao.getByIds(registrationIds); + + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", + "SyncRegistrationServiceImpl::getByIds()::exit"); + return convertEntityListToDtoListAndGetExternalStatus(syncRegistrationEntityList); + } + return null; + } catch (DataAccessLayerException e) { + + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + "", e.getMessage() + ExceptionUtils.getStackTrace(e)); + throw new TablenotAccessibleException( + PlatformErrorMessages.RPR_RGS_REGISTRATION_TABLE_NOT_ACCESSIBLE.getMessage(), e); + } + + } + + @Override + public List searchLostRid(SearchInfo searchInfo) { + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), "", + "SyncRegistrationServiceImpl::getByIds()::entry"); + try { + updateFiltersWithHashedValues(searchInfo); + List syncRegistrationEntities = syncRegistrationDao.getSearchResults( + searchInfo.getFilters(), + searchInfo.getSort()); + List lostRidDtos = entityToDtoMapper(syncRegistrationEntities); + validateRegistrationIds(lostRidDtos); + return lostRidDtos; + } catch (DataAccessLayerException | NoSuchAlgorithmException | RegStatusAppException e) { + + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + "", e.getMessage() + ExceptionUtils.getStackTrace(e)); + throw new TablenotAccessibleException( + PlatformErrorMessages.RPR_RGS_REGISTRATION_TABLE_NOT_ACCESSIBLE.getMessage(), e); + } + } + + @Override + public List getExternalStatusByIds(List requestIds) { + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", + "SyncRegistrationServiceImpl::getExternalStatusByIds()::entry"); + + try { + if (!requestIds.isEmpty()) { + List syncRegistrationEntityList = syncRegistrationDao.getByIds(requestIds); + + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", + "SyncRegistrationServiceImpl::getExternalStatusByIds()::exit"); + return convertEntityListToDtoListAndGetExternalStatus(syncRegistrationEntityList); + } + return null; + } catch (DataAccessLayerException e) { + + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + "", e.getMessage() + ExceptionUtils.getStackTrace(e)); + throw new TablenotAccessibleException( + PlatformErrorMessages.RPR_RGS_REGISTRATION_TABLE_NOT_ACCESSIBLE.getMessage(), e); + } + + } + + private List entityToDtoMapper(List syncRegistrationEntities) { + List lostRidDtos = new ArrayList(); + syncRegistrationEntities.forEach(syncEntity -> { + LostRidDto lostRidDto = new LostRidDto(); + lostRidDto.setRegistrationId(syncEntity.getRegistrationId()); + lostRidDto.setRegistartionDate(null!=syncEntity.getRegistrationDate()?syncEntity.getRegistrationDate().toString():null); + lostRidDto.setSyncDateTime(null!=syncEntity.getCreateDateTime()?syncEntity.getCreateDateTime().toString():null); + if(syncEntity.getOptionalValues()!=null) { + getAdditionalInfo(syncEntity.getReferenceId(), syncEntity.getOptionalValues(), lostRidDto.getAdditionalInfo()); + } + lostRidDtos.add(lostRidDto); + }); + return lostRidDtos.stream().distinct().collect(Collectors.toList()); + } + + private void getAdditionalInfo(String referenceId, byte[] optionalValues, Map additionalInfo) { + String name=null; + try { + String decryptedData=decryptor.decrypt(CryptoUtil.encodeBase64String(optionalValues),referenceId, DateUtils.formatToISOString(DateUtils.getUTCCurrentDateTime())); + JSONObject jsonObject=new JSONObject(decryptedData); + name=jsonObject.getString("name"); + additionalInfo.put("name",name); + + } catch (PacketDecryptionFailureException | ApisResourceAccessException |JSONException e) { + throw new TablenotAccessibleException( + PlatformErrorMessages.RPR_RGS_DECRYPTION_FAILED.getMessage(),e); } + } + + private void validateRegistrationIds(List lostRidDtos) throws RegStatusAppException { + LostRidValidationException exception = new LostRidValidationException(); + if (lostRidDtos.size() >= maxSearchResult) { + throw new RegStatusAppException(PlatformErrorMessages.RPR_RGS_INVALID_SEARCH, exception); + } + + } + + private void updateFiltersWithHashedValues(SearchInfo searchInfo) + throws NoSuchAlgorithmException, RegStatusAppException { + for (FilterInfo filterInfo : searchInfo.getFilters()) { + if (filterInfo.getColumnName().equals("email") || filterInfo.getColumnName().equals("phone") + || filterInfo.getColumnName().equals("centerId") + || filterInfo.getColumnName().equals("locationCode")) { + + filterInfo.setValue(getHashCode(filterInfo.getValue())); + } else if (filterInfo.getColumnName().equalsIgnoreCase("name")) { + filterInfo.setValue(getHashCode(filterInfo.getValue().replaceAll("\\s", "").toLowerCase())); + } + } + } + + /** + * Convert entity list to dto list and get external status. + * + * @param syncRegistrationEntityList + * the sync registration entity list + * @return the list + */ + private List convertEntityListToDtoListAndGetExternalStatus( + List syncRegistrationEntityList) { + List list = new ArrayList<>(); + if (syncRegistrationEntityList != null) { + for (SyncRegistrationEntity entity : syncRegistrationEntityList) { + list.add(convertEntityToDtoAndGetExternalStatus(entity)); + } + + } + return list; + } + + /** + * Convert entity to dto and get external status. + * + * @param entity + * the entity + * @return the registration status dto + */ + private RegistrationStatusDto convertEntityToDtoAndGetExternalStatus(SyncRegistrationEntity entity) { + RegistrationStatusDto registrationStatusDto = new RegistrationStatusDto(); + registrationStatusDto.setRegistrationId(entity.getRegistrationId()); + registrationStatusDto.setAdditionalInfoReqId(entity.getAdditionalInfoReqId()); + registrationStatusDto.setStatusCode(RegistrationExternalStatusCode.UPLOAD_PENDING.toString()); + return registrationStatusDto; + } + + private String getLocationCode(String centerId, String langCode) { + String requestUrl = locationCodeReqUrl + "/" + centerId + "/" + langCode; + URI requestUri = URI.create(requestUrl); + String locationCode = null; + try { + String response = restApiClient.getApi(requestUri, String.class); + JSONObject jsonObjects = new JSONObject(response); + locationCode = jsonObjects.getJSONObject("response") != null ? ((JSONObject) jsonObjects.getJSONObject("response").getJSONArray("registrationCenters").get(0)) + .getString("locationCode") : null; + } catch (Exception e) { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + "", e.getMessage() + ExceptionUtils.getStackTrace(e)); + } + return locationCode; + } + + @Override + public boolean deleteAdditionalInfo(SyncRegistrationEntity syncEntity) { + return syncRegistrationDao.deleteAdditionalInfo(syncEntity); + } + + @Override + public List getByPacketIds(List packetIdList) { + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", + "SyncRegistrationServiceImpl::getByPacketIds()::entry"); + try { + if (!packetIdList.isEmpty()) { + List syncRegistrationEntityList = syncRegistrationDao + .getByPacketIds(packetIdList); + + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", + "SyncRegistrationServiceImpl::getByPacketIds()::exit"); + return syncRegistrationEntityList; + } + return null; + } catch (DataAccessLayerException e) { + + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + "", e.getMessage() + ExceptionUtils.getStackTrace(e)); + throw new TablenotAccessibleException( + PlatformErrorMessages.RPR_RGS_REGISTRATION_TABLE_NOT_ACCESSIBLE.getMessage(), e); + } + } + + private static byte[] getHMACHash(String value) throws java.security.NoSuchAlgorithmException { + if (value == null) + return null; + return HMACUtils2.generateHash(value.getBytes()); + } + + private static byte[] getHMACHashWithSalt(byte[] valueBytes, byte[] saltBytes) + throws java.security.NoSuchAlgorithmException { + if (valueBytes == null) + return null; + return HMACUtils2.digestAsPlainTextWithSalt(valueBytes, saltBytes).getBytes(); + } + + private String getHashCode(String value) throws RegStatusAppException { + String encodedHash = null; + if (value == null) { + return null; + } + try { + byte[] hashCode = getHMACHash(value); + byte[] nonce = Arrays.copyOfRange(hashCode, hashCode.length - 2, hashCode.length); + String result = convertBytesToHex(nonce); + Long hashValue = Long.parseLong(result, 16); + Long saltIndex = hashValue % 10000; + String salt = syncRegistrationDao.getSaltValue(saltIndex); + byte[] saltBytes=null; + try { + saltBytes= CryptoUtil.decodeURLSafeBase64(salt); + } catch (IllegalArgumentException exception) { + saltBytes = CryptoUtil.decodePlainBase64(salt); + } + byte[] hashBytes = value.getBytes(); + for (int i = 0; i <= iteration; i++) { + hashBytes = getHMACHashWithSalt(hashBytes, saltBytes); + } + encodedHash = CryptoUtil.encodeToURLSafeBase64(hashBytes); + } catch (NoSuchAlgorithmException e) { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + "", e.getMessage() + ExceptionUtils.getStackTrace(e)); + throw new RegStatusAppException(PlatformErrorMessages.RPR_RGS_INVALID_SEARCH, e); + } + return encodedHash; + } + + private static String convertBytesToHex(byte[] bytes) { + StringBuilder result = new StringBuilder(); + for (byte temp : bytes) { + result.append(String.format("%02x", temp)); + } + return result.toString(); + } + +} From c005d3fb9415baa2436f553599ff61a9c0ebfb9a Mon Sep 17 00:00:00 2001 From: Sowmya Ujjappa Banakar Date: Thu, 27 Jun 2024 15:45:12 +0530 Subject: [PATCH 2/4] MOSIP-32461 duplicate code removal Signed-off-by: Sowmya Ujjappa Banakar --- .../ManualVerificationExceptionHandler.java | 666 ++++++++--------- .../ManualVerificationRequestValidator.java | 4 +- .../ManualVerificationAppException.java | 110 --- ...ManualVerificationValidationException.java | 63 -- .../ManualVerificationExceptionHandler.java | 667 +++++++++--------- .../ManualVerificationRequestValidator.java | 4 +- .../sender/stage/MessageSenderStage.java | 2 +- ...ketDecryptionFailureExceptionConstant.java | 45 -- .../exception/PacketReceiverAppException.java | 128 ---- .../core/constant}/MessageSenderConstant.java | 50 +- ...ketDecryptionFailureExceptionConstant.java | 90 +-- .../ManualVerificationAppException.java | 220 +++--- ...ManualVerificationValidationException.java | 127 ++-- .../constants/MessageSenderConstant.java | 25 - .../manager/decryptor/DecryptorImpl.java | 416 +++++------ ...ketDecryptionFailureExceptionConstant.java | 45 -- .../processor/status/decryptor/Decryptor.java | 424 +++++------ ...ketDecryptionFailureExceptionConstant.java | 45 -- 18 files changed, 1336 insertions(+), 1795 deletions(-) delete mode 100644 registration-processor/core-processor/registration-processor-verification-stage/src/main/java/io/mosip/registration/processor/verification/exception/ManualVerificationAppException.java delete mode 100644 registration-processor/core-processor/registration-processor-verification-stage/src/main/java/io/mosip/registration/processor/verification/exception/ManualVerificationValidationException.java delete mode 100644 registration-processor/pre-processor/registration-processor-packet-uploader-stage/src/main/java/io/mosip/registration/processor/packet/uploader/constants/PacketDecryptionFailureExceptionConstant.java delete mode 100644 registration-processor/pre-processor/registration-processor-packet-uploader-stage/src/main/java/io/mosip/registration/processor/packet/uploader/exception/PacketReceiverAppException.java rename registration-processor/{post-processor/registration-processor-message-sender-stage/src/main/java/io/mosip/registration/processor/message/sender/constants => registration-processor-core/src/main/java/io/mosip/registration/processor/core/constant}/MessageSenderConstant.java (93%) rename registration-processor/{registration-processor-packet-manager/src/main/java/io/mosip/registration/processor/packet/manager/exception => registration-processor-core/src/main/java/io/mosip/registration/processor/core/constant}/PacketDecryptionFailureExceptionConstant.java (90%) rename registration-processor/{core-processor/registration-processor-manual-adjudication-stage/src/main/java/io/mosip/registration/processor/adjudication => registration-processor-core/src/main/java/io/mosip/registration/processor/core}/exception/ManualVerificationAppException.java (94%) rename registration-processor/{core-processor/registration-processor-manual-adjudication-stage/src/main/java/io/mosip/registration/processor/adjudication => registration-processor-core/src/main/java/io/mosip/registration/processor/core}/exception/ManualVerificationValidationException.java (89%) delete mode 100644 registration-processor/registration-processor-notification-service/src/main/java/io/mosip/registration/processor/notification/constants/MessageSenderConstant.java delete mode 100644 registration-processor/registration-processor-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/constants/PacketDecryptionFailureExceptionConstant.java delete mode 100644 registration-processor/registration-processor-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/dto/PacketDecryptionFailureExceptionConstant.java diff --git a/registration-processor/core-processor/registration-processor-manual-adjudication-stage/src/main/java/io/mosip/registration/processor/adjudication/exception/handler/ManualVerificationExceptionHandler.java b/registration-processor/core-processor/registration-processor-manual-adjudication-stage/src/main/java/io/mosip/registration/processor/adjudication/exception/handler/ManualVerificationExceptionHandler.java index cb5ca19fc3f..4b28e5d2b1a 100644 --- a/registration-processor/core-processor/registration-processor-manual-adjudication-stage/src/main/java/io/mosip/registration/processor/adjudication/exception/handler/ManualVerificationExceptionHandler.java +++ b/registration-processor/core-processor/registration-processor-manual-adjudication-stage/src/main/java/io/mosip/registration/processor/adjudication/exception/handler/ManualVerificationExceptionHandler.java @@ -1,334 +1,334 @@ -package io.mosip.registration.processor.adjudication.exception.handler; - -import java.util.List; -import java.util.Objects; -import java.util.stream.Collectors; - -import io.mosip.registration.processor.adjudication.exception.FileNotFoundInFileStoreException; -import io.mosip.registration.processor.adjudication.exception.FileNotPresentException; -import io.mosip.registration.processor.adjudication.exception.InvalidFieldsException; -import io.mosip.registration.processor.adjudication.exception.InvalidFileNameException; -import io.mosip.registration.processor.adjudication.exception.InvalidTokenHandlerException; -import io.mosip.registration.processor.adjudication.exception.InvalidUpdateException; -import io.mosip.registration.processor.adjudication.exception.ManualVerificationAppException; -import io.mosip.registration.processor.adjudication.exception.MatchTypeNotFoundException; -import io.mosip.registration.processor.adjudication.exception.NoRecordAssignedException; -import io.mosip.registration.processor.adjudication.exception.PacketNotFoundException; -import io.mosip.registration.processor.adjudication.exception.UserIDNotPresentException; -import io.mosip.registration.processor.adjudication.response.dto.ManualVerificationAssignResponseDTO; -import io.mosip.registration.processor.adjudication.response.dto.ManualVerificationBioDemoResponseDTO; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.core.env.Environment; - -import io.mosip.kernel.core.exception.BaseCheckedException; -import io.mosip.kernel.core.exception.BaseUncheckedException; -import io.mosip.kernel.core.fsadapter.exception.FSAdapterException; -import io.mosip.kernel.core.logger.spi.Logger; -import io.mosip.kernel.core.util.DateUtils; -import io.mosip.registration.processor.core.common.rest.dto.BaseRestResponseDTO; -import io.mosip.registration.processor.core.common.rest.dto.ErrorDTO; -import io.mosip.registration.processor.core.constant.LoggerFileConstant; -import io.mosip.registration.processor.core.exception.util.PlatformErrorMessages; -import io.mosip.registration.processor.core.logger.RegProcessorLogger; -import io.mosip.registration.processor.core.token.validation.exception.InvalidTokenException; -import io.vertx.core.json.DecodeException; - -/** - * The Class ManualAssignDecisionExceptionHandler. - * - * @author Rishabh Keshari - */ -public class ManualVerificationExceptionHandler { - - /** The reg proc logger. */ - private static Logger regProcLogger = RegProcessorLogger.getLogger(ManualVerificationExceptionHandler.class); - - /** The Constant APPLICATION_VERSION. */ - private static final String APPLICATION_VERSION = "mosip.registration.processor.application.version"; - - /** The Constant DATETIME_PATTERN. */ - private static final String DATETIME_PATTERN = "mosip.registration.processor.datetime.pattern"; - /** The id. */ - private String id = ""; - Object responseDtoType; - /** The env. */ - @Autowired - private Environment env; - - /** - * Gets the id. - * - * @return the id - */ - public String getId() { - return id; - } - - /** - * Sets the id. - * - * @param id - * the new id - */ - public void setId(String id) { - this.id = id; - } - - /** - * Instantiates a new manual assign decision exception handler. - */ - public ManualVerificationExceptionHandler() { - - } - - public Object getResponseDtoType() { - return responseDtoType; - } - - public void setResponseDtoType(Object responseDtoType) { - this.responseDtoType = responseDtoType; - } - - /** - * Instantiates a new manual assign decision exception handler. - * - * @param id - * the id - */ - public ManualVerificationExceptionHandler(String id) { - this.id = id; - } - - /** - * Invalid file name exception handler. - * - * @param e - * the e - * @return the string - */ - public BaseRestResponseDTO invalidFileNameExceptionHandler(final InvalidFileNameException e) { - return buildAssignDecisionExceptionResponse((Exception) e); - } - - /** - * Packet not found exception handler. - * - * @param e - * the e - * @return the string - */ - public BaseRestResponseDTO packetNotFoundExceptionHandler(final PacketNotFoundException e) { - FileNotPresentException fileNotPresentException = new FileNotPresentException( - PlatformErrorMessages.RPR_MVS_FILE_NOT_PRESENT.getCode(), - PlatformErrorMessages.RPR_MVS_FILE_NOT_PRESENT.getMessage()); - return buildAssignDecisionExceptionResponse(fileNotPresentException); - } - - /** - * No record assigned exception handler. - * - * @param e - * the e - * @return the string - */ - public BaseRestResponseDTO noRecordAssignedExceptionHandler(NoRecordAssignedException e) { - return buildAssignDecisionExceptionResponse((Exception) e); - } - - /** - * No record assigned exception handler. - * - * @param e - * the e - * @return the string - */ - public BaseRestResponseDTO UserIDNotPresentException(UserIDNotPresentException e) { - return buildAssignDecisionExceptionResponse((Exception) e); - } - - /** - * Data exception handler. - * - * @param e - * the e - * @return the string - */ - public BaseRestResponseDTO decodeExceptionHandler(DecodeException e) { - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), - "RPR-DBE-001 JSON DATA DECODE exception", e.getMessage()); - ManualVerificationAppException ex = new ManualVerificationAppException( - PlatformErrorMessages.RPR_MVS_DECODE_EXCEPTION, e); - return buildAssignDecisionExceptionResponse((Exception) ex); - } - - public BaseRestResponseDTO matchTypeNotFoundExceptionHandler(MatchTypeNotFoundException e) { - MatchTypeNotFoundException ex = new MatchTypeNotFoundException( - PlatformErrorMessages.RPR_MVS_NO_MATCH_TYPE_PRESENT.getCode(), - PlatformErrorMessages.RPR_MVS_NO_MATCH_TYPE_PRESENT.getMessage()); - return buildAssignDecisionExceptionResponse((Exception) ex); - } - - public BaseRestResponseDTO fileNotFoundInFileStoreExceptionHandler(FSAdapterException e) { - FileNotFoundInFileStoreException ex = new FileNotFoundInFileStoreException( - PlatformErrorMessages.RPR_PIS_FILE_NOT_FOUND_IN_PACKET_STORE.getCode(), - PlatformErrorMessages.RPR_PIS_FILE_NOT_FOUND_IN_PACKET_STORE.getMessage()); - return buildAssignDecisionExceptionResponse((Exception) ex); - } - - public BaseRestResponseDTO invalidTokenExceptionHandler(InvalidTokenException e) { - InvalidTokenHandlerException ex = new InvalidTokenHandlerException( - PlatformErrorMessages.RPR_AUT_INVALID_TOKEN.getCode(), - PlatformErrorMessages.RPR_AUT_INVALID_TOKEN.getMessage()); - return buildAssignDecisionExceptionResponse((Exception) ex); - } - - public BaseRestResponseDTO unknownExceptionHandler(Exception e) { - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), - "RPR-DBE-001 JSON DATA DECODE exception", e.getMessage()); - ManualVerificationAppException ex = new ManualVerificationAppException( - PlatformErrorMessages.RPR_MVS_UNKNOWN_EXCEPTION, e); - return buildAssignDecisionExceptionResponse((Exception) ex); - } - - /** - * Invalid update exception. - * - * @param e - * the e - * @return the string - */ - public BaseRestResponseDTO invalidUpdateException(InvalidUpdateException e) { - return buildAssignDecisionExceptionResponse((Exception) e); - } - - /** - * Invalid filed exception. - * - * @param e - * the e - * @return the string - */ - public BaseRestResponseDTO invalidFiledException(InvalidFieldsException e) { - return buildAssignDecisionExceptionResponse((Exception) e); - } - - public BaseRestResponseDTO invalidManualVerificationAppException(ManualVerificationAppException e) { - return buildAssignDecisionExceptionResponse((Exception) e); - } - - public BaseRestResponseDTO invalidIllegalArgumentException(IllegalArgumentException e) { - ManualVerificationAppException ex = new ManualVerificationAppException( - PlatformErrorMessages.RPR_MVS_INVALID_ARGUMENT_EXCEPTION, e); - return buildAssignDecisionExceptionResponse((Exception) ex); - } - - /** - * Builds the packet receiver exception response. - * - * @param ex - * the ex - * @return the string - */ - private BaseRestResponseDTO buildAssignDecisionExceptionResponse(Exception ex) { - if (responseDtoType.getClass() == ManualVerificationAssignResponseDTO.class) { - ManualVerificationAssignResponseDTO response = new ManualVerificationAssignResponseDTO(); - Throwable e = ex; - - if (Objects.isNull(response.getId())) { - response.setId(id); - } - if (e instanceof BaseCheckedException) { - List errorCodes = ((BaseCheckedException) e).getCodes(); - List errorTexts = ((BaseCheckedException) e).getErrorTexts(); - List errors = errorTexts.parallelStream() - .map(errMsg -> new ErrorDTO(errorCodes.get(errorTexts.indexOf(errMsg)), errMsg)).distinct() - .collect(Collectors.toList()); - response.setErrors(errors); - } - if (e instanceof BaseUncheckedException) { - List errorCodes = ((BaseUncheckedException) e).getCodes(); - List errorTexts = ((BaseUncheckedException) e).getErrorTexts(); - - List errors = errorTexts.parallelStream() - .map(errMsg -> new ErrorDTO(errorCodes.get(errorTexts.indexOf(errMsg)), errMsg)).distinct() - .collect(Collectors.toList()); - - response.setErrors(errors); - } - - response.setResponsetime(DateUtils.getUTCCurrentDateTimeString("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")); - response.setVersion("1.0"); - response.setResponse(null); - return response; - } else { - ManualVerificationBioDemoResponseDTO response = new ManualVerificationBioDemoResponseDTO(); - Throwable e = ex; - - if (Objects.isNull(response.getId())) { - response.setId(id); - } - if (e instanceof BaseCheckedException) { - List errorCodes = ((BaseCheckedException) e).getCodes(); - List errorTexts = ((BaseCheckedException) e).getErrorTexts(); - List errors = errorTexts.parallelStream() - .map(errMsg -> new ErrorDTO(errorCodes.get(errorTexts.indexOf(errMsg)), errMsg)).distinct() - .collect(Collectors.toList()); - response.setErrors(errors); - } - if (e instanceof BaseUncheckedException) { - List errorCodes = ((BaseUncheckedException) e).getCodes(); - List errorTexts = ((BaseUncheckedException) e).getErrorTexts(); - - List errors = errorTexts.parallelStream() - .map(errMsg -> new ErrorDTO(errorCodes.get(errorTexts.indexOf(errMsg)), errMsg)).distinct() - .collect(Collectors.toList()); - - response.setErrors(errors); - } - - response.setResponsetime(DateUtils.getUTCCurrentDateTimeString(env.getProperty(DATETIME_PATTERN))); - response.setVersion(env.getProperty(APPLICATION_VERSION)); - response.setResponse(null); - return response; - } - - } - - /** - * Handler. - * - * @param exe - * the exe - * @return the string - */ - public BaseRestResponseDTO handler(Throwable exe) { - if (exe instanceof InvalidFieldsException) - return invalidFiledException((InvalidFieldsException) exe); - if (exe instanceof InvalidUpdateException) - return invalidUpdateException((InvalidUpdateException) exe); - if (exe instanceof NoRecordAssignedException) - return noRecordAssignedExceptionHandler((NoRecordAssignedException) exe); - if (exe instanceof UserIDNotPresentException) - return UserIDNotPresentException((UserIDNotPresentException) exe); - if (exe instanceof PacketNotFoundException) - return packetNotFoundExceptionHandler((PacketNotFoundException) exe); - if (exe instanceof InvalidFileNameException) - return invalidFileNameExceptionHandler((InvalidFileNameException) exe); - if (exe instanceof ManualVerificationAppException) - return invalidManualVerificationAppException((ManualVerificationAppException) exe); - if (exe instanceof IllegalArgumentException) - return invalidIllegalArgumentException((IllegalArgumentException) exe); - if (exe instanceof DecodeException) - return decodeExceptionHandler((DecodeException) exe); - if (exe instanceof MatchTypeNotFoundException) - return matchTypeNotFoundExceptionHandler((MatchTypeNotFoundException) exe); - if (exe instanceof FSAdapterException) { - return fileNotFoundInFileStoreExceptionHandler((FSAdapterException) exe); - } - if (exe instanceof InvalidTokenException) { - return invalidTokenExceptionHandler((InvalidTokenException) exe); - } else - return unknownExceptionHandler((Exception) exe); - } - +package io.mosip.registration.processor.adjudication.exception.handler; + +import java.util.List; +import java.util.Objects; +import java.util.stream.Collectors; + +import io.mosip.registration.processor.adjudication.exception.FileNotFoundInFileStoreException; +import io.mosip.registration.processor.adjudication.exception.FileNotPresentException; +import io.mosip.registration.processor.adjudication.exception.InvalidFieldsException; +import io.mosip.registration.processor.adjudication.exception.InvalidFileNameException; +import io.mosip.registration.processor.adjudication.exception.InvalidTokenHandlerException; +import io.mosip.registration.processor.adjudication.exception.InvalidUpdateException; +import io.mosip.registration.processor.adjudication.exception.MatchTypeNotFoundException; +import io.mosip.registration.processor.adjudication.exception.NoRecordAssignedException; +import io.mosip.registration.processor.adjudication.exception.PacketNotFoundException; +import io.mosip.registration.processor.adjudication.exception.UserIDNotPresentException; +import io.mosip.registration.processor.adjudication.response.dto.ManualVerificationAssignResponseDTO; +import io.mosip.registration.processor.adjudication.response.dto.ManualVerificationBioDemoResponseDTO; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; + +import io.mosip.kernel.core.exception.BaseCheckedException; +import io.mosip.kernel.core.exception.BaseUncheckedException; +import io.mosip.kernel.core.fsadapter.exception.FSAdapterException; +import io.mosip.kernel.core.logger.spi.Logger; +import io.mosip.kernel.core.util.DateUtils; +import io.mosip.registration.processor.core.common.rest.dto.BaseRestResponseDTO; +import io.mosip.registration.processor.core.common.rest.dto.ErrorDTO; +import io.mosip.registration.processor.core.constant.LoggerFileConstant; +import io.mosip.registration.processor.core.exception.ManualVerificationAppException; +import io.mosip.registration.processor.core.exception.util.PlatformErrorMessages; +import io.mosip.registration.processor.core.logger.RegProcessorLogger; +import io.mosip.registration.processor.core.token.validation.exception.InvalidTokenException; +import io.vertx.core.json.DecodeException; + +/** + * The Class ManualAssignDecisionExceptionHandler. + * + * @author Rishabh Keshari + */ +public class ManualVerificationExceptionHandler { + + /** The reg proc logger. */ + private static Logger regProcLogger = RegProcessorLogger.getLogger(ManualVerificationExceptionHandler.class); + + /** The Constant APPLICATION_VERSION. */ + private static final String APPLICATION_VERSION = "mosip.registration.processor.application.version"; + + /** The Constant DATETIME_PATTERN. */ + private static final String DATETIME_PATTERN = "mosip.registration.processor.datetime.pattern"; + /** The id. */ + private String id = ""; + Object responseDtoType; + /** The env. */ + @Autowired + private Environment env; + + /** + * Gets the id. + * + * @return the id + */ + public String getId() { + return id; + } + + /** + * Sets the id. + * + * @param id + * the new id + */ + public void setId(String id) { + this.id = id; + } + + /** + * Instantiates a new manual assign decision exception handler. + */ + public ManualVerificationExceptionHandler() { + + } + + public Object getResponseDtoType() { + return responseDtoType; + } + + public void setResponseDtoType(Object responseDtoType) { + this.responseDtoType = responseDtoType; + } + + /** + * Instantiates a new manual assign decision exception handler. + * + * @param id + * the id + */ + public ManualVerificationExceptionHandler(String id) { + this.id = id; + } + + /** + * Invalid file name exception handler. + * + * @param e + * the e + * @return the string + */ + public BaseRestResponseDTO invalidFileNameExceptionHandler(final InvalidFileNameException e) { + return buildAssignDecisionExceptionResponse((Exception) e); + } + + /** + * Packet not found exception handler. + * + * @param e + * the e + * @return the string + */ + public BaseRestResponseDTO packetNotFoundExceptionHandler(final PacketNotFoundException e) { + FileNotPresentException fileNotPresentException = new FileNotPresentException( + PlatformErrorMessages.RPR_MVS_FILE_NOT_PRESENT.getCode(), + PlatformErrorMessages.RPR_MVS_FILE_NOT_PRESENT.getMessage()); + return buildAssignDecisionExceptionResponse(fileNotPresentException); + } + + /** + * No record assigned exception handler. + * + * @param e + * the e + * @return the string + */ + public BaseRestResponseDTO noRecordAssignedExceptionHandler(NoRecordAssignedException e) { + return buildAssignDecisionExceptionResponse((Exception) e); + } + + /** + * No record assigned exception handler. + * + * @param e + * the e + * @return the string + */ + public BaseRestResponseDTO UserIDNotPresentException(UserIDNotPresentException e) { + return buildAssignDecisionExceptionResponse((Exception) e); + } + + /** + * Data exception handler. + * + * @param e + * the e + * @return the string + */ + public BaseRestResponseDTO decodeExceptionHandler(DecodeException e) { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), + "RPR-DBE-001 JSON DATA DECODE exception", e.getMessage()); + ManualVerificationAppException ex = new ManualVerificationAppException( + PlatformErrorMessages.RPR_MVS_DECODE_EXCEPTION, e); + return buildAssignDecisionExceptionResponse((Exception) ex); + } + + public BaseRestResponseDTO matchTypeNotFoundExceptionHandler(MatchTypeNotFoundException e) { + MatchTypeNotFoundException ex = new MatchTypeNotFoundException( + PlatformErrorMessages.RPR_MVS_NO_MATCH_TYPE_PRESENT.getCode(), + PlatformErrorMessages.RPR_MVS_NO_MATCH_TYPE_PRESENT.getMessage()); + return buildAssignDecisionExceptionResponse((Exception) ex); + } + + public BaseRestResponseDTO fileNotFoundInFileStoreExceptionHandler(FSAdapterException e) { + FileNotFoundInFileStoreException ex = new FileNotFoundInFileStoreException( + PlatformErrorMessages.RPR_PIS_FILE_NOT_FOUND_IN_PACKET_STORE.getCode(), + PlatformErrorMessages.RPR_PIS_FILE_NOT_FOUND_IN_PACKET_STORE.getMessage()); + return buildAssignDecisionExceptionResponse((Exception) ex); + } + + public BaseRestResponseDTO invalidTokenExceptionHandler(InvalidTokenException e) { + InvalidTokenHandlerException ex = new InvalidTokenHandlerException( + PlatformErrorMessages.RPR_AUT_INVALID_TOKEN.getCode(), + PlatformErrorMessages.RPR_AUT_INVALID_TOKEN.getMessage()); + return buildAssignDecisionExceptionResponse((Exception) ex); + } + + public BaseRestResponseDTO unknownExceptionHandler(Exception e) { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), + "RPR-DBE-001 JSON DATA DECODE exception", e.getMessage()); + ManualVerificationAppException ex = new ManualVerificationAppException( + PlatformErrorMessages.RPR_MVS_UNKNOWN_EXCEPTION, e); + return buildAssignDecisionExceptionResponse((Exception) ex); + } + + /** + * Invalid update exception. + * + * @param e + * the e + * @return the string + */ + public BaseRestResponseDTO invalidUpdateException(InvalidUpdateException e) { + return buildAssignDecisionExceptionResponse((Exception) e); + } + + /** + * Invalid filed exception. + * + * @param e + * the e + * @return the string + */ + public BaseRestResponseDTO invalidFiledException(InvalidFieldsException e) { + return buildAssignDecisionExceptionResponse((Exception) e); + } + + public BaseRestResponseDTO invalidManualVerificationAppException(ManualVerificationAppException e) { + return buildAssignDecisionExceptionResponse((Exception) e); + } + + public BaseRestResponseDTO invalidIllegalArgumentException(IllegalArgumentException e) { + ManualVerificationAppException ex = new ManualVerificationAppException( + PlatformErrorMessages.RPR_MVS_INVALID_ARGUMENT_EXCEPTION, e); + return buildAssignDecisionExceptionResponse((Exception) ex); + } + + /** + * Builds the packet receiver exception response. + * + * @param ex + * the ex + * @return the string + */ + private BaseRestResponseDTO buildAssignDecisionExceptionResponse(Exception ex) { + if (responseDtoType.getClass() == ManualVerificationAssignResponseDTO.class) { + ManualVerificationAssignResponseDTO response = new ManualVerificationAssignResponseDTO(); + Throwable e = ex; + + if (Objects.isNull(response.getId())) { + response.setId(id); + } + if (e instanceof BaseCheckedException) { + List errorCodes = ((BaseCheckedException) e).getCodes(); + List errorTexts = ((BaseCheckedException) e).getErrorTexts(); + List errors = errorTexts.parallelStream() + .map(errMsg -> new ErrorDTO(errorCodes.get(errorTexts.indexOf(errMsg)), errMsg)).distinct() + .collect(Collectors.toList()); + response.setErrors(errors); + } + if (e instanceof BaseUncheckedException) { + List errorCodes = ((BaseUncheckedException) e).getCodes(); + List errorTexts = ((BaseUncheckedException) e).getErrorTexts(); + + List errors = errorTexts.parallelStream() + .map(errMsg -> new ErrorDTO(errorCodes.get(errorTexts.indexOf(errMsg)), errMsg)).distinct() + .collect(Collectors.toList()); + + response.setErrors(errors); + } + + response.setResponsetime(DateUtils.getUTCCurrentDateTimeString("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")); + response.setVersion("1.0"); + response.setResponse(null); + return response; + } else { + ManualVerificationBioDemoResponseDTO response = new ManualVerificationBioDemoResponseDTO(); + Throwable e = ex; + + if (Objects.isNull(response.getId())) { + response.setId(id); + } + if (e instanceof BaseCheckedException) { + List errorCodes = ((BaseCheckedException) e).getCodes(); + List errorTexts = ((BaseCheckedException) e).getErrorTexts(); + List errors = errorTexts.parallelStream() + .map(errMsg -> new ErrorDTO(errorCodes.get(errorTexts.indexOf(errMsg)), errMsg)).distinct() + .collect(Collectors.toList()); + response.setErrors(errors); + } + if (e instanceof BaseUncheckedException) { + List errorCodes = ((BaseUncheckedException) e).getCodes(); + List errorTexts = ((BaseUncheckedException) e).getErrorTexts(); + + List errors = errorTexts.parallelStream() + .map(errMsg -> new ErrorDTO(errorCodes.get(errorTexts.indexOf(errMsg)), errMsg)).distinct() + .collect(Collectors.toList()); + + response.setErrors(errors); + } + + response.setResponsetime(DateUtils.getUTCCurrentDateTimeString(env.getProperty(DATETIME_PATTERN))); + response.setVersion(env.getProperty(APPLICATION_VERSION)); + response.setResponse(null); + return response; + } + + } + + /** + * Handler. + * + * @param exe + * the exe + * @return the string + */ + public BaseRestResponseDTO handler(Throwable exe) { + if (exe instanceof InvalidFieldsException) + return invalidFiledException((InvalidFieldsException) exe); + if (exe instanceof InvalidUpdateException) + return invalidUpdateException((InvalidUpdateException) exe); + if (exe instanceof NoRecordAssignedException) + return noRecordAssignedExceptionHandler((NoRecordAssignedException) exe); + if (exe instanceof UserIDNotPresentException) + return UserIDNotPresentException((UserIDNotPresentException) exe); + if (exe instanceof PacketNotFoundException) + return packetNotFoundExceptionHandler((PacketNotFoundException) exe); + if (exe instanceof InvalidFileNameException) + return invalidFileNameExceptionHandler((InvalidFileNameException) exe); + if (exe instanceof ManualVerificationAppException) + return invalidManualVerificationAppException((ManualVerificationAppException) exe); + if (exe instanceof IllegalArgumentException) + return invalidIllegalArgumentException((IllegalArgumentException) exe); + if (exe instanceof DecodeException) + return decodeExceptionHandler((DecodeException) exe); + if (exe instanceof MatchTypeNotFoundException) + return matchTypeNotFoundExceptionHandler((MatchTypeNotFoundException) exe); + if (exe instanceof FSAdapterException) { + return fileNotFoundInFileStoreExceptionHandler((FSAdapterException) exe); + } + if (exe instanceof InvalidTokenException) { + return invalidTokenExceptionHandler((InvalidTokenException) exe); + } else + return unknownExceptionHandler((Exception) exe); + } + } \ No newline at end of file diff --git a/registration-processor/core-processor/registration-processor-manual-adjudication-stage/src/main/java/io/mosip/registration/processor/adjudication/util/ManualVerificationRequestValidator.java b/registration-processor/core-processor/registration-processor-manual-adjudication-stage/src/main/java/io/mosip/registration/processor/adjudication/util/ManualVerificationRequestValidator.java index 76189c5e06b..3aba9c0822a 100644 --- a/registration-processor/core-processor/registration-processor-manual-adjudication-stage/src/main/java/io/mosip/registration/processor/adjudication/util/ManualVerificationRequestValidator.java +++ b/registration-processor/core-processor/registration-processor-manual-adjudication-stage/src/main/java/io/mosip/registration/processor/adjudication/util/ManualVerificationRequestValidator.java @@ -16,11 +16,11 @@ import io.mosip.kernel.core.exception.ExceptionUtils; import io.mosip.kernel.core.logger.spi.Logger; import io.mosip.kernel.core.util.DateUtils; +import io.mosip.registration.processor.core.exception.ManualVerificationAppException; +import io.mosip.registration.processor.core.exception.ManualVerificationValidationException; import io.mosip.registration.processor.core.exception.util.PlatformErrorMessages; import io.mosip.registration.processor.core.logger.RegProcessorLogger; import io.mosip.registration.processor.adjudication.constants.ManualAdjudicationConstants; -import io.mosip.registration.processor.adjudication.exception.ManualVerificationAppException; -import io.mosip.registration.processor.adjudication.exception.ManualVerificationValidationException; import io.vertx.core.json.JsonObject; /** diff --git a/registration-processor/core-processor/registration-processor-verification-stage/src/main/java/io/mosip/registration/processor/verification/exception/ManualVerificationAppException.java b/registration-processor/core-processor/registration-processor-verification-stage/src/main/java/io/mosip/registration/processor/verification/exception/ManualVerificationAppException.java deleted file mode 100644 index eb2e6d0615a..00000000000 --- a/registration-processor/core-processor/registration-processor-verification-stage/src/main/java/io/mosip/registration/processor/verification/exception/ManualVerificationAppException.java +++ /dev/null @@ -1,110 +0,0 @@ -package io.mosip.registration.processor.verification.exception; - -import io.mosip.kernel.core.exception.BaseUncheckedException; -import io.mosip.registration.processor.core.exception.util.PlatformErrorMessages; - -/** - * The Class ManualVerificationAppException. - * @author Rishabh Keshari - */ -public class ManualVerificationAppException extends BaseUncheckedException { - - /** The Constant serialVersionUID. */ - private static final long serialVersionUID = 6748760277721155095L; - - /** The id. */ - private String id; - - /** - * Gets the id. - * - * @return the id - */ - public String getId() { - return id; - } - - /** - * Instantiates a new id repo app exception. - */ - public ManualVerificationAppException() { - super(); - } - - /** - * Instantiates a new id repo app exception. - * - * @param errorCode the error code - * @param errorMessage the error message - */ - public ManualVerificationAppException(String errorCode, String errorMessage) { - super(errorCode, errorMessage); - } - - /** - * Instantiates a new id repo app exception. - * - * @param errorCode the error code - * @param errorMessage the error message - * @param rootCause the root cause - */ - public ManualVerificationAppException(String errorCode, String errorMessage, Throwable rootCause) { - super(errorCode, errorMessage, rootCause); - } - - /** - * Instantiates a new id repo app exception. - * - * @param errorCode the error code - * @param errorMessage the error message - * @param rootCause the root cause - * @param id the id - */ - public ManualVerificationAppException(String errorCode, String errorMessage, Throwable rootCause, String id) { - super(errorCode, errorMessage, rootCause); - this.id = id; - } - - /** - * Instantiates a new id repo app exception. - * - * @param exceptionConstant the exception constant - */ - public ManualVerificationAppException(PlatformErrorMessages exceptionConstant) { - this(exceptionConstant.getCode(), exceptionConstant.getMessage()); - } - - /** - * Instantiates a new id repo app exception. - * - * @param exceptionConstant the exception constant - * @param rootCause the root cause - */ - public ManualVerificationAppException(PlatformErrorMessages exceptionConstant, Throwable rootCause) { - this(exceptionConstant.getCode(), exceptionConstant.getMessage(), rootCause); - } - - /** - * Instantiates a new id repo app exception. - * - * @param exceptionConstant the exception constant - * @param id the id - */ - public ManualVerificationAppException(PlatformErrorMessages exceptionConstant, String id) { - this(exceptionConstant.getCode(), exceptionConstant.getMessage()); - this.id = id; - } - - /** - * Instantiates a new id repo app exception. - * - * @param exceptionConstant the exception constant - * @param rootCause the root cause - * @param id the id - */ - public ManualVerificationAppException(PlatformErrorMessages exceptionConstant, Throwable rootCause, String id) { - this(exceptionConstant.getCode(), exceptionConstant.getMessage(), rootCause); - this.id = id; - } - -} diff --git a/registration-processor/core-processor/registration-processor-verification-stage/src/main/java/io/mosip/registration/processor/verification/exception/ManualVerificationValidationException.java b/registration-processor/core-processor/registration-processor-verification-stage/src/main/java/io/mosip/registration/processor/verification/exception/ManualVerificationValidationException.java deleted file mode 100644 index f29be15f8b2..00000000000 --- a/registration-processor/core-processor/registration-processor-verification-stage/src/main/java/io/mosip/registration/processor/verification/exception/ManualVerificationValidationException.java +++ /dev/null @@ -1,63 +0,0 @@ -package io.mosip.registration.processor.verification.exception; - -import io.mosip.registration.processor.core.exception.util.PlatformErrorMessages; - -/** - * The Class ManualVerificationValidationException. - * @author Rishabh Keshari - */ -public class ManualVerificationValidationException extends ManualVerificationAppException { - - - - /** The Constant serialVersionUID. */ - private static final long serialVersionUID = -2685586188884469940L; - - /** - * Instantiates a new id repo data validation exception. - */ - public ManualVerificationValidationException() { - super(); - } - - /** - * Instantiates a new id repo data validation exception. - * - * @param errorCode the error code - * @param errorMessage the error message - */ - public ManualVerificationValidationException(String errorCode, String errorMessage) { - super(errorCode, errorMessage); - } - - /** - * Instantiates a new id repo data validation exception. - * - * @param errorCode the error code - * @param errorMessage the error message - * @param rootCause the root cause - */ - public ManualVerificationValidationException(String errorCode, String errorMessage, Throwable rootCause) { - super(errorCode, errorMessage, rootCause); - } - - /** - * Instantiates a new id repo data validation exception. - * - * @param exceptionConstant the exception constant - */ - public ManualVerificationValidationException(PlatformErrorMessages exceptionConstant) { - super(exceptionConstant); - } - - /** - * Instantiates a new id repo data validation exception. - * - * @param exceptionConstant the exception constant - * @param rootCause the root cause - */ - public ManualVerificationValidationException(PlatformErrorMessages exceptionConstant, Throwable rootCause) { - super(exceptionConstant, rootCause); - } - -} diff --git a/registration-processor/core-processor/registration-processor-verification-stage/src/main/java/io/mosip/registration/processor/verification/exception/handler/ManualVerificationExceptionHandler.java b/registration-processor/core-processor/registration-processor-verification-stage/src/main/java/io/mosip/registration/processor/verification/exception/handler/ManualVerificationExceptionHandler.java index 6e050c919c5..081d8a3b6f2 100644 --- a/registration-processor/core-processor/registration-processor-verification-stage/src/main/java/io/mosip/registration/processor/verification/exception/handler/ManualVerificationExceptionHandler.java +++ b/registration-processor/core-processor/registration-processor-verification-stage/src/main/java/io/mosip/registration/processor/verification/exception/handler/ManualVerificationExceptionHandler.java @@ -1,334 +1,335 @@ -package io.mosip.registration.processor.verification.exception.handler; - -import java.util.List; -import java.util.Objects; -import java.util.stream.Collectors; - -import io.mosip.registration.processor.verification.exception.ManualVerificationAppException; -import io.mosip.registration.processor.verification.exception.MatchTypeNotFoundException; -import io.mosip.registration.processor.verification.exception.NoRecordAssignedException; -import io.mosip.registration.processor.verification.exception.PacketNotFoundException; -import io.mosip.registration.processor.verification.exception.UserIDNotPresentException; -import io.mosip.registration.processor.verification.response.dto.ManualVerificationAssignResponseDTO; -import io.mosip.registration.processor.verification.response.dto.ManualVerificationBioDemoResponseDTO; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.core.env.Environment; - -import io.mosip.kernel.core.exception.BaseCheckedException; -import io.mosip.kernel.core.exception.BaseUncheckedException; -import io.mosip.kernel.core.fsadapter.exception.FSAdapterException; -import io.mosip.kernel.core.logger.spi.Logger; -import io.mosip.kernel.core.util.DateUtils; -import io.mosip.registration.processor.core.common.rest.dto.BaseRestResponseDTO; -import io.mosip.registration.processor.core.common.rest.dto.ErrorDTO; -import io.mosip.registration.processor.core.constant.LoggerFileConstant; -import io.mosip.registration.processor.core.exception.util.PlatformErrorMessages; -import io.mosip.registration.processor.core.logger.RegProcessorLogger; -import io.mosip.registration.processor.core.token.validation.exception.InvalidTokenException; -import io.mosip.registration.processor.verification.exception.FileNotFoundInFileStoreException; -import io.mosip.registration.processor.verification.exception.FileNotPresentException; -import io.mosip.registration.processor.verification.exception.InvalidFieldsException; -import io.mosip.registration.processor.verification.exception.InvalidFileNameException; -import io.mosip.registration.processor.verification.exception.InvalidTokenHandlerException; -import io.mosip.registration.processor.verification.exception.InvalidUpdateException; -import io.vertx.core.json.DecodeException; - -/** - * The Class ManualAssignDecisionExceptionHandler. - * - * @author Rishabh Keshari - */ -public class ManualVerificationExceptionHandler { - - /** The reg proc logger. */ - private static Logger regProcLogger = RegProcessorLogger.getLogger(ManualVerificationExceptionHandler.class); - - /** The Constant APPLICATION_VERSION. */ - private static final String APPLICATION_VERSION = "mosip.registration.processor.application.version"; - - /** The Constant DATETIME_PATTERN. */ - private static final String DATETIME_PATTERN = "mosip.registration.processor.datetime.pattern"; - /** The id. */ - private String id = ""; - Object responseDtoType; - /** The env. */ - @Autowired - private Environment env; - - /** - * Gets the id. - * - * @return the id - */ - public String getId() { - return id; - } - - /** - * Sets the id. - * - * @param id - * the new id - */ - public void setId(String id) { - this.id = id; - } - - /** - * Instantiates a new manual assign decision exception handler. - */ - public ManualVerificationExceptionHandler() { - - } - - public Object getResponseDtoType() { - return responseDtoType; - } - - public void setResponseDtoType(Object responseDtoType) { - this.responseDtoType = responseDtoType; - } - - /** - * Instantiates a new manual assign decision exception handler. - * - * @param id - * the id - */ - public ManualVerificationExceptionHandler(String id) { - this.id = id; - } - - /** - * Invalid file name exception handler. - * - * @param e - * the e - * @return the string - */ - public BaseRestResponseDTO invalidFileNameExceptionHandler(final InvalidFileNameException e) { - return buildAssignDecisionExceptionResponse((Exception) e); - } - - /** - * Packet not found exception handler. - * - * @param e - * the e - * @return the string - */ - public BaseRestResponseDTO packetNotFoundExceptionHandler(final PacketNotFoundException e) { - FileNotPresentException fileNotPresentException = new FileNotPresentException( - PlatformErrorMessages.RPR_MVS_FILE_NOT_PRESENT.getCode(), - PlatformErrorMessages.RPR_MVS_FILE_NOT_PRESENT.getMessage()); - return buildAssignDecisionExceptionResponse(fileNotPresentException); - } - - /** - * No record assigned exception handler. - * - * @param e - * the e - * @return the string - */ - public BaseRestResponseDTO noRecordAssignedExceptionHandler(NoRecordAssignedException e) { - return buildAssignDecisionExceptionResponse((Exception) e); - } - - /** - * No record assigned exception handler. - * - * @param e - * the e - * @return the string - */ - public BaseRestResponseDTO UserIDNotPresentException(UserIDNotPresentException e) { - return buildAssignDecisionExceptionResponse((Exception) e); - } - - /** - * Data exception handler. - * - * @param e - * the e - * @return the string - */ - public BaseRestResponseDTO decodeExceptionHandler(DecodeException e) { - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), - "RPR-DBE-001 JSON DATA DECODE exception", e.getMessage()); - ManualVerificationAppException ex = new ManualVerificationAppException( - PlatformErrorMessages.RPR_MVS_DECODE_EXCEPTION, e); - return buildAssignDecisionExceptionResponse((Exception) ex); - } - - public BaseRestResponseDTO matchTypeNotFoundExceptionHandler(MatchTypeNotFoundException e) { - MatchTypeNotFoundException ex = new MatchTypeNotFoundException( - PlatformErrorMessages.RPR_MVS_NO_MATCH_TYPE_PRESENT.getCode(), - PlatformErrorMessages.RPR_MVS_NO_MATCH_TYPE_PRESENT.getMessage()); - return buildAssignDecisionExceptionResponse((Exception) ex); - } - - public BaseRestResponseDTO fileNotFoundInFileStoreExceptionHandler(FSAdapterException e) { - FileNotFoundInFileStoreException ex = new FileNotFoundInFileStoreException( - PlatformErrorMessages.RPR_PIS_FILE_NOT_FOUND_IN_PACKET_STORE.getCode(), - PlatformErrorMessages.RPR_PIS_FILE_NOT_FOUND_IN_PACKET_STORE.getMessage()); - return buildAssignDecisionExceptionResponse((Exception) ex); - } - - public BaseRestResponseDTO invalidTokenExceptionHandler(InvalidTokenException e) { - InvalidTokenHandlerException ex = new InvalidTokenHandlerException( - PlatformErrorMessages.RPR_AUT_INVALID_TOKEN.getCode(), - PlatformErrorMessages.RPR_AUT_INVALID_TOKEN.getMessage()); - return buildAssignDecisionExceptionResponse((Exception) ex); - } - - public BaseRestResponseDTO unknownExceptionHandler(Exception e) { - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), - "RPR-DBE-001 JSON DATA DECODE exception", e.getMessage()); - ManualVerificationAppException ex = new ManualVerificationAppException( - PlatformErrorMessages.RPR_MVS_UNKNOWN_EXCEPTION, e); - return buildAssignDecisionExceptionResponse((Exception) ex); - } - - /** - * Invalid update exception. - * - * @param e - * the e - * @return the string - */ - public BaseRestResponseDTO invalidUpdateException(InvalidUpdateException e) { - return buildAssignDecisionExceptionResponse((Exception) e); - } - - /** - * Invalid filed exception. - * - * @param e - * the e - * @return the string - */ - public BaseRestResponseDTO invalidFiledException(InvalidFieldsException e) { - return buildAssignDecisionExceptionResponse((Exception) e); - } - - public BaseRestResponseDTO invalidManualVerificationAppException(ManualVerificationAppException e) { - return buildAssignDecisionExceptionResponse((Exception) e); - } - - public BaseRestResponseDTO invalidIllegalArgumentException(IllegalArgumentException e) { - ManualVerificationAppException ex = new ManualVerificationAppException( - PlatformErrorMessages.RPR_MVS_INVALID_ARGUMENT_EXCEPTION, e); - return buildAssignDecisionExceptionResponse((Exception) ex); - } - - /** - * Builds the packet receiver exception response. - * - * @param ex - * the ex - * @return the string - */ - private BaseRestResponseDTO buildAssignDecisionExceptionResponse(Exception ex) { - if (responseDtoType.getClass() == ManualVerificationAssignResponseDTO.class) { - ManualVerificationAssignResponseDTO response = new ManualVerificationAssignResponseDTO(); - Throwable e = ex; - - if (Objects.isNull(response.getId())) { - response.setId(id); - } - if (e instanceof BaseCheckedException) { - List errorCodes = ((BaseCheckedException) e).getCodes(); - List errorTexts = ((BaseCheckedException) e).getErrorTexts(); - List errors = errorTexts.parallelStream() - .map(errMsg -> new ErrorDTO(errorCodes.get(errorTexts.indexOf(errMsg)), errMsg)).distinct() - .collect(Collectors.toList()); - response.setErrors(errors); - } - if (e instanceof BaseUncheckedException) { - List errorCodes = ((BaseUncheckedException) e).getCodes(); - List errorTexts = ((BaseUncheckedException) e).getErrorTexts(); - - List errors = errorTexts.parallelStream() - .map(errMsg -> new ErrorDTO(errorCodes.get(errorTexts.indexOf(errMsg)), errMsg)).distinct() - .collect(Collectors.toList()); - - response.setErrors(errors); - } - - response.setResponsetime(DateUtils.getUTCCurrentDateTimeString("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")); - response.setVersion("1.0"); - response.setResponse(null); - return response; - } else { - ManualVerificationBioDemoResponseDTO response = new ManualVerificationBioDemoResponseDTO(); - Throwable e = ex; - - if (Objects.isNull(response.getId())) { - response.setId(id); - } - if (e instanceof BaseCheckedException) { - List errorCodes = ((BaseCheckedException) e).getCodes(); - List errorTexts = ((BaseCheckedException) e).getErrorTexts(); - List errors = errorTexts.parallelStream() - .map(errMsg -> new ErrorDTO(errorCodes.get(errorTexts.indexOf(errMsg)), errMsg)).distinct() - .collect(Collectors.toList()); - response.setErrors(errors); - } - if (e instanceof BaseUncheckedException) { - List errorCodes = ((BaseUncheckedException) e).getCodes(); - List errorTexts = ((BaseUncheckedException) e).getErrorTexts(); - - List errors = errorTexts.parallelStream() - .map(errMsg -> new ErrorDTO(errorCodes.get(errorTexts.indexOf(errMsg)), errMsg)).distinct() - .collect(Collectors.toList()); - - response.setErrors(errors); - } - - response.setResponsetime(DateUtils.getUTCCurrentDateTimeString(env.getProperty(DATETIME_PATTERN))); - response.setVersion(env.getProperty(APPLICATION_VERSION)); - response.setResponse(null); - return response; - } - - } - - /** - * Handler. - * - * @param exe - * the exe - * @return the string - */ - public BaseRestResponseDTO handler(Throwable exe) { - if (exe instanceof InvalidFieldsException) - return invalidFiledException((InvalidFieldsException) exe); - if (exe instanceof InvalidUpdateException) - return invalidUpdateException((InvalidUpdateException) exe); - if (exe instanceof NoRecordAssignedException) - return noRecordAssignedExceptionHandler((NoRecordAssignedException) exe); - if (exe instanceof UserIDNotPresentException) - return UserIDNotPresentException((UserIDNotPresentException) exe); - if (exe instanceof PacketNotFoundException) - return packetNotFoundExceptionHandler((PacketNotFoundException) exe); - if (exe instanceof InvalidFileNameException) - return invalidFileNameExceptionHandler((InvalidFileNameException) exe); - if (exe instanceof ManualVerificationAppException) - return invalidManualVerificationAppException((ManualVerificationAppException) exe); - if (exe instanceof IllegalArgumentException) - return invalidIllegalArgumentException((IllegalArgumentException) exe); - if (exe instanceof DecodeException) - return decodeExceptionHandler((DecodeException) exe); - if (exe instanceof MatchTypeNotFoundException) - return matchTypeNotFoundExceptionHandler((MatchTypeNotFoundException) exe); - if (exe instanceof FSAdapterException) { - return fileNotFoundInFileStoreExceptionHandler((FSAdapterException) exe); - } - if (exe instanceof InvalidTokenException) { - return invalidTokenExceptionHandler((InvalidTokenException) exe); - } else - return unknownExceptionHandler((Exception) exe); - } - +package io.mosip.registration.processor.verification.exception.handler; + +import java.util.List; +import java.util.Objects; +import java.util.stream.Collectors; + + +import io.mosip.registration.processor.verification.exception.MatchTypeNotFoundException; +import io.mosip.registration.processor.verification.exception.NoRecordAssignedException; +import io.mosip.registration.processor.verification.exception.PacketNotFoundException; +import io.mosip.registration.processor.verification.exception.UserIDNotPresentException; +import io.mosip.registration.processor.verification.response.dto.ManualVerificationAssignResponseDTO; +import io.mosip.registration.processor.verification.response.dto.ManualVerificationBioDemoResponseDTO; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; + +import io.mosip.kernel.core.exception.BaseCheckedException; +import io.mosip.kernel.core.exception.BaseUncheckedException; +import io.mosip.kernel.core.fsadapter.exception.FSAdapterException; +import io.mosip.kernel.core.logger.spi.Logger; +import io.mosip.kernel.core.util.DateUtils; +import io.mosip.registration.processor.core.common.rest.dto.BaseRestResponseDTO; +import io.mosip.registration.processor.core.common.rest.dto.ErrorDTO; +import io.mosip.registration.processor.core.constant.LoggerFileConstant; +import io.mosip.registration.processor.core.exception.ManualVerificationAppException; +import io.mosip.registration.processor.core.exception.util.PlatformErrorMessages; +import io.mosip.registration.processor.core.logger.RegProcessorLogger; +import io.mosip.registration.processor.core.token.validation.exception.InvalidTokenException; +import io.mosip.registration.processor.verification.exception.FileNotFoundInFileStoreException; +import io.mosip.registration.processor.verification.exception.FileNotPresentException; +import io.mosip.registration.processor.verification.exception.InvalidFieldsException; +import io.mosip.registration.processor.verification.exception.InvalidFileNameException; +import io.mosip.registration.processor.verification.exception.InvalidTokenHandlerException; +import io.mosip.registration.processor.verification.exception.InvalidUpdateException; +import io.vertx.core.json.DecodeException; + +/** + * The Class ManualAssignDecisionExceptionHandler. + * + * @author Rishabh Keshari + */ +public class ManualVerificationExceptionHandler { + + /** The reg proc logger. */ + private static Logger regProcLogger = RegProcessorLogger.getLogger(ManualVerificationExceptionHandler.class); + + /** The Constant APPLICATION_VERSION. */ + private static final String APPLICATION_VERSION = "mosip.registration.processor.application.version"; + + /** The Constant DATETIME_PATTERN. */ + private static final String DATETIME_PATTERN = "mosip.registration.processor.datetime.pattern"; + /** The id. */ + private String id = ""; + Object responseDtoType; + /** The env. */ + @Autowired + private Environment env; + + /** + * Gets the id. + * + * @return the id + */ + public String getId() { + return id; + } + + /** + * Sets the id. + * + * @param id + * the new id + */ + public void setId(String id) { + this.id = id; + } + + /** + * Instantiates a new manual assign decision exception handler. + */ + public ManualVerificationExceptionHandler() { + + } + + public Object getResponseDtoType() { + return responseDtoType; + } + + public void setResponseDtoType(Object responseDtoType) { + this.responseDtoType = responseDtoType; + } + + /** + * Instantiates a new manual assign decision exception handler. + * + * @param id + * the id + */ + public ManualVerificationExceptionHandler(String id) { + this.id = id; + } + + /** + * Invalid file name exception handler. + * + * @param e + * the e + * @return the string + */ + public BaseRestResponseDTO invalidFileNameExceptionHandler(final InvalidFileNameException e) { + return buildAssignDecisionExceptionResponse((Exception) e); + } + + /** + * Packet not found exception handler. + * + * @param e + * the e + * @return the string + */ + public BaseRestResponseDTO packetNotFoundExceptionHandler(final PacketNotFoundException e) { + FileNotPresentException fileNotPresentException = new FileNotPresentException( + PlatformErrorMessages.RPR_MVS_FILE_NOT_PRESENT.getCode(), + PlatformErrorMessages.RPR_MVS_FILE_NOT_PRESENT.getMessage()); + return buildAssignDecisionExceptionResponse(fileNotPresentException); + } + + /** + * No record assigned exception handler. + * + * @param e + * the e + * @return the string + */ + public BaseRestResponseDTO noRecordAssignedExceptionHandler(NoRecordAssignedException e) { + return buildAssignDecisionExceptionResponse((Exception) e); + } + + /** + * No record assigned exception handler. + * + * @param e + * the e + * @return the string + */ + public BaseRestResponseDTO UserIDNotPresentException(UserIDNotPresentException e) { + return buildAssignDecisionExceptionResponse((Exception) e); + } + + /** + * Data exception handler. + * + * @param e + * the e + * @return the string + */ + public BaseRestResponseDTO decodeExceptionHandler(DecodeException e) { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), + "RPR-DBE-001 JSON DATA DECODE exception", e.getMessage()); + ManualVerificationAppException ex = new ManualVerificationAppException( + PlatformErrorMessages.RPR_MVS_DECODE_EXCEPTION, e); + return buildAssignDecisionExceptionResponse((Exception) ex); + } + + public BaseRestResponseDTO matchTypeNotFoundExceptionHandler(MatchTypeNotFoundException e) { + MatchTypeNotFoundException ex = new MatchTypeNotFoundException( + PlatformErrorMessages.RPR_MVS_NO_MATCH_TYPE_PRESENT.getCode(), + PlatformErrorMessages.RPR_MVS_NO_MATCH_TYPE_PRESENT.getMessage()); + return buildAssignDecisionExceptionResponse((Exception) ex); + } + + public BaseRestResponseDTO fileNotFoundInFileStoreExceptionHandler(FSAdapterException e) { + FileNotFoundInFileStoreException ex = new FileNotFoundInFileStoreException( + PlatformErrorMessages.RPR_PIS_FILE_NOT_FOUND_IN_PACKET_STORE.getCode(), + PlatformErrorMessages.RPR_PIS_FILE_NOT_FOUND_IN_PACKET_STORE.getMessage()); + return buildAssignDecisionExceptionResponse((Exception) ex); + } + + public BaseRestResponseDTO invalidTokenExceptionHandler(InvalidTokenException e) { + InvalidTokenHandlerException ex = new InvalidTokenHandlerException( + PlatformErrorMessages.RPR_AUT_INVALID_TOKEN.getCode(), + PlatformErrorMessages.RPR_AUT_INVALID_TOKEN.getMessage()); + return buildAssignDecisionExceptionResponse((Exception) ex); + } + + public BaseRestResponseDTO unknownExceptionHandler(Exception e) { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.APPLICATIONID.toString(), + "RPR-DBE-001 JSON DATA DECODE exception", e.getMessage()); + ManualVerificationAppException ex = new ManualVerificationAppException( + PlatformErrorMessages.RPR_MVS_UNKNOWN_EXCEPTION, e); + return buildAssignDecisionExceptionResponse((Exception) ex); + } + + /** + * Invalid update exception. + * + * @param e + * the e + * @return the string + */ + public BaseRestResponseDTO invalidUpdateException(InvalidUpdateException e) { + return buildAssignDecisionExceptionResponse((Exception) e); + } + + /** + * Invalid filed exception. + * + * @param e + * the e + * @return the string + */ + public BaseRestResponseDTO invalidFiledException(InvalidFieldsException e) { + return buildAssignDecisionExceptionResponse((Exception) e); + } + + public BaseRestResponseDTO invalidManualVerificationAppException(ManualVerificationAppException e) { + return buildAssignDecisionExceptionResponse((Exception) e); + } + + public BaseRestResponseDTO invalidIllegalArgumentException(IllegalArgumentException e) { + ManualVerificationAppException ex = new ManualVerificationAppException( + PlatformErrorMessages.RPR_MVS_INVALID_ARGUMENT_EXCEPTION, e); + return buildAssignDecisionExceptionResponse((Exception) ex); + } + + /** + * Builds the packet receiver exception response. + * + * @param ex + * the ex + * @return the string + */ + private BaseRestResponseDTO buildAssignDecisionExceptionResponse(Exception ex) { + if (responseDtoType.getClass() == ManualVerificationAssignResponseDTO.class) { + ManualVerificationAssignResponseDTO response = new ManualVerificationAssignResponseDTO(); + Throwable e = ex; + + if (Objects.isNull(response.getId())) { + response.setId(id); + } + if (e instanceof BaseCheckedException) { + List errorCodes = ((BaseCheckedException) e).getCodes(); + List errorTexts = ((BaseCheckedException) e).getErrorTexts(); + List errors = errorTexts.parallelStream() + .map(errMsg -> new ErrorDTO(errorCodes.get(errorTexts.indexOf(errMsg)), errMsg)).distinct() + .collect(Collectors.toList()); + response.setErrors(errors); + } + if (e instanceof BaseUncheckedException) { + List errorCodes = ((BaseUncheckedException) e).getCodes(); + List errorTexts = ((BaseUncheckedException) e).getErrorTexts(); + + List errors = errorTexts.parallelStream() + .map(errMsg -> new ErrorDTO(errorCodes.get(errorTexts.indexOf(errMsg)), errMsg)).distinct() + .collect(Collectors.toList()); + + response.setErrors(errors); + } + + response.setResponsetime(DateUtils.getUTCCurrentDateTimeString("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")); + response.setVersion("1.0"); + response.setResponse(null); + return response; + } else { + ManualVerificationBioDemoResponseDTO response = new ManualVerificationBioDemoResponseDTO(); + Throwable e = ex; + + if (Objects.isNull(response.getId())) { + response.setId(id); + } + if (e instanceof BaseCheckedException) { + List errorCodes = ((BaseCheckedException) e).getCodes(); + List errorTexts = ((BaseCheckedException) e).getErrorTexts(); + List errors = errorTexts.parallelStream() + .map(errMsg -> new ErrorDTO(errorCodes.get(errorTexts.indexOf(errMsg)), errMsg)).distinct() + .collect(Collectors.toList()); + response.setErrors(errors); + } + if (e instanceof BaseUncheckedException) { + List errorCodes = ((BaseUncheckedException) e).getCodes(); + List errorTexts = ((BaseUncheckedException) e).getErrorTexts(); + + List errors = errorTexts.parallelStream() + .map(errMsg -> new ErrorDTO(errorCodes.get(errorTexts.indexOf(errMsg)), errMsg)).distinct() + .collect(Collectors.toList()); + + response.setErrors(errors); + } + + response.setResponsetime(DateUtils.getUTCCurrentDateTimeString(env.getProperty(DATETIME_PATTERN))); + response.setVersion(env.getProperty(APPLICATION_VERSION)); + response.setResponse(null); + return response; + } + + } + + /** + * Handler. + * + * @param exe + * the exe + * @return the string + */ + public BaseRestResponseDTO handler(Throwable exe) { + if (exe instanceof InvalidFieldsException) + return invalidFiledException((InvalidFieldsException) exe); + if (exe instanceof InvalidUpdateException) + return invalidUpdateException((InvalidUpdateException) exe); + if (exe instanceof NoRecordAssignedException) + return noRecordAssignedExceptionHandler((NoRecordAssignedException) exe); + if (exe instanceof UserIDNotPresentException) + return UserIDNotPresentException((UserIDNotPresentException) exe); + if (exe instanceof PacketNotFoundException) + return packetNotFoundExceptionHandler((PacketNotFoundException) exe); + if (exe instanceof InvalidFileNameException) + return invalidFileNameExceptionHandler((InvalidFileNameException) exe); + if (exe instanceof ManualVerificationAppException) + return invalidManualVerificationAppException((ManualVerificationAppException) exe); + if (exe instanceof IllegalArgumentException) + return invalidIllegalArgumentException((IllegalArgumentException) exe); + if (exe instanceof DecodeException) + return decodeExceptionHandler((DecodeException) exe); + if (exe instanceof MatchTypeNotFoundException) + return matchTypeNotFoundExceptionHandler((MatchTypeNotFoundException) exe); + if (exe instanceof FSAdapterException) { + return fileNotFoundInFileStoreExceptionHandler((FSAdapterException) exe); + } + if (exe instanceof InvalidTokenException) { + return invalidTokenExceptionHandler((InvalidTokenException) exe); + } else + return unknownExceptionHandler((Exception) exe); + } + } \ No newline at end of file diff --git a/registration-processor/core-processor/registration-processor-verification-stage/src/main/java/io/mosip/registration/processor/verification/util/ManualVerificationRequestValidator.java b/registration-processor/core-processor/registration-processor-verification-stage/src/main/java/io/mosip/registration/processor/verification/util/ManualVerificationRequestValidator.java index 6ea208596c3..7cdd9df713a 100644 --- a/registration-processor/core-processor/registration-processor-verification-stage/src/main/java/io/mosip/registration/processor/verification/util/ManualVerificationRequestValidator.java +++ b/registration-processor/core-processor/registration-processor-verification-stage/src/main/java/io/mosip/registration/processor/verification/util/ManualVerificationRequestValidator.java @@ -7,8 +7,6 @@ import java.util.Objects; import java.util.TimeZone; -import io.mosip.registration.processor.verification.exception.ManualVerificationAppException; -import io.mosip.registration.processor.verification.exception.ManualVerificationValidationException; import org.joda.time.DateTime; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; @@ -18,6 +16,8 @@ import io.mosip.kernel.core.exception.ExceptionUtils; import io.mosip.kernel.core.logger.spi.Logger; import io.mosip.kernel.core.util.DateUtils; +import io.mosip.registration.processor.core.exception.ManualVerificationAppException; +import io.mosip.registration.processor.core.exception.ManualVerificationValidationException; import io.mosip.registration.processor.core.exception.util.PlatformErrorMessages; import io.mosip.registration.processor.core.logger.RegProcessorLogger; import io.mosip.registration.processor.verification.constants.VerificationConstants; diff --git a/registration-processor/post-processor/registration-processor-message-sender-stage/src/main/java/io/mosip/registration/processor/message/sender/stage/MessageSenderStage.java b/registration-processor/post-processor/registration-processor-message-sender-stage/src/main/java/io/mosip/registration/processor/message/sender/stage/MessageSenderStage.java index 103659aca51..17eea07e34f 100644 --- a/registration-processor/post-processor/registration-processor-message-sender-stage/src/main/java/io/mosip/registration/processor/message/sender/stage/MessageSenderStage.java +++ b/registration-processor/post-processor/registration-processor-message-sender-stage/src/main/java/io/mosip/registration/processor/message/sender/stage/MessageSenderStage.java @@ -40,6 +40,7 @@ import io.mosip.registration.processor.core.code.RegistrationTransactionTypeCode; import io.mosip.registration.processor.core.constant.IdType; import io.mosip.registration.processor.core.constant.LoggerFileConstant; +import io.mosip.registration.processor.core.constant.MessageSenderConstant; import io.mosip.registration.processor.core.exception.ApisResourceAccessException; import io.mosip.registration.processor.core.exception.util.PlatformErrorMessages; import io.mosip.registration.processor.core.exception.util.PlatformSuccessMessages; @@ -53,7 +54,6 @@ 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.message.sender.constants.MessageSenderConstant; import io.mosip.registration.processor.message.sender.constants.NotificationTypeEnum; import io.mosip.registration.processor.message.sender.dto.MessageSenderDto; import io.mosip.registration.processor.message.sender.exception.ConfigurationNotFoundException; diff --git a/registration-processor/pre-processor/registration-processor-packet-uploader-stage/src/main/java/io/mosip/registration/processor/packet/uploader/constants/PacketDecryptionFailureExceptionConstant.java b/registration-processor/pre-processor/registration-processor-packet-uploader-stage/src/main/java/io/mosip/registration/processor/packet/uploader/constants/PacketDecryptionFailureExceptionConstant.java deleted file mode 100644 index 6cd9bb92da7..00000000000 --- a/registration-processor/pre-processor/registration-processor-packet-uploader-stage/src/main/java/io/mosip/registration/processor/packet/uploader/constants/PacketDecryptionFailureExceptionConstant.java +++ /dev/null @@ -1,45 +0,0 @@ -package io.mosip.registration.processor.packet.uploader.constants; - -/** - * The Enum PacketDecryptionFailureExceptionConstant. - */ -public enum PacketDecryptionFailureExceptionConstant { - - /** The mosip packet decryption failure error code. */ - MOSIP_PACKET_DECRYPTION_FAILURE_ERROR_CODE("RPR-PKD-004", "The Decryption for the Packet has failed"); - - /** The error code. */ - public final String errorCode; - - /** The error message. */ - public final String errorMessage; - - /** - * Instantiates a new packet decryption failure exception constant. - * - * @param string1 the string 1 - * @param string2 the string 2 - */ - PacketDecryptionFailureExceptionConstant(String string1,String string2) { - this.errorCode = string1; - this.errorMessage = string2; - } - - /** - * Gets the error code. - * - * @return the error code - */ - public String getErrorCode() { - return errorCode; - } - - /** - * Gets the error message. - * - * @return the error message - */ - public String getErrorMessage() { - return errorMessage; - } -} diff --git a/registration-processor/pre-processor/registration-processor-packet-uploader-stage/src/main/java/io/mosip/registration/processor/packet/uploader/exception/PacketReceiverAppException.java b/registration-processor/pre-processor/registration-processor-packet-uploader-stage/src/main/java/io/mosip/registration/processor/packet/uploader/exception/PacketReceiverAppException.java deleted file mode 100644 index 10f4bf4bb28..00000000000 --- a/registration-processor/pre-processor/registration-processor-packet-uploader-stage/src/main/java/io/mosip/registration/processor/packet/uploader/exception/PacketReceiverAppException.java +++ /dev/null @@ -1,128 +0,0 @@ -package io.mosip.registration.processor.packet.uploader.exception; - -import io.mosip.kernel.core.exception.BaseUncheckedException; -import io.mosip.registration.processor.core.exception.util.PlatformErrorMessages; - -/** - * The Class PacketReceiverAppException. - * - * @author Rishabh Keshari - */ -public class PacketReceiverAppException extends BaseUncheckedException { - - /** The Constant serialVersionUID. */ - private static final long serialVersionUID = 6748760277721155095L; - - /** The id. */ - private String id; - - /** - * Gets the id. - * - * @return the id - */ - public String getId() { - return id; - } - - /** - * Instantiates a new id repo app exception. - */ - public PacketReceiverAppException() { - super(); - } - - /** - * Instantiates a new id repo app exception. - * - * @param errorCode - * the error code - * @param errorMessage - * the error message - */ - public PacketReceiverAppException(String errorCode, String errorMessage) { - super(errorCode, errorMessage); - } - - /** - * Instantiates a new id repo app exception. - * - * @param errorCode - * the error code - * @param errorMessage - * the error message - * @param rootCause - * the root cause - */ - public PacketReceiverAppException(String errorCode, String errorMessage, Throwable rootCause) { - super(errorCode, errorMessage, rootCause); - } - - /** - * Instantiates a new id repo app exception. - * - * @param errorCode - * the error code - * @param errorMessage - * the error message - * @param rootCause - * the root cause - * @param id - * the id - */ - public PacketReceiverAppException(String errorCode, String errorMessage, Throwable rootCause, String id) { - super(errorCode, errorMessage, rootCause); - this.id = id; - } - - /** - * Instantiates a new id repo app exception. - * - * @param exceptionConstant - * the exception constant - */ - public PacketReceiverAppException(PlatformErrorMessages exceptionConstant) { - this(exceptionConstant.getCode(), exceptionConstant.getMessage()); - } - - /** - * Instantiates a new id repo app exception. - * - * @param exceptionConstant - * the exception constant - * @param rootCause - * the root cause - */ - public PacketReceiverAppException(PlatformErrorMessages exceptionConstant, Throwable rootCause) { - this(exceptionConstant.getCode(), exceptionConstant.getMessage(), rootCause); - } - - /** - * Instantiates a new id repo app exception. - * - * @param exceptionConstant - * the exception constant - * @param id - * the id - */ - public PacketReceiverAppException(PlatformErrorMessages exceptionConstant, String id) { - this(exceptionConstant.getCode(), exceptionConstant.getMessage()); - this.id = id; - } - - /** - * Instantiates a new id repo app exception. - * - * @param exceptionConstant - * the exception constant - * @param rootCause - * the root cause - * @param id - * the id - */ - public PacketReceiverAppException(PlatformErrorMessages exceptionConstant, Throwable rootCause, String id) { - this(exceptionConstant.getCode(), exceptionConstant.getMessage(), rootCause); - this.id = id; - } - -} diff --git a/registration-processor/post-processor/registration-processor-message-sender-stage/src/main/java/io/mosip/registration/processor/message/sender/constants/MessageSenderConstant.java b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/constant/MessageSenderConstant.java similarity index 93% rename from registration-processor/post-processor/registration-processor-message-sender-stage/src/main/java/io/mosip/registration/processor/message/sender/constants/MessageSenderConstant.java rename to registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/constant/MessageSenderConstant.java index 66adb14f8cd..1f096312b50 100644 --- a/registration-processor/post-processor/registration-processor-message-sender-stage/src/main/java/io/mosip/registration/processor/message/sender/constants/MessageSenderConstant.java +++ b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/constant/MessageSenderConstant.java @@ -1,25 +1,25 @@ -package io.mosip.registration.processor.message.sender.constants; - -public class MessageSenderConstant { - /** - * Private Constructor for this class - */ - private MessageSenderConstant() { - - } - - - public static final String MESSAGE_SENDER_FAILED ="Notification failed for registrationId "; - public static final String MESSAGE_SENDER_NOTIF_SUCC ="Notification sent successfully for registrationId "; - public static final String REFERENCE_TYPE_ID ="updated registration record"; - public static final String LATEST_TRANSACTION_TYPE_CODE ="updated registration status record"; - public static final String MESAGE_SENDER_EPTN_MISSING ="Email/phone/template/notification type is missing for registrationId " ; - public static final String MESAGE_SENDER_TEMP_MISSING ="Template not found for notification with registrationId " ; - public static final String MESAGE_SENDER_PACKET_STORE ="The Packet store set by the System is not accessible"; - public static final String MESAGE_SENDER_INTERNAL_ERROR ="Internal error occurred while processing registrationId "; - public static final String MESSAGE_SENDER_SMS_FAILED ="SMS failed for registrationId "; - public static final String MESSAGE_SENDER_EMAIL_FAILED ="Email failed for registrationId "; - - - -} +package io.mosip.registration.processor.core.constant; + +public class MessageSenderConstant { + /** + * Private Constructor for this class + */ + private MessageSenderConstant() { + + } + + + public static final String MESSAGE_SENDER_FAILED ="Notification failed for registrationId "; + public static final String MESSAGE_SENDER_NOTIF_SUCC ="Notification sent successfully for registrationId "; + public static final String REFERENCE_TYPE_ID ="updated registration record"; + public static final String LATEST_TRANSACTION_TYPE_CODE ="updated registration status record"; + public static final String MESAGE_SENDER_EPTN_MISSING ="Email/phone/template/notification type is missing for registrationId " ; + public static final String MESAGE_SENDER_TEMP_MISSING ="Template not found for notification with registrationId " ; + public static final String MESAGE_SENDER_PACKET_STORE ="The Packet store set by the System is not accessible"; + public static final String MESAGE_SENDER_INTERNAL_ERROR ="Internal error occurred while processing registrationId "; + public static final String MESSAGE_SENDER_SMS_FAILED ="SMS failed for registrationId "; + public static final String MESSAGE_SENDER_EMAIL_FAILED ="Email failed for registrationId "; + + + +} diff --git a/registration-processor/registration-processor-packet-manager/src/main/java/io/mosip/registration/processor/packet/manager/exception/PacketDecryptionFailureExceptionConstant.java b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/constant/PacketDecryptionFailureExceptionConstant.java similarity index 90% rename from registration-processor/registration-processor-packet-manager/src/main/java/io/mosip/registration/processor/packet/manager/exception/PacketDecryptionFailureExceptionConstant.java rename to registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/constant/PacketDecryptionFailureExceptionConstant.java index 6d4b9dd1823..2ad52766b05 100644 --- a/registration-processor/registration-processor-packet-manager/src/main/java/io/mosip/registration/processor/packet/manager/exception/PacketDecryptionFailureExceptionConstant.java +++ b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/constant/PacketDecryptionFailureExceptionConstant.java @@ -1,45 +1,45 @@ -package io.mosip.registration.processor.packet.manager.exception; - -/** - * The Enum PacketDecryptionFailureExceptionConstant. - */ -public enum PacketDecryptionFailureExceptionConstant { - - /** The mosip packet decryption failure error code. */ - MOSIP_PACKET_DECRYPTION_FAILURE_ERROR_CODE("RPR-PKD-004", "The Decryption for the Packet has failed"); - - /** The error code. */ - public final String errorCode; - - /** The error message. */ - public final String errorMessage; - - /** - * Instantiates a new packet decryption failure exception constant. - * - * @param string1 the string 1 - * @param string2 the string 2 - */ - PacketDecryptionFailureExceptionConstant(String string1,String string2) { - this.errorCode = string1; - this.errorMessage = string2; - } - - /** - * Gets the error code. - * - * @return the error code - */ - public String getErrorCode() { - return errorCode; - } - - /** - * Gets the error message. - * - * @return the error message - */ - public String getErrorMessage() { - return errorMessage; - } -} +package io.mosip.registration.processor.core.constant; + +/** + * The Enum PacketDecryptionFailureExceptionConstant. + */ +public enum PacketDecryptionFailureExceptionConstant { + + /** The mosip packet decryption failure error code. */ + MOSIP_PACKET_DECRYPTION_FAILURE_ERROR_CODE("RPR-PKD-004", "The Decryption for the Packet has failed"); + + /** The error code. */ + public final String errorCode; + + /** The error message. */ + public final String errorMessage; + + /** + * Instantiates a new packet decryption failure exception constant. + * + * @param string1 the string 1 + * @param string2 the string 2 + */ + PacketDecryptionFailureExceptionConstant(String string1,String string2) { + this.errorCode = string1; + this.errorMessage = string2; + } + + /** + * Gets the error code. + * + * @return the error code + */ + public String getErrorCode() { + return errorCode; + } + + /** + * Gets the error message. + * + * @return the error message + */ + public String getErrorMessage() { + return errorMessage; + } +} diff --git a/registration-processor/core-processor/registration-processor-manual-adjudication-stage/src/main/java/io/mosip/registration/processor/adjudication/exception/ManualVerificationAppException.java b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/exception/ManualVerificationAppException.java similarity index 94% rename from registration-processor/core-processor/registration-processor-manual-adjudication-stage/src/main/java/io/mosip/registration/processor/adjudication/exception/ManualVerificationAppException.java rename to registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/exception/ManualVerificationAppException.java index 186e309dc8f..512b74ef803 100644 --- a/registration-processor/core-processor/registration-processor-manual-adjudication-stage/src/main/java/io/mosip/registration/processor/adjudication/exception/ManualVerificationAppException.java +++ b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/exception/ManualVerificationAppException.java @@ -1,110 +1,110 @@ -package io.mosip.registration.processor.adjudication.exception; - -import io.mosip.kernel.core.exception.BaseUncheckedException; -import io.mosip.registration.processor.core.exception.util.PlatformErrorMessages; - -/** - * The Class ManualVerificationAppException. - * @author Rishabh Keshari - */ -public class ManualVerificationAppException extends BaseUncheckedException { - - /** The Constant serialVersionUID. */ - private static final long serialVersionUID = 6748760277721155095L; - - /** The id. */ - private String id; - - /** - * Gets the id. - * - * @return the id - */ - public String getId() { - return id; - } - - /** - * Instantiates a new id repo app exception. - */ - public ManualVerificationAppException() { - super(); - } - - /** - * Instantiates a new id repo app exception. - * - * @param errorCode the error code - * @param errorMessage the error message - */ - public ManualVerificationAppException(String errorCode, String errorMessage) { - super(errorCode, errorMessage); - } - - /** - * Instantiates a new id repo app exception. - * - * @param errorCode the error code - * @param errorMessage the error message - * @param rootCause the root cause - */ - public ManualVerificationAppException(String errorCode, String errorMessage, Throwable rootCause) { - super(errorCode, errorMessage, rootCause); - } - - /** - * Instantiates a new id repo app exception. - * - * @param errorCode the error code - * @param errorMessage the error message - * @param rootCause the root cause - * @param id the id - */ - public ManualVerificationAppException(String errorCode, String errorMessage, Throwable rootCause, String id) { - super(errorCode, errorMessage, rootCause); - this.id = id; - } - - /** - * Instantiates a new id repo app exception. - * - * @param exceptionConstant the exception constant - */ - public ManualVerificationAppException(PlatformErrorMessages exceptionConstant) { - this(exceptionConstant.getCode(), exceptionConstant.getMessage()); - } - - /** - * Instantiates a new id repo app exception. - * - * @param exceptionConstant the exception constant - * @param rootCause the root cause - */ - public ManualVerificationAppException(PlatformErrorMessages exceptionConstant, Throwable rootCause) { - this(exceptionConstant.getCode(), exceptionConstant.getMessage(), rootCause); - } - - /** - * Instantiates a new id repo app exception. - * - * @param exceptionConstant the exception constant - * @param id the id - */ - public ManualVerificationAppException(PlatformErrorMessages exceptionConstant, String id) { - this(exceptionConstant.getCode(), exceptionConstant.getMessage()); - this.id = id; - } - - /** - * Instantiates a new id repo app exception. - * - * @param exceptionConstant the exception constant - * @param rootCause the root cause - * @param id the id - */ - public ManualVerificationAppException(PlatformErrorMessages exceptionConstant, Throwable rootCause, String id) { - this(exceptionConstant.getCode(), exceptionConstant.getMessage(), rootCause); - this.id = id; - } - -} +package io.mosip.registration.processor.core.exception; + +import io.mosip.kernel.core.exception.BaseUncheckedException; +import io.mosip.registration.processor.core.exception.util.PlatformErrorMessages; + +/** + * The Class ManualVerificationAppException. + * @author Rishabh Keshari + */ +public class ManualVerificationAppException extends BaseUncheckedException { + + /** The Constant serialVersionUID. */ + private static final long serialVersionUID = 6748760277721155095L; + + /** The id. */ + private String id; + + /** + * Gets the id. + * + * @return the id + */ + public String getId() { + return id; + } + + /** + * Instantiates a new id repo app exception. + */ + public ManualVerificationAppException() { + super(); + } + + /** + * Instantiates a new id repo app exception. + * + * @param errorCode the error code + * @param errorMessage the error message + */ + public ManualVerificationAppException(String errorCode, String errorMessage) { + super(errorCode, errorMessage); + } + + /** + * Instantiates a new id repo app exception. + * + * @param errorCode the error code + * @param errorMessage the error message + * @param rootCause the root cause + */ + public ManualVerificationAppException(String errorCode, String errorMessage, Throwable rootCause) { + super(errorCode, errorMessage, rootCause); + } + + /** + * Instantiates a new id repo app exception. + * + * @param errorCode the error code + * @param errorMessage the error message + * @param rootCause the root cause + * @param id the id + */ + public ManualVerificationAppException(String errorCode, String errorMessage, Throwable rootCause, String id) { + super(errorCode, errorMessage, rootCause); + this.id = id; + } + + /** + * Instantiates a new id repo app exception. + * + * @param exceptionConstant the exception constant + */ + public ManualVerificationAppException(PlatformErrorMessages exceptionConstant) { + this(exceptionConstant.getCode(), exceptionConstant.getMessage()); + } + + /** + * Instantiates a new id repo app exception. + * + * @param exceptionConstant the exception constant + * @param rootCause the root cause + */ + public ManualVerificationAppException(PlatformErrorMessages exceptionConstant, Throwable rootCause) { + this(exceptionConstant.getCode(), exceptionConstant.getMessage(), rootCause); + } + + /** + * Instantiates a new id repo app exception. + * + * @param exceptionConstant the exception constant + * @param id the id + */ + public ManualVerificationAppException(PlatformErrorMessages exceptionConstant, String id) { + this(exceptionConstant.getCode(), exceptionConstant.getMessage()); + this.id = id; + } + + /** + * Instantiates a new id repo app exception. + * + * @param exceptionConstant the exception constant + * @param rootCause the root cause + * @param id the id + */ + public ManualVerificationAppException(PlatformErrorMessages exceptionConstant, Throwable rootCause, String id) { + this(exceptionConstant.getCode(), exceptionConstant.getMessage(), rootCause); + this.id = id; + } + +} diff --git a/registration-processor/core-processor/registration-processor-manual-adjudication-stage/src/main/java/io/mosip/registration/processor/adjudication/exception/ManualVerificationValidationException.java b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/exception/ManualVerificationValidationException.java similarity index 89% rename from registration-processor/core-processor/registration-processor-manual-adjudication-stage/src/main/java/io/mosip/registration/processor/adjudication/exception/ManualVerificationValidationException.java rename to registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/exception/ManualVerificationValidationException.java index 72ca2611ae2..1861976b449 100644 --- a/registration-processor/core-processor/registration-processor-manual-adjudication-stage/src/main/java/io/mosip/registration/processor/adjudication/exception/ManualVerificationValidationException.java +++ b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/exception/ManualVerificationValidationException.java @@ -1,63 +1,64 @@ -package io.mosip.registration.processor.adjudication.exception; - -import io.mosip.registration.processor.core.exception.util.PlatformErrorMessages; - -/** - * The Class ManualVerificationValidationException. - * @author Rishabh Keshari - */ -public class ManualVerificationValidationException extends ManualVerificationAppException { - - - - /** The Constant serialVersionUID. */ - private static final long serialVersionUID = -2685586188884469940L; - - /** - * Instantiates a new id repo data validation exception. - */ - public ManualVerificationValidationException() { - super(); - } - - /** - * Instantiates a new id repo data validation exception. - * - * @param errorCode the error code - * @param errorMessage the error message - */ - public ManualVerificationValidationException(String errorCode, String errorMessage) { - super(errorCode, errorMessage); - } - - /** - * Instantiates a new id repo data validation exception. - * - * @param errorCode the error code - * @param errorMessage the error message - * @param rootCause the root cause - */ - public ManualVerificationValidationException(String errorCode, String errorMessage, Throwable rootCause) { - super(errorCode, errorMessage, rootCause); - } - - /** - * Instantiates a new id repo data validation exception. - * - * @param exceptionConstant the exception constant - */ - public ManualVerificationValidationException(PlatformErrorMessages exceptionConstant) { - super(exceptionConstant); - } - - /** - * Instantiates a new id repo data validation exception. - * - * @param exceptionConstant the exception constant - * @param rootCause the root cause - */ - public ManualVerificationValidationException(PlatformErrorMessages exceptionConstant, Throwable rootCause) { - super(exceptionConstant, rootCause); - } - -} +package io.mosip.registration.processor.core.exception; + +import io.mosip.registration.processor.core.exception.ManualVerificationAppException; +import io.mosip.registration.processor.core.exception.util.PlatformErrorMessages; + +/** + * The Class ManualVerificationValidationException. + * @author Rishabh Keshari + */ +public class ManualVerificationValidationException extends ManualVerificationAppException { + + + + /** The Constant serialVersionUID. */ + private static final long serialVersionUID = -2685586188884469940L; + + /** + * Instantiates a new id repo data validation exception. + */ + public ManualVerificationValidationException() { + super(); + } + + /** + * Instantiates a new id repo data validation exception. + * + * @param errorCode the error code + * @param errorMessage the error message + */ + public ManualVerificationValidationException(String errorCode, String errorMessage) { + super(errorCode, errorMessage); + } + + /** + * Instantiates a new id repo data validation exception. + * + * @param errorCode the error code + * @param errorMessage the error message + * @param rootCause the root cause + */ + public ManualVerificationValidationException(String errorCode, String errorMessage, Throwable rootCause) { + super(errorCode, errorMessage, rootCause); + } + + /** + * Instantiates a new id repo data validation exception. + * + * @param exceptionConstant the exception constant + */ + public ManualVerificationValidationException(PlatformErrorMessages exceptionConstant) { + super(exceptionConstant); + } + + /** + * Instantiates a new id repo data validation exception. + * + * @param exceptionConstant the exception constant + * @param rootCause the root cause + */ + public ManualVerificationValidationException(PlatformErrorMessages exceptionConstant, Throwable rootCause) { + super(exceptionConstant, rootCause); + } + +} diff --git a/registration-processor/registration-processor-notification-service/src/main/java/io/mosip/registration/processor/notification/constants/MessageSenderConstant.java b/registration-processor/registration-processor-notification-service/src/main/java/io/mosip/registration/processor/notification/constants/MessageSenderConstant.java deleted file mode 100644 index 00898259a6f..00000000000 --- a/registration-processor/registration-processor-notification-service/src/main/java/io/mosip/registration/processor/notification/constants/MessageSenderConstant.java +++ /dev/null @@ -1,25 +0,0 @@ -package io.mosip.registration.processor.notification.constants; - -public class MessageSenderConstant { - /** - * Private Constructor for this class - */ - private MessageSenderConstant() { - - } - - - public static final String MESSAGE_SENDER_FAILED ="Notification failed for registrationId "; - public static final String MESSAGE_SENDER_NOTIF_SUCC ="Notification sent successfully for registrationId "; - public static final String REFERENCE_TYPE_ID ="updated registration record"; - public static final String LATEST_TRANSACTION_TYPE_CODE ="updated registration status record"; - public static final String MESAGE_SENDER_EPTN_MISSING ="Email/phone/template/notification type is missing for registrationId " ; - public static final String MESAGE_SENDER_TEMP_MISSING ="Template not found for notification with registrationId " ; - public static final String MESAGE_SENDER_PACKET_STORE ="The Packet store set by the System is not accessible"; - public static final String MESAGE_SENDER_INTERNAL_ERROR ="Internal error occurred while processing registrationId "; - public static final String MESSAGE_SENDER_SMS_FAILED ="SMS failed for registrationId "; - public static final String MESSAGE_SENDER_EMAIL_FAILED ="Email failed for registrationId "; - - - -} diff --git a/registration-processor/registration-processor-packet-manager/src/main/java/io/mosip/registration/processor/packet/manager/decryptor/DecryptorImpl.java b/registration-processor/registration-processor-packet-manager/src/main/java/io/mosip/registration/processor/packet/manager/decryptor/DecryptorImpl.java index c965a9820c1..df3b2142f93 100644 --- a/registration-processor/registration-processor-packet-manager/src/main/java/io/mosip/registration/processor/packet/manager/decryptor/DecryptorImpl.java +++ b/registration-processor/registration-processor-packet-manager/src/main/java/io/mosip/registration/processor/packet/manager/decryptor/DecryptorImpl.java @@ -1,209 +1,209 @@ -package io.mosip.registration.processor.packet.manager.decryptor; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.time.LocalDateTime; -import java.time.format.DateTimeFormatter; -import java.time.format.DateTimeParseException; -import java.util.Arrays; - -import io.mosip.kernel.core.http.RequestWrapper; -import io.mosip.registration.processor.packet.manager.constant.CryptomanagerConstant; -import org.apache.commons.io.IOUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.core.env.Environment; -import org.springframework.stereotype.Component; -import org.springframework.web.client.HttpClientErrorException; -import org.springframework.web.client.HttpServerErrorException; - -import io.mosip.kernel.core.exception.ServiceError; -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.registration.processor.core.code.ApiName; -import io.mosip.registration.processor.core.code.EventId; -import io.mosip.registration.processor.core.code.EventName; -import io.mosip.registration.processor.core.code.EventType; -import io.mosip.registration.processor.core.code.ModuleName; -import io.mosip.registration.processor.core.constant.LoggerFileConstant; -import io.mosip.registration.processor.core.exception.ApisResourceAccessException; -import io.mosip.registration.processor.core.exception.PacketDecryptionFailureException; -import io.mosip.registration.processor.core.exception.util.PlatformErrorMessages; -import io.mosip.registration.processor.core.exception.util.PlatformSuccessMessages; -import io.mosip.registration.processor.core.logger.LogDescription; -import io.mosip.registration.processor.core.logger.RegProcessorLogger; -import io.mosip.registration.processor.core.spi.restclient.RegistrationProcessorRestClientService; -import io.mosip.registration.processor.packet.manager.dto.CryptomanagerRequestDto; -import io.mosip.registration.processor.packet.manager.dto.CryptomanagerResponseDto; -import io.mosip.registration.processor.packet.manager.exception.PacketDecryptionFailureExceptionConstant; -import io.mosip.registration.processor.rest.client.audit.builder.AuditLogRequestBuilder; - -/** - * Decryptor class for packet decryption. - * - * @author Girish Yarru - * @author Abhishek Kumar - * @since 1.0.0 - */ -@Component -public class DecryptorImpl implements Decryptor { - private static Logger regProcLogger = RegProcessorLogger.getLogger(DecryptorImpl.class); - - @Value("${registration.processor.application.id}") - private String applicationId; - - @Value("${crypto.PrependThumbprint.enable:true}") - private boolean isPrependThumbprintEnabled; - - @Autowired - private RegistrationProcessorRestClientService restClientService; - - @Autowired - private AuditLogRequestBuilder auditLogRequestBuilder; - - @Autowired - private Environment env; - - private static final String DECRYPT_SERVICE_ID = "mosip.registration.processor.crypto.decrypt.id"; - private static final String REG_PROC_APPLICATION_VERSION = "mosip.registration.processor.application.version"; - private static final String DATETIME_PATTERN = "mosip.registration.processor.datetime.pattern"; - - private static final String DECRYPTION_SUCCESS = "Decryption success"; - private static final String DECRYPTION_FAILURE = "Virus scan decryption failed for registrationId "; - private static final String IO_EXCEPTION = "Exception while reading packet inputStream"; - private static final String DATE_TIME_EXCEPTION = "Error while parsing packet timestamp"; - - /* - * (non-Javadoc) - * - * @see - * io.mosip.registration.processor.core.spi.decryptor.Decryptor#decrypt(java.io. - * InputStream, java.lang.String) - */ - @Override - public InputStream decrypt(String id, String refId, InputStream packetStream) - throws PacketDecryptionFailureException, ApisResourceAccessException { - InputStream outstream = null; - boolean isTransactionSuccessful = false; - LogDescription description = new LogDescription(); - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - id, "Decryptor::decrypt()::entry"); - try { - byte[] packet = IOUtils.toByteArray(packetStream); - CryptomanagerRequestDto cryptomanagerRequestDto = new CryptomanagerRequestDto(); - cryptomanagerRequestDto.setPrependThumbprint(isPrependThumbprintEnabled); - io.mosip.kernel.core.http.RequestWrapper request = new RequestWrapper<>(); - cryptomanagerRequestDto.setApplicationId(applicationId); - cryptomanagerRequestDto.setReferenceId(refId); - regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), - LoggerFileConstant.REGISTRATIONID.toString(), id, - "Size = " + packet.length); - byte[] nonce = Arrays.copyOfRange(packet, 0, CryptomanagerConstant.GCM_NONCE_LENGTH); - byte[] aad = Arrays.copyOfRange(packet, CryptomanagerConstant.GCM_NONCE_LENGTH, - CryptomanagerConstant.GCM_NONCE_LENGTH + CryptomanagerConstant.GCM_AAD_LENGTH); - byte[] encryptedData = Arrays.copyOfRange(packet, CryptomanagerConstant.GCM_NONCE_LENGTH + CryptomanagerConstant.GCM_AAD_LENGTH, - packet.length); - cryptomanagerRequestDto.setAad(CryptoUtil.encodeToURLSafeBase64(aad)); - cryptomanagerRequestDto.setSalt(CryptoUtil.encodeToURLSafeBase64(nonce)); - cryptomanagerRequestDto.setData(CryptoUtil.encodeToURLSafeBase64(encryptedData)); - cryptomanagerRequestDto.setTimeStamp(DateUtils.getUTCCurrentDateTime()); - - request.setId(env.getProperty(DECRYPT_SERVICE_ID)); - request.setMetadata(null); - request.setRequest(cryptomanagerRequestDto); - DateTimeFormatter format = DateTimeFormatter.ofPattern(env.getProperty(DATETIME_PATTERN)); - LocalDateTime localdatetime = LocalDateTime - .parse(DateUtils.getUTCCurrentDateTimeString(env.getProperty(DATETIME_PATTERN)), format); - request.setRequesttime(localdatetime); - request.setVersion(env.getProperty(REG_PROC_APPLICATION_VERSION)); - CryptomanagerResponseDto response; - response = (CryptomanagerResponseDto) restClientService.postApi(ApiName.CRYPTOMANAGERDECRYPT, "", "", - request, CryptomanagerResponseDto.class); - if (response.getErrors() != null && !response.getErrors().isEmpty()) { - ServiceError error = response.getErrors().get(0); - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), - LoggerFileConstant.REGISTRATIONID.toString(), id, DECRYPTION_FAILURE); - description.setMessage(PlatformErrorMessages.RPR_PDS_PACKET_DECRYPTION_FAILURE.getMessage()); - description.setCode(PlatformErrorMessages.RPR_PDS_PACKET_DECRYPTION_FAILURE.getCode()); - throw new PacketDecryptionFailureException(error.getErrorCode(), error.getMessage()); - } - byte[] decryptedPacket =null; - try { - decryptedPacket= CryptoUtil.decodeURLSafeBase64(response.getResponse().getData()); - } catch (IllegalArgumentException exception) { - decryptedPacket= CryptoUtil.decodePlainBase64(response.getResponse().getData()); - } - outstream = new ByteArrayInputStream(decryptedPacket); - isTransactionSuccessful = true; - description.setMessage(PlatformSuccessMessages.RPR_DECRYPTION_SUCCESS.getMessage()); - description.setCode(PlatformSuccessMessages.RPR_DECRYPTION_SUCCESS.getCode()); - - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - id, "Decryptor::decrypt()::exit"); - regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - id, description.getMessage()); - } catch (IOException e) { - description.setMessage(PlatformErrorMessages.RPR_PDS_IO_EXCEPTION.getMessage()); - description.setCode(PlatformErrorMessages.RPR_PDS_IO_EXCEPTION.getCode()); - - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - id, description.getMessage()); - throw new PacketDecryptionFailureException( - PacketDecryptionFailureExceptionConstant.MOSIP_PACKET_DECRYPTION_FAILURE_ERROR_CODE.getErrorCode(), - IO_EXCEPTION, e); - } catch (DateTimeParseException e) { - description.setMessage(PlatformErrorMessages.RPR_PDS_DATE_TIME_EXCEPTION.getMessage()); - description.setCode(PlatformErrorMessages.RPR_PDS_DATE_TIME_EXCEPTION.getCode()); - - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - id, description.getMessage()); - throw new PacketDecryptionFailureException( - PacketDecryptionFailureExceptionConstant.MOSIP_PACKET_DECRYPTION_FAILURE_ERROR_CODE.getErrorCode(), - DATE_TIME_EXCEPTION); - } catch (ApisResourceAccessException e) { - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - id, "Internal Error occurred "); - if (e.getCause() instanceof HttpClientErrorException) { - HttpClientErrorException httpClientException = (HttpClientErrorException) e.getCause(); - - description.setMessage(PlatformErrorMessages.RPR_PDS_PACKET_DECRYPTION_FAILURE.getMessage() - + httpClientException.getResponseBodyAsString()); - description.setCode(PlatformErrorMessages.RPR_PDS_PACKET_DECRYPTION_FAILURE.getCode()); - - throw new PacketDecryptionFailureException( - PacketDecryptionFailureExceptionConstant.MOSIP_PACKET_DECRYPTION_FAILURE_ERROR_CODE - .getErrorCode(), - httpClientException.getResponseBodyAsString()); - } else { - description.setMessage( - PlatformErrorMessages.RPR_PDS_PACKET_DECRYPTION_FAILURE.getMessage() + e.getMessage()); - description.setCode(PlatformErrorMessages.RPR_PDS_PACKET_DECRYPTION_FAILURE.getCode()); - - throw e; - } - - } finally { - String eventId = ""; - String eventName = ""; - String eventType = ""; - eventId = isTransactionSuccessful ? EventId.RPR_402.toString() : EventId.RPR_405.toString(); - eventName = eventId.equalsIgnoreCase(EventId.RPR_402.toString()) ? EventName.UPDATE.toString() - : EventName.EXCEPTION.toString(); - eventType = eventId.equalsIgnoreCase(EventId.RPR_402.toString()) ? EventType.BUSINESS.toString() - : EventType.SYSTEM.toString(); - - /** Module-Id can be Both Success/Error code */ - String moduleId = isTransactionSuccessful ? PlatformSuccessMessages.RPR_DECRYPTION_SUCCESS.getCode() - : description.getCode(); - String moduleName = ModuleName.DECRYPTOR.toString(); - auditLogRequestBuilder.createAuditRequestBuilder(description.getMessage(), eventId, eventName, eventType, - moduleId, moduleName, id); - } - regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - id, DECRYPTION_SUCCESS); - return outstream; - } - +package io.mosip.registration.processor.packet.manager.decryptor; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; +import java.util.Arrays; + +import io.mosip.kernel.core.http.RequestWrapper; +import io.mosip.registration.processor.packet.manager.constant.CryptomanagerConstant; +import org.apache.commons.io.IOUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Component; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.web.client.HttpServerErrorException; + +import io.mosip.kernel.core.exception.ServiceError; +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.registration.processor.core.code.ApiName; +import io.mosip.registration.processor.core.code.EventId; +import io.mosip.registration.processor.core.code.EventName; +import io.mosip.registration.processor.core.code.EventType; +import io.mosip.registration.processor.core.code.ModuleName; +import io.mosip.registration.processor.core.constant.LoggerFileConstant; +import io.mosip.registration.processor.core.constant.PacketDecryptionFailureExceptionConstant; +import io.mosip.registration.processor.core.exception.ApisResourceAccessException; +import io.mosip.registration.processor.core.exception.PacketDecryptionFailureException; +import io.mosip.registration.processor.core.exception.util.PlatformErrorMessages; +import io.mosip.registration.processor.core.exception.util.PlatformSuccessMessages; +import io.mosip.registration.processor.core.logger.LogDescription; +import io.mosip.registration.processor.core.logger.RegProcessorLogger; +import io.mosip.registration.processor.core.spi.restclient.RegistrationProcessorRestClientService; +import io.mosip.registration.processor.packet.manager.dto.CryptomanagerRequestDto; +import io.mosip.registration.processor.packet.manager.dto.CryptomanagerResponseDto; +import io.mosip.registration.processor.rest.client.audit.builder.AuditLogRequestBuilder; + +/** + * Decryptor class for packet decryption. + * + * @author Girish Yarru + * @author Abhishek Kumar + * @since 1.0.0 + */ +@Component +public class DecryptorImpl implements Decryptor { + private static Logger regProcLogger = RegProcessorLogger.getLogger(DecryptorImpl.class); + + @Value("${registration.processor.application.id}") + private String applicationId; + + @Value("${crypto.PrependThumbprint.enable:true}") + private boolean isPrependThumbprintEnabled; + + @Autowired + private RegistrationProcessorRestClientService restClientService; + + @Autowired + private AuditLogRequestBuilder auditLogRequestBuilder; + + @Autowired + private Environment env; + + private static final String DECRYPT_SERVICE_ID = "mosip.registration.processor.crypto.decrypt.id"; + private static final String REG_PROC_APPLICATION_VERSION = "mosip.registration.processor.application.version"; + private static final String DATETIME_PATTERN = "mosip.registration.processor.datetime.pattern"; + + private static final String DECRYPTION_SUCCESS = "Decryption success"; + private static final String DECRYPTION_FAILURE = "Virus scan decryption failed for registrationId "; + private static final String IO_EXCEPTION = "Exception while reading packet inputStream"; + private static final String DATE_TIME_EXCEPTION = "Error while parsing packet timestamp"; + + /* + * (non-Javadoc) + * + * @see + * io.mosip.registration.processor.core.spi.decryptor.Decryptor#decrypt(java.io. + * InputStream, java.lang.String) + */ + @Override + public InputStream decrypt(String id, String refId, InputStream packetStream) + throws PacketDecryptionFailureException, ApisResourceAccessException { + InputStream outstream = null; + boolean isTransactionSuccessful = false; + LogDescription description = new LogDescription(); + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + id, "Decryptor::decrypt()::entry"); + try { + byte[] packet = IOUtils.toByteArray(packetStream); + CryptomanagerRequestDto cryptomanagerRequestDto = new CryptomanagerRequestDto(); + cryptomanagerRequestDto.setPrependThumbprint(isPrependThumbprintEnabled); + io.mosip.kernel.core.http.RequestWrapper request = new RequestWrapper<>(); + cryptomanagerRequestDto.setApplicationId(applicationId); + cryptomanagerRequestDto.setReferenceId(refId); + regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString(), id, + "Size = " + packet.length); + byte[] nonce = Arrays.copyOfRange(packet, 0, CryptomanagerConstant.GCM_NONCE_LENGTH); + byte[] aad = Arrays.copyOfRange(packet, CryptomanagerConstant.GCM_NONCE_LENGTH, + CryptomanagerConstant.GCM_NONCE_LENGTH + CryptomanagerConstant.GCM_AAD_LENGTH); + byte[] encryptedData = Arrays.copyOfRange(packet, CryptomanagerConstant.GCM_NONCE_LENGTH + CryptomanagerConstant.GCM_AAD_LENGTH, + packet.length); + cryptomanagerRequestDto.setAad(CryptoUtil.encodeToURLSafeBase64(aad)); + cryptomanagerRequestDto.setSalt(CryptoUtil.encodeToURLSafeBase64(nonce)); + cryptomanagerRequestDto.setData(CryptoUtil.encodeToURLSafeBase64(encryptedData)); + cryptomanagerRequestDto.setTimeStamp(DateUtils.getUTCCurrentDateTime()); + + request.setId(env.getProperty(DECRYPT_SERVICE_ID)); + request.setMetadata(null); + request.setRequest(cryptomanagerRequestDto); + DateTimeFormatter format = DateTimeFormatter.ofPattern(env.getProperty(DATETIME_PATTERN)); + LocalDateTime localdatetime = LocalDateTime + .parse(DateUtils.getUTCCurrentDateTimeString(env.getProperty(DATETIME_PATTERN)), format); + request.setRequesttime(localdatetime); + request.setVersion(env.getProperty(REG_PROC_APPLICATION_VERSION)); + CryptomanagerResponseDto response; + response = (CryptomanagerResponseDto) restClientService.postApi(ApiName.CRYPTOMANAGERDECRYPT, "", "", + request, CryptomanagerResponseDto.class); + if (response.getErrors() != null && !response.getErrors().isEmpty()) { + ServiceError error = response.getErrors().get(0); + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString(), id, DECRYPTION_FAILURE); + description.setMessage(PlatformErrorMessages.RPR_PDS_PACKET_DECRYPTION_FAILURE.getMessage()); + description.setCode(PlatformErrorMessages.RPR_PDS_PACKET_DECRYPTION_FAILURE.getCode()); + throw new PacketDecryptionFailureException(error.getErrorCode(), error.getMessage()); + } + byte[] decryptedPacket =null; + try { + decryptedPacket= CryptoUtil.decodeURLSafeBase64(response.getResponse().getData()); + } catch (IllegalArgumentException exception) { + decryptedPacket= CryptoUtil.decodePlainBase64(response.getResponse().getData()); + } + outstream = new ByteArrayInputStream(decryptedPacket); + isTransactionSuccessful = true; + description.setMessage(PlatformSuccessMessages.RPR_DECRYPTION_SUCCESS.getMessage()); + description.setCode(PlatformSuccessMessages.RPR_DECRYPTION_SUCCESS.getCode()); + + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + id, "Decryptor::decrypt()::exit"); + regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + id, description.getMessage()); + } catch (IOException e) { + description.setMessage(PlatformErrorMessages.RPR_PDS_IO_EXCEPTION.getMessage()); + description.setCode(PlatformErrorMessages.RPR_PDS_IO_EXCEPTION.getCode()); + + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + id, description.getMessage()); + throw new PacketDecryptionFailureException( + PacketDecryptionFailureExceptionConstant.MOSIP_PACKET_DECRYPTION_FAILURE_ERROR_CODE.getErrorCode(), + IO_EXCEPTION, e); + } catch (DateTimeParseException e) { + description.setMessage(PlatformErrorMessages.RPR_PDS_DATE_TIME_EXCEPTION.getMessage()); + description.setCode(PlatformErrorMessages.RPR_PDS_DATE_TIME_EXCEPTION.getCode()); + + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + id, description.getMessage()); + throw new PacketDecryptionFailureException( + PacketDecryptionFailureExceptionConstant.MOSIP_PACKET_DECRYPTION_FAILURE_ERROR_CODE.getErrorCode(), + DATE_TIME_EXCEPTION); + } catch (ApisResourceAccessException e) { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + id, "Internal Error occurred "); + if (e.getCause() instanceof HttpClientErrorException) { + HttpClientErrorException httpClientException = (HttpClientErrorException) e.getCause(); + + description.setMessage(PlatformErrorMessages.RPR_PDS_PACKET_DECRYPTION_FAILURE.getMessage() + + httpClientException.getResponseBodyAsString()); + description.setCode(PlatformErrorMessages.RPR_PDS_PACKET_DECRYPTION_FAILURE.getCode()); + + throw new PacketDecryptionFailureException( + PacketDecryptionFailureExceptionConstant.MOSIP_PACKET_DECRYPTION_FAILURE_ERROR_CODE + .getErrorCode(), + httpClientException.getResponseBodyAsString()); + } else { + description.setMessage( + PlatformErrorMessages.RPR_PDS_PACKET_DECRYPTION_FAILURE.getMessage() + e.getMessage()); + description.setCode(PlatformErrorMessages.RPR_PDS_PACKET_DECRYPTION_FAILURE.getCode()); + + throw e; + } + + } finally { + String eventId = ""; + String eventName = ""; + String eventType = ""; + eventId = isTransactionSuccessful ? EventId.RPR_402.toString() : EventId.RPR_405.toString(); + eventName = eventId.equalsIgnoreCase(EventId.RPR_402.toString()) ? EventName.UPDATE.toString() + : EventName.EXCEPTION.toString(); + eventType = eventId.equalsIgnoreCase(EventId.RPR_402.toString()) ? EventType.BUSINESS.toString() + : EventType.SYSTEM.toString(); + + /** Module-Id can be Both Success/Error code */ + String moduleId = isTransactionSuccessful ? PlatformSuccessMessages.RPR_DECRYPTION_SUCCESS.getCode() + : description.getCode(); + String moduleName = ModuleName.DECRYPTOR.toString(); + auditLogRequestBuilder.createAuditRequestBuilder(description.getMessage(), eventId, eventName, eventType, + moduleId, moduleName, id); + } + regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + id, DECRYPTION_SUCCESS); + return outstream; + } + } \ No newline at end of file diff --git a/registration-processor/registration-processor-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/constants/PacketDecryptionFailureExceptionConstant.java b/registration-processor/registration-processor-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/constants/PacketDecryptionFailureExceptionConstant.java deleted file mode 100644 index 81416303568..00000000000 --- a/registration-processor/registration-processor-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/constants/PacketDecryptionFailureExceptionConstant.java +++ /dev/null @@ -1,45 +0,0 @@ -package io.mosip.registration.processor.status.constants; - -/** - * The Enum PacketDecryptionFailureExceptionConstant. - */ -public enum PacketDecryptionFailureExceptionConstant { - - /** The mosip packet decryption failure error code. */ - MOSIP_PACKET_DECRYPTION_FAILURE_ERROR_CODE("RPR-PKD-004", "The Decryption for the Packet has failed"); - - /** The error code. */ - public final String errorCode; - - /** The error message. */ - public final String errorMessage; - - /** - * Instantiates a new packet decryption failure exception constant. - * - * @param string1 the string 1 - * @param string2 the string 2 - */ - PacketDecryptionFailureExceptionConstant(String string1,String string2) { - this.errorCode = string1; - this.errorMessage = string2; - } - - /** - * Gets the error code. - * - * @return the error code - */ - public String getErrorCode() { - return errorCode; - } - - /** - * Gets the error message. - * - * @return the error message - */ - public String getErrorMessage() { - return errorMessage; - } -} diff --git a/registration-processor/registration-processor-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/decryptor/Decryptor.java b/registration-processor/registration-processor-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/decryptor/Decryptor.java index ae1179a2697..2a02a903202 100644 --- a/registration-processor/registration-processor-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/decryptor/Decryptor.java +++ b/registration-processor/registration-processor-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/decryptor/Decryptor.java @@ -1,212 +1,212 @@ -package io.mosip.registration.processor.status.decryptor; - -import java.io.IOException; -import java.text.ParseException; -import java.time.LocalDateTime; -import java.time.format.DateTimeFormatter; -import java.util.Arrays; -import java.util.Base64; -import java.util.LinkedHashMap; - -import io.mosip.kernel.core.http.RequestWrapper; -import io.mosip.registration.processor.packet.manager.constant.CryptomanagerConstant; -import io.mosip.registration.processor.status.dto.CryptomanagerRequestDto; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.core.env.Environment; -import org.springframework.stereotype.Component; -import org.springframework.web.client.HttpClientErrorException; -import org.springframework.web.client.HttpServerErrorException; - -import com.fasterxml.jackson.databind.ObjectMapper; - -import io.mosip.kernel.core.exception.ExceptionUtils; -import io.mosip.kernel.core.logger.spi.Logger; -import io.mosip.kernel.core.util.CryptoUtil; -import io.mosip.kernel.core.util.DateUtils; -import io.mosip.registration.processor.core.code.ApiName; -import io.mosip.registration.processor.core.code.EventId; -import io.mosip.registration.processor.core.code.EventName; -import io.mosip.registration.processor.core.code.EventType; -import io.mosip.registration.processor.core.code.ModuleName; -import io.mosip.registration.processor.core.constant.LoggerFileConstant; -import io.mosip.registration.processor.core.exception.ApisResourceAccessException; -import io.mosip.registration.processor.core.exception.util.PlatformErrorMessages; -import io.mosip.registration.processor.core.exception.util.PlatformSuccessMessages; -import io.mosip.registration.processor.core.http.ResponseWrapper; -import io.mosip.registration.processor.core.logger.LogDescription; -import io.mosip.registration.processor.core.logger.RegProcessorLogger; -import io.mosip.registration.processor.core.spi.restclient.RegistrationProcessorRestClientService; -import io.mosip.registration.processor.rest.client.audit.builder.AuditLogRequestBuilder; -import io.mosip.registration.processor.status.constants.PacketDecryptionFailureExceptionConstant; -import io.mosip.registration.processor.status.dto.CryptomanagerResponseDto; -import io.mosip.registration.processor.status.exception.PacketDecryptionFailureException; - -/** - * Decryptor class for packet decryption. - * - * @author Girish Yarru - */ -@Component -public class Decryptor { - private static Logger regProcLogger = RegProcessorLogger.getLogger(Decryptor.class); - private static final String KEY = "data"; - - @Value("${registration.processor.application.id}") - private String applicationId; - - @Value("${crypto.PrependThumbprint.enable:true}") - private boolean isPrependThumbprintEnabled; - - @Autowired - private RegistrationProcessorRestClientService restClientService; - - @Autowired - private AuditLogRequestBuilder auditLogRequestBuilder; - - @Autowired - private Environment env; - - @Autowired - private ObjectMapper mapper; - - private static final String DECRYPT_SERVICE_ID = "mosip.registration.processor.crypto.decrypt.id"; - private static final String REG_PROC_APPLICATION_VERSION = "mosip.registration.processor.application.version"; - private static final String DATETIME_PATTERN = "mosip.registration.processor.datetime.pattern"; - - private static final String DECRYPTION_SUCCESS = "Decryption success"; - private static final String DECRYPTION_FAILURE = "Virus scan decryption failed for registrationId "; - private static final String IO_EXCEPTION = "Exception Converting encrypted packet inputStream to string"; - - /** - * This method consumes inputStream of encrypted packet and registrationId as - * arguments. Hits the kernel's crypto-manager api passing 'application - * id,center id and encrypted inputStream in form of string. gets the - * response(Success or Failure) as string if success convert string to - * cryptomanager response dto and then get decrypted data and then return - * inputStream of decrypted data. if failure convert string to cryptomanager - * response dto and then get error code and error response and throw - * PacketDecryptionFailureException. - * - * @param encryptedSyncMetaInfo - * @return - * @throws PacketDecryptionFailureException - * @throws ApisResourceAccessException - * @throws ParseException - */ - - @SuppressWarnings("unchecked") - public String decrypt(Object encryptedSyncMetaInfo, String referenceId, String timeStamp) - throws PacketDecryptionFailureException, ApisResourceAccessException { - String decryptedData = null; - boolean isTransactionSuccessful = false; - LogDescription description = new LogDescription(); - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), "", - "Decryptor::decrypt()::entry"); - try { - byte[] packet = null; - try { - packet= CryptoUtil.decodeURLSafeBase64(encryptedSyncMetaInfo.toString()); - } catch (IllegalArgumentException exception) { - packet= CryptoUtil.decodePlainBase64(encryptedSyncMetaInfo.toString()); - } - CryptomanagerRequestDto cryptomanagerRequestDto = new CryptomanagerRequestDto(); - cryptomanagerRequestDto.setPrependThumbprint(isPrependThumbprintEnabled); - io.mosip.kernel.core.http.RequestWrapper request = new RequestWrapper<>(); - cryptomanagerRequestDto.setApplicationId(applicationId); - cryptomanagerRequestDto.setReferenceId(referenceId); - byte[] nonce = Arrays.copyOfRange(packet, 0, CryptomanagerConstant.GCM_NONCE_LENGTH); - byte[] aad = Arrays.copyOfRange(packet, CryptomanagerConstant.GCM_NONCE_LENGTH, - CryptomanagerConstant.GCM_NONCE_LENGTH + CryptomanagerConstant.GCM_AAD_LENGTH); - byte[] encryptedData = Arrays.copyOfRange(packet, CryptomanagerConstant.GCM_NONCE_LENGTH + CryptomanagerConstant.GCM_AAD_LENGTH, - packet.length); - cryptomanagerRequestDto.setAad(CryptoUtil.encodeToURLSafeBase64(aad)); - cryptomanagerRequestDto.setSalt(CryptoUtil.encodeToURLSafeBase64(nonce)); - cryptomanagerRequestDto.setData(CryptoUtil.encodeToURLSafeBase64(encryptedData)); - DateTimeFormatter format = DateTimeFormatter.ofPattern(env.getProperty(DATETIME_PATTERN)); - LocalDateTime time = LocalDateTime.parse(timeStamp, format); - cryptomanagerRequestDto.setTimeStamp(time); - // setLocal Date Time - request.setId(env.getProperty(DECRYPT_SERVICE_ID)); - request.setMetadata(null); - request.setRequest(cryptomanagerRequestDto); - LocalDateTime localdatetime = LocalDateTime - .parse(DateUtils.getUTCCurrentDateTimeString(env.getProperty(DATETIME_PATTERN)), format); - request.setRequesttime(localdatetime); - request.setVersion(env.getProperty(REG_PROC_APPLICATION_VERSION)); - - ResponseWrapper response = (ResponseWrapper) restClientService - .postApi(ApiName.CRYPTOMANAGERDECRYPT, "", "", request, ResponseWrapper.class); - if (response.getResponse() != null) { - LinkedHashMap responseMap = mapper.readValue(mapper.writeValueAsString(response.getResponse()), - LinkedHashMap.class); - byte[] decryptedPacket = CryptoUtil.decodeURLSafeBase64(responseMap.get(KEY).toString()); - decryptedData = new String(decryptedPacket); - } else { - description.setMessage(PlatformErrorMessages.RPR_PDS_PACKET_DECRYPTION_FAILURE.getMessage()); - description.setCode(PlatformErrorMessages.RPR_PDS_PACKET_DECRYPTION_FAILURE.getCode()); - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), - LoggerFileConstant.REGISTRATIONID.toString(), "", IO_EXCEPTION); - throw new PacketDecryptionFailureException(response.getErrors().get(0).getErrorCode(), - response.getErrors().get(0).getMessage()); - } - - isTransactionSuccessful = true; - description.setMessage(PlatformSuccessMessages.RPR_DECRYPTION_SUCCESS.getMessage()); - description.setCode(PlatformSuccessMessages.RPR_DECRYPTION_SUCCESS.getCode()); - regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - "", "Decryptor::decrypt()::exit"); - regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - "", description.getMessage()); - } catch (IOException e) { - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - "", IO_EXCEPTION); - description.setMessage(PlatformErrorMessages.RPR_PDS_IO_EXCEPTION.getMessage()); - description.setCode(PlatformErrorMessages.RPR_PDS_IO_EXCEPTION.getCode()); - - throw new PacketDecryptionFailureException( - PacketDecryptionFailureExceptionConstant.MOSIP_PACKET_DECRYPTION_FAILURE_ERROR_CODE.getErrorCode(), - IO_EXCEPTION); - } catch (ApisResourceAccessException e) { - regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - "", "Internal Error occurred " + ExceptionUtils.getStackTrace(e)); - if (e.getCause() instanceof HttpClientErrorException) { - HttpClientErrorException httpClientException = (HttpClientErrorException) e.getCause(); - description.setMessage(PlatformErrorMessages.RPR_PDS_PACKET_DECRYPTION_FAILURE.getMessage() - + httpClientException.getResponseBodyAsString()); - description.setCode(PlatformErrorMessages.RPR_PDS_PACKET_DECRYPTION_FAILURE.getCode()); - throw new PacketDecryptionFailureException( - PacketDecryptionFailureExceptionConstant.MOSIP_PACKET_DECRYPTION_FAILURE_ERROR_CODE - .getErrorCode(), - httpClientException.getResponseBodyAsString()); - } else { - description.setMessage( - PlatformErrorMessages.RPR_PDS_PACKET_DECRYPTION_FAILURE.getMessage() + e.getMessage()); - description.setCode(PlatformErrorMessages.RPR_PDS_PACKET_DECRYPTION_FAILURE.getCode()); - - throw e; - } - - } finally { - String eventId = ""; - String eventName = ""; - String eventType = ""; - eventId = isTransactionSuccessful ? EventId.RPR_402.toString() : EventId.RPR_405.toString(); - eventName = eventId.equalsIgnoreCase(EventId.RPR_402.toString()) ? EventName.UPDATE.toString() - : EventName.EXCEPTION.toString(); - eventType = eventId.equalsIgnoreCase(EventId.RPR_402.toString()) ? EventType.BUSINESS.toString() - : EventType.SYSTEM.toString(); - - /** Module-Id can be Both Success/Error code */ - String moduleId = isTransactionSuccessful ? PlatformSuccessMessages.RPR_DECRYPTION_SUCCESS.getCode() - : description.getCode(); - String moduleName = ModuleName.DECRYPTOR.toString(); - auditLogRequestBuilder.createAuditRequestBuilder(description.getMessage(), eventId, eventName, eventType, - moduleId, moduleName, ""); - } - regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), "", - DECRYPTION_SUCCESS); - return decryptedData; - } - -} +package io.mosip.registration.processor.status.decryptor; + +import java.io.IOException; +import java.text.ParseException; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.Arrays; +import java.util.Base64; +import java.util.LinkedHashMap; + +import io.mosip.kernel.core.http.RequestWrapper; +import io.mosip.registration.processor.packet.manager.constant.CryptomanagerConstant; +import io.mosip.registration.processor.status.dto.CryptomanagerRequestDto; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Component; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.web.client.HttpServerErrorException; + +import com.fasterxml.jackson.databind.ObjectMapper; + +import io.mosip.kernel.core.exception.ExceptionUtils; +import io.mosip.kernel.core.logger.spi.Logger; +import io.mosip.kernel.core.util.CryptoUtil; +import io.mosip.kernel.core.util.DateUtils; +import io.mosip.registration.processor.core.code.ApiName; +import io.mosip.registration.processor.core.code.EventId; +import io.mosip.registration.processor.core.code.EventName; +import io.mosip.registration.processor.core.code.EventType; +import io.mosip.registration.processor.core.code.ModuleName; +import io.mosip.registration.processor.core.constant.LoggerFileConstant; +import io.mosip.registration.processor.core.constant.PacketDecryptionFailureExceptionConstant; +import io.mosip.registration.processor.core.exception.ApisResourceAccessException; +import io.mosip.registration.processor.core.exception.util.PlatformErrorMessages; +import io.mosip.registration.processor.core.exception.util.PlatformSuccessMessages; +import io.mosip.registration.processor.core.http.ResponseWrapper; +import io.mosip.registration.processor.core.logger.LogDescription; +import io.mosip.registration.processor.core.logger.RegProcessorLogger; +import io.mosip.registration.processor.core.spi.restclient.RegistrationProcessorRestClientService; +import io.mosip.registration.processor.rest.client.audit.builder.AuditLogRequestBuilder; +import io.mosip.registration.processor.status.dto.CryptomanagerResponseDto; +import io.mosip.registration.processor.status.exception.PacketDecryptionFailureException; + +/** + * Decryptor class for packet decryption. + * + * @author Girish Yarru + */ +@Component +public class Decryptor { + private static Logger regProcLogger = RegProcessorLogger.getLogger(Decryptor.class); + private static final String KEY = "data"; + + @Value("${registration.processor.application.id}") + private String applicationId; + + @Value("${crypto.PrependThumbprint.enable:true}") + private boolean isPrependThumbprintEnabled; + + @Autowired + private RegistrationProcessorRestClientService restClientService; + + @Autowired + private AuditLogRequestBuilder auditLogRequestBuilder; + + @Autowired + private Environment env; + + @Autowired + private ObjectMapper mapper; + + private static final String DECRYPT_SERVICE_ID = "mosip.registration.processor.crypto.decrypt.id"; + private static final String REG_PROC_APPLICATION_VERSION = "mosip.registration.processor.application.version"; + private static final String DATETIME_PATTERN = "mosip.registration.processor.datetime.pattern"; + + private static final String DECRYPTION_SUCCESS = "Decryption success"; + private static final String DECRYPTION_FAILURE = "Virus scan decryption failed for registrationId "; + private static final String IO_EXCEPTION = "Exception Converting encrypted packet inputStream to string"; + + /** + * This method consumes inputStream of encrypted packet and registrationId as + * arguments. Hits the kernel's crypto-manager api passing 'application + * id,center id and encrypted inputStream in form of string. gets the + * response(Success or Failure) as string if success convert string to + * cryptomanager response dto and then get decrypted data and then return + * inputStream of decrypted data. if failure convert string to cryptomanager + * response dto and then get error code and error response and throw + * PacketDecryptionFailureException. + * + * @param encryptedSyncMetaInfo + * @return + * @throws PacketDecryptionFailureException + * @throws ApisResourceAccessException + * @throws ParseException + */ + + @SuppressWarnings("unchecked") + public String decrypt(Object encryptedSyncMetaInfo, String referenceId, String timeStamp) + throws PacketDecryptionFailureException, ApisResourceAccessException { + String decryptedData = null; + boolean isTransactionSuccessful = false; + LogDescription description = new LogDescription(); + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), "", + "Decryptor::decrypt()::entry"); + try { + byte[] packet = null; + try { + packet= CryptoUtil.decodeURLSafeBase64(encryptedSyncMetaInfo.toString()); + } catch (IllegalArgumentException exception) { + packet= CryptoUtil.decodePlainBase64(encryptedSyncMetaInfo.toString()); + } + CryptomanagerRequestDto cryptomanagerRequestDto = new CryptomanagerRequestDto(); + cryptomanagerRequestDto.setPrependThumbprint(isPrependThumbprintEnabled); + io.mosip.kernel.core.http.RequestWrapper request = new RequestWrapper<>(); + cryptomanagerRequestDto.setApplicationId(applicationId); + cryptomanagerRequestDto.setReferenceId(referenceId); + byte[] nonce = Arrays.copyOfRange(packet, 0, CryptomanagerConstant.GCM_NONCE_LENGTH); + byte[] aad = Arrays.copyOfRange(packet, CryptomanagerConstant.GCM_NONCE_LENGTH, + CryptomanagerConstant.GCM_NONCE_LENGTH + CryptomanagerConstant.GCM_AAD_LENGTH); + byte[] encryptedData = Arrays.copyOfRange(packet, CryptomanagerConstant.GCM_NONCE_LENGTH + CryptomanagerConstant.GCM_AAD_LENGTH, + packet.length); + cryptomanagerRequestDto.setAad(CryptoUtil.encodeToURLSafeBase64(aad)); + cryptomanagerRequestDto.setSalt(CryptoUtil.encodeToURLSafeBase64(nonce)); + cryptomanagerRequestDto.setData(CryptoUtil.encodeToURLSafeBase64(encryptedData)); + DateTimeFormatter format = DateTimeFormatter.ofPattern(env.getProperty(DATETIME_PATTERN)); + LocalDateTime time = LocalDateTime.parse(timeStamp, format); + cryptomanagerRequestDto.setTimeStamp(time); + // setLocal Date Time + request.setId(env.getProperty(DECRYPT_SERVICE_ID)); + request.setMetadata(null); + request.setRequest(cryptomanagerRequestDto); + LocalDateTime localdatetime = LocalDateTime + .parse(DateUtils.getUTCCurrentDateTimeString(env.getProperty(DATETIME_PATTERN)), format); + request.setRequesttime(localdatetime); + request.setVersion(env.getProperty(REG_PROC_APPLICATION_VERSION)); + + ResponseWrapper response = (ResponseWrapper) restClientService + .postApi(ApiName.CRYPTOMANAGERDECRYPT, "", "", request, ResponseWrapper.class); + if (response.getResponse() != null) { + LinkedHashMap responseMap = mapper.readValue(mapper.writeValueAsString(response.getResponse()), + LinkedHashMap.class); + byte[] decryptedPacket = CryptoUtil.decodeURLSafeBase64(responseMap.get(KEY).toString()); + decryptedData = new String(decryptedPacket); + } else { + description.setMessage(PlatformErrorMessages.RPR_PDS_PACKET_DECRYPTION_FAILURE.getMessage()); + description.setCode(PlatformErrorMessages.RPR_PDS_PACKET_DECRYPTION_FAILURE.getCode()); + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString(), "", IO_EXCEPTION); + throw new PacketDecryptionFailureException(response.getErrors().get(0).getErrorCode(), + response.getErrors().get(0).getMessage()); + } + + isTransactionSuccessful = true; + description.setMessage(PlatformSuccessMessages.RPR_DECRYPTION_SUCCESS.getMessage()); + description.setCode(PlatformSuccessMessages.RPR_DECRYPTION_SUCCESS.getCode()); + regProcLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + "", "Decryptor::decrypt()::exit"); + regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + "", description.getMessage()); + } catch (IOException e) { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + "", IO_EXCEPTION); + description.setMessage(PlatformErrorMessages.RPR_PDS_IO_EXCEPTION.getMessage()); + description.setCode(PlatformErrorMessages.RPR_PDS_IO_EXCEPTION.getCode()); + + throw new PacketDecryptionFailureException( + PacketDecryptionFailureExceptionConstant.MOSIP_PACKET_DECRYPTION_FAILURE_ERROR_CODE.getErrorCode(), + IO_EXCEPTION); + } catch (ApisResourceAccessException e) { + regProcLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + "", "Internal Error occurred " + ExceptionUtils.getStackTrace(e)); + if (e.getCause() instanceof HttpClientErrorException) { + HttpClientErrorException httpClientException = (HttpClientErrorException) e.getCause(); + description.setMessage(PlatformErrorMessages.RPR_PDS_PACKET_DECRYPTION_FAILURE.getMessage() + + httpClientException.getResponseBodyAsString()); + description.setCode(PlatformErrorMessages.RPR_PDS_PACKET_DECRYPTION_FAILURE.getCode()); + throw new PacketDecryptionFailureException( + PacketDecryptionFailureExceptionConstant.MOSIP_PACKET_DECRYPTION_FAILURE_ERROR_CODE + .getErrorCode(), + httpClientException.getResponseBodyAsString()); + } else { + description.setMessage( + PlatformErrorMessages.RPR_PDS_PACKET_DECRYPTION_FAILURE.getMessage() + e.getMessage()); + description.setCode(PlatformErrorMessages.RPR_PDS_PACKET_DECRYPTION_FAILURE.getCode()); + + throw e; + } + + } finally { + String eventId = ""; + String eventName = ""; + String eventType = ""; + eventId = isTransactionSuccessful ? EventId.RPR_402.toString() : EventId.RPR_405.toString(); + eventName = eventId.equalsIgnoreCase(EventId.RPR_402.toString()) ? EventName.UPDATE.toString() + : EventName.EXCEPTION.toString(); + eventType = eventId.equalsIgnoreCase(EventId.RPR_402.toString()) ? EventType.BUSINESS.toString() + : EventType.SYSTEM.toString(); + + /** Module-Id can be Both Success/Error code */ + String moduleId = isTransactionSuccessful ? PlatformSuccessMessages.RPR_DECRYPTION_SUCCESS.getCode() + : description.getCode(); + String moduleName = ModuleName.DECRYPTOR.toString(); + auditLogRequestBuilder.createAuditRequestBuilder(description.getMessage(), eventId, eventName, eventType, + moduleId, moduleName, ""); + } + regProcLogger.info(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), "", + DECRYPTION_SUCCESS); + return decryptedData; + } + +} diff --git a/registration-processor/registration-processor-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/dto/PacketDecryptionFailureExceptionConstant.java b/registration-processor/registration-processor-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/dto/PacketDecryptionFailureExceptionConstant.java deleted file mode 100644 index aecd43af886..00000000000 --- a/registration-processor/registration-processor-registration-status-service-impl/src/main/java/io/mosip/registration/processor/status/dto/PacketDecryptionFailureExceptionConstant.java +++ /dev/null @@ -1,45 +0,0 @@ -package io.mosip.registration.processor.status.dto; - -/** - * The Enum PacketDecryptionFailureExceptionConstant. - */ -public enum PacketDecryptionFailureExceptionConstant { - - /** The mosip packet decryption failure error code. */ - MOSIP_PACKET_DECRYPTION_FAILURE_ERROR_CODE("RPR-PKD-004", "The Decryption for the Packet has failed"); - - /** The error code. */ - public final String errorCode; - - /** The error message. */ - public final String errorMessage; - - /** - * Instantiates a new packet decryption failure exception constant. - * - * @param string1 the string 1 - * @param string2 the string 2 - */ - PacketDecryptionFailureExceptionConstant(String string1,String string2) { - this.errorCode = string1; - this.errorMessage = string2; - } - - /** - * Gets the error code. - * - * @return the error code - */ - public String getErrorCode() { - return errorCode; - } - - /** - * Gets the error message. - * - * @return the error message - */ - public String getErrorMessage() { - return errorMessage; - } -} From 3814282751af969d809f6866694af7d314355ca5 Mon Sep 17 00:00:00 2001 From: Sowmya Ujjappa Banakar Date: Thu, 27 Jun 2024 16:46:22 +0530 Subject: [PATCH 3/4] MOSIP-32461 removed some packages for sonar from pom.xml Signed-off-by: Sowmya Ujjappa Banakar --- registration-processor/pom.xml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/registration-processor/pom.xml b/registration-processor/pom.xml index e2845a2e346..7ba2be51bf1 100644 --- a/registration-processor/pom.xml +++ b/registration-processor/pom.xml @@ -268,7 +268,8 @@ **/registration/processor/core/**/TokenValidator.java, **/registration/processor/core/abstractverticle/StageHealthCheckHandler.java, **/registration/processor/core/abstractverticle/MessageDTO.java, - **/registration/processor/request/handler/**/*.java + **/registration/processor/request/handler/**/*.java, + **/registration/processor/message/sender/stage/*.java; **/dto/**,**/entity/**,**/config/**,**/handler/**,**/utilities/**, **/validator/**, **/utils/**,**/util/**,**/code/** From 86deaf1e463947c044dea5f74613af0533339c90 Mon Sep 17 00:00:00 2001 From: Sowmya Ujjappa Banakar Date: Fri, 28 Jun 2024 12:07:35 +0530 Subject: [PATCH 4/4] MOSIP-31793 security hotspot Signed-off-by: Sowmya Ujjappa Banakar --- .../registration/processor/core/logger/RegProcessorLogger.java | 1 + 1 file changed, 1 insertion(+) diff --git a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/logger/RegProcessorLogger.java b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/logger/RegProcessorLogger.java index fa5579de122..bbdf673d44e 100644 --- a/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/logger/RegProcessorLogger.java +++ b/registration-processor/registration-processor-core/src/main/java/io/mosip/registration/processor/core/logger/RegProcessorLogger.java @@ -34,6 +34,7 @@ private RegProcessorLogger() { * @param clazz the clazz * @return the logger */ + @SuppressWarnings({ "java:S4792" }) public static Logger getLogger(Class clazz) { if(loggingLevelMap.isEmpty()) { loggingLevelMap = System.getProperties().entrySet().stream()